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.Collections;
23 import java.util.Comparator;
24 import java.util.HashMap;
25 import java.util.HashSet;
26 import java.util.List;
29 import java.util.UUID;
30 import java.util.logging.Level;
31 import java.util.logging.Logger;
33 import net.pterodactylus.sone.core.SoneException.Type;
34 import net.pterodactylus.sone.data.Post;
35 import net.pterodactylus.sone.data.Profile;
36 import net.pterodactylus.sone.data.Reply;
37 import net.pterodactylus.sone.data.Sone;
38 import net.pterodactylus.util.config.Configuration;
39 import net.pterodactylus.util.config.ConfigurationException;
40 import net.pterodactylus.util.logging.Logging;
41 import net.pterodactylus.util.service.AbstractService;
42 import freenet.keys.FreenetURI;
47 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
49 public class Core extends AbstractService {
52 private static final Logger logger = Logging.getLogger(Core.class);
54 /** The configuration. */
55 private Configuration configuration;
57 /** Interface to freenet. */
58 private FreenetInterface freenetInterface;
60 /** The Sone downloader. */
61 private SoneDownloader soneDownloader;
63 /** The local Sones. */
64 private final Set<Sone> localSones = new HashSet<Sone>();
66 /** Sone inserters. */
67 private final Map<Sone, SoneInserter> soneInserters = new HashMap<Sone, SoneInserter>();
69 /* various caches follow here. */
71 /** Cache for all known Sones. */
72 private final Map<String, Sone> soneCache = new HashMap<String, Sone>();
74 /** Cache for all known posts. */
75 private final Map<String, Post> postCache = new HashMap<String, Post>();
77 /** Cache for all known replies. */
78 private final Map<String, Reply> replyCache = new HashMap<String, Reply>();
92 * Sets the configuration of the core.
94 * @param configuration
95 * The configuration of the core
96 * @return This core (for method chaining)
98 public Core configuration(Configuration configuration) {
99 this.configuration = configuration;
104 * Sets the Freenet interface to use.
106 * @param freenetInterface
107 * The Freenet interface to use
108 * @return This core (for method chaining)
110 public Core freenetInterface(FreenetInterface freenetInterface) {
111 this.freenetInterface = freenetInterface;
112 soneDownloader = new SoneDownloader(this, freenetInterface);
113 soneDownloader.start();
118 * Returns the local Sones.
120 * @return The local Sones
122 public Set<Sone> getSones() {
123 return Collections.unmodifiableSet(localSones);
127 * Returns the Sone with the given ID, or an empty Sone that has been
128 * initialized with the given ID.
134 public Sone getSone(String soneId) {
135 if (!soneCache.containsKey(soneId)) {
136 Sone sone = new Sone(soneId);
137 soneCache.put(soneId, sone);
139 return soneCache.get(soneId);
143 * Creates a new post.
146 * The sone that creates the post
148 * The text of the post
149 * @return The created post
151 public Post createPost(Sone sone, String text) {
152 return createPost(sone, System.currentTimeMillis(), text);
156 * Creates a new post.
159 * The Sone that creates the post
161 * The time of the post
163 * The text of the post
164 * @return The created post
166 public Post createPost(Sone sone, long time, String text) {
167 Post post = getPost(UUID.randomUUID().toString()).setSone(sone).setTime(time).setText(text);
176 * The Sone that posts the reply
178 * The post the reply refers to
180 * The text of the reply
181 * @return The created reply
183 public Reply createReply(Sone sone, Post post, String text) {
184 return createReply(sone, post, System.currentTimeMillis(), text);
191 * The Sone that posts the reply
193 * The post the reply refers to
195 * The time of the post
197 * The text of the reply
198 * @return The created reply
200 public Reply createReply(Sone sone, Post post, long time, String text) {
201 Reply reply = getReply(UUID.randomUUID().toString()).setSone(sone).setPost(post).setTime(time).setText(text);
202 sone.addReply(reply);
211 * Adds the given Sone.
216 public void addLocalSone(Sone sone) {
217 if (localSones.add(sone)) {
218 SoneInserter soneInserter = new SoneInserter(freenetInterface, sone);
219 soneInserter.start();
220 soneDownloader.addSone(sone);
221 soneInserters.put(sone, soneInserter);
226 * Creates a new Sone at a random location.
229 * The name of the Sone
230 * @return The created Sone
231 * @throws SoneException
232 * if a Sone error occurs
234 public Sone createSone(String name) throws SoneException {
235 return createSone(name, null, null);
239 * Creates a new Sone at the given location. If one of {@code requestUri} or
240 * {@code insertUrI} is {@code null}, the Sone is created at a random
244 * The name of the Sone
246 * The request URI of the Sone, or {@link NullPointerException}
247 * to create a Sone at a random location
249 * The insert URI of the Sone, or {@code null} to create a Sone
250 * at a random location
251 * @return The created Sone
252 * @throws SoneException
253 * if a Sone error occurs
255 public Sone createSone(String name, String requestUri, String insertUri) throws SoneException {
256 if ((name == null) || (name.trim().length() == 0)) {
257 throw new SoneException(Type.INVALID_SONE_NAME);
259 String finalRequestUri;
260 String finalInsertUri;
261 if ((requestUri == null) || (insertUri == null)) {
262 String[] keyPair = freenetInterface.generateKeyPair();
263 finalRequestUri = keyPair[0];
264 finalInsertUri = keyPair[1];
266 finalRequestUri = requestUri;
267 finalInsertUri = insertUri;
271 logger.log(Level.FINEST, "Creating new Sone “%s” at %s (%s)…", new Object[] { name, finalRequestUri, finalInsertUri });
272 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));
273 sone.setProfile(new Profile());
274 /* set modification counter to 1 so it is inserted immediately. */
275 sone.setModificationCounter(1);
277 } catch (MalformedURLException mue1) {
278 throw new SoneException(Type.INVALID_URI);
284 * Deletes the given Sone from this plugin instance.
289 public void deleteSone(Sone sone) {
290 SoneInserter soneInserter = soneInserters.remove(sone);
292 localSones.remove(sone);
296 * Returns the post with the given ID. If no post exists yet with the given
297 * ID, a new post is returned.
303 public Post getPost(String postId) {
304 if (!postCache.containsKey(postId)) {
305 postCache.put(postId, new Post(postId));
307 return postCache.get(postId);
311 * Returns the reply with the given ID. If no reply exists yet with the
312 * given ID, a new reply is returned.
315 * The ID of the reply
318 public Reply getReply(String replyId) {
319 if (!replyCache.containsKey(replyId)) {
320 replyCache.put(replyId, new Reply(replyId));
322 return replyCache.get(replyId);
326 * Gets all replies to the given post, sorted by date, oldest first.
329 * The post the replies refer to
330 * @return The sorted list of replies for the post
332 public List<Reply> getReplies(Post post) {
333 List<Reply> replies = new ArrayList<Reply>();
334 for (Reply reply : replyCache.values()) {
335 if (reply.getPost().equals(post)) {
339 Collections.sort(replies, new Comparator<Reply>() {
345 public int compare(Reply leftReply, Reply rightReply) {
346 return (int) Math.max(Integer.MIN_VALUE, Math.min(Integer.MAX_VALUE, leftReply.getTime() - rightReply.getTime()));
360 protected void serviceStart() {
368 protected void serviceStop() {
369 soneDownloader.stop();
370 /* stop all Sone inserters. */
371 for (SoneInserter soneInserter : soneInserters.values()) {
382 * Loads the configuration.
384 private void loadConfiguration() {
385 logger.entering(Core.class.getName(), "loadConfiguration()");
387 /* parse local Sones. */
388 logger.log(Level.INFO, "Loading Sones…");
391 String sonePrefix = "Sone/Sone." + soneId++;
392 String id = configuration.getStringValue(sonePrefix + "/ID").getValue(null);
396 String name = configuration.getStringValue(sonePrefix + "/Name").getValue(null);
397 String insertUri = configuration.getStringValue(sonePrefix + "/InsertURI").getValue(null);
398 String requestUri = configuration.getStringValue(sonePrefix + "/RequestURI").getValue(null);
399 long modificationCounter = configuration.getLongValue(sonePrefix + "/ModificationCounter").getValue((long) 0);
400 String firstName = configuration.getStringValue(sonePrefix + "/Profile/FirstName").getValue(null);
401 String middleName = configuration.getStringValue(sonePrefix + "/Profile/MiddleName").getValue(null);
402 String lastName = configuration.getStringValue(sonePrefix + "/Profile/LastName").getValue(null);
404 Profile profile = new Profile();
405 profile.setFirstName(firstName);
406 profile.setMiddleName(middleName);
407 profile.setLastName(lastName);
408 Sone sone = getSone(id).setName(name).setRequestUri(new FreenetURI(requestUri)).setInsertUri(new FreenetURI(insertUri));
409 sone.setProfile(profile);
412 String postPrefix = sonePrefix + "/Post." + postId++;
413 id = configuration.getStringValue(postPrefix + "/ID").getValue(null);
417 long time = configuration.getLongValue(postPrefix + "/Time").getValue(null);
418 String text = configuration.getStringValue(postPrefix + "/Text").getValue(null);
419 Post post = getPost(id).setSone(sone).setTime(time).setText(text);
422 int replyCounter = 0;
424 String replyPrefix = sonePrefix + "/Reply." + replyCounter++;
425 String replyId = configuration.getStringValue(replyPrefix + "/ID").getValue(null);
426 if (replyId == null) {
429 Post replyPost = getPost(configuration.getStringValue(replyPrefix + "/Post").getValue(null));
430 long replyTime = configuration.getLongValue(replyPrefix + "/Time").getValue(null);
431 String replyText = configuration.getStringValue(replyPrefix + "/Text").getValue(null);
432 Reply reply = getReply(replyId).setSone(sone).setPost(replyPost).setTime(replyTime).setText(replyText);
433 sone.addReply(reply);
437 int friendCounter = 0;
439 String friendPrefix = sonePrefix + "/Friend." + friendCounter++;
440 String friendId = configuration.getStringValue(friendPrefix + "/ID").getValue(null);
441 if (friendId == null) {
444 Sone friendSone = getSone(friendId);
445 String friendKey = configuration.getStringValue(friendPrefix + "/Key").getValue(null);
446 String friendName = configuration.getStringValue(friendPrefix + "/Name").getValue(null);
447 friendSone.setRequestUri(new FreenetURI(friendKey)).setName(friendName);
448 soneDownloader.addSone(friendSone);
449 sone.addFriend(friendSone);
452 sone.setModificationCounter(modificationCounter);
454 } catch (MalformedURLException mue1) {
455 logger.log(Level.WARNING, "Could not create Sone from requestUri (“" + requestUri + "”) and insertUri (“" + insertUri + "”)!", mue1);
458 logger.log(Level.INFO, "Loaded %d Sones.", getSones().size());
460 logger.exiting(Core.class.getName(), "loadConfiguration()");
464 * Saves the configuraiton.
466 private void saveConfiguration() {
467 Set<Sone> sones = getSones();
468 logger.log(Level.INFO, "Storing %d Sones…", sones.size());
470 /* store all Sones. */
472 for (Sone sone : localSones) {
473 String sonePrefix = "Sone/Sone." + soneId++;
474 configuration.getStringValue(sonePrefix + "/ID").setValue(sone.getId());
475 configuration.getStringValue(sonePrefix + "/Name").setValue(sone.getName());
476 configuration.getStringValue(sonePrefix + "/RequestURI").setValue(sone.getRequestUri().toString());
477 configuration.getStringValue(sonePrefix + "/InsertURI").setValue(sone.getInsertUri().toString());
478 configuration.getLongValue(sonePrefix + "/ModificationCounter").setValue(sone.getModificationCounter());
479 Profile profile = sone.getProfile();
480 configuration.getStringValue(sonePrefix + "/Profile/FirstName").setValue(profile.getFirstName());
481 configuration.getStringValue(sonePrefix + "/Profile/MiddleName").setValue(profile.getMiddleName());
482 configuration.getStringValue(sonePrefix + "/Profile/LastName").setValue(profile.getLastName());
484 for (Post post : sone.getPosts()) {
485 String postPrefix = sonePrefix + "/Post." + postId++;
486 configuration.getStringValue(postPrefix + "/ID").setValue(post.getId());
487 configuration.getLongValue(postPrefix + "/Time").setValue(post.getTime());
488 configuration.getStringValue(postPrefix + "/Text").setValue(post.getText());
490 /* write null ID as terminator. */
491 configuration.getStringValue(sonePrefix + "/Post." + postId + "/ID").setValue(null);
494 for (Reply reply : sone.getReplies()) {
495 String replyPrefix = sonePrefix + "/Reply." + replyId++;
496 configuration.getStringValue(replyPrefix + "/ID").setValue(reply.getId());
497 configuration.getStringValue(replyPrefix + "/Post").setValue(reply.getPost().getId());
498 configuration.getLongValue(replyPrefix + "/Time").setValue(reply.getTime());
499 configuration.getStringValue(replyPrefix + "/Text").setValue(reply.getText());
501 /* write null ID as terminator. */
502 configuration.getStringValue(sonePrefix + "/Reply." + replyId + "/ID").setValue(null);
505 for (Sone friend : sone.getFriends()) {
506 String friendPrefix = sonePrefix + "/Friend." + friendId++;
507 configuration.getStringValue(friendPrefix + "/ID").setValue(friend.getId());
508 configuration.getStringValue(friendPrefix + "/Key").setValue(friend.getRequestUri().toString());
509 configuration.getStringValue(friendPrefix + "/Name").setValue(friend.getName());
511 /* write null ID as terminator. */
512 configuration.getStringValue(sonePrefix + "/Friend." + friendId + "/ID").setValue(null);
515 /* write null ID as terminator. */
516 configuration.getStringValue("Sone/Sone." + soneId + "/ID").setValue(null);
518 } catch (ConfigurationException ce1) {
519 logger.log(Level.WARNING, "Could not store configuration!", ce1);