Don’t access the Sone cache directly.
[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.Profile;
33 import net.pterodactylus.sone.data.Reply;
34 import net.pterodactylus.sone.data.Sone;
35 import net.pterodactylus.util.config.Configuration;
36 import net.pterodactylus.util.config.ConfigurationException;
37 import net.pterodactylus.util.logging.Logging;
38 import net.pterodactylus.util.service.AbstractService;
39 import freenet.keys.FreenetURI;
40
41 /**
42  * The Sone core.
43  *
44  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
45  */
46 public class Core extends AbstractService {
47
48         /** The logger. */
49         private static final Logger logger = Logging.getLogger(Core.class);
50
51         /** The configuration. */
52         private Configuration configuration;
53
54         /** Interface to freenet. */
55         private FreenetInterface freenetInterface;
56
57         /** The Sone downloader. */
58         private SoneDownloader soneDownloader;
59
60         /** The local Sones. */
61         private final Set<Sone> localSones = new HashSet<Sone>();
62
63         /** Sone inserters. */
64         private final Map<Sone, SoneInserter> soneInserters = new HashMap<Sone, SoneInserter>();
65
66         /* various caches follow here. */
67
68         /** Cache for all known Sones. */
69         private final Map<String, Sone> soneCache = new HashMap<String, Sone>();
70
71         /** Cache for all known posts. */
72         private final Map<String, Post> postCache = new HashMap<String, Post>();
73
74         /** Cache for all known replies. */
75         private final Map<String, Reply> replyCache = new HashMap<String, Reply>();
76
77         /**
78          * Creates a new core.
79          */
80         public Core() {
81                 super("Sone Core");
82         }
83
84         //
85         // ACCESSORS
86         //
87
88         /**
89          * Sets the configuration of the core.
90          *
91          * @param configuration
92          *            The configuration of the core
93          * @return This core (for method chaining)
94          */
95         public Core configuration(Configuration configuration) {
96                 this.configuration = configuration;
97                 return this;
98         }
99
100         /**
101          * Sets the Freenet interface to use.
102          *
103          * @param freenetInterface
104          *            The Freenet interface to use
105          * @return This core (for method chaining)
106          */
107         public Core freenetInterface(FreenetInterface freenetInterface) {
108                 this.freenetInterface = freenetInterface;
109                 soneDownloader = new SoneDownloader(freenetInterface);
110                 return this;
111         }
112
113         /**
114          * Returns the local Sones.
115          *
116          * @return The local Sones
117          */
118         public Set<Sone> getSones() {
119                 return Collections.unmodifiableSet(localSones);
120         }
121
122         /**
123          * Returns the Sone with the given ID, or an empty Sone that has been
124          * initialized with the given ID.
125          *
126          * @param soneId
127          *            The ID of the Sone
128          * @return The Sone
129          */
130         public Sone getSone(String soneId) {
131                 if (!soneCache.containsKey(soneId)) {
132                         Sone sone = new Sone(soneId);
133                         soneCache.put(soneId, sone);
134                 }
135                 return soneCache.get(soneId);
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                         soneDownloader.addSone(sone);
154                         soneInserters.put(sone, soneInserter);
155                 }
156         }
157
158         /**
159          * Adds a remote Sone so that it is watched for updates.
160          *
161          * @param sone
162          *            The sone to watch
163          */
164         public void addRemoteSone(Sone sone) {
165                 if (!soneCache.containsKey(sone.getId())) {
166                         soneCache.put(sone.getId(), sone);
167                 }
168                 soneDownloader.addSone(sone);
169         }
170
171         /**
172          * Creates a new Sone at a random location.
173          *
174          * @param name
175          *            The name of the Sone
176          * @return The created Sone
177          * @throws SoneException
178          *             if a Sone error occurs
179          */
180         public Sone createSone(String name) throws SoneException {
181                 return createSone(name, null, null);
182         }
183
184         /**
185          * Creates a new Sone at the given location. If one of {@code requestUri} or
186          * {@code insertUrI} is {@code null}, the Sone is created at a random
187          * location.
188          *
189          * @param name
190          *            The name of the Sone
191          * @param requestUri
192          *            The request URI of the Sone, or {@link NullPointerException}
193          *            to create a Sone at a random location
194          * @param insertUri
195          *            The insert URI of the Sone, or {@code null} to create a Sone
196          *            at a random location
197          * @return The created Sone
198          * @throws SoneException
199          *             if a Sone error occurs
200          */
201         public Sone createSone(String name, String requestUri, String insertUri) throws SoneException {
202                 if ((name == null) || (name.trim().length() == 0)) {
203                         throw new SoneException(Type.INVALID_SONE_NAME);
204                 }
205                 String finalRequestUri;
206                 String finalInsertUri;
207                 if ((requestUri == null) || (insertUri == null)) {
208                         String[] keyPair = freenetInterface.generateKeyPair();
209                         finalRequestUri = keyPair[0];
210                         finalInsertUri = keyPair[1];
211                 } else {
212                         finalRequestUri = requestUri;
213                         finalInsertUri = insertUri;
214                 }
215                 Sone sone;
216                 try {
217                         logger.log(Level.FINEST, "Creating new Sone “%s” at %s (%s)…", new Object[] { name, finalRequestUri, finalInsertUri });
218                         sone = new Sone(UUID.randomUUID().toString()).setName(name).setRequestUri(new FreenetURI(finalRequestUri).setKeyType("USK").setDocName("Sone-" + name)).setInsertUri(new FreenetURI(finalInsertUri).setKeyType("USK").setDocName("Sone-" + name));
219                         sone.setProfile(new Profile());
220                         /* set modification counter to 1 so it is inserted immediately. */
221                         sone.setModificationCounter(1);
222                         addSone(sone);
223                 } catch (MalformedURLException mue1) {
224                         throw new SoneException(Type.INVALID_URI);
225                 }
226                 return sone;
227         }
228
229         /**
230          * Deletes the given Sone from this plugin instance.
231          *
232          * @param sone
233          *            The sone to delete
234          */
235         public void deleteSone(Sone sone) {
236                 SoneInserter soneInserter = soneInserters.remove(sone);
237                 soneInserter.stop();
238                 localSones.remove(sone);
239         }
240
241         //
242         // SERVICE METHODS
243         //
244
245         /**
246          * {@inheritDoc}
247          */
248         @Override
249         protected void serviceStart() {
250                 loadConfiguration();
251         }
252
253         /**
254          * {@inheritDoc}
255          */
256         @Override
257         protected void serviceStop() {
258                 soneDownloader.stop();
259                 /* stop all Sone inserters. */
260                 for (SoneInserter soneInserter : soneInserters.values()) {
261                         soneInserter.stop();
262                 }
263                 saveConfiguration();
264         }
265
266         //
267         // PRIVATE METHODS
268         //
269
270         /**
271          * Loads the configuration.
272          */
273         private void loadConfiguration() {
274                 logger.entering(Core.class.getName(), "loadConfiguration()");
275
276                 /* parse local Sones. */
277                 logger.log(Level.INFO, "Loading Sones…");
278                 int soneId = 0;
279                 do {
280                         String sonePrefix = "Sone/Sone." + soneId++;
281                         String id = configuration.getStringValue(sonePrefix + "/ID").getValue(null);
282                         if (id == null) {
283                                 break;
284                         }
285                         String name = configuration.getStringValue(sonePrefix + "/Name").getValue(null);
286                         String insertUri = configuration.getStringValue(sonePrefix + "/InsertURI").getValue(null);
287                         String requestUri = configuration.getStringValue(sonePrefix + "/RequestURI").getValue(null);
288                         long modificationCounter = configuration.getLongValue(sonePrefix + "/ModificationCounter").getValue((long) 0);
289                         String firstName = configuration.getStringValue(sonePrefix + "/Profile/FirstName").getValue(null);
290                         String middleName = configuration.getStringValue(sonePrefix + "/Profile/MiddleName").getValue(null);
291                         String lastName = configuration.getStringValue(sonePrefix + "/Profile/LastName").getValue(null);
292                         try {
293                                 Profile profile = new Profile();
294                                 profile.setFirstName(firstName);
295                                 profile.setMiddleName(middleName);
296                                 profile.setLastName(lastName);
297                                 Sone sone = new Sone(id).setName(name).setRequestUri(new FreenetURI(requestUri)).setInsertUri(new FreenetURI(insertUri));
298                                 soneCache.put(id, sone);
299                                 sone.setProfile(profile);
300                                 int postId = 0;
301                                 do {
302                                         String postPrefix = sonePrefix + "/Post." + postId++;
303                                         id = configuration.getStringValue(postPrefix + "/ID").getValue(null);
304                                         if (id == null) {
305                                                 break;
306                                         }
307                                         long time = configuration.getLongValue(postPrefix + "/Time").getValue(null);
308                                         String text = configuration.getStringValue(postPrefix + "/Text").getValue(null);
309                                         Post post = new Post(id, sone, time, text);
310                                         postCache.put(id, post);
311                                         sone.addPost(post);
312                                 } while (true);
313                                 int replyCounter = 0;
314                                 do {
315                                         String replyPrefix = sonePrefix + "/Reply." + replyCounter++;
316                                         String replyId = configuration.getStringValue(replyPrefix + "/ID").getValue(null);
317                                         if (replyId == null) {
318                                                 break;
319                                         }
320                                         Sone replySone = getSone(configuration.getStringValue(replyPrefix + "/Sone/ID").getValue(null));
321                                         String replySoneKey = configuration.getStringValue(replyPrefix + "/Sone/Key").getValue(null);
322                                         String replySoneName = configuration.getStringValue(replyPrefix + "/Sone/Name").getValue(null);
323                                         replySone.setRequestUri(new FreenetURI(replySoneKey)).setName(replySoneName);
324                                         Post replyPost = postCache.get(configuration.getStringValue(replyPrefix + "/Post").getValue(null));
325                                         long replyTime = configuration.getLongValue(replyPrefix + "/Time").getValue(null);
326                                         String replyText = configuration.getStringValue(replyPrefix + "/Text").getValue(null);
327                                         Reply reply = new Reply(replyId, replySone, replyPost, replyTime, replyText);
328                                         replyCache.put(replyId, reply);
329                                 } while (true);
330
331                                 /* load friends. */
332                                 int friendCounter = 0;
333                                 while (true) {
334                                         String friendPrefix = sonePrefix + "/Friend." + friendCounter++;
335                                         String friendId = configuration.getStringValue(friendPrefix + "/ID").getValue(null);
336                                         if (friendId == null) {
337                                                 break;
338                                         }
339                                         Sone friendSone = getSone(friendId);
340                                         String friendKey = configuration.getStringValue(friendPrefix + "/Key").getValue(null);
341                                         String friendName = configuration.getStringValue(friendPrefix + "/Name").getValue(null);
342                                         friendSone.setRequestUri(new FreenetURI(friendKey)).setName(friendName);
343                                         addRemoteSone(friendSone);
344                                         sone.addFriend(sone);
345                                 }
346
347                                 sone.setModificationCounter(modificationCounter);
348                                 addSone(sone);
349                         } catch (MalformedURLException mue1) {
350                                 logger.log(Level.WARNING, "Could not create Sone from requestUri (“" + requestUri + "”) and insertUri (“" + insertUri + "”)!", mue1);
351                         }
352                 } while (true);
353                 logger.log(Level.INFO, "Loaded %d Sones.", getSones().size());
354
355                 logger.exiting(Core.class.getName(), "loadConfiguration()");
356         }
357
358         /**
359          * Saves the configuraiton.
360          */
361         private void saveConfiguration() {
362                 Set<Sone> sones = getSones();
363                 logger.log(Level.INFO, "Storing %d Sones…", sones.size());
364                 try {
365                         /* store all Sones. */
366                         int soneId = 0;
367                         for (Sone sone : localSones) {
368                                 String sonePrefix = "Sone/Sone." + soneId++;
369                                 configuration.getStringValue(sonePrefix + "/ID").setValue(sone.getId());
370                                 configuration.getStringValue(sonePrefix + "/Name").setValue(sone.getName());
371                                 configuration.getStringValue(sonePrefix + "/RequestURI").setValue(sone.getRequestUri().toString());
372                                 configuration.getStringValue(sonePrefix + "/InsertURI").setValue(sone.getInsertUri().toString());
373                                 configuration.getLongValue(sonePrefix + "/ModificationCounter").setValue(sone.getModificationCounter());
374                                 Profile profile = sone.getProfile();
375                                 configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
376                                 configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
377                                 configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
378                                 int postId = 0;
379                                 for (Post post : sone.getPosts()) {
380                                         String postPrefix = sonePrefix + "/Post." + postId++;
381                                         configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
382                                         configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
383                                         configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
384                                 }
385                                 /* write null ID as terminator. */
386                                 configuration.getStringValue(sonePrefix + "/Post." + postId + "/ID").setValue(null);
387
388                                 int replyId = 0;
389                                 for (Reply reply : sone.getReplies()) {
390                                         String replyPrefix = sonePrefix + "/Reply." + replyId++;
391                                         configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
392                                         configuration.getStringValue(replyPrefix + "/Sone/ID").setValue(reply.getSone().getId());
393                                         configuration.getStringValue(replyPrefix + "/Sone/Key").setValue(reply.getSone().getRequestUri().toString());
394                                         configuration.getStringValue(replyPrefix + "/Sone/Name").setValue(reply.getSone().getName());
395                                         configuration.getStringValue(replyPrefix + "/Post").setValue(reply.getPost().getId());
396                                         configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
397                                         configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
398                                 }
399                                 /* write null ID as terminator. */
400                                 configuration.getStringValue(sonePrefix + "/Reply." + replyId + "/ID").setValue(null);
401
402                                 int friendId = 0;
403                                 for (Sone friend : sone.getFriends()) {
404                                         String friendPrefix = sonePrefix + "/Friend." + friendId++;
405                                         configuration.getStringValue(friendPrefix + "/ID").setValue(friend.getId());
406                                         configuration.getStringValue(friendPrefix + "/Key").setValue(friend.getRequestUri().toString());
407                                         configuration.getStringValue(friendPrefix + "/Name").setValue(friend.getName());
408                                 }
409                                 /* write null ID as terminator. */
410                                 configuration.getStringValue(sonePrefix + "/Friend." + friendId + "/ID").setValue(null);
411
412                         }
413                         /* write null ID as terminator. */
414                         configuration.getStringValue("Sone/Sone." + soneId + "/ID").setValue(null);
415
416                 } catch (ConfigurationException ce1) {
417                         logger.log(Level.WARNING, "Could not store configuration!", ce1);
418                 }
419         }
420
421 }