Load replies and store everything in caches.
[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.ShellCache;
37 import net.pterodactylus.sone.data.Sone;
38 import net.pterodactylus.sone.data.SoneShell;
39 import net.pterodactylus.util.config.Configuration;
40 import net.pterodactylus.util.config.ConfigurationException;
41 import net.pterodactylus.util.logging.Logging;
42 import net.pterodactylus.util.service.AbstractService;
43 import freenet.keys.FreenetURI;
44
45 /**
46  * The Sone core.
47  *
48  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
49  */
50 public class Core extends AbstractService {
51
52         /** The logger. */
53         private static final Logger logger = Logging.getLogger(Core.class);
54
55         /** The configuration. */
56         private Configuration configuration;
57
58         /** Interface to freenet. */
59         private FreenetInterface freenetInterface;
60
61         /** The local Sones. */
62         private final Set<Sone> localSones = new HashSet<Sone>();
63
64         /** Sone inserters. */
65         private final Map<Sone, SoneInserter> soneInserters = new HashMap<Sone, SoneInserter>();
66
67         /* various caches follow here. */
68
69         /** Cache for all known Sones. */
70         private final ShellCache<Sone> soneCache = new ShellCache<Sone>(SoneShell.creator);
71
72         /** Cache for all known posts. */
73         private final ShellCache<Post> postCache = new ShellCache<Post>(PostShell.creator);
74
75         /** Cache for all known replies. */
76         private final ShellCache<Reply> replyCache = new ShellCache<Reply>(ReplyShell.creator);
77
78         /**
79          * Creates a new core.
80          */
81         public Core() {
82                 super("Sone Core");
83         }
84
85         //
86         // ACCESSORS
87         //
88
89         /**
90          * Sets the configuration of the core.
91          *
92          * @param configuration
93          *            The configuration of the core
94          * @return This core (for method chaining)
95          */
96         public Core configuration(Configuration configuration) {
97                 this.configuration = configuration;
98                 return this;
99         }
100
101         /**
102          * Sets the Freenet interface to use.
103          *
104          * @param freenetInterface
105          *            The Freenet interface to use
106          * @return This core (for method chaining)
107          */
108         public Core freenetInterface(FreenetInterface freenetInterface) {
109                 this.freenetInterface = 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         // ACTIONS
124         //
125
126         /**
127          * Adds the given Sone.
128          *
129          * @param sone
130          *            The Sone to add
131          */
132         public void addSone(Sone sone) {
133                 if (localSones.add(sone)) {
134                         SoneInserter soneInserter = new SoneInserter(freenetInterface, sone);
135                         soneInserter.start();
136                         soneInserters.put(sone, soneInserter);
137                 }
138         }
139
140         /**
141          * Creates a new Sone at a random location.
142          *
143          * @param name
144          *            The name of the Sone
145          * @return The created Sone
146          * @throws SoneException
147          *             if a Sone error occurs
148          */
149         public Sone createSone(String name) throws SoneException {
150                 return createSone(name, null, null);
151         }
152
153         /**
154          * Creates a new Sone at the given location. If one of {@code requestUri} or
155          * {@code insertUrI} is {@code null}, the Sone is created at a random
156          * location.
157          *
158          * @param name
159          *            The name of the Sone
160          * @param requestUri
161          *            The request URI of the Sone, or {@link NullPointerException}
162          *            to create a Sone at a random location
163          * @param insertUri
164          *            The insert URI of the Sone, or {@code null} to create a Sone
165          *            at a random location
166          * @return The created Sone
167          * @throws SoneException
168          *             if a Sone error occurs
169          */
170         public Sone createSone(String name, String requestUri, String insertUri) throws SoneException {
171                 if ((name == null) || (name.trim().length() == 0)) {
172                         throw new SoneException(Type.INVALID_SONE_NAME);
173                 }
174                 String finalRequestUri;
175                 String finalInsertUri;
176                 if ((requestUri == null) || (insertUri == null)) {
177                         String[] keyPair = freenetInterface.generateKeyPair();
178                         finalRequestUri = keyPair[0];
179                         finalInsertUri = keyPair[1];
180                 } else {
181                         finalRequestUri = requestUri;
182                         finalInsertUri = insertUri;
183                 }
184                 Sone sone;
185                 try {
186                         logger.log(Level.FINEST, "Creating new Sone “%s” at %s (%s)…", new Object[] { name, finalRequestUri, finalInsertUri });
187                         sone = new Sone(UUID.randomUUID(), name, new FreenetURI(finalRequestUri), new FreenetURI(finalInsertUri));
188                         sone.setProfile(new Profile());
189                         /* set modification counter to 1 so it is inserted immediately. */
190                         sone.setModificationCounter(1);
191                         addSone(sone);
192                 } catch (MalformedURLException mue1) {
193                         throw new SoneException(Type.INVALID_URI);
194                 }
195                 localSones.add(sone);
196                 return sone;
197         }
198
199         /**
200          * Deletes the given Sone from this plugin instance.
201          *
202          * @param sone
203          *            The sone to delete
204          */
205         public void deleteSone(Sone sone) {
206                 SoneInserter soneInserter = soneInserters.remove(sone);
207                 soneInserter.stop();
208                 localSones.remove(sone);
209         }
210
211         //
212         // SERVICE METHODS
213         //
214
215         /**
216          * {@inheritDoc}
217          */
218         @Override
219         protected void serviceStart() {
220                 loadConfiguration();
221         }
222
223         /**
224          * {@inheritDoc}
225          */
226         @Override
227         protected void serviceStop() {
228                 /* stop all Sone inserters. */
229                 for (SoneInserter soneInserter : soneInserters.values()) {
230                         soneInserter.stop();
231                 }
232                 saveConfiguration();
233         }
234
235         //
236         // PRIVATE METHODS
237         //
238
239         /**
240          * Loads the configuration.
241          */
242         private void loadConfiguration() {
243                 logger.entering(Core.class.getName(), "loadConfiguration()");
244
245                 /* parse local Sones. */
246                 logger.log(Level.INFO, "Loading Sones…");
247                 int soneId = 0;
248                 do {
249                         String sonePrefix = "Sone/Sone." + soneId++;
250                         String id = configuration.getStringValue(sonePrefix + "/ID").getValue(null);
251                         if (id == null) {
252                                 break;
253                         }
254                         String name = configuration.getStringValue(sonePrefix + "/Name").getValue(null);
255                         String insertUri = configuration.getStringValue(sonePrefix + "/InsertURI").getValue(null);
256                         String requestUri = configuration.getStringValue(sonePrefix + "/RequestURI").getValue(null);
257                         long modificationCounter = configuration.getLongValue(sonePrefix + "/ModificationCounter").getValue((long) 0);
258                         String firstName = configuration.getStringValue(sonePrefix + "/Profile/FirstName").getValue(null);
259                         String middleName = configuration.getStringValue(sonePrefix + "/Profile/MiddleName").getValue(null);
260                         String lastName = configuration.getStringValue(sonePrefix + "/Profile/LastName").getValue(null);
261                         try {
262                                 Profile profile = new Profile();
263                                 profile.setFirstName(firstName);
264                                 profile.setMiddleName(middleName);
265                                 profile.setLastName(lastName);
266                                 Sone sone = new Sone(UUID.fromString(id), name, new FreenetURI(requestUri), new FreenetURI(insertUri));
267                                 soneCache.put(id, sone);
268                                 sone.setProfile(profile);
269                                 int postId = 0;
270                                 do {
271                                         String postPrefix = sonePrefix + "/Post." + postId++;
272                                         id = configuration.getStringValue(postPrefix + "/ID").getValue(null);
273                                         if (id == null) {
274                                                 break;
275                                         }
276                                         long time = configuration.getLongValue(postPrefix + "/Time").getValue(null);
277                                         String text = configuration.getStringValue(postPrefix + "/Text").getValue(null);
278                                         Post post = new Post(UUID.fromString(id), sone, time, text);
279                                         postCache.put(id, post);
280                                         sone.addPost(post);
281                                 } while (true);
282                                 int replyCounter = 0;
283                                 do {
284                                         String replyPrefix = sonePrefix + "/Reply." + replyCounter++;
285                                         String replyId = configuration.getStringValue(replyPrefix + "/ID").getValue(null);
286                                         if (replyId == null) {
287                                                 break;
288                                         }
289                                         Sone replySone = soneCache.get(configuration.getStringValue(replyPrefix + "/Sone").getValue(null));
290                                         Post replyPost = postCache.get(configuration.getStringValue(replyPrefix + "/Post").getValue(null));
291                                         long replyTime = configuration.getLongValue(replyPrefix + "/Time").getValue(null);
292                                         String replyText = configuration.getStringValue(replyPrefix + "/Text").getValue(null);
293                                         Reply reply = new ReplyShell().setSone(replySone).setPost(replyPost).setTime(replyTime).setText(replyText).getShelled();
294                                         replyCache.put(replyId, reply);
295                                 } while (true);
296                                 sone.setModificationCounter(modificationCounter);
297                                 addSone(sone);
298                         } catch (MalformedURLException mue1) {
299                                 logger.log(Level.WARNING, "Could not create Sone from requestUri (“" + requestUri + "”) and insertUri (“" + insertUri + "”)!", mue1);
300                         }
301                 } while (true);
302                 logger.log(Level.INFO, "Loaded %d Sones.", getSones().size());
303
304                 logger.exiting(Core.class.getName(), "loadConfiguration()");
305         }
306
307         /**
308          * Saves the configuraiton.
309          */
310         private void saveConfiguration() {
311                 Set<Sone> sones = getSones();
312                 logger.log(Level.INFO, "Storing %d Sones…", sones.size());
313                 try {
314                         /* store all Sones. */
315                         int soneId = 0;
316                         for (Sone sone : localSones) {
317                                 String sonePrefix = "Sone/Sone." + soneId++;
318                                 configuration.getStringValue(sonePrefix + "/ID").setValue(sone.getId());
319                                 configuration.getStringValue(sonePrefix + "/Name").setValue(sone.getName());
320                                 configuration.getStringValue(sonePrefix + "/RequestURI").setValue(sone.getRequestUri().toString());
321                                 configuration.getStringValue(sonePrefix + "/InsertURI").setValue(sone.getInsertUri().toString());
322                                 configuration.getLongValue(sonePrefix + "/ModificationCounter").setValue(sone.getModificationCounter());
323                                 Profile profile = sone.getProfile();
324                                 configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
325                                 configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
326                                 configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
327                                 int postId = 0;
328                                 for (Post post : sone.getPosts()) {
329                                         String postPrefix = sonePrefix + "/Post." + postId++;
330                                         configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
331                                         configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
332                                         configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
333                                 }
334                                 int replyId = 0;
335                                 for (Reply reply : sone.getReplies()) {
336                                         String replyPrefix = sonePrefix + "/Reply." + replyId++;
337                                         configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
338                                         configuration.getStringValue(replyPrefix + "/Sone").setValue(reply.getSone().getId());
339                                         configuration.getStringValue(replyPrefix + "/Post").setValue(reply.getPost().getId());
340                                         configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
341                                         configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
342                                 }
343                         }
344                 } catch (ConfigurationException ce1) {
345                         logger.log(Level.WARNING, "Could not store configuration!", ce1);
346                 }
347         }
348
349 }