format (shendaras)

This commit is contained in:
shendaras
2004-04-10 11:50:11 +00:00
committed by zzz
parent 17a1b11f66
commit 51c49d7c1b
17 changed files with 1462 additions and 1464 deletions

View File

@ -102,8 +102,7 @@ public class ByteCollector {
}
public int indexOf(byte[] ba) {
loop:
for (int i=0;i<size-ba.length+1;i++) {
loop: for (int i = 0; i < size - ba.length + 1; i++) {
for (int j = 0; j < ba.length; j++) {
if (contents[i + j] != ba[j]) continue loop;
}
@ -148,8 +147,7 @@ public class ByteCollector {
public byte removeFirst() {
byte bb = contents[0];
if (size==0)
throw new IllegalArgumentException("ByteCollector is empty");
if (size == 0) throw new IllegalArgumentException("ByteCollector is empty");
if (size > 1)
System.arraycopy(contents, 1, contents, 0, --size);
else

View File

@ -43,8 +43,11 @@ class I2PServerSocketImpl implements I2PServerSocket {
private void myWait() {
try {
wait();
} catch (InterruptedException ex) {}
} catch (InterruptedException ex) {
}
}
public I2PSocketManager getManager() { return mgr; }
public I2PSocketManager getManager() {
return mgr;
}
}

View File

@ -33,8 +33,7 @@ class I2PSocketImpl implements I2PSocket {
private Object flagLock = new Object();
private boolean closed = false, sendClose = true, closed2 = false;
public I2PSocketImpl(Destination peer, I2PSocketManager mgr,
boolean outgoing, String localID) {
public I2PSocketImpl(Destination peer, I2PSocketManager mgr, boolean outgoing, String localID) {
this.outgoing = outgoing;
manager = mgr;
remote = peer;
@ -60,6 +59,7 @@ class I2PSocketImpl implements I2PSocket {
public String getRemoteID(boolean wait) throws InterruptedIOException {
return getRemoteID(wait, -1);
}
public String getRemoteID(boolean wait, long maxWait) throws InterruptedIOException {
long dieAfter = System.currentTimeMillis() + maxWait;
synchronized (remoteIDWaiter) {
@ -69,13 +69,15 @@ class I2PSocketImpl implements I2PSocket {
remoteIDWaiter.wait(maxWait);
else
remoteIDWaiter.wait();
} catch (InterruptedException ex) {}
} catch (InterruptedException ex) {
}
if ((maxWait > 0) && (System.currentTimeMillis() > dieAfter))
throw new InterruptedIOException("Timed out waiting for remote ID");
}
if (wait) {
_log.debug("TIMING: RemoteID set to " + I2PSocketManager.getReadableForm(remoteID) +" for "+this.hashCode());
_log.debug("TIMING: RemoteID set to " + I2PSocketManager.getReadableForm(remoteID) + " for "
+ this.hashCode());
}
return remoteID;
}
@ -92,19 +94,22 @@ class I2PSocketImpl implements I2PSocket {
/**
* Return the Destination of this side of the socket.
*/
public Destination getThisDestination() { return local; }
public Destination getThisDestination() {
return local;
}
/**
* Return the destination of the peer.
*/
public Destination getPeerDestination() { return remote; }
public Destination getPeerDestination() {
return remote;
}
/**
* Return an InputStream to read from the socket.
*/
public InputStream getInputStream() throws IOException {
if ( (in == null) )
throw new IOException("Not connected");
if ((in == null)) throw new IOException("Not connected");
return in;
}
@ -112,8 +117,7 @@ class I2PSocketImpl implements I2PSocket {
* Return an OutputStream to write into the socket.
*/
public OutputStream getOutputStream() throws IOException {
if ( (out == null) )
throw new IOException("Not connected");
if ((out == null)) throw new IOException("Not connected");
return out;
}
@ -139,7 +143,6 @@ class I2PSocketImpl implements I2PSocket {
in.notifyClosed();
}
private byte getMask(int add) {
return (byte) ((outgoing ? (byte) 0xA0 : (byte) 0x50) + (byte) add);
}
@ -170,15 +173,15 @@ class I2PSocketImpl implements I2PSocket {
}
try {
wait();
} catch (InterruptedException ex) {}
} catch (InterruptedException ex) {
}
read = bc.startToByteArray(len);
}
if (read.length > len) throw new RuntimeException("BUG");
System.arraycopy(read, 0, b, off, read.length);
if (_log.shouldLog(Log.DEBUG)) {
_log.debug("Read from I2PInputStream " + this.hashCode()
+ " returned "+read.length+" bytes");
_log.debug("Read from I2PInputStream " + this.hashCode() + " returned " + read.length + " bytes");
}
//if (_log.shouldLog(Log.DEBUG)) {
// _log.debug("Read from I2PInputStream " + this.hashCode()
@ -215,6 +218,7 @@ class I2PSocketImpl implements I2PSocket {
public I2POutputStream(I2PInputStream sendTo) {
this.sendTo = sendTo;
}
public void write(int b) throws IOException {
write(new byte[] { (byte) b});
}
@ -254,8 +258,7 @@ class I2PSocketImpl implements I2PSocket {
} else if (bcsize == 0) {
break;
}
if ((bcsize < MAX_PACKET_SIZE)
&& (in.available()==0)) {
if ((bcsize < MAX_PACKET_SIZE) && (in.available() == 0)) {
_log.debug("Runner Point d: " + this.hashCode());
try {
@ -264,8 +267,7 @@ class I2PSocketImpl implements I2PSocket {
e.printStackTrace();
}
}
if ((bcsize >= MAX_PACKET_SIZE)
|| (in.available()==0) ) {
if ((bcsize >= MAX_PACKET_SIZE) || (in.available() == 0)) {
byte[] data = bc.startToByteArray(MAX_PACKET_SIZE);
if (data.length > 0) {
_log.debug("Message size is: " + data.length);
@ -278,8 +280,7 @@ class I2PSocketImpl implements I2PSocket {
}
}
if ((bc.getCurrentSize() > 0) && sent) {
_log.error("A SCARY MONSTER HAS EATEN SOME DATA! "
+ "(input stream: " + in.hashCode() + "; "
_log.error("A SCARY MONSTER HAS EATEN SOME DATA! " + "(input stream: " + in.hashCode() + "; "
+ "queue size: " + bc.getCurrentSize() + ")");
}
synchronized (flagLock) {
@ -295,8 +296,7 @@ class I2PSocketImpl implements I2PSocket {
} // FIXME: Race here?
if (sc) {
_log.info("Sending close packet: " + outgoing);
byte[] packet = I2PSocketManager.makePacket
((byte)(getMask(0x02)),remoteID, new byte[0]);
byte[] packet = I2PSocketManager.makePacket((byte) (getMask(0x02)), remoteID, new byte[0]);
synchronized (manager.getSession()) {
sent = manager.getSession().sendMessage(remote, packet);
}
@ -322,8 +322,7 @@ class I2PSocketImpl implements I2PSocket {
_log.error("NULL REMOTEID");
return false;
}
byte[] packet = I2PSocketManager.makePacket(getMask(0x00), remoteID,
data);
byte[] packet = I2PSocketManager.makePacket(getMask(0x00), remoteID, data);
boolean sent;
synchronized (flagLock) {
if (closed2) return false;

View File

@ -39,7 +39,6 @@ public class I2PSocketManager implements I2PSessionListener {
public static final int PUBKEY_LENGTH = 387;
public I2PSocketManager() {
_session = null;
_serverSocket = new I2PServerSocketImpl(this);
@ -53,8 +52,7 @@ public class I2PSocketManager implements I2PSessionListener {
public void setSession(I2PSession session) {
_session = session;
if (session != null)
session.setSessionListener(this);
if (session != null) session.setSessionListener(this);
}
public void disconnected(I2PSession session) {
@ -78,24 +76,22 @@ public class I2PSocketManager implements I2PSessionListener {
return;
}
int type = msg[0] & 0xff;
String id = new String(new byte[] {msg[1], msg[2], msg[3]},
"ISO-8859-1");
String id = new String(new byte[] { msg[1], msg[2], msg[3]}, "ISO-8859-1");
byte[] payload = new byte[msg.length - 4];
System.arraycopy(msg, 4, payload, 0, payload.length);
_log.debug("Message read: type = [" + Integer.toHexString(type) +
"] id = [" + getReadableForm(id)+
"] payload length: " + payload.length + "]");
_log.debug("Message read: type = [" + Integer.toHexString(type) + "] id = [" + getReadableForm(id)
+ "] payload length: " + payload.length + "]");
synchronized (lock) {
switch (type) {
case 0x51: // ACK outgoing
case 0x51:
// ACK outgoing
s = (I2PSocketImpl) _outSockets.get(id);
if (s == null) {
_log.warn("No socket responsible for ACK packet");
return;
}
if (payload.length == 3 && s.getRemoteID(false) == null) {
String newID = new String(payload,
"ISO-8859-1");
String newID = new String(payload, "ISO-8859-1");
s.setRemoteID(newID);
return;
} else {
@ -105,7 +101,8 @@ public class I2PSocketManager implements I2PSessionListener {
_log.warn("Remote ID already exists? " + s.getRemoteID());
return;
}
case 0x52: // disconnect outgoing
case 0x52:
// disconnect outgoing
_log.debug("*Disconnect outgoing!");
try {
s = (I2PSocketImpl) _outSockets.get(id);
@ -114,14 +111,14 @@ public class I2PSocketManager implements I2PSessionListener {
_outSockets.remove(id);
return;
} else {
if (payload.length > 0)
_log.warn("Disconnect packet had " + payload.length + " bytes");
if (payload.length > 0) _log.warn("Disconnect packet had " + payload.length + " bytes");
return;
}
} catch (Exception t) {
_log.error("Ignoring error on disconnect", t);
}
case 0x50: // packet send outgoing
case 0x50:
// packet send outgoing
_log.debug("*Packet send outgoing [" + payload.length + "]");
s = (I2PSocketImpl) _outSockets.get(id);
if (s != null) {
@ -131,35 +128,30 @@ public class I2PSocketManager implements I2PSessionListener {
_log.error("Null socket with data available");
throw new IllegalStateException("Null socket with data available");
}
case 0xA1: // SYN incoming
case 0xA1:
// SYN incoming
_log.debug("*Syn!");
if (payload.length == PUBKEY_LENGTH) {
String newLocalID = makeID(_inSockets);
Destination d = new Destination();
d.readBytes(new ByteArrayInputStream(payload));
s = new I2PSocketImpl(d, this, false,
newLocalID);
s = new I2PSocketImpl(d, this, false, newLocalID);
s.setRemoteID(id);
if (_serverSocket.getNewSocket(s)) {
_inSockets.put(newLocalID, s);
byte[] packet = makePacket
((byte)0x51, id,
newLocalID.getBytes("ISO-8859-1"));
byte[] packet = makePacket((byte) 0x51, id, newLocalID.getBytes("ISO-8859-1"));
boolean replySentOk = false;
synchronized (_session) {
replySentOk = _session.sendMessage(d, packet);
}
if (!replySentOk) {
_log.error("Error sending reply to " +
d.calculateHash().toBase64() +
" in response to a new con message",
new Exception("Failed creation"));
_log.error("Error sending reply to " + d.calculateHash().toBase64()
+ " in response to a new con message", new Exception("Failed creation"));
s.internalClose();
}
} else {
byte[] packet =
(" "+id).getBytes("ISO-8859-1");
byte[] packet = (" " + id).getBytes("ISO-8859-1");
packet[0] = 0x52;
boolean nackSent = session.sendMessage(d, packet);
if (!nackSent) {
@ -169,10 +161,12 @@ public class I2PSocketManager implements I2PSessionListener {
}
return;
} else {
_log.error("Syn packet that has a payload not equal to the pubkey length (" + payload.length + " != " + PUBKEY_LENGTH + ")");
_log.error("Syn packet that has a payload not equal to the pubkey length (" + payload.length
+ " != " + PUBKEY_LENGTH + ")");
return;
}
case 0xA2: // disconnect incoming
case 0xA2:
// disconnect incoming
_log.debug("*Disconnect incoming!");
try {
s = (I2PSocketImpl) _inSockets.get(id);
@ -181,15 +175,15 @@ public class I2PSocketManager implements I2PSessionListener {
_inSockets.remove(id);
return;
} else {
if (payload.length > 0)
_log.warn("Disconnect packet had " + payload.length + " bytes");
if (payload.length > 0) _log.warn("Disconnect packet had " + payload.length + " bytes");
return;
}
} catch (Exception t) {
_log.error("Ignoring error on disconnect", t);
return;
}
case 0xA0: // packet send incoming
case 0xA0:
// packet send incoming
_log.debug("*Packet send incoming [" + payload.length + "]");
s = (I2PSocketImpl) _inSockets.get(id);
if (s != null) {
@ -199,15 +193,13 @@ public class I2PSocketManager implements I2PSessionListener {
_log.error("Null socket with data available");
throw new IllegalStateException("Null socket with data available");
}
case 0xFF: // ignore
case 0xFF:
// ignore
return;
}
_log.error("\n\n=============== Unknown packet! "+
"============"+
"\nType: "+(int)type+
"\nID: " + getReadableForm(id)+
"\nBase64'ed Data: "+Base64.encode(payload)+
"\n\n\n");
_log.error("\n\n=============== Unknown packet! " + "============" + "\nType: " + (int) type
+ "\nID: " + getReadableForm(id) + "\nBase64'ed Data: " + Base64.encode(payload)
+ "\n\n\n");
if (id != null) {
_inSockets.remove(id);
_outSockets.remove(id);
@ -226,11 +218,17 @@ public class I2PSocketManager implements I2PSessionListener {
_log.error("Abuse reported [" + severity + "]");
}
public void setDefaultOptions(I2PSocketOptions options) { _defaultOptions = options; }
public void setDefaultOptions(I2PSocketOptions options) {
_defaultOptions = options;
}
public I2PSocketOptions getDefaultOptions() { return _defaultOptions ; }
public I2PSocketOptions getDefaultOptions() {
return _defaultOptions;
}
public I2PServerSocket getServerSocket() { return _serverSocket; }
public I2PServerSocket getServerSocket() {
return _serverSocket;
}
/**
* Create a new connected socket (block until the socket is created)
@ -251,8 +249,7 @@ public class I2PSocketManager implements I2PSessionListener {
ByteArrayOutputStream pubkey = new ByteArrayOutputStream();
_session.getMyDestination().writeBytes(pubkey);
String remoteID;
byte[] packet = makePacket((byte)0xA1, localID,
pubkey.toByteArray());
byte[] packet = makePacket((byte) 0xA1, localID, pubkey.toByteArray());
boolean sent = false;
synchronized (_session) {
sent = _session.sendMessage(peer, packet);
@ -265,9 +262,7 @@ public class I2PSocketManager implements I2PSessionListener {
throw new I2PException("Unable to reach peer");
}
remoteID = s.getRemoteID(true, options.getConnectTimeout());
if ("".equals(remoteID)) {
throw new I2PException("Unable to reach peer");
}
if ("".equals(remoteID)) { throw new I2PException("Unable to reach peer"); }
_log.debug("TIMING: s given out for remoteID " + getReadableForm(remoteID));
return s;
} catch (InterruptedIOException ioe) {
@ -371,15 +366,12 @@ public class I2PSocketManager implements I2PSessionListener {
byte[] packet = new byte[payload.length + 4];
packet[0] = type;
byte[] temp = id.getBytes("ISO-8859-1");
if (temp.length != 3)
throw new RuntimeException("Incorrect ID length: "+
temp.length);
if (temp.length != 3) throw new RuntimeException("Incorrect ID length: " + temp.length);
System.arraycopy(temp, 0, packet, 1, 3);
System.arraycopy(payload, 0, packet, 4, payload.length);
return packet;
} catch (UnsupportedEncodingException ex) {
if (_log.shouldLog(Log.ERROR))
_log.error("Error building the packet", ex);
if (_log.shouldLog(Log.ERROR)) _log.error("Error building the packet", ex);
return new byte[0];
}
}

View File

@ -62,7 +62,8 @@ public class I2PSocketManagerFactory {
*
* @return the newly created socket manager, or null if there were errors
*/
public static I2PSocketManager createManager(InputStream myPrivateKeyStream, String i2cpHost, int i2cpPort, Properties opts) {
public static I2PSocketManager createManager(InputStream myPrivateKeyStream, String i2cpHost, int i2cpPort,
Properties opts) {
I2PClient client = I2PClientFactory.createClient();
opts.setProperty(I2PClient.PROP_RELIABILITY, I2PClient.PROP_RELIABILITY_GUARANTEED);
opts.setProperty(I2PClient.PROP_TCP_HOST, i2cpHost);

View File

@ -7,6 +7,7 @@ package net.i2p.client.streaming;
*/
public class I2PSocketOptions {
private long _connectTimeout;
public I2PSocketOptions() {
_connectTimeout = -1;
}
@ -16,6 +17,11 @@ public class I2PSocketOptions {
*
* @return milliseconds to wait, or -1 if we will wait indefinitely
*/
public long getConnectTimeout() { return _connectTimeout; }
public void setConnectTimeout(long ms) { _connectTimeout = ms; }
public long getConnectTimeout() {
return _connectTimeout;
}
public void setConnectTimeout(long ms) {
_connectTimeout = ms;
}
}

View File

@ -1,4 +1,5 @@
package net.i2p.phttprelay;
/*
* free (adj.): unencumbered; not under the control of others
* Written by jrandom in 2003 and released into the public domain

View File

@ -1,4 +1,5 @@
package net.i2p.phttprelay;
/*
* free (adj.): unencumbered; not under the control of others
* Written by jrandom in 2003 and released into the public domain
@ -26,7 +27,10 @@ class LockManager {
_locks.add(target);
return;
}
try { _locks.wait(1000); } catch (InterruptedException ie) {}
try {
_locks.wait(1000);
} catch (InterruptedException ie) {
}
}
}
}

View File

@ -1,4 +1,5 @@
package net.i2p.phttprelay;
/*
* free (adj.): unencumbered; not under the control of others
* Written by jrandom in 2003 and released into the public domain
@ -67,6 +68,7 @@ abstract class PHTTPRelayServlet extends HttpServlet {
public void log(String msg) {
_log.debug(msg);
}
public void log(String msg, Throwable t) {
_log.debug(msg, t);
}

View File

@ -1,4 +1,5 @@
package net.i2p.phttprelay;
/*
* free (adj.): unencumbered; not under the control of others
* Written by jrandom in 2003 and released into the public domain
@ -197,7 +198,6 @@ public class PollServlet extends PHTTPRelayServlet {
}
}
private boolean isKnown(String target) throws IOException {
File identDir = getIdentDir(target);
if (identDir.exists()) {

View File

@ -1,4 +1,5 @@
package net.i2p.phttprelay;
/*
* free (adj.): unencumbered; not under the control of others
* Written by jrandom in 2003 and released into the public domain
@ -112,7 +113,10 @@ public class RegisterServlet extends PHTTPRelayServlet {
fos = new FileOutputStream(identFile);
ident.writeBytes(fos);
} finally {
if (fos != null) try { fos.close(); } catch (IOException ioe) {}
if (fos != null) try {
fos.close();
} catch (IOException ioe) {
}
}
log("Identity registered into " + identFile.getAbsolutePath());
return true;

View File

@ -1,4 +1,5 @@
package net.i2p.phttprelay;
/*
* free (adj.): unencumbered; not under the control of others
* Written by jrandom in 2003 and released into the public domain
@ -82,22 +83,21 @@ public class SendServlet extends PHTTPRelayServlet {
/** msgId parameter to access the check path servlet with (along side PARAM_SEND_TARGET) */
public final static String PARAM_MSG_ID = "msgId";
/* key=val keys sent back on registration */
public final static String PROP_CHECK_URL = "statusCheckURL";
public final static String PROP_STATUS = "status";
public final static String STATUS_OK = "accepted";
public final static String STATUS_UNKNOWN = "unknown";
private final static String STATUS_CLOCKSKEW = "clockSkew_"; /** prefix for (local-remote) */
private final static String STATUS_CLOCKSKEW = "clockSkew_";
/** prefix for (local-remote) */
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletInputStream in = req.getInputStream();
try {
int contentLen = req.getContentLength();
String firstLine = getFirstLine(in, contentLen);
if (firstLine == null) {
return;
}
if (firstLine == null) { return; }
Map params = getParameters(firstLine);
String target = (String) params.get(PARAM_SEND_TARGET);
String timeoutStr = (String) params.get(PARAM_SEND_TIMEOUTMS);
@ -141,10 +141,12 @@ public class SendServlet extends PHTTPRelayServlet {
fail(req, resp, "Unable to queue up the message for delivery");
}
} finally {
try { in.close(); } catch (IOException ioe) {}
try {
in.close();
} catch (IOException ioe) {
}
}
}
private String getFirstLine(ServletInputStream in, int len) throws ServletException, IOException {
StringBuffer buf = new StringBuffer(128);
@ -238,28 +240,30 @@ public class SendServlet extends PHTTPRelayServlet {
byte buf[] = new byte[4096];
while (remaining > 0) {
int read = in.read(buf);
if (read == -1)
break;
if (read == -1) break;
remaining -= read;
if (read > 0)
fos.write(buf, 0, read);
if (read > 0) fos.write(buf, 0, read);
}
} finally {
if (fos != null) {
try { fos.close(); } catch (IOException ioe) {}
try {
fos.close();
} catch (IOException ioe) {
}
}
if (remaining != 0) {
log("Invalid remaining bytes [" + remaining + " out of " + len + "] - perhaps message was cancelled partway through delivery? deleting " + file.getAbsolutePath());
log("Invalid remaining bytes [" + remaining + " out of " + len
+ "] - perhaps message was cancelled partway through delivery? deleting " + file.getAbsolutePath());
boolean deleted = file.delete();
if (!deleted)
log("!!!Error deleting temporary file " + file.getAbsolutePath());
if (!deleted) log("!!!Error deleting temporary file " + file.getAbsolutePath());
return false;
}
}
return true;
}
private void sendSuccess(HttpServletRequest req, HttpServletResponse resp, String target, int msgId) throws IOException {
private void sendSuccess(HttpServletRequest req, HttpServletResponse resp, String target, int msgId)
throws IOException {
ServletOutputStream out = resp.getOutputStream();
StringBuffer buf = new StringBuffer();
buf.append(PROP_STATUS).append('=').append(STATUS_OK).append('\n');
@ -298,11 +302,13 @@ public class SendServlet extends PHTTPRelayServlet {
String maxMessagesPerIdentStr = config.getInitParameter(PARAM_MAX_MESSAGES_PER_IDENT);
if (maxMessagesPerIdentStr == null)
throw new ServletException("Max messages per ident for the sending servlet required [" + PARAM_MAX_MESSAGES_PER_IDENT + "]");
throw new ServletException("Max messages per ident for the sending servlet required ["
+ PARAM_MAX_MESSAGES_PER_IDENT + "]");
try {
_maxMessagesPerIdent = Integer.parseInt(maxMessagesPerIdentStr);
} catch (Throwable t) {
throw new ServletException("Valid max messages per ident for the sending servlet required [" + PARAM_MAX_MESSAGES_PER_IDENT + "]");
throw new ServletException("Valid max messages per ident for the sending servlet required ["
+ PARAM_MAX_MESSAGES_PER_IDENT + "]");
}
}

View File

@ -20,21 +20,13 @@ public class BasicEchoTestAnalyzer implements EchoTestAnalyzer {
SUMMARY_SIZE = summarySize;
}
private int events = 0,
packetLosses = 0,
packetLossesDisconnect=0,
disconnects = 0,
disconnectsRefused = 0,
delayCount=0,
lastDelayPtr = 0;
private int events = 0, packetLosses = 0, packetLossesDisconnect = 0, disconnects = 0, disconnectsRefused = 0,
delayCount = 0, lastDelayPtr = 0;
private long minDelay = Long.MAX_VALUE, maxDelay = 0, delaySum = 0;
private long[] lastDelays = new long[SUMMARY_SIZE];
public synchronized void packetLossOccurred(boolean beforeDisconnect) {
System.out.println("1: Packet lost"+
(beforeDisconnect?" before disconnect":"")+
".");
System.out.println("1: Packet lost" + (beforeDisconnect ? " before disconnect" : "") + ".");
packetLosses++;
if (beforeDisconnect) packetLossesDisconnect++;
countEvent();
@ -52,9 +44,7 @@ public class BasicEchoTestAnalyzer implements EchoTestAnalyzer {
}
public synchronized void disconnected(boolean refused) {
System.out.println("2: Disconnected"+
(refused?" (connection refused)":"")+
".");
System.out.println("2: Disconnected" + (refused ? " (connection refused)" : "") + ".");
disconnects++;
if (refused) disconnectsRefused++;
countEvent();
@ -68,27 +58,31 @@ public class BasicEchoTestAnalyzer implements EchoTestAnalyzer {
for (int i = 0; i < SUMMARY_SIZE; i++) {
delaySummary += lastDelays[i];
}
System.out.println
("++++++++++++++++ ECHO STATISTICS +++++++++++++++++++++++++"+
"\n++ Number of total echo messages: "+packets+
"\n++ No response for "+packetLosses+
"\n++ (of which "+ packetLossesDisconnect+
" due to a disconnect)"+
"\n++ Disconnects: "+disconnects+
"\n++ (of which "+disconnectsRefused+
" due to 'connection refused')"+
(disconnects>0 || true
?"\n++ Average lost packets per disconnect: "+
(packetLossesDisconnect/(float)disconnects)
:"")+
"\n++++++++++++++++++++++++++++++++++++++++++++++++++++++++"+
"\n++ Minimal delay: "+minDelay+
"\n++ Average delay: "+(delaySum/(float)delayCount)+
"\n++ Maximal delay: "+maxDelay+
(delayCount >=SUMMARY_SIZE
?"\n++ Average delay over last " + SUMMARY_SIZE + ": "+(delaySummary/(float)SUMMARY_SIZE)
:"")+
"\n++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
System.out.println("++++++++++++++++ ECHO STATISTICS +++++++++++++++++++++++++"
+ "\n++ Number of total echo messages: "
+ packets
+ "\n++ No response for "
+ packetLosses
+ "\n++ (of which "
+ packetLossesDisconnect
+ " due to a disconnect)"
+ "\n++ Disconnects: "
+ disconnects
+ "\n++ (of which "
+ disconnectsRefused
+ " due to 'connection refused')"
+ (disconnects > 0 || true ? "\n++ Average lost packets per disconnect: "
+ (packetLossesDisconnect / (float) disconnects) : "")
+ "\n++++++++++++++++++++++++++++++++++++++++++++++++++++++++"
+ "\n++ Minimal delay: "
+ minDelay
+ "\n++ Average delay: "
+ (delaySum / (float) delayCount)
+ "\n++ Maximal delay: "
+ maxDelay
+ (delayCount >= SUMMARY_SIZE ? "\n++ Average delay over last " + SUMMARY_SIZE + ": "
+ (delaySummary / (float) SUMMARY_SIZE) : "")
+ "\n++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
}
}
}

View File

@ -15,5 +15,3 @@ public interface EchoTestAnalyzer {
}

View File

@ -34,7 +34,6 @@ public class EchoTester extends Thread {
*/
private static final long MAX_PACKETS_QUEUED = 50; // unused
private EchoTestAnalyzer eta;
private String host;
private int port;
@ -46,10 +45,8 @@ public class EchoTester extends Thread {
private boolean readerRunning = false;
public static void main(String[] args) {
if (args.length == 3)
PACKET_DELAY = Long.parseLong(args[2]);
new EchoTester(args[0], Integer.parseInt(args[1]),
new BasicEchoTestAnalyzer());
if (args.length == 3) PACKET_DELAY = Long.parseLong(args[2]);
new EchoTester(args[0], Integer.parseInt(args[1]), new BasicEchoTestAnalyzer());
}
public EchoTester(String host, int port, EchoTestAnalyzer eta) {
@ -75,8 +72,7 @@ public class EchoTester extends Thread {
nextUnreceived = nextPacket;
}
Thread t = new ResponseReaderThread(s);
Writer w = new BufferedWriter(new OutputStreamWriter
(s.getOutputStream()));
Writer w = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
while (true) {
long no;
synchronized (lock) {
@ -94,16 +90,14 @@ public class EchoTester extends Thread {
t.join();
synchronized (lock) {
if (readerRunning) {
System.out.println("*** WHY IS THIS THREAD STILL"+
" RUNNING?");
System.out.println("*** WHY IS THIS THREAD STILL" + " RUNNING?");
}
while (nextUnreceived < nextPacket) {
nextUnreceived++;
eta.packetLossOccurred(true);
}
if (nextUnreceived > nextPacket) {
System.out.println("*** WTF? "+nextUnreceived+" > "+
nextPacket);
System.out.println("*** WTF? " + nextUnreceived + " > " + nextPacket);
}
}
eta.disconnected(false);
@ -132,20 +126,16 @@ public class EchoTester extends Thread {
public void run() {
try {
BufferedReader br = new BufferedReader(new InputStreamReader
(s.getInputStream()));
BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
String line;
int index;
while ((line = br.readLine()) != null) {
if ((index=line.indexOf(" ")) == -1)
continue;
if ((index = line.indexOf(" ")) == -1) continue;
long now, packetNumber, packetTime;
now = System.currentTimeMillis();
try {
packetNumber = Long.parseLong
(line.substring(0,index));
packetTime = Long.parseLong
(line.substring(index+1));
packetNumber = Long.parseLong(line.substring(0, index));
packetTime = Long.parseLong(line.substring(index + 1));
} catch (NumberFormatException ex) {
System.out.println(ex.toString());
continue;