Start factoring OSGi accesses.
authorMathieu Baudier <mbaudier@argeo.org>
Mon, 9 Nov 2020 13:42:11 +0000 (14:42 +0100)
committerMathieu Baudier <mbaudier@argeo.org>
Mon, 9 Nov 2020 13:42:11 +0000 (14:42 +0100)
org.argeo.cms/src/org/argeo/cms/internal/kernel/Activator.java
org.argeo.cms/src/org/argeo/cms/internal/kernel/CmsShutdown.java
org.argeo.cms/src/org/argeo/cms/internal/kernel/CmsState.java
org.argeo.cms/src/org/argeo/cms/internal/kernel/KernelUtils.java
org.argeo.cms/src/org/argeo/cms/internal/kernel/NodeLogger.java
org.argeo.cms/src/org/argeo/cms/internal/kernel/NodeRepositoryFactory.java
org.argeo.cms/src/org/argeo/cms/internal/kernel/NodeUserAdmin.java
org.argeo.cms/src/org/argeo/cms/internal/kernel/RepositoryServiceFactory.java

index 7b2cb78bfe403105566d7b1a60468cf399b711ab..ae482d792e5703d7a935abed11c4d9e8638e92be 100644 (file)
@@ -3,6 +3,7 @@ package org.argeo.cms.internal.kernel;
 import java.io.IOException;
 import java.net.URL;
 import java.security.AllPermission;
+import java.util.Dictionary;
 import java.util.List;
 import java.util.Locale;
 import java.util.concurrent.ExecutorService;
@@ -17,13 +18,13 @@ import org.argeo.api.NodeConstants;
 import org.argeo.api.NodeDeployment;
 import org.argeo.api.NodeInstance;
 import org.argeo.api.NodeState;
-import org.argeo.cms.CmsException;
 import org.argeo.ident.IdentClient;
 import org.ietf.jgss.GSSCredential;
+import org.osgi.framework.Bundle;
 import org.osgi.framework.BundleActivator;
 import org.osgi.framework.BundleContext;
 import org.osgi.framework.Constants;
-import org.osgi.framework.ServiceReference;
+import org.osgi.framework.FrameworkUtil;
 import org.osgi.service.condpermadmin.BundleLocationCondition;
 import org.osgi.service.condpermadmin.ConditionInfo;
 import org.osgi.service.condpermadmin.ConditionalPermissionAdmin;
