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
.Repository
;
24 import javax
.jcr
.RepositoryException
;
25 import javax
.jcr
.Session
;
26 import javax
.security
.auth
.callback
.CallbackHandler
;
27 import javax
.servlet
.Servlet
;
29 import org
.apache
.jackrabbit
.commons
.cnd
.CndImporter
;
30 import org
.apache
.jackrabbit
.core
.RepositoryContext
;
31 import org
.apache
.jackrabbit
.core
.RepositoryImpl
;
32 import org
.argeo
.api
.cms
.CmsConstants
;
33 import org
.argeo
.api
.cms
.CmsDeployment
;
34 import org
.argeo
.api
.cms
.CmsLog
;
35 import org
.argeo
.cms
.ArgeoNames
;
36 import org
.argeo
.cms
.internal
.jcr
.JcrInitUtils
;
37 import org
.argeo
.cms
.jcr
.CmsJcrUtils
;
38 import org
.argeo
.cms
.jcr
.internal
.servlet
.CmsRemotingServlet
;
39 import org
.argeo
.cms
.jcr
.internal
.servlet
.CmsWebDavServlet
;
40 import org
.argeo
.cms
.jcr
.internal
.servlet
.JcrHttpUtils
;
41 import org
.argeo
.cms
.osgi
.DataModelNamespace
;
42 import org
.argeo
.cms
.security
.CryptoKeyring
;
43 import org
.argeo
.cms
.security
.Keyring
;
44 import org
.argeo
.jcr
.Jcr
;
45 import org
.argeo
.jcr
.JcrException
;
46 import org
.argeo
.jcr
.JcrUtils
;
47 import org
.argeo
.util
.LangUtils
;
48 import org
.argeo
.util
.naming
.LdapAttrs
;
49 import org
.osgi
.framework
.Bundle
;
50 import org
.osgi
.framework
.BundleContext
;
51 import org
.osgi
.framework
.Constants
;
52 import org
.osgi
.framework
.FrameworkUtil
;
53 import org
.osgi
.framework
.InvalidSyntaxException
;
54 import org
.osgi
.framework
.ServiceReference
;
55 import org
.osgi
.framework
.wiring
.BundleCapability
;
56 import org
.osgi
.framework
.wiring
.BundleWire
;
57 import org
.osgi
.framework
.wiring
.BundleWiring
;
58 import org
.osgi
.service
.cm
.ManagedService
;
59 import org
.osgi
.service
.http
.whiteboard
.HttpWhiteboardConstants
;
60 import org
.osgi
.util
.tracker
.ServiceTracker
;
62 /** Implementation of a CMS deployment. */
63 public class CmsJcrDeployment
{
64 private final CmsLog log
= CmsLog
.getLog(getClass());
65 private final BundleContext bc
= FrameworkUtil
.getBundle(getClass()).getBundleContext();
67 private DataModels dataModels
;
68 private String webDavConfig
= JcrHttpUtils
.WEBDAV_CONFIG
;
70 private boolean argeoDataModelExtensionsAvailable
= false;
73 private boolean nodeAvailable
= false;
75 CmsDeployment cmsDeployment
;
78 dataModels
= new DataModels(bc
);
80 ServiceTracker
<?
, ?
> repoContextSt
= new RepositoryContextStc();
82 //KernelUtils.asyncOpen(repoContextSt);
84 // nodeDeployment = CmsJcrActivator.getService(NodeDeployment.class);
86 JcrInitUtils
.addToDeployment(cmsDeployment
);
91 // if (nodeHttp != null)
92 // nodeHttp.destroy();
95 for (ServiceReference
<JackrabbitLocalRepository
> sr
: bc
96 .getServiceReferences(JackrabbitLocalRepository
.class, null)) {
97 bc
.getService(sr
).destroy();
99 } catch (InvalidSyntaxException e1
) {
100 log
.error("Cannot clean repositories", e1
);
105 public void setCmsDeployment(CmsDeployment cmsDeployment
) {
106 this.cmsDeployment
= cmsDeployment
;
110 * Checks whether the deployment is available according to expectations, and
111 * mark it as available.
113 // private synchronized void checkReadiness() {
114 // if (isAvailable())
116 // if (nodeAvailable && userAdminAvailable && (httpExpected ? httpAvailable : true)) {
117 // String data = KernelUtils.getFrameworkProp(KernelUtils.OSGI_INSTANCE_AREA);
118 // String state = KernelUtils.getFrameworkProp(KernelUtils.OSGI_CONFIGURATION_AREA);
119 // availableSince = System.currentTimeMillis();
120 // long jvmUptime = ManagementFactory.getRuntimeMXBean().getUptime();
121 // String jvmUptimeStr = " in " + (jvmUptime / 1000) + "." + (jvmUptime % 1000) + "s";
122 // log.info("## ARGEO NODE AVAILABLE" + (log.isDebugEnabled() ? jvmUptimeStr : "") + " ##");
123 // if (log.isDebugEnabled()) {
124 // log.debug("## state: " + state);
126 // log.debug("## data: " + data);
128 // long begin = bc.getService(bc.getServiceReference(NodeState.class)).getAvailableSince();
129 // long initDuration = System.currentTimeMillis() - begin;
130 // if (log.isTraceEnabled())
131 // log.trace("Kernel initialization took " + initDuration + "ms");
132 // tributeToFreeSoftware(initDuration);
136 private void prepareNodeRepository(Repository deployedNodeRepository
, List
<String
> publishAsLocalRepo
) {
137 // if (availableSince != null) {
138 // throw new IllegalStateException("Deployment is already available");
142 prepareDataModel(CmsConstants
.NODE_REPOSITORY
, deployedNodeRepository
, publishAsLocalRepo
);
145 // if (deployConfig.isFirstInit()) {
146 // Path restorePath = Paths.get(System.getProperty("user.dir"), "restore");
147 // if (Files.exists(restorePath)) {
148 // if (log.isDebugEnabled())
149 // log.debug("Found backup " + restorePath + ", restoring it...");
150 // LogicalRestore logicalRestore = new LogicalRestore(bc, deployedNodeRepository, restorePath);
151 // KernelUtils.doAsDataAdmin(logicalRestore);
152 // log.info("Restored backup from " + restorePath);
156 // init from repository
157 Collection
<ServiceReference
<Repository
>> initRepositorySr
;
159 initRepositorySr
= bc
.getServiceReferences(Repository
.class,
160 "(" + CmsConstants
.CN
+ "=" + CmsConstants
.NODE_INIT
+ ")");
161 } catch (InvalidSyntaxException e1
) {
162 throw new IllegalArgumentException(e1
);
164 Iterator
<ServiceReference
<Repository
>> it
= initRepositorySr
.iterator();
165 while (it
.hasNext()) {
166 ServiceReference
<Repository
> sr
= it
.next();
167 Object labeledUri
= sr
.getProperties().get(LdapAttrs
.labeledURI
.name());
168 Repository initRepository
= bc
.getService(sr
);
169 if (log
.isDebugEnabled())
170 log
.debug("Found init repository " + labeledUri
+ ", copying it...");
171 initFromRepository(deployedNodeRepository
, initRepository
);
172 log
.info("Node repository initialised from " + labeledUri
);
176 /** Init from a (typically remote) repository. */
177 private void initFromRepository(Repository deployedNodeRepository
, Repository initRepository
) {
178 Session initSession
= null;
180 initSession
= initRepository
.login();
181 workspaces
: for (String workspaceName
: initSession
.getWorkspace().getAccessibleWorkspaceNames()) {
182 if ("security".equals(workspaceName
))
184 if (log
.isDebugEnabled())
185 log
.debug("Copying workspace " + workspaceName
+ " from init repository...");
186 long begin
= System
.currentTimeMillis();
187 Session targetSession
= null;
188 Session sourceSession
= null;
191 targetSession
= CmsJcrUtils
.openDataAdminSession(deployedNodeRepository
, workspaceName
);
192 } catch (IllegalArgumentException e
) {// no such workspace
193 Session adminSession
= CmsJcrUtils
.openDataAdminSession(deployedNodeRepository
, null);
195 adminSession
.getWorkspace().createWorkspace(workspaceName
);
197 Jcr
.logout(adminSession
);
199 targetSession
= CmsJcrUtils
.openDataAdminSession(deployedNodeRepository
, workspaceName
);
201 sourceSession
= initRepository
.login(workspaceName
);
202 // JcrUtils.copyWorkspaceXml(sourceSession, targetSession);
203 // TODO deal with referenceable nodes
204 JcrUtils
.copy(sourceSession
.getRootNode(), targetSession
.getRootNode());
205 targetSession
.save();
206 long duration
= System
.currentTimeMillis() - begin
;
207 if (log
.isDebugEnabled())
208 log
.debug("Copied workspace " + workspaceName
+ " from init repository in " + (duration
/ 1000)
210 } catch (Exception e
) {
211 log
.error("Cannot copy workspace " + workspaceName
+ " from init repository.", e
);
213 Jcr
.logout(sourceSession
);
214 Jcr
.logout(targetSession
);
217 } catch (RepositoryException e
) {
218 throw new JcrException(e
);
220 Jcr
.logout(initSession
);
224 private void prepareHomeRepository(RepositoryImpl deployedRepository
) {
225 Session adminSession
= KernelUtils
.openAdminSession(deployedRepository
);
227 argeoDataModelExtensionsAvailable
= Arrays
228 .asList(adminSession
.getWorkspace().getNamespaceRegistry().getURIs())
229 .contains(ArgeoNames
.ARGEO_NAMESPACE
);
230 } catch (RepositoryException e
) {
231 log
.warn("Cannot check whether Argeo namespace is registered assuming it isn't.", e
);
232 argeoDataModelExtensionsAvailable
= false;
234 JcrUtils
.logoutQuietly(adminSession
);
237 // Publish home with the highest service ranking
238 Hashtable
<String
, Object
> regProps
= new Hashtable
<>();
239 regProps
.put(CmsConstants
.CN
, CmsConstants
.EGO_REPOSITORY
);
240 regProps
.put(Constants
.SERVICE_RANKING
, Integer
.MAX_VALUE
);
241 Repository egoRepository
= new EgoRepository(deployedRepository
, false);
242 bc
.registerService(Repository
.class, egoRepository
, regProps
);
243 registerRepositoryServlets(CmsConstants
.EGO_REPOSITORY
, egoRepository
);
245 // Keyring only if Argeo extensions are available
246 if (argeoDataModelExtensionsAvailable
) {
247 new ServiceTracker
<CallbackHandler
, CallbackHandler
>(bc
, CallbackHandler
.class, null) {
250 public CallbackHandler
addingService(ServiceReference
<CallbackHandler
> reference
) {
251 NodeKeyRing nodeKeyring
= new NodeKeyRing(egoRepository
);
252 CallbackHandler callbackHandler
= bc
.getService(reference
);
253 nodeKeyring
.setDefaultCallbackHandler(callbackHandler
);
254 bc
.registerService(LangUtils
.names(Keyring
.class, CryptoKeyring
.class, ManagedService
.class),
255 nodeKeyring
, LangUtils
.dict(Constants
.SERVICE_PID
, CmsConstants
.NODE_KEYRING_PID
));
256 return callbackHandler
;
263 /** Session is logged out. */
264 private void prepareDataModel(String cn
, Repository repository
, List
<String
> publishAsLocalRepo
) {
265 Session adminSession
= KernelUtils
.openAdminSession(repository
);
267 Set
<String
> processed
= new HashSet
<String
>();
268 bundles
: for (Bundle bundle
: bc
.getBundles()) {
269 BundleWiring wiring
= bundle
.adapt(BundleWiring
.class);
272 if (CmsConstants
.NODE_REPOSITORY
.equals(cn
))// process all data models
273 processWiring(cn
, adminSession
, wiring
, processed
, false, publishAsLocalRepo
);
275 List
<BundleCapability
> capabilities
= wiring
.getCapabilities(CMS_DATA_MODEL_NAMESPACE
);
276 for (BundleCapability capability
: capabilities
) {
277 String dataModelName
= (String
) capability
.getAttributes().get(DataModelNamespace
.NAME
);
278 if (dataModelName
.equals(cn
))// process only own data model
279 processWiring(cn
, adminSession
, wiring
, processed
, false, publishAsLocalRepo
);
284 JcrUtils
.logoutQuietly(adminSession
);
288 private void processWiring(String cn
, Session adminSession
, BundleWiring wiring
, Set
<String
> processed
,
289 boolean importListedAbstractModels
, List
<String
> publishAsLocalRepo
) {
290 // recursively process requirements first
291 List
<BundleWire
> requiredWires
= wiring
.getRequiredWires(CMS_DATA_MODEL_NAMESPACE
);
292 for (BundleWire wire
: requiredWires
) {
293 processWiring(cn
, adminSession
, wire
.getProviderWiring(), processed
, true, publishAsLocalRepo
);
296 List
<BundleCapability
> capabilities
= wiring
.getCapabilities(CMS_DATA_MODEL_NAMESPACE
);
297 capabilities
: for (BundleCapability capability
: capabilities
) {
298 if (!importListedAbstractModels
299 && KernelUtils
.asBoolean((String
) capability
.getAttributes().get(DataModelNamespace
.ABSTRACT
))) {
300 continue capabilities
;
302 boolean publish
= registerDataModelCapability(cn
, adminSession
, capability
, processed
);
304 publishAsLocalRepo
.add((String
) capability
.getAttributes().get(DataModelNamespace
.NAME
));
308 private boolean registerDataModelCapability(String cn
, Session adminSession
, BundleCapability capability
,
309 Set
<String
> processed
) {
310 Map
<String
, Object
> attrs
= capability
.getAttributes();
311 String name
= (String
) attrs
.get(DataModelNamespace
.NAME
);
312 if (processed
.contains(name
)) {
313 if (log
.isTraceEnabled())
314 log
.trace("Data model " + name
+ " has already been processed");
319 String path
= (String
) attrs
.get(DataModelNamespace
.CND
);
321 File dataModel
= bc
.getBundle().getDataFile("dataModels/" + path
);
322 if (!dataModel
.exists()) {
323 URL url
= capability
.getRevision().getBundle().getResource(path
);
325 throw new IllegalArgumentException("No data model '" + name
+ "' found under path " + path
);
326 try (Reader reader
= new InputStreamReader(url
.openStream())) {
327 CndImporter
.registerNodeTypes(reader
, adminSession
, true);
329 dataModel
.getParentFile().mkdirs();
330 dataModel
.createNewFile();
331 if (log
.isDebugEnabled())
332 log
.debug("Registered CND " + url
);
333 } catch (Exception e
) {
334 log
.error("Cannot import CND " + url
, e
);
339 if (KernelUtils
.asBoolean((String
) attrs
.get(DataModelNamespace
.ABSTRACT
)))
342 boolean isStandalone
= isStandalone(name
);
343 boolean publishLocalRepo
;
344 if (isStandalone
&& name
.equals(cn
))// includes the node itself
345 publishLocalRepo
= true;
346 else if (!isStandalone
&& cn
.equals(CmsConstants
.NODE_REPOSITORY
))
347 publishLocalRepo
= true;
349 publishLocalRepo
= false;
351 return publishLocalRepo
;
354 boolean isStandalone(String dataModelName
) {
355 return cmsDeployment
.getProps(CmsConstants
.NODE_REPOS_FACTORY_PID
, dataModelName
) != null;
358 private void publishLocalRepo(String dataModelName
, Repository repository
) {
359 Hashtable
<String
, Object
> properties
= new Hashtable
<>();
360 properties
.put(CmsConstants
.CN
, dataModelName
);
361 LocalRepository localRepository
;
363 if (repository
instanceof RepositoryImpl
) {
364 localRepository
= new JackrabbitLocalRepository((RepositoryImpl
) repository
, dataModelName
);
365 classes
= new String
[] { Repository
.class.getName(), LocalRepository
.class.getName(),
366 JackrabbitLocalRepository
.class.getName() };
368 localRepository
= new LocalRepository(repository
, dataModelName
);
369 classes
= new String
[] { Repository
.class.getName(), LocalRepository
.class.getName() };
371 bc
.registerService(classes
, localRepository
, properties
);
373 // TODO make it configurable
374 registerRepositoryServlets(dataModelName
, localRepository
);
375 if (log
.isTraceEnabled())
376 log
.trace("Published data model " + dataModelName
);
380 // public synchronized Long getAvailableSince() {
381 // return availableSince;
384 // public synchronized boolean isAvailable() {
385 // return availableSince != null;
388 protected void registerRepositoryServlets(String alias
, Repository repository
) {
389 registerRemotingServlet(alias
, repository
);
390 registerWebdavServlet(alias
, repository
);
393 protected void registerWebdavServlet(String alias
, Repository repository
) {
394 CmsWebDavServlet webdavServlet
= new CmsWebDavServlet(alias
, repository
);
395 Hashtable
<String
, String
> ip
= new Hashtable
<>();
396 ip
.put(HTTP_WHITEBOARD_SERVLET_INIT_PARAM_PREFIX
+ CmsWebDavServlet
.INIT_PARAM_RESOURCE_CONFIG
, webDavConfig
);
397 ip
.put(HTTP_WHITEBOARD_SERVLET_INIT_PARAM_PREFIX
+ CmsWebDavServlet
.INIT_PARAM_RESOURCE_PATH_PREFIX
,
400 ip
.put(HttpWhiteboardConstants
.HTTP_WHITEBOARD_SERVLET_PATTERN
, "/" + alias
+ "/*");
401 ip
.put(HttpWhiteboardConstants
.HTTP_WHITEBOARD_CONTEXT_SELECT
,
402 "(" + HttpWhiteboardConstants
.HTTP_WHITEBOARD_CONTEXT_PATH
+ "=" + CmsConstants
.PATH_DATA
+ ")");
403 bc
.registerService(Servlet
.class, webdavServlet
, ip
);
406 protected void registerRemotingServlet(String alias
, Repository repository
) {
407 CmsRemotingServlet remotingServlet
= new CmsRemotingServlet(alias
, repository
);
408 Hashtable
<String
, String
> ip
= new Hashtable
<>();
409 ip
.put(CmsConstants
.CN
, alias
);
410 // Properties ip = new Properties();
411 ip
.put(HTTP_WHITEBOARD_SERVLET_INIT_PARAM_PREFIX
+ CmsRemotingServlet
.INIT_PARAM_RESOURCE_PATH_PREFIX
,
413 ip
.put(HTTP_WHITEBOARD_SERVLET_INIT_PARAM_PREFIX
+ CmsRemotingServlet
.INIT_PARAM_AUTHENTICATE_HEADER
,
416 // Looks like a bug in Jackrabbit remoting init
419 tmpDir
= Files
.createTempDirectory("remoting_" + alias
);
420 } catch (IOException e
) {
421 throw new RuntimeException("Cannot create temp directory for remoting servlet", e
);
423 ip
.put(HTTP_WHITEBOARD_SERVLET_INIT_PARAM_PREFIX
+ CmsRemotingServlet
.INIT_PARAM_HOME
, tmpDir
.toString());
424 ip
.put(HTTP_WHITEBOARD_SERVLET_INIT_PARAM_PREFIX
+ CmsRemotingServlet
.INIT_PARAM_TMP_DIRECTORY
,
425 "remoting_" + alias
);
426 ip
.put(HTTP_WHITEBOARD_SERVLET_INIT_PARAM_PREFIX
+ CmsRemotingServlet
.INIT_PARAM_PROTECTED_HANDLERS_CONFIG
,
427 JcrHttpUtils
.DEFAULT_PROTECTED_HANDLERS
);
428 ip
.put(HTTP_WHITEBOARD_SERVLET_INIT_PARAM_PREFIX
+ CmsRemotingServlet
.INIT_PARAM_CREATE_ABSOLUTE_URI
, "false");
430 ip
.put(HttpWhiteboardConstants
.HTTP_WHITEBOARD_SERVLET_PATTERN
, "/" + alias
+ "/*");
431 ip
.put(HttpWhiteboardConstants
.HTTP_WHITEBOARD_CONTEXT_SELECT
,
432 "(" + HttpWhiteboardConstants
.HTTP_WHITEBOARD_CONTEXT_PATH
+ "=" + CmsConstants
.PATH_JCR
+ ")");
433 bc
.registerService(Servlet
.class, remotingServlet
, ip
);
436 private class RepositoryContextStc
extends ServiceTracker
<RepositoryContext
, RepositoryContext
> {
438 public RepositoryContextStc() {
439 super(bc
, RepositoryContext
.class, null);
443 public RepositoryContext
addingService(ServiceReference
<RepositoryContext
> reference
) {
444 RepositoryContext repoContext
= bc
.getService(reference
);
445 String cn
= (String
) reference
.getProperty(CmsConstants
.CN
);
447 List
<String
> publishAsLocalRepo
= new ArrayList
<>();
448 if (cn
.equals(CmsConstants
.NODE_REPOSITORY
)) {
449 // JackrabbitDataModelMigration.clearRepositoryCaches(repoContext.getRepositoryConfig());
450 prepareNodeRepository(repoContext
.getRepository(), publishAsLocalRepo
);
451 // TODO separate home repository
452 prepareHomeRepository(repoContext
.getRepository());
453 registerRepositoryServlets(cn
, repoContext
.getRepository());
454 nodeAvailable
= true;
457 prepareDataModel(cn
, repoContext
.getRepository(), publishAsLocalRepo
);
459 // Publish all at once, so that bundles with multiple CNDs are consistent
460 for (String dataModelName
: publishAsLocalRepo
)
461 publishLocalRepo(dataModelName
, repoContext
.getRepository());
467 public void modifiedService(ServiceReference
<RepositoryContext
> reference
, RepositoryContext service
) {
471 public void removedService(ServiceReference
<RepositoryContext
> reference
, RepositoryContext service
) {