Code formatting and small cleanups.

This commit is contained in:
akwizgran
2015-01-28 21:18:31 +00:00
parent fcb983a651
commit 47bd84122e
22 changed files with 371 additions and 439 deletions

View File

@@ -49,6 +49,10 @@ Service, EventListener {
private static final int PRIVATE_MESSAGE_NOTIFICATION_ID = 3; private static final int PRIVATE_MESSAGE_NOTIFICATION_ID = 3;
private static final int GROUP_POST_NOTIFICATION_ID = 4; private static final int GROUP_POST_NOTIFICATION_ID = 4;
private static final String CONTACT_URI =
"content://org.briarproject/contact";
private static final String GROUP_URI =
"content://org.briarproject/group";
private static final Logger LOG = private static final Logger LOG =
Logger.getLogger(AndroidNotificationManagerImpl.class.getName()); Logger.getLogger(AndroidNotificationManagerImpl.class.getName());
@@ -58,15 +62,15 @@ Service, EventListener {
private final EventBus eventBus; private final EventBus eventBus;
private final Context appContext; private final Context appContext;
private final Map<ContactId, Integer> contactCounts = private final Map<ContactId, Integer> contactCounts =
new HashMap<ContactId, Integer>(); new HashMap<ContactId, Integer>();
private final Map<GroupId, Integer> groupCounts = private final Map<GroupId, Integer> groupCounts =
new HashMap<GroupId, Integer>(); new HashMap<GroupId, Integer>();
private int privateTotal = 0, groupTotal = 0; private int privateTotal = 0, groupTotal = 0;
private int nextRequestId = 0; private int nextRequestId = 0;
private volatile Settings settings = new Settings(); private volatile Settings settings = new Settings();
private final Lock synchLock = new ReentrantLock(); private final Lock synchLock = new ReentrantLock();
@Inject @Inject
@@ -109,27 +113,25 @@ Service, EventListener {
public void showPrivateMessageNotification(ContactId c) { public void showPrivateMessageNotification(ContactId c) {
synchLock.lock(); synchLock.lock();
try{ try {
Integer count = contactCounts.get(c); Integer count = contactCounts.get(c);
if(count == null) contactCounts.put(c, 1); if(count == null) contactCounts.put(c, 1);
else contactCounts.put(c, count + 1); else contactCounts.put(c, count + 1);
privateTotal++; privateTotal++;
updatePrivateMessageNotification(); updatePrivateMessageNotification();
} } finally {
finally{
synchLock.unlock(); synchLock.unlock();
} }
} }
public void clearPrivateMessageNotification(ContactId c) { public void clearPrivateMessageNotification(ContactId c) {
synchLock.lock(); synchLock.lock();
try{ try {
Integer count = contactCounts.remove(c); Integer count = contactCounts.remove(c);
if(count == null) return; // Already cleared if(count == null) return; // Already cleared
privateTotal -= count; privateTotal -= count;
updatePrivateMessageNotification(); updatePrivateMessageNotification();
} } finally {
finally{
synchLock.unlock(); synchLock.unlock();
} }
} }
@@ -158,7 +160,7 @@ Service, EventListener {
Intent i = new Intent(appContext, ConversationActivity.class); Intent i = new Intent(appContext, ConversationActivity.class);
ContactId c = contactCounts.keySet().iterator().next(); ContactId c = contactCounts.keySet().iterator().next();
i.putExtra("briar.CONTACT_ID", c.getInt()); i.putExtra("briar.CONTACT_ID", c.getInt());
i.setData(Uri.parse(String.format("content://contact/%s", c.getInt()))); i.setData(Uri.parse(CONTACT_URI + "/" + c.getInt()));
i.setFlags(FLAG_ACTIVITY_CLEAR_TOP | FLAG_ACTIVITY_SINGLE_TOP); i.setFlags(FLAG_ACTIVITY_CLEAR_TOP | FLAG_ACTIVITY_SINGLE_TOP);
TaskStackBuilder t = TaskStackBuilder.create(appContext); TaskStackBuilder t = TaskStackBuilder.create(appContext);
t.addParentStack(ConversationActivity.class); t.addParentStack(ConversationActivity.class);
@@ -197,27 +199,25 @@ Service, EventListener {
public void showGroupPostNotification(GroupId g) { public void showGroupPostNotification(GroupId g) {
synchLock.lock(); synchLock.lock();
try{ try {
Integer count = groupCounts.get(g); Integer count = groupCounts.get(g);
if(count == null) groupCounts.put(g, 1); if(count == null) groupCounts.put(g, 1);
else groupCounts.put(g, count + 1); else groupCounts.put(g, count + 1);
groupTotal++; groupTotal++;
updateGroupPostNotification(); updateGroupPostNotification();
} } finally {
finally{
synchLock.unlock(); synchLock.unlock();
} }
} }
public void clearGroupPostNotification(GroupId g) { public void clearGroupPostNotification(GroupId g) {
synchLock.lock(); synchLock.lock();
try{ try {
Integer count = groupCounts.remove(g); Integer count = groupCounts.remove(g);
if(count == null) return; // Already cleared if(count == null) return; // Already cleared
groupTotal -= count; groupTotal -= count;
updateGroupPostNotification(); updateGroupPostNotification();
} } finally {
finally{
synchLock.unlock(); synchLock.unlock();
} }
} }
@@ -245,8 +245,8 @@ Service, EventListener {
Intent i = new Intent(appContext, GroupActivity.class); Intent i = new Intent(appContext, GroupActivity.class);
GroupId g = groupCounts.keySet().iterator().next(); GroupId g = groupCounts.keySet().iterator().next();
i.putExtra("briar.GROUP_ID", g.getBytes()); i.putExtra("briar.GROUP_ID", g.getBytes());
String groupIdString = new String(g.getBytes()); String idHex = StringUtils.toHexString(g.getBytes());
i.setData(Uri.parse(String.format("content://org.brairproject.group/%s", groupIdString))); i.setData(Uri.parse(GROUP_URI + "/" + idHex));
i.setFlags(FLAG_ACTIVITY_CLEAR_TOP | FLAG_ACTIVITY_SINGLE_TOP); i.setFlags(FLAG_ACTIVITY_CLEAR_TOP | FLAG_ACTIVITY_SINGLE_TOP);
TaskStackBuilder t = TaskStackBuilder.create(appContext); TaskStackBuilder t = TaskStackBuilder.create(appContext);
t.addParentStack(GroupActivity.class); t.addParentStack(GroupActivity.class);
@@ -274,14 +274,13 @@ Service, EventListener {
public void clearNotifications() { public void clearNotifications() {
synchLock.lock(); synchLock.lock();
try{ try {
contactCounts.clear(); contactCounts.clear();
groupCounts.clear(); groupCounts.clear();
privateTotal = groupTotal = 0; privateTotal = groupTotal = 0;
clearPrivateMessageNotification(); clearPrivateMessageNotification();
clearGroupPostNotification(); clearGroupPostNotification();
} } finally {
finally{
synchLock.unlock(); synchLock.unlock();
} }
} }

View File

@@ -24,7 +24,7 @@ class ReferenceManagerImpl implements ReferenceManager {
public <T> T getReference(long handle, Class<T> c) { public <T> T getReference(long handle, Class<T> c) {
synchLock.lock(); synchLock.lock();
try{ try {
Map<Long, Object> innerMap = outerMap.get(c); Map<Long, Object> innerMap = outerMap.get(c);
if(innerMap == null) { if(innerMap == null) {
if(LOG.isLoggable(INFO)) if(LOG.isLoggable(INFO))
@@ -35,16 +35,15 @@ class ReferenceManagerImpl implements ReferenceManager {
LOG.info(innerMap.size() + " handles for " + c.getName()); LOG.info(innerMap.size() + " handles for " + c.getName());
Object o = innerMap.get(handle); Object o = innerMap.get(handle);
return c.cast(o); return c.cast(o);
} } finally {
finally{
synchLock.unlock(); synchLock.unlock();
} }
} }
public <T> long putReference(T reference, Class<T> c) { public <T> long putReference(T reference, Class<T> c) {
synchLock.lock(); synchLock.lock();
try{ try {
Map<Long, Object> innerMap = outerMap.get(c); Map<Long, Object> innerMap = outerMap.get(c);
if(innerMap == null) { if(innerMap == null) {
innerMap = new HashMap<Long, Object>(); innerMap = new HashMap<Long, Object>();
@@ -57,15 +56,14 @@ class ReferenceManagerImpl implements ReferenceManager {
" after put"); " after put");
} }
return handle; return handle;
} } finally {
finally{
synchLock.unlock(); synchLock.unlock();
} }
} }
public <T> T removeReference(long handle, Class<T> c) { public <T> T removeReference(long handle, Class<T> c) {
synchLock.lock(); synchLock.lock();
try{ try {
Map<Long, Object> innerMap = outerMap.get(c); Map<Long, Object> innerMap = outerMap.get(c);
if(innerMap == null) return null; if(innerMap == null) return null;
Object o = innerMap.remove(handle); Object o = innerMap.remove(handle);
@@ -75,8 +73,7 @@ class ReferenceManagerImpl implements ReferenceManager {
" after remove"); " after remove");
} }
return c.cast(o); return c.cast(o);
} } finally {
finally{
synchLock.unlock(); synchLock.unlock();
} }

View File

@@ -34,9 +34,6 @@ class AndroidLocationUtils implements LocationUtils {
* <ul> * <ul>
* <li>Phone network. This works even when no SIM card is inserted, or a * <li>Phone network. This works even when no SIM card is inserted, or a
* foreign SIM card is inserted.</li> * foreign SIM card is inserted.</li>
* <li><del>Location service (GPS/WiFi/etc).</del> <em>This is disabled for
* now, until we figure out an offline method of converting a long/lat
* into a country code, that doesn't involve a network call.</em>
* <li>SIM card. This is only an heuristic and assumes the user is not * <li>SIM card. This is only an heuristic and assumes the user is not
* roaming.</li> * roaming.</li>
* <li>User locale. This is an even worse heuristic.</li> * <li>User locale. This is an even worse heuristic.</li>

View File

@@ -25,8 +25,8 @@ class FortunaGenerator {
private final byte[] counter = new byte[BLOCK_BYTES]; private final byte[] counter = new byte[BLOCK_BYTES];
private final byte[] buffer = new byte[BLOCK_BYTES]; private final byte[] buffer = new byte[BLOCK_BYTES];
private final byte[] newKey = new byte[KEY_BYTES]; private final byte[] newKey = new byte[KEY_BYTES];
private final Lock synchLock = new ReentrantLock(); private final Lock synchLock = new ReentrantLock();
FortunaGenerator(byte[] seed) { FortunaGenerator(byte[] seed) {
reseed(seed); reseed(seed);
@@ -34,13 +34,12 @@ class FortunaGenerator {
void reseed(byte[] seed) { void reseed(byte[] seed) {
synchLock.lock(); synchLock.lock();
try{ try {
digest.update(key); digest.update(key);
digest.update(seed); digest.update(seed);
digest.digest(key, 0, KEY_BYTES); digest.digest(key, 0, KEY_BYTES);
incrementCounter(); incrementCounter();
} } finally {
finally{
synchLock.unlock(); synchLock.unlock();
} }
@@ -49,26 +48,24 @@ class FortunaGenerator {
// Package access for testing // Package access for testing
void incrementCounter() { void incrementCounter() {
synchLock.lock(); synchLock.lock();
try{ try {
counter[0]++; counter[0]++;
for(int i = 0; counter[i] == 0; i++) { for(int i = 0; counter[i] == 0; i++) {
if(i + 1 == BLOCK_BYTES) if(i + 1 == BLOCK_BYTES)
throw new RuntimeException("Counter exhausted"); throw new RuntimeException("Counter exhausted");
counter[i + 1]++; counter[i + 1]++;
} }
} } finally {
finally{
synchLock.unlock(); synchLock.unlock();
} }
} }
// Package access for testing // Package access for testing
byte[] getCounter() { byte[] getCounter() {
synchLock.lock(); synchLock.lock();
try{ try {
return counter; return counter;
} } finally {
finally{
synchLock.unlock(); synchLock.unlock();
} }
@@ -76,7 +73,7 @@ class FortunaGenerator {
int nextBytes(byte[] dest, int off, int len) { int nextBytes(byte[] dest, int off, int len) {
synchLock.lock(); synchLock.lock();
try{ try {
// Don't write more than the maximum number of bytes in one request // Don't write more than the maximum number of bytes in one request
if(len > MAX_BYTES_PER_REQUEST) len = MAX_BYTES_PER_REQUEST; if(len > MAX_BYTES_PER_REQUEST) len = MAX_BYTES_PER_REQUEST;
cipher.init(true, new KeyParameter(key)); cipher.init(true, new KeyParameter(key));
@@ -105,8 +102,7 @@ class FortunaGenerator {
for(int i = 0; i < KEY_BYTES; i++) newKey[i] = 0; for(int i = 0; i < KEY_BYTES; i++) newKey[i] = 0;
// Return the number of bytes written // Return the number of bytes written
return len; return len;
} } finally {
finally{
synchLock.unlock(); synchLock.unlock();
} }
} }

View File

@@ -13,7 +13,7 @@ class PseudoRandomImpl implements PseudoRandom {
private byte[] state; private byte[] state;
private int offset; private int offset;
private final Lock synchLock = new ReentrantLock(); private final Lock synchLock = new ReentrantLock();
PseudoRandomImpl(MessageDigest messageDigest, int seed1, int seed2) { PseudoRandomImpl(MessageDigest messageDigest, int seed1, int seed2) {
@@ -28,7 +28,7 @@ class PseudoRandomImpl implements PseudoRandom {
public byte[] nextBytes(int bytes) { public byte[] nextBytes(int bytes) {
synchLock.lock(); synchLock.lock();
try{ try {
byte[] b = new byte[bytes]; byte[] b = new byte[bytes];
int half = state.length / 2; int half = state.length / 2;
int off = 0, len = b.length, available = half - offset; int off = 0, len = b.length, available = half - offset;
@@ -44,8 +44,7 @@ class PseudoRandomImpl implements PseudoRandom {
System.arraycopy(state, offset, b, off, len); System.arraycopy(state, offset, b, off, len);
offset += len; offset += len;
return b; return b;
} } finally {
finally{
synchLock.unlock(); synchLock.unlock();
} }
} }

View File

@@ -325,7 +325,7 @@ abstract class JdbcDatabase implements Database<Connection> {
protected abstract Connection createConnection() throws SQLException; protected abstract Connection createConnection() throws SQLException;
protected abstract void flushBuffersToDisk(Statement s) throws SQLException; protected abstract void flushBuffersToDisk(Statement s) throws SQLException;
private final Lock connectionsLock = new ReentrantLock(); private final Lock connectionsLock = new ReentrantLock();
private final Condition connectionsChanged = connectionsLock.newCondition(); private final Condition connectionsChanged = connectionsLock.newCondition();
@@ -441,11 +441,10 @@ abstract class JdbcDatabase implements Database<Connection> {
try { try {
if(closed) throw new DbClosedException(); if(closed) throw new DbClosedException();
txn = connections.poll(); txn = connections.poll();
} } finally {
finally{
connectionsLock.unlock(); connectionsLock.unlock();
} }
try { try {
if(txn == null) { if(txn == null) {
// Open a new connection // Open a new connection
@@ -455,8 +454,7 @@ abstract class JdbcDatabase implements Database<Connection> {
connectionsLock.lock(); connectionsLock.lock();
try { try {
openConnections++; openConnections++;
} } finally {
finally{
connectionsLock.unlock(); connectionsLock.unlock();
} }
} }
@@ -474,8 +472,7 @@ abstract class JdbcDatabase implements Database<Connection> {
try { try {
connections.add(txn); connections.add(txn);
connectionsChanged.signalAll(); connectionsChanged.signalAll();
} } finally {
finally{
connectionsLock.unlock(); connectionsLock.unlock();
} }
} catch(SQLException e) { } catch(SQLException e) {
@@ -491,10 +488,10 @@ abstract class JdbcDatabase implements Database<Connection> {
try { try {
openConnections--; openConnections--;
connectionsChanged.signalAll(); connectionsChanged.signalAll();
} } finally {
finally{
connectionsLock.unlock(); connectionsLock.unlock();
} } }
}
} }
public void commitTransaction(Connection txn) throws DbException { public void commitTransaction(Connection txn) throws DbException {
@@ -509,11 +506,10 @@ abstract class JdbcDatabase implements Database<Connection> {
throw new DbException(e); throw new DbException(e);
} }
connectionsLock.lock(); connectionsLock.lock();
try{ try {
connections.add(txn); connections.add(txn);
connectionsChanged.signalAll(); connectionsChanged.signalAll();
} } finally {
finally{
connectionsLock.unlock(); connectionsLock.unlock();
} }
} }
@@ -529,7 +525,7 @@ abstract class JdbcDatabase implements Database<Connection> {
protected void closeAllConnections() throws SQLException { protected void closeAllConnections() throws SQLException {
boolean interrupted = false; boolean interrupted = false;
connectionsLock.lock(); connectionsLock.lock();
try{ try {
closed = true; closed = true;
for(Connection c : connections) c.close(); for(Connection c : connections) c.close();
openConnections -= connections.size(); openConnections -= connections.size();
@@ -545,11 +541,10 @@ abstract class JdbcDatabase implements Database<Connection> {
openConnections -= connections.size(); openConnections -= connections.size();
connections.clear(); connections.clear();
} }
} } finally {
finally{
connectionsLock.unlock(); connectionsLock.unlock();
} }
if(interrupted) Thread.currentThread().interrupt(); if(interrupted) Thread.currentThread().interrupt();
} }

View File

@@ -62,7 +62,7 @@ class ConnectorGroup extends Thread implements InvitationTask {
private final Collection<InvitationListener> listeners; private final Collection<InvitationListener> listeners;
private final AtomicBoolean connected; private final AtomicBoolean connected;
private final CountDownLatch localConfirmationLatch; private final CountDownLatch localConfirmationLatch;
private final Lock synchLock = new ReentrantLock(); private final Lock synchLock = new ReentrantLock();
/*The state that's accessed in addListener() after /*The state that's accessed in addListener() after
@@ -107,14 +107,14 @@ class ConnectorGroup extends Thread implements InvitationTask {
public InvitationState addListener(InvitationListener l) { public InvitationState addListener(InvitationListener l) {
synchLock.lock(); synchLock.lock();
try{ try {
listeners.add(l); listeners.add(l);
return new InvitationState(localInvitationCode, remoteInvitationCode, return new InvitationState(localInvitationCode,
localConfirmationCode, remoteConfirmationCode, connected.get(), remoteInvitationCode, localConfirmationCode,
connectionFailed, localCompared, remoteCompared, localMatched, remoteConfirmationCode, connected.get(), connectionFailed,
remoteMatched, remoteName); localCompared, remoteCompared, localMatched, remoteMatched,
} remoteName);
finally{ } finally {
synchLock.unlock(); synchLock.unlock();
} }
} }
@@ -140,8 +140,7 @@ class ConnectorGroup extends Thread implements InvitationTask {
synchLock.lock(); synchLock.lock();
try { try {
connectionFailed = true; connectionFailed = true;
} } finally {
finally{
synchLock.unlock(); synchLock.unlock();
} }
for(InvitationListener l : listeners) l.connectionFailed(); for(InvitationListener l : listeners) l.connectionFailed();
@@ -177,8 +176,7 @@ class ConnectorGroup extends Thread implements InvitationTask {
synchLock.lock(); synchLock.lock();
try { try {
connectionFailed = true; connectionFailed = true;
} } finally {
finally{
synchLock.unlock(); synchLock.unlock();
} }
for(InvitationListener l : listeners) l.connectionFailed(); for(InvitationListener l : listeners) l.connectionFailed();
@@ -212,8 +210,7 @@ class ConnectorGroup extends Thread implements InvitationTask {
try { try {
localCompared = true; localCompared = true;
localMatched = true; localMatched = true;
} } finally {
finally{
synchLock.unlock(); synchLock.unlock();
} }
localConfirmationLatch.countDown(); localConfirmationLatch.countDown();
@@ -224,8 +221,7 @@ class ConnectorGroup extends Thread implements InvitationTask {
try { try {
localCompared = true; localCompared = true;
localMatched = false; localMatched = false;
} } finally {
finally{
synchLock.unlock(); synchLock.unlock();
} }
localConfirmationLatch.countDown(); localConfirmationLatch.countDown();
@@ -243,8 +239,7 @@ class ConnectorGroup extends Thread implements InvitationTask {
try { try {
localConfirmationCode = localCode; localConfirmationCode = localCode;
remoteConfirmationCode = remoteCode; remoteConfirmationCode = remoteCode;
} } finally {
finally{
synchLock.unlock(); synchLock.unlock();
} }
for(InvitationListener l : listeners) for(InvitationListener l : listeners)
@@ -260,8 +255,7 @@ class ConnectorGroup extends Thread implements InvitationTask {
synchLock.lock(); synchLock.lock();
try { try {
return localMatched; return localMatched;
} } finally {
finally{
synchLock.unlock(); synchLock.unlock();
} }
} }
@@ -271,8 +265,7 @@ class ConnectorGroup extends Thread implements InvitationTask {
try { try {
remoteCompared = true; remoteCompared = true;
remoteMatched = true; remoteMatched = true;
} } finally {
finally{
synchLock.unlock(); synchLock.unlock();
} }
for(InvitationListener l : listeners) l.remoteConfirmationSucceeded(); for(InvitationListener l : listeners) l.remoteConfirmationSucceeded();
@@ -283,8 +276,7 @@ class ConnectorGroup extends Thread implements InvitationTask {
try { try {
remoteCompared = true; remoteCompared = true;
remoteMatched = false; remoteMatched = false;
} } finally {
finally{
synchLock.unlock(); synchLock.unlock();
} }
for(InvitationListener l : listeners) l.remoteConfirmationFailed(); for(InvitationListener l : listeners) l.remoteConfirmationFailed();
@@ -295,8 +287,7 @@ class ConnectorGroup extends Thread implements InvitationTask {
synchLock.lock(); synchLock.lock();
try { try {
remoteName = name; remoteName = name;
} } finally {
finally{
synchLock.unlock(); synchLock.unlock();
} }
for(InvitationListener l : listeners) for(InvitationListener l : listeners)

View File

@@ -12,7 +12,7 @@ class ShutdownManagerImpl implements ShutdownManager {
protected final Map<Integer, Thread> hooks; protected final Map<Integer, Thread> hooks;
private int nextHandle = 0; private int nextHandle = 0;
private final Lock synchLock = new ReentrantLock(); private final Lock synchLock = new ReentrantLock();
ShutdownManagerImpl() { ShutdownManagerImpl() {
@@ -21,14 +21,13 @@ class ShutdownManagerImpl implements ShutdownManager {
public int addShutdownHook(Runnable r) { public int addShutdownHook(Runnable r) {
synchLock.lock(); synchLock.lock();
try{ try {
int handle = nextHandle++; int handle = nextHandle++;
Thread hook = createThread(r); Thread hook = createThread(r);
hooks.put(handle, hook); hooks.put(handle, hook);
Runtime.getRuntime().addShutdownHook(hook); Runtime.getRuntime().addShutdownHook(hook);
return handle; return handle;
} } finally {
finally{
synchLock.unlock(); synchLock.unlock();
} }
@@ -40,12 +39,11 @@ class ShutdownManagerImpl implements ShutdownManager {
public boolean removeShutdownHook(int handle) { public boolean removeShutdownHook(int handle) {
synchLock.lock(); synchLock.lock();
try{ try {
Thread hook = hooks.remove(handle); Thread hook = hooks.remove(handle);
if(hook == null) return false; if(hook == null) return false;
else return Runtime.getRuntime().removeShutdownHook(hook); else return Runtime.getRuntime().removeShutdownHook(hook);
} } finally {
finally{
synchLock.unlock(); synchLock.unlock();
} }

View File

@@ -9,9 +9,9 @@ import org.briarproject.api.messaging.Group;
import org.briarproject.api.messaging.GroupFactory; import org.briarproject.api.messaging.GroupFactory;
import org.briarproject.api.messaging.MessageFactory; import org.briarproject.api.messaging.MessageFactory;
import org.briarproject.api.messaging.MessageVerifier; import org.briarproject.api.messaging.MessageVerifier;
import org.briarproject.api.messaging.MessagingSessionFactory;
import org.briarproject.api.messaging.PacketReaderFactory; import org.briarproject.api.messaging.PacketReaderFactory;
import org.briarproject.api.messaging.PacketWriterFactory; import org.briarproject.api.messaging.PacketWriterFactory;
import org.briarproject.api.messaging.MessagingSessionFactory;
import org.briarproject.api.messaging.SubscriptionUpdate; import org.briarproject.api.messaging.SubscriptionUpdate;
import org.briarproject.api.messaging.UnverifiedMessage; import org.briarproject.api.messaging.UnverifiedMessage;
import org.briarproject.api.serial.StructReader; import org.briarproject.api.serial.StructReader;

View File

@@ -31,7 +31,7 @@ class ConnectionRegistryImpl implements ConnectionRegistry {
private final Map<TransportId, Map<ContactId, Integer>> connections; private final Map<TransportId, Map<ContactId, Integer>> connections;
// Locking: this // Locking: this
private final Map<ContactId, Integer> contactCounts; private final Map<ContactId, Integer> contactCounts;
private final Lock synchLock = new ReentrantLock(); private final Lock synchLock = new ReentrantLock();
@Inject @Inject
@@ -61,8 +61,7 @@ class ConnectionRegistryImpl implements ConnectionRegistry {
} else { } else {
contactCounts.put(c, count + 1); contactCounts.put(c, count + 1);
} }
} } finally {
finally{
synchLock.unlock(); synchLock.unlock();
} }
@@ -94,8 +93,7 @@ class ConnectionRegistryImpl implements ConnectionRegistry {
} else { } else {
contactCounts.put(c, count - 1); contactCounts.put(c, count - 1);
} }
} } finally {
finally{
synchLock.unlock(); synchLock.unlock();
} }
@@ -108,14 +106,13 @@ class ConnectionRegistryImpl implements ConnectionRegistry {
public Collection<ContactId> getConnectedContacts( public Collection<ContactId> getConnectedContacts(
TransportId t) { TransportId t) {
synchLock.lock(); synchLock.lock();
try{ try {
Map<ContactId, Integer> m = connections.get(t); Map<ContactId, Integer> m = connections.get(t);
if(m == null) return Collections.emptyList(); if(m == null) return Collections.emptyList();
List<ContactId> ids = new ArrayList<ContactId>(m.keySet()); List<ContactId> ids = new ArrayList<ContactId>(m.keySet());
if(LOG.isLoggable(INFO)) LOG.info(ids.size() + " contacts connected"); if(LOG.isLoggable(INFO)) LOG.info(ids.size() + " contacts connected");
return Collections.unmodifiableList(ids); return Collections.unmodifiableList(ids);
} } finally {
finally{
synchLock.unlock(); synchLock.unlock();
} }
@@ -123,10 +120,9 @@ class ConnectionRegistryImpl implements ConnectionRegistry {
public boolean isConnected(ContactId c) { public boolean isConnected(ContactId c) {
synchLock.lock(); synchLock.lock();
try{ try {
return contactCounts.containsKey(c); return contactCounts.containsKey(c);
} } finally {
finally{
synchLock.unlock(); synchLock.unlock();
} }

View File

@@ -1,11 +1,12 @@
package org.briarproject.reliability; package org.briarproject.reliability;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import java.io.IOException; import java.io.IOException;
import java.util.Comparator; import java.util.Comparator;
import java.util.Iterator; import java.util.Iterator;
import java.util.SortedSet; import java.util.SortedSet;
import java.util.TreeSet; import java.util.TreeSet;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock; import java.util.concurrent.locks.ReentrantLock;
@@ -38,12 +39,12 @@ class Receiver implements ReadHandler {
Data read() throws IOException, InterruptedException { Data read() throws IOException, InterruptedException {
synchLock.lock(); synchLock.lock();
try{ try {
long now = clock.currentTimeMillis(), end = now + READ_TIMEOUT; long now = clock.currentTimeMillis(), end = now + READ_TIMEOUT;
while(now < end && valid) { while(now < end && valid) {
if(dataFrames.isEmpty()) { if(dataFrames.isEmpty()) {
// Wait for a data frame // Wait for a data frame
dataFrameAvailable.await(end - now, TimeUnit.MILLISECONDS); dataFrameAvailable.await(end - now, MILLISECONDS);
} else { } else {
Data d = dataFrames.first(); Data d = dataFrames.first();
if(d.getSequenceNumber() == nextSequenceNumber) { if(d.getSequenceNumber() == nextSequenceNumber) {
@@ -55,15 +56,14 @@ class Receiver implements ReadHandler {
return d; return d;
} else { } else {
// Wait for the next in-order data frame // Wait for the next in-order data frame
dataFrameAvailable.await(end - now, TimeUnit.MILLISECONDS); dataFrameAvailable.await(end - now, MILLISECONDS);
} }
} }
now = clock.currentTimeMillis(); now = clock.currentTimeMillis();
} }
if(valid) throw new IOException("Read timed out"); if(valid) throw new IOException("Read timed out");
throw new IOException("Connection closed"); throw new IOException("Connection closed");
} } finally {
finally{
synchLock.unlock(); synchLock.unlock();
} }
} }
@@ -73,8 +73,7 @@ class Receiver implements ReadHandler {
synchLock.lock(); synchLock.lock();
try { try {
dataFrameAvailable.signalAll(); dataFrameAvailable.signalAll();
} } finally {
finally{
synchLock.unlock(); synchLock.unlock();
} }
} }
@@ -97,7 +96,7 @@ class Receiver implements ReadHandler {
private void handleData(byte[] b) throws IOException { private void handleData(byte[] b) throws IOException {
synchLock.lock(); synchLock.lock();
try{ try {
if(b.length < Data.MIN_LENGTH || b.length > Data.MAX_LENGTH) { if(b.length < Data.MIN_LENGTH || b.length > Data.MAX_LENGTH) {
// Ignore data frame with invalid length // Ignore data frame with invalid length
return; return;
@@ -134,8 +133,7 @@ class Receiver implements ReadHandler {
} }
// Acknowledge the data frame even if it's a duplicate // Acknowledge the data frame even if it's a duplicate
sender.sendAck(sequenceNumber, windowSize); sender.sendAck(sequenceNumber, windowSize);
} } finally {
finally{
synchLock.unlock(); synchLock.unlock();
} }
} }

View File

@@ -1,11 +1,12 @@
package org.briarproject.reliability; package org.briarproject.reliability;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import java.io.IOException; import java.io.IOException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Iterator; import java.util.Iterator;
import java.util.LinkedList; import java.util.LinkedList;
import java.util.List; import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock; import java.util.concurrent.locks.ReentrantLock;
@@ -101,9 +102,9 @@ class Sender {
// Don't accept an unreasonably large window size // Don't accept an unreasonably large window size
windowSize = Math.min(a.getWindowSize(), MAX_WINDOW_SIZE); windowSize = Math.min(a.getWindowSize(), MAX_WINDOW_SIZE);
// If space has become available, notify any waiting writers // If space has become available, notify any waiting writers
if(windowSize > oldWindowSize || foundIndex != -1) sendWindowAvailable.signalAll(); if(windowSize > oldWindowSize || foundIndex != -1)
} sendWindowAvailable.signalAll();
finally{ } finally {
synchLock.unlock(); synchLock.unlock();
} }
// Fast retransmission // Fast retransmission
@@ -145,8 +146,7 @@ class Sender {
} }
} }
} }
} } finally {
finally{
synchLock.unlock(); synchLock.unlock();
} }
// Send a window probe if necessary // Send a window probe if necessary
@@ -171,7 +171,7 @@ class Sender {
long now = clock.currentTimeMillis(), end = now + WRITE_TIMEOUT; long now = clock.currentTimeMillis(), end = now + WRITE_TIMEOUT;
while(now < end && outstandingBytes + payloadLength >= windowSize) { while(now < end && outstandingBytes + payloadLength >= windowSize) {
dataWaiting = true; dataWaiting = true;
sendWindowAvailable.await(end - now, TimeUnit.MILLISECONDS); sendWindowAvailable.await(end - now, MILLISECONDS);
now = clock.currentTimeMillis(); now = clock.currentTimeMillis();
} }
if(outstandingBytes + payloadLength >= windowSize) if(outstandingBytes + payloadLength >= windowSize)
@@ -179,8 +179,7 @@ class Sender {
outstanding.add(new Outstanding(d, now)); outstanding.add(new Outstanding(d, now));
outstandingBytes += payloadLength; outstandingBytes += payloadLength;
dataWaiting = false; dataWaiting = false;
} } finally {
finally{
synchLock.unlock(); synchLock.unlock();
} }
writeHandler.handleWrite(d.getBuffer()); writeHandler.handleWrite(d.getBuffer());
@@ -188,10 +187,10 @@ class Sender {
void flush() throws IOException, InterruptedException { void flush() throws IOException, InterruptedException {
synchLock.lock(); synchLock.lock();
try{ try {
while(dataWaiting || !outstanding.isEmpty()) sendWindowAvailable.await(); while(dataWaiting || !outstanding.isEmpty())
} sendWindowAvailable.await();
finally{ } finally {
synchLock.unlock(); synchLock.unlock();
} }
} }

View File

@@ -78,7 +78,7 @@ class KeyManagerImpl extends TimerTask implements KeyManager, EventListener {
synchLock.lock(); synchLock.lock();
try { try {
eventBus.addListener(this); eventBus.addListener(this);
// Load the temporary secrets and transport latencies from the database // Load the temporary secrets and transport latencies from the DB
Collection<TemporarySecret> secrets; Collection<TemporarySecret> secrets;
try { try {
secrets = db.getSecrets(); secrets = db.getSecrets();
@@ -89,15 +89,18 @@ class KeyManagerImpl extends TimerTask implements KeyManager, EventListener {
} }
// Work out what phase of its lifecycle each secret is in // Work out what phase of its lifecycle each secret is in
long now = clock.currentTimeMillis(); long now = clock.currentTimeMillis();
Collection<TemporarySecret> dead = assignSecretsToMaps(now, secrets); Collection<TemporarySecret> dead =
assignSecretsToMaps(now, secrets);
// Replace any dead secrets // Replace any dead secrets
Collection<TemporarySecret> created = replaceDeadSecrets(now, dead); Collection<TemporarySecret> created = replaceDeadSecrets(now, dead);
if(!created.isEmpty()) { if(!created.isEmpty()) {
// Store any secrets that have been created, removing any dead ones // Store any secrets that have been created,
// removing any dead ones
try { try {
db.addSecrets(created); db.addSecrets(created);
} catch(DbException e) { } catch(DbException e) {
if(LOG.isLoggable(WARNING)) LOG.log(WARNING, e.toString(), e); if(LOG.isLoggable(WARNING))
LOG.log(WARNING, e.toString(), e);
return false; return false;
} }
} }
@@ -109,10 +112,10 @@ class KeyManagerImpl extends TimerTask implements KeyManager, EventListener {
for(TemporarySecret s : newSecrets.values()) for(TemporarySecret s : newSecrets.values())
tagRecogniser.addSecret(s); tagRecogniser.addSecret(s);
// Schedule periodic key rotation // Schedule periodic key rotation
timer.scheduleAtFixedRate(this, MS_BETWEEN_CHECKS, MS_BETWEEN_CHECKS); timer.scheduleAtFixedRate(this, MS_BETWEEN_CHECKS,
MS_BETWEEN_CHECKS);
return true; return true;
} } finally {
finally{
synchLock.unlock(); synchLock.unlock();
} }
} }
@@ -209,7 +212,7 @@ class KeyManagerImpl extends TimerTask implements KeyManager, EventListener {
public boolean stop() { public boolean stop() {
synchLock.lock(); synchLock.lock();
try{ try {
eventBus.removeListener(this); eventBus.removeListener(this);
timer.cancel(); timer.cancel();
tagRecogniser.removeSecrets(); tagRecogniser.removeSecrets();
@@ -218,8 +221,7 @@ class KeyManagerImpl extends TimerTask implements KeyManager, EventListener {
currentSecrets.clear(); currentSecrets.clear();
newSecrets.clear(); newSecrets.clear();
return true; return true;
} } finally {
finally{
synchLock.unlock(); synchLock.unlock();
} }
} }
@@ -227,7 +229,7 @@ class KeyManagerImpl extends TimerTask implements KeyManager, EventListener {
public StreamContext getStreamContext(ContactId c, public StreamContext getStreamContext(ContactId c,
TransportId t) { TransportId t) {
synchLock.lock(); synchLock.lock();
try{ try {
TemporarySecret s = currentSecrets.get(new EndpointKey(c, t)); TemporarySecret s = currentSecrets.get(new EndpointKey(c, t));
if(s == null) { if(s == null) {
LOG.info("No secret for endpoint"); LOG.info("No secret for endpoint");
@@ -244,10 +246,9 @@ class KeyManagerImpl extends TimerTask implements KeyManager, EventListener {
if(LOG.isLoggable(WARNING)) LOG.log(WARNING, e.toString(), e); if(LOG.isLoggable(WARNING)) LOG.log(WARNING, e.toString(), e);
return null; return null;
} }
byte[] secret = s.getSecret(); byte[] secret = s.getSecret();
return new StreamContext(c, t, secret, streamNumber, s.getAlice()); return new StreamContext(c, t, secret, streamNumber, s.getAlice());
} } finally {
finally{
synchLock.unlock(); synchLock.unlock();
} }
} }
@@ -255,7 +256,7 @@ class KeyManagerImpl extends TimerTask implements KeyManager, EventListener {
public synchronized void endpointAdded(Endpoint ep, int maxLatency, public synchronized void endpointAdded(Endpoint ep, int maxLatency,
byte[] initialSecret) { byte[] initialSecret) {
synchLock.lock(); synchLock.lock();
try{ try {
maxLatencies.put(ep.getTransportId(), maxLatency); maxLatencies.put(ep.getTransportId(), maxLatency);
// Work out which rotation period we're in // Work out which rotation period we're in
long elapsed = clock.currentTimeMillis() - ep.getEpoch(); long elapsed = clock.currentTimeMillis() - ep.getEpoch();
@@ -287,8 +288,7 @@ class KeyManagerImpl extends TimerTask implements KeyManager, EventListener {
tagRecogniser.addSecret(s1); tagRecogniser.addSecret(s1);
tagRecogniser.addSecret(s2); tagRecogniser.addSecret(s2);
tagRecogniser.addSecret(s3); tagRecogniser.addSecret(s3);
} } finally {
finally{
synchLock.unlock(); synchLock.unlock();
} }
} }
@@ -296,8 +296,8 @@ class KeyManagerImpl extends TimerTask implements KeyManager, EventListener {
@Override @Override
public void run() { public void run() {
synchLock.lock(); synchLock.lock();
try{ try {
// Rebuild the maps because we may be running a whole period late // Rebuild the maps because we may be running a whole period late
Collection<TemporarySecret> secrets = new ArrayList<TemporarySecret>(); Collection<TemporarySecret> secrets = new ArrayList<TemporarySecret>();
secrets.addAll(oldSecrets.values()); secrets.addAll(oldSecrets.values());
secrets.addAll(currentSecrets.values()); secrets.addAll(currentSecrets.values());
@@ -327,8 +327,7 @@ class KeyManagerImpl extends TimerTask implements KeyManager, EventListener {
// Pass any secrets that have been created to the recogniser // Pass any secrets that have been created to the recogniser
for(TemporarySecret s : created) tagRecogniser.addSecret(s); for(TemporarySecret s : created) tagRecogniser.addSecret(s);
} }
} } finally {
finally{
synchLock.unlock(); synchLock.unlock();
} }
} }
@@ -401,12 +400,11 @@ class KeyManagerImpl extends TimerTask implements KeyManager, EventListener {
ContactId c = event.getContactId(); ContactId c = event.getContactId();
tagRecogniser.removeSecrets(c); tagRecogniser.removeSecrets(c);
synchLock.lock(); synchLock.lock();
try{ try {
removeSecrets(c, oldSecrets); removeSecrets(c, oldSecrets);
removeSecrets(c, currentSecrets); removeSecrets(c, currentSecrets);
removeSecrets(c, newSecrets); removeSecrets(c, newSecrets);
} } finally {
finally{
synchLock.unlock(); synchLock.unlock();
} }
} }
@@ -425,8 +423,7 @@ class KeyManagerImpl extends TimerTask implements KeyManager, EventListener {
synchLock.lock(); synchLock.lock();
try { try {
maxLatencies.put(event.getTransportId(), event.getMaxLatency()); maxLatencies.put(event.getTransportId(), event.getMaxLatency());
} } finally {
finally{
synchLock.unlock(); synchLock.unlock();
} }
} }
@@ -450,8 +447,7 @@ class KeyManagerImpl extends TimerTask implements KeyManager, EventListener {
removeSecrets(t, oldSecrets); removeSecrets(t, oldSecrets);
removeSecrets(t, currentSecrets); removeSecrets(t, currentSecrets);
removeSecrets(t, newSecrets); removeSecrets(t, newSecrets);
} } finally {
finally{
synchLock.unlock(); synchLock.unlock();
} }
} }

View File

@@ -22,7 +22,7 @@ class TagRecogniserImpl implements TagRecogniser {
private final DatabaseComponent db; private final DatabaseComponent db;
private final Map<TransportId, TransportTagRecogniser> recognisers; private final Map<TransportId, TransportTagRecogniser> recognisers;
private final Lock synchLock = new ReentrantLock(); private final Lock synchLock = new ReentrantLock();
@@ -39,8 +39,7 @@ class TagRecogniserImpl implements TagRecogniser {
synchLock.lock(); synchLock.lock();
try { try {
r = recognisers.get(t); r = recognisers.get(t);
} } finally {
finally{
synchLock.unlock(); synchLock.unlock();
} }
if(r == null) return null; if(r == null) return null;
@@ -57,8 +56,7 @@ class TagRecogniserImpl implements TagRecogniser {
r = new TransportTagRecogniser(crypto, db, t); r = new TransportTagRecogniser(crypto, db, t);
recognisers.put(t, r); recognisers.put(t, r);
} }
} } finally {
finally{
synchLock.unlock(); synchLock.unlock();
} }
r.addSecret(s); r.addSecret(s);
@@ -69,8 +67,7 @@ class TagRecogniserImpl implements TagRecogniser {
synchLock.lock(); synchLock.lock();
try { try {
r = recognisers.get(t); r = recognisers.get(t);
} } finally {
finally{
synchLock.unlock(); synchLock.unlock();
} }
if(r != null) r.removeSecret(c, period); if(r != null) r.removeSecret(c, period);
@@ -78,21 +75,19 @@ class TagRecogniserImpl implements TagRecogniser {
public void removeSecrets(ContactId c) { public void removeSecrets(ContactId c) {
synchLock.lock(); synchLock.lock();
try{ try {
for(TransportTagRecogniser r : recognisers.values()) for(TransportTagRecogniser r : recognisers.values())
r.removeSecrets(c); r.removeSecrets(c);
} } finally {
finally{
synchLock.unlock(); synchLock.unlock();
} }
} }
public void removeSecrets(TransportId t) { public void removeSecrets(TransportId t) {
synchLock.lock(); synchLock.lock();
try{ try {
recognisers.remove(t); recognisers.remove(t);
} } finally {
finally{
synchLock.unlock(); synchLock.unlock();
} }
@@ -100,11 +95,10 @@ class TagRecogniserImpl implements TagRecogniser {
public void removeSecrets() { public void removeSecrets() {
synchLock.lock(); synchLock.lock();
try{ try {
for(TransportTagRecogniser r : recognisers.values()) for(TransportTagRecogniser r : recognisers.values())
r.removeSecrets(); r.removeSecrets();
} } finally {
finally{
synchLock.unlock(); synchLock.unlock();
} }

View File

@@ -45,7 +45,7 @@ class TransportTagRecogniser {
StreamContext recogniseTag(byte[] tag) throws DbException { StreamContext recogniseTag(byte[] tag) throws DbException {
synchLock.lock(); synchLock.lock();
try{ try {
TagContext t = tagMap.remove(new Bytes(tag)); TagContext t = tagMap.remove(new Bytes(tag));
if(t == null) return null; // The tag was not expected if(t == null) return null; // The tag was not expected
// Update the reordering window and the expected tags // Update the reordering window and the expected tags
@@ -65,17 +65,16 @@ class TransportTagRecogniser {
// Store the updated reordering window in the DB // Store the updated reordering window in the DB
db.setReorderingWindow(t.contactId, transportId, t.period, db.setReorderingWindow(t.contactId, transportId, t.period,
t.window.getCentre(), t.window.getBitmap()); t.window.getCentre(), t.window.getBitmap());
return new StreamContext(t.contactId, transportId, t.secret, return new StreamContext(t.contactId, transportId, t.secret,
t.streamNumber, t.alice); t.streamNumber, t.alice);
} } finally {
finally{
synchLock.unlock(); synchLock.unlock();
} }
} }
void addSecret(TemporarySecret s) { void addSecret(TemporarySecret s) {
synchLock.lock(); synchLock.lock();
try{ try {
ContactId contactId = s.getContactId(); ContactId contactId = s.getContactId();
boolean alice = s.getAlice(); boolean alice = s.getAlice();
long period = s.getPeriod(); long period = s.getPeriod();
@@ -96,21 +95,19 @@ class TransportTagRecogniser {
// Create a removal context to remove the window and the tags later // Create a removal context to remove the window and the tags later
RemovalContext r = new RemovalContext(window, secret, alice); RemovalContext r = new RemovalContext(window, secret, alice);
removalMap.put(new RemovalKey(contactId, period), r); removalMap.put(new RemovalKey(contactId, period), r);
} } finally {
finally{
synchLock.unlock(); synchLock.unlock();
} }
} }
void removeSecret(ContactId contactId, long period) { void removeSecret(ContactId contactId, long period) {
synchLock.lock(); synchLock.lock();
try{ try {
RemovalKey k = new RemovalKey(contactId, period); RemovalKey k = new RemovalKey(contactId, period);
RemovalContext removed = removalMap.remove(k); RemovalContext removed = removalMap.remove(k);
if(removed == null) throw new IllegalArgumentException(); if(removed == null) throw new IllegalArgumentException();
removeSecret(removed); removeSecret(removed);
} } finally {
finally{
synchLock.unlock(); synchLock.unlock();
} }
} }
@@ -128,25 +125,24 @@ class TransportTagRecogniser {
void removeSecrets(ContactId c) { void removeSecrets(ContactId c) {
synchLock.lock(); synchLock.lock();
try{ try {
Collection<RemovalKey> keysToRemove = new ArrayList<RemovalKey>(); Collection<RemovalKey> keysToRemove = new ArrayList<RemovalKey>();
for(RemovalKey k : removalMap.keySet()) for(RemovalKey k : removalMap.keySet())
if(k.contactId.equals(c)) keysToRemove.add(k); if(k.contactId.equals(c)) keysToRemove.add(k);
for(RemovalKey k : keysToRemove) removeSecret(k.contactId, k.period); for(RemovalKey k : keysToRemove)
} removeSecret(k.contactId, k.period);
finally{ } finally {
synchLock.unlock(); synchLock.unlock();
} }
} }
void removeSecrets() { void removeSecrets() {
synchLock.lock(); synchLock.lock();
try{ try {
for(RemovalContext r : removalMap.values()) removeSecret(r); for(RemovalContext r : removalMap.values()) removeSecret(r);
assert tagMap.isEmpty(); assert tagMap.isEmpty();
removalMap.clear(); removalMap.clear();
} } finally {
finally{
synchLock.unlock(); synchLock.unlock();
} }
} }

View File

@@ -1,7 +1,8 @@
package org.briarproject.util; package org.briarproject.util;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import java.util.concurrent.CountDownLatch; import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference; import java.util.concurrent.atomic.AtomicReference;
public class LatchedReference<T> { public class LatchedReference<T> {
@@ -23,7 +24,7 @@ public class LatchedReference<T> {
} }
public T waitForReference(long timeout) throws InterruptedException { public T waitForReference(long timeout) throws InterruptedException {
latch.await(timeout, TimeUnit.MILLISECONDS); latch.await(timeout, MILLISECONDS);
return reference.get(); return reference.get();
} }
} }

View File

@@ -40,7 +40,7 @@ class WindowsShutdownManagerImpl extends ShutdownManagerImpl {
private final Map<String, Object> options; private final Map<String, Object> options;
private boolean initialised = false; private boolean initialised = false;
private final Lock synchLock = new ReentrantLock(); private final Lock synchLock = new ReentrantLock();
@@ -58,8 +58,7 @@ class WindowsShutdownManagerImpl extends ShutdownManagerImpl {
try { try {
if(!initialised) initialise(); if(!initialised) initialise();
return super.addShutdownHook(r); return super.addShutdownHook(r);
} } finally {
finally{
synchLock.unlock(); synchLock.unlock();
} }
} }
@@ -95,8 +94,7 @@ class WindowsShutdownManagerImpl extends ShutdownManagerImpl {
} }
} }
if(interrupted) Thread.currentThread().interrupt(); if(interrupted) Thread.currentThread().interrupt();
} } finally {
finally{
synchLock.unlock(); synchLock.unlock();
} }
} }
@@ -108,7 +106,7 @@ class WindowsShutdownManagerImpl extends ShutdownManagerImpl {
} }
@Override @Override
public void run() { public void run() {
try { try {
// Load user32.dll // Load user32.dll
final User32 user32 = (User32) Native.loadLibrary("user32", final User32 user32 = (User32) Native.loadLibrary("user32",

View File

@@ -1,10 +1,11 @@
package org.briarproject.plugins.file; package org.briarproject.plugins.file;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.util.Collection; import java.util.Collection;
import java.util.concurrent.Executor; import java.util.concurrent.Executor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock; import java.util.concurrent.locks.ReentrantLock;
@@ -44,7 +45,7 @@ class PollingRemovableDriveMonitor implements RemovableDriveMonitor, Runnable {
pollingLock.lock(); pollingLock.lock();
try { try {
stopPolling.signalAll(); stopPolling.signalAll();
} }
finally { finally {
pollingLock.unlock(); pollingLock.unlock();
} }
@@ -56,9 +57,8 @@ class PollingRemovableDriveMonitor implements RemovableDriveMonitor, Runnable {
while(running) { while(running) {
pollingLock.lock(); pollingLock.lock();
try { try {
stopPolling.await(pollingInterval, TimeUnit.MILLISECONDS); stopPolling.await(pollingInterval, MILLISECONDS);
} } finally {
finally{
pollingLock.unlock(); pollingLock.unlock();
} }
if(!running) return; if(!running) return;

View File

@@ -4,7 +4,6 @@ import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock; import java.util.concurrent.locks.ReentrantLock;
@@ -23,11 +22,11 @@ JNotifyListener {
private Callback callback = null; private Callback callback = null;
protected abstract String[] getPathsToWatch(); protected abstract String[] getPathsToWatch();
//TODO: rationalise this in a further refactor //TODO: rationalise this in a further refactor
private final Lock synchLock = new ReentrantLock(); private final Lock synchLock = new ReentrantLock();
private static final Lock staticSynchLock = new ReentrantLock(); private static final Lock staticSynchLock = new ReentrantLock();
private static Throwable tryLoad() { private static Throwable tryLoad() {
try { try {
Class.forName("net.contentobjects.jnotify.JNotify"); Class.forName("net.contentobjects.jnotify.JNotify");
@@ -47,8 +46,7 @@ JNotifyListener {
triedLoad = true; triedLoad = true;
} }
if(loadError != null) throw new IOException(loadError.toString()); if(loadError != null) throw new IOException(loadError.toString());
} } finally {
finally{
staticSynchLock.unlock(); staticSynchLock.unlock();
} }
} }
@@ -61,46 +59,43 @@ JNotifyListener {
if(new File(path).exists()) if(new File(path).exists())
watches.add(JNotify.addWatch(path, mask, false, this)); watches.add(JNotify.addWatch(path, mask, false, this));
} }
synchLock.lock(); synchLock.lock();
try { try {
assert !started; assert !started;
assert this.callback == null; assert this.callback == null;
started = true; started = true;
this.callback = callback; this.callback = callback;
this.watches.addAll(watches); this.watches.addAll(watches);
} } finally {
finally{ synchLock.unlock();
synchLock.unlock(); }
}
} }
public void stop() throws IOException { public void stop() throws IOException {
checkEnabled(); checkEnabled();
List<Integer> watches; List<Integer> watches;
synchLock.lock(); synchLock.lock();
try { try {
assert started; assert started;
assert callback != null; assert callback != null;
started = false; started = false;
callback = null; callback = null;
watches = new ArrayList<Integer>(this.watches); watches = new ArrayList<Integer>(this.watches);
this.watches.clear(); this.watches.clear();
} } finally {
finally{ synchLock.unlock();
synchLock.unlock(); }
}
for(Integer w : watches) JNotify.removeWatch(w); for(Integer w : watches) JNotify.removeWatch(w);
} }
public void fileCreated(int wd, String rootPath, String name) { public void fileCreated(int wd, String rootPath, String name) {
Callback callback; Callback callback;
synchLock.lock(); synchLock.lock();
try { try {
callback = this.callback; callback = this.callback;
} } finally {
finally{ synchLock.unlock();
synchLock.unlock(); }
}
if(callback != null) if(callback != null)
callback.driveInserted(new File(rootPath + "/" + name)); callback.driveInserted(new File(rootPath + "/" + name));
} }

View File

@@ -91,160 +91,161 @@ class CountryCodes {
new Country("GP", "Guadeloupe", "590", "00", ""), new Country("GP", "Guadeloupe", "590", "00", ""),
new Country("GQ", "Equatorial Guinea", "240", "00", ""), new Country("GQ", "Equatorial Guinea", "240", "00", ""),
new Country("GR", "Greece", "30", "00", ""), new Country("GR", "Greece", "30", "00", ""),
new Country("GS", "South Georgia and the South Sandwich Islands", "995", "8**10", "8"), new Country("GS", "South Georgia and the South Sandwich Islands",
new Country("GT", "Guatemala", "502", "00", ""), "995", "8**10", "8"),
new Country("GU", "Guam", "1", "011", "1"), new Country("GT", "Guatemala", "502", "00", ""),
new Country("GW", "Guinea-Bissau", "245", "00", ""), new Country("GU", "Guam", "1", "011", "1"),
new Country("GY", "Guyana", "592", "001", "0"), new Country("GW", "Guinea-Bissau", "245", "00", ""),
new Country("HK", "Hong Kong", "852", "001", ""), new Country("GY", "Guyana", "592", "001", "0"),
new Country("HM", "Heard Island and McDonald Islands", "692", "00", "0"), new Country("HK", "Hong Kong", "852", "001", ""),
new Country("HN", "Honduras", "504", "00", "0"), new Country("HM", "Heard Island and McDonald Islands", "692", "00", "0"),
new Country("HR", "Croatia", "385", "00", "0"), new Country("HN", "Honduras", "504", "00", "0"),
new Country("HT", "Haiti", "509", "00", "0"), new Country("HR", "Croatia", "385", "00", "0"),
new Country("HU", "Hungary", "36", "00", "06"), new Country("HT", "Haiti", "509", "00", "0"),
new Country("ID", "Indonesia", "62", "001", "0"), new Country("HU", "Hungary", "36", "00", "06"),
new Country("IE", "Ireland", "353", "00", "0"), new Country("ID", "Indonesia", "62", "001", "0"),
new Country("IL", "Israel", "972", "00", "0"), new Country("IE", "Ireland", "353", "00", "0"),
new Country("IN", "India", "91", "00", "0"), new Country("IL", "Israel", "972", "00", "0"),
new Country("IO", "British Indian Ocean Territory", "246", "00", ""), new Country("IN", "India", "91", "00", "0"),
new Country("IQ", "Iraq", "964", "00", "0"), new Country("IO", "British Indian Ocean Territory", "246", "00", ""),
new Country("IR", "Iran", "98", "00", "0"), new Country("IQ", "Iraq", "964", "00", "0"),
new Country("IS", "Iceland", "354", "00", "0"), new Country("IR", "Iran", "98", "00", "0"),
new Country("IT", "Italy", "39", "00", ""), new Country("IS", "Iceland", "354", "00", "0"),
new Country("JM", "Jamaica", "1", "011", "1"), new Country("IT", "Italy", "39", "00", ""),
new Country("JO", "Jordan", "962", "00", "0"), new Country("JM", "Jamaica", "1", "011", "1"),
new Country("JP", "Japan", "81", "001", "0"), new Country("JO", "Jordan", "962", "00", "0"),
new Country("KE", "Kenya", "254", "000", "0"), new Country("JP", "Japan", "81", "001", "0"),
new Country("KG", "Kyrgyzstan", "996", "00", "0"), new Country("KE", "Kenya", "254", "000", "0"),
new Country("KH", "Cambodia", "855", "001", "0"), new Country("KG", "Kyrgyzstan", "996", "00", "0"),
new Country("KI", "Kiribati", "686", "00", "0"), new Country("KH", "Cambodia", "855", "001", "0"),
new Country("KM", "Comoros", "269", "00", ""), new Country("KI", "Kiribati", "686", "00", "0"),
new Country("KN", "Saint Kitts and Nevis", "1", "011", "1"), new Country("KM", "Comoros", "269", "00", ""),
new Country("KP", "Korea (North)", "850", "00", "0"), new Country("KN", "Saint Kitts and Nevis", "1", "011", "1"),
new Country("KR", "Korea (South)", "82", "001", "0"), new Country("KP", "Korea (North)", "850", "00", "0"),
new Country("KW", "Kuwait", "965", "00", "0"), new Country("KR", "Korea (South)", "82", "001", "0"),
new Country("KY", "Cayman Islands", "1", "011", "1"), new Country("KW", "Kuwait", "965", "00", "0"),
new Country("KZ", "Kazakhstan", "7", "8**10", "8"), new Country("KY", "Cayman Islands", "1", "011", "1"),
new Country("LA", "Laos", "856", "00", "0"), new Country("KZ", "Kazakhstan", "7", "8**10", "8"),
new Country("LB", "Lebanon", "961", "00", "0"), new Country("LA", "Laos", "856", "00", "0"),
new Country("LC", "Saint Lucia", "1", "011", "1"), new Country("LB", "Lebanon", "961", "00", "0"),
new Country("LI", "Liechtenstein", "423", "00", ""), new Country("LC", "Saint Lucia", "1", "011", "1"),
new Country("LK", "Sri Lanka", "94", "00", "0"), new Country("LI", "Liechtenstein", "423", "00", ""),
new Country("LR", "Liberia", "231", "00", "22"), new Country("LK", "Sri Lanka", "94", "00", "0"),
new Country("LS", "Lesotho", "266", "00", "0"), new Country("LR", "Liberia", "231", "00", "22"),
new Country("LT", "Lithuania", "370", "00", "8"), new Country("LS", "Lesotho", "266", "00", "0"),
new Country("LU", "Luxembourg", "352", "00", ""), new Country("LT", "Lithuania", "370", "00", "8"),
new Country("LV", "Latvia", "371", "00", "8"), new Country("LU", "Luxembourg", "352", "00", ""),
new Country("LY", "Libya", "218", "00", "0"), new Country("LV", "Latvia", "371", "00", "8"),
new Country("MA", "Morocco", "212", "00", ""), new Country("LY", "Libya", "218", "00", "0"),
new Country("MC", "Monaco", "377", "00", "0"), new Country("MA", "Morocco", "212", "00", ""),
new Country("MD", "Moldova", "373", "00", "0"), new Country("MC", "Monaco", "377", "00", "0"),
new Country("ME", "Montenegro", "382", "99", "0"), new Country("MD", "Moldova", "373", "00", "0"),
new Country("MG", "Madagascar", "261", "00", "0"), new Country("ME", "Montenegro", "382", "99", "0"),
new Country("MH", "Marshall Islands", "692", "011", "1"), new Country("MG", "Madagascar", "261", "00", "0"),
new Country("MK", "Macedonia", "389", "00", "0"), new Country("MH", "Marshall Islands", "692", "011", "1"),
new Country("ML", "Mali", "223", "00", "0"), new Country("MK", "Macedonia", "389", "00", "0"),
new Country("MM", "Myanmar", "95", "00", ""), new Country("ML", "Mali", "223", "00", "0"),
new Country("MN", "Mongolia", "976", "001", "0"), new Country("MM", "Myanmar", "95", "00", ""),
new Country("MO", "Macao", "853", "00", "0"), new Country("MN", "Mongolia", "976", "001", "0"),
new Country("MP", "Northern Mariana Islands", "1", "011", "1"), new Country("MO", "Macao", "853", "00", "0"),
new Country("MQ", "Martinique", "596", "00", "0"), new Country("MP", "Northern Mariana Islands", "1", "011", "1"),
new Country("MR", "Mauritania", "222", "00", "0"), new Country("MQ", "Martinique", "596", "00", "0"),
new Country("MS", "Montserrat", "1", "011", "1"), new Country("MR", "Mauritania", "222", "00", "0"),
new Country("MT", "Malta", "356", "00", "21"), new Country("MS", "Montserrat", "1", "011", "1"),
new Country("MU", "Mauritius", "230", "00", "0"), new Country("MT", "Malta", "356", "00", "21"),
new Country("MV", "Maldives", "960", "00", "0"), new Country("MU", "Mauritius", "230", "00", "0"),
new Country("MW", "Malawi", "265", "00", ""), new Country("MV", "Maldives", "960", "00", "0"),
new Country("MX", "Mexico", "52", "00", "01"), new Country("MW", "Malawi", "265", "00", ""),
new Country("MY", "Malaysia", "60", "00", "0"), new Country("MX", "Mexico", "52", "00", "01"),
new Country("MZ", "Mozambique", "258", "00", "0"), new Country("MY", "Malaysia", "60", "00", "0"),
new Country("NA", "Namibia", "264", "00", "0"), new Country("MZ", "Mozambique", "258", "00", "0"),
new Country("NC", "New Caledonia", "687", "00", "0"), new Country("NA", "Namibia", "264", "00", "0"),
new Country("NE", "Niger", "227", "00", "0"), new Country("NC", "New Caledonia", "687", "00", "0"),
new Country("NF", "Norfolk Island", "672", "00", ""), new Country("NE", "Niger", "227", "00", "0"),
new Country("NG", "Nigeria", "234", "009", "0"), new Country("NF", "Norfolk Island", "672", "00", ""),
new Country("NI", "Nicaragua", "505", "00", "0"), new Country("NG", "Nigeria", "234", "009", "0"),
new Country("NL", "Netherlands", "31", "00", "0"), new Country("NI", "Nicaragua", "505", "00", "0"),
new Country("NO", "Norway", "47", "00", ""), new Country("NL", "Netherlands", "31", "00", "0"),
new Country("NP", "Nepal", "977", "00", "0"), new Country("NO", "Norway", "47", "00", ""),
new Country("NR", "Nauru", "674", "00", "0"), new Country("NP", "Nepal", "977", "00", "0"),
new Country("NU", "Niue", "683", "00", "0"), new Country("NR", "Nauru", "674", "00", "0"),
new Country("NZ", "New Zealand", "64", "00", "0"), new Country("NU", "Niue", "683", "00", "0"),
new Country("OM", "Oman", "968", "00", "0"), new Country("NZ", "New Zealand", "64", "00", "0"),
new Country("PA", "Panama", "507", "00", "0"), new Country("OM", "Oman", "968", "00", "0"),
new Country("PE", "Peru", "51", "00", "0"), new Country("PA", "Panama", "507", "00", "0"),
new Country("PF", "French Polynesia", "689", "00", ""), new Country("PE", "Peru", "51", "00", "0"),
new Country("PG", "Papua New Guinea", "675", "05", ""), new Country("PF", "French Polynesia", "689", "00", ""),
new Country("PH", "Philippines", "63", "00", "0"), new Country("PG", "Papua New Guinea", "675", "05", ""),
new Country("PK", "Pakistan", "92", "00", "0"), new Country("PH", "Philippines", "63", "00", "0"),
new Country("PL", "Poland", "48", "00", "0"), new Country("PK", "Pakistan", "92", "00", "0"),
new Country("PM", "Saint Pierre and Miquelon", "508", "00", "0"), new Country("PL", "Poland", "48", "00", "0"),
new Country("PN", "Pitcairn", "872", "", ""), new Country("PM", "Saint Pierre and Miquelon", "508", "00", "0"),
new Country("PR", "Puerto Rico", "1", "011", "1"), new Country("PN", "Pitcairn", "872", "", ""),
new Country("PS", "Palestine", "970", "00", "0"), new Country("PR", "Puerto Rico", "1", "011", "1"),
new Country("PT", "Portugal", "351", "00", ""), new Country("PS", "Palestine", "970", "00", "0"),
new Country("PW", "Palau", "680", "011", ""), new Country("PT", "Portugal", "351", "00", ""),
new Country("PY", "Paraguay", "595", "002", "0"), new Country("PW", "Palau", "680", "011", ""),
new Country("QA", "Qatar", "974", "00", "0"), new Country("PY", "Paraguay", "595", "002", "0"),
new Country("RE", "Reunion", "262", "00", "0"), new Country("QA", "Qatar", "974", "00", "0"),
new Country("RO", "Romania", "40", "00", "0"), new Country("RE", "Reunion", "262", "00", "0"),
new Country("RS", "Serbia", "381", "99", "0"), new Country("RO", "Romania", "40", "00", "0"),
new Country("RU", "Russia", "7", "8**10", "8"), new Country("RS", "Serbia", "381", "99", "0"),
new Country("RW", "Rwanda", "250", "00", "0"), new Country("RU", "Russia", "7", "8**10", "8"),
new Country("SA", "Saudi Arabia", "966", "00", "0"), new Country("RW", "Rwanda", "250", "00", "0"),
new Country("SB", "Solomon Islands", "677", "00", ""), new Country("SA", "Saudi Arabia", "966", "00", "0"),
new Country("SC", "Seychelles", "248", "00", "0"), new Country("SB", "Solomon Islands", "677", "00", ""),
new Country("SD", "Sudan", "249", "00", "0"), new Country("SC", "Seychelles", "248", "00", "0"),
new Country("SE", "Sweden", "46", "00", "0"), new Country("SD", "Sudan", "249", "00", "0"),
new Country("SG", "Singapore", "65", "001", ""), new Country("SE", "Sweden", "46", "00", "0"),
new Country("SH", "Saint Helena", "290", "00", ""), new Country("SG", "Singapore", "65", "001", ""),
new Country("SI", "Slovenia", "386", "00", "0"), new Country("SH", "Saint Helena", "290", "00", ""),
new Country("SJ", "Svalbard and Jan Mayen", "378", "00", "0"), new Country("SI", "Slovenia", "386", "00", "0"),
new Country("SK", "Slovakia", "421", "00", "0"), new Country("SJ", "Svalbard and Jan Mayen", "378", "00", "0"),
new Country("SL", "Sierra Leone", "232", "00", "0"), new Country("SK", "Slovakia", "421", "00", "0"),
new Country("SM", "San Marino", "378", "00", "0"), new Country("SL", "Sierra Leone", "232", "00", "0"),
new Country("SN", "Senegal", "221", "00", "0"), new Country("SM", "San Marino", "378", "00", "0"),
new Country("SO", "Somalia", "252", "00", ""), new Country("SN", "Senegal", "221", "00", "0"),
new Country("SR", "Suriname", "597", "00", ""), new Country("SO", "Somalia", "252", "00", ""),
new Country("ST", "Sao Tome and Principe", "239", "00", "0"), new Country("SR", "Suriname", "597", "00", ""),
new Country("SV", "El Salvador", "503", "00", ""), new Country("ST", "Sao Tome and Principe", "239", "00", "0"),
new Country("SY", "Syria", "963", "00", "0"), new Country("SV", "El Salvador", "503", "00", ""),
new Country("SZ", "Swaziland", "268", "00", ""), new Country("SY", "Syria", "963", "00", "0"),
new Country("TC", "Turks and Caicos Islands", "1", "011", "1"), new Country("SZ", "Swaziland", "268", "00", ""),
new Country("TD", "Chad", "235", "15", ""), new Country("TC", "Turks and Caicos Islands", "1", "011", "1"),
new Country("TF", "French Southern Territories", "596", "00", "0"), new Country("TD", "Chad", "235", "15", ""),
new Country("TG", "Togo", "228", "00", ""), new Country("TF", "French Southern Territories", "596", "00", "0"),
new Country("TH", "Thailand", "66", "001", "0"), new Country("TG", "Togo", "228", "00", ""),
new Country("TJ", "Tajikistan", "992", "8**10", "8"), new Country("TH", "Thailand", "66", "001", "0"),
new Country("TK", "Tokelau", "690", "00", ""), new Country("TJ", "Tajikistan", "992", "8**10", "8"),
new Country("TL", "Timor-Leste", "670", "00", ""), new Country("TK", "Tokelau", "690", "00", ""),
new Country("TM", "Turkmenistan", "993", "8**10", "8"), new Country("TL", "Timor-Leste", "670", "00", ""),
new Country("TN", "Tunisia", "216", "00", "0"), new Country("TM", "Turkmenistan", "993", "8**10", "8"),
new Country("TO", "Tonga Islands", "676", "00", ""), new Country("TN", "Tunisia", "216", "00", "0"),
new Country("TR", "Turkey", "90", "00", "0"), new Country("TO", "Tonga Islands", "676", "00", ""),
new Country("TT", "Trinidad and Tobago", "1", "011", "1"), new Country("TR", "Turkey", "90", "00", "0"),
new Country("TV", "Tuvalu", "688", "00", ""), new Country("TT", "Trinidad and Tobago", "1", "011", "1"),
new Country("TW", "Taiwan", "886", "002", ""), new Country("TV", "Tuvalu", "688", "00", ""),
new Country("TZ", "Tanzania", "255", "000", "0"), new Country("TW", "Taiwan", "886", "002", ""),
new Country("UA", "Ukraine", "380", "8**10", "8"), new Country("TZ", "Tanzania", "255", "000", "0"),
new Country("UG", "Uganda", "256", "000", "0"), new Country("UA", "Ukraine", "380", "8**10", "8"),
new Country("US", "United States", "1", "011", "1"), new Country("UG", "Uganda", "256", "000", "0"),
new Country("UY", "Uruguay", "598", "00", "0"), new Country("US", "United States", "1", "011", "1"),
new Country("UZ", "Uzbekistan", "998", "8**10", "8"), new Country("UY", "Uruguay", "598", "00", "0"),
new Country("VA", "Holy See (Vatican City State)", "379", "00", ""), new Country("UZ", "Uzbekistan", "998", "8**10", "8"),
new Country("VC", "Saint Vincent and the Grenadines", "1", "011", "1"), new Country("VA", "Holy See (Vatican City State)", "379", "00", ""),
new Country("VE", "Venezuela", "58", "00", "0"), new Country("VC", "Saint Vincent and the Grenadines", "1", "011", "1"),
new Country("VG", "Virgin Islands (British)", "1", "011", "1"), new Country("VE", "Venezuela", "58", "00", "0"),
new Country("VI", "Virgin Islands (U.S.)", "1", "011", "1"), new Country("VG", "Virgin Islands (British)", "1", "011", "1"),
new Country("VN", "Viet Nam", "84", "00", "0"), new Country("VI", "Virgin Islands (U.S.)", "1", "011", "1"),
new Country("VU", "Vanuatu", "678", "00", ""), new Country("VN", "Viet Nam", "84", "00", "0"),
new Country("WF", "Wallis and Futuna Islands", "681", "19", ""), new Country("VU", "Vanuatu", "678", "00", ""),
new Country("WS", "Samoa (Western)", "685", "0", "0"), new Country("WF", "Wallis and Futuna Islands", "681", "19", ""),
new Country("YE", "Yemen", "967", "00", "0"), new Country("WS", "Samoa (Western)", "685", "0", "0"),
new Country("YT", "Mayotte", "269", "00", ""), new Country("YE", "Yemen", "967", "00", "0"),
new Country("ZA", "South Africa", "27", "09", "0"), new Country("YT", "Mayotte", "269", "00", ""),
new Country("ZM", "Zambia", "260", "00", "0"), new Country("ZA", "South Africa", "27", "09", "0"),
new Country("ZW", "Zimbabwe", "263", "110", "0") new Country("ZM", "Zambia", "260", "00", "0"),
new Country("ZW", "Zimbabwe", "263", "110", "0")
}; };
private static final Map<String, Country> COUNTRY_MAP = private static final Map<String, Country> COUNTRY_MAP =

View File

@@ -1,5 +1,6 @@
package org.briarproject.plugins.modem; package org.briarproject.plugins.modem;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static java.util.logging.Level.INFO; import static java.util.logging.Level.INFO;
import static java.util.logging.Level.WARNING; import static java.util.logging.Level.WARNING;
import static jssc.SerialPort.PURGE_RXCLEAR; import static jssc.SerialPort.PURGE_RXCLEAR;
@@ -10,7 +11,6 @@ import java.io.InputStream;
import java.io.OutputStream; import java.io.OutputStream;
import java.util.concurrent.Executor; import java.util.concurrent.Executor;
import java.util.concurrent.Semaphore; import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock; import java.util.concurrent.locks.ReentrantLock;
@@ -48,7 +48,7 @@ class ModemImpl implements Modem, WriteHandler, SerialPortEventListener {
private ReliabilityLayer reliability = null; private ReliabilityLayer reliability = null;
private boolean initialised = false, connected = false; private boolean initialised = false, connected = false;
private final Lock synchLock = new ReentrantLock(); private final Lock synchLock = new ReentrantLock();
private final Condition connectedStateChanged = synchLock.newCondition(); private final Condition connectedStateChanged = synchLock.newCondition();
private final Condition initialisedStateChanged = synchLock.newCondition(); private final Condition initialisedStateChanged = synchLock.newCondition();
@@ -105,12 +105,11 @@ class ModemImpl implements Modem, WriteHandler, SerialPortEventListener {
long now = clock.currentTimeMillis(); long now = clock.currentTimeMillis();
long end = now + OK_TIMEOUT; long end = now + OK_TIMEOUT;
while(now < end && !initialised) { while(now < end && !initialised) {
initialisedStateChanged.await(end - now, TimeUnit.MILLISECONDS); initialisedStateChanged.await(end - now, MILLISECONDS);
now = clock.currentTimeMillis(); now = clock.currentTimeMillis();
} }
success = initialised; success = initialised;
} } finally {
finally{
synchLock.unlock(); synchLock.unlock();
} }
} catch(InterruptedException e) { } catch(InterruptedException e) {
@@ -143,8 +142,7 @@ class ModemImpl implements Modem, WriteHandler, SerialPortEventListener {
connected = false; connected = false;
initialisedStateChanged.signalAll(); initialisedStateChanged.signalAll();
connectedStateChanged.signalAll(); connectedStateChanged.signalAll();
} } finally {
finally{
synchLock.unlock(); synchLock.unlock();
} }
// Hang up if necessary and close the port // Hang up if necessary and close the port
@@ -174,8 +172,7 @@ class ModemImpl implements Modem, WriteHandler, SerialPortEventListener {
reliability = this.reliability; reliability = this.reliability;
this.reliability = null; this.reliability = null;
connected = false; connected = false;
} } finally {
finally{
synchLock.unlock(); synchLock.unlock();
} }
reliability.stop(); reliability.stop();
@@ -214,8 +211,7 @@ class ModemImpl implements Modem, WriteHandler, SerialPortEventListener {
return false; return false;
} }
this.reliability = reliability; this.reliability = reliability;
} } finally {
finally{
synchLock.unlock(); synchLock.unlock();
} }
reliability.start(); reliability.start();
@@ -234,12 +230,11 @@ class ModemImpl implements Modem, WriteHandler, SerialPortEventListener {
long now = clock.currentTimeMillis(); long now = clock.currentTimeMillis();
long end = now + CONNECT_TIMEOUT; long end = now + CONNECT_TIMEOUT;
while(now < end && initialised && !connected) { while(now < end && initialised && !connected) {
connectedStateChanged.await(end - now, TimeUnit.MILLISECONDS); connectedStateChanged.await(end - now, MILLISECONDS);
now = clock.currentTimeMillis(); now = clock.currentTimeMillis();
} }
if(connected) return true; if(connected) return true;
} } finally {
finally{
synchLock.unlock(); synchLock.unlock();
} }
} catch(InterruptedException e) { } catch(InterruptedException e) {
@@ -259,8 +254,7 @@ class ModemImpl implements Modem, WriteHandler, SerialPortEventListener {
synchLock.lock(); synchLock.lock();
try { try {
reliability = this.reliability; reliability = this.reliability;
} } finally {
finally{
synchLock.unlock(); synchLock.unlock();
} }
if(reliability == null) throw new IOException("Not connected"); if(reliability == null) throw new IOException("Not connected");
@@ -272,8 +266,7 @@ class ModemImpl implements Modem, WriteHandler, SerialPortEventListener {
synchLock.lock(); synchLock.lock();
try { try {
reliability = this.reliability; reliability = this.reliability;
} } finally {
finally{
synchLock.unlock(); synchLock.unlock();
} }
if(reliability == null) throw new IOException("Not connected"); if(reliability == null) throw new IOException("Not connected");
@@ -328,8 +321,7 @@ class ModemImpl implements Modem, WriteHandler, SerialPortEventListener {
synchLock.lock(); synchLock.lock();
try { try {
reliability = this.reliability; reliability = this.reliability;
} } finally {
finally{
synchLock.unlock(); synchLock.unlock();
} }
if(reliability == null) return false; if(reliability == null) return false;
@@ -354,8 +346,7 @@ class ModemImpl implements Modem, WriteHandler, SerialPortEventListener {
try { try {
connected = true; connected = true;
connectedStateChanged.signalAll(); connectedStateChanged.signalAll();
} } finally {
finally{
synchLock.unlock(); synchLock.unlock();
} }
// There might be data in the buffer as well as text // There might be data in the buffer as well as text
@@ -372,8 +363,7 @@ class ModemImpl implements Modem, WriteHandler, SerialPortEventListener {
try { try {
connected = false; connected = false;
connectedStateChanged.signalAll(); connectedStateChanged.signalAll();
} } finally {
finally{
synchLock.unlock(); synchLock.unlock();
} }
} else if(s.equals("OK")) { } else if(s.equals("OK")) {
@@ -381,8 +371,7 @@ class ModemImpl implements Modem, WriteHandler, SerialPortEventListener {
try { try {
initialised = true; initialised = true;
initialisedStateChanged.signalAll(); initialisedStateChanged.signalAll();
} } finally {
finally{
synchLock.unlock(); synchLock.unlock();
} }
} else if(s.equals("RING")) { } else if(s.equals("RING")) {
@@ -422,8 +411,7 @@ class ModemImpl implements Modem, WriteHandler, SerialPortEventListener {
return; return;
} }
this.reliability = reliability; this.reliability = reliability;
} } finally {
finally{
synchLock.unlock(); synchLock.unlock();
} }
reliability.start(); reliability.start();
@@ -442,12 +430,11 @@ class ModemImpl implements Modem, WriteHandler, SerialPortEventListener {
long now = clock.currentTimeMillis(); long now = clock.currentTimeMillis();
long end = now + CONNECT_TIMEOUT; long end = now + CONNECT_TIMEOUT;
while(now < end && initialised && !connected) { while(now < end && initialised && !connected) {
connectedStateChanged.await(end - now, TimeUnit.MILLISECONDS); connectedStateChanged.await(end - now, MILLISECONDS);
now = clock.currentTimeMillis(); now = clock.currentTimeMillis();
} }
success = connected; success = connected;
} } finally {
finally{
synchLock.unlock(); synchLock.unlock();
} }
} catch(InterruptedException e) { } catch(InterruptedException e) {

View File

@@ -11,7 +11,6 @@ import org.briarproject.api.event.ContactConnectedEvent;
import org.briarproject.api.event.ContactDisconnectedEvent; import org.briarproject.api.event.ContactDisconnectedEvent;
import org.briarproject.api.event.EventBus; import org.briarproject.api.event.EventBus;
import org.briarproject.api.plugins.ConnectionRegistry; import org.briarproject.api.plugins.ConnectionRegistry;
import org.briarproject.plugins.ConnectionRegistryImpl;
import org.jmock.Expectations; import org.jmock.Expectations;
import org.jmock.Mockery; import org.jmock.Mockery;
import org.junit.Test; import org.junit.Test;