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
.internal
.servlet
.CmsRemotingServlet
;
41 import org
.argeo
.cms
.jcr
.internal
.servlet
.CmsWebDavServlet
;
42 import org
.argeo
.cms
.jcr
.internal
.servlet
.JcrHttpUtils
;
43 import org
.argeo
.cms
.osgi
.DataModelNamespace
;
44 import org
.argeo
.cms
.security
.CryptoKeyring
;
45 import org
.argeo
.cms
.security
.Keyring
;
46 import org
.argeo
.jcr
.Jcr
;
47 import org
.argeo
.jcr
.JcrException
;
48 import org
.argeo
.jcr
.JcrUtils
;
49 import org
.argeo
.util
.LangUtils
;
50 import org
.argeo
.util
.naming
.LdapAttrs
;
51 import org
.osgi
.framework
.Bundle
;
52 import org
.osgi
.framework
.BundleContext
;
53 import org
.osgi
.framework
.Constants
;
54 import org
.osgi
.framework
.FrameworkUtil
;
55 import org
.osgi
.framework
.InvalidSyntaxException
;
56 import org
.osgi
.framework
.ServiceReference
;
57 import org
.osgi
.framework
.wiring
.BundleCapability
;
58 import org
.osgi
.framework
.wiring
.BundleWire
;
59 import org
.osgi
.framework
.wiring
.BundleWiring
;
60 import org
.osgi
.service
.cm
.ManagedService
;
61 import org
.osgi
.service
.http
.whiteboard
.HttpWhiteboardConstants
;
62 import org
.osgi
.util
.tracker
.ServiceTracker
;
64 /** Implementation of a CMS deployment. */
65 public class CmsJcrDeployment
{
66 private final CmsLog log
= CmsLog
.getLog(getClass());
67 private final BundleContext bc
= FrameworkUtil
.getBundle(getClass()).getBundleContext();
69 private DataModels dataModels
;
70 private String webDavConfig
= JcrHttpUtils
.WEBDAV_CONFIG
;
72 private boolean argeoDataModelExtensionsAvailable
= false;
75 private boolean nodeAvailable
= false;
77 CmsDeployment cmsDeployment
;
78 private ProvidedRepository contentRepository
;
81 dataModels
= new DataModels(bc
);
83 ServiceTracker
<?
, ?
> repoContextSt
= new RepositoryContextStc();
85 // KernelUtils.asyncOpen(repoContextSt);
87 // nodeDeployment = CmsJcrActivator.getService(NodeDeployment.class);
89 JcrInitUtils
.addToDeployment(cmsDeployment
);
91 contentRepository
.registerTypes(NamespaceRegistry
.PREFIX_JCR
, NamespaceRegistry
.NAMESPACE_JCR
, null);
92 contentRepository
.registerTypes(NamespaceRegistry
.PREFIX_MIX
, NamespaceRegistry
.NAMESPACE_MIX
, null);
93 contentRepository
.registerTypes(NamespaceRegistry
.PREFIX_NT
, NamespaceRegistry
.NAMESPACE_NT
, null);
95 // see https://jackrabbit.apache.org/archive/wiki/JCR/NamespaceRegistry_115513459.html
96 contentRepository
.registerTypes("rep", "internal", null);
101 // if (nodeHttp != null)
102 // nodeHttp.destroy();
105 for (ServiceReference
<JackrabbitLocalRepository
> sr
: bc
106 .getServiceReferences(JackrabbitLocalRepository
.class, null)) {
107 bc
.getService(sr
).destroy();
109 } catch (InvalidSyntaxException e1
) {
110 log
.error("Cannot clean repositories", e1
);
115 public void setCmsDeployment(CmsDeployment cmsDeployment
) {
116 this.cmsDeployment
= cmsDeployment
;
119 public void setContentRepository(ProvidedRepository contentRepository
) {
120 this.contentRepository
= contentRepository
;
124 * Checks whether the deployment is available according to expectations, and
125 * mark it as available.
127 // private synchronized void checkReadiness() {
128 // if (isAvailable())
130 // if (nodeAvailable && userAdminAvailable && (httpExpected ? httpAvailable : true)) {
131 // String data = KernelUtils.getFrameworkProp(KernelUtils.OSGI_INSTANCE_AREA);
132 // String state = KernelUtils.getFrameworkProp(KernelUtils.OSGI_CONFIGURATION_AREA);
133 // availableSince = System.currentTimeMillis();
134 // long jvmUptime = ManagementFactory.getRuntimeMXBean().getUptime();
135 // String jvmUptimeStr = " in " + (jvmUptime / 1000) + "." + (jvmUptime % 1000) + "s";
136 // log.info("## ARGEO NODE AVAILABLE" + (log.isDebugEnabled() ? jvmUptimeStr : "") + " ##");
137 // if (log.isDebugEnabled()) {
138 // log.debug("## state: " + state);
140 // log.debug("## data: " + data);
142 // long begin = bc.getService(bc.getServiceReference(NodeState.class)).getAvailableSince();
143 // long initDuration = System.currentTimeMillis() - begin;
144 // if (log.isTraceEnabled())
145 // log.trace("Kernel initialization took " + initDuration + "ms");
146 // tributeToFreeSoftware(initDuration);
150 private void prepareNodeRepository(Repository deployedNodeRepository
, List
<String
> publishAsLocalRepo
) {
151 // if (availableSince != null) {
152 // throw new IllegalStateException("Deployment is already available");
156 prepareDataModel(CmsConstants
.NODE_REPOSITORY
, deployedNodeRepository
, publishAsLocalRepo
);
159 // if (deployConfig.isFirstInit()) {
160 // Path restorePath = Paths.get(System.getProperty("user.dir"), "restore");
161 // if (Files.exists(restorePath)) {
162 // if (log.isDebugEnabled())
163 // log.debug("Found backup " + restorePath + ", restoring it...");
164 // LogicalRestore logicalRestore = new LogicalRestore(bc, deployedNodeRepository, restorePath);
165 // KernelUtils.doAsDataAdmin(logicalRestore);
166 // log.info("Restored backup from " + restorePath);
170 // init from repository
171 Collection
<ServiceReference
<Repository
>> initRepositorySr
;
173 initRepositorySr
= bc
.getServiceReferences(Repository
.class,
174 "(" + CmsConstants
.CN
+ "=" + CmsConstants
.NODE_INIT
+ ")");
175 } catch (InvalidSyntaxException e1
) {
176 throw new IllegalArgumentException(e1
);
178 Iterator
<ServiceReference
<Repository
>> it
= initRepositorySr
.iterator();
179 while (it
.hasNext()) {
180 ServiceReference
<Repository
> sr
= it
.next();
181 Object labeledUri
= sr
.getProperties().get(LdapAttrs
.labeledURI
.name());
182 Repository initRepository
= bc
.getService(sr
);
183 if (log
.isDebugEnabled())
184 log
.debug("Found init repository " + labeledUri
+ ", copying it...");
185 initFromRepository(deployedNodeRepository
, initRepository
);
186 log
.info("Node repository initialised from " + labeledUri
);
190 /** Init from a (typically remote) repository. */
191 private void initFromRepository(Repository deployedNodeRepository
, Repository initRepository
) {
192 Session initSession
= null;
194 initSession
= initRepository
.login();
195 workspaces
: for (String workspaceName
: initSession
.getWorkspace().getAccessibleWorkspaceNames()) {
196 if ("security".equals(workspaceName
))
198 if (log
.isDebugEnabled())
199 log
.debug("Copying workspace " + workspaceName
+ " from init repository...");
200 long begin
= System
.currentTimeMillis();
201 Session targetSession
= null;
202 Session sourceSession
= null;
205 targetSession
= CmsJcrUtils
.openDataAdminSession(deployedNodeRepository
, workspaceName
);
206 } catch (IllegalArgumentException e
) {// no such workspace
207 Session adminSession
= CmsJcrUtils
.openDataAdminSession(deployedNodeRepository
, null);
209 adminSession
.getWorkspace().createWorkspace(workspaceName
);
211 Jcr
.logout(adminSession
);
213 targetSession
= CmsJcrUtils
.openDataAdminSession(deployedNodeRepository
, workspaceName
);
215 sourceSession
= initRepository
.login(workspaceName
);
216 // JcrUtils.copyWorkspaceXml(sourceSession, targetSession);
217 // TODO deal with referenceable nodes
218 JcrUtils
.copy(sourceSession
.getRootNode(), targetSession
.getRootNode());
219 targetSession
.save();
220 long duration
= System
.currentTimeMillis() - begin
;
221 if (log
.isDebugEnabled())
222 log
.debug("Copied workspace " + workspaceName
+ " from init repository in " + (duration
/ 1000)
224 } catch (Exception e
) {
225 log
.error("Cannot copy workspace " + workspaceName
+ " from init repository.", e
);
227 Jcr
.logout(sourceSession
);
228 Jcr
.logout(targetSession
);
231 } catch (RepositoryException e
) {
232 throw new JcrException(e
);
234 Jcr
.logout(initSession
);
238 private void prepareHomeRepository(RepositoryImpl deployedRepository
) {
239 Session adminSession
= KernelUtils
.openAdminSession(deployedRepository
);
241 argeoDataModelExtensionsAvailable
= Arrays
242 .asList(adminSession
.getWorkspace().getNamespaceRegistry().getURIs())
243 .contains(ArgeoNames
.ARGEO_NAMESPACE
);
244 } catch (RepositoryException e
) {
245 log
.warn("Cannot check whether Argeo namespace is registered assuming it isn't.", e
);
246 argeoDataModelExtensionsAvailable
= false;
248 JcrUtils
.logoutQuietly(adminSession
);
251 // Publish home with the highest service ranking
252 Hashtable
<String
, Object
> regProps
= new Hashtable
<>();
253 regProps
.put(CmsConstants
.CN
, CmsConstants
.EGO_REPOSITORY
);
254 regProps
.put(Constants
.SERVICE_RANKING
, Integer
.MAX_VALUE
);
255 Repository egoRepository
= new EgoRepository(deployedRepository
, false);
256 bc
.registerService(Repository
.class, egoRepository
, regProps
);
257 registerRepositoryServlets(CmsConstants
.EGO_REPOSITORY
, egoRepository
);
259 // Keyring only if Argeo extensions are available
260 if (argeoDataModelExtensionsAvailable
) {
261 new ServiceTracker
<CallbackHandler
, CallbackHandler
>(bc
, CallbackHandler
.class, null) {
264 public CallbackHandler
addingService(ServiceReference
<CallbackHandler
> reference
) {
265 NodeKeyRing nodeKeyring
= new NodeKeyRing(egoRepository
);
266 CallbackHandler callbackHandler
= bc
.getService(reference
);
267 nodeKeyring
.setDefaultCallbackHandler(callbackHandler
);
268 bc
.registerService(LangUtils
.names(Keyring
.class, CryptoKeyring
.class, ManagedService
.class),
269 nodeKeyring
, LangUtils
.dict(Constants
.SERVICE_PID
, CmsConstants
.NODE_KEYRING_PID
));
270 return callbackHandler
;
277 /** Session is logged out. */
278 private void prepareDataModel(String cn
, Repository repository
, List
<String
> publishAsLocalRepo
) {
279 Session adminSession
= KernelUtils
.openAdminSession(repository
);
281 Set
<String
> processed
= new HashSet
<String
>();
282 bundles
: for (Bundle bundle
: bc
.getBundles()) {
283 BundleWiring wiring
= bundle
.adapt(BundleWiring
.class);
286 if (CmsConstants
.NODE_REPOSITORY
.equals(cn
))// process all data models
287 processWiring(cn
, adminSession
, wiring
, processed
, false, publishAsLocalRepo
);
289 List
<BundleCapability
> capabilities
= wiring
.getCapabilities(CMS_DATA_MODEL_NAMESPACE
);
290 for (BundleCapability capability
: capabilities
) {
291 String dataModelName
= (String
) capability
.getAttributes().get(DataModelNamespace
.NAME
);
292 if (dataModelName
.equals(cn
))// process only own data model
293 processWiring(cn
, adminSession
, wiring
, processed
, false, publishAsLocalRepo
);
298 JcrUtils
.logoutQuietly(adminSession
);
302 private void processWiring(String cn
, Session adminSession
, BundleWiring wiring
, Set
<String
> processed
,
303 boolean importListedAbstractModels
, List
<String
> publishAsLocalRepo
) {
304 // recursively process requirements first
305 List
<BundleWire
> requiredWires
= wiring
.getRequiredWires(CMS_DATA_MODEL_NAMESPACE
);
306 for (BundleWire wire
: requiredWires
) {
307 processWiring(cn
, adminSession
, wire
.getProviderWiring(), processed
, true, publishAsLocalRepo
);
310 List
<BundleCapability
> capabilities
= wiring
.getCapabilities(CMS_DATA_MODEL_NAMESPACE
);
311 capabilities
: for (BundleCapability capability
: capabilities
) {
312 if (!importListedAbstractModels
313 && KernelUtils
.asBoolean((String
) capability
.getAttributes().get(DataModelNamespace
.ABSTRACT
))) {
314 continue capabilities
;
316 boolean publish
= registerDataModelCapability(cn
, adminSession
, capability
, processed
);
318 publishAsLocalRepo
.add((String
) capability
.getAttributes().get(DataModelNamespace
.NAME
));
322 private boolean registerDataModelCapability(String cn
, Session adminSession
, BundleCapability capability
,
323 Set
<String
> processed
) {
324 Map
<String
, Object
> attrs
= capability
.getAttributes();
325 String name
= (String
) attrs
.get(DataModelNamespace
.NAME
);
326 if (processed
.contains(name
)) {
327 if (log
.isTraceEnabled())
328 log
.trace("Data model " + name
+ " has already been processed");
333 String path
= (String
) attrs
.get(DataModelNamespace
.CND
);
335 File dataModel
= bc
.getBundle().getDataFile("dataModels/" + path
);
336 if (!dataModel
.exists()) {
337 URL url
= capability
.getRevision().getBundle().getResource(path
);
339 throw new IllegalArgumentException("No data model '" + name
+ "' found under path " + path
);
340 try (Reader reader
= new InputStreamReader(url
.openStream())) {
341 CndImporter
.registerNodeTypes(reader
, adminSession
, true);
343 dataModel
.getParentFile().mkdirs();
344 dataModel
.createNewFile();
345 if (log
.isDebugEnabled())
346 log
.debug("Registered CND " + url
);
347 } catch (Exception e
) {
348 log
.error("Cannot import CND " + url
, e
);
353 if (KernelUtils
.asBoolean((String
) attrs
.get(DataModelNamespace
.ABSTRACT
)))
356 boolean isStandalone
= isStandalone(name
);
357 boolean publishLocalRepo
;
358 if (isStandalone
&& name
.equals(cn
))// includes the node itself
359 publishLocalRepo
= true;
360 else if (!isStandalone
&& cn
.equals(CmsConstants
.NODE_REPOSITORY
))
361 publishLocalRepo
= true;
363 publishLocalRepo
= false;
365 return publishLocalRepo
;
368 boolean isStandalone(String dataModelName
) {
369 return cmsDeployment
.getProps(CmsConstants
.NODE_REPOS_FACTORY_PID
, dataModelName
) != null;
372 private void publishLocalRepo(String dataModelName
, Repository repository
) {
373 Hashtable
<String
, Object
> properties
= new Hashtable
<>();
374 properties
.put(CmsConstants
.CN
, dataModelName
);
375 LocalRepository localRepository
;
377 if (repository
instanceof RepositoryImpl
) {
378 localRepository
= new JackrabbitLocalRepository((RepositoryImpl
) repository
, dataModelName
);
379 classes
= new String
[] { Repository
.class.getName(), LocalRepository
.class.getName(),
380 JackrabbitLocalRepository
.class.getName() };
382 localRepository
= new LocalRepository(repository
, dataModelName
);
383 classes
= new String
[] { Repository
.class.getName(), LocalRepository
.class.getName() };
385 bc
.registerService(classes
, localRepository
, properties
);
387 // TODO make it configurable
388 registerRepositoryServlets(dataModelName
, localRepository
);
389 if (log
.isTraceEnabled())
390 log
.trace("Published data model " + dataModelName
);
394 // public synchronized Long getAvailableSince() {
395 // return availableSince;
398 // public synchronized boolean isAvailable() {
399 // return availableSince != null;
402 protected void registerRepositoryServlets(String alias
, Repository repository
) {
403 registerRemotingServlet(alias
, repository
);
404 registerWebdavServlet(alias
, repository
);
407 protected void registerWebdavServlet(String alias
, Repository repository
) {
408 CmsWebDavServlet webdavServlet
= new CmsWebDavServlet(alias
, repository
);
409 Hashtable
<String
, String
> ip
= new Hashtable
<>();
410 ip
.put(HTTP_WHITEBOARD_SERVLET_INIT_PARAM_PREFIX
+ CmsWebDavServlet
.INIT_PARAM_RESOURCE_CONFIG
, webDavConfig
);
411 ip
.put(HTTP_WHITEBOARD_SERVLET_INIT_PARAM_PREFIX
+ CmsWebDavServlet
.INIT_PARAM_RESOURCE_PATH_PREFIX
,
414 ip
.put(HttpWhiteboardConstants
.HTTP_WHITEBOARD_SERVLET_PATTERN
, "/" + alias
+ "/*");
415 ip
.put(HttpWhiteboardConstants
.HTTP_WHITEBOARD_CONTEXT_SELECT
,
416 "(" + HttpWhiteboardConstants
.HTTP_WHITEBOARD_CONTEXT_PATH
+ "=" + CmsConstants
.PATH_DATA
+ ")");
417 bc
.registerService(Servlet
.class, webdavServlet
, ip
);
420 protected void registerRemotingServlet(String alias
, Repository repository
) {
421 CmsRemotingServlet remotingServlet
= new CmsRemotingServlet(alias
, repository
);
422 Hashtable
<String
, String
> ip
= new Hashtable
<>();
423 ip
.put(CmsConstants
.CN
, alias
);
424 // Properties ip = new Properties();
425 ip
.put(HTTP_WHITEBOARD_SERVLET_INIT_PARAM_PREFIX
+ CmsRemotingServlet
.INIT_PARAM_RESOURCE_PATH_PREFIX
,
427 ip
.put(HTTP_WHITEBOARD_SERVLET_INIT_PARAM_PREFIX
+ CmsRemotingServlet
.INIT_PARAM_AUTHENTICATE_HEADER
,
430 // Looks like a bug in Jackrabbit remoting init
433 tmpDir
= Files
.createTempDirectory("remoting_" + alias
);
434 } catch (IOException e
) {
435 throw new RuntimeException("Cannot create temp directory for remoting servlet", e
);
437 ip
.put(HTTP_WHITEBOARD_SERVLET_INIT_PARAM_PREFIX
+ CmsRemotingServlet
.INIT_PARAM_HOME
, tmpDir
.toString());
438 ip
.put(HTTP_WHITEBOARD_SERVLET_INIT_PARAM_PREFIX
+ CmsRemotingServlet
.INIT_PARAM_TMP_DIRECTORY
,
439 "remoting_" + alias
);
440 ip
.put(HTTP_WHITEBOARD_SERVLET_INIT_PARAM_PREFIX
+ CmsRemotingServlet
.INIT_PARAM_PROTECTED_HANDLERS_CONFIG
,
441 JcrHttpUtils
.DEFAULT_PROTECTED_HANDLERS
);
442 ip
.put(HTTP_WHITEBOARD_SERVLET_INIT_PARAM_PREFIX
+ CmsRemotingServlet
.INIT_PARAM_CREATE_ABSOLUTE_URI
, "false");
444 ip
.put(HttpWhiteboardConstants
.HTTP_WHITEBOARD_SERVLET_PATTERN
, "/" + alias
+ "/*");
445 ip
.put(HttpWhiteboardConstants
.HTTP_WHITEBOARD_CONTEXT_SELECT
,
446 "(" + HttpWhiteboardConstants
.HTTP_WHITEBOARD_CONTEXT_PATH
+ "=" + CmsConstants
.PATH_JCR
+ ")");
447 bc
.registerService(Servlet
.class, remotingServlet
, ip
);
450 private class RepositoryContextStc
extends ServiceTracker
<RepositoryContext
, RepositoryContext
> {
452 public RepositoryContextStc() {
453 super(bc
, RepositoryContext
.class, null);
457 public RepositoryContext
addingService(ServiceReference
<RepositoryContext
> reference
) {
458 RepositoryContext repoContext
= bc
.getService(reference
);
459 String cn
= (String
) reference
.getProperty(CmsConstants
.CN
);
461 List
<String
> publishAsLocalRepo
= new ArrayList
<>();
462 if (cn
.equals(CmsConstants
.NODE_REPOSITORY
)) {
463 // JackrabbitDataModelMigration.clearRepositoryCaches(repoContext.getRepositoryConfig());
464 prepareNodeRepository(repoContext
.getRepository(), publishAsLocalRepo
);
465 // TODO separate home repository
466 prepareHomeRepository(repoContext
.getRepository());
467 registerRepositoryServlets(cn
, repoContext
.getRepository());
468 nodeAvailable
= true;
471 prepareDataModel(cn
, repoContext
.getRepository(), publishAsLocalRepo
);
473 // Publish all at once, so that bundles with multiple CNDs are consistent
474 for (String dataModelName
: publishAsLocalRepo
)
475 publishLocalRepo(dataModelName
, repoContext
.getRepository());
481 public void modifiedService(ServiceReference
<RepositoryContext
> reference
, RepositoryContext service
) {
485 public void removedService(ServiceReference
<RepositoryContext
> reference
, RepositoryContext service
) {