(Current state.)
[jSite2.git] / src / net / pterodactylus / jsite / core / RequestManager.java
index 002cd17..54ae5ac 100644 (file)
@@ -1,6 +1,6 @@
 /*
- * jSite2 - RequestManager.java -
- * Copyright © 2008 David Roden
+ * jSite-next - RequestManager.java -
+ * Copyright © 2009 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.jsite.core;
 
 import java.io.IOException;
-import java.util.ArrayList;
+import java.util.Collection;
 import java.util.Collections;
 import java.util.HashMap;
-import java.util.List;
+import java.util.HashSet;
 import java.util.Map;
-import java.util.Set;
 import java.util.logging.Level;
 import java.util.logging.Logger;
 
-import net.pterodactylus.fcp.highlevel.HighLevelCallback;
-import net.pterodactylus.fcp.highlevel.HighLevelCallbackListener;
-import net.pterodactylus.fcp.highlevel.HighLevelClient;
-import net.pterodactylus.fcp.highlevel.HighLevelProgress;
-import net.pterodactylus.fcp.highlevel.HighLevelProgressListener;
-import net.pterodactylus.fcp.highlevel.RequestListResult;
-import net.pterodactylus.fcp.highlevel.RequestResult;
-import net.pterodactylus.util.logging.Logging;
+import net.pterodactylus.fcp.highlevel.FcpClient;
+import net.pterodactylus.fcp.highlevel.FcpException;
+import net.pterodactylus.jsite.util.IdGenerator;
+import net.pterodactylus.util.number.Hex;
 
 /**
- * The request manager keeps track of all the request on all connected nodes.
- * The request manager is added to the {@link NodeManager} as a
- * {@link NodeListener} so that it can fire request-removed events in case a
- * node is disconnected.
- * 
- * @author David ‘Bombe’ Roden <bombe@freenetproject.org>
- * @version $Id$
+ * Manages requests.
+ *
+ * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
  */
