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.ArrayList;
22 import java.util.Collection;
23 import java.util.Collections;
24 import java.util.Comparator;
25 import java.util.HashMap;
26 import java.util.HashSet;
27 import java.util.List;
30 import java.util.UUID;
31 import java.util.logging.Level;
32 import java.util.logging.Logger;
34 import net.pterodactylus.sone.core.SoneException.Type;
35 import net.pterodactylus.sone.data.Post;
36 import net.pterodactylus.sone.data.Profile;
37 import net.pterodactylus.sone.data.Reply;
38 import net.pterodactylus.sone.data.Sone;
39 import net.pterodactylus.util.config.Configuration;
40 import net.pterodactylus.util.config.ConfigurationException;
41 import net.pterodactylus.util.filter.Filter;
42 import net.pterodactylus.util.filter.Filters;
43 import net.pterodactylus.util.logging.Logging;
44 import net.pterodactylus.util.service.AbstractService;
45 import freenet.client.FetchResult;
46 import freenet.keys.FreenetURI;
51 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
53 public class Core extends AbstractService {
56 private static final Logger logger = Logging.getLogger(Core.class);
58 /** The configuration. */
59 private Configuration configuration;
61 /** Interface to freenet. */
62 private FreenetInterface freenetInterface;
64 /** The Sone downloader. */
65 private SoneDownloader soneDownloader;
67 /** The local Sones. */
68 private final Set<Sone> localSones = new HashSet<Sone>();
70 /** Sone inserters. */
71 private final Map<Sone, SoneInserter> soneInserters = new HashMap<Sone, SoneInserter>();
73 /* various caches follow here. */
75 /** Cache for all known Sones. */
76 private final Map<String, Sone> soneCache = new HashMap<String, Sone>();
78 /** Cache for all known posts. */
79 private final Map<String, Post> postCache = new HashMap<String, Post>();
81 /** Cache for all known replies. */
82 private final Map<String, Reply> replyCache = new HashMap<String, Reply>();
96 * Sets the configuration of the core.
98 * @param configuration
99 * The configuration of the core
100 * @return This core (for method chaining)
102 public Core configuration(Configuration configuration) {
103 this.configuration = configuration;
108 * Sets the Freenet interface to use.
110 * @param freenetInterface
111 * The Freenet interface to use
112 * @return This core (for method chaining)
114 public Core freenetInterface(FreenetInterface freenetInterface) {
115 this.freenetInterface = freenetInterface;
116 soneDownloader = new SoneDownloader(this, freenetInterface);
117 soneDownloader.start();
122 * Returns the local Sones.
124 * @return The local Sones
126 public Set<Sone> getSones() {
127 return Collections.unmodifiableSet(localSones);
131 * Returns the Sone with the given ID, or an empty Sone that has been
132 * initialized with the given ID.
138 public Sone getSone(String soneId) {
139 if (!soneCache.containsKey(soneId)) {
140 Sone sone = new Sone(soneId);
141 soneCache.put(soneId, sone);
143 return soneCache.get(soneId);
147 * Returns all known sones.
149 * @return All known sones
151 public Collection<Sone> getKnownSones() {
152 return soneCache.values();
156 * Gets all known Sones that are not local Sones.
158 * @return All remote Sones
160 public Collection<Sone> getRemoteSones() {
161 return Filters.filteredCollection(getKnownSones(), new Filter<Sone>() {
164 @SuppressWarnings("synthetic-access")
165 public boolean filterObject(Sone object) {
166 return !localSones.contains(object);
172 * Creates a new post and adds it to the given Sone.
175 * The sone that creates the post
177 * The text of the post
178 * @return The created post
180 public Post createPost(Sone sone, String text) {
181 return createPost(sone, System.currentTimeMillis(), text);
185 * Creates a new post and adds it to the given Sone.
188 * The Sone that creates the post
190 * The time of the post
192 * The text of the post
193 * @return The created post
195 public Post createPost(Sone sone, long time, String text) {
196 Post post = getPost(UUID.randomUUID().toString()).setSone(sone).setTime(time).setText(text);
205 * The Sone that posts the reply
207 * The post the reply refers to
209 * The text of the reply
210 * @return The created reply
212 public Reply createReply(Sone sone, Post post, String text) {
213 return createReply(sone, post, System.currentTimeMillis(), text);
220 * The Sone that posts the reply
222 * The post the reply refers to
224 * The time of the post
226 * The text of the reply
227 * @return The created reply
229 public Reply createReply(Sone sone, Post post, long time, String text) {
230 Reply reply = getReply(UUID.randomUUID().toString()).setSone(sone).setPost(post).setTime(time).setText(text);
231 sone.addReply(reply);
240 * Adds a Sone to watch for updates. The Sone needs to be completely
244 * The Sone to watch for updates
246 public void addSone(Sone sone) {
247 soneCache.put(sone.getId(), sone);
248 if (!localSones.contains(sone)) {
249 soneDownloader.addSone(sone);
254 * Adds the given Sone.
259 public void addLocalSone(Sone sone) {
260 if (localSones.add(sone)) {
261 SoneInserter soneInserter = new SoneInserter(this, freenetInterface, sone);
262 soneInserter.start();
263 soneInserters.put(sone, soneInserter);
268 * Creates a new Sone at a random location.
271 * The name of the Sone
272 * @return The created Sone
273 * @throws SoneException
274 * if a Sone error occurs
276 public Sone createSone(String name) throws SoneException {
277 return createSone(name, "Sone-" + name, null, null);
281 * Creates a new Sone at the given location. If one of {@code requestUri} or
282 * {@code insertUrI} is {@code null}, the Sone is created at a random
286 * The name of the Sone
287 * @param documentName
288 * The document name in the SSK
290 * The request URI of the Sone, or {@link NullPointerException}
291 * to create a Sone at a random location
293 * The insert URI of the Sone, or {@code null} to create a Sone
294 * at a random location
295 * @return The created Sone
296 * @throws SoneException
297 * if a Sone error occurs
299 public Sone createSone(String name, String documentName, String requestUri, String insertUri) throws SoneException {
300 if ((name == null) || (name.trim().length() == 0)) {
301 throw new SoneException(Type.INVALID_SONE_NAME);
303 String finalRequestUri;
304 String finalInsertUri;
305 if ((requestUri == null) || (insertUri == null)) {
306 String[] keyPair = freenetInterface.generateKeyPair();
307 finalRequestUri = keyPair[0];
308 finalInsertUri = keyPair[1];
310 finalRequestUri = requestUri;
311 finalInsertUri = insertUri;
315 logger.log(Level.FINEST, "Creating new Sone “%s” at %s (%s)…", new Object[] { name, finalRequestUri, finalInsertUri });
316 sone = getSone(UUID.randomUUID().toString()).setName(name).setRequestUri(new FreenetURI(finalRequestUri).setKeyType("USK").setDocName(documentName)).setInsertUri(new FreenetURI(finalInsertUri).setKeyType("USK").setDocName(documentName));
317 sone.setProfile(new Profile());
318 /* set modification counter to 1 so it is inserted immediately. */
319 sone.setModificationCounter(1);
321 } catch (MalformedURLException mue1) {
322 throw new SoneException(Type.INVALID_URI);
328 * Loads the Sone from the given request URI. The fetching of the data is
329 * performed in a new thread so this method returns immediately.
332 * The request URI to load the Sone from
334 public void loadSone(final String requestUri) {
335 loadSone(requestUri, null);
339 * Loads the Sone from the given request URI. The fetching of the data is
340 * performed in a new thread so this method returns immediately. If
341 * {@code insertUri} is not {@code null} the loaded Sone is converted into a
342 * local Sone and available using as any other local Sone.
345 * The request URI to load the Sone from
347 * The insert URI of the Sone
349 public void loadSone(final String requestUri, final String insertUri) {
350 new Thread(new Runnable() {
353 @SuppressWarnings("synthetic-access")
356 FreenetURI realRequestUri = new FreenetURI(requestUri).setMetaString(new String[] { "sone.xml" });
357 FetchResult fetchResult = freenetInterface.fetchUri(realRequestUri);
358 Sone parsedSone = soneDownloader.parseSone(null, fetchResult, realRequestUri);
359 if (parsedSone != null) {
360 if (insertUri != null) {
361 parsedSone.setInsertUri(new FreenetURI(insertUri));
362 addLocalSone(parsedSone);
367 } catch (MalformedURLException mue1) {
368 logger.log(Level.INFO, "Could not create URI from “" + requestUri + "”.", mue1);
371 }, "Sone Downloader").start();
375 * Loads and updates the given Sone.
380 public void loadSone(final Sone sone) {
381 new Thread(new Runnable() {
384 @SuppressWarnings("synthetic-access")
386 FreenetURI realRequestUri = sone.getRequestUri().setMetaString(new String[] { "sone.xml" });
387 FetchResult fetchResult = freenetInterface.fetchUri(realRequestUri);
388 Sone parsedSone = soneDownloader.parseSone(sone, fetchResult, realRequestUri);
389 if (parsedSone != null) {
393 }, "Sone Downloader").start();
397 * Deletes the given Sone from this plugin instance.
402 public void deleteSone(Sone sone) {
403 SoneInserter soneInserter = soneInserters.remove(sone);
405 localSones.remove(sone);
409 * Returns the post with the given ID. If no post exists yet with the given
410 * ID, a new post is returned.
416 public Post getPost(String postId) {
417 if (!postCache.containsKey(postId)) {
418 postCache.put(postId, new Post(postId));
420 return postCache.get(postId);
424 * Returns the reply with the given ID. If no reply exists yet with the
425 * given ID, a new reply is returned.
428 * The ID of the reply
431 public Reply getReply(String replyId) {
432 if (!replyCache.containsKey(replyId)) {
433 replyCache.put(replyId, new Reply(replyId));
435 return replyCache.get(replyId);
439 * Gets all replies to the given post, sorted by date, oldest first.
442 * The post the replies refer to
443 * @return The sorted list of replies for the post
445 public List<Reply> getReplies(Post post) {
446 List<Reply> replies = new ArrayList<Reply>();
447 for (Reply reply : replyCache.values()) {
448 if (reply.getPost().equals(post)) {
452 Collections.sort(replies, new Comparator<Reply>() {
458 public int compare(Reply leftReply, Reply rightReply) {
459 return (int) Math.max(Integer.MIN_VALUE, Math.min(Integer.MAX_VALUE, leftReply.getTime() - rightReply.getTime()));
473 protected void serviceStart() {
481 protected void serviceStop() {
482 soneDownloader.stop();
483 /* stop all Sone inserters. */
484 for (SoneInserter soneInserter : soneInserters.values()) {
495 * Loads the configuration.
497 private void loadConfiguration() {
498 logger.entering(Core.class.getName(), "loadConfiguration()");
500 /* parse local Sones. */
501 logger.log(Level.INFO, "Loading Sones…");
504 String sonePrefix = "Sone/Sone." + soneId++;
505 String id = configuration.getStringValue(sonePrefix + "/ID").getValue(null);
509 String name = configuration.getStringValue(sonePrefix + "/Name").getValue(null);
510 long time = configuration.getLongValue(sonePrefix + "/Time").getValue((long) 0);
511 String insertUri = configuration.getStringValue(sonePrefix + "/InsertURI").getValue(null);
512 String requestUri = configuration.getStringValue(sonePrefix + "/RequestURI").getValue(null);
513 long modificationCounter = configuration.getLongValue(sonePrefix + "/ModificationCounter").getValue((long) 0);
514 String firstName = configuration.getStringValue(sonePrefix + "/Profile/FirstName").getValue(null);
515 String middleName = configuration.getStringValue(sonePrefix + "/Profile/MiddleName").getValue(null);
516 String lastName = configuration.getStringValue(sonePrefix + "/Profile/LastName").getValue(null);
518 Profile profile = new Profile();
519 profile.setFirstName(firstName);
520 profile.setMiddleName(middleName);
521 profile.setLastName(lastName);
522 Sone sone = getSone(id).setName(name).setTime(time).setRequestUri(new FreenetURI(requestUri)).setInsertUri(new FreenetURI(insertUri));
523 sone.setProfile(profile);
526 String postPrefix = sonePrefix + "/Post." + postId++;
527 id = configuration.getStringValue(postPrefix + "/ID").getValue(null);
531 time = configuration.getLongValue(postPrefix + "/Time").getValue((long) 0);
532 String text = configuration.getStringValue(postPrefix + "/Text").getValue(null);
533 Post post = getPost(id).setSone(sone).setTime(time).setText(text);
536 int replyCounter = 0;
538 String replyPrefix = sonePrefix + "/Reply." + replyCounter++;
539 String replyId = configuration.getStringValue(replyPrefix + "/ID").getValue(null);
540 if (replyId == null) {
543 Post replyPost = getPost(configuration.getStringValue(replyPrefix + "/Post").getValue(null));
544 long replyTime = configuration.getLongValue(replyPrefix + "/Time").getValue(null);
545 String replyText = configuration.getStringValue(replyPrefix + "/Text").getValue(null);
546 Reply reply = getReply(replyId).setSone(sone).setPost(replyPost).setTime(replyTime).setText(replyText);
547 sone.addReply(reply);
551 int friendCounter = 0;
553 String friendPrefix = sonePrefix + "/Friend." + friendCounter++;
554 String friendId = configuration.getStringValue(friendPrefix + "/ID").getValue(null);
555 if (friendId == null) {
558 Sone friendSone = getSone(friendId);
559 String friendKey = configuration.getStringValue(friendPrefix + "/Key").getValue(null);
560 String friendName = configuration.getStringValue(friendPrefix + "/Name").getValue(null);
561 friendSone.setRequestUri(new FreenetURI(friendKey)).setName(friendName);
562 sone.addFriend(friendSone);
565 /* load blocked Sone IDs. */
566 int blockedSoneCounter = 0;
568 String blockedSonePrefix = sonePrefix + "/BlockedSone." + blockedSoneCounter++;
569 String blockedSoneId = configuration.getStringValue(blockedSonePrefix + "/ID").getValue(null);
570 if (blockedSoneId == null) {
573 sone.addBlockedSoneId(blockedSoneId);
576 sone.setModificationCounter(modificationCounter);
578 } catch (MalformedURLException mue1) {
579 logger.log(Level.WARNING, "Could not create Sone from requestUri (“" + requestUri + "”) and insertUri (“" + insertUri + "”)!", mue1);
582 logger.log(Level.INFO, "Loaded %d Sones.", getSones().size());
584 /* load all known Sones. */
585 int knownSonesCounter = 0;
587 String knownSonePrefix = "KnownSone." + knownSonesCounter++;
588 String knownSoneId = configuration.getStringValue(knownSonePrefix + "/ID").getValue(null);
589 if (knownSoneId == null) {
592 String knownSoneName = configuration.getStringValue(knownSonePrefix + "/Name").getValue(null);
593 String knownSoneKey = configuration.getStringValue(knownSonePrefix + "/Key").getValue(null);
595 getSone(knownSoneId).setName(knownSoneName).setRequestUri(new FreenetURI(knownSoneKey));
596 } catch (MalformedURLException mue1) {
597 logger.log(Level.WARNING, "Could not create Sone from requestUri (“" + knownSoneKey + "”)!", mue1);
601 /* load all remote Sones. */
602 for (Sone remoteSone : getRemoteSones()) {
603 loadSone(remoteSone);
606 logger.exiting(Core.class.getName(), "loadConfiguration()");
610 * Saves the configuraiton.
612 private void saveConfiguration() {
613 Set<Sone> sones = getSones();
614 logger.log(Level.INFO, "Storing %d Sones…", sones.size());
616 /* store all Sones. */
618 for (Sone sone : localSones) {
619 String sonePrefix = "Sone/Sone." + soneId++;
620 configuration.getStringValue(sonePrefix + "/ID").setValue(sone.getId());
621 configuration.getStringValue(sonePrefix + "/Name").setValue(sone.getName());
622 configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime());
623 configuration.getStringValue(sonePrefix + "/RequestURI").setValue(sone.getRequestUri().toString());
624 configuration.getStringValue(sonePrefix + "/InsertURI").setValue(sone.getInsertUri().toString());
625 configuration.getLongValue(sonePrefix + "/ModificationCounter").setValue(sone.getModificationCounter());
626 Profile profile = sone.getProfile();
627 configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
628 configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
629 configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
631 for (Post post : sone.getPosts()) {
632 String postPrefix = sonePrefix + "/Post." + postId++;
633 configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
634 configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
635 configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
637 /* write null ID as terminator. */
638 configuration.getStringValue(sonePrefix + "/Post." + postId + "/ID").setValue(null);
641 for (Reply reply : sone.getReplies()) {
642 String replyPrefix = sonePrefix + "/Reply." + replyId++;
643 configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
644 configuration.getStringValue(replyPrefix + "/Post").setValue(reply.getPost().getId());
645 configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
646 configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
648 /* write null ID as terminator. */
649 configuration.getStringValue(sonePrefix + "/Reply." + replyId + "/ID").setValue(null);
652 for (Sone friend : sone.getFriends()) {
653 String friendPrefix = sonePrefix + "/Friend." + friendId++;
654 configuration.getStringValue(friendPrefix + "/ID").setValue(friend.getId());
655 configuration.getStringValue(friendPrefix + "/Key").setValue(friend.getRequestUri().toString());
656 configuration.getStringValue(friendPrefix + "/Name").setValue(friend.getName());
658 /* write null ID as terminator. */
659 configuration.getStringValue(sonePrefix + "/Friend." + friendId + "/ID").setValue(null);
661 /* write all blocked Sones. */
662 int blockedSoneCounter = 0;
663 for (String blockedSoneId : sone.getBlockedSoneIds()) {
664 String blockedSonePrefix = sonePrefix + "/BlockedSone." + blockedSoneCounter++;
665 configuration.getStringValue(blockedSonePrefix + "/ID").setValue(blockedSoneId);
667 configuration.getStringValue(sonePrefix + "/BlockedSone." + blockedSoneCounter + "/ID").setValue(null);
670 /* write null ID as terminator. */
671 configuration.getStringValue("Sone/Sone." + soneId + "/ID").setValue(null);
673 /* write all known Sones. */
674 int knownSonesCounter = 0;
675 for (Sone knownSone : getRemoteSones()) {
676 String knownSonePrefix = "KnownSone." + knownSonesCounter++;
677 configuration.getStringValue(knownSonePrefix + "/ID").setValue(knownSone.getId());
678 configuration.getStringValue(knownSonePrefix + "/Name").setValue(knownSone.getName());
679 configuration.getStringValue(knownSonePrefix + "/Key").setValue(knownSone.getRequestUri().toString());
680 /* TODO - store all known stuff? */
682 configuration.getStringValue("KnownSone." + knownSonesCounter + "/ID").setValue(null);
684 } catch (ConfigurationException ce1) {
685 logger.log(Level.WARNING, "Could not store configuration!", ce1);