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 * Enumeration for the possible states of a {@link Sone}.
58 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
60 public enum SoneStatus {
62 /** The Sone is idle, i.e. not being downloaded or inserted. */
65 /** The Sone is currently being inserted. */
68 /** The Sone is currently being downloaded. */
73 private static final Logger logger = Logging.getLogger(Core.class);
75 /** The configuration. */
76 private Configuration configuration;
78 /** Interface to freenet. */
79 private FreenetInterface freenetInterface;
81 /** The Sone downloader. */
82 private SoneDownloader soneDownloader;
84 /** The local Sones. */
85 private final Set<Sone> localSones = new HashSet<Sone>();
87 /** Sone inserters. */
88 private final Map<Sone, SoneInserter> soneInserters = new HashMap<Sone, SoneInserter>();
90 /** The Sones’ statuses. */
91 private final Map<Sone, SoneStatus> soneStatuses = new HashMap<Sone, SoneStatus>();
93 /* various caches follow here. */
95 /** Cache for all known Sones. */
96 private final Map<String, Sone> soneCache = new HashMap<String, Sone>();
98 /** Cache for all known posts. */
99 private final Map<String, Post> postCache = new HashMap<String, Post>();
101 /** Cache for all known replies. */
102 private final Map<String, Reply> replyCache = new HashMap<String, Reply>();
105 * Creates a new core.
116 * Sets the configuration of the core.
118 * @param configuration
119 * The configuration of the core
120 * @return This core (for method chaining)
122 public Core configuration(Configuration configuration) {
123 this.configuration = configuration;
128 * Sets the Freenet interface to use.
130 * @param freenetInterface
131 * The Freenet interface to use
132 * @return This core (for method chaining)
134 public Core freenetInterface(FreenetInterface freenetInterface) {
135 this.freenetInterface = freenetInterface;
136 soneDownloader = new SoneDownloader(this, freenetInterface);
137 soneDownloader.start();
142 * Returns the local Sones.
144 * @return The local Sones
146 public Set<Sone> getSones() {
147 return Collections.unmodifiableSet(localSones);
151 * Returns the Sone with the given ID, or an empty Sone that has been
152 * initialized with the given ID.
158 public Sone getSone(String soneId) {
159 if (!soneCache.containsKey(soneId)) {
160 Sone sone = new Sone(soneId);
161 soneCache.put(soneId, sone);
162 setSoneStatus(sone, SoneStatus.idle);
164 return soneCache.get(soneId);
168 * Returns all known sones.
170 * @return All known sones
172 public Collection<Sone> getKnownSones() {
173 return soneCache.values();
177 * Gets all known Sones that are not local Sones.
179 * @return All remote Sones
181 public Collection<Sone> getRemoteSones() {
182 return Filters.filteredCollection(getKnownSones(), new Filter<Sone>() {
185 @SuppressWarnings("synthetic-access")
186 public boolean filterObject(Sone object) {
187 return !localSones.contains(object);
193 * Returns the status of the given Sone.
196 * The Sone to get the status for
197 * @return The status of the Sone
199 public SoneStatus getSoneStatus(Sone sone) {
200 return soneStatuses.get(sone);
204 * Sets the status of the Sone.
207 * The Sone to set the status for
209 * The status of the Sone
211 public void setSoneStatus(Sone sone, SoneStatus soneStatus) {
212 soneStatuses.put(sone, soneStatus);
216 * Creates a new post and adds it to the given Sone.
219 * The sone that creates the post
221 * The text of the post
222 * @return The created post
224 public Post createPost(Sone sone, String text) {
225 return createPost(sone, System.currentTimeMillis(), text);
229 * Creates a new post and adds it to the given Sone.
232 * The Sone that creates the post
234 * The time of the post
236 * The text of the post
237 * @return The created post
239 public Post createPost(Sone sone, long time, String text) {
240 Post post = getPost(UUID.randomUUID().toString()).setSone(sone).setTime(time).setText(text);
249 * The Sone that posts the reply
251 * The post the reply refers to
253 * The text of the reply
254 * @return The created reply
256 public Reply createReply(Sone sone, Post post, String text) {
257 return createReply(sone, post, System.currentTimeMillis(), text);
264 * The Sone that posts the reply
266 * The post the reply refers to
268 * The time of the post
270 * The text of the reply
271 * @return The created reply
273 public Reply createReply(Sone sone, Post post, long time, String text) {
274 Reply reply = getReply(UUID.randomUUID().toString()).setSone(sone).setPost(post).setTime(time).setText(text);
275 sone.addReply(reply);
284 * Adds a Sone to watch for updates. The Sone needs to be completely
288 * The Sone to watch for updates
290 public void addSone(Sone sone) {
291 soneCache.put(sone.getId(), sone);
292 if (!localSones.contains(sone)) {
293 soneDownloader.addSone(sone);
298 * Adds the given Sone.
303 public void addLocalSone(Sone sone) {
304 if (localSones.add(sone)) {
305 SoneInserter soneInserter = new SoneInserter(this, freenetInterface, sone);
306 soneInserter.start();
307 soneInserters.put(sone, soneInserter);
312 * Creates a new Sone at a random location.
315 * The name of the Sone
316 * @return The created Sone
317 * @throws SoneException
318 * if a Sone error occurs
320 public Sone createSone(String name) throws SoneException {
321 return createSone(name, "Sone-" + name, null, null);
325 * Creates a new Sone at the given location. If one of {@code requestUri} or
326 * {@code insertUrI} is {@code null}, the Sone is created at a random
330 * The name of the Sone
331 * @param documentName
332 * The document name in the SSK
334 * The request URI of the Sone, or {@link NullPointerException}
335 * to create a Sone at a random location
337 * The insert URI of the Sone, or {@code null} to create a Sone
338 * at a random location
339 * @return The created Sone
340 * @throws SoneException
341 * if a Sone error occurs
343 public Sone createSone(String name, String documentName, String requestUri, String insertUri) throws SoneException {
344 if ((name == null) || (name.trim().length() == 0)) {
345 throw new SoneException(Type.INVALID_SONE_NAME);
347 String finalRequestUri;
348 String finalInsertUri;
349 if ((requestUri == null) || (insertUri == null)) {
350 String[] keyPair = freenetInterface.generateKeyPair();
351 finalRequestUri = keyPair[0];
352 finalInsertUri = keyPair[1];
354 finalRequestUri = requestUri;
355 finalInsertUri = insertUri;
359 logger.log(Level.FINEST, "Creating new Sone “%s” at %s (%s)…", new Object[] { name, finalRequestUri, finalInsertUri });
360 sone = getSone(UUID.randomUUID().toString()).setName(name).setRequestUri(new FreenetURI(finalRequestUri).setKeyType("USK").setDocName(documentName)).setInsertUri(new FreenetURI(finalInsertUri).setKeyType("USK").setDocName(documentName));
361 sone.setProfile(new Profile());
362 /* set modification counter to 1 so it is inserted immediately. */
363 sone.setModificationCounter(1);
365 } catch (MalformedURLException mue1) {
366 throw new SoneException(Type.INVALID_URI);
372 * Loads the Sone from the given request URI. The fetching of the data is
373 * performed in a new thread so this method returns immediately.
376 * The request URI to load the Sone from
378 public void loadSone(final String requestUri) {
379 loadSone(requestUri, null);
383 * Loads the Sone from the given request URI. The fetching of the data is
384 * performed in a new thread so this method returns immediately. If
385 * {@code insertUri} is not {@code null} the loaded Sone is converted into a
386 * local Sone and available using as any other local Sone.
389 * The request URI to load the Sone from
391 * The insert URI of the Sone
393 public void loadSone(final String requestUri, final String insertUri) {
394 new Thread(new Runnable() {
397 @SuppressWarnings("synthetic-access")
400 FreenetURI realRequestUri = new FreenetURI(requestUri).setMetaString(new String[] { "sone.xml" });
401 FetchResult fetchResult = freenetInterface.fetchUri(realRequestUri);
402 Sone parsedSone = soneDownloader.parseSone(null, fetchResult, realRequestUri);
403 if (parsedSone != null) {
404 if (insertUri != null) {
405 parsedSone.setInsertUri(new FreenetURI(insertUri));
406 addLocalSone(parsedSone);
411 } catch (MalformedURLException mue1) {
412 logger.log(Level.INFO, "Could not create URI from “" + requestUri + "”.", mue1);
415 }, "Sone Downloader").start();
419 * Loads and updates the given Sone.
424 public void loadSone(final Sone sone) {
425 new Thread(new Runnable() {
428 @SuppressWarnings("synthetic-access")
430 FreenetURI realRequestUri = sone.getRequestUri().setMetaString(new String[] { "sone.xml" });
431 FetchResult fetchResult = freenetInterface.fetchUri(realRequestUri);
432 Sone parsedSone = soneDownloader.parseSone(sone, fetchResult, realRequestUri);
433 if (parsedSone != null) {
437 }, "Sone Downloader").start();
441 * Deletes the given Sone from this plugin instance.
446 public void deleteSone(Sone sone) {
447 SoneInserter soneInserter = soneInserters.remove(sone);
449 localSones.remove(sone);
453 * Returns the post with the given ID. If no post exists yet with the given
454 * ID, a new post is returned.
460 public Post getPost(String postId) {
461 if (!postCache.containsKey(postId)) {
462 postCache.put(postId, new Post(postId));
464 return postCache.get(postId);
468 * Returns the reply with the given ID. If no reply exists yet with the
469 * given ID, a new reply is returned.
472 * The ID of the reply
475 public Reply getReply(String replyId) {
476 if (!replyCache.containsKey(replyId)) {
477 replyCache.put(replyId, new Reply(replyId));
479 return replyCache.get(replyId);
483 * Gets all replies to the given post, sorted by date, oldest first.
486 * The post the replies refer to
487 * @return The sorted list of replies for the post
489 public List<Reply> getReplies(Post post) {
490 List<Reply> replies = new ArrayList<Reply>();
491 for (Reply reply : replyCache.values()) {
492 if (reply.getPost().equals(post)) {
496 Collections.sort(replies, new Comparator<Reply>() {
502 public int compare(Reply leftReply, Reply rightReply) {
503 return (int) Math.max(Integer.MIN_VALUE, Math.min(Integer.MAX_VALUE, leftReply.getTime() - rightReply.getTime()));
517 protected void serviceStart() {
525 protected void serviceStop() {
526 soneDownloader.stop();
527 /* stop all Sone inserters. */
528 for (SoneInserter soneInserter : soneInserters.values()) {
539 * Loads the configuration.
541 private void loadConfiguration() {
542 logger.entering(Core.class.getName(), "loadConfiguration()");
544 /* parse local Sones. */
545 logger.log(Level.INFO, "Loading Sones…");
548 String sonePrefix = "Sone/Sone." + soneId++;
549 String id = configuration.getStringValue(sonePrefix + "/ID").getValue(null);
553 String name = configuration.getStringValue(sonePrefix + "/Name").getValue(null);
554 long time = configuration.getLongValue(sonePrefix + "/Time").getValue((long) 0);
555 String insertUri = configuration.getStringValue(sonePrefix + "/InsertURI").getValue(null);
556 String requestUri = configuration.getStringValue(sonePrefix + "/RequestURI").getValue(null);
557 long modificationCounter = configuration.getLongValue(sonePrefix + "/ModificationCounter").getValue((long) 0);
558 String firstName = configuration.getStringValue(sonePrefix + "/Profile/FirstName").getValue(null);
559 String middleName = configuration.getStringValue(sonePrefix + "/Profile/MiddleName").getValue(null);
560 String lastName = configuration.getStringValue(sonePrefix + "/Profile/LastName").getValue(null);
562 Profile profile = new Profile();
563 profile.setFirstName(firstName);
564 profile.setMiddleName(middleName);
565 profile.setLastName(lastName);
566 Sone sone = getSone(id).setName(name).setTime(time).setRequestUri(new FreenetURI(requestUri)).setInsertUri(new FreenetURI(insertUri));
567 sone.setProfile(profile);
570 String postPrefix = sonePrefix + "/Post." + postId++;
571 id = configuration.getStringValue(postPrefix + "/ID").getValue(null);
575 time = configuration.getLongValue(postPrefix + "/Time").getValue((long) 0);
576 String text = configuration.getStringValue(postPrefix + "/Text").getValue(null);
577 Post post = getPost(id).setSone(sone).setTime(time).setText(text);
580 int replyCounter = 0;
582 String replyPrefix = sonePrefix + "/Reply." + replyCounter++;
583 String replyId = configuration.getStringValue(replyPrefix + "/ID").getValue(null);
584 if (replyId == null) {
587 Post replyPost = getPost(configuration.getStringValue(replyPrefix + "/Post").getValue(null));
588 long replyTime = configuration.getLongValue(replyPrefix + "/Time").getValue(null);
589 String replyText = configuration.getStringValue(replyPrefix + "/Text").getValue(null);
590 Reply reply = getReply(replyId).setSone(sone).setPost(replyPost).setTime(replyTime).setText(replyText);
591 sone.addReply(reply);
595 int friendCounter = 0;
597 String friendPrefix = sonePrefix + "/Friend." + friendCounter++;
598 String friendId = configuration.getStringValue(friendPrefix + "/ID").getValue(null);
599 if (friendId == null) {
602 Sone friendSone = getSone(friendId);
603 String friendKey = configuration.getStringValue(friendPrefix + "/Key").getValue(null);
604 String friendName = configuration.getStringValue(friendPrefix + "/Name").getValue(null);
605 friendSone.setRequestUri(new FreenetURI(friendKey)).setName(friendName);
606 sone.addFriend(friendSone);
609 /* load blocked Sone IDs. */
610 int blockedSoneCounter = 0;
612 String blockedSonePrefix = sonePrefix + "/BlockedSone." + blockedSoneCounter++;
613 String blockedSoneId = configuration.getStringValue(blockedSonePrefix + "/ID").getValue(null);
614 if (blockedSoneId == null) {
617 sone.addBlockedSoneId(blockedSoneId);
620 sone.setModificationCounter(modificationCounter);
622 } catch (MalformedURLException mue1) {
623 logger.log(Level.WARNING, "Could not create Sone from requestUri (“" + requestUri + "”) and insertUri (“" + insertUri + "”)!", mue1);
626 logger.log(Level.INFO, "Loaded %d Sones.", getSones().size());
628 /* load all known Sones. */
629 int knownSonesCounter = 0;
631 String knownSonePrefix = "KnownSone." + knownSonesCounter++;
632 String knownSoneId = configuration.getStringValue(knownSonePrefix + "/ID").getValue(null);
633 if (knownSoneId == null) {
636 String knownSoneName = configuration.getStringValue(knownSonePrefix + "/Name").getValue(null);
637 String knownSoneKey = configuration.getStringValue(knownSonePrefix + "/Key").getValue(null);
639 getSone(knownSoneId).setName(knownSoneName).setRequestUri(new FreenetURI(knownSoneKey));
640 } catch (MalformedURLException mue1) {
641 logger.log(Level.WARNING, "Could not create Sone from requestUri (“" + knownSoneKey + "”)!", mue1);
645 /* load all remote Sones. */
646 for (Sone remoteSone : getRemoteSones()) {
647 loadSone(remoteSone);
650 logger.exiting(Core.class.getName(), "loadConfiguration()");
654 * Saves the configuraiton.
656 private void saveConfiguration() {
657 Set<Sone> sones = getSones();
658 logger.log(Level.INFO, "Storing %d Sones…", sones.size());
660 /* store all Sones. */
662 for (Sone sone : localSones) {
663 String sonePrefix = "Sone/Sone." + soneId++;
664 configuration.getStringValue(sonePrefix + "/ID").setValue(sone.getId());
665 configuration.getStringValue(sonePrefix + "/Name").setValue(sone.getName());
666 configuration.getLongValue(sonePrefix + "/Time").setValue(sone.getTime());
667 configuration.getStringValue(sonePrefix + "/RequestURI").setValue(sone.getRequestUri().toString());
668 configuration.getStringValue(sonePrefix + "/InsertURI").setValue(sone.getInsertUri().toString());
669 configuration.getLongValue(sonePrefix + "/ModificationCounter").setValue(sone.getModificationCounter());
670 Profile profile = sone.getProfile();
671 configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
672 configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
673 configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
675 for (Post post : sone.getPosts()) {
676 String postPrefix = sonePrefix + "/Post." + postId++;
677 configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
678 configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
679 configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
681 /* write null ID as terminator. */
682 configuration.getStringValue(sonePrefix + "/Post." + postId + "/ID").setValue(null);
685 for (Reply reply : sone.getReplies()) {
686 String replyPrefix = sonePrefix + "/Reply." + replyId++;
687 configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
688 configuration.getStringValue(replyPrefix + "/Post").setValue(reply.getPost().getId());
689 configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
690 configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
692 /* write null ID as terminator. */
693 configuration.getStringValue(sonePrefix + "/Reply." + replyId + "/ID").setValue(null);
696 for (Sone friend : sone.getFriends()) {
697 String friendPrefix = sonePrefix + "/Friend." + friendId++;
698 configuration.getStringValue(friendPrefix + "/ID").setValue(friend.getId());
699 configuration.getStringValue(friendPrefix + "/Key").setValue(friend.getRequestUri().toString());
700 configuration.getStringValue(friendPrefix + "/Name").setValue(friend.getName());
702 /* write null ID as terminator. */
703 configuration.getStringValue(sonePrefix + "/Friend." + friendId + "/ID").setValue(null);
705 /* write all blocked Sones. */
706 int blockedSoneCounter = 0;
707 for (String blockedSoneId : sone.getBlockedSoneIds()) {
708 String blockedSonePrefix = sonePrefix + "/BlockedSone." + blockedSoneCounter++;
709 configuration.getStringValue(blockedSonePrefix + "/ID").setValue(blockedSoneId);
711 configuration.getStringValue(sonePrefix + "/BlockedSone." + blockedSoneCounter + "/ID").setValue(null);
714 /* write null ID as terminator. */
715 configuration.getStringValue("Sone/Sone." + soneId + "/ID").setValue(null);
717 /* write all known Sones. */
718 int knownSonesCounter = 0;
719 for (Sone knownSone : getRemoteSones()) {
720 String knownSonePrefix = "KnownSone." + knownSonesCounter++;
721 configuration.getStringValue(knownSonePrefix + "/ID").setValue(knownSone.getId());
722 configuration.getStringValue(knownSonePrefix + "/Name").setValue(knownSone.getName());
723 configuration.getStringValue(knownSonePrefix + "/Key").setValue(knownSone.getRequestUri().toString());
724 /* TODO - store all known stuff? */
726 configuration.getStringValue("KnownSone." + knownSonesCounter + "/ID").setValue(null);
728 } catch (ConfigurationException ce1) {
729 logger.log(Level.WARNING, "Could not store configuration!", ce1);