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.logging.Logging;
42 import net.pterodactylus.util.service.AbstractService;
43 import freenet.client.FetchResult;
44 import freenet.keys.FreenetURI;
49 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
51 public class Core extends AbstractService {
54 private static final Logger logger = Logging.getLogger(Core.class);
56 /** The configuration. */
57 private Configuration configuration;
59 /** Interface to freenet. */
60 private FreenetInterface freenetInterface;
62 /** The Sone downloader. */
63 private SoneDownloader soneDownloader;
65 /** The local Sones. */
66 private final Set<Sone> localSones = new HashSet<Sone>();
68 /** Sone inserters. */
69 private final Map<Sone, SoneInserter> soneInserters = new HashMap<Sone, SoneInserter>();
71 /* various caches follow here. */
73 /** Cache for all known Sones. */
74 private final Map<String, Sone> soneCache = new HashMap<String, Sone>();
76 /** Cache for all known posts. */
77 private final Map<String, Post> postCache = new HashMap<String, Post>();
79 /** Cache for all known replies. */
80 private final Map<String, Reply> replyCache = new HashMap<String, Reply>();
94 * Sets the configuration of the core.
96 * @param configuration
97 * The configuration of the core
98 * @return This core (for method chaining)
100 public Core configuration(Configuration configuration) {
101 this.configuration = configuration;
106 * Sets the Freenet interface to use.
108 * @param freenetInterface
109 * The Freenet interface to use
110 * @return This core (for method chaining)
112 public Core freenetInterface(FreenetInterface freenetInterface) {
113 this.freenetInterface = freenetInterface;
114 soneDownloader = new SoneDownloader(this, freenetInterface);
115 soneDownloader.start();
120 * Returns the local Sones.
122 * @return The local Sones
124 public Set<Sone> getSones() {
125 return Collections.unmodifiableSet(localSones);
129 * Returns the Sone with the given ID, or an empty Sone that has been
130 * initialized with the given ID.
136 public Sone getSone(String soneId) {
137 if (!soneCache.containsKey(soneId)) {
138 Sone sone = new Sone(soneId);
139 soneCache.put(soneId, sone);
141 return soneCache.get(soneId);
145 * Returns all known sones.
147 * @return All known sones
149 public Collection<Sone> getKnownSones() {
150 return soneCache.values();
154 * Creates a new post.
157 * The sone that creates the post
159 * The text of the post
160 * @return The created post
162 public Post createPost(Sone sone, String text) {
163 return createPost(sone, System.currentTimeMillis(), text);
167 * Creates a new post.
170 * The Sone that creates the post
172 * The time of the post
174 * The text of the post
175 * @return The created post
177 public Post createPost(Sone sone, long time, String text) {
178 Post post = getPost(UUID.randomUUID().toString()).setSone(sone).setTime(time).setText(text);
187 * The Sone that posts the reply
189 * The post the reply refers to
191 * The text of the reply
192 * @return The created reply
194 public Reply createReply(Sone sone, Post post, String text) {
195 return createReply(sone, post, System.currentTimeMillis(), text);
202 * The Sone that posts the reply
204 * The post the reply refers to
206 * The time of the post
208 * The text of the reply
209 * @return The created reply
211 public Reply createReply(Sone sone, Post post, long time, String text) {
212 Reply reply = getReply(UUID.randomUUID().toString()).setSone(sone).setPost(post).setTime(time).setText(text);
213 sone.addReply(reply);
222 * Adds a Sone to watch for updates. The Sone needs to be completely
226 * The Sone to watch for updates
228 public void addSone(Sone sone) {
229 soneCache.put(sone.getId(), sone);
230 soneDownloader.addSone(sone);
234 * Adds the given Sone.
239 public void addLocalSone(Sone sone) {
240 if (localSones.add(sone)) {
241 SoneInserter soneInserter = new SoneInserter(freenetInterface, sone);
242 soneInserter.start();
243 soneInserters.put(sone, soneInserter);
248 * Creates a new Sone at a random location.
251 * The name of the Sone
252 * @return The created Sone
253 * @throws SoneException
254 * if a Sone error occurs
256 public Sone createSone(String name) throws SoneException {
257 return createSone(name, null, null);
261 * Creates a new Sone at the given location. If one of {@code requestUri} or
262 * {@code insertUrI} is {@code null}, the Sone is created at a random
266 * The name of the Sone
268 * The request URI of the Sone, or {@link NullPointerException}
269 * to create a Sone at a random location
271 * The insert URI of the Sone, or {@code null} to create a Sone
272 * at a random location
273 * @return The created Sone
274 * @throws SoneException
275 * if a Sone error occurs
277 public Sone createSone(String name, String requestUri, String insertUri) throws SoneException {
278 if ((name == null) || (name.trim().length() == 0)) {
279 throw new SoneException(Type.INVALID_SONE_NAME);
281 String finalRequestUri;
282 String finalInsertUri;
283 if ((requestUri == null) || (insertUri == null)) {
284 String[] keyPair = freenetInterface.generateKeyPair();
285 finalRequestUri = keyPair[0];
286 finalInsertUri = keyPair[1];
288 finalRequestUri = requestUri;
289 finalInsertUri = insertUri;
293 logger.log(Level.FINEST, "Creating new Sone “%s” at %s (%s)…", new Object[] { name, finalRequestUri, finalInsertUri });
294 sone = getSone(UUID.randomUUID().toString()).setName(name).setRequestUri(new FreenetURI(finalRequestUri).setKeyType("USK").setDocName("Sone-" + name)).setInsertUri(new FreenetURI(finalInsertUri).setKeyType("USK").setDocName("Sone-" + name));
295 sone.setProfile(new Profile());
296 /* set modification counter to 1 so it is inserted immediately. */
297 sone.setModificationCounter(1);
299 } catch (MalformedURLException mue1) {
300 throw new SoneException(Type.INVALID_URI);
306 * Loads the Sone from the given request URI. The fetching of the data is
307 * performed in a new thread so this method returns immediately.
310 * The request URI to load the Sone from
312 public void loadSone(final String requestUri) {
313 new Thread(new Runnable() {
316 @SuppressWarnings("synthetic-access")
319 FreenetURI realRequestUri = new FreenetURI(requestUri).setMetaString(new String[] { "sone.xml" });
320 FetchResult fetchResult = freenetInterface.fetchUri(realRequestUri);
321 Sone parsedSone = soneDownloader.parseSone(null, fetchResult, realRequestUri);
322 if (parsedSone != null) {
325 } catch (MalformedURLException mue1) {
326 logger.log(Level.INFO, "Could not create URI from “" + requestUri + "”.", mue1);
329 }, "Sone Downloader").start();
333 * Deletes the given Sone from this plugin instance.
338 public void deleteSone(Sone sone) {
339 SoneInserter soneInserter = soneInserters.remove(sone);
341 localSones.remove(sone);
345 * Returns the post with the given ID. If no post exists yet with the given
346 * ID, a new post is returned.
352 public Post getPost(String postId) {
353 if (!postCache.containsKey(postId)) {
354 postCache.put(postId, new Post(postId));
356 return postCache.get(postId);
360 * Returns the reply with the given ID. If no reply exists yet with the
361 * given ID, a new reply is returned.
364 * The ID of the reply
367 public Reply getReply(String replyId) {
368 if (!replyCache.containsKey(replyId)) {
369 replyCache.put(replyId, new Reply(replyId));
371 return replyCache.get(replyId);
375 * Gets all replies to the given post, sorted by date, oldest first.
378 * The post the replies refer to
379 * @return The sorted list of replies for the post
381 public List<Reply> getReplies(Post post) {
382 List<Reply> replies = new ArrayList<Reply>();
383 for (Reply reply : replyCache.values()) {
384 if (reply.getPost().equals(post)) {
388 Collections.sort(replies, new Comparator<Reply>() {
394 public int compare(Reply leftReply, Reply rightReply) {
395 return (int) Math.max(Integer.MIN_VALUE, Math.min(Integer.MAX_VALUE, leftReply.getTime() - rightReply.getTime()));
409 protected void serviceStart() {
417 protected void serviceStop() {
418 soneDownloader.stop();
419 /* stop all Sone inserters. */
420 for (SoneInserter soneInserter : soneInserters.values()) {
431 * Loads the configuration.
433 private void loadConfiguration() {
434 logger.entering(Core.class.getName(), "loadConfiguration()");
436 /* parse local Sones. */
437 logger.log(Level.INFO, "Loading Sones…");
440 String sonePrefix = "Sone/Sone." + soneId++;
441 String id = configuration.getStringValue(sonePrefix + "/ID").getValue(null);
445 String name = configuration.getStringValue(sonePrefix + "/Name").getValue(null);
446 String insertUri = configuration.getStringValue(sonePrefix + "/InsertURI").getValue(null);
447 String requestUri = configuration.getStringValue(sonePrefix + "/RequestURI").getValue(null);
448 long modificationCounter = configuration.getLongValue(sonePrefix + "/ModificationCounter").getValue((long) 0);
449 String firstName = configuration.getStringValue(sonePrefix + "/Profile/FirstName").getValue(null);
450 String middleName = configuration.getStringValue(sonePrefix + "/Profile/MiddleName").getValue(null);
451 String lastName = configuration.getStringValue(sonePrefix + "/Profile/LastName").getValue(null);
453 Profile profile = new Profile();
454 profile.setFirstName(firstName);
455 profile.setMiddleName(middleName);
456 profile.setLastName(lastName);
457 Sone sone = getSone(id).setName(name).setRequestUri(new FreenetURI(requestUri)).setInsertUri(new FreenetURI(insertUri));
458 sone.setProfile(profile);
461 String postPrefix = sonePrefix + "/Post." + postId++;
462 id = configuration.getStringValue(postPrefix + "/ID").getValue(null);
466 long time = configuration.getLongValue(postPrefix + "/Time").getValue(null);
467 String text = configuration.getStringValue(postPrefix + "/Text").getValue(null);
468 Post post = getPost(id).setSone(sone).setTime(time).setText(text);
471 int replyCounter = 0;
473 String replyPrefix = sonePrefix + "/Reply." + replyCounter++;
474 String replyId = configuration.getStringValue(replyPrefix + "/ID").getValue(null);
475 if (replyId == null) {
478 Post replyPost = getPost(configuration.getStringValue(replyPrefix + "/Post").getValue(null));
479 long replyTime = configuration.getLongValue(replyPrefix + "/Time").getValue(null);
480 String replyText = configuration.getStringValue(replyPrefix + "/Text").getValue(null);
481 Reply reply = getReply(replyId).setSone(sone).setPost(replyPost).setTime(replyTime).setText(replyText);
482 sone.addReply(reply);
486 int friendCounter = 0;
488 String friendPrefix = sonePrefix + "/Friend." + friendCounter++;
489 String friendId = configuration.getStringValue(friendPrefix + "/ID").getValue(null);
490 if (friendId == null) {
493 Sone friendSone = getSone(friendId);
494 String friendKey = configuration.getStringValue(friendPrefix + "/Key").getValue(null);
495 String friendName = configuration.getStringValue(friendPrefix + "/Name").getValue(null);
496 friendSone.setRequestUri(new FreenetURI(friendKey)).setName(friendName);
498 sone.addFriend(friendSone);
501 sone.setModificationCounter(modificationCounter);
503 } catch (MalformedURLException mue1) {
504 logger.log(Level.WARNING, "Could not create Sone from requestUri (“" + requestUri + "”) and insertUri (“" + insertUri + "”)!", mue1);
507 logger.log(Level.INFO, "Loaded %d Sones.", getSones().size());
509 logger.exiting(Core.class.getName(), "loadConfiguration()");
513 * Saves the configuraiton.
515 private void saveConfiguration() {
516 Set<Sone> sones = getSones();
517 logger.log(Level.INFO, "Storing %d Sones…", sones.size());
519 /* store all Sones. */
521 for (Sone sone : localSones) {
522 String sonePrefix = "Sone/Sone." + soneId++;
523 configuration.getStringValue(sonePrefix + "/ID").setValue(sone.getId());
524 configuration.getStringValue(sonePrefix + "/Name").setValue(sone.getName());
525 configuration.getStringValue(sonePrefix + "/RequestURI").setValue(sone.getRequestUri().toString());
526 configuration.getStringValue(sonePrefix + "/InsertURI").setValue(sone.getInsertUri().toString());
527 configuration.getLongValue(sonePrefix + "/ModificationCounter").setValue(sone.getModificationCounter());
528 Profile profile = sone.getProfile();
529 configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
530 configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
531 configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
533 for (Post post : sone.getPosts()) {
534 String postPrefix = sonePrefix + "/Post." + postId++;
535 configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
536 configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
537 configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
539 /* write null ID as terminator. */
540 configuration.getStringValue(sonePrefix + "/Post." + postId + "/ID").setValue(null);
543 for (Reply reply : sone.getReplies()) {
544 String replyPrefix = sonePrefix + "/Reply." + replyId++;
545 configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
546 configuration.getStringValue(replyPrefix + "/Post").setValue(reply.getPost().getId());
547 configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
548 configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
550 /* write null ID as terminator. */
551 configuration.getStringValue(sonePrefix + "/Reply." + replyId + "/ID").setValue(null);
554 for (Sone friend : sone.getFriends()) {
555 String friendPrefix = sonePrefix + "/Friend." + friendId++;
556 configuration.getStringValue(friendPrefix + "/ID").setValue(friend.getId());
557 configuration.getStringValue(friendPrefix + "/Key").setValue(friend.getRequestUri().toString());
558 configuration.getStringValue(friendPrefix + "/Name").setValue(friend.getName());
560 /* write null ID as terminator. */
561 configuration.getStringValue(sonePrefix + "/Friend." + friendId + "/ID").setValue(null);
564 /* write null ID as terminator. */
565 configuration.getStringValue("Sone/Sone." + soneId + "/ID").setValue(null);
567 } catch (ConfigurationException ce1) {
568 logger.log(Level.WARNING, "Could not store configuration!", ce1);