Add method to return a Sone by its ID.
[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                 return soneCache.get(soneId);
132         }
133
134         //
135         // ACTIONS
136         //
137
138         /**
139          * Adds the given Sone.
140          *
141          * @param sone
142          *            The Sone to add
143          */
144         public void addSone(Sone sone) {
145                 if (localSones.add(sone)) {
146                         SoneInserter soneInserter = new SoneInserter(freenetInterface, sone);
147                         soneInserter.start();
148                         soneInserters.put(sone, soneInserter);
149                 }
150         }
151
152         /**
153          * Creates a new Sone at a random location.
154          *
155          * @param name
156          *            The name of the Sone
157          * @return The created Sone
158          * @throws SoneException
159          *             if a Sone error occurs
160          */
161         public Sone createSone(String name) throws SoneException {
162                 return createSone(name, null, null);
163         }
164
165         /**
166          * Creates a new Sone at the given location. If one of {@code requestUri} or
167          * {@code insertUrI} is {@code null}, the Sone is created at a random
168          * location.
169          *
170          * @param name
171          *            The name of the Sone
172          * @param requestUri
173          *            The request URI of the Sone, or {@link NullPointerException}
174          *            to create a Sone at a random location
175          * @param insertUri
176          *            The insert URI of the Sone, or {@code null} to create a Sone
177          *            at a random location
178          * @return The created Sone
179          * @throws SoneException
180          *             if a Sone error occurs
181          */
182         public Sone createSone(String name, String requestUri, String insertUri) throws SoneException {
183                 if ((name == null) || (name.trim().length() == 0)) {
184                         throw new SoneException(Type.INVALID_SONE_NAME);
185                 }
186                 String finalRequestUri;
187                 String finalInsertUri;
188                 if ((requestUri == null) || (insertUri == null)) {
189                         String[] keyPair = freenetInterface.generateKeyPair();
190                         finalRequestUri = keyPair[0];
191                         finalInsertUri = keyPair[1];
192                 } else {
193                         finalRequestUri = requestUri;
194                         finalInsertUri = insertUri;
195                 }
196                 Sone sone;
197                 try {
198                         logger.log(Level.FINEST, "Creating new Sone “%s” at %s (%s)…", new Object[] { name, finalRequestUri, finalInsertUri });
199                         sone = new Sone(UUID.randomUUID(), name, new FreenetURI(finalRequestUri), new FreenetURI(finalInsertUri));
200                         sone.setProfile(new Profile());
201                         /* set modification counter to 1 so it is inserted immediately. */
202                         sone.setModificationCounter(1);
203                         addSone(sone);
204                 } catch (MalformedURLException mue1) {
205                         throw new SoneException(Type.INVALID_URI);
206                 }
207                 localSones.add(sone);
208                 return sone;
209         }
210
211         /**
212          * Deletes the given Sone from this plugin instance.
213          *
214          * @param sone
215          *            The sone to delete
216          */
217         public void deleteSone(Sone sone) {
218                 SoneInserter soneInserter = soneInserters.remove(sone);
219                 soneInserter.stop();
220                 localSones.remove(sone);
221         }
222
223         //
224         // SERVICE METHODS
225         //
226
227         /**
228          * {@inheritDoc}
229          */
230         @Override
231         protected void serviceStart() {
232                 loadConfiguration();
233         }
234
235         /**
236          * {@inheritDoc}
237          */
238         @Override
239         protected void serviceStop() {
240                 /* stop all Sone inserters. */
241                 for (SoneInserter soneInserter : soneInserters.values()) {
242                         soneInserter.stop();
243                 }
244                 saveConfiguration();
245         }
246
247         //
248         // PRIVATE METHODS
249         //
250
251         /**
252          * Loads the configuration.
253          */
254         private void loadConfiguration() {
255                 logger.entering(Core.class.getName(), "loadConfiguration()");
256
257                 /* parse local Sones. */
258                 logger.log(Level.INFO, "Loading Sones…");
259                 int soneId = 0;
260                 do {
261                         String sonePrefix = "Sone/Sone." + soneId++;
262                         String id = configuration.getStringValue(sonePrefix + "/ID").getValue(null);
263                         if (id == null) {
264                                 break;
265                         }
266                         String name = configuration.getStringValue(sonePrefix + "/Name").getValue(null);
267                         String insertUri = configuration.getStringValue(sonePrefix + "/InsertURI").getValue(null);
268                         String requestUri = configuration.getStringValue(sonePrefix + "/RequestURI").getValue(null);
269                         long modificationCounter = configuration.getLongValue(sonePrefix + "/ModificationCounter").getValue((long) 0);
270                         String firstName = configuration.getStringValue(sonePrefix + "/Profile/FirstName").getValue(null);
271                         String middleName = configuration.getStringValue(sonePrefix + "/Profile/MiddleName").getValue(null);
272                         String lastName = configuration.getStringValue(sonePrefix + "/Profile/LastName").getValue(null);
273                         try {
274                                 Profile profile = new Profile();
275                                 profile.setFirstName(firstName);
276                                 profile.setMiddleName(middleName);
277                                 profile.setLastName(lastName);
278                                 Sone sone = new Sone(UUID.fromString(id), name, new FreenetURI(requestUri), new FreenetURI(insertUri));
279                                 soneCache.put(id, sone);
280                                 sone.setProfile(profile);
281                                 int postId = 0;
282                                 do {
283                                         String postPrefix = sonePrefix + "/Post." + postId++;
284                                         id = configuration.getStringValue(postPrefix + "/ID").getValue(null);
285                                         if (id == null) {
286                                                 break;
287                                         }
288                                         long time = configuration.getLongValue(postPrefix + "/Time").getValue(null);
289                                         String text = configuration.getStringValue(postPrefix + "/Text").getValue(null);
290                                         Post post = new Post(UUID.fromString(id), sone, time, text);
291                                         postCache.put(id, post);
292                                         sone.addPost(post);
293                                 } while (true);
294                                 int replyCounter = 0;
295                                 do {
296                                         String replyPrefix = sonePrefix + "/Reply." + replyCounter++;
297                                         String replyId = configuration.getStringValue(replyPrefix + "/ID").getValue(null);
298                                         if (replyId == null) {
299                                                 break;
300                                         }
301                                         Sone replySone = soneCache.get(configuration.getStringValue(replyPrefix + "/Sone").getValue(null));
302                                         Post replyPost = postCache.get(configuration.getStringValue(replyPrefix + "/Post").getValue(null));
303                                         long replyTime = configuration.getLongValue(replyPrefix + "/Time").getValue(null);
304                                         String replyText = configuration.getStringValue(replyPrefix + "/Text").getValue(null);
305                                         Reply reply = new ReplyShell().setSone(replySone).setPost(replyPost).setTime(replyTime).setText(replyText).getShelled();
306                                         replyCache.put(replyId, reply);
307                                 } while (true);
308                                 sone.setModificationCounter(modificationCounter);
309                                 addSone(sone);
310                         } catch (MalformedURLException mue1) {
311                                 logger.log(Level.WARNING, "Could not create Sone from requestUri (“" + requestUri + "”) and insertUri (“" + insertUri + "”)!", mue1);
312                         }
313                 } while (true);
314                 logger.log(Level.INFO, "Loaded %d Sones.", getSones().size());
315
316                 logger.exiting(Core.class.getName(), "loadConfiguration()");
317         }
318
319         /**
320          * Saves the configuraiton.
321          */
322         private void saveConfiguration() {
323                 Set<Sone> sones = getSones();
324                 logger.log(Level.INFO, "Storing %d Sones…", sones.size());
325                 try {
326                         /* store all Sones. */
327                         int soneId = 0;
328                         for (Sone sone : localSones) {
329                                 String sonePrefix = "Sone/Sone." + soneId++;
330                                 configuration.getStringValue(sonePrefix + "/ID").setValue(sone.getId());
331                                 configuration.getStringValue(sonePrefix + "/Name").setValue(sone.getName());
332                                 configuration.getStringValue(sonePrefix + "/RequestURI").setValue(sone.getRequestUri().toString());
333                                 configuration.getStringValue(sonePrefix + "/InsertURI").setValue(sone.getInsertUri().toString());
334                                 configuration.getLongValue(sonePrefix + "/ModificationCounter").setValue(sone.getModificationCounter());
335                                 Profile profile = sone.getProfile();
336                                 configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
337                                 configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
338                                 configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
339                                 int postId = 0;
340                                 for (Post post : sone.getPosts()) {
341                                         String postPrefix = sonePrefix + "/Post." + postId++;
342                                         configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
343                                         configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
344                                         configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
345                                 }
346                                 int replyId = 0;
347                                 for (Reply reply : sone.getReplies()) {
348                                         String replyPrefix = sonePrefix + "/Reply." + replyId++;
349                                         configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
350                                         configuration.getStringValue(replyPrefix + "/Sone").setValue(reply.getSone().getId());
351                                         configuration.getStringValue(replyPrefix + "/Post").setValue(reply.getPost().getId());
352                                         configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
353                                         configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
354                                 }
355                         }
356                 } catch (ConfigurationException ce1) {
357                         logger.log(Level.WARNING, "Could not store configuration!", ce1);
358                 }
359         }
360
361 }