Refactor Argeo init
[lgpl/argeo-commons.git] / org.argeo.cms / src / org / argeo / cms / internal / runtime / CmsContextImpl.java
index cc98072a3827fd7a5836f700dab6a47fc7a0e2e1..25f8dad6a784f1c496b6ff3a2b2efaa941e2512d 100644 (file)
@@ -6,19 +6,15 @@ import java.util.HashMap;
 import java.util.List;
 import java.util.Locale;
 import java.util.Map;
-import java.util.TreeMap;
 import java.util.UUID;
 import java.util.concurrent.CompletableFuture;
 import java.util.concurrent.ExecutionException;
-import java.util.concurrent.Flow;
-import java.util.concurrent.Flow.Subscription;
-import java.util.concurrent.SubmissionPublisher;
 
 import javax.security.auth.Subject;
 
 import org.argeo.api.cms.CmsContext;
 import org.argeo.api.cms.CmsDeployment;
-import org.argeo.api.cms.CmsEventSubscriber;
+import org.argeo.api.cms.CmsEventBus;
 import org.argeo.api.cms.CmsLog;
 import org.argeo.api.cms.CmsSession;
 import org.argeo.api.cms.CmsSessionId;
@@ -29,19 +25,18 @@ import org.argeo.cms.internal.auth.CmsSessionImpl;
 import org.ietf.jgss.GSSCredential;
 import org.osgi.service.useradmin.UserAdmin;
 
