dfa94d68264876f4d9862ccc69a015afc566092b
[Sone.git] / src / main / java / net / pterodactylus / sone / core / Core.java
1 /*
2  * FreenetSone - Core.java - Copyright © 2010 David Roden
3  *
4  * This program is free software: you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation, either version 3 of the License, or
7  * (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
16  */
17
18 package net.pterodactylus.sone.core;
19
20 import java.net.MalformedURLException;
21 import java.util.Collections;
22 import java.util.HashMap;
23 import java.util.HashSet;
24 import java.util.Map;
25 import java.util.Set;
26 import java.util.UUID;
27 import java.util.logging.Level;
28 import java.util.logging.Logger;
29
30 import net.pterodactylus.sone.core.SoneException.Type;
31 import net.pterodactylus.sone.data.Post;
32 import net.pterodactylus.sone.data.PostShell;
33 import net.pterodactylus.sone.data.Profile;
34 import net.pterodactylus.sone.data.Reply;
35 import net.pterodactylus.sone.data.ReplyShell;
36 import net.pterodactylus.sone.data.Shell;
37 import net.pterodactylus.sone.data.ShellCache;
38 import net.pterodactylus.sone.data.Sone;
39 import net.pterodactylus.sone.data.SoneShell;
40 import net.pterodactylus.util.config.Configuration;
41 import net.pterodactylus.util.config.ConfigurationException;
42 import net.pterodactylus.util.logging.Logging;
43 import net.pterodactylus.util.service.AbstractService;
44 import freenet.keys.FreenetURI;
45
46 /**
47  * The Sone core.
48  *
49  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
50  */
51 public class Core extends AbstractService {
52
53         /** The logger. */
54         private static final Logger logger = Logging.getLogger(Core.class);
55
56         /** The configuration. */
57         private Configuration configuration;
58
59         /** Interface to freenet. */
60         private FreenetInterface freenetInterface;
61
62         /** The local Sones. */
63         private final Set<Sone> localSones = new HashSet<Sone>();
64
65         /** Sone inserters. */
66         private final Map<Sone, SoneInserter> soneInserters = new HashMap<Sone, SoneInserter>();
67
68         /* various caches follow here. */
69
70         /** Cache for all known Sones. */
71         private final ShellCache<Sone> soneCache = new ShellCache<Sone>(SoneShell.creator);
72
73         /** Cache for all known posts. */
74         private final ShellCache<Post> postCache = new ShellCache<Post>(PostShell.creator);
75
76         /** Cache for all known replies. */
77         private final ShellCache<Reply> replyCache = new ShellCache<Reply>(ReplyShell.creator);
78
79         /**
80          * Creates a new core.
81          */
82         public Core() {
83                 super("Sone Core");
84         }
85
86         //
87         // ACCESSORS
88         //
89
90         /**
91          * Sets the configuration of the core.
92          *
93          * @param configuration
94          *            The configuration of the core
95          * @return This core (for method chaining)
96          */
97         public Core configuration(Configuration configuration) {
98                 this.configuration = configuration;
99                 return this;
100         }
101
102         /**
103          * Sets the Freenet interface to use.
104          *
105          * @param freenetInterface
106          *            The Freenet interface to use
107          * @return This core (for method chaining)
108          */
109         public Core freenetInterface(FreenetInterface freenetInterface) {
110                 this.freenetInterface = freenetInterface;
111                 return this;
112         }
113
114         /**
115          * Returns the local Sones.
116          *
117          * @return The local Sones
118          */
119         public Set<Sone> getSones() {
120                 return Collections.unmodifiableSet(localSones);
121         }
122
123         /**
124          * Returns a Sone or a {@link Shell} around one for the given ID.
125          *
126          * @param soneId
127          *            The ID of the Sone
128          * @return The Sone, or a {@link Shell} around one
129          */
130         public Sone getSone(String soneId) {
131                 Sone sone = soneCache.get(soneId);
132                 if (sone instanceof SoneShell) {
133                         soneCache.put(soneId, sone = ((SoneShell) sone).getShelled());
134                 }
135                 return sone;
136         }
137
138         //
139         // ACTIONS
140         //
141
142         /**
143          * Adds the given Sone.
144          *
145          * @param sone
146          *            The Sone to add
147          */
148         public void addSone(Sone sone) {
149                 if (localSones.add(sone)) {
150                         soneCache.put(sone.getId(), sone);
151                         SoneInserter soneInserter = new SoneInserter(freenetInterface, sone);
152                         soneInserter.start();
153                         soneInserters.put(sone, soneInserter);
154                 }
155         }
156
157         /**
158          * Creates a new Sone at a random location.
159          *
160          * @param name
161          *            The name of the Sone
162          * @return The created Sone
163          * @throws SoneException
164          *             if a Sone error occurs
165          */
166         public Sone createSone(String name) throws SoneException {
167                 return createSone(name, null, null);
168         }
169
170         /**
171          * Creates a new Sone at the given location. If one of {@code requestUri} or
172          * {@code insertUrI} is {@code null}, the Sone is created at a random
173          * location.
174          *
175          * @param name
176          *            The name of the Sone
177          * @param requestUri
178          *            The request URI of the Sone, or {@link NullPointerException}
179          *            to create a Sone at a random location
180          * @param insertUri
181          *            The insert URI of the Sone, or {@code null} to create a Sone
182          *            at a random location
183          * @return The created Sone
184          * @throws SoneException
185          *             if a Sone error occurs
186          */
187         public Sone createSone(String name, String requestUri, String insertUri) throws SoneException {
188                 if ((name == null) || (name.trim().length() == 0)) {
189                         throw new SoneException(Type.INVALID_SONE_NAME);
190                 }
191                 String finalRequestUri;
192                 String finalInsertUri;
193                 if ((requestUri == null) || (insertUri == null)) {
194                         String[] keyPair = freenetInterface.generateKeyPair();
195                         finalRequestUri = keyPair[0];
196                         finalInsertUri = keyPair[1];
197                 } else {
198                         finalRequestUri = requestUri;
199                         finalInsertUri = insertUri;
200                 }
201                 Sone sone;
202                 try {
203                         logger.log(Level.FINEST, "Creating new Sone “%s” at %s (%s)…", new Object[] { name, finalRequestUri, finalInsertUri });
204                         sone = new Sone(UUID.randomUUID(), name, new FreenetURI(finalRequestUri).setKeyType("USK").setDocName("Sone-" + name), new FreenetURI(finalInsertUri).setKeyType("USK").setDocName("Sone-" + name));
205                         sone.setProfile(new Profile());
206                         /* set modification counter to 1 so it is inserted immediately. */
207                         sone.setModificationCounter(1);
208                         addSone(sone);
209                 } catch (MalformedURLException mue1) {
210                         throw new SoneException(Type.INVALID_URI);
211                 }
212                 return sone;
213         }
214
215         /**
216          * Deletes the given Sone from this plugin instance.
217          *
218          * @param sone
219          *            The sone to delete
220          */
221         public void deleteSone(Sone sone) {
222                 SoneInserter soneInserter = soneInserters.remove(sone);
223                 soneInserter.stop();
224                 localSones.remove(sone);
225         }
226
227         //
228         // SERVICE METHODS
229         //
230
231         /**
232          * {@inheritDoc}
233          */
234         @Override
235         protected void serviceStart() {
236                 loadConfiguration();
237         }
238
239         /**
240          * {@inheritDoc}
241          */
242         @Override
243         protected void serviceStop() {
244                 /* stop all Sone inserters. */
245                 for (SoneInserter soneInserter : soneInserters.values()) {
246                         soneInserter.stop();
247                 }
248                 saveConfiguration();
249         }
250
251         //
252         // PRIVATE METHODS
253         //
254
255         /**
256          * Loads the configuration.
257          */
258         private void loadConfiguration() {
259                 logger.entering(Core.class.getName(), "loadConfiguration()");
260
261                 /* parse local Sones. */
262                 logger.log(Level.INFO, "Loading Sones…");
263                 int soneId = 0;
264                 do {
265                         String sonePrefix = "Sone/Sone." + soneId++;
266                         String id = configuration.getStringValue(sonePrefix + "/ID").getValue(null);
267                         if (id == null) {
268                                 break;
269                         }
270                         String name = configuration.getStringValue(sonePrefix + "/Name").getValue(null);
271                         String insertUri = configuration.getStringValue(sonePrefix + "/InsertURI").getValue(null);
272                         String requestUri = configuration.getStringValue(sonePrefix + "/RequestURI").getValue(null);
273                         long modificationCounter = configuration.getLongValue(sonePrefix + "/ModificationCounter").getValue((long) 0);
274                         String firstName = configuration.getStringValue(sonePrefix + "/Profile/FirstName").getValue(null);
275                         String middleName = configuration.getStringValue(sonePrefix + "/Profile/MiddleName").getValue(null);
276                         String lastName = configuration.getStringValue(sonePrefix + "/Profile/LastName").getValue(null);
277                         try {
278                                 Profile profile = new Profile();
279                                 profile.setFirstName(firstName);
280                                 profile.setMiddleName(middleName);
281                                 profile.setLastName(lastName);
282                                 Sone sone = new Sone(UUID.fromString(id), name, new FreenetURI(requestUri), new FreenetURI(insertUri));
283                                 soneCache.put(id, sone);
284                                 sone.setProfile(profile);
285                                 int postId = 0;
286                                 do {
287                                         String postPrefix = sonePrefix + "/Post." + postId++;
288                                         id = configuration.getStringValue(postPrefix + "/ID").getValue(null);
289                                         if (id == null) {
290                                                 break;
291                                         }
292                                         long time = configuration.getLongValue(postPrefix + "/Time").getValue(null);
293                                         String text = configuration.getStringValue(postPrefix + "/Text").getValue(null);
294                                         Post post = new Post(UUID.fromString(id), sone, time, text);
295                                         postCache.put(id, post);
296                                         sone.addPost(post);
297                                 } while (true);
298                                 int replyCounter = 0;
299                                 do {
300                                         String replyPrefix = sonePrefix + "/Reply." + replyCounter++;
301                                         String replyId = configuration.getStringValue(replyPrefix + "/ID").getValue(null);
302                                         if (replyId == null) {
303                                                 break;
304                                         }
305                                         Sone replySone = soneCache.get(configuration.getStringValue(replyPrefix + "/Sone/ID").getValue(null));
306                                         String replySoneKey = configuration.getStringValue(replyPrefix + "/Sone/Key").getValue(null);
307                                         String replySoneName = configuration.getStringValue(replyPrefix + "/Sone/Name").getValue(null);
308                                         if (replySone instanceof SoneShell) {
309                                                 ((SoneShell) replySone).setRequestUri(new FreenetURI(replySoneKey)).setName(replySoneName);
310                                         }
311                                         Post replyPost = postCache.get(configuration.getStringValue(replyPrefix + "/Post").getValue(null));
312                                         long replyTime = configuration.getLongValue(replyPrefix + "/Time").getValue(null);
313                                         String replyText = configuration.getStringValue(replyPrefix + "/Text").getValue(null);
314                                         Reply reply = new ReplyShell().setSone(replySone).setPost(replyPost).setTime(replyTime).setText(replyText).getShelled();
315                                         replyCache.put(replyId, reply);
316                                 } while (true);
317                                 sone.setModificationCounter(modificationCounter);
318                                 addSone(sone);
319                         } catch (MalformedURLException mue1) {
320                                 logger.log(Level.WARNING, "Could not create Sone from requestUri (“" + requestUri + "”) and insertUri (“" + insertUri + "”)!", mue1);
321                         }
322                 } while (true);
323                 logger.log(Level.INFO, "Loaded %d Sones.", getSones().size());
324
325                 logger.exiting(Core.class.getName(), "loadConfiguration()");
326         }
327
328         /**
329          * Saves the configuraiton.
330          */
331         private void saveConfiguration() {
332                 Set<Sone> sones = getSones();
333                 logger.log(Level.INFO, "Storing %d Sones…", sones.size());
334                 try {
335                         /* store all Sones. */
336                         int soneId = 0;
337                         for (Sone sone : localSones) {
338                                 String sonePrefix = "Sone/Sone." + soneId++;
339                                 configuration.getStringValue(sonePrefix + "/ID").setValue(sone.getId());
340                                 configuration.getStringValue(sonePrefix + "/Name").setValue(sone.getName());
341                                 configuration.getStringValue(sonePrefix + "/RequestURI").setValue(sone.getRequestUri().toString());
342                                 configuration.getStringValue(sonePrefix + "/InsertURI").setValue(sone.getInsertUri().toString());
343                                 configuration.getLongValue(sonePrefix + "/ModificationCounter").setValue(sone.getModificationCounter());
344                                 Profile profile = sone.getProfile();
345                                 configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
346                                 configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
347                                 configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
348                                 int postId = 0;
349                                 for (Post post : sone.getPosts()) {
350                                         String postPrefix = sonePrefix + "/Post." + postId++;
351                                         configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
352                                         configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
353                                         configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
354                                 }
355                                 /* write null ID as terminator. */
356                                 configuration.getStringValue(sonePrefix + "/Post." + postId + "/ID").setValue(null);
357
358                                 int replyId = 0;
359                                 for (Reply reply : sone.getReplies()) {
360                                         String replyPrefix = sonePrefix + "/Reply." + replyId++;
361                                         configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
362                                         configuration.getStringValue(replyPrefix + "/Sone/ID").setValue(reply.getSone().getId());
363                                         configuration.getStringValue(replyPrefix + "/Sone/Key").setValue(reply.getSone().getRequestUri().toString());
364                                         configuration.getStringValue(replyPrefix + "/Sone/Name").setValue(reply.getSone().getName());
365                                         configuration.getStringValue(replyPrefix + "/Post").setValue(reply.getPost().getId());
366                                         configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
367                                         configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
368                                 }
369                                 /* write null ID as terminator. */
370                                 configuration.getStringValue(sonePrefix + "/Reply." + replyId + "/ID").setValue(null);
371                         }
372                         /* write null ID as terminator. */
373                         configuration.getStringValue("Sone/Sone." + soneId + "/ID").setValue(null);
374
375                 } catch (ConfigurationException ce1) {
376                         logger.log(Level.WARNING, "Could not store configuration!", ce1);
377                 }
378         }
379
380 }