2 * FreenetSone - Core.java - Copyright © 2010 David Roden
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.
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.
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/>.
18 package net.pterodactylus.sone.core;
20 import java.net.MalformedURLException;
21 import java.util.Collections;
22 import java.util.HashMap;
23 import java.util.HashSet;
26 import java.util.UUID;
27 import java.util.logging.Level;
28 import java.util.logging.Logger;
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;
44 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
46 public class Core extends AbstractService {
49 private static final Logger logger = Logging.getLogger(Core.class);
51 /** The configuration. */
52 private Configuration configuration;
54 /** Interface to freenet. */
55 private FreenetInterface freenetInterface;
57 /** The Sone downloader. */
58 private SoneDownloader soneDownloader;
60 /** The local Sones. */
61 private final Set<Sone> localSones = new HashSet<Sone>();
63 /** Sone inserters. */
64 private final Map<Sone, SoneInserter> soneInserters = new HashMap<Sone, SoneInserter>();
66 /* various caches follow here. */
68 /** Cache for all known Sones. */
69 private final Map<String, Sone> soneCache = new HashMap<String, Sone>();
71 /** Cache for all known posts. */
72 private final Map<String, Post> postCache = new HashMap<String, Post>();
74 /** Cache for all known replies. */
75 private final Map<String, Reply> replyCache = new HashMap<String, Reply>();
89 * Sets the configuration of the core.
91 * @param configuration
92 * The configuration of the core
93 * @return This core (for method chaining)
95 public Core configuration(Configuration configuration) {
96 this.configuration = configuration;
101 * Sets the Freenet interface to use.
103 * @param freenetInterface
104 * The Freenet interface to use
105 * @return This core (for method chaining)
107 public Core freenetInterface(FreenetInterface freenetInterface) {
108 this.freenetInterface = freenetInterface;
109 soneDownloader = new SoneDownloader(this, freenetInterface);
110 soneDownloader.start();
115 * Returns the local Sones.
117 * @return The local Sones
119 public Set<Sone> getSones() {
120 return Collections.unmodifiableSet(localSones);
124 * Returns the Sone with the given ID, or an empty Sone that has been
125 * initialized with the given ID.
131 public Sone getSone(String soneId) {
132 if (!soneCache.containsKey(soneId)) {
133 Sone sone = new Sone(soneId);
134 soneCache.put(soneId, sone);
136 return soneCache.get(soneId);
140 * Creates a new post.
143 * The sone that creates the post
145 * The text of the post
146 * @return The created post
148 public Post createPost(Sone sone, String text) {
149 return createPost(sone, System.currentTimeMillis(), text);
153 * Creates a new post.
156 * The Sone that creates the post
158 * The time of the post
160 * The text of the post
161 * @return The created post
163 public Post createPost(Sone sone, long time, String text) {
164 return getPost(UUID.randomUUID().toString()).setSone(sone).setTime(time).setText(text);
172 * Adds the given Sone.
177 public void addLocalSone(Sone sone) {
178 if (localSones.add(sone)) {
179 soneCache.put(sone.getId(), sone);
180 SoneInserter soneInserter = new SoneInserter(freenetInterface, sone);
181 soneInserter.start();
182 soneDownloader.addSone(sone);
183 soneInserters.put(sone, soneInserter);
188 * Adds a remote Sone so that it is watched for updates.
193 public void addSone(Sone sone) {
194 if (!soneCache.containsKey(sone.getId())) {
195 soneCache.put(sone.getId(), sone);
197 soneDownloader.addSone(sone);
201 * Creates a new Sone at a random location.
204 * The name of the Sone
205 * @return The created Sone
206 * @throws SoneException
207 * if a Sone error occurs
209 public Sone createSone(String name) throws SoneException {
210 return createSone(name, null, null);
214 * Creates a new Sone at the given location. If one of {@code requestUri} or
215 * {@code insertUrI} is {@code null}, the Sone is created at a random
219 * The name of the Sone
221 * The request URI of the Sone, or {@link NullPointerException}
222 * to create a Sone at a random location
224 * The insert URI of the Sone, or {@code null} to create a Sone
225 * at a random location
226 * @return The created Sone
227 * @throws SoneException
228 * if a Sone error occurs
230 public Sone createSone(String name, String requestUri, String insertUri) throws SoneException {
231 if ((name == null) || (name.trim().length() == 0)) {
232 throw new SoneException(Type.INVALID_SONE_NAME);
234 String finalRequestUri;
235 String finalInsertUri;
236 if ((requestUri == null) || (insertUri == null)) {
237 String[] keyPair = freenetInterface.generateKeyPair();
238 finalRequestUri = keyPair[0];
239 finalInsertUri = keyPair[1];
241 finalRequestUri = requestUri;
242 finalInsertUri = insertUri;
246 logger.log(Level.FINEST, "Creating new Sone “%s” at %s (%s)…", new Object[] { name, finalRequestUri, finalInsertUri });
247 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));
248 sone.setProfile(new Profile());
249 /* set modification counter to 1 so it is inserted immediately. */
250 sone.setModificationCounter(1);
252 } catch (MalformedURLException mue1) {
253 throw new SoneException(Type.INVALID_URI);
259 * Deletes the given Sone from this plugin instance.
264 public void deleteSone(Sone sone) {
265 SoneInserter soneInserter = soneInserters.remove(sone);
267 localSones.remove(sone);
271 * Returns the post with the given ID. If no post exists yet with the given
272 * ID, a new post is returned.
278 public Post getPost(String postId) {
279 if (!postCache.containsKey(postId)) {
280 postCache.put(postId, new Post(postId));
282 return postCache.get(postId);
286 * Returns the reply with the given ID. If no reply exists yet with the
287 * given ID, a new reply is returned.
290 * The ID of the reply
293 public Reply getReply(String replyId) {
294 if (!replyCache.containsKey(replyId)) {
295 replyCache.put(replyId, new Reply(replyId));
297 return replyCache.get(replyId);
308 protected void serviceStart() {
316 protected void serviceStop() {
317 soneDownloader.stop();
318 /* stop all Sone inserters. */
319 for (SoneInserter soneInserter : soneInserters.values()) {
330 * Loads the configuration.
332 private void loadConfiguration() {
333 logger.entering(Core.class.getName(), "loadConfiguration()");
335 /* parse local Sones. */
336 logger.log(Level.INFO, "Loading Sones…");
339 String sonePrefix = "Sone/Sone." + soneId++;
340 String id = configuration.getStringValue(sonePrefix + "/ID").getValue(null);
344 String name = configuration.getStringValue(sonePrefix + "/Name").getValue(null);
345 String insertUri = configuration.getStringValue(sonePrefix + "/InsertURI").getValue(null);
346 String requestUri = configuration.getStringValue(sonePrefix + "/RequestURI").getValue(null);
347 long modificationCounter = configuration.getLongValue(sonePrefix + "/ModificationCounter").getValue((long) 0);
348 String firstName = configuration.getStringValue(sonePrefix + "/Profile/FirstName").getValue(null);
349 String middleName = configuration.getStringValue(sonePrefix + "/Profile/MiddleName").getValue(null);
350 String lastName = configuration.getStringValue(sonePrefix + "/Profile/LastName").getValue(null);
352 Profile profile = new Profile();
353 profile.setFirstName(firstName);
354 profile.setMiddleName(middleName);
355 profile.setLastName(lastName);
356 Sone sone = new Sone(id).setName(name).setRequestUri(new FreenetURI(requestUri)).setInsertUri(new FreenetURI(insertUri));
357 soneCache.put(id, sone);
358 sone.setProfile(profile);
361 String postPrefix = sonePrefix + "/Post." + postId++;
362 id = configuration.getStringValue(postPrefix + "/ID").getValue(null);
366 long time = configuration.getLongValue(postPrefix + "/Time").getValue(null);
367 String text = configuration.getStringValue(postPrefix + "/Text").getValue(null);
368 Post post = getPost(id).setSone(sone).setTime(time).setText(text);
371 int replyCounter = 0;
373 String replyPrefix = sonePrefix + "/Reply." + replyCounter++;
374 String replyId = configuration.getStringValue(replyPrefix + "/ID").getValue(null);
375 if (replyId == null) {
378 Sone replySone = getSone(configuration.getStringValue(replyPrefix + "/Sone/ID").getValue(null));
379 String replySoneKey = configuration.getStringValue(replyPrefix + "/Sone/Key").getValue(null);
380 String replySoneName = configuration.getStringValue(replyPrefix + "/Sone/Name").getValue(null);
381 replySone.setRequestUri(new FreenetURI(replySoneKey)).setName(replySoneName);
382 Post replyPost = postCache.get(configuration.getStringValue(replyPrefix + "/Post").getValue(null));
383 long replyTime = configuration.getLongValue(replyPrefix + "/Time").getValue(null);
384 String replyText = configuration.getStringValue(replyPrefix + "/Text").getValue(null);
385 Reply reply = getReply(replyId).setSone(replySone).setPost(replyPost).setTime(replyTime).setText(replyText);
386 replyCache.put(replyId, reply);
390 int friendCounter = 0;
392 String friendPrefix = sonePrefix + "/Friend." + friendCounter++;
393 String friendId = configuration.getStringValue(friendPrefix + "/ID").getValue(null);
394 if (friendId == null) {
397 Sone friendSone = getSone(friendId);
398 String friendKey = configuration.getStringValue(friendPrefix + "/Key").getValue(null);
399 String friendName = configuration.getStringValue(friendPrefix + "/Name").getValue(null);
400 friendSone.setRequestUri(new FreenetURI(friendKey)).setName(friendName);
402 sone.addFriend(sone);
405 sone.setModificationCounter(modificationCounter);
407 } catch (MalformedURLException mue1) {
408 logger.log(Level.WARNING, "Could not create Sone from requestUri (“" + requestUri + "”) and insertUri (“" + insertUri + "”)!", mue1);
411 logger.log(Level.INFO, "Loaded %d Sones.", getSones().size());
413 logger.exiting(Core.class.getName(), "loadConfiguration()");
417 * Saves the configuraiton.
419 private void saveConfiguration() {
420 Set<Sone> sones = getSones();
421 logger.log(Level.INFO, "Storing %d Sones…", sones.size());
423 /* store all Sones. */
425 for (Sone sone : localSones) {
426 String sonePrefix = "Sone/Sone." + soneId++;
427 configuration.getStringValue(sonePrefix + "/ID").setValue(sone.getId());
428 configuration.getStringValue(sonePrefix + "/Name").setValue(sone.getName());
429 configuration.getStringValue(sonePrefix + "/RequestURI").setValue(sone.getRequestUri().toString());
430 configuration.getStringValue(sonePrefix + "/InsertURI").setValue(sone.getInsertUri().toString());
431 configuration.getLongValue(sonePrefix + "/ModificationCounter").setValue(sone.getModificationCounter());
432 Profile profile = sone.getProfile();
433 configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
434 configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
435 configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
437 for (Post post : sone.getPosts()) {
438 String postPrefix = sonePrefix + "/Post." + postId++;
439 configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
440 configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
441 configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
443 /* write null ID as terminator. */
444 configuration.getStringValue(sonePrefix + "/Post." + postId + "/ID").setValue(null);
447 for (Reply reply : sone.getReplies()) {
448 String replyPrefix = sonePrefix + "/Reply." + replyId++;
449 configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
450 configuration.getStringValue(replyPrefix + "/Sone/ID").setValue(reply.getSone().getId());
451 configuration.getStringValue(replyPrefix + "/Sone/Key").setValue(reply.getSone().getRequestUri().toString());
452 configuration.getStringValue(replyPrefix + "/Sone/Name").setValue(reply.getSone().getName());
453 configuration.getStringValue(replyPrefix + "/Post").setValue(reply.getPost().getId());
454 configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
455 configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
457 /* write null ID as terminator. */
458 configuration.getStringValue(sonePrefix + "/Reply." + replyId + "/ID").setValue(null);
461 for (Sone friend : sone.getFriends()) {
462 String friendPrefix = sonePrefix + "/Friend." + friendId++;
463 configuration.getStringValue(friendPrefix + "/ID").setValue(friend.getId());
464 configuration.getStringValue(friendPrefix + "/Key").setValue(friend.getRequestUri().toString());
465 configuration.getStringValue(friendPrefix + "/Name").setValue(friend.getName());
467 /* write null ID as terminator. */
468 configuration.getStringValue(sonePrefix + "/Friend." + friendId + "/ID").setValue(null);
471 /* write null ID as terminator. */
472 configuration.getStringValue("Sone/Sone." + soneId + "/ID").setValue(null);
474 } catch (ConfigurationException ce1) {
475 logger.log(Level.WARNING, "Could not store configuration!", ce1);