+/** Reference implementation of {@link CmsContext}. */
 public class CmsContextImpl implements CmsContext {
 
        private final CmsLog log = CmsLog.getLog(getClass());
-//     private final BundleContext bc = FrameworkUtil.getBundle(getClass()).getBundleContext();
 
-//     private EgoRepository egoRepository;
        private static CompletableFuture<CmsContextImpl> instance = new CompletableFuture<CmsContextImpl>();
 
        private CmsState cmsState;
        private CmsDeployment cmsDeployment;
        private UserAdmin userAdmin;
        private UuidFactory uuidFactory;
-//     private ProvidedRepository contentRepository;
+       private CmsEventBus cmsEventBus;
 
        // i18n
        private Locale defaultLocale;
@@ -49,59 +44,35 @@ public class CmsContextImpl implements CmsContext {
 
        private Long availableSince;
 
+       // time in ms to wait for CMS to be ready
+       private final long readynessTimeout = 30 * 1000;
+
        // CMS sessions
        private Map<UUID, CmsSessionImpl> cmsSessionsByUuid = new HashMap<>();
        private Map<String, CmsSessionImpl> cmsSessionsByLocalId = new HashMap<>();
 
-       // CMS events
-       private Map<String, SubmissionPublisher<Map<String, Object>>> topics = new TreeMap<>();
-//     private IdentityHashMap<CmsEventSubscriber, List<CmsEventFlowSubscriber>> subscriptions = new IdentityHashMap<>();
-
-//     public CmsContextImpl() {
-//             initTrackers();
-//     }
-
        public void start() {
                List<String> codes = CmsStateImpl.getDeployProperties(cmsState, CmsDeployProperty.LOCALE);
                locales = getLocaleList(codes);
                if (locales.size() == 0)
                        throw new IllegalStateException("At least one locale must be set");
                defaultLocale = locales.get(0);
-//             Object defaultLocaleValue = KernelUtils.getFrameworkProp(CmsConstants.I18N_DEFAULT_LOCALE);
-//             defaultLocale = defaultLocaleValue != null ? new Locale(defaultLocaleValue.toString())
-//                             : new Locale(ENGLISH.getLanguage());
-               // node repository
-//             new ServiceTracker<Repository, Repository>(bc, Repository.class, null) {
-//                     @Override
-//                     public Repository addingService(ServiceReference<Repository> reference) {
-//                             Object cn = reference.getProperty(NodeConstants.CN);
-//                             if (cn != null && cn.equals(NodeConstants.EGO_REPOSITORY)) {
-////                                   egoRepository = (EgoRepository) bc.getService(reference);
-//                                     if (log.isTraceEnabled())
-//                                             log.trace("Home repository is available");
-//                             }
-//                             return super.addingService(reference);
-//                     }
-//
-//                     @Override
-//                     public void removedService(ServiceReference<Repository> reference, Repository service) {
-//                             super.removedService(reference, service);
-////                           egoRepository = null;
-//                     }
-//
-//             }.open();
 
                new Thread(() -> {
-                       while (!checkReadiness()) {
+                       long begin = System.currentTimeMillis();
+                       long duration = 0;
+                       readyness: while (!checkReadiness()) {
+                               duration = System.currentTimeMillis() - begin;
+                               if (duration > readynessTimeout) {
+                                       log.error("## CMS not ready after " + duration + " ms. Giving up checking.");
+                                       break readyness;
+                               }
                                try {
-                                       Thread.sleep(500);
+                                       Thread.sleep(100);
                                } catch (InterruptedException e) {
                                }
                        }
                }, "Check readiness").start();
-               
-               // checkReadiness();
-
                setInstance(this);
        }
 
@@ -125,7 +96,8 @@ public class CmsContextImpl implements CmsContext {
                        availableSince = System.currentTimeMillis();
                        long jvmUptime = ManagementFactory.getRuntimeMXBean().getUptime();
                        String jvmUptimeStr = " in " + (jvmUptime / 1000) + "." + (jvmUptime % 1000) + "s";
-                       log.info("## ARGEO CMS AVAILABLE" + (log.isDebugEnabled() ? jvmUptimeStr : "") + " ##");
+                       log.info("## ARGEO CMS " + cmsState.getUuid() + " AVAILABLE" + (log.isDebugEnabled() ? jvmUptimeStr : "")
+                                       + " ##");
                        if (log.isDebugEnabled()) {
                                log.debug("## state: " + state);
                                if (data != null)
@@ -213,63 +185,70 @@ public class CmsContextImpl implements CmsContext {
                this.uuidFactory = uuidFactory;
        }
 
-//     public ProvidedRepository getContentRepository() {
-//             return contentRepository;
-//     }
-//
-//     public void setContentRepository(ProvidedRepository contentRepository) {
-//             this.contentRepository = contentRepository;
-//     }
-
        @Override
        public Locale getDefaultLocale() {
                return defaultLocale;
        }
 
+       @Override
+       public UUID timeUUID() {
+               return uuidFactory.timeUUID();
+       }
+
        @Override
        public List<Locale> getLocales() {
                return locales;
        }
 
        @Override
-       public synchronized Long getAvailableSince() {
+       public Long getAvailableSince() {
                return availableSince;
        }
 
-       public synchronized boolean isAvailable() {
+       public boolean isAvailable() {
                return availableSince != null;
        }
 
-       @Override
        public CmsState getCmsState() {
                return cmsState;
        }
 
+       @Override
+       public CmsEventBus getCmsEventBus() {
+               return cmsEventBus;
+       }
+
+       public void setCmsEventBus(CmsEventBus cmsEventBus) {
+               this.cmsEventBus = cmsEventBus;
+       }
+
        /*
         * STATIC
         */
 
-       public synchronized static CmsContextImpl getCmsContext() {
+       public static CmsContextImpl getCmsContext() {
                return getInstance();
        }
 
        /** Required by SPNEGO login module. */
-       public synchronized static GSSCredential getAcceptorCredentials() {
+       public GSSCredential getAcceptorCredentials() {
                // TODO find a cleaner way
-               return ((CmsUserAdmin) getInstance().userAdmin).getAcceptorCredentials();
+               return ((CmsUserAdmin) userAdmin).getAcceptorCredentials();
        }
 
-       private synchronized static void setInstance(CmsContextImpl cmsContextImpl) {
+       private static void setInstance(CmsContextImpl cmsContextImpl) {
                if (cmsContextImpl != null) {
                        if (instance.isDone())
                                throw new IllegalStateException("CMS Context is already set");
                        instance.complete(cmsContextImpl);
                } else {
+                       if (!instance.isDone())
+                               instance.cancel(true);
                        instance = new CompletableFuture<CmsContextImpl>();
                }
        }
 
-       private synchronized static CmsContextImpl getInstance() {
+       private static CmsContextImpl getInstance() {
                try {
                        return instance.get();
                } catch (InterruptedException | ExecutionException e) {
@@ -286,14 +265,14 @@ public class CmsContextImpl implements CmsContext {
         */
 
        @Override
-       public synchronized CmsSession getCmsSession(Subject subject) {
+       public CmsSession getCmsSession(Subject subject) {
                if (subject.getPrivateCredentials(CmsSessionId.class).isEmpty())
                        return null;
                CmsSessionId cmsSessionId = subject.getPrivateCredentials(CmsSessionId.class).iterator().next();
                return getCmsSessionByUuid(cmsSessionId.getUuid());
        }
 
-       public synchronized void registerCmsSession(CmsSessionImpl cmsSession) {
+       public void registerCmsSession(CmsSessionImpl cmsSession) {
                if (cmsSessionsByUuid.containsKey(cmsSession.getUuid())
                                || cmsSessionsByLocalId.containsKey(cmsSession.getLocalId()))
                        throw new IllegalStateException("CMS session " + cmsSession + " is already registered.");
@@ -301,7 +280,7 @@ public class CmsContextImpl implements CmsContext {
                cmsSessionsByLocalId.put(cmsSession.getLocalId(), cmsSession);
        }
 
-       public synchronized void unregisterCmsSession(CmsSessionImpl cmsSession) {
+       public void unregisterCmsSession(CmsSessionImpl cmsSession) {
                if (!cmsSessionsByUuid.containsKey(cmsSession.getUuid())
                                || !cmsSessionsByLocalId.containsKey(cmsSession.getLocalId()))
                        throw new IllegalStateException("CMS session " + cmsSession + " is not registered.");
@@ -314,7 +293,7 @@ public class CmsContextImpl implements CmsContext {
         * The {@link CmsSession} related to this UUID, or <code>null</null> if not
         * registered.
         */
-       public synchronized CmsSessionImpl getCmsSessionByUuid(UUID uuid) {
+       public CmsSessionImpl getCmsSessionByUuid(UUID uuid) {
                return cmsSessionsByUuid.get(uuid);
        }
 
@@ -322,90 +301,8 @@ public class CmsContextImpl implements CmsContext {
         * The {@link CmsSession} related to this local id, or <code>null</null> if not
         * registered.
         */
-       public synchronized CmsSessionImpl getCmsSessionByLocalId(String localId) {
+       public CmsSessionImpl getCmsSessionByLocalId(String localId) {
                return cmsSessionsByLocalId.get(localId);
        }
 
-       /*
-        * CMS Events
-        */
-       public void sendEvent(String topic, Map<String, Object> event) {
-               SubmissionPublisher<Map<String, Object>> publisher = topics.get(topic);
-               if (publisher == null)
-                       return; // no one is interested
-               publisher.submit(event);
-       }
-
-       public void addEventSubscriber(String topic, CmsEventSubscriber subscriber) {
-               synchronized (topics) {
-                       if (!topics.containsKey(topic))
-                               topics.put(topic, new SubmissionPublisher<>());
-               }
-               SubmissionPublisher<Map<String, Object>> publisher = topics.get(topic);
-               CmsEventFlowSubscriber flowSubscriber = new CmsEventFlowSubscriber(topic, subscriber);
-               publisher.subscribe(flowSubscriber);
-       }
-
-       public void removeEventSubscriber(String topic, CmsEventSubscriber subscriber) {
-               SubmissionPublisher<Map<String, Object>> publisher = topics.get(topic);
-               if (publisher == null) {
-                       log.error("There should be an event topic " + topic);
-                       return;
-               }
-               for (Flow.Subscriber<? super Map<String, Object>> flowSubscriber : publisher.getSubscribers()) {
-                       if (flowSubscriber instanceof CmsEventFlowSubscriber)
-                               ((CmsEventFlowSubscriber) flowSubscriber).unsubscribe();
-               }
-               synchronized (topics) {
-                       if (!publisher.hasSubscribers()) {
-                               publisher.close();
-                               topics.remove(topic);
-                       }
-               }
-       }
-
-       static class CmsEventFlowSubscriber implements Flow.Subscriber<Map<String, Object>> {
-               private String topic;
-               private CmsEventSubscriber eventSubscriber;
-
-               private Subscription subscription;
-
-               public CmsEventFlowSubscriber(String topic, CmsEventSubscriber eventSubscriber) {
-                       this.topic = topic;
-                       this.eventSubscriber = eventSubscriber;
-               }
-
-               @Override
-               public void onSubscribe(Subscription subscription) {
-                       this.subscription = subscription;
-                       subscription.request(Long.MAX_VALUE);
-               }
-
-               @Override
-               public void onNext(Map<String, Object> item) {
-                       eventSubscriber.onEvent(topic, item);
-
-               }
-
-               @Override
-               public void onError(Throwable throwable) {
-                       // TODO Auto-generated method stub
-
-               }
-
-               @Override
-               public void onComplete() {
-                       // TODO Auto-generated method stub
-
-               }
-
-               void unsubscribe() {
-                       if (subscription != null)
-                               subscription.cancel();
-                       else
-                               throw new IllegalStateException("No subscription to cancel");
-               }
-
-       }
-
 }