(Current state.)
[jSite2.git] / src / net / pterodactylus / jsite / core / RequestManager.java
1 /*
2  * jSite-next - RequestManager.java -
3  * Copyright © 2009 David Roden
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; either version 2 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software
17  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
18  */
19
20 package net.pterodactylus.jsite.core;
21
22 import java.io.IOException;
23 import java.util.Collection;
24 import java.util.Collections;
25 import java.util.HashMap;
26 import java.util.HashSet;
27 import java.util.Map;
28 import java.util.logging.Level;
29 import java.util.logging.Logger;
30
31 import net.pterodactylus.fcp.highlevel.FcpClient;
32 import net.pterodactylus.fcp.highlevel.FcpException;
33 import net.pterodactylus.jsite.util.IdGenerator;
34 import net.pterodactylus.util.number.Hex;
35
36 /**
37  * Manages requests.
38  *
39  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
40  */
41 public class RequestManager implements NodeListener {
42
43         /** The logger. */
44         private static final Logger logger = Logger.getLogger(RequestManager.class.getName());
45
46         /** Request event manager. */
47         private final RequestListenerManager requestListenerManager = new RequestListenerManager();
48
49         /** The node manager. */
50         private final NodeManager nodeManager;
51
52         /** Maps request IDs to requests. */
53         private final Map<String, Request> idRequests = Collections.synchronizedMap(new HashMap<String, Request>());
54
55         /**
56          * Creates a new request manager.
57          *
58          * @param nodeManager
59          *            The node manager to utilize
60          */
61         public RequestManager(NodeManager nodeManager) {
62                 this.nodeManager = nodeManager;
63         }
64
65         //
66         // LISTENER MANAGEMENT
67         //
68
69         /**
70          * Adds the given request listener to the list of registered listeners.
71          *
72          * @see RequestListenerManager#addListener(RequestListener)
73          * @param requestListener
74          *            The request listener to add
75          */
76         public void addRequestListener(RequestListener requestListener) {
77                 requestListenerManager.addListener(requestListener);
78         }
79
80         /**
81          * Removes the given request listener from the list of registered listeners.
82          *
83          * @see RequestListenerManager#removeListener(RequestListener)
84          * @param requestListener
85          *            The request listener to remove
86          */
87         public void removeRequestListener(RequestListener requestListener) {
88                 requestListenerManager.removeListener(requestListener);
89         }
90
91         //
92         // ACTIONS
93         //
94
95         public void load() throws IOException {
96         }
97
98         public void save() throws IOException {
99         }
100
101         /**
102          * Starts inserting the given project.
103          *
104          * @param project
105          *            The project to insert
106          * @throws JSiteException
107          *             if the project’s node is not connected, or no node is
108          *             connected at all
109          */
110         public void insertProject(Project project) throws JSiteException {
111                 Request request = new Request();
112                 request.setClientToken(generateClientToken(project));
113                 Node wantedNode = project.getNode();
114                 if (wantedNode == null) {
115                         for (Node node : nodeManager.getNodes()) {
116                                 if (nodeManager.getFcpClient(node) != null) {
117                                         wantedNode = node;
118                                         break;
119                                 }
120                         }
121                 }
122                 if (wantedNode == null) {
123                         /* TODO use custom exception */
124                         throw new JSiteException("No node connected.");
125                 }
126                 FcpClient fcpClient = nodeManager.getFcpClient(wantedNode);
127         }
128
129         //
130         // PRIVATE METHODS
131         //
132
133         /**
134          * Checks whether the given client token is a client token created by this
135          * request manager.
136          *
137          * @param clientToken
138          *            The client token to check
139          * @return {@code true} if the client token was created by this request
140          *         manager, {@code false} otherwise
141          */
142         private boolean isKnownClientToken(String clientToken) {
143                 String[] clientTokenParts = clientToken.split("\\.");
144                 if (clientTokenParts.length != 3) {
145                         return false;
146                 }
147                 String projectIdString = clientTokenParts[0];
148                 if (projectIdString.length() != (IdGenerator.DEFAULT_LENGTH * 2)) {
149                         return false;
150                 }
151                 int clientTokenHashCode = -1;
152                 try {
153                         Hex.toByte(projectIdString);
154                         Long.valueOf(clientTokenParts[1]);
155                         clientTokenHashCode = Integer.valueOf(clientTokenParts[2]);
156                 } catch (NumberFormatException nfe1) {
157                         return false;
158                 }
159                 if ((clientTokenParts[0] + "." + clientTokenParts[1]).hashCode() != clientTokenHashCode) {
160                         return false;
161                 }
162                 return true;
163         }
164
165         /**
166          * Generates a client token for the given project.
167          *
168          * @param project
169          *            The project to generate a client token for
170          * @return The generated client token
171          */
172         public String generateClientToken(Project project) {
173                 String clientToken = project.getId() + "." + System.currentTimeMillis();
174                 clientToken += "." + clientToken.hashCode();
175                 return clientToken;
176         }
177
178         /**
179          * Wraps the requests of the FCP API into jSite requests.
180          *
181          * @param requests
182          *            The requests to wrap
183          * @return The wrapped requests
184          */
185         private Collection<Request> wrapRequests(Collection<net.pterodactylus.fcp.highlevel.Request> requests) {
186                 Collection<Request> wrappedRequests = new HashSet<Request>();
187                 for (net.pterodactylus.fcp.highlevel.Request request : requests) {
188                         Request wrappedRequest = new Request(request.getIdentifier());
189                         wrappedRequest.setClientToken(request.getClientToken());
190                         wrappedRequests.add(wrappedRequest);
191                 }
192                 return wrappedRequests;
193         }
194
195         //
196         // INTERFACE NodeListener
197         //
198
199         /**
200          * {@inheritDoc}
201          */
202         public void nodeAdded(Node node) {
203                 /* ignore. */
204         }
205
206         /**
207          * {@inheritDoc}
208          */
209         public void nodeConnected(Node node) {
210                 FcpClient fcpClient = nodeManager.getFcpClient(node);
211                 if (fcpClient == null) {
212                         logger.log(Level.WARNING, "Got no FCP client for node (" + node + ")!");
213                         return;
214                 }
215                 try {
216                         Collection<Request> requests = wrapRequests(fcpClient.getRequests(true));
217                         for (Request request : requests) {
218                                 String clientToken = request.getClientToken();
219                                 if ((clientToken == null) || (clientToken.trim().length() == 0)) {
220                                         continue;
221                                 }
222                                 if (!isKnownClientToken(clientToken)) {
223                                         continue;
224                                 }
225                                 /* TODO - process request. */
226                         }
227                 } catch (IOException ioe1) {
228                         logger.log(Level.WARNING, "Could not get requests from node (" + node + ")!", ioe1);
229                 } catch (FcpException fe1) {
230                         logger.log(Level.WARNING, "Could not get requests from node (" + node + ")!", fe1);
231                 }
232         }
233
234         /**
235          * {@inheritDoc}
236          */
237         public void nodeConnectionFailed(Node node, Throwable cause) {
238                 /* ignore. */
239         }
240
241         /**
242          * {@inheritDoc}
243          */
244         public void nodeDisconnected(Node node, Throwable throwable) {
245                 /* TODO */
246         }
247
248         /**
249          * {@inheritDoc}
250          */
251         public void nodeRemoved(Node node) {
252                 /* ignore. */
253         }
254
255 }