-public class RequestManager implements NodeListener, HighLevelProgressListener {
+public class RequestManager implements NodeListener {
 
-       /** Logger. */
-       private static final Logger logger = Logging.getLogger(RequestManager.class.getName());
+       /** The logger. */
+       private static final Logger logger = Logger.getLogger(RequestManager.class.getName());
 
-       /** Request listeners. */
-       private List<RequestListener> requestListeners = Collections.synchronizedList(new ArrayList<RequestListener>());
+       /** Request event manager. */
+       private final RequestListenerManager requestListenerManager = new RequestListenerManager();
 
        /** The node manager. */
-       private NodeManager nodeManager;
+       private final NodeManager nodeManager;
+
+       /** Maps request IDs to requests. */
+       private final Map<String, Request> idRequests = Collections.synchronizedMap(new HashMap<String, Request>());
 
-       /** Request lists for all nodes. */
-       @SuppressWarnings("unused")
-       private Map<Node, Set<Request>> nodeRequests = Collections.synchronizedMap(new HashMap<Node, Set<Request>>());
+       /**
+        * Creates a new request manager.
+        *
+        * @param nodeManager
+        *            The node manager to utilize
+        */
+       public RequestManager(NodeManager nodeManager) {
+               this.nodeManager = nodeManager;
+       }
 
        //
-       // EVENT MANAGEMENT
+       // LISTENER MANAGEMENT
        //
 
        /**
-        * Adds a request listener.
-        * 
+        * Adds the given request listener to the list of registered listeners.
+        *
+        * @see RequestListenerManager#addListener(RequestListener)
         * @param requestListener
         *            The request listener to add
         */
        public void addRequestListener(RequestListener requestListener) {
-               requestListeners.add(requestListener);
+               requestListenerManager.addListener(requestListener);
        }
 
        /**
-        * Removes a request listener.
-        * 
+        * Removes the given request listener from the list of registered listeners.
+        *
+        * @see RequestListenerManager#removeListener(RequestListener)
         * @param requestListener
         *            The request listener to remove
         */
        public void removeRequestListener(RequestListener requestListener) {
-               requestListeners.remove(requestListener);
+               requestListenerManager.removeListener(requestListener);
        }
 
-       /**
-        * Notifies all listeners that a request was added.
-        * 
-        * @param node
-        *            The node that added the request
-        * @param request
-        *            The request that was added
-        */
-       private void fireRequestAdded(Node node, Request request) {
-               for (RequestListener requestListener: requestListeners) {
-                       requestListener.requestAdded(node, request);
-               }
+       //
+       // ACTIONS
+       //
+
+       public void load() throws IOException {
+       }
+
+       public void save() throws IOException {
        }
 
        /**
-        * Notifies all listeners that a request progressed.
-        * 
-        * @param node
-        *            The node that runs the request
-        * @param request
-        *            The request
-        * @param totalBlocks
-        *            The total number of blocks
-        * @param requiredBlocks
-        *            The number of required blocks
-        * @param successfulBlocks
-        *            The number of successful blocks
-        * @param failedBlocks
-        *            The number of failed blocks
-        * @param fatallyFailedBlocks
-        *            The number of fatally failed blocks
-        * @param finalizedTotal
-        *            <code>true</code> if the total number of blocks in final,
-        *            <code>false</code> otherwise
+        * Starts inserting the given project.
+        *
+        * @param project
+        *            The project to insert
+        * @throws JSiteException
+        *             if the project’s node is not connected, or no node is
+        *             connected at all
         */
-       private void fireRequestProgressed(Node node, Request request, int totalBlocks, int requiredBlocks, int successfulBlocks, int failedBlocks, int fatallyFailedBlocks, boolean finalizedTotal) {
-               for (RequestListener requestListener: requestListeners) {
-                       requestListener.requestProgressed(node, request, totalBlocks, requiredBlocks, successfulBlocks, failedBlocks, fatallyFailedBlocks, finalizedTotal);
+       public void insertProject(Project project) throws JSiteException {
+               Request request = new Request();
+               request.setClientToken(generateClientToken(project));
+               Node wantedNode = project.getNode();
+               if (wantedNode == null) {
+                       for (Node node : nodeManager.getNodes()) {
+                               if (nodeManager.getFcpClient(node) != null) {
+                                       wantedNode = node;
+                                       break;
+                               }
+                       }
+               }
+               if (wantedNode == null) {
+                       /* TODO use custom exception */
+                       throw new JSiteException("No node connected.");
                }
+               FcpClient fcpClient = nodeManager.getFcpClient(wantedNode);
        }
 
        //
-       // ACCESSORS
+       // PRIVATE METHODS
        //
 
        /**
-        * Sets the node manager to use.
-        * 
-        * @param nodeManager
-        *            The node manager
+        * Checks whether the given client token is a client token created by this
+        * request manager.
+        *
+        * @param clientToken
+        *            The client token to check
+        * @return {@code true} if the client token was created by this request
+        *         manager, {@code false} otherwise
         */
-       public void setNodeManager(NodeManager nodeManager) {
-               this.nodeManager = nodeManager;
+       private boolean isKnownClientToken(String clientToken) {
+               String[] clientTokenParts = clientToken.split("\\.");
+               if (clientTokenParts.length != 3) {
+                       return false;
+               }
+               String projectIdString = clientTokenParts[0];
+               if (projectIdString.length() != (IdGenerator.DEFAULT_LENGTH * 2)) {
+                       return false;
+               }
+               int clientTokenHashCode = -1;
+               try {
+                       Hex.toByte(projectIdString);
+                       Long.valueOf(clientTokenParts[1]);
+                       clientTokenHashCode = Integer.valueOf(clientTokenParts[2]);
+               } catch (NumberFormatException nfe1) {
+                       return false;
+               }
+               if ((clientTokenParts[0] + "." + clientTokenParts[1]).hashCode() != clientTokenHashCode) {
+                       return false;
+               }
+               return true;
        }
 
-       //
-       // ACTIONS
-       //
-
-       //
-       // PRIVATE ACTIONS
-       //
+       /**
+        * Generates a client token for the given project.
+        *
+        * @param project
+        *            The project to generate a client token for
+        * @return The generated client token
+        */
+       public String generateClientToken(Project project) {
+               String clientToken = project.getId() + "." + System.currentTimeMillis();
+               clientToken += "." + clientToken.hashCode();
+               return clientToken;
+       }
 
        /**
-        * Requests a list of all running requests from a node. This method will
-        * block until the request has been sent!
-        * 
-        * @param node
-        *            The node to get all requests for
-        * @throws IOException
-        *             if an I/O error occurs while communicating with the node
+        * Wraps the requests of the FCP API into jSite requests.
+        *
+        * @param requests
+        *            The requests to wrap
+        * @return The wrapped requests
         */
-       private void getRequests(final Node node) throws IOException {
-               HighLevelClient highLevelClient = nodeManager.getHighLevelClient(node);
-               if (highLevelClient == null) {
-                       logger.log(Level.WARNING, "no client for node: " + node);
-                       return;
+       private Collection<Request> wrapRequests(Collection<net.pterodactylus.fcp.highlevel.Request> requests) {
+               Collection<Request> wrappedRequests = new HashSet<Request>();
+               for (net.pterodactylus.fcp.highlevel.Request request : requests) {
+                       Request wrappedRequest = new Request(request.getIdentifier());
+                       wrappedRequest.setClientToken(request.getClientToken());
+                       wrappedRequests.add(wrappedRequest);
                }
-               HighLevelCallback<RequestListResult> requestListCallback = highLevelClient.getRequests();
-               requestListCallback.addHighLevelCallbackListener(new HighLevelCallbackListener<RequestListResult>() {
-
-                       @SuppressWarnings("synthetic-access")
-                       public void gotResult(HighLevelCallback<RequestListResult> highLevelCallback) {
-                               RequestListResult requestListResult;
-                               try {
-                                       requestListResult = highLevelCallback.getResult();
-                               } catch (InterruptedException e) {
-                                       logger.log(Level.SEVERE, "getResult() blocked and was interrupted");
-                                       return;
-                               }
-                               for (RequestResult requestResult: requestListResult) {
-                                       Request request = new Request(requestResult.getIdentifier());
-                                       /* TODO - fill request */
-                                       fireRequestAdded(node, request);
-                               }
-                       }
-               });
+               return wrappedRequests;
        }
 
        //
@@ -193,40 +200,34 @@ public class RequestManager implements NodeListener, HighLevelProgressListener {
         * {@inheritDoc}
         */
        public void nodeAdded(Node node) {
-               HighLevelClient highLevelClient = nodeManager.getHighLevelClient(node);
-               if (highLevelClient == null) {
-                       logger.warning("got nodeAdded but no high-level client: " + node);
-                       return;
-               }
-               highLevelClient.addHighLevelProgressListener(this);
-       }
-
-       /**
-        * {@inheritDoc}
-        */
-       public void nodeRemoved(Node node) {
-               HighLevelClient highLevelClient = nodeManager.getHighLevelClient(node);
-               if (highLevelClient == null) {
-                       logger.warning("got nodeRemoved but no high-level client: " + node);
-                       return;
-               }
-               highLevelClient.removeHighLevelProgressListener(this);
+               /* ignore. */
        }
 
        /**
         * {@inheritDoc}
         */
        public void nodeConnected(Node node) {
-               HighLevelClient highLevelClient = nodeManager.getHighLevelClient(node);
-               if (highLevelClient == null) {
-                       logger.log(Level.WARNING, "got no high-level client for node " + node);
+               FcpClient fcpClient = nodeManager.getFcpClient(node);
+               if (fcpClient == null) {
+                       logger.log(Level.WARNING, "Got no FCP client for node (" + node + ")!");
                        return;
                }
                try {
-                       highLevelClient.setWatchGlobal(true);
-                       getRequests(node);
-               } catch (IOException e) {
-                       /* ignore exception, disconnects are handled elsewhere. */
+                       Collection<Request> requests = wrapRequests(fcpClient.getRequests(true));
+                       for (Request request : requests) {
+                               String clientToken = request.getClientToken();
+                               if ((clientToken == null) || (clientToken.trim().length() == 0)) {
+                                       continue;
+                               }
+                               if (!isKnownClientToken(clientToken)) {
+                                       continue;
+                               }
+                               /* TODO - process request. */
+                       }
+               } catch (IOException ioe1) {
+                       logger.log(Level.WARNING, "Could not get requests from node (" + node + ")!", ioe1);
+               } catch (FcpException fe1) {
+                       logger.log(Level.WARNING, "Could not get requests from node (" + node + ")!", fe1);
                }
        }
 
@@ -234,30 +235,21 @@ public class RequestManager implements NodeListener, HighLevelProgressListener {
         * {@inheritDoc}
         */
        public void nodeConnectionFailed(Node node, Throwable cause) {
-               /* we don't care about this. */
+               /* ignore. */
        }
 
        /**
         * {@inheritDoc}
         */
        public void nodeDisconnected(Node node, Throwable throwable) {
-               HighLevelClient highLevelClient = nodeManager.getHighLevelClient(node);
-               if (highLevelClient == null) {
-                       logger.warning("got nodeDisconnected from node without high-level client: " + node);
-                       return;
-               }
+               /* TODO */
        }
 
-       //
-       // INTERFACE HighLevelProgressListener
-       //
-
        /**
-        * @see net.pterodactylus.fcp.highlevel.HighLevelProgressListener#progressReceived(java.lang.String,
-        *      net.pterodactylus.fcp.highlevel.HighLevelProgress)
+        * {@inheritDoc}
         */
-       public void progressReceived(String identifier, HighLevelProgress highLevelProgress) {
-               fireRequestProgressed(null, new Request(identifier), highLevelProgress.getTotalBlocks(), highLevelProgress.getRequiredBlocks(), highLevelProgress.getSuccessfulBlocks(), highLevelProgress.getFailedBlocks(), highLevelProgress.getFatallyFailedBlocks(), highLevelProgress.isTotalFinalized());
+       public void nodeRemoved(Node node) {
+               /* ignore. */
        }
 
 }