Save replies on stopping.
[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 local Sones. */
58         private final Set<Sone> localSones = new HashSet<Sone>();
59
60         /** Sone inserters. */
61         private final Map<Sone, SoneInserter> soneInserters = new HashMap<Sone, SoneInserter>();
62
63         /**
64          * Creates a new core.
65          */
66         public Core() {
67                 super("Sone Core");
68         }
69
70         //
71         // ACCESSORS
72         //
73
74         /**
75          * Sets the configuration of the core.
76          *
77          * @param configuration
78          *            The configuration of the core
79          * @return This core (for method chaining)
80          */
81         public Core configuration(Configuration configuration) {
82                 this.configuration = configuration;
83                 return this;
84         }
85
86         /**
87          * Sets the Freenet interface to use.
88          *
89          * @param freenetInterface
90          *            The Freenet interface to use
91          * @return This core (for method chaining)
92          */
93         public Core freenetInterface(FreenetInterface freenetInterface) {
94                 this.freenetInterface = freenetInterface;
95                 return this;
96         }
97
98         /**
99          * Returns the local Sones.
100          *
101          * @return The local Sones
102          */
103         public Set<Sone> getSones() {
104                 return Collections.unmodifiableSet(localSones);
105         }
106
107         //
108         // ACTIONS
109         //
110
111         /**
112          * Adds the given Sone.
113          *
114          * @param sone
115          *            The Sone to add
116          */
117         public void addSone(Sone sone) {
118                 if (localSones.add(sone)) {
119                         SoneInserter soneInserter = new SoneInserter(freenetInterface, sone);
120                         soneInserter.start();
121                         soneInserters.put(sone, soneInserter);
122                 }
123         }
124
125         /**
126          * Creates a new Sone at a random location.
127          *
128          * @param name
129          *            The name of the Sone
130          * @return The created Sone
131          * @throws SoneException
132          *             if a Sone error occurs
133          */
134         public Sone createSone(String name) throws SoneException {
135                 return createSone(name, null, null);
136         }
137
138         /**
139          * Creates a new Sone at the given location. If one of {@code requestUri} or
140          * {@code insertUrI} is {@code null}, the Sone is created at a random
141          * location.
142          *
143          * @param name
144          *            The name of the Sone
145          * @param requestUri
146          *            The request URI of the Sone, or {@link NullPointerException}
147          *            to create a Sone at a random location
148          * @param insertUri
149          *            The insert URI of the Sone, or {@code null} to create a Sone
150          *            at a random location
151          * @return The created Sone
152          * @throws SoneException
153          *             if a Sone error occurs
154          */
155         public Sone createSone(String name, String requestUri, String insertUri) throws SoneException {
156                 if ((name == null) || (name.trim().length() == 0)) {
157                         throw new SoneException(Type.INVALID_SONE_NAME);
158                 }
159                 String finalRequestUri;
160                 String finalInsertUri;
161                 if ((requestUri == null) || (insertUri == null)) {
162                         String[] keyPair = freenetInterface.generateKeyPair();
163                         finalRequestUri = keyPair[0];
164                         finalInsertUri = keyPair[1];
165                 } else {
166                         finalRequestUri = requestUri;
167                         finalInsertUri = insertUri;
168                 }
169                 Sone sone;
170                 try {
171                         logger.log(Level.FINEST, "Creating new Sone “%s” at %s (%s)…", new Object[] { name, finalRequestUri, finalInsertUri });
172                         sone = new Sone(UUID.randomUUID(), name, new FreenetURI(finalRequestUri), new FreenetURI(finalInsertUri));
173                         sone.setProfile(new Profile());
174                         /* set modification counter to 1 so it is inserted immediately. */
175                         sone.setModificationCounter(1);
176                         addSone(sone);
177                 } catch (MalformedURLException mue1) {
178                         throw new SoneException(Type.INVALID_URI);
179                 }
180                 localSones.add(sone);
181                 return sone;
182         }
183
184         /**
185          * Deletes the given Sone from this plugin instance.
186          *
187          * @param sone
188          *            The sone to delete
189          */
190         public void deleteSone(Sone sone) {
191                 SoneInserter soneInserter = soneInserters.remove(sone);
192                 soneInserter.stop();
193                 localSones.remove(sone);
194         }
195
196         //
197         // SERVICE METHODS
198         //
199
200         /**
201          * {@inheritDoc}
202          */
203         @Override
204         protected void serviceStart() {
205                 loadConfiguration();
206         }
207
208         /**
209          * {@inheritDoc}
210          */
211         @Override
212         protected void serviceStop() {
213                 /* stop all Sone inserters. */
214                 for (SoneInserter soneInserter : soneInserters.values()) {
215                         soneInserter.stop();
216                 }
217                 saveConfiguration();
218         }
219
220         //
221         // PRIVATE METHODS
222         //
223
224         /**
225          * Loads the configuration.
226          */
227         private void loadConfiguration() {
228                 logger.entering(Core.class.getName(), "loadConfiguration()");
229
230                 /* parse local Sones. */
231                 logger.log(Level.INFO, "Loading Sones…");
232                 int soneId = 0;
233                 do {
234                         String sonePrefix = "Sone/Sone." + soneId++;
235                         String id = configuration.getStringValue(sonePrefix + "/ID").getValue(null);
236                         if (id == null) {
237                                 break;
238                         }
239                         String name = configuration.getStringValue(sonePrefix + "/Name").getValue(null);
240                         String insertUri = configuration.getStringValue(sonePrefix + "/InsertURI").getValue(null);
241                         String requestUri = configuration.getStringValue(sonePrefix + "/RequestURI").getValue(null);
242                         long modificationCounter = configuration.getLongValue(sonePrefix + "/ModificationCounter").getValue((long) 0);
243                         String firstName = configuration.getStringValue(sonePrefix + "/Profile/FirstName").getValue(null);
244                         String middleName = configuration.getStringValue(sonePrefix + "/Profile/MiddleName").getValue(null);
245                         String lastName = configuration.getStringValue(sonePrefix + "/Profile/LastName").getValue(null);
246                         try {
247                                 Profile profile = new Profile();
248                                 profile.setFirstName(firstName);
249                                 profile.setMiddleName(middleName);
250                                 profile.setLastName(lastName);
251                                 Sone sone = new Sone(UUID.fromString(id), name, new FreenetURI(requestUri), new FreenetURI(insertUri));
252                                 sone.setProfile(profile);
253                                 int postId = 0;
254                                 do {
255                                         String postPrefix = sonePrefix + "/Post." + postId++;
256                                         id = configuration.getStringValue(postPrefix + "/ID").getValue(null);
257                                         if (id == null) {
258                                                 break;
259                                         }
260                                         long time = configuration.getLongValue(postPrefix + "/Time").getValue(null);
261                                         String text = configuration.getStringValue(postPrefix + "/Text").getValue(null);
262                                         Post post = new Post(UUID.fromString(id), sone, time, text);
263                                         sone.addPost(post);
264                                 } while (true);
265                                 sone.setModificationCounter(modificationCounter);
266                                 addSone(sone);
267                         } catch (MalformedURLException mue1) {
268                                 logger.log(Level.WARNING, "Could not create Sone from requestUri (“" + requestUri + "”) and insertUri (“" + insertUri + "”)!", mue1);
269                         }
270                 } while (true);
271                 logger.log(Level.INFO, "Loaded %d Sones.", getSones().size());
272
273                 logger.exiting(Core.class.getName(), "loadConfiguration()");
274         }
275
276         /**
277          * Saves the configuraiton.
278          */
279         private void saveConfiguration() {
280                 Set<Sone> sones = getSones();
281                 logger.log(Level.INFO, "Storing %d Sones…", sones.size());
282                 try {
283                         /* store all Sones. */
284                         int soneId = 0;
285                         for (Sone sone : localSones) {
286                                 String sonePrefix = "Sone/Sone." + soneId++;
287                                 configuration.getStringValue(sonePrefix + "/ID").setValue(sone.getId());
288                                 configuration.getStringValue(sonePrefix + "/Name").setValue(sone.getName());
289                                 configuration.getStringValue(sonePrefix + "/RequestURI").setValue(sone.getRequestUri().toString());
290                                 configuration.getStringValue(sonePrefix + "/InsertURI").setValue(sone.getInsertUri().toString());
291                                 configuration.getLongValue(sonePrefix + "/ModificationCounter").setValue(sone.getModificationCounter());
292                                 Profile profile = sone.getProfile();
293                                 configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
294                                 configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
295                                 configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
296                                 int postId = 0;
297                                 for (Post post : sone.getPosts()) {
298                                         String postPrefix = sonePrefix + "/Post." + postId++;
299                                         configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
300                                         configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
301                                         configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
302                                 }
303                                 int replyId = 0;
304                                 for (Reply reply : sone.getReplies()) {
305                                         String replyPrefix = sonePrefix + "/Reply." + replyId++;
306                                         configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
307                                         configuration.getStringValue(replyPrefix + "/Sone").setValue(reply.getSone().getId());
308                                         configuration.getStringValue(replyPrefix + "/Post").setValue(reply.getPost().getId());
309                                         configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
310                                         configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
311                                 }
312                         }
313                 } catch (ConfigurationException ce1) {
314                         logger.log(Level.WARNING, "Could not store configuration!", ce1);
315                 }
316         }
317
318 }