Permalink
Browse files

Merge pull request #39 from tomamic/master

keep log of dht lookups
  • Loading branch information...
2 parents 2e0f697 + 6f3ef7b commit 392140553d6c75b20e53bac2c43f62879249e04e @rik0 committed Mar 6, 2013
@@ -1,31 +1,31 @@
package net.blogracy;
-import net.blogracy.model.users.User;
+import java.util.List;
+
+import net.blogracy.config.Configurations;
+import net.blogracy.controller.ActivitiesController;
import net.blogracy.controller.ChatController;
import net.blogracy.controller.DistributedHashTable;
import net.blogracy.controller.FileSharing;
-import net.blogracy.config.Configurations;
-import java.util.List;
+import net.blogracy.model.users.User;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.webapp.WebAppContext;
-public class WebServer
-{
- public static void main(String[] args) throws Exception
- {
- String webDir = WebServer.class.getClassLoader().getResource("webapp").toExternalForm();
-
- Server server = new Server(8080);
-
+public class WebServer {
+
+ public static void main(String[] args) throws Exception {
+
+ String webDir = WebServer.class.getClassLoader().getResource("webapp")
+ .toExternalForm();
WebAppContext context = new WebAppContext();
context.setResourceBase(webDir);
- //context.setDescriptor(webDir + "/WEB-INF/web.xml");
- context.setContextPath("/");
- context.setParentLoaderPriority(true);
-
+ // context.setDescriptor(webDir + "/WEB-INF/web.xml");
+ // context.setContextPath("/");
+ // context.setParentLoaderPriority(true);
+
+ Server server = new Server(8080);
server.setHandler(context);
-
server.start();
// server.join();
@@ -34,20 +34,23 @@ public static void main(String[] args) throws Exception
String hash = friend.getHash().toString();
ChatController.getSingleton().joinChannel(hash);
}
- String id = Configurations.getUserConfig().getUser().getHash().toString();
+ String id = Configurations.getUserConfig().getUser().getHash()
+ .toString();
ChatController.getSingleton().joinChannel(id);
-
+
int TOTAL_WAIT = 5 * 60 * 1000; // 5 minutes
-
+
while (true) {
- FileSharing sharing = FileSharing.getSingleton();
- sharing.addFeedEntry(id, "" + new java.util.Date(), null);
-
+ ActivitiesController activities = ActivitiesController
+ .getSingleton();
+ activities.addFeedEntry(id, "" + new java.util.Date(), null);
+
// List<User> friends = Configurations.getUserConfig().getFriends();
int wait = TOTAL_WAIT / friends.size();
for (User friend : friends) {
- DistributedHashTable.getSingleton().lookup(friend.getHash().toString());
- FileSharing.getFeed(friend.getHash().toString());
+ DistributedHashTable.getSingleton().lookup(
+ friend.getHash().toString());
+ activities.getFeed(friend.getHash().toString());
Thread.currentThread().sleep(wait);
}
}
@@ -23,8 +23,8 @@
package net.blogracy.config;
import java.io.File;
-import java.io.IOException;
import java.io.FileInputStream;
+import java.io.IOException;
import java.io.InputStream;
import java.security.Key;
import java.security.KeyPair;
@@ -62,17 +62,7 @@
private static final String BLOGRACY_USER_FRIENDS = "blogracy.user.friends";
static private Properties loadProperties(String file) throws IOException {
- // ClassLoader loader = ClassLoader.getSystemClassLoader();
- // InputStream is = loader.getResourceAsStream(file);
- InputStream is = null;
- File f = new File(file);
- if (f.exists()) {
- is = new FileInputStream(f);
- } else {
- is = Configurations.class.getClassLoader()
- .getResourceAsStream(file);
- }
-
+ InputStream is = getResourceAsStream(file);
if (is != null) {
Properties properties = new Properties();
properties.load(is);
@@ -82,6 +72,19 @@ static private Properties loadProperties(String file) throws IOException {
}
}
+ static private InputStream getResourceAsStream(String file)
+ throws IOException {
+ InputStream is = null;
+ File f = new File(file);
+ if (f.exists()) {
+ is = new FileInputStream(f);
+ } else {
+ is = Configurations.class.getClassLoader()
+ .getResourceAsStream(file);
+ }
+ return is;
+ }
+
static public PathConfig getPathConfig() {
try {
@@ -180,22 +183,23 @@ public User getUser() {
}
return friends;
}
-
- public User getFriend(final String hash){
- for (User friend : this.getFriends())
- if(friend.getHash().toString().equals(hash))
- return friend;
- return null;
+
+ public User getFriend(final String hash) {
+ for (User friend : this.getFriends())
+ if (friend.getHash().toString().equals(hash))
+ return friend;
+ return null;
}
private User loadUser(String text) {
String[] hashAndNick = text.split(" ", 2);
User user = Users
.newUser(Hashes.fromString(hashAndNick[0]));
- if (hashAndNick.length == 2)
+ if (hashAndNick.length == 2) {
user.setLocalNick(hashAndNick[1]);
- else
+ } else {
user.setLocalNick(hashAndNick[0]);
+ }
return user;
}
@@ -206,8 +210,7 @@ public KeyPair getUserKeyPair() {
String alias = getUser().getLocalNick();
char[] password = new char[] { 'b', 'l', 'o', 'g', 'r',
'a', 'c', 'y' };
- InputStream is = Configurations.class.getClassLoader()
- .getResourceAsStream("blogracy.jks");
+ InputStream is = getResourceAsStream("blogracy.jks");
KeyStore keyStore = KeyStore.getInstance(KeyStore
.getDefaultType());
keyStore.load(is, password);
@@ -0,0 +1,212 @@
+/*
+ * Copyright (c) 2011 Enrico Franchi, Michele Tomaiuolo and University of Parma.
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+
+package net.blogracy.controller;
+
+import java.io.File;
+import java.io.FileReader;
+import java.io.FileWriter;
+import java.io.IOException;
+import java.security.InvalidParameterException;
+import java.security.MessageDigest;
+import java.security.NoSuchAlgorithmException;
+import java.text.DateFormat;
+import java.text.SimpleDateFormat;
+import java.util.TimeZone;
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+
+import javax.jms.Connection;
+import javax.jms.ConnectionFactory;
+import javax.jms.DeliveryMode;
+import javax.jms.Destination;
+import javax.jms.Message;
+import javax.jms.MessageConsumer;
+import javax.jms.MessageListener;
+import javax.jms.MessageProducer;
+import javax.jms.Session;
+import javax.jms.TextMessage;
+
+import net.blogracy.config.Configurations;
+import net.blogracy.util.FileUtils;
+
+import org.apache.activemq.ActiveMQConnection;
+import org.apache.activemq.ActiveMQConnectionFactory;
+import org.apache.commons.codec.binary.Base32;
+import org.apache.shindig.protocol.conversion.BeanConverter;
+import org.apache.shindig.protocol.conversion.BeanJsonConverter;
+import org.apache.shindig.social.core.model.ActivityEntryImpl;
+import org.apache.shindig.social.core.model.ActivityObjectImpl;
+import org.apache.shindig.social.core.model.AlbumImpl;
+import org.apache.shindig.social.core.model.MediaItemImpl;
+import org.apache.shindig.social.opensocial.model.ActivityEntry;
+import org.apache.shindig.social.opensocial.model.ActivityObject;
+import org.apache.shindig.social.opensocial.model.Album;
+import org.apache.shindig.social.opensocial.model.MediaItem;
+import org.apache.shindig.social.opensocial.model.MediaItem.Type;
+import org.json.JSONArray;
+import org.json.JSONException;
+import org.json.JSONObject;
+import org.json.JSONTokener;
+
+import com.google.inject.Binder;
+import com.google.inject.Guice;
+import com.google.inject.Module;
+import com.google.inject.name.Names;
+
+/**
+ * Generic functions to manipulate feeds are defined in this class.
+ */
+public class ActivitiesController {
+
+ static final DateFormat ISO_DATE_FORMAT = new SimpleDateFormat(
+ "yyyy-MM-dd'T'HH:mm:ss'Z'");
+ static final String CACHE_FOLDER = Configurations.getPathConfig()
+ .getCachedFilesDirectoryPath();
+
+ private static final FileSharing sharing = FileSharing.getSingleton();
+ private static final DistributedHashTable dht = DistributedHashTable
+ .getSingleton();
+ private static final ActivitiesController theInstance = new ActivitiesController();
+
+ private static BeanJsonConverter CONVERTER = new BeanJsonConverter(
+ Guice.createInjector(new Module() {
+ @Override
+ public void configure(Binder b) {
+ b.bind(BeanConverter.class)
+ .annotatedWith(
+ Names.named("shindig.bean.converter.json"))
+ .to(BeanJsonConverter.class);
+ }
+ }));
+
+ public static ActivitiesController getSingleton() {
+ return theInstance;
+ }
+
+ public ActivitiesController() {
+ ISO_DATE_FORMAT.setTimeZone(TimeZone.getTimeZone("UTC"));
+ }
+
+ static public List<ActivityEntry> getFeed(String user) {
+ List<ActivityEntry> result = new ArrayList<ActivityEntry>();
+ System.out.println("Getting feed: " + user);
+ JSONObject record = dht.getRecord(user);
+ if (record != null) {
+ try {
+ String latestHash = FileSharing.getHashFromMagnetURI(record
+ .getString("uri"));
+ File dbFile = new File(CACHE_FOLDER + File.separator
+ + latestHash + ".json");
+ if (!dbFile.exists() && record.has("prev")) {
+ latestHash = FileSharing.getHashFromMagnetURI(record
+ .getString("prev"));
+ dbFile = new File(CACHE_FOLDER + File.separator
+ + latestHash + ".json");
+ }
+ if (dbFile.exists()) {
+ System.out.println("Getting feed: "
+ + dbFile.getAbsolutePath());
+ JSONObject db = new JSONObject(new JSONTokener(
+ new FileReader(dbFile)));
+
+ JSONArray items = db.getJSONArray("items");
+ for (int i = 0; i < items.length(); ++i) {
+ JSONObject item = items.getJSONObject(i);
+ ActivityEntry entry = (ActivityEntry) CONVERTER
+ .convertToObject(item, ActivityEntry.class);
+ result.add(entry);
+ }
+ System.out.println("Feed loaded");
+ } else {
+ System.out.println("Feed not found");
+ }
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ }
+ return result;
+ }
+
+ public void addFeedEntry(String id, String text, File attachment) {
+ try {
+ String hash = sharing.hash(text);
+ File textFile = new File(CACHE_FOLDER + File.separator + hash
+ + ".txt");
+
+ FileWriter w = new FileWriter(textFile);
+ w.write(text);
+ w.close();
+
+ String textUri = sharing.seed(textFile);
+ String attachmentUri = null;
+ if (attachment != null) {
+ attachmentUri = sharing.seed(attachment);
+ }
+
+ final List<ActivityEntry> feed = getFeed(id);
+ final ActivityEntry entry = new ActivityEntryImpl();
+ entry.setVerb("post");
+ entry.setUrl(textUri);
+ entry.setPublished(ISO_DATE_FORMAT.format(new Date()));
+ entry.setContent(text);
+ if (attachment != null) {
+ ActivityObject enclosure = new ActivityObjectImpl();
+ enclosure.setUrl(attachmentUri);
+ entry.setObject(enclosure);
+ }
+ feed.add(0, entry);
+ String feedUri = seedActivityStream(id, feed);
+ DistributedHashTable.getSingleton().store(id, feedUri,
+ entry.getPublished());
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ }
+
+ public String seedActivityStream(String userId,
+ final List<ActivityEntry> feed) throws JSONException, IOException {
+ final File feedFile = new File(CACHE_FOLDER + File.separator + userId
+ + ".json");
+
+ JSONArray items = new JSONArray();
+ for (int i = 0; i < feed.size(); ++i) {
+ JSONObject item = new JSONObject(feed.get(i));
+ items.put(item);
+ }
+ JSONObject db = new JSONObject();
+
+ db.put("items", items);
+
+ FileWriter writer = new FileWriter(feedFile);
+ db.write(writer);
+ writer.close();
+
+ String feedUri = sharing.seed(feedFile);
+ return feedUri;
+ }
+}
Oops, something went wrong.

0 comments on commit 3921405

Please sign in to comment.