1 package org
.argeo
.cms
.jcr
.internal
;
3 import static org
.argeo
.cms
.osgi
.DataModelNamespace
.CMS_DATA_MODEL_NAMESPACE
;
4 import static org
.osgi
.service
.http
.whiteboard
.HttpWhiteboardConstants
.HTTP_WHITEBOARD_SERVLET_INIT_PARAM_PREFIX
;
7 import java
.io
.IOException
;
8 import java
.io
.InputStreamReader
;
11 import java
.nio
.file
.Files
;
12 import java
.nio
.file
.Path
;
13 import java
.util
.ArrayList
;
14 import java
.util
.Arrays
;
15 import java
.util
.Collection
;
16 import java
.util
.HashSet
;
17 import java
.util
.Hashtable
;
18 import java
.util
.Iterator
;
19 import java
.util
.List
;
23 import javax
.jcr
.NamespaceRegistry
;
24 import javax
.jcr
.Repository
;
25 import javax
.jcr
.RepositoryException
;
26 import javax
.jcr
.Session
;
27 import javax
.security
.auth
.callback
.CallbackHandler
;
28 import javax
.servlet
.Servlet
;
30 import org
.apache
.jackrabbit
.commons
.cnd
.CndImporter
;
31 import org
.apache
.jackrabbit
.core
.RepositoryContext
;
32 import org
.apache
.jackrabbit
.core
.RepositoryImpl
;
33 import org
.argeo
.api
.acr
.spi
.ProvidedRepository
;
34 import org
.argeo
.api
.cms
.CmsConstants
;
35 import org
.argeo
.api
.cms
.CmsDeployment
;
36 import org
.argeo
.api
.cms
.CmsLog
;
37 import org
.argeo
.cms
.ArgeoNames
;
38 import org
.argeo
.cms
.internal
.jcr
.JcrInitUtils
;
39 import org
.argeo
.cms
.jcr
.CmsJcrUtils
;
40 import org
.argeo
.cms
.jcr
.acr
.JcrContentProvider
;
41 import org
.argeo
.cms
.jcr
.internal
.servlet
.CmsRemotingServlet
;
42 import org
.argeo
.cms
.jcr
.internal
.servlet
.CmsWebDavServlet
;
43 import org
.argeo
.cms
.jcr
.internal
.servlet
.JcrHttpUtils
;
44 import org
.argeo
.cms
.osgi
.DataModelNamespace
;
45 import org
.argeo
.cms
.security
.CryptoKeyring
;
46 import org
.argeo
.cms
.security
.Keyring
;
47 import org
.argeo
.jcr
.Jcr
;
48 import org
.argeo
.jcr
.JcrException
;
49 import org
.argeo
.jcr
.JcrUtils
;
50 import org
.argeo
.util
.LangUtils
;
51 import org
.argeo
.util
.naming
.LdapAttrs
;
52 import org
.osgi
.framework
.Bundle
;
53 import org
.osgi
.framework
.BundleContext
;
54 import org
.osgi
.framework
.Constants
;
55 import org
.osgi
.framework
.FrameworkUtil
;
56 import org
.osgi
.framework
.InvalidSyntaxException
;
57 import org
.osgi
.framework
.ServiceReference
;
58 import org
.osgi
.framework
.wiring
.BundleCapability
;
59 import org
.osgi
.framework
.wiring
.BundleWire
;
60 import org
.osgi
.framework
.wiring
.BundleWiring
;
61 import org
.osgi
.service
.cm
.ManagedService
;
62 import org
.osgi
.service
.http
.whiteboard
.HttpWhiteboardConstants
;
63 import org
.osgi
.util
.tracker
.ServiceTracker
;
65 /** Implementation of a CMS deployment. */
66 public class CmsJcrDeployment
{
67 private final CmsLog log
= CmsLog
.getLog(getClass());
68 private final BundleContext bc
= FrameworkUtil
.getBundle(getClass()).getBundleContext();
70 private DataModels dataModels
;
71 private String webDavConfig
= JcrHttpUtils
.WEBDAV_CONFIG
;
73 private boolean argeoDataModelExtensionsAvailable
= false;
76 private boolean nodeAvailable
= false;
78 CmsDeployment cmsDeployment
;
80 dataModels
= new DataModels(bc
);
82 ServiceTracker
<?
, ?
> repoContextSt
= new RepositoryContextStc();
84 // KernelUtils.asyncOpen(repoContextSt);
86 // nodeDeployment = CmsJcrActivator.getService(NodeDeployment.class);
88 JcrInitUtils
.addToDeployment(cmsDeployment
);
90 // contentRepository.registerTypes(NamespaceRegistry.PREFIX_JCR, NamespaceRegistry.NAMESPACE_JCR, null);
91 // contentRepository.registerTypes(NamespaceRegistry.PREFIX_MIX, NamespaceRegistry.NAMESPACE_MIX, null);
92 // contentRepository.registerTypes(NamespaceRegistry.PREFIX_NT, NamespaceRegistry.NAMESPACE_NT, null);
95 // // https://jackrabbit.apache.org/archive/wiki/JCR/NamespaceRegistry_115513459.html
96 // contentRepository.registerTypes("rep", "internal", null);
101 // if (nodeHttp != null)
102 // nodeHttp.destroy();
106 for (ServiceReference
<JackrabbitLocalRepository
> sr
: bc
107 .getServiceReferences(JackrabbitLocalRepository
.class, null)) {
108 bc
.getService(sr
).destroy();
110 } catch (InvalidSyntaxException e1
) {
111 log
.error("Cannot clean repositories", e1
);
116 public void setCmsDeployment(CmsDeployment cmsDeployment
) {
117 this.cmsDeployment
= cmsDeployment
;
121 * Checks whether the deployment is available according to expectations, and
122 * mark it as available.
124 // private synchronized void checkReadiness() {
125 // if (isAvailable())
127 // if (nodeAvailable && userAdminAvailable && (httpExpected ? httpAvailable : true)) {
128 // String data = KernelUtils.getFrameworkProp(KernelUtils.OSGI_INSTANCE_AREA);
129 // String state = KernelUtils.getFrameworkProp(KernelUtils.OSGI_CONFIGURATION_AREA);
130 // availableSince = System.currentTimeMillis();
131 // long jvmUptime = ManagementFactory.getRuntimeMXBean().getUptime();
132 // String jvmUptimeStr = " in " + (jvmUptime / 1000) + "." + (jvmUptime % 1000) + "s";
133 // log.info("## ARGEO NODE AVAILABLE" + (log.isDebugEnabled() ? jvmUptimeStr : "") + " ##");
134 // if (log.isDebugEnabled()) {
135 // log.debug("## state: " + state);
137 // log.debug("## data: " + data);
139 // long begin = bc.getService(bc.getServiceReference(NodeState.class)).getAvailableSince();
140 // long initDuration = System.currentTimeMillis() - begin;
141 // if (log.isTraceEnabled())
142 // log.trace("Kernel initialization took " + initDuration + "ms");
143 // tributeToFreeSoftware(initDuration);
147 private void prepareNodeRepository(Repository deployedNodeRepository
, List
<String
> publishAsLocalRepo
) {
148 // if (availableSince != null) {
149 // throw new IllegalStateException("Deployment is already available");
153 prepareDataModel(CmsConstants
.NODE_REPOSITORY
, deployedNodeRepository
, publishAsLocalRepo
);
156 // if (deployConfig.isFirstInit()) {
157 // Path restorePath = Paths.get(System.getProperty("user.dir"), "restore");
158 // if (Files.exists(restorePath)) {
159 // if (log.isDebugEnabled())
160 // log.debug("Found backup " + restorePath + ", restoring it...");
161 // LogicalRestore logicalRestore = new LogicalRestore(bc, deployedNodeRepository, restorePath);
162 // KernelUtils.doAsDataAdmin(logicalRestore);
163 // log.info("Restored backup from " + restorePath);
167 // init from repository
168 Collection
<ServiceReference
<Repository
>> initRepositorySr
;
170 initRepositorySr
= bc
.getServiceReferences(Repository
.class,
171 "(" + CmsConstants
.CN
+ "=" + CmsConstants
.NODE_INIT
+ ")");
172 } catch (InvalidSyntaxException e1
) {
173 throw new IllegalArgumentException(e1
);
175 Iterator
<ServiceReference
<Repository
>> it
= initRepositorySr
.iterator();
176 while (it
.hasNext()) {
177 ServiceReference
<Repository
> sr
= it
.next();
178 Object labeledUri
= sr
.getProperties().get(LdapAttrs
.labeledURI
.name());
179 Repository initRepository
= bc
.getService(sr
);
180 if (log
.isDebugEnabled())
181 log
.debug("Found init repository " + labeledUri
+ ", copying it...");
182 initFromRepository(deployedNodeRepository
, initRepository
);
183 log
.info("Node repository initialised from " + labeledUri
);
187 /** Init from a (typically remote) repository. */
188 private void initFromRepository(Repository deployedNodeRepository
, Repository initRepository
) {
189 Session initSession
= null;
191 initSession
= initRepository
.login();
192 workspaces
: for (String workspaceName
: initSession
.getWorkspace().getAccessibleWorkspaceNames()) {
193 if ("security".equals(workspaceName
))
195 if (log
.isDebugEnabled())
196 log
.debug("Copying workspace " + workspaceName
+ " from init repository...");
197 long begin
= System
.currentTimeMillis();
198 Session targetSession
= null;
199 Session sourceSession
= null;
202 targetSession
= CmsJcrUtils
.openDataAdminSession(deployedNodeRepository
, workspaceName
);
203 } catch (IllegalArgumentException e
) {// no such workspace
204 Session adminSession
= CmsJcrUtils
.openDataAdminSession(deployedNodeRepository
, null);
206 adminSession
.getWorkspace().createWorkspace(workspaceName
);
208 Jcr
.logout(adminSession
);
210 targetSession
= CmsJcrUtils
.openDataAdminSession(deployedNodeRepository
, workspaceName
);
212 sourceSession
= initRepository
.login(workspaceName
);
213 // JcrUtils.copyWorkspaceXml(sourceSession, targetSession);
214 // TODO deal with referenceable nodes
215 JcrUtils
.copy(sourceSession
.getRootNode(), targetSession
.getRootNode());
216 targetSession
.save();
217 long duration
= System
.currentTimeMillis() - begin
;
218 if (log
.isDebugEnabled())
219 log
.debug("Copied workspace " + workspaceName
+ " from init repository in " + (duration
/ 1000)
221 } catch (Exception e
) {
222 log
.error("Cannot copy workspace " + workspaceName
+ " from init repository.", e
);
224 Jcr
.logout(sourceSession
);
225 Jcr
.logout(targetSession
);
228 } catch (RepositoryException e
) {
229 throw new JcrException(e
);
231 Jcr
.logout(initSession
);
235 private void prepareHomeRepository(RepositoryImpl deployedRepository
) {
236 Session adminSession
= KernelUtils
.openAdminSession(deployedRepository
);
238 argeoDataModelExtensionsAvailable
= Arrays
239 .asList(adminSession
.getWorkspace().getNamespaceRegistry().getURIs())
240 .contains(ArgeoNames
.ARGEO_NAMESPACE
);
241 } catch (RepositoryException e
) {
242 log
.warn("Cannot check whether Argeo namespace is registered assuming it isn't.", e
);
243 argeoDataModelExtensionsAvailable
= false;
245 JcrUtils
.logoutQuietly(adminSession
);
248 // Publish home with the highest service ranking
249 Hashtable
<String
, Object
> regProps
= new Hashtable
<>();
250 regProps
.put(CmsConstants
.CN
, CmsConstants
.EGO_REPOSITORY
);
251 regProps
.put(Constants
.SERVICE_RANKING
, Integer
.MAX_VALUE
);
252 Repository egoRepository
= new EgoRepository(deployedRepository
, false);
253 bc
.registerService(Repository
.class, egoRepository
, regProps
);
254 registerRepositoryServlets(CmsConstants
.EGO_REPOSITORY
, egoRepository
);
256 // Keyring only if Argeo extensions are available
257 if (argeoDataModelExtensionsAvailable
) {
258 new ServiceTracker
<CallbackHandler
, CallbackHandler
>(bc
, CallbackHandler
.class, null) {
261 public CallbackHandler
addingService(ServiceReference
<CallbackHandler
> reference
) {
262 NodeKeyRing nodeKeyring
= new NodeKeyRing(egoRepository
);
263 CallbackHandler callbackHandler
= bc
.getService(reference
);
264 nodeKeyring
.setDefaultCallbackHandler(callbackHandler
);
265 bc
.registerService(LangUtils
.names(Keyring
.class, CryptoKeyring
.class, ManagedService
.class),
266 nodeKeyring
, LangUtils
.dict(Constants
.SERVICE_PID
, CmsConstants
.NODE_KEYRING_PID
));
267 return callbackHandler
;
274 /** Session is logged out. */
275 private void prepareDataModel(String cn
, Repository repository
, List
<String
> publishAsLocalRepo
) {
276 Session adminSession
= KernelUtils
.openAdminSession(repository
);
278 Set
<String
> processed
= new HashSet
<String
>();
279 bundles
: for (Bundle bundle
: bc
.getBundles()) {
280 BundleWiring wiring
= bundle
.adapt(BundleWiring
.class);
283 if (CmsConstants
.NODE_REPOSITORY
.equals(cn
))// process all data models
284 processWiring(cn
, adminSession
, wiring
, processed
, false, publishAsLocalRepo
);
286 List
<BundleCapability
> capabilities
= wiring
.getCapabilities(CMS_DATA_MODEL_NAMESPACE
);
287 for (BundleCapability capability
: capabilities
) {
288 String dataModelName
= (String
) capability
.getAttributes().get(DataModelNamespace
.NAME
);
289 if (dataModelName
.equals(cn
))// process only own data model
290 processWiring(cn
, adminSession
, wiring
, processed
, false, publishAsLocalRepo
);
295 JcrUtils
.logoutQuietly(adminSession
);
299 private void processWiring(String cn
, Session adminSession
, BundleWiring wiring
, Set
<String
> processed
,
300 boolean importListedAbstractModels
, List
<String
> publishAsLocalRepo
) {
301 // recursively process requirements first
302 List
<BundleWire
> requiredWires
= wiring
.getRequiredWires(CMS_DATA_MODEL_NAMESPACE
);
303 for (BundleWire wire
: requiredWires
) {
304 processWiring(cn
, adminSession
, wire
.getProviderWiring(), processed
, true, publishAsLocalRepo
);
307 List
<BundleCapability
> capabilities
= wiring
.getCapabilities(CMS_DATA_MODEL_NAMESPACE
);
308 capabilities
: for (BundleCapability capability
: capabilities
) {
309 if (!importListedAbstractModels
310 && KernelUtils
.asBoolean((String
) capability
.getAttributes().get(DataModelNamespace
.ABSTRACT
))) {
311 continue capabilities
;
313 boolean publish
= registerDataModelCapability(cn
, adminSession
, capability
, processed
);
315 publishAsLocalRepo
.add((String
) capability
.getAttributes().get(DataModelNamespace
.NAME
));
319 private boolean registerDataModelCapability(String cn
, Session adminSession
, BundleCapability capability
,
320 Set
<String
> processed
) {
321 Map
<String
, Object
> attrs
= capability
.getAttributes();
322 String name
= (String
) attrs
.get(DataModelNamespace
.NAME
);
323 if (processed
.contains(name
)) {
324 if (log
.isTraceEnabled())
325 log
.trace("Data model " + name
+ " has already been processed");
330 String path
= (String
) attrs
.get(DataModelNamespace
.CND
);
332 File dataModel
= bc
.getBundle().getDataFile("dataModels/" + path
);
333 if (!dataModel
.exists()) {
334 URL url
= capability
.getRevision().getBundle().getResource(path
);
336 throw new IllegalArgumentException("No data model '" + name
+ "' found under path " + path
);
337 try (Reader reader
= new InputStreamReader(url
.openStream())) {
338 CndImporter
.registerNodeTypes(reader
, adminSession
, true);
340 dataModel
.getParentFile().mkdirs();
341 dataModel
.createNewFile();
342 if (log
.isDebugEnabled())
343 log
.debug("Registered CND " + url
);
344 } catch (Exception e
) {
345 log
.error("Cannot import CND " + url
, e
);
350 if (KernelUtils
.asBoolean((String
) attrs
.get(DataModelNamespace
.ABSTRACT
)))
353 boolean isStandalone
= isStandalone(name
);
354 boolean publishLocalRepo
;
355 if (isStandalone
&& name
.equals(cn
))// includes the node itself
356 publishLocalRepo
= true;
357 else if (!isStandalone
&& cn
.equals(CmsConstants
.NODE_REPOSITORY
))
358 publishLocalRepo
= true;
360 publishLocalRepo
= false;
362 return publishLocalRepo
;
365 boolean isStandalone(String dataModelName
) {
366 return cmsDeployment
.getProps(CmsConstants
.NODE_REPOS_FACTORY_PID
, dataModelName
) != null;
369 private void publishLocalRepo(String dataModelName
, Repository repository
) {
370 Hashtable
<String
, Object
> properties
= new Hashtable
<>();
371 properties
.put(CmsConstants
.CN
, dataModelName
);
372 LocalRepository localRepository
;
374 if (repository
instanceof RepositoryImpl
) {
375 localRepository
= new JackrabbitLocalRepository((RepositoryImpl
) repository
, dataModelName
);
376 classes
= new String
[] { Repository
.class.getName(), LocalRepository
.class.getName(),
377 JackrabbitLocalRepository
.class.getName() };
379 localRepository
= new LocalRepository(repository
, dataModelName
);
380 classes
= new String
[] { Repository
.class.getName(), LocalRepository
.class.getName() };
382 bc
.registerService(classes
, localRepository
, properties
);
384 // TODO make it configurable
385 registerRepositoryServlets(dataModelName
, localRepository
);
386 if (log
.isTraceEnabled())
387 log
.trace("Published data model " + dataModelName
);
391 // public synchronized Long getAvailableSince() {
392 // return availableSince;
395 // public synchronized boolean isAvailable() {
396 // return availableSince != null;
399 protected void registerRepositoryServlets(String alias
, Repository repository
) {
400 registerRemotingServlet(alias
, repository
);
401 registerWebdavServlet(alias
, repository
);
404 protected void registerWebdavServlet(String alias
, Repository repository
) {
405 CmsWebDavServlet webdavServlet
= new CmsWebDavServlet(alias
, repository
);
406 Hashtable
<String
, String
> ip
= new Hashtable
<>();
407 ip
.put(HTTP_WHITEBOARD_SERVLET_INIT_PARAM_PREFIX
+ CmsWebDavServlet
.INIT_PARAM_RESOURCE_CONFIG
, webDavConfig
);
408 ip
.put(HTTP_WHITEBOARD_SERVLET_INIT_PARAM_PREFIX
+ CmsWebDavServlet
.INIT_PARAM_RESOURCE_PATH_PREFIX
,
411 ip
.put(HttpWhiteboardConstants
.HTTP_WHITEBOARD_SERVLET_PATTERN
, "/" + alias
+ "/*");
412 ip
.put(HttpWhiteboardConstants
.HTTP_WHITEBOARD_CONTEXT_SELECT
,
413 "(" + HttpWhiteboardConstants
.HTTP_WHITEBOARD_CONTEXT_PATH
+ "=" + CmsConstants
.PATH_DATA
+ ")");
414 bc
.registerService(Servlet
.class, webdavServlet
, ip
);
417 protected void registerRemotingServlet(String alias
, Repository repository
) {
418 CmsRemotingServlet remotingServlet
= new CmsRemotingServlet(alias
, repository
);
419 Hashtable
<String
, String
> ip
= new Hashtable
<>();
420 ip
.put(CmsConstants
.CN
, alias
);
421 // Properties ip = new Properties();
422 ip
.put(HTTP_WHITEBOARD_SERVLET_INIT_PARAM_PREFIX
+ CmsRemotingServlet
.INIT_PARAM_RESOURCE_PATH_PREFIX
,
424 ip
.put(HTTP_WHITEBOARD_SERVLET_INIT_PARAM_PREFIX
+ CmsRemotingServlet
.INIT_PARAM_AUTHENTICATE_HEADER
,
427 // Looks like a bug in Jackrabbit remoting init
430 tmpDir
= Files
.createTempDirectory("remoting_" + alias
);
431 } catch (IOException e
) {
432 throw new RuntimeException("Cannot create temp directory for remoting servlet", e
);
434 ip
.put(HTTP_WHITEBOARD_SERVLET_INIT_PARAM_PREFIX
+ CmsRemotingServlet
.INIT_PARAM_HOME
, tmpDir
.toString());
435 ip
.put(HTTP_WHITEBOARD_SERVLET_INIT_PARAM_PREFIX
+ CmsRemotingServlet
.INIT_PARAM_TMP_DIRECTORY
,
436 "remoting_" + alias
);
437 ip
.put(HTTP_WHITEBOARD_SERVLET_INIT_PARAM_PREFIX
+ CmsRemotingServlet
.INIT_PARAM_PROTECTED_HANDLERS_CONFIG
,
438 JcrHttpUtils
.DEFAULT_PROTECTED_HANDLERS
);
439 ip
.put(HTTP_WHITEBOARD_SERVLET_INIT_PARAM_PREFIX
+ CmsRemotingServlet
.INIT_PARAM_CREATE_ABSOLUTE_URI
, "false");
441 ip
.put(HttpWhiteboardConstants
.HTTP_WHITEBOARD_SERVLET_PATTERN
, "/" + alias
+ "/*");
442 ip
.put(HttpWhiteboardConstants
.HTTP_WHITEBOARD_CONTEXT_SELECT
,
443 "(" + HttpWhiteboardConstants
.HTTP_WHITEBOARD_CONTEXT_PATH
+ "=" + CmsConstants
.PATH_JCR
+ ")");
444 bc
.registerService(Servlet
.class, remotingServlet
, ip
);
447 private class RepositoryContextStc
extends ServiceTracker
<RepositoryContext
, RepositoryContext
> {
449 public RepositoryContextStc() {
450 super(bc
, RepositoryContext
.class, null);
454 public RepositoryContext
addingService(ServiceReference
<RepositoryContext
> reference
) {
455 RepositoryContext repoContext
= bc
.getService(reference
);
456 String cn
= (String
) reference
.getProperty(CmsConstants
.CN
);
458 List
<String
> publishAsLocalRepo
= new ArrayList
<>();
459 if (cn
.equals(CmsConstants
.NODE_REPOSITORY
)) {
460 // JackrabbitDataModelMigration.clearRepositoryCaches(repoContext.getRepositoryConfig());
461 prepareNodeRepository(repoContext
.getRepository(), publishAsLocalRepo
);
462 // TODO separate home repository
463 prepareHomeRepository(repoContext
.getRepository());
464 registerRepositoryServlets(cn
, repoContext
.getRepository());
465 nodeAvailable
= true;
468 prepareDataModel(cn
, repoContext
.getRepository(), publishAsLocalRepo
);
470 // Publish all at once, so that bundles with multiple CNDs are consistent
471 for (String dataModelName
: publishAsLocalRepo
)
472 publishLocalRepo(dataModelName
, repoContext
.getRepository());
478 public void modifiedService(ServiceReference
<RepositoryContext
> reference
, RepositoryContext service
) {
482 public void removedService(ServiceReference
<RepositoryContext
> reference
, RepositoryContext service
) {