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