@@ -46,7 +47,7 @@ public class Activator implements BundleActivator {
        // TODO make it configurable
        private boolean hardened = false;
 
-       private BundleContext bc;
+       private static BundleContext bundleContext;
 
        private LogReaderService logReaderService;
 
@@ -58,12 +59,19 @@ public class Activator implements BundleActivator {
        private ServiceTracker<UserAdmin, NodeUserAdmin> userAdminSt;
        private ExecutorService internalExecutorService;
 
-       @Override
-       public void start(BundleContext bundleContext) throws Exception {
+       static {
+               Bundle bundle = FrameworkUtil.getBundle(Activator.class);
+               if (bundle != null) {
+                       bundleContext = bundle.getBundleContext();
+               }
+       }
+
+       void init() {
                Runtime.getRuntime().addShutdownHook(new CmsShutdown());
                instance = this;
-               this.bc = bundleContext;
-               this.logReaderService = getService(LogReaderService.class);
+//             this.bc = bundleContext;
+               if (bundleContext != null)
+                       this.logReaderService = getService(LogReaderService.class);
                this.internalExecutorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
 
                try {
@@ -71,8 +79,6 @@ public class Activator implements BundleActivator {
                        initArgeoLogger();
                        initNode();
 
-                       userAdminSt = new ServiceTracker<>(instance.bc, UserAdmin.class, null);
-                       userAdminSt.open();
                        if (log.isTraceEnabled())
                                log.trace("Kernel bundle started");
                } catch (Throwable e) {
@@ -80,10 +86,32 @@ public class Activator implements BundleActivator {
                }
        }
 
+       void destroy() {
+               try {
+                       if (nodeInstance != null)
+                               nodeInstance.shutdown();
+                       if (nodeDeployment != null)
+                               nodeDeployment.shutdown();
+                       if (nodeState != null)
+                               nodeState.shutdown();
+
+                       if (userAdminSt != null)
+                               userAdminSt.close();
+
+                       internalExecutorService.shutdown();
+                       instance = null;
+                       bundleContext = null;
+                       this.logReaderService = null;
+                       // this.configurationAdmin = null;
+               } catch (Exception e) {
+                       log.error("CMS activator shutdown failed", e);
+               }
+       }
+
        private void initSecurity() {
                if (System.getProperty(KernelConstants.JAAS_CONFIG_PROP) == null) {
                        String jaasConfig = KernelConstants.JAAS_CONFIG;
-                       URL url = getClass().getClassLoader().getResource(jaasConfig);
+                       URL url = getClass().getResource(jaasConfig);
                        // System.setProperty(KernelConstants.JAAS_CONFIG_PROP,
                        // url.toExternalForm());
                        KernelUtils.setJaasConfiguration(url);
@@ -95,8 +123,8 @@ public class Activator implements BundleActivator {
                String osgiSecurity = KernelUtils.getFrameworkProp(Constants.FRAMEWORK_SECURITY);
                if (osgiSecurity != null && Constants.FRAMEWORK_SECURITY_OSGI.equals(osgiSecurity)) {
                        // TODO rather use a tracker?
-                       ConditionalPermissionAdmin permissionAdmin = bc
-                                       .getService(bc.getServiceReference(ConditionalPermissionAdmin.class));
+                       ConditionalPermissionAdmin permissionAdmin = bundleContext
+                                       .getService(bundleContext.getServiceReference(ConditionalPermissionAdmin.class));
                        if (!hardened) {
                                // All permissions to all bundles
                                ConditionalPermissionUpdate update = permissionAdmin.newConditionalPermissionUpdate();
@@ -128,7 +156,8 @@ public class Activator implements BundleActivator {
 
        private void initArgeoLogger() {
                logger = new NodeLogger(logReaderService);
-               bc.registerService(ArgeoLogger.class, logger, null);
+               if (bundleContext != null)
+                       bundleContext.registerService(ArgeoLogger.class, logger, null);
        }
 
        private void initNode() throws IOException {
@@ -144,47 +173,61 @@ public class Activator implements BundleActivator {
                nodeState = new CmsState();
 //             Dictionary<String, Object> regProps = LangUtils.dico(Constants.SERVICE_PID, NodeConstants.NODE_STATE_PID);
 //             regProps.put(NodeConstants.CN, stateUuid);
-               bc.registerService(NodeState.class, nodeState, null);
+               registerService(NodeState.class, nodeState, null);
 
                // Node deployment
                nodeDeployment = new CmsDeployment();
-               bc.registerService(NodeDeployment.class, nodeDeployment, null);
+               registerService(NodeDeployment.class, nodeDeployment, null);
 
                // Node instance
                nodeInstance = new CmsInstance();
-               bc.registerService(NodeInstance.class, nodeInstance, null);
+               registerService(NodeInstance.class, nodeInstance, null);
        }
 
-       @Override
-       public void stop(BundleContext bundleContext) throws Exception {
-               try {
-                       if (nodeInstance != null)
-                               nodeInstance.shutdown();
-                       if (nodeDeployment != null)
-                               nodeDeployment.shutdown();
-                       if (nodeState != null)
-                               nodeState.shutdown();
+       public static <T> void registerService(Class<T> clss, T service, Dictionary<String, ?> properties) {
+               if (bundleContext != null) {
+                       bundleContext.registerService(clss, service, properties);
+               }
 
-                       if (userAdminSt != null)
-                               userAdminSt.close();
+       }
 
-                       internalExecutorService.shutdown();
-                       instance = null;
-                       this.bc = null;
-                       this.logReaderService = null;
-                       // this.configurationAdmin = null;
-               } catch (Exception e) {
-                       log.error("CMS activator shutdown failed", e);
+       public static <T> T getService(Class<T> clss) {
+               if (bundleContext != null) {
+                       return bundleContext.getService(bundleContext.getServiceReference(clss));
+               } else {
+                       return null;
                }
        }
 
-       private <T> T getService(Class<T> clazz) {
-               ServiceReference<T> sr = bc.getServiceReference(clazz);
-               if (sr == null)
-                       throw new CmsException("No service available for " + clazz);
-               return bc.getService(sr);
+       /*
+        * OSGi
+        */
+
+       @Override
+       public void start(BundleContext bc) throws Exception {
+               if (!bc.getBundle().equals(bundleContext.getBundle()))
+                       throw new IllegalStateException(
+                                       "Bundle " + bc.getBundle() + " is not consistent with " + bundleContext.getBundle());
+               init();
+               userAdminSt = new ServiceTracker<>(bundleContext, UserAdmin.class, null);
+               userAdminSt.open();
        }
 
+       @Override
+       public void stop(BundleContext bc) throws Exception {
+               if (!bc.getBundle().equals(bundleContext.getBundle()))
+                       throw new IllegalStateException(
+                                       "Bundle " + bc.getBundle() + " is not consistent with " + bundleContext.getBundle());
+               destroy();
+       }
+
+//     private <T> T getService(Class<T> clazz) {
+//             ServiceReference<T> sr = bundleContext.getServiceReference(clazz);
+//             if (sr == null)
+//                     throw new IllegalStateException("No service available for " + clazz);
+//             return bundleContext.getService(sr);
+//     }
+
        public static NodeState getNodeState() {
                return instance.nodeState;
        }
@@ -217,10 +260,10 @@ public class Activator implements BundleActivator {
                try {
                        res = instance.userAdminSt.waitForService(60000);
                } catch (InterruptedException e) {
-                       throw new CmsException("Cannot retrieve Node user admin", e);
+                       throw new IllegalStateException("Cannot retrieve Node user admin", e);
                }
                if (res == null)
-                       throw new CmsException("No Node user admin found");
+                       throw new IllegalStateException("No Node user admin found");
 
                return res;
                // ServiceReference<UserAdmin> sr =
@@ -247,4 +290,13 @@ public class Activator implements BundleActivator {
                return res;
        }
 
+       static BundleContext getBundleContext() {
+               return bundleContext;
+       }
+
+       public static void main(String[] args) {
+               instance = new Activator();
+               instance.init();
+       }
+
 }
index 43295ae3f2681f47eee52d03c573a7bd68ba5652..bfc58501c48ee1b4c0b8f5766524b6c4d18ccb9e 100644 (file)
@@ -24,38 +24,42 @@ class CmsShutdown extends Thread {
 
        public CmsShutdown() {
                super("CMS Shutdown Hook");
-               framework = (Framework) FrameworkUtil.getBundle(CmsShutdown.class).getBundleContext().getBundle(0);
+               framework = FrameworkUtil.getBundle(CmsShutdown.class) != null
+                               ? (Framework) FrameworkUtil.getBundle(CmsShutdown.class).getBundleContext().getBundle(0)
+                               : null;
        }
 
        @Override
        public void run() {
-               if (framework.getState() != Bundle.ACTIVE) {
+               if (framework != null && framework.getState() != Bundle.ACTIVE) {
                        return;
                }
-               
+
                if (log.isDebugEnabled())
                        log.debug("Shutting down OSGi framework...");
                try {
-                       // shutdown framework
-                       framework.stop();
-                       // wait for shutdown
-                       FrameworkEvent shutdownEvent = framework.waitForStop(timeout);
-                       int stoppedType = shutdownEvent.getType();
-                       Runtime runtime = Runtime.getRuntime();
-                       if (stoppedType == FrameworkEvent.STOPPED) {
-                               // close VM
-                               //System.exit(EXIT_OK);
-                       } else if (stoppedType == FrameworkEvent.ERROR) {
-                               log.error("The OSGi framework stopped with an error");
-                               runtime.halt(EXIT_ERROR);
-                       } else if (stoppedType == FrameworkEvent.WAIT_TIMEDOUT) {
-                               log.error("The OSGi framework hasn't stopped after " + timeout + "ms."
-                                               + " Forcibly terminating the JVM...");
-                               runtime.halt(EXIT_TIMEOUT);
-                       } else {
-                               log.error("Unknown state of OSGi framework after " + timeout + "ms."
-                                               + " Forcibly terminating the JVM... (" + shutdownEvent + ")");
-                               runtime.halt(EXIT_UNKNOWN);
+                       if (framework != null) {
+                               // shutdown framework
+                               framework.stop();
+                               // wait for shutdown
+                               FrameworkEvent shutdownEvent = framework.waitForStop(timeout);
+                               int stoppedType = shutdownEvent.getType();
+                               Runtime runtime = Runtime.getRuntime();
+                               if (stoppedType == FrameworkEvent.STOPPED) {
+                                       // close VM
+                                       // System.exit(EXIT_OK);
+                               } else if (stoppedType == FrameworkEvent.ERROR) {
+                                       log.error("The OSGi framework stopped with an error");
+                                       runtime.halt(EXIT_ERROR);
+                               } else if (stoppedType == FrameworkEvent.WAIT_TIMEDOUT) {
+                                       log.error("The OSGi framework hasn't stopped after " + timeout + "ms."
+                                                       + " Forcibly terminating the JVM...");
+                                       runtime.halt(EXIT_TIMEOUT);
+                               } else {
+                                       log.error("Unknown state of OSGi framework after " + timeout + "ms."
+                                                       + " Forcibly terminating the JVM... (" + shutdownEvent + ")");
+                                       runtime.halt(EXIT_UNKNOWN);
+                               }
                        }
                } catch (Exception e) {
                        e.printStackTrace();
index 53a3de8ef6edb660eded8add8c259db2d637c649..b794d088e619392088fd179043aa1d3690030631 100644 (file)
@@ -20,9 +20,7 @@ import org.argeo.api.NodeState;
 import org.argeo.cms.LocaleUtils;
 import org.argeo.transaction.simple.SimpleTransactionManager;
 import org.argeo.util.LangUtils;
-import org.osgi.framework.BundleContext;
 import org.osgi.framework.Constants;
-import org.osgi.framework.FrameworkUtil;
 import org.osgi.service.cm.ManagedServiceFactory;
 
 /**
@@ -30,7 +28,7 @@ import org.osgi.service.cm.ManagedServiceFactory;
  */
 public class CmsState implements NodeState {
        private final static Log log = LogFactory.getLog(CmsState.class);
-       private final BundleContext bc = FrameworkUtil.getBundle(CmsState.class).getBundleContext();
+//     private final BundleContext bc = FrameworkUtil.getBundle(CmsState.class).getBundleContext();
 
        // REFERENCES
        private Long availableSince;
@@ -110,16 +108,16 @@ public class CmsState implements NodeState {
                // JCR
                RepositoryServiceFactory repositoryServiceFactory = new RepositoryServiceFactory();
                stopHooks.add(() -> repositoryServiceFactory.shutdown());
-               bc.registerService(ManagedServiceFactory.class, repositoryServiceFactory,
+               Activator.registerService(ManagedServiceFactory.class, repositoryServiceFactory,
                                LangUtils.dict(Constants.SERVICE_PID, NodeConstants.NODE_REPOS_FACTORY_PID));
 
                NodeRepositoryFactory repositoryFactory = new NodeRepositoryFactory();
-               bc.registerService(RepositoryFactory.class, repositoryFactory, null);
+               Activator.registerService(RepositoryFactory.class, repositoryFactory, null);
 
                // Security
                NodeUserAdmin userAdmin = new NodeUserAdmin(NodeConstants.ROLES_BASEDN, NodeConstants.TOKENS_BASEDN);
                stopHooks.add(() -> userAdmin.destroy());
-               bc.registerService(ManagedServiceFactory.class, userAdmin,
+               Activator.registerService(ManagedServiceFactory.class, userAdmin,
                                LangUtils.dict(Constants.SERVICE_PID, NodeConstants.NODE_USER_ADMIN_PID));
 
                // File System
@@ -134,14 +132,14 @@ public class CmsState implements NodeState {
 //             for (FileSystemProvider fsp : FileSystemProvider.installedProviders()) {
 //                     log.debug("Installed FileSystemProvider " + fsp);
 //             }
-               bc.registerService(FileSystemProvider.class, cmsFsProvider,
+               Activator.registerService(FileSystemProvider.class, cmsFsProvider,
                                LangUtils.dict(Constants.SERVICE_PID, NodeConstants.NODE_FS_PROVIDER_PID));
        }
 
        private void initSimpleTransactionManager() {
                SimpleTransactionManager transactionManager = new SimpleTransactionManager();
-               bc.registerService(TransactionManager.class, transactionManager, null);
-               bc.registerService(UserTransaction.class, transactionManager, null);
+               Activator.registerService(TransactionManager.class, transactionManager, null);
+               Activator.registerService(UserTransaction.class, transactionManager, null);
                // TODO TransactionSynchronizationRegistry
        }
 
index bf8e8d38e462a58a6821e5a41c4bed69b53a092a..a5362c64e7484686ff64a0c2631d84acdc06b1cd 100644 (file)
@@ -29,7 +29,6 @@ import org.argeo.api.NodeConstants;
 import org.argeo.cms.CmsException;
 import org.osgi.framework.Bundle;
 import org.osgi.framework.BundleContext;
-import org.osgi.framework.FrameworkUtil;
 import org.osgi.util.tracker.ServiceTracker;
 
 /** Package utilities */
@@ -44,7 +43,7 @@ class KernelUtils implements KernelConstants {
                                        .getInstance("JavaLoginConfig", uriParameter);
                        javax.security.auth.login.Configuration.setConfiguration(jaasConfiguration);
                } catch (Exception e) {
-                       throw new CmsException("Cannot set configuration " + jaasConfigurationUrl, e);
+                       throw new IllegalArgumentException("Cannot set configuration " + jaasConfigurationUrl, e);
                }
        }
 
@@ -61,7 +60,7 @@ class KernelUtils implements KernelConstants {
                try {
                        props.load(cl.getResourceAsStream(resource));
                } catch (IOException e) {
-                       throw new CmsException("Cannot load " + resource + " from classpath", e);
+                       throw new IllegalArgumentException("Cannot load " + resource + " from classpath", e);
                }
                return asDictionary(props);
        }
@@ -73,7 +72,7 @@ class KernelUtils implements KernelConstants {
                try {
                        return new File(executionDir, relativePath).getCanonicalFile();
                } catch (IOException e) {
-                       throw new CmsException("Cannot get canonical file", e);
+                       throw new IllegalArgumentException("Cannot get canonical file", e);
                }
        }
 
@@ -88,7 +87,10 @@ class KernelUtils implements KernelConstants {
 
        static URI getOsgiInstanceUri(String relativePath) {
                String osgiInstanceBaseUri = getFrameworkProp(OSGI_INSTANCE_AREA);
-               return safeUri(osgiInstanceBaseUri + (relativePath != null ? relativePath : ""));
+               if (osgiInstanceBaseUri != null)
+                       return safeUri(osgiInstanceBaseUri + (relativePath != null ? relativePath : ""));
+               else
+                       return Paths.get(System.getProperty("user.dir")).toUri();
        }
 
        static File getOsgiConfigurationFile(String relativePath) {
@@ -96,12 +98,17 @@ class KernelUtils implements KernelConstants {
                        return new File(new URI(getBundleContext().getProperty(OSGI_CONFIGURATION_AREA) + relativePath))
                                        .getCanonicalFile();
                } catch (Exception e) {
-                       throw new CmsException("Cannot get configuration file for " + relativePath, e);
+                       throw new IllegalArgumentException("Cannot get configuration file for " + relativePath, e);
                }
        }
 
        static String getFrameworkProp(String key, String def) {
-               String value = getBundleContext().getProperty(key);
+               BundleContext bundleContext = Activator.getBundleContext();
+               String value;
+               if (bundleContext != null)
+                       value = bundleContext.getProperty(key);
+               else
+                       value = System.getProperty(key);
                if (value == null)
                        return def;
                return value;
@@ -160,7 +167,7 @@ class KernelUtils implements KernelConstants {
                        loginContext = new LoginContext(NodeConstants.LOGIN_CONTEXT_DATA_ADMIN);
                        loginContext.login();
                } catch (LoginException e1) {
-                       throw new CmsException("Could not login as data admin", e1);
+                       throw new IllegalStateException("Could not login as data admin", e1);
                } finally {
                        Thread.currentThread().setContextClassLoader(currentCl);
                }
@@ -171,7 +178,7 @@ class KernelUtils implements KernelConstants {
                                try {
                                        return repository.login(workspaceName);
                                } catch (RepositoryException e) {
-                                       throw new CmsException("Cannot open admin session", e);
+                                       throw new IllegalStateException("Cannot open admin session", e);
                                }
                        }
 
@@ -195,16 +202,16 @@ class KernelUtils implements KernelConstants {
         *         class, never null.
         * @throws CmsException if the related bundle is not active
         */
-       static BundleContext getBundleContext(Class<?> clzz) {
-               Bundle bundle = FrameworkUtil.getBundle(clzz);
-               BundleContext bc = bundle.getBundleContext();
-               if (bc == null)
-                       throw new CmsException("Bundle " + bundle.getSymbolicName() + " is not active");
-               return bc;
-       }
+//     static BundleContext getBundleContext(Class<?> clzz) {
+////           Bundle bundle = FrameworkUtil.getBundle(clzz);
+//             BundleContext bc = Activator.getBundleContext();
+//             if (bc == null)
+//                     throw new CmsException("Bundle " + bundle.getSymbolicName() + " is not active");
+//             return bc;
+//     }
 
        static BundleContext getBundleContext() {
-               return getBundleContext(KernelUtils.class);
+               return Activator.getBundleContext();
        }
 
        static boolean asBoolean(String value) {
@@ -216,17 +223,18 @@ class KernelUtils implements KernelConstants {
                case "false":
                        return false;
                default:
-                       throw new CmsException("Unsupported value for attribute " + DataModelNamespace.ABSTRACT + ": " + value);
+                       throw new IllegalArgumentException(
+                                       "Unsupported value for attribute " + DataModelNamespace.ABSTRACT + ": " + value);
                }
        }
 
        private static URI safeUri(String uri) {
                if (uri == null)
-                       throw new CmsException("URI cannot be null");
+                       throw new IllegalArgumentException("URI cannot be null");
                try {
                        return new URI(uri);
                } catch (URISyntaxException e) {
-                       throw new CmsException("Dadly formatted URI " + uri, e);
+                       throw new IllegalArgumentException("Badly formatted URI " + uri, e);
                }
        }
 
index 158bac70a40159c1bebcb353adf245b355184edd..fef7a7a30a0e4b308cdca33a374fac8f57e6d849 100644 (file)
@@ -86,30 +86,32 @@ class NodeLogger implements ArgeoLogger, LogListener {
        };
 
        public NodeLogger(LogReaderService lrs) {
-               Enumeration<LogEntry> logEntries = lrs.getLog();
-               while (logEntries.hasMoreElements())
-                       logged(logEntries.nextElement());
-               lrs.addLogListener(this);
-
-               // configure log4j watcher
-               String log4jConfiguration = KernelUtils.getFrameworkProp("log4j.configuration");
-               if (log4jConfiguration != null && log4jConfiguration.startsWith("file:")) {
-                       if (log4jConfiguration.contains("..")) {
-                               if (log4jConfiguration.startsWith("file://"))
-                                       log4jConfiguration = log4jConfiguration.substring("file://".length());
-                               else if (log4jConfiguration.startsWith("file:"))
-                                       log4jConfiguration = log4jConfiguration.substring("file:".length());
-                       }
-                       try {
-                               Path log4jconfigPath;
-                               if (log4jConfiguration.startsWith("file:"))
-                                       log4jconfigPath = Paths.get(new URI(log4jConfiguration));
-                               else
-                                       log4jconfigPath = Paths.get(log4jConfiguration);
-                               Thread log4jConfWatcher = new Log4jConfWatcherThread(log4jconfigPath);
-                               log4jConfWatcher.start();
-                       } catch (Exception e) {
-                               stdErr("Badly formatted log4j configuration URI " + log4jConfiguration + ": " + e.getMessage());
+               if (lrs != null) {
+                       Enumeration<LogEntry> logEntries = lrs.getLog();
+                       while (logEntries.hasMoreElements())
+                               logged(logEntries.nextElement());
+                       lrs.addLogListener(this);
+
+                       // configure log4j watcher
+                       String log4jConfiguration = KernelUtils.getFrameworkProp("log4j.configuration");
+                       if (log4jConfiguration != null && log4jConfiguration.startsWith("file:")) {
+                               if (log4jConfiguration.contains("..")) {
+                                       if (log4jConfiguration.startsWith("file://"))
+                                               log4jConfiguration = log4jConfiguration.substring("file://".length());
+                                       else if (log4jConfiguration.startsWith("file:"))
+                                               log4jConfiguration = log4jConfiguration.substring("file:".length());
+                               }
+                               try {
+                                       Path log4jconfigPath;
+                                       if (log4jConfiguration.startsWith("file:"))
+                                               log4jconfigPath = Paths.get(new URI(log4jConfiguration));
+                                       else
+                                               log4jconfigPath = Paths.get(log4jConfiguration);
+                                       Thread log4jConfWatcher = new Log4jConfWatcherThread(log4jconfigPath);
+                                       log4jConfWatcher.start();
+                               } catch (Exception e) {
+                                       stdErr("Badly formatted log4j configuration URI " + log4jConfiguration + ": " + e.getMessage());
+                               }
                        }
                }
        }
index a6c722015f7fd6d9c3ec077f5ff522fc34659aad..efbb724ff9174a751bad9ae639809e14b44fc443 100644 (file)
@@ -26,23 +26,29 @@ import org.osgi.framework.ServiceReference;
  */
 class NodeRepositoryFactory implements RepositoryFactory {
        private final Log log = LogFactory.getLog(getClass());
-       private final BundleContext bundleContext = FrameworkUtil.getBundle(getClass()).getBundleContext();
+//     private final BundleContext bundleContext = FrameworkUtil.getBundle(getClass()).getBundleContext();
 
        // private Resource fileRepositoryConfiguration = new ClassPathResource(
        // "/org/argeo/cms/internal/kernel/repository-localfs.xml");
 
        protected Repository getRepositoryByAlias(String alias) {
-               try {
-                       Collection<ServiceReference<Repository>> srs = bundleContext.getServiceReferences(Repository.class,
-                                       "(" + NodeConstants.CN + "=" + alias + ")");
-                       if (srs.size() == 0)
-                               throw new IllegalArgumentException("No repository with alias " + alias + " found in OSGi registry");
-                       else if (srs.size() > 1)
-                               throw new IllegalArgumentException(
-                                               srs.size() + " repositories with alias " + alias + " found in OSGi registry");
-                       return bundleContext.getService(srs.iterator().next());
-               } catch (InvalidSyntaxException e) {
-                       throw new IllegalArgumentException("Cannot find repository with alias " + alias, e);
+               BundleContext bundleContext = Activator.getBundleContext();
+               if (bundleContext != null) {
+                       try {
+                               Collection<ServiceReference<Repository>> srs = bundleContext.getServiceReferences(Repository.class,
+                                               "(" + NodeConstants.CN + "=" + alias + ")");
+                               if (srs.size() == 0)
+                                       throw new IllegalArgumentException("No repository with alias " + alias + " found in OSGi registry");
+                               else if (srs.size() > 1)
+                                       throw new IllegalArgumentException(
+                                                       srs.size() + " repositories with alias " + alias + " found in OSGi registry");
+                               return bundleContext.getService(srs.iterator().next());
+                       } catch (InvalidSyntaxException e) {
+                               throw new IllegalArgumentException("Cannot find repository with alias " + alias, e);
+                       }
+               } else {
+                       // TODO ability to filter static services
+                       return null;
                }
        }
 
index 69affd25a2b160d8c1f154e883a4e11fb6fcc547..40e23541ba0ad46b3c444acfd586a094c3a4d9d0 100644 (file)
@@ -35,7 +35,6 @@ import org.apache.commons.httpclient.params.HttpParams;
 import org.apache.commons.logging.Log;
 import org.apache.commons.logging.LogFactory;
 import org.argeo.api.NodeConstants;
-import org.argeo.cms.CmsException;
 import org.argeo.cms.internal.http.client.HttpCredentialProvider;
 import org.argeo.cms.internal.http.client.SpnegoAuthScheme;
 import org.argeo.naming.DnsBrowser;
@@ -53,8 +52,6 @@ import org.ietf.jgss.GSSName;
 import org.ietf.jgss.Oid;
 import org.osgi.framework.BundleContext;
 import org.osgi.framework.Constants;
-import org.osgi.framework.FrameworkUtil;
-import org.osgi.framework.ServiceRegistration;
 import org.osgi.service.cm.ConfigurationException;
 import org.osgi.service.cm.ManagedServiceFactory;
 import org.osgi.service.useradmin.Authorization;
@@ -67,11 +64,11 @@ import org.osgi.util.tracker.ServiceTracker;
  */
 class NodeUserAdmin extends AggregatingUserAdmin implements ManagedServiceFactory, KernelConstants {
        private final static Log log = LogFactory.getLog(NodeUserAdmin.class);
-       private final BundleContext bc = FrameworkUtil.getBundle(getClass()).getBundleContext();
+//     private final BundleContext bc = FrameworkUtil.getBundle(getClass()).getBundleContext();
 
        // OSGi
        private Map<String, LdapName> pidToBaseDn = new HashMap<>();
-       private Map<String, ServiceRegistration<UserDirectory>> pidToServiceRegs = new HashMap<>();
+//     private Map<String, ServiceRegistration<UserDirectory>> pidToServiceRegs = new HashMap<>();
 //     private ServiceRegistration<UserAdmin> userAdminReg;
 
        // JTA
@@ -87,8 +84,13 @@ class NodeUserAdmin extends AggregatingUserAdmin implements ManagedServiceFactor
 
        public NodeUserAdmin(String systemRolesBaseDn, String tokensBaseDn) {
                super(systemRolesBaseDn, tokensBaseDn);
-               tmTracker = new ServiceTracker<>(bc, TransactionManager.class, null);
-               tmTracker.open();
+               BundleContext bc = Activator.getBundleContext();
+               if (bc != null) {
+                       tmTracker = new ServiceTracker<>(bc, TransactionManager.class, null);
+                       tmTracker.open();
+               } else {
+                       tmTracker = null;
+               }
        }
 
        @Override
@@ -102,7 +104,7 @@ class NodeUserAdmin extends AggregatingUserAdmin implements ManagedServiceFactor
                        } else
                                u = new URI(uri);
                } catch (URISyntaxException e) {
-                       throw new CmsException("Badly formatted URI " + uri, e);
+                       throw new IllegalArgumentException("Badly formatted URI " + uri, e);
                }
 
                // Create
@@ -115,7 +117,7 @@ class NodeUserAdmin extends AggregatingUserAdmin implements ManagedServiceFactor
                        userDirectory = new OsUserDirectory(u, properties);
                        singleUser = true;
                } else {
-                       throw new CmsException("Unsupported scheme " + u.getScheme());
+                       throw new IllegalArgumentException("Unsupported scheme " + u.getScheme());
                }
                Object realm = userDirectory.getProperties().get(UserAdminConf.realm.name());
                addUserDirectory(userDirectory);
@@ -127,9 +129,11 @@ class NodeUserAdmin extends AggregatingUserAdmin implements ManagedServiceFactor
                if (isSystemRolesBaseDn(baseDn))
                        regProps.put(Constants.SERVICE_RANKING, Integer.MAX_VALUE);
                regProps.put(UserAdminConf.baseDn.name(), baseDn);
-               ServiceRegistration<UserDirectory> reg = bc.registerService(UserDirectory.class, userDirectory, regProps);
+               // ServiceRegistration<UserDirectory> reg =
+               // bc.registerService(UserDirectory.class, userDirectory, regProps);
+               Activator.registerService(UserDirectory.class, userDirectory, regProps);
                pidToBaseDn.put(pid, baseDn);
-               pidToServiceRegs.put(pid, reg);
+               // pidToServiceRegs.put(pid, reg);
 
                if (log.isDebugEnabled())
                        log.debug("User directory " + userDirectory.getBaseDn() + " [" + u.getScheme() + "] enabled."
@@ -140,7 +144,7 @@ class NodeUserAdmin extends AggregatingUserAdmin implements ManagedServiceFactor
                        Dictionary<String, Object> userAdminregProps = new Hashtable<>();
                        userAdminregProps.put(NodeConstants.CN, NodeConstants.DEFAULT);
                        userAdminregProps.put(Constants.SERVICE_RANKING, Integer.MAX_VALUE);
-                       bc.registerService(UserAdmin.class, this, userAdminregProps);
+                       Activator.registerService(UserAdmin.class, this, userAdminregProps);
                }
 
 //             if (isSystemRolesBaseDn(baseDn))
@@ -162,9 +166,9 @@ class NodeUserAdmin extends AggregatingUserAdmin implements ManagedServiceFactor
 
        @Override
        public void deleted(String pid) {
-               assert pidToServiceRegs.get(pid) != null;
+               // assert pidToServiceRegs.get(pid) != null;
                assert pidToBaseDn.get(pid) != null;
-               pidToServiceRegs.remove(pid).unregister();
+               // pidToServiceRegs.remove(pid).unregister();
                LdapName baseDn = pidToBaseDn.remove(pid);
                removeUserDirectory(baseDn);
        }
@@ -185,9 +189,9 @@ class NodeUserAdmin extends AggregatingUserAdmin implements ManagedServiceFactor
 
        protected void postAdd(AbstractUserDirectory userDirectory) {
                // JTA
-               TransactionManager tm = tmTracker.getService();
+               TransactionManager tm = tmTracker != null ? tmTracker.getService() : null;
                if (tm == null)
-                       throw new CmsException("A JTA transaction manager must be available.");
+                       throw new IllegalStateException("A JTA transaction manager must be available.");
                userDirectory.setTransactionManager(tm);
 //             if (tmTracker.getService() instanceof BitronixTransactionManager)
 //                     EhCacheXAResourceProducer.registerXAResource(cacheName, userDirectory.getXaResource());
@@ -211,7 +215,7 @@ class NodeUserAdmin extends AggregatingUserAdmin implements ManagedServiceFactor
                                                nodeLc.login();
                                                acceptorCredentials = logInAsAcceptor(nodeLc.getSubject(), servicePrincipal);
                                        } catch (LoginException e) {
-                                               throw new CmsException("Cannot log in kernel", e);
+                                               throw new IllegalStateException("Cannot log in kernel", e);
                                        }
                                }
                        }
@@ -297,7 +301,7 @@ class NodeUserAdmin extends AggregatingUserAdmin implements ManagedServiceFactor
                                log.debug("GSS acceptor configured for " + krb5Principal);
                        return serverCredentials;
                } catch (Exception gsse) {
-                       throw new CmsException("Cannot create acceptor credentials for " + krb5Principal, gsse);
+                       throw new IllegalStateException("Cannot create acceptor credentials for " + krb5Principal, gsse);
                }
        }
 
index 27e5199221212136428238f1adc5f444448f64d8..630a453c2d5a40008c0d0af9af127c6278290b89 100644 (file)
@@ -1,44 +1,28 @@
 package org.argeo.cms.internal.kernel;
 
-import static org.osgi.service.http.whiteboard.HttpWhiteboardConstants.HTTP_WHITEBOARD_SERVLET_INIT_PARAM_PREFIX;
-
-import java.io.IOException;
 import java.net.URI;
-import java.nio.file.Files;
-import java.nio.file.Path;
 import java.util.Dictionary;
 import java.util.HashMap;
-import java.util.Hashtable;
 import java.util.Map;
 
 import javax.jcr.Repository;
 import javax.jcr.RepositoryFactory;
-import javax.servlet.Servlet;
-import javax.servlet.ServletException;
 
 import org.apache.commons.logging.Log;
 import org.apache.commons.logging.LogFactory;
 import org.apache.jackrabbit.core.RepositoryContext;
-import org.apache.jackrabbit.server.remoting.davex.JcrRemotingServlet;
 import org.argeo.api.NodeConstants;
-import org.argeo.cms.CmsException;
-import org.argeo.cms.internal.http.CmsRemotingServlet;
-import org.argeo.cms.internal.http.HttpUtils;
 import org.argeo.cms.internal.jcr.RepoConf;
 import org.argeo.cms.internal.jcr.RepositoryBuilder;
 import org.argeo.util.LangUtils;
-import org.osgi.framework.BundleContext;
 import org.osgi.framework.Constants;
-import org.osgi.framework.FrameworkUtil;
 import org.osgi.service.cm.ConfigurationException;
 import org.osgi.service.cm.ManagedServiceFactory;
-import org.osgi.service.http.NamespaceException;
-import org.osgi.service.http.whiteboard.HttpWhiteboardConstants;
 
 /** A {@link ManagedServiceFactory} creating or referencing JCR repositories. */
 class RepositoryServiceFactory implements ManagedServiceFactory {
        private final static Log log = LogFactory.getLog(RepositoryServiceFactory.class);
-       private final BundleContext bc = FrameworkUtil.getBundle(RepositoryServiceFactory.class).getBundleContext();
+//     private final BundleContext bc = FrameworkUtil.getBundle(RepositoryServiceFactory.class).getBundleContext();
 
        private Map<String, RepositoryContext> repositories = new HashMap<String, RepositoryContext>();
        private Map<String, Object> pidToCn = new HashMap<String, Object>();
@@ -51,7 +35,7 @@ class RepositoryServiceFactory implements ManagedServiceFactory {
        @Override
        public void updated(String pid, Dictionary<String, ?> properties) throws ConfigurationException {
                if (repositories.containsKey(pid))
-                       throw new CmsException("Already a repository registered for " + pid);
+                       throw new IllegalArgumentException("Already a repository registered for " + pid);
 
                if (properties == null)
                        return;
@@ -67,7 +51,7 @@ class RepositoryServiceFactory implements ManagedServiceFactory {
                                RepositoryBuilder repositoryBuilder = new RepositoryBuilder();
                                RepositoryContext repositoryContext = repositoryBuilder.createRepositoryContext(properties);
                                repositories.put(pid, repositoryContext);
-                               Dictionary<String, Object> props = LangUtils.dico(Constants.SERVICE_PID, pid);
+                               Dictionary<String, Object> props = LangUtils.dict(Constants.SERVICE_PID, pid);
                                // props.put(ArgeoJcrConstants.JCR_REPOSITORY_URI,
                                // properties.get(RepoConf.labeledUri.name()));
                                Object cn = properties.get(NodeConstants.CN);
@@ -76,7 +60,7 @@ class RepositoryServiceFactory implements ManagedServiceFactory {
                                        // props.put(NodeConstants.JCR_REPOSITORY_ALIAS, cn);
                                        pidToCn.put(pid, cn);
                                }
-                               bc.registerService(RepositoryContext.class, repositoryContext, props);
+                               Activator.registerService(RepositoryContext.class, repositoryContext, props);
                        } else {
                                try {
                                        Object cn = properties.get(NodeConstants.CN);
@@ -84,15 +68,16 @@ class RepositoryServiceFactory implements ManagedServiceFactory {
                                        if (defaultWorkspace == null)
                                                defaultWorkspace = RepoConf.defaultWorkspace.getDefault();
                                        URI uri = new URI(labeledUri.toString());
-                                       RepositoryFactory repositoryFactory = bc
-                                                       .getService(bc.getServiceReference(RepositoryFactory.class));
+//                                     RepositoryFactory repositoryFactory = bc
+//                                                     .getService(bc.getServiceReference(RepositoryFactory.class));
+                                       RepositoryFactory repositoryFactory = Activator.getService(RepositoryFactory.class);
                                        Map<String, String> parameters = new HashMap<String, String>();
                                        parameters.put(RepoConf.labeledUri.name(), uri.toString());
                                        parameters.put(RepoConf.defaultWorkspace.name(), defaultWorkspace.toString());
                                        Repository repository = repositoryFactory.getRepository(parameters);
                                        // Repository repository = NodeUtils.getRepositoryByUri(repositoryFactory,
                                        // uri.toString());
-                                       Dictionary<String, Object> props = LangUtils.dico(Constants.SERVICE_PID, pid);
+                                       Dictionary<String, Object> props = LangUtils.dict(Constants.SERVICE_PID, pid);
                                        props.put(RepoConf.labeledUri.name(),
                                                        new URI(uri.getScheme(), null, uri.getHost(), uri.getPort(), uri.getPath(), null, null)
                                                                        .toString());
@@ -101,14 +86,14 @@ class RepositoryServiceFactory implements ManagedServiceFactory {
                                                // props.put(NodeConstants.JCR_REPOSITORY_ALIAS, cn);
                                                pidToCn.put(pid, cn);
                                        }
-                                       bc.registerService(Repository.class, repository, props);
+                                       Activator.registerService(Repository.class, repository, props);
 
                                        // home
                                        if (cn.equals(NodeConstants.NODE_REPOSITORY)) {
-                                               Dictionary<String, Object> homeProps = LangUtils.dico(NodeConstants.CN,
+                                               Dictionary<String, Object> homeProps = LangUtils.dict(NodeConstants.CN,
                                                                NodeConstants.EGO_REPOSITORY);
                                                EgoRepository homeRepository = new EgoRepository(repository, true);
-                                               bc.registerService(Repository.class, homeRepository, homeProps);
+                                               Activator.registerService(Repository.class, homeRepository, homeProps);
                                        }
                                } catch (Exception e) {
                                        // TODO Auto-generated catch block
@@ -116,7 +101,7 @@ class RepositoryServiceFactory implements ManagedServiceFactory {
                                }
                        }
                } catch (Exception e) {
-                       throw new CmsException("Cannot create Jackrabbit repository " + pid, e);
+                       throw new IllegalStateException("Cannot create Jackrabbit repository " + pid, e);
                }
 
        }