X-Git-Url: https://git.pterodactylus.net/?a=blobdiff_plain;f=src%2Fmain%2Fjava%2Fnet%2Fpterodactylus%2Fsone%2Fcore%2FSoneInserter.java;h=04254d491c1ab17b4c741ef32696ce3369f6a321;hb=7fb49938b9198110c34bcc600c545bfa91acf6f2;hp=15e054f957413db5725a818b893f1977b5a746df;hpb=a23c4f218c3adf236d89d5927cae37d6e6e4feda;p=Sone.git
diff --git a/src/main/java/net/pterodactylus/sone/core/SoneInserter.java b/src/main/java/net/pterodactylus/sone/core/SoneInserter.java
index 15e054f..04254d4 100644
--- a/src/main/java/net/pterodactylus/sone/core/SoneInserter.java
+++ b/src/main/java/net/pterodactylus/sone/core/SoneInserter.java
@@ -1,5 +1,5 @@
/*
- * FreenetSone - SoneInserter.java - Copyright © 2010 David Roden
+ * Sone - SoneInserter.java - Copyright © 2010â2013 David Roden
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
@@ -17,20 +17,29 @@
package net.pterodactylus.sone.core;
+import static com.google.common.base.Preconditions.checkArgument;
+import static net.pterodactylus.sone.data.Album.NOT_EMPTY;
+import static net.pterodactylus.sone.data.Sone.TO_FREENET_URI;
+import static net.pterodactylus.sone.data.Sone.TO_INSERT_URI;
+
import java.io.InputStreamReader;
import java.io.StringWriter;
import java.nio.charset.Charset;
-import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
+import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
-import net.pterodactylus.sone.core.Core.SoneStatus;
+import net.pterodactylus.sone.core.event.SoneInsertAbortedEvent;
+import net.pterodactylus.sone.core.event.SoneInsertedEvent;
+import net.pterodactylus.sone.core.event.SoneInsertingEvent;
+import net.pterodactylus.sone.data.Album;
import net.pterodactylus.sone.data.Post;
import net.pterodactylus.sone.data.Reply;
import net.pterodactylus.sone.data.Sone;
+import net.pterodactylus.sone.data.Sone.SoneStatus;
import net.pterodactylus.sone.freenet.StringBucket;
import net.pterodactylus.sone.main.SonePlugin;
import net.pterodactylus.util.io.Closer;
@@ -44,8 +53,14 @@ import net.pterodactylus.util.template.TemplateContextFactory;
import net.pterodactylus.util.template.TemplateException;
import net.pterodactylus.util.template.TemplateParser;
import net.pterodactylus.util.template.XmlFilter;
+
import freenet.client.async.ManifestElement;
import freenet.keys.FreenetURI;
+import freenet.support.api.Bucket;
+
+import com.google.common.collect.FluentIterable;
+import com.google.common.collect.Ordering;
+import com.google.common.eventbus.EventBus;
/**
* A Sone inserter is responsible for inserting a Sone if it has changed.
@@ -75,11 +90,14 @@ public class SoneInserter extends AbstractService {
/** The core. */
private final Core core;
+ /** The event bus. */
+ private final EventBus eventBus;
+
/** The Freenet interface. */
private final FreenetInterface freenetInterface;
/** The Sone to insert. */
- private final Sone sone;
+ private volatile Sone sone;
/** Whether a modification has been detected. */
private volatile boolean modified = false;
@@ -92,14 +110,17 @@ public class SoneInserter extends AbstractService {
*
* @param core
* The core
+ * @param eventBus
+ * The event bus
* @param freenetInterface
* The freenet interface
* @param sone
* The Sone to insert
*/
- public SoneInserter(Core core, FreenetInterface freenetInterface, Sone sone) {
+ public SoneInserter(Core core, EventBus eventBus, FreenetInterface freenetInterface, Sone sone) {
super("Sone Inserter for â" + sone.getName() + "â", false);
this.core = core;
+ this.eventBus = eventBus;
this.freenetInterface = freenetInterface;
this.sone = sone;
}
@@ -109,8 +130,21 @@ public class SoneInserter extends AbstractService {
//
/**
- * Changes the insertion delay, i.e. the time the Sone inserter waits after
- * it has noticed a Sone modification before it starts the insert.
+ * Sets the Sone to insert.
+ *
+ * @param sone
+ * The Sone to insert
+ * @return This Sone inserter
+ */
+ public SoneInserter setSone(Sone sone) {
+ checkArgument((this.sone == null) || sone.equals(this.sone), "Sone to insert can not be set to a different Sone");
+ this.sone = sone;
+ return this;
+ }
+
+ /**
+ * Changes the insertion delay, i.e. the time the Sone inserter waits after it
+ * has noticed a Sone modification before it starts the insert.
*
* @param insertionDelay
* The insertion delay (in seconds)
@@ -153,92 +187,99 @@ public class SoneInserter extends AbstractService {
// SERVICE METHODS
//
- /**
- * {@inheritDoc}
- */
@Override
protected void serviceRun() {
long lastModificationTime = 0;
+ String lastInsertedFingerprint = lastInsertFingerprint;
String lastFingerprint = "";
- while (!shouldStop()) { try {
- /* check every seconds. */
- sleep(1000);
+ Sone sone;
+ while (!shouldStop()) {
+ try {
+ /* check every seconds. */
+ sleep(1000);
- /* donât insert locked Sones. */
- if (core.isLocked(sone)) {
- /* trigger redetection when the Sone is unlocked. */
- synchronized (sone) {
- modified = !sone.getFingerprint().equals(lastInsertFingerprint);
+ /* donât insert locked Sones. */
+ sone = this.sone;
+ if (core.isLocked(sone)) {
+ /* trigger redetection when the Sone is unlocked. */
+ synchronized (sone) {
+ modified = !sone.getFingerprint().equals(lastInsertedFingerprint);
+ }
+ lastFingerprint = "";
+ lastModificationTime = 0;
+ continue;
}
- lastFingerprint = "";
- lastModificationTime = 0;
- continue;
- }
- InsertInformation insertInformation = null;
- synchronized (sone) {
- String fingerprint = sone.getFingerprint();
- if (!fingerprint.equals(lastFingerprint)) {
- if (fingerprint.equals(lastInsertFingerprint)) {
- modified = false;
- lastModificationTime = 0;
- logger.log(Level.FINE, "Sone %s has been reverted to last insert state.", sone);
- } else {
- lastModificationTime = System.currentTimeMillis();
- modified = true;
- logger.log(Level.FINE, "Sone %s has been modified, waiting %d seconds before inserting.", new Object[] { sone.getName(), insertionDelay });
+ InsertInformation insertInformation = null;
+ synchronized (sone) {
+ String fingerprint = sone.getFingerprint();
+ if (!fingerprint.equals(lastFingerprint)) {
+ if (fingerprint.equals(lastInsertedFingerprint)) {
+ modified = false;
+ lastModificationTime = 0;
+ logger.log(Level.FINE, String.format("Sone %s has been reverted to last insert state.", sone));
+ } else {
+ lastModificationTime = System.currentTimeMillis();
+ modified = true;
+ logger.log(Level.FINE, String.format("Sone %s has been modified, waiting %d seconds before inserting.", sone.getName(), insertionDelay));
+ }
+ lastFingerprint = fingerprint;
+ }
+ if (modified && (lastModificationTime > 0) && ((System.currentTimeMillis() - lastModificationTime) > (insertionDelay * 1000))) {
+ lastInsertedFingerprint = fingerprint;
+ insertInformation = new InsertInformation(sone);
}
- lastFingerprint = fingerprint;
- }
- if (modified && (lastModificationTime > 0) && ((System.currentTimeMillis() - lastModificationTime) > (insertionDelay * 1000))) {
- lastInsertFingerprint = fingerprint;
- insertInformation = new InsertInformation(sone);
}
- }
- if (insertInformation != null) {
- logger.log(Level.INFO, "Inserting Sone â%sââ¦", new Object[] { sone.getName() });
-
- boolean success = false;
- try {
- core.setSoneStatus(sone, SoneStatus.inserting);
- long insertTime = System.currentTimeMillis();
- insertInformation.setTime(insertTime);
- FreenetURI finalUri = freenetInterface.insertDirectory(insertInformation.getInsertUri(), insertInformation.generateManifestEntries(), "index.html");
- /* at this point we might already be stopped. */
- if (shouldStop()) {
- /* if so, bail out, donât change anything. */
- break;
+ if (insertInformation != null) {
+ logger.log(Level.INFO, String.format("Inserting Sone â%sââ¦", sone.getName()));
+
+ boolean success = false;
+ try {
+ sone.setStatus(SoneStatus.inserting);
+ long insertTime = System.currentTimeMillis();
+ insertInformation.setTime(insertTime);
+ eventBus.post(new SoneInsertingEvent(sone));
+ FreenetURI finalUri = freenetInterface.insertDirectory(insertInformation.getInsertUri(), insertInformation.generateManifestEntries(), "index.html");
+ eventBus.post(new SoneInsertedEvent(sone, System.currentTimeMillis() - insertTime));
+ /* at this point we might already be stopped. */
+ if (shouldStop()) {
+ /* if so, bail out, donât change anything. */
+ break;
+ }
+ sone.setTime(insertTime);
+ sone.modify().setLatestEdition(finalUri.getEdition()).update();
+ core.touchConfiguration();
+ success = true;
+ logger.log(Level.INFO, String.format("Inserted Sone â%sâ at %s.", sone.getName(), finalUri));
+ } catch (SoneException se1) {
+ eventBus.post(new SoneInsertAbortedEvent(sone, se1));
+ logger.log(Level.WARNING, String.format("Could not insert Sone â%sâ!", sone.getName()), se1);
+ } finally {
+ insertInformation.freeBuckets();
+ sone.setStatus(SoneStatus.idle);
}
- sone.setTime(insertTime);
- sone.setLatestEdition(finalUri.getEdition());
- core.saveSone(sone);
- success = true;
- logger.log(Level.INFO, "Inserted Sone â%sâ at %s.", new Object[] { sone.getName(), finalUri });
- } catch (SoneException se1) {
- logger.log(Level.WARNING, "Could not insert Sone â" + sone.getName() + "â!", se1);
- } finally {
- core.setSoneStatus(sone, SoneStatus.idle);
- }
- /*
- * reset modification counter if Sone has not been modified
- * while it was inserted.
- */
- if (success) {
- synchronized (sone) {
- if (lastInsertFingerprint.equals(sone.getFingerprint())) {
- logger.log(Level.FINE, "Sone â%sâ was not modified further, resetting counterâ¦", new Object[] { sone });
- core.saveSone(sone);
- lastModificationTime = 0;
- modified = false;
+ /*
+ * reset modification counter if Sone has not been modified
+ * while it was inserted.
+ */
+ if (success) {
+ synchronized (sone) {
+ if (lastInsertedFingerprint.equals(sone.getFingerprint())) {
+ logger.log(Level.FINE, String.format("Sone â%sâ was not modified further, resetting counterâ¦", sone));
+ lastModificationTime = 0;
+ lastInsertFingerprint = lastInsertedFingerprint;
+ core.touchConfiguration();
+ modified = false;
+ }
}
}
}
+ } catch (Throwable t1) {
+ logger.log(Level.SEVERE, "SoneInserter threw an Exception!", t1);
}
- } catch (Throwable t1) {
- logger.log(Level.SEVERE, "SoneInserter threw an Exception!", t1);
- }}
+ }
}
/**
@@ -248,10 +289,11 @@ public class SoneInserter extends AbstractService {
*
* @author David âBombeâ Roden
*/
- private static class InsertInformation {
+ private class InsertInformation {
/** All properties of the Sone, copied for thread safety. */
private final Map soneProperties = new HashMap();
+ private final Set buckets = new HashSet();
/**
* Creates a new insert information container.
@@ -263,13 +305,14 @@ public class SoneInserter extends AbstractService {
soneProperties.put("id", sone.getId());
soneProperties.put("name", sone.getName());
soneProperties.put("time", sone.getTime());
- soneProperties.put("requestUri", sone.getRequestUri());
- soneProperties.put("insertUri", sone.getInsertUri());
+ soneProperties.put("requestUri", TO_FREENET_URI.apply(sone));
+ soneProperties.put("insertUri", TO_INSERT_URI.apply(sone));
soneProperties.put("profile", sone.getProfile());
- soneProperties.put("posts", new ArrayList(sone.getPosts()));
- soneProperties.put("replies", new HashSet(sone.getReplies()));
+ soneProperties.put("posts", Ordering.from(Post.TIME_COMPARATOR).sortedCopy(sone.getPosts()));
+ soneProperties.put("replies", Ordering.from(Reply.TIME_COMPARATOR).reverse().sortedCopy(sone.getReplies()));
soneProperties.put("likedPostIds", new HashSet(sone.getLikedPostIds()));
soneProperties.put("likedReplyIds", new HashSet(sone.getLikedReplyIds()));
+ soneProperties.put("albums", FluentIterable.from(sone.getRootAlbum().getAlbums()).transformAndConcat(Album.FLATTENER).filter(NOT_EMPTY).toList());
}
//
@@ -316,6 +359,12 @@ public class SoneInserter extends AbstractService {
return manifestEntries;
}
+ public void freeBuckets() {
+ for (Bucket bucket : buckets) {
+ bucket.free();
+ }
+ }
+
//
// PRIVATE METHODS
//
@@ -339,14 +388,16 @@ public class SoneInserter extends AbstractService {
templateInputStreamReader = new InputStreamReader(getClass().getResourceAsStream(templateName), utf8Charset);
template = TemplateParser.parse(templateInputStreamReader);
} catch (TemplateException te1) {
- logger.log(Level.SEVERE, "Could not parse template â" + templateName + "â!", te1);
+ logger.log(Level.SEVERE, String.format("Could not parse template â%sâ!", templateName), te1);
return null;
} finally {
Closer.close(templateInputStreamReader);
}
TemplateContext templateContext = templateContextFactory.createTemplateContext();
+ templateContext.set("core", core);
templateContext.set("currentSone", soneProperties);
+ templateContext.set("currentEdition", core.getUpdateChecker().getLatestEdition());
templateContext.set("version", SonePlugin.VERSION);
StringWriter writer = new StringWriter();
StringBucket bucket = null;
@@ -355,13 +406,10 @@ public class SoneInserter extends AbstractService {
bucket = new StringBucket(writer.toString(), utf8Charset);
return new ManifestElement(name, bucket, contentType, bucket.size());
} catch (TemplateException te1) {
- logger.log(Level.SEVERE, "Could not render template â" + templateName + "â!", te1);
+ logger.log(Level.SEVERE, String.format("Could not render template â%sâ!", templateName), te1);
return null;
} finally {
Closer.close(writer);
- if (bucket != null) {
- bucket.free();
- }
}
}