Skip to content

Commit

Permalink
code cleanup and bug fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
mic authored and mic committed Mar 15, 2013
1 parent 6f3ef7b commit 77316e5
Show file tree
Hide file tree
Showing 8 changed files with 107 additions and 28 deletions.
Expand Up @@ -127,6 +127,7 @@ public void onMessage(Message request) {
if (download != null && file != null) {
download.renameDownload(file.getName());
download.addCompletionListener(new CompletionListener((TextMessage) request));
download.setForceStart(true);
}
Logger.info(magnetUri + " added to download list");
} catch (ResourceDownloaderException e) {
Expand Down
Expand Up @@ -74,6 +74,7 @@ public void event(DistributedDatabaseEvent event) {
value = (String) event.getValue().getValue(String.class);
JSONObject record = new JSONObject(request.getText());
record.put("value", value);
Logger.info(record.toString());
TextMessage response = session.createTextMessage();
response.setText(record.toString());
response.setJMSCorrelationID(request.getJMSCorrelationID());
Expand Down
20 changes: 17 additions & 3 deletions blogracy-web/src/main/java/net/blogracy/WebServer.java
@@ -1,6 +1,9 @@
package net.blogracy;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.TimeZone;

import net.blogracy.config.Configurations;
import net.blogracy.controller.ActivitiesController;
Expand All @@ -14,7 +17,19 @@

public class WebServer {

public static final String LOREM_IPSUM = "Lorem ipsum dolor sit amet, "
+ "consectetur adipisicing elit, sed do eiusmod tempor "
+ "incididunt ut labore et dolore magna aliqua.";
static final DateFormat ISO_DATE_FORMAT = new SimpleDateFormat(
"yyyy-MM-dd'T'HH:mm:ss'Z'");

static final int TOTAL_WAIT = 2 * 60 * 1000; // 2 minutes

public static void main(String[] args) throws Exception {
ISO_DATE_FORMAT.setTimeZone(TimeZone.getTimeZone("UTC"));

int randomWait = (int) (TOTAL_WAIT * Math.random());
Thread.currentThread().sleep(randomWait);

String webDir = WebServer.class.getClassLoader().getResource("webapp")
.toExternalForm();
Expand All @@ -38,12 +53,11 @@ public static void main(String[] args) throws Exception {
.toString();
ChatController.getSingleton().joinChannel(id);

int TOTAL_WAIT = 5 * 60 * 1000; // 5 minutes

while (true) {
ActivitiesController activities = ActivitiesController
.getSingleton();
activities.addFeedEntry(id, "" + new java.util.Date(), null);
String now = ISO_DATE_FORMAT.format(new java.util.Date());
activities.addFeedEntry(id, now + " " + LOREM_IPSUM, null);

// List<User> friends = Configurations.getUserConfig().getFriends();
int wait = TOTAL_WAIT / friends.size();
Expand Down
Expand Up @@ -171,12 +171,16 @@ public User getUser() {

@Override
public List<User> getFriends() {
String userRow = userProperties
.getProperty(BLOGRACY_USER_USER);
ArrayList<User> friends = new ArrayList<User>();
int i = 1;
String friendRow = userProperties
.getProperty(BLOGRACY_USER_FRIENDS + '.' + i);
while (friendRow != null) {
friends.add(loadUser(friendRow));
if (!friendRow.equals(userRow)) {
friends.add(loadUser(friendRow));
}
++i;
friendRow = userProperties
.getProperty(BLOGRACY_USER_FRIENDS + '.' + i);
Expand Down
Expand Up @@ -28,17 +28,23 @@
import java.io.IOException;
import java.security.KeyPair;
import java.security.PublicKey;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.TimeZone;
import java.util.logging.FileHandler;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.DeliveryMode;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageListener;
Expand Down Expand Up @@ -70,46 +76,80 @@
*/
public class DistributedHashTable {

class DownloadListener implements MessageListener {
private String id;
private String version;
private JSONObject record;
private long start;
private long sent;

DownloadListener(String id, String version, JSONObject record) {
this.id = id;
this.version = version;
this.record = record;
this.start = System.currentTimeMillis();
try {
this.sent = ISO_DATE_FORMAT.parse(version).getTime();
} catch (ParseException e) {
e.printStackTrace();
}
log.info("download-req " + id + " " + version);
}

@Override
public void onMessage(Message response) {
String now = ISO_DATE_FORMAT.format(new java.util.Date());
long delay = System.currentTimeMillis() - start;
long size = -1;
long received = -1;
try {
received = ISO_DATE_FORMAT.parse(now).getTime() - sent;
String msgText = ((TextMessage) response).getText();
JSONObject obj = new JSONObject(msgText);
File file = new File(obj.getString("file"));
size = file.length();
} catch (Exception e) {
e.printStackTrace();
}
log.info("download-ans " + id + " " + version + " " + now + " "
+ delay + " " + " " + received + " " + size);
putRecord(record);
}
}

class LookupListener implements MessageListener {
private String id;
private long start;

LookupListener(String id) {
this.id = id;
this.start = System.currentTimeMillis();
log.info("Lookup req: " + id);
log.info("lookup-req " + id);
}

@Override
public void onMessage(Message response) {
try {
long delay = System.currentTimeMillis() - start;
String msgText = ((TextMessage) response).getText();
log.info("Lookup ans: " + id + " @ "
+ (System.currentTimeMillis() - start));
JSONObject keyValue = new JSONObject(msgText);
String value = keyValue.getString("value");
PublicKey signerKey = JsonWebSignature.getSignerKey(value);
final JSONObject record = new JSONObject(
JsonWebSignature.verify(value, signerKey));
JSONObject record = new JSONObject(JsonWebSignature.verify(
value, signerKey));
String version = record.getString("version");
String now = ISO_DATE_FORMAT.format(new java.util.Date());
log.info("lookup-ans " + id + " " + version + " " + now + " "
+ delay);
JSONObject currentRecord = getRecord(id);
if (currentRecord == null
|| currentRecord.getString("version").compareTo(
record.getString("version")) < 0) {
|| currentRecord.getString("version")
.compareTo(version) < 0) {
String uri = record.getString("uri");
FileSharing fileSharing = FileSharing.getSingleton();
String hash = fileSharing.getHashFromMagnetURI(uri);
log.info("Download req: " + id + " @ "
+ (System.currentTimeMillis() - start));
fileSharing.downloadByHash(hash, ".json",
new MessageListener() {
public void onMessage(Message response) {
log.info("Download ans: "
+ id
+ " @ "
+ (System.currentTimeMillis() - start));
putRecord(record);
}
});
new DownloadListener(id, version, record));
}
} catch (Exception e) {
e.printStackTrace();
Expand All @@ -126,6 +166,9 @@ public void onMessage(Message response) {
private MessageProducer producer;
private MessageConsumer consumer;

static final DateFormat ISO_DATE_FORMAT = new SimpleDateFormat(
"yyyy-MM-dd'T'HH:mm:ss'Z'");

static final String CACHE_FOLDER = Configurations.getPathConfig()
.getCachedFilesDirectoryPath();

Expand All @@ -139,9 +182,11 @@ public static DistributedHashTable getSingleton() {
}

public DistributedHashTable() {
ISO_DATE_FORMAT.setTimeZone(TimeZone.getTimeZone("UTC"));
try {
log = Logger.getLogger("net.blogracy.controller.dht");
log.addHandler(new FileHandler("dht.log"));
log.getHandlers()[0].setFormatter(new SimpleFormatter());

File recordsFile = new File(CACHE_FOLDER + File.separator
+ "records.json");
Expand Down
19 changes: 15 additions & 4 deletions blogracy-web/src/main/java/net/blogracy/model/hashes/Hashes.java
Expand Up @@ -35,10 +35,15 @@ public class Hashes {

private static Base32 base32 = new Base32();

public static String hash(String text) throws NoSuchAlgorithmException {
MessageDigest digester = MessageDigest.getInstance("SHA-1");
byte[] digest = digester.digest(text.getBytes());
String result = base32.encodeAsString(digest);
public static String hash(String text) {
String result = null;
try {
MessageDigest digester = MessageDigest.getInstance("SHA-1");
byte[] digest = digester.digest(text.getBytes());
result = base32.encodeAsString(digest);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return result;
}

Expand Down Expand Up @@ -159,4 +164,10 @@ static public boolean validateHash(Hash hash) {
private Hashes() {
/* no instances, thanks */
}

public static void main(String[] args) {
for (String arg : args) {
System.out.println(hash(arg) + " " + arg);
}
}
}
3 changes: 3 additions & 0 deletions blogracy-web/src/main/webapp/chat.jsp
@@ -1,3 +1,6 @@
<%@ page import="net.blogracy.controller.ChatController" %>
<% ChatController.getSingleton().joinChannel(channel); // Blogracy %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
Expand Down
4 changes: 2 additions & 2 deletions blogracy-web/src/main/webapp/user.jsp
Expand Up @@ -17,7 +17,7 @@ if (userHash == null || userHash.length() == 0) {
}
String channel = ChatController.getPrivateChannel(localUserHash, userHash);
ChatController.getSingleton().joinChannel(channel);
//ChatController.getSingleton().joinChannel(channel);
pageContext.setAttribute("localUserHash", localUserHash);
pageContext.setAttribute("userHash", userHash);
Expand Down Expand Up @@ -171,7 +171,7 @@ pageContext.setAttribute("publicChannel", userHash);
<div class="content">
<div class="page-header">
<h1>${user.localNick}
<small>(hardcoded email)</small>
<small>(UserID)</small>
</h1>
</div>
<div class="row">
Expand Down

0 comments on commit 77316e5

Please sign in to comment.