Use the identity loader for loading identities.
[Sone.git] / src / main / java / net / pterodactylus / sone / freenet / wot / IdentityManager.java
index 3c97e55..9817038 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Sone - IdentityManager.java - Copyright © 2010 David Roden
+ * Sone - IdentityManager.java - Copyright © 2010–2013 David Roden
  *
  * This program is free software: you can redistribute it and/or modify
  * it under the terms of the GNU General Public License as published by
 
 package net.pterodactylus.sone.freenet.wot;
 
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Map.Entry;
+import static com.google.common.base.Optional.fromNullable;
+import static com.google.common.collect.HashMultimap.create;
+
+import java.util.HashSet;
 import java.util.Set;
 import java.util.logging.Level;
 import java.util.logging.Logger;
 
 import net.pterodactylus.sone.freenet.plugin.PluginException;
+import net.pterodactylus.sone.freenet.wot.IdentityChangeDetector.IdentityProcessor;
+import net.pterodactylus.sone.freenet.wot.event.IdentityAddedEvent;
+import net.pterodactylus.sone.freenet.wot.event.IdentityRemovedEvent;
+import net.pterodactylus.sone.freenet.wot.event.IdentityUpdatedEvent;
+import net.pterodactylus.sone.freenet.wot.event.OwnIdentityAddedEvent;
+import net.pterodactylus.sone.freenet.wot.event.OwnIdentityRemovedEvent;
 import net.pterodactylus.util.logging.Logging;
 import net.pterodactylus.util.service.AbstractService;
 
+import com.google.common.collect.Multimap;
+import com.google.common.collect.Sets;
+import com.google.common.eventbus.EventBus;
+import com.google.inject.Inject;
+import com.google.inject.name.Named;
+
 /**
  * The identity manager takes care of loading and storing identities, their
  * contexts, and properties. It does so in a way that does not expose errors via
  * exceptions but it only logs them and tries to return sensible defaults.
- * <p>
+ * <p/>
  * It is also responsible for polling identities from the Web of Trust plugin
- * and notifying registered {@link IdentityListener}s when {@link Identity}s and
- * {@link OwnIdentity}s are discovered or disappearing.
+ * and sending events to the {@link EventBus} when {@link Identity}s and {@link
+ * OwnIdentity}s are discovered or disappearing.
  *
  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
  */
 public class IdentityManager extends AbstractService {
 
-       /** Object used for synchronization. */
-       private final Object syncObject = new Object() {
-               /* inner class for better lock names. */
-       };
-
        /** The logger. */
        private static final Logger logger = Logging.getLogger(IdentityManager.class);
 
-       /** The event manager. */
-       private final IdentityListenerManager identityListenerManager = new IdentityListenerManager();
+       /** The event bus. */
+       private final EventBus eventBus;
+
+       private final IdentityLoader identityLoader;
 
        /** The Web of Trust connector. */
        private final WebOfTrustConnector webOfTrustConnector;
 
-       /** The context to filter for. */
-       private volatile String context;
-
        /** The currently known own identities. */
        /* synchronize access on syncObject. */
-       private Map<String, OwnIdentity> currentOwnIdentities = new HashMap<String, OwnIdentity>();
+       private final Set<OwnIdentity> currentOwnIdentities = Sets.newHashSet();
 
        /**
         * Creates a new identity manager.
         *
+        * @param eventBus
+        *              The event bus
         * @param webOfTrustConnector
-        *            The Web of Trust connector
+        *              The Web of Trust connector
+        * @param context
+        *              The context to focus on (may be {@code null} to ignore contexts)
         */
-       public IdentityManager(WebOfTrustConnector webOfTrustConnector) {
+       @Inject
+       public IdentityManager(EventBus eventBus, WebOfTrustConnector webOfTrustConnector, @Named("WebOfTrustContext") String context) {
                super("Sone Identity Manager", false);
+               this.eventBus = eventBus;
                this.webOfTrustConnector = webOfTrustConnector;
-       }
-
-       //
-       // LISTENER MANAGEMENT
-       //
-
-       /**
-        * Adds a listener for identity events.
-        *
-        * @param identityListener
-        *            The listener to add
-        */
-       public void addIdentityListener(IdentityListener identityListener) {
-               identityListenerManager.addListener(identityListener);
-       }
-
-       /**
-        * Removes a listener for identity events.
-        *
-        * @param identityListener
-        *            The listener to remove
-        */
-       public void removeIdentityListener(IdentityListener identityListener) {
-               identityListenerManager.removeListener(identityListener);
+               this.identityLoader = new IdentityLoader(webOfTrustConnector, fromNullable(context));
        }
 
        //
@@ -103,21 +92,11 @@ public class IdentityManager extends AbstractService {
        //
 
        /**
-        * Sets the context to filter own identities and trusted identities for.
-        *
-        * @param context
-        *            The context to filter for, or {@code null} to not filter
-        */
-       public void setContext(String context) {
-               this.context = context;
-       }
-
-       /**
         * Returns whether the Web of Trust plugin could be reached during the last
         * try.
         *
-        * @return {@code true} if the Web of Trust plugin is connected,
-        *         {@code false} otherwise
+        * @return {@code true} if the Web of Trust plugin is connected, {@code false}
+        *         otherwise
         */
        public boolean isConnected() {
                try {
@@ -130,39 +109,13 @@ public class IdentityManager extends AbstractService {
        }
 
        /**
-        * Returns the own identity with the given ID.
-        *
-        * @param id
-        *            The ID of the own identity
-        * @return The own identity, or {@code null} if there is no such identity
-        */
-       public OwnIdentity getOwnIdentity(String id) {
-               Set<OwnIdentity> allOwnIdentities = getAllOwnIdentities();
-               for (OwnIdentity ownIdentity : allOwnIdentities) {
-                       if (ownIdentity.getId().equals(id)) {
-                               return ownIdentity;
-                       }
-               }
-               return null;
-       }
-
-       /**
         * Returns all own identities.
         *
         * @return All own identities
         */
        public Set<OwnIdentity> getAllOwnIdentities() {
-               try {
-                       Set<OwnIdentity> ownIdentities = webOfTrustConnector.loadAllOwnIdentities();
-                       Map<String, OwnIdentity> newOwnIdentities = new HashMap<String, OwnIdentity>();
-                       for (OwnIdentity ownIdentity : ownIdentities) {
-                               newOwnIdentities.put(ownIdentity.getId(), ownIdentity);
-                       }
-                       checkOwnIdentities(newOwnIdentities);
-                       return ownIdentities;
-               } catch (WebOfTrustException wote1) {
-                       logger.log(Level.WARNING, "Could not load all own identities!", wote1);
-                       return Collections.emptySet();
+               synchronized (currentOwnIdentities) {
+                       return new HashSet<OwnIdentity>(currentOwnIdentities);
                }
        }
 
@@ -170,146 +123,112 @@ public class IdentityManager extends AbstractService {
        // SERVICE METHODS
        //
 
-       /**
-        * {@inheritDoc}
-        */
        @Override
        protected void serviceRun() {
-               Map<OwnIdentity, Map<String, Identity>> oldIdentities = Collections.emptyMap();
-               while (!shouldStop()) {
-                       Map<OwnIdentity, Map<String, Identity>> currentIdentities = new HashMap<OwnIdentity, Map<String, Identity>>();
-                       Map<String, OwnIdentity> currentOwnIdentities = new HashMap<String, OwnIdentity>();
+               Multimap<OwnIdentity, Identity> oldIdentities = create();
 
-                       Set<OwnIdentity> ownIdentities = null;
-                       boolean identitiesLoaded = false;
+               while (!shouldStop()) {
                        try {
-                               /* get all identities with the wanted context from WoT. */
-                               ownIdentities = webOfTrustConnector.loadAllOwnIdentities();
-
-                               /* load trusted identities. */
-                               for (OwnIdentity ownIdentity : ownIdentities) {
-                                       if ((context != null) && !ownIdentity.hasContext(context)) {
-                                               continue;
-                                       }
-                                       currentOwnIdentities.put(ownIdentity.getId(), ownIdentity);
-
-                                       Set<Identity> trustedIdentities = webOfTrustConnector.loadTrustedIdentities(ownIdentity, context);
-                                       Map<String, Identity> identities = new HashMap<String, Identity>();
-                                       currentIdentities.put(ownIdentity, identities);
-                                       for (Identity identity : trustedIdentities) {
-                                               identities.put(identity.getId(), identity);
-                                       }
+                               Multimap<OwnIdentity, Identity> currentIdentities = identityLoader.loadIdentities();
+
+                               detectChangesInIdentities(currentIdentities, oldIdentities);
+                               oldIdentities = currentIdentities;
+
+                               synchronized (currentOwnIdentities) {
+                                       currentOwnIdentities.clear();
+                                       currentOwnIdentities.addAll(currentIdentities.keySet());
                                }
-                               identitiesLoaded = true;
                        } catch (WebOfTrustException wote1) {
                                logger.log(Level.WARNING, "WoT has disappeared!", wote1);
                        }
 
-                       if (identitiesLoaded) {
-
-                               /* check for changes. */
-                               checkOwnIdentities(currentOwnIdentities);
-
-                               /* now check for changes in remote identities. */
-                               for (OwnIdentity ownIdentity : currentOwnIdentities.values()) {
-
-                                       /* find new identities. */
-                                       for (Identity currentIdentity : currentIdentities.get(ownIdentity).values()) {
-                                               if (!oldIdentities.containsKey(ownIdentity) || !oldIdentities.get(ownIdentity).containsKey(currentIdentity.getId())) {
-                                                       identityListenerManager.fireIdentityAdded(ownIdentity, currentIdentity);
-                                               }
-                                       }
-
-                                       /* find removed identities. */
-                                       if (oldIdentities.containsKey(ownIdentity)) {
-                                               for (Identity oldIdentity : oldIdentities.get(ownIdentity).values()) {
-                                                       if (!currentIdentities.get(ownIdentity).containsKey(oldIdentity.getId())) {
-                                                               identityListenerManager.fireIdentityRemoved(ownIdentity, oldIdentity);
-                                                       }
-                                               }
-
-                                               /* check for changes in the contexts. */
-                                               for (Identity oldIdentity : oldIdentities.get(ownIdentity).values()) {
-                                                       if (!currentIdentities.get(ownIdentity).containsKey(oldIdentity.getId())) {
-                                                               continue;
-                                                       }
-                                                       Identity newIdentity = currentIdentities.get(ownIdentity).get(oldIdentity.getId());
-                                                       Set<String> oldContexts = oldIdentity.getContexts();
-                                                       Set<String> newContexts = newIdentity.getContexts();
-                                                       if (oldContexts.size() != newContexts.size()) {
-                                                               identityListenerManager.fireIdentityUpdated(ownIdentity, newIdentity);
-                                                               continue;
-                                                       }
-                                                       for (String oldContext : oldContexts) {
-                                                               if (!newContexts.contains(oldContext)) {
-                                                                       identityListenerManager.fireIdentityUpdated(ownIdentity, newIdentity);
-                                                                       break;
-                                                               }
-                                                       }
-                                               }
-
-                                               /* check for changes in the properties. */
-                                               for (Identity oldIdentity : oldIdentities.get(ownIdentity).values()) {
-                                                       if (!currentIdentities.get(ownIdentity).containsKey(oldIdentity.getId())) {
-                                                               continue;
-                                                       }
-                                                       Identity newIdentity = currentIdentities.get(ownIdentity).get(oldIdentity.getId());
-                                                       Map<String, String> oldProperties = oldIdentity.getProperties();
-                                                       Map<String, String> newProperties = newIdentity.getProperties();
-                                                       if (oldProperties.size() != newProperties.size()) {
-                                                               identityListenerManager.fireIdentityUpdated(ownIdentity, newIdentity);
-                                                               continue;
-                                                       }
-                                                       for (Entry<String, String> oldProperty : oldProperties.entrySet()) {
-                                                               if (!newProperties.containsKey(oldProperty.getKey()) || !newProperties.get(oldProperty.getKey()).equals(oldProperty.getValue())) {
-                                                                       identityListenerManager.fireIdentityUpdated(ownIdentity, newIdentity);
-                                                                       break;
-                                                               }
-                                                       }
-                                               }
-                                       }
-                               }
-
-                               /* remember the current set of identities. */
-                               oldIdentities = currentIdentities;
-                       }
-
                        /* wait a minute before checking again. */
                        sleep(60 * 1000);
                }
        }
 
-       //
-       // PRIVATE METHODS
-       //
+       private void detectChangesInIdentities(Multimap<OwnIdentity, Identity> newIdentities, Multimap<OwnIdentity, Identity> oldIdentities) {
+               IdentityChangeDetector identityChangeDetector = new IdentityChangeDetector(getAllOwnIdentities());
+               identityChangeDetector.onNewIdentity(addNewOwnIdentityAndItsTrustedIdentities(newIdentities));
+               identityChangeDetector.onRemovedIdentity(removeOwnIdentityAndItsTrustedIdentities(oldIdentities));
+               identityChangeDetector.onUnchangedIdentity(detectChangesInTrustedIdentities(newIdentities, oldIdentities));
+               identityChangeDetector.detectChanges(newIdentities.keySet());
+       }
 
-       /**
-        * Checks the given new list of own identities for added or removed own
-        * identities, as compared to {@link #currentOwnIdentities}.
-        *
-        * @param newOwnIdentities
-        *            The new own identities
-        */
-       private void checkOwnIdentities(Map<String, OwnIdentity> newOwnIdentities) {
-               synchronized (syncObject) {
+       private IdentityProcessor detectChangesInTrustedIdentities(Multimap<OwnIdentity, Identity> newIdentities, Multimap<OwnIdentity, Identity> oldIdentities) {
+               return new DefaultIdentityProcessor(oldIdentities, newIdentities);
+       }
 
-                       /* find removed own identities: */
-                       for (OwnIdentity oldOwnIdentity : currentOwnIdentities.values()) {
-                               if (!newOwnIdentities.containsKey(oldOwnIdentity.getId())) {
-                                       identityListenerManager.fireOwnIdentityRemoved(oldOwnIdentity);
+       private IdentityProcessor removeOwnIdentityAndItsTrustedIdentities(final Multimap<OwnIdentity, Identity> oldIdentities) {
+               return new IdentityProcessor() {
+                       @Override
+                       public void processIdentity(Identity identity) {
+                               eventBus.post(new OwnIdentityRemovedEvent((OwnIdentity) identity));
+                               for (Identity removedIdentity : oldIdentities.get((OwnIdentity) identity)) {
+                                       eventBus.post(new IdentityRemovedEvent((OwnIdentity) identity, removedIdentity));
                                }
                        }
+               };
+       }
 
-                       /* find added own identities. */
-                       for (OwnIdentity currentOwnIdentity : newOwnIdentities.values()) {
-                               if (!currentOwnIdentities.containsKey(currentOwnIdentity.getId())) {
-                                       identityListenerManager.fireOwnIdentityAdded(currentOwnIdentity);
+       private IdentityProcessor addNewOwnIdentityAndItsTrustedIdentities(final Multimap<OwnIdentity, Identity> newIdentities) {
+               return new IdentityProcessor() {
+                       @Override
+                       public void processIdentity(Identity identity) {
+                               eventBus.post(new OwnIdentityAddedEvent((OwnIdentity) identity));
+                               for (Identity newIdentity : newIdentities.get((OwnIdentity) identity)) {
+                                       eventBus.post(new IdentityAddedEvent((OwnIdentity) identity, newIdentity));
                                }
                        }
+               };
+       }
+
+       private class DefaultIdentityProcessor implements IdentityProcessor {
+
+               private final Multimap<OwnIdentity, Identity> oldIdentities;
+               private final Multimap<OwnIdentity, Identity> newIdentities;
 
-                       currentOwnIdentities.clear();
-                       currentOwnIdentities.putAll(newOwnIdentities);
+               public DefaultIdentityProcessor(Multimap<OwnIdentity, Identity> oldIdentities, Multimap<OwnIdentity, Identity> newIdentities) {
+                       this.oldIdentities = oldIdentities;
+                       this.newIdentities = newIdentities;
                }
+
+               @Override
+               public void processIdentity(Identity ownIdentity) {
+                       IdentityChangeDetector identityChangeDetector = new IdentityChangeDetector(oldIdentities.get((OwnIdentity) ownIdentity));
+                       identityChangeDetector.onNewIdentity(notifyForAddedIdentities((OwnIdentity) ownIdentity));
+                       identityChangeDetector.onRemovedIdentity(notifyForRemovedIdentities((OwnIdentity) ownIdentity));
+                       identityChangeDetector.onChangedIdentity(notifyForChangedIdentities((OwnIdentity) ownIdentity));
+                       identityChangeDetector.detectChanges(newIdentities.get((OwnIdentity) ownIdentity));
+               }
+
+               private IdentityProcessor notifyForChangedIdentities(final OwnIdentity ownIdentity) {
+                       return new IdentityProcessor() {
+                               @Override
+                               public void processIdentity(Identity identity) {
+                                       eventBus.post(new IdentityUpdatedEvent(ownIdentity, identity));
+                               }
+                       };
+               }
+
+               private IdentityProcessor notifyForRemovedIdentities(final OwnIdentity ownIdentity) {
+                       return new IdentityProcessor() {
+                               @Override
+                               public void processIdentity(Identity identity) {
+                                       eventBus.post(new IdentityRemovedEvent(ownIdentity, identity));
+                               }
+                       };
+               }
+
+               private IdentityProcessor notifyForAddedIdentities(final OwnIdentity ownIdentity) {
+                       return new IdentityProcessor() {
+                               @Override
+                               public void processIdentity(Identity identity) {
+                                       eventBus.post(new IdentityAddedEvent(ownIdentity, identity));
+                               }
+                       };
+               }
+
        }
 
 }