Switched Roboguice/Guice out for Dagger 2

This commit is contained in:
Ernir Erlingsson
2016-03-03 10:24:40 +01:00
parent e5d7038195
commit 1be400eb84
89 changed files with 1640 additions and 802 deletions

5
briar-android-tests/.gitignore vendored Normal file
View File

@@ -0,0 +1,5 @@
bin
gen
build
local.properties
.settings

View File

@@ -0,0 +1,39 @@
apply plugin: 'com.android.library'
sourceCompatibility = 1.6
targetCompatibility = 1.6
apply plugin: 'witness'
apply plugin: 'com.neenbedankt.android-apt'
repositories {
maven { url 'http://repo1.maven.org/maven2' }
}
android {
compileSdkVersion 23
buildToolsVersion "23.0.2"
defaultConfig {
minSdkVersion 10
targetSdkVersion 23
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile project(':briar-api')
compile project(':briar-core')
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:23.2.0'
testApt 'com.google.dagger:dagger-compiler:2.0.2'
provided 'javax.annotation:jsr250-api:1.0'
compile 'cglib:cglib-nodep:3.1'
testCompile project(':briar-tests')
}

17
briar-android-tests/proguard-rules.pro vendored Normal file
View File

@@ -0,0 +1,17 @@
# Add project specific ProGuard rules here.
# By default, the flags in this file are appended to flags specified
# in /home/ernir/dev/sdk/tools/proguard/proguard-android.txt
# You can edit the include path and order by changing the proguardFiles
# directive in build.gradle.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html
# Add any project specific keep options here:
# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
# public *;
#}

View File

@@ -0,0 +1,13 @@
package com.ymirmobile.briar_android_tests;
import android.app.Application;
import android.test.ApplicationTestCase;
/**
* <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a>
*/
public class ApplicationTest extends ApplicationTestCase<Application> {
public ApplicationTest() {
super(Application.class);
}
}

View File

@@ -0,0 +1,12 @@
<manifest package="org.briarproject"
xmlns:android="http://schemas.android.com/apk/res/android">
<application
android:allowBackup="true"
android:label="@string/app_name"
android:supportsRtl="true"
>
</application>
</manifest>

View File

@@ -0,0 +1,3 @@
<resources>
<string name="app_name">briar-android-tests</string>
</resources>

View File

@@ -1,8 +1,7 @@
package org.briarproject; package org.briarproject.protocol;
import com.google.inject.Guice;
import com.google.inject.Injector;
import org.briarproject.BriarTestCase;
import org.briarproject.TestUtils;
import org.briarproject.api.TransportId; import org.briarproject.api.TransportId;
import org.briarproject.api.contact.ContactId; import org.briarproject.api.contact.ContactId;
import org.briarproject.api.crypto.SecretKey; import org.briarproject.api.crypto.SecretKey;
@@ -22,21 +21,8 @@ import org.briarproject.api.sync.Request;
import org.briarproject.api.transport.StreamContext; import org.briarproject.api.transport.StreamContext;
import org.briarproject.api.transport.StreamReaderFactory; import org.briarproject.api.transport.StreamReaderFactory;
import org.briarproject.api.transport.StreamWriterFactory; import org.briarproject.api.transport.StreamWriterFactory;
import org.briarproject.crypto.CryptoModule;
import org.briarproject.data.DataModule;
import org.briarproject.db.DatabaseModule;
import org.briarproject.event.EventModule;
import org.briarproject.sync.SyncModule;
import org.briarproject.transport.TransportModule;
import org.junit.Test; import org.junit.Test;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.Collection;
import static org.briarproject.api.sync.SyncConstants.MAX_GROUP_DESCRIPTOR_LENGTH; import static org.briarproject.api.sync.SyncConstants.MAX_GROUP_DESCRIPTOR_LENGTH;
import static org.briarproject.api.transport.TransportConstants.TAG_LENGTH; import static org.briarproject.api.transport.TransportConstants.TAG_LENGTH;
import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertArrayEquals;
@@ -44,41 +30,50 @@ import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.Collection;
import javax.inject.Inject;
public class ProtocolIntegrationTest extends BriarTestCase { public class ProtocolIntegrationTest extends BriarTestCase {
private final StreamReaderFactory streamReaderFactory; @Inject
private final StreamWriterFactory streamWriterFactory; StreamReaderFactory streamReaderFactory;
private final PacketReaderFactory packetReaderFactory; @Inject
private final PacketWriterFactory packetWriterFactory; StreamWriterFactory streamWriterFactory;
@Inject
PacketReaderFactory packetReaderFactory;
@Inject
PacketWriterFactory packetWriterFactory;
private final ContactId contactId; private final ContactId contactId;
private final TransportId transportId; private final TransportId transportId;
private final SecretKey tagKey, headerKey; private final SecretKey tagKey, headerKey;
private final Message message, message1; private final Message message, message1;
private final Collection<MessageId> messageIds; private final Collection<MessageId> messageIds;
private final ProtocolTestComponent component;
public ProtocolIntegrationTest() throws Exception { public ProtocolIntegrationTest() throws Exception {
Injector i = Guice.createInjector(new TestDatabaseModule(),
new TestLifecycleModule(), new TestSystemModule(), component = DaggerProtocolTestComponent.builder().build();
new CryptoModule(), new DatabaseModule(), new EventModule(), component.inject(this);
new SyncModule(), new DataModule(),
new TransportModule());
streamReaderFactory = i.getInstance(StreamReaderFactory.class);
streamWriterFactory = i.getInstance(StreamWriterFactory.class);
packetReaderFactory = i.getInstance(PacketReaderFactory.class);
packetWriterFactory = i.getInstance(PacketWriterFactory.class);
contactId = new ContactId(234); contactId = new ContactId(234);
transportId = new TransportId("id"); transportId = new TransportId("id");
// Create the transport keys // Create the transport keys
tagKey = TestUtils.createSecretKey(); tagKey = TestUtils.createSecretKey();
headerKey = TestUtils.createSecretKey(); headerKey = TestUtils.createSecretKey();
// Create a group // Create a group
GroupFactory groupFactory = i.getInstance(GroupFactory.class); GroupFactory groupFactory = component.getGroupFactory();
ClientId clientId = new ClientId(TestUtils.getRandomId()); ClientId clientId = new ClientId(TestUtils.getRandomId());
byte[] descriptor = new byte[MAX_GROUP_DESCRIPTOR_LENGTH]; byte[] descriptor = new byte[MAX_GROUP_DESCRIPTOR_LENGTH];
Group group = groupFactory.createGroup(clientId, descriptor); Group group = groupFactory.createGroup(clientId, descriptor);
// Add two messages to the group // Add two messages to the group
MessageFactory messageFactory = i.getInstance(MessageFactory.class); MessageFactory messageFactory = component.getMessageFactory();
long timestamp = System.currentTimeMillis(); long timestamp = System.currentTimeMillis();
String messageBody = "Hello world"; String messageBody = "Hello world";
message = messageFactory.createMessage(group.getId(), timestamp, message = messageFactory.createMessage(group.getId(), timestamp,
@@ -159,4 +154,5 @@ public class ProtocolIntegrationTest extends BriarTestCase {
assertEquals(m1.getTimestamp(), m2.getTimestamp()); assertEquals(m1.getTimestamp(), m2.getTimestamp());
assertArrayEquals(m1.getRaw(), m2.getRaw()); assertArrayEquals(m1.getRaw(), m2.getRaw());
} }
} }

View File

@@ -0,0 +1,26 @@
package org.briarproject.protocol;
import org.briarproject.TestDatabaseModule;
import org.briarproject.TestSystemModule;
import org.briarproject.api.sync.GroupFactory;
import org.briarproject.api.sync.MessageFactory;
import org.briarproject.crypto.CryptoModule;
import org.briarproject.data.DataModule;
import org.briarproject.db.DatabaseModule;
import org.briarproject.event.EventModule;
import org.briarproject.sync.SyncModule;
import org.briarproject.transport.TransportModule;
import javax.inject.Singleton;
import dagger.Component;
@Singleton
@Component(modules = {TestDatabaseModule.class, TestSystemModule.class,
CryptoModule.class, DatabaseModule.class, EventModule.class,
SyncModule.class, DataModule.class, TransportModule.class})
public interface ProtocolTestComponent {
void inject(ProtocolIntegrationTest testCase);
GroupFactory getGroupFactory();
MessageFactory getMessageFactory();
}

View File

@@ -0,0 +1,28 @@
package org.briarproject.sync;
import org.briarproject.TestDatabaseModule;
import org.briarproject.TestLifecycleModule;
import org.briarproject.TestSystemModule;
import org.briarproject.contact.ContactModule;
import org.briarproject.crypto.CryptoModule;
import org.briarproject.data.DataModule;
import org.briarproject.db.DatabaseModule;
import org.briarproject.event.EventModule;
import org.briarproject.forum.ForumModule;
import org.briarproject.identity.IdentityModule;
import org.briarproject.messaging.MessagingModule;
import org.briarproject.transport.TransportModule;
import javax.inject.Singleton;
import dagger.Component;
@Singleton
@Component(modules = {TestDatabaseModule.class, TestLifecycleModule.class,
TestSystemModule.class, ContactModule.class, CryptoModule.class,
DatabaseModule.class, EventModule.class, SyncModule.class,
DataModule.class, TransportModule.class, ForumModule.class,
IdentityModule.class, MessagingModule.class})
public interface ConstantsComponent {
void inject(ConstantsTest testCase);
}

View File

@@ -1,12 +1,6 @@
package org.briarproject.sync; package org.briarproject.sync;
import com.google.inject.Guice;
import com.google.inject.Injector;
import org.briarproject.BriarTestCase; import org.briarproject.BriarTestCase;
import org.briarproject.TestDatabaseModule;
import org.briarproject.TestLifecycleModule;
import org.briarproject.TestSystemModule;
import org.briarproject.TestUtils; import org.briarproject.TestUtils;
import org.briarproject.api.UniqueId; import org.briarproject.api.UniqueId;
import org.briarproject.api.crypto.CryptoComponent; import org.briarproject.api.crypto.CryptoComponent;
@@ -21,22 +15,6 @@ import org.briarproject.api.identity.AuthorFactory;
import org.briarproject.api.messaging.MessagingConstants; import org.briarproject.api.messaging.MessagingConstants;
import org.briarproject.api.messaging.PrivateMessage; import org.briarproject.api.messaging.PrivateMessage;
import org.briarproject.api.messaging.PrivateMessageFactory; import org.briarproject.api.messaging.PrivateMessageFactory;
import org.briarproject.api.sync.GroupId;
import org.briarproject.api.sync.MessageId;
import org.briarproject.clients.ClientsModule;
import org.briarproject.contact.ContactModule;
import org.briarproject.crypto.CryptoModule;
import org.briarproject.data.DataModule;
import org.briarproject.db.DatabaseModule;
import org.briarproject.event.EventModule;
import org.briarproject.forum.ForumModule;
import org.briarproject.identity.IdentityModule;
import org.briarproject.messaging.MessagingModule;
import org.briarproject.transport.TransportModule;
import org.junit.Test;
import java.util.Random;
import static org.briarproject.api.forum.ForumConstants.MAX_FORUM_POST_BODY_LENGTH; import static org.briarproject.api.forum.ForumConstants.MAX_FORUM_POST_BODY_LENGTH;
import static org.briarproject.api.identity.AuthorConstants.MAX_AUTHOR_NAME_LENGTH; import static org.briarproject.api.identity.AuthorConstants.MAX_AUTHOR_NAME_LENGTH;
import static org.briarproject.api.identity.AuthorConstants.MAX_PUBLIC_KEY_LENGTH; import static org.briarproject.api.identity.AuthorConstants.MAX_PUBLIC_KEY_LENGTH;
@@ -45,26 +23,32 @@ import static org.briarproject.api.messaging.MessagingConstants.MAX_PRIVATE_MESS
import static org.briarproject.api.sync.SyncConstants.MAX_PACKET_PAYLOAD_LENGTH; import static org.briarproject.api.sync.SyncConstants.MAX_PACKET_PAYLOAD_LENGTH;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
import org.briarproject.api.sync.GroupId;
import org.briarproject.api.sync.MessageId;
import org.junit.Test;
import java.util.Random;
import javax.inject.Inject;
public class ConstantsTest extends BriarTestCase { public class ConstantsTest extends BriarTestCase {
// TODO: Break this up into tests that are relevant for each package // TODO: Break this up into tests that are relevant for each package
@Inject
CryptoComponent crypto;
@Inject
AuthorFactory authorFactory;
@Inject
PrivateMessageFactory privateMessageFactory;
@Inject
ForumPostFactory forumPostFactory;
private final CryptoComponent crypto; private final ConstantsComponent component;
private final AuthorFactory authorFactory;
private final PrivateMessageFactory privateMessageFactory;
private final ForumPostFactory forumPostFactory;
public ConstantsTest() throws Exception { public ConstantsTest() throws Exception {
Injector i = Guice.createInjector(new TestDatabaseModule(),
new TestLifecycleModule(), new TestSystemModule(), component = DaggerConstantsComponent.builder().build();
new ClientsModule(), new ContactModule(), new CryptoModule(), component.inject(this);
new DatabaseModule(), new DataModule(), new EventModule(),
new ForumModule(), new IdentityModule(), new MessagingModule(),
new SyncModule(), new TransportModule());
crypto = i.getInstance(CryptoComponent.class);
authorFactory = i.getInstance(AuthorFactory.class);
privateMessageFactory = i.getInstance(PrivateMessageFactory.class);
forumPostFactory = i.getInstance(ForumPostFactory.class);
} }
@Test @Test

View File

@@ -0,0 +1,54 @@
package org.briarproject.sync;
import org.briarproject.TestDatabaseModule;
import org.briarproject.TestSystemModule;
import org.briarproject.api.contact.ContactManager;
import org.briarproject.api.db.DatabaseComponent;
import org.briarproject.api.event.EventBus;
import org.briarproject.api.identity.IdentityManager;
import org.briarproject.api.lifecycle.LifecycleManager;
import org.briarproject.api.messaging.MessagingManager;
import org.briarproject.api.messaging.PrivateMessageFactory;
import org.briarproject.api.sync.PacketReaderFactory;
import org.briarproject.api.sync.PacketWriterFactory;
import org.briarproject.api.transport.KeyManager;
import org.briarproject.api.transport.StreamReaderFactory;
import org.briarproject.api.transport.StreamWriterFactory;
import org.briarproject.contact.ContactModule;
import org.briarproject.crypto.CryptoModule;
import org.briarproject.data.DataModule;
import org.briarproject.db.DatabaseModule;
import org.briarproject.event.EventModule;
import org.briarproject.identity.IdentityModule;
import org.briarproject.lifecycle.LifecycleModule;
import org.briarproject.messaging.MessagingModule;
import org.briarproject.transport.TransportModule;
import javax.inject.Singleton;
import dagger.Component;
/**
* Created by Ernir Erlingsson (ernir@ymirmobile.com) on 3.3.2016.
*/
@Singleton
@Component(modules = {TestDatabaseModule.class, TestSystemModule.class,
LifecycleModule.class, ContactModule.class, CryptoModule.class,
DatabaseModule.class, EventModule.class, SyncModule.class,
DataModule.class, TransportModule.class, IdentityModule.class,
MessagingModule.class})
public interface SimplexMessagingComponent {
void inject(SimplexMessagingIntegrationTest testCase);
LifecycleManager getLifeCycleManager();
DatabaseComponent getDatabaseComponent();
IdentityManager getIdentityManager();
ContactManager getContactManager();
MessagingManager getMessagingManager();
KeyManager getKeyManager();
PrivateMessageFactory getPrivateMessageFactory();
PacketWriterFactory getPacketWriterFactory();
EventBus getEventBus();
StreamWriterFactory getStreamWriterFactory();
StreamReaderFactory getStreamReaderFactory();
PacketReaderFactory getPacketReaderFactory();
}

View File

@@ -1,19 +1,14 @@
package org.briarproject.sync; package org.briarproject.sync;
import com.google.inject.Guice;
import com.google.inject.Injector;
import org.briarproject.BriarTestCase; import org.briarproject.BriarTestCase;
import org.briarproject.ImmediateExecutor;
import org.briarproject.TestDatabaseModule; import org.briarproject.TestDatabaseModule;
import org.briarproject.TestSystemModule;
import org.briarproject.TestUtils; import org.briarproject.TestUtils;
import org.briarproject.api.TransportId; import org.briarproject.api.TransportId;
import org.briarproject.api.contact.ContactId; import org.briarproject.api.contact.ContactId;
import org.briarproject.api.contact.ContactManager; import org.briarproject.api.contact.ContactManager;
import org.briarproject.api.crypto.SecretKey; import org.briarproject.api.crypto.SecretKey;
import org.briarproject.api.db.DatabaseComponent; import org.briarproject.api.db.DatabaseComponent;
import org.briarproject.api.db.Transaction; import org.briarproject.api.db.StorageStatus;
import org.briarproject.api.event.Event; import org.briarproject.api.event.Event;
import org.briarproject.api.event.EventBus; import org.briarproject.api.event.EventBus;
import org.briarproject.api.event.EventListener; import org.briarproject.api.event.EventListener;
@@ -36,33 +31,24 @@ import org.briarproject.api.transport.KeyManager;
import org.briarproject.api.transport.StreamContext; import org.briarproject.api.transport.StreamContext;
import org.briarproject.api.transport.StreamReaderFactory; import org.briarproject.api.transport.StreamReaderFactory;
import org.briarproject.api.transport.StreamWriterFactory; import org.briarproject.api.transport.StreamWriterFactory;
import org.briarproject.clients.ClientsModule; import org.briarproject.plugins.ImmediateExecutor;
import org.briarproject.contact.ContactModule;
import org.briarproject.crypto.CryptoModule;
import org.briarproject.data.DataModule;
import org.briarproject.db.DatabaseModule;
import org.briarproject.event.EventModule;
import org.briarproject.identity.IdentityModule;
import org.briarproject.lifecycle.LifecycleModule;
import org.briarproject.messaging.MessagingModule;
import org.briarproject.transport.TransportModule;
import org.junit.After; import org.junit.After;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.briarproject.api.identity.AuthorConstants.MAX_PUBLIC_KEY_LENGTH;
import static org.briarproject.api.transport.TransportConstants.TAG_LENGTH;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
import java.io.File; import java.io.File;
import java.io.InputStream; import java.io.InputStream;
import java.io.OutputStream; import java.io.OutputStream;
import static org.briarproject.api.identity.AuthorConstants.MAX_PUBLIC_KEY_LENGTH;
import static org.briarproject.api.transport.TransportConstants.TAG_LENGTH;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
public class SimplexMessagingIntegrationTest extends BriarTestCase { public class SimplexMessagingIntegrationTest extends BriarTestCase {
private static final int MAX_LATENCY = 2 * 60 * 1000; // 2 minutes private static final int MAX_LATENCY = 2 * 60 * 1000; // 2 minutes
@@ -76,22 +62,16 @@ public class SimplexMessagingIntegrationTest extends BriarTestCase {
private final AuthorId aliceId = new AuthorId(TestUtils.getRandomId()); private final AuthorId aliceId = new AuthorId(TestUtils.getRandomId());
private final AuthorId bobId = new AuthorId(TestUtils.getRandomId()); private final AuthorId bobId = new AuthorId(TestUtils.getRandomId());
private Injector alice, bob; // private Injector alice, bob;
private SimplexMessagingComponent alice, bob;
@Before @Before
public void setUp() { public void setUp() {
assertTrue(testDir.mkdirs()); assertTrue(testDir.mkdirs());
alice = createInjector(aliceDir); alice = DaggerSimplexMessagingComponent.builder()
bob = createInjector(bobDir); .testDatabaseModule(new TestDatabaseModule(aliceDir)).build();
} bob = DaggerSimplexMessagingComponent.builder()
.testDatabaseModule(new TestDatabaseModule(bobDir)).build();
private Injector createInjector(File dir) {
return Guice.createInjector(new TestDatabaseModule(dir),
new TestSystemModule(), new ClientsModule(),
new ContactModule(), new CryptoModule(), new DatabaseModule(),
new DataModule(), new EventModule(), new IdentityModule(),
new LifecycleModule(), new MessagingModule(), new SyncModule(),
new TransportModule());
} }
@Test @Test
@@ -101,43 +81,34 @@ public class SimplexMessagingIntegrationTest extends BriarTestCase {
private byte[] write() throws Exception { private byte[] write() throws Exception {
// Instantiate Alice's services // Instantiate Alice's services
LifecycleManager lifecycleManager = LifecycleManager lifecycleManager = alice.getLifeCycleManager();
alice.getInstance(LifecycleManager.class); DatabaseComponent db = alice.getDatabaseComponent();
DatabaseComponent db = alice.getInstance(DatabaseComponent.class); IdentityManager identityManager = alice.getIdentityManager();
IdentityManager identityManager =
alice.getInstance(IdentityManager.class); ContactManager contactManager = alice.getContactManager();
ContactManager contactManager = alice.getInstance(ContactManager.class); MessagingManager messagingManager = alice.getMessagingManager();
MessagingManager messagingManager = KeyManager keyManager = alice.getKeyManager();
alice.getInstance(MessagingManager.class); PrivateMessageFactory privateMessageFactory = alice.getPrivateMessageFactory();
KeyManager keyManager = alice.getInstance(KeyManager.class); PacketWriterFactory packetWriterFactory = alice.getPacketWriterFactory();
PrivateMessageFactory privateMessageFactory = EventBus eventBus = alice.getEventBus();
alice.getInstance(PrivateMessageFactory.class); StreamWriterFactory streamWriterFactory = alice.getStreamWriterFactory();
PacketWriterFactory packetWriterFactory =
alice.getInstance(PacketWriterFactory.class);
EventBus eventBus = alice.getInstance(EventBus.class);
StreamWriterFactory streamWriterFactory =
alice.getInstance(StreamWriterFactory.class);
// Start the lifecycle manager // Start the lifecycle manager
lifecycleManager.startServices(); lifecycleManager.startServices();
lifecycleManager.waitForStartup(); lifecycleManager.waitForStartup();
// Add a transport // Add a transport
Transaction txn = db.startTransaction(); db.addTransport(transportId, MAX_LATENCY);
try {
db.addTransport(txn, transportId, MAX_LATENCY);
txn.setComplete();
} finally {
db.endTransaction(txn);
}
// Add an identity for Alice // Add an identity for Alice
LocalAuthor aliceAuthor = new LocalAuthor(aliceId, "Alice", LocalAuthor aliceAuthor = new LocalAuthor(aliceId, "Alice",
new byte[MAX_PUBLIC_KEY_LENGTH], new byte[123], timestamp); new byte[MAX_PUBLIC_KEY_LENGTH], new byte[123], timestamp,
StorageStatus.ADDING);
identityManager.addLocalAuthor(aliceAuthor); identityManager.addLocalAuthor(aliceAuthor);
// Add Bob as a contact // Add Bob as a contact
Author bobAuthor = new Author(bobId, "Bob", Author bobAuthor = new Author(bobId, "Bob",
new byte[MAX_PUBLIC_KEY_LENGTH]); new byte[MAX_PUBLIC_KEY_LENGTH]);
ContactId contactId = contactManager.addContact(bobAuthor, aliceId, ContactId contactId = contactManager.addContact(bobAuthor, aliceId);
master, timestamp, true, true); // Derive and store the transport keys
keyManager.addContact(contactId, master, timestamp, true);
// Send Bob a message // Send Bob a message
GroupId groupId = messagingManager.getConversationId(contactId); GroupId groupId = messagingManager.getConversationId(contactId);
@@ -172,45 +143,37 @@ public class SimplexMessagingIntegrationTest extends BriarTestCase {
private void read(byte[] stream) throws Exception { private void read(byte[] stream) throws Exception {
// Instantiate Bob's services // Instantiate Bob's services
LifecycleManager lifecycleManager = LifecycleManager lifecycleManager = bob.getLifeCycleManager();
bob.getInstance(LifecycleManager.class); DatabaseComponent db = bob.getDatabaseComponent();
DatabaseComponent db = bob.getInstance(DatabaseComponent.class); IdentityManager identityManager = bob.getIdentityManager();
IdentityManager identityManager = ContactManager contactManager = bob.getContactManager();
bob.getInstance(IdentityManager.class); KeyManager keyManager = bob.getKeyManager();
ContactManager contactManager = bob.getInstance(ContactManager.class); StreamReaderFactory streamReaderFactory = bob.getStreamReaderFactory();
KeyManager keyManager = bob.getInstance(KeyManager.class); PacketReaderFactory packetReaderFactory = bob.getPacketReaderFactory();
StreamReaderFactory streamReaderFactory = EventBus eventBus = bob.getEventBus();
bob.getInstance(StreamReaderFactory.class);
PacketReaderFactory packetReaderFactory =
bob.getInstance(PacketReaderFactory.class);
EventBus eventBus = bob.getInstance(EventBus.class);
// Bob needs a MessagingManager even though we're not using it directly // Bob needs a MessagingManager even though we're not using it directly
bob.getInstance(MessagingManager.class); bob.getMessagingManager();
// Start the lifecyle manager // Start the lifecyle manager
lifecycleManager.startServices(); lifecycleManager.startServices();
lifecycleManager.waitForStartup(); lifecycleManager.waitForStartup();
// Add a transport // Add a transport
Transaction txn = db.startTransaction(); db.addTransport(transportId, MAX_LATENCY);
try {
db.addTransport(txn, transportId, MAX_LATENCY);
txn.setComplete();
} finally {
db.endTransaction(txn);
}
// Add an identity for Bob // Add an identity for Bob
LocalAuthor bobAuthor = new LocalAuthor(bobId, "Bob", LocalAuthor bobAuthor = new LocalAuthor(bobId, "Bob",
new byte[MAX_PUBLIC_KEY_LENGTH], new byte[123], timestamp); new byte[MAX_PUBLIC_KEY_LENGTH], new byte[123], timestamp,
StorageStatus.ADDING);
identityManager.addLocalAuthor(bobAuthor); identityManager.addLocalAuthor(bobAuthor);
// Add Alice as a contact // Add Alice as a contact
Author aliceAuthor = new Author(aliceId, "Alice", Author aliceAuthor = new Author(aliceId, "Alice",
new byte[MAX_PUBLIC_KEY_LENGTH]); new byte[MAX_PUBLIC_KEY_LENGTH]);
ContactId contactId = contactManager.addContact(aliceAuthor, bobId, ContactId contactId = contactManager.addContact(aliceAuthor, bobId);
master, timestamp, false, true); // Derive and store the transport keys
keyManager.addContact(contactId, master, timestamp, false);
// Set up an event listener // Set up an event listener
MessageListener listener = new MessageListener(); MessageListener listener = new MessageListener();
bob.getInstance(EventBus.class).addListener(listener); bob.getEventBus().addListener(listener);
// Read and recognise the tag // Read and recognise the tag
ByteArrayInputStream in = new ByteArrayInputStream(stream); ByteArrayInputStream in = new ByteArrayInputStream(stream);
byte[] tag = new byte[TAG_LENGTH]; byte[] tag = new byte[TAG_LENGTH];

View File

@@ -1,5 +1,6 @@
apply plugin: 'com.android.application' apply plugin: 'com.android.application'
apply plugin: 'witness' apply plugin: 'witness'
apply plugin: 'com.neenbedankt.android-apt'
repositories { repositories {
jcenter() jcenter()
@@ -27,10 +28,13 @@ dependencies {
exclude module: 'support-v4' exclude module: 'support-v4'
exclude module: 'recyclerview-v7' exclude module: 'recyclerview-v7'
} }
compile "org.roboguice:roboguice:2.0"
compile "info.guardianproject.panic:panic:0.5" compile "info.guardianproject.panic:panic:0.5"
compile "info.guardianproject.trustedintents:trustedintents:0.2" compile "info.guardianproject.trustedintents:trustedintents:0.2"
compile "de.hdodenhof:circleimageview:2.0.0" compile "de.hdodenhof:circleimageview:2.0.0"
apt 'com.google.dagger:dagger-compiler:2.0.2'
provided 'javax.annotation:jsr250-api:1.0'
compile 'cglib:cglib-nodep:3.1'
} }
dependencyVerification { dependencyVerification {
@@ -42,7 +46,6 @@ dependencyVerification {
'com.android.support:design:41a9cd75ca78f25df5f573db7cedf8bb66beae00c330943923ba9f3e2051736d', 'com.android.support:design:41a9cd75ca78f25df5f573db7cedf8bb66beae00c330943923ba9f3e2051736d',
'com.android.support:support-annotations:f347a35b9748a4103b39a6714a77e2100f488d623fd6268e259c177b200e9d82', 'com.android.support:support-annotations:f347a35b9748a4103b39a6714a77e2100f488d623fd6268e259c177b200e9d82',
'com.android.support:recyclerview-v7:7606373da0931a1e62588335465a0e390cd676c98117edab29220317495faefd', 'com.android.support:recyclerview-v7:7606373da0931a1e62588335465a0e390cd676c98117edab29220317495faefd',
'org.roboguice:roboguice:c5302f2648170ee6015a0d18fe0fcc87e09e415a34aeae3566e8d1a9dbb53f28',
'info.guardianproject.panic:panic:a7ed9439826db2e9901649892cf9afbe76f00991b768d8f4c26332d7c9406cb2', 'info.guardianproject.panic:panic:a7ed9439826db2e9901649892cf9afbe76f00991b768d8f4c26332d7c9406cb2',
'info.guardianproject.trustedintents:trustedintents:6221456d8821a8d974c2acf86306900237cf6afaaa94a4c9c44e161350f80f3e', 'info.guardianproject.trustedintents:trustedintents:6221456d8821a8d974c2acf86306900237cf6afaaa94a4c9c44e161350f80f3e',
] ]
@@ -95,4 +98,4 @@ android {
lintOptions { lintOptions {
abortOnError false abortOnError false
} }
} }

View File

@@ -46,6 +46,8 @@
-keep class javax.inject.** { *; } -keep class javax.inject.** { *; }
-keep class javax.annotation.** { *; } -keep class javax.annotation.** { *; }
-keep class roboguice.** { *; } -keep class roboguice.** { *; }
-keep class dagger.** { *; }
-keep class com.google.** { *; }
-dontwarn org.h2.** -dontwarn org.h2.**
-dontnote org.h2.** -dontnote org.h2.**
@@ -53,4 +55,7 @@
-dontwarn org.briarproject.plugins.tcp.** -dontwarn org.briarproject.plugins.tcp.**
-dontwarn roboguice.** -dontwarn roboguice.**
-dontwarn net.sourceforge.jsocks.** -dontwarn net.sourceforge.jsocks.**
-dontnote android.support.** -dontnote android.support.**
-dontnote dagger.**
-dontwarn dagger.**
-dontwarn com.google.common.**

View File

@@ -23,11 +23,9 @@ import org.briarproject.api.crypto.CryptoComponent;
import javax.inject.Inject; import javax.inject.Inject;
import roboguice.RoboGuice;
public class AsymmetricIdenticon extends IdenticonView { public class AsymmetricIdenticon extends IdenticonView {
@Inject private CryptoComponent mCrypto; @Inject protected CryptoComponent mCrypto;
private IdenticonBase mDelegate; private IdenticonBase mDelegate;
public AsymmetricIdenticon(Context context) { public AsymmetricIdenticon(Context context) {
@@ -51,7 +49,6 @@ public class AsymmetricIdenticon extends IdenticonView {
} }
private void initDelegate() { private void initDelegate() {
RoboGuice.injectMembers(getContext(), this);
mDelegate = new IdenticonBase() { mDelegate = new IdenticonBase() {
@Override @Override
protected CryptoComponent getCrypto() { protected CryptoComponent getCrypto() {

View File

@@ -23,13 +23,11 @@ import org.briarproject.api.crypto.CryptoComponent;
import javax.inject.Inject; import javax.inject.Inject;
import roboguice.RoboGuice;
public class SymmetricIdenticon extends IdenticonView { public class SymmetricIdenticon extends IdenticonView {
private static final int CENTER_COLUMN_INDEX = 5; private static final int CENTER_COLUMN_INDEX = 5;
@Inject private CryptoComponent mCrypto; @Inject protected CryptoComponent mCrypto;
private IdenticonBase mDelegate; private IdenticonBase mDelegate;
public SymmetricIdenticon(Context context) { public SymmetricIdenticon(Context context) {
@@ -48,7 +46,6 @@ public class SymmetricIdenticon extends IdenticonView {
} }
private void initDelegate() { private void initDelegate() {
RoboGuice.injectMembers(getContext(), this);
mDelegate = new IdenticonBase() { mDelegate = new IdenticonBase() {
@Override @Override
protected CryptoComponent getCrypto() { protected CryptoComponent getCrypto() {

View File

@@ -0,0 +1,70 @@
package org.briarproject.android;
import org.briarproject.android.contact.ContactListFragment;
import org.briarproject.android.contact.ConversationActivity;
import org.briarproject.android.forum.AvailableForumsActivity;
import org.briarproject.android.forum.CreateForumActivity;
import org.briarproject.android.forum.ForumActivity;
import org.briarproject.android.forum.ForumListFragment;
import org.briarproject.android.forum.ReadForumPostActivity;
import org.briarproject.android.forum.ShareForumActivity;
import org.briarproject.android.forum.WriteForumPostActivity;
import org.briarproject.android.fragment.SettingsFragment;
import org.briarproject.android.identity.CreateIdentityActivity;
import org.briarproject.android.invitation.AddContactActivity;
import org.briarproject.android.panic.PanicPreferencesActivity;
import org.briarproject.android.panic.PanicResponderActivity;
import org.briarproject.contact.ContactModule;
import org.briarproject.crypto.CryptoModule;
import org.briarproject.data.DataModule;
import org.briarproject.db.DatabaseModule;
import org.briarproject.event.EventModule;
import org.briarproject.forum.ForumModule;
import org.briarproject.identity.IdentityModule;
import org.briarproject.invitation.InvitationModule;
import org.briarproject.lifecycle.LifecycleModule;
import org.briarproject.messaging.MessagingModule;
import org.briarproject.plugins.AndroidPluginsModule;
import org.briarproject.properties.PropertiesModule;
import org.briarproject.reliability.ReliabilityModule;
import org.briarproject.settings.SettingsModule;
import org.briarproject.sync.SyncModule;
import org.briarproject.system.AndroidSystemModule;
import org.briarproject.transport.TransportModule;
import javax.inject.Singleton;
import dagger.Component;
@Singleton
@Component(
modules = {AppModule.class, AndroidModule.class, DatabaseModule.class,
CryptoModule.class, LifecycleModule.class,
ReliabilityModule.class, MessagingModule.class,
InvitationModule.class, ForumModule.class, IdentityModule.class,
EventModule.class, DataModule.class, ContactModule.class,
AndroidSystemModule.class, AndroidPluginsModule.class,
PropertiesModule.class, TransportModule.class, SyncModule.class,
SettingsModule.class})
public interface AndroidComponent {
void inject(SplashScreenActivity activity);
void inject(SetupActivity activity);
void inject(NavDrawerActivity activity);
void inject(PasswordActivity activity);
void inject(BriarService activity);
void inject(PanicResponderActivity activity);
void inject(PanicPreferencesActivity activity);
void inject(AddContactActivity activity);
void inject(ConversationActivity activity);
void inject(CreateIdentityActivity activity);
void inject(TestingActivity activity);
void inject(AvailableForumsActivity activity);
void inject(WriteForumPostActivity activity);
void inject(CreateForumActivity activity);
void inject(ShareForumActivity activity);
void inject(ReadForumPostActivity activity);
void inject(ForumActivity activity);
void inject(ContactListFragment fragment);
void inject(SettingsFragment fragment);
void inject(ForumListFragment fragment);
}

View File

@@ -1,9 +1,8 @@
package org.briarproject.android; package org.briarproject.android;
import android.app.Application; import android.app.Application;
import android.content.SharedPreferences;
import com.google.inject.AbstractModule; import android.support.v7.preference.PreferenceManager;
import com.google.inject.Provides;
import org.briarproject.api.android.AndroidExecutor; import org.briarproject.api.android.AndroidExecutor;
import org.briarproject.api.android.AndroidNotificationManager; import org.briarproject.api.android.AndroidNotificationManager;
@@ -18,9 +17,13 @@ import java.io.File;
import javax.inject.Singleton; import javax.inject.Singleton;
import dagger.Module;
import dagger.Provides;
import static android.content.Context.MODE_PRIVATE; import static android.content.Context.MODE_PRIVATE;
public class AndroidModule extends AbstractModule { @Module
public class AndroidModule {
private final UiCallback uiCallback; private final UiCallback uiCallback;
@@ -42,17 +45,27 @@ public class AndroidModule extends AbstractModule {
}; };
} }
@Override @Provides
protected void configure() { UiCallback provideUICallback() {
bind(AndroidExecutor.class).to(AndroidExecutorImpl.class).in( return uiCallback;
Singleton.class);
bind(ReferenceManager.class).to(ReferenceManagerImpl.class).in(
Singleton.class);
bind(UiCallback.class).toInstance(uiCallback);
} }
@Provides @Singleton @Provides
DatabaseConfig getDatabaseConfig(final Application app) { @Singleton
ReferenceManager provideReferenceManager() {
return new ReferenceManagerImpl();
}
@Provides
@Singleton
AndroidExecutor provideAndroidExecutor(
AndroidExecutorImpl androidExecutor) {
return androidExecutor;
}
@Provides
@Singleton
DatabaseConfig provideDatabaseConfig(final Application app) {
final File dir = app.getApplicationContext().getDir("db", MODE_PRIVATE); final File dir = app.getApplicationContext().getDir("db", MODE_PRIVATE);
return new DatabaseConfig() { return new DatabaseConfig() {
@@ -80,12 +93,15 @@ public class AndroidModule extends AbstractModule {
}; };
} }
@Provides @Singleton
AndroidNotificationManager getAndroidNotificationManager( @Provides
@Singleton
AndroidNotificationManager provideAndroidNotificationManager(
LifecycleManager lifecycleManager, EventBus eventBus, LifecycleManager lifecycleManager, EventBus eventBus,
AndroidNotificationManagerImpl notificationManager) { AndroidNotificationManagerImpl notificationManager) {
lifecycleManager.register(notificationManager); lifecycleManager.register(notificationManager);
eventBus.addListener(notificationManager); eventBus.addListener(notificationManager);
return notificationManager; return notificationManager;
} }
} }

View File

@@ -0,0 +1,25 @@
package org.briarproject.android;
import android.app.Application;
import android.content.Context;
import javax.inject.Singleton;
import dagger.Module;
import dagger.Provides;
@Module
public class AppModule {
Application application;
public AppModule(Application application) {
this.application = application;
}
@Provides
@Singleton
Application providesApplication() {
return application;
}
}

View File

@@ -9,125 +9,31 @@ import android.support.v7.app.AppCompatActivity;
import android.view.View; import android.view.View;
import android.view.inputmethod.InputMethodManager; import android.view.inputmethod.InputMethodManager;
import com.google.inject.Inject;
import com.google.inject.Key;
import java.util.HashMap; import javax.inject.Inject;
import java.util.Map;
import roboguice.RoboGuice;
import roboguice.activity.event.OnActivityResultEvent;
import roboguice.activity.event.OnConfigurationChangedEvent;
import roboguice.activity.event.OnContentChangedEvent;
import roboguice.activity.event.OnCreateEvent;
import roboguice.activity.event.OnDestroyEvent;
import roboguice.activity.event.OnNewIntentEvent;
import roboguice.activity.event.OnPauseEvent;
import roboguice.activity.event.OnRestartEvent;
import roboguice.activity.event.OnResumeEvent;
import roboguice.activity.event.OnStartEvent;
import roboguice.activity.event.OnStopEvent;
import roboguice.event.EventManager;
import roboguice.inject.RoboInjector;
import roboguice.util.RoboContext;
import static android.view.WindowManager.LayoutParams.FLAG_SECURE; import static android.view.WindowManager.LayoutParams.FLAG_SECURE;
import static android.view.inputmethod.InputMethodManager.SHOW_IMPLICIT; import static android.view.inputmethod.InputMethodManager.SHOW_IMPLICIT;
import static org.briarproject.android.TestingConstants.PREVENT_SCREENSHOTS; import static org.briarproject.android.TestingConstants.PREVENT_SCREENSHOTS;
public abstract class BaseActivity extends AppCompatActivity public abstract class BaseActivity extends AppCompatActivity {
implements RoboContext {
public final static String PREFS_NAME = "db"; public final static String PREFS_NAME = "db";
public final static String PREF_DB_KEY = "key"; public final static String PREF_DB_KEY = "key";
public final static String PREF_SEEN_WELCOME_MESSAGE = "welcome_message"; public final static String PREF_SEEN_WELCOME_MESSAGE = "welcome_message";
private final HashMap<Key<?>, Object> scopedObjects =
new HashMap<Key<?>, Object>();
@Inject private EventManager eventManager;
@Override @Override
public void onCreate(Bundle savedInstanceState) { public void onCreate(Bundle savedInstanceState) {
RoboInjector injector = RoboGuice.getInjector(this);
injector.injectMembersWithoutViews(this);
super.onCreate(savedInstanceState); super.onCreate(savedInstanceState);
eventManager.fire(new OnCreateEvent(savedInstanceState));
if (PREVENT_SCREENSHOTS) getWindow().addFlags(FLAG_SECURE); if (PREVENT_SCREENSHOTS) getWindow().addFlags(FLAG_SECURE);
AndroidComponent component =
((BriarApplication) getApplication()).getApplicationComponent();
injectActivity(component);
} }
protected void onRestart() { public abstract void injectActivity(AndroidComponent component);
super.onRestart();
eventManager.fire(new OnRestartEvent());
}
protected void onStart() {
super.onStart();
eventManager.fire(new OnStartEvent());
}
protected void onResume() {
super.onResume();
eventManager.fire(new OnResumeEvent());
}
protected void onPause() {
super.onPause();
eventManager.fire(new OnPauseEvent());
}
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
eventManager.fire(new OnNewIntentEvent());
}
protected void onStop() {
try {
eventManager.fire(new OnStopEvent());
} finally {
super.onStop();
}
}
protected void onDestroy() {
try {
eventManager.fire(new OnDestroyEvent());
} finally {
try {
RoboGuice.destroyInjector(this);
} finally {
super.onDestroy();
}
}
}
public void onConfigurationChanged(Configuration newConfig) {
Configuration currentConfig = getResources().getConfiguration();
super.onConfigurationChanged(newConfig);
eventManager.fire(new OnConfigurationChangedEvent(currentConfig,
newConfig));
}
public void onContentChanged() {
super.onContentChanged();
RoboGuice.getInjector(this).injectViewMembers(this);
eventManager.fire(new OnContentChangedEvent());
}
protected void onActivityResult(int requestCode, int resultCode,
Intent data) {
super.onActivityResult(requestCode, resultCode, data);
eventManager.fire(new OnActivityResultEvent(requestCode, resultCode,
data));
}
@Override
public Map<Key<?>, Object> getScopedObjectMap() {
return scopedObjects;
}
private SharedPreferences getSharedPrefs() { private SharedPreferences getSharedPrefs() {
return getSharedPreferences(PREFS_NAME, MODE_PRIVATE); return getSharedPreferences(PREFS_NAME, MODE_PRIVATE);

View File

@@ -27,7 +27,8 @@ import static android.content.Intent.FLAG_ACTIVITY_SINGLE_TOP;
@SuppressLint("Registered") @SuppressLint("Registered")
public abstract class BriarActivity extends BaseActivity { public abstract class BriarActivity extends BaseActivity {
public static final String KEY_LOCAL_AUTHOR_HANDLE = "briar.LOCAL_AUTHOR_HANDLE"; public static final String KEY_LOCAL_AUTHOR_HANDLE =
"briar.LOCAL_AUTHOR_HANDLE";
public static final String KEY_STARTUP_FAILED = "briar.STARTUP_FAILED"; public static final String KEY_STARTUP_FAILED = "briar.STARTUP_FAILED";
public static final int REQUEST_PASSWORD = 1; public static final int REQUEST_PASSWORD = 1;
@@ -38,16 +39,21 @@ public abstract class BriarActivity extends BaseActivity {
private final BriarServiceConnection serviceConnection = private final BriarServiceConnection serviceConnection =
new BriarServiceConnection(); new BriarServiceConnection();
@Inject private DatabaseConfig databaseConfig; @Inject
DatabaseConfig databaseConfig;
private boolean bound = false; private boolean bound = false;
// Fields that are accessed from background threads must be volatile // Fields that are accessed from background threads must be volatile
@Inject @DatabaseExecutor private volatile Executor dbExecutor; @Inject
@Inject private volatile LifecycleManager lifecycleManager; @DatabaseExecutor
protected volatile Executor dbExecutor;
@Inject
protected volatile LifecycleManager lifecycleManager;
@Override @Override
public void onCreate(Bundle state) { public void onCreate(Bundle state) {
super.onCreate(state); super.onCreate(state);
if (databaseConfig.getEncryptionKey() != null) startAndBindService(); if (databaseConfig.getEncryptionKey() != null) startAndBindService();
} }

View File

@@ -11,6 +11,8 @@ public class BriarApplication extends Application {
private static final Logger LOG = private static final Logger LOG =
Logger.getLogger(BriarApplication.class.getName()); Logger.getLogger(BriarApplication.class.getName());
private AndroidComponent applicationComponent;
@Override @Override
public void onCreate() { public void onCreate() {
super.onCreate(); super.onCreate();
@@ -20,5 +22,14 @@ public class BriarApplication extends Application {
Context ctx = getApplicationContext(); Context ctx = getApplicationContext();
CrashHandler newHandler = new CrashHandler(ctx, oldHandler); CrashHandler newHandler = new CrashHandler(ctx, oldHandler);
Thread.setDefaultUncaughtExceptionHandler(newHandler); Thread.setDefaultUncaughtExceptionHandler(newHandler);
applicationComponent = DaggerAndroidComponent.builder()
.appModule(new AppModule(this))
.androidModule(new AndroidModule())
.build();
}
public AndroidComponent getApplicationComponent() {
return applicationComponent;
} }
} }

View File

@@ -2,6 +2,7 @@ package org.briarproject.android;
import android.app.NotificationManager; import android.app.NotificationManager;
import android.app.PendingIntent; import android.app.PendingIntent;
import android.app.Service;
import android.content.ComponentName; import android.content.ComponentName;
import android.content.Intent; import android.content.Intent;
import android.content.ServiceConnection; import android.content.ServiceConnection;
@@ -22,8 +23,6 @@ import java.util.logging.Logger;
import javax.inject.Inject; import javax.inject.Inject;
import roboguice.service.RoboService;
import static android.app.PendingIntent.FLAG_UPDATE_CURRENT; import static android.app.PendingIntent.FLAG_UPDATE_CURRENT;
import static android.content.Intent.FLAG_ACTIVITY_CLEAR_TOP; import static android.content.Intent.FLAG_ACTIVITY_CLEAR_TOP;
import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK; import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK;
@@ -34,7 +33,7 @@ import static java.util.logging.Level.WARNING;
import static org.briarproject.api.lifecycle.LifecycleManager.StartResult.ALREADY_RUNNING; import static org.briarproject.api.lifecycle.LifecycleManager.StartResult.ALREADY_RUNNING;
import static org.briarproject.api.lifecycle.LifecycleManager.StartResult.SUCCESS; import static org.briarproject.api.lifecycle.LifecycleManager.StartResult.SUCCESS;
public class BriarService extends RoboService { public class BriarService extends Service {
private static final int ONGOING_NOTIFICATION_ID = 1; private static final int ONGOING_NOTIFICATION_ID = 1;
private static final int FAILURE_NOTIFICATION_ID = 2; private static final int FAILURE_NOTIFICATION_ID = 2;
@@ -45,16 +44,20 @@ public class BriarService extends RoboService {
private final AtomicBoolean created = new AtomicBoolean(false); private final AtomicBoolean created = new AtomicBoolean(false);
private final Binder binder = new BriarBinder(); private final Binder binder = new BriarBinder();
@Inject private DatabaseConfig databaseConfig; @Inject protected DatabaseConfig databaseConfig;
// Fields that are accessed from background threads must be volatile // Fields that are accessed from background threads must be volatile
@Inject private volatile LifecycleManager lifecycleManager; @Inject protected volatile LifecycleManager lifecycleManager;
@Inject private volatile AndroidExecutor androidExecutor; @Inject protected volatile AndroidExecutor androidExecutor;
private volatile boolean started = false; private volatile boolean started = false;
@Override @Override
public void onCreate() { public void onCreate() {
super.onCreate(); super.onCreate();
((BriarApplication) this.getApplication())
.getApplicationComponent().inject(this);
LOG.info("Created"); LOG.info("Created");
if (created.getAndSet(true)) { if (created.getAndSet(true)) {
LOG.info("Already created"); LOG.info("Already created");

View File

@@ -14,6 +14,7 @@ import android.view.LayoutInflater;
import android.view.View; import android.view.View;
import android.view.ViewGroup; import android.view.ViewGroup;
import android.widget.BaseAdapter; import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.GridView; import android.widget.GridView;
import android.widget.ImageView; import android.widget.ImageView;
import android.widget.TextView; import android.widget.TextView;
@@ -42,9 +43,6 @@ import java.util.logging.Logger;
import javax.inject.Inject; import javax.inject.Inject;
import roboguice.RoboGuice;
import roboguice.inject.InjectView;
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;
@@ -60,33 +58,23 @@ public class NavDrawerActivity extends BriarFragmentActivity implements
private ActionBarDrawerToggle drawerToggle; private ActionBarDrawerToggle drawerToggle;
@Inject @Inject
private ReferenceManager referenceManager; protected ReferenceManager referenceManager;
// Fields that are accessed from background threads must be volatile // Fields that are accessed from background threads must be volatile
@Inject @Inject
private volatile IdentityManager identityManager; protected volatile IdentityManager identityManager;
@Inject @Inject
private PluginManager pluginManager; protected PluginManager pluginManager;
@Inject @Inject
protected volatile EventBus eventBus; protected volatile EventBus eventBus;
@InjectView(R.id.toolbar)
private Toolbar toolbar; private Toolbar toolbar;
@InjectView(R.id.drawer_layout)
private DrawerLayout drawerLayout; private DrawerLayout drawerLayout;
@InjectView(R.id.nav_btn_contacts) private Button contactButton;
private AppCompatButton contactButton; private Button forumsButton;
@InjectView(R.id.nav_btn_contacts) private Button settingsButton;
private AppCompatButton forumsButton;
@InjectView(R.id.nav_btn_contacts)
private AppCompatButton settingsButton;
@InjectView(R.id.nav_menu_header)
private TextView menuHeader;
@InjectView(R.id.title_progress_bar)
private TextView progressTitle;
@InjectView(R.id.container_progress)
ViewGroup progressViewGroup;
@InjectView(R.id.transportsView)
private GridView transportsView; private GridView transportsView;
private TextView progressTitle;
private ViewGroup progressViewGroup;
private List<Transport> transports; private List<Transport> transports;
private BaseAdapter transportsAdapter; private BaseAdapter transportsAdapter;
@@ -104,6 +92,11 @@ public class NavDrawerActivity extends BriarFragmentActivity implements
} }
} }
@Override
public void injectActivity(AndroidComponent component) {
component.inject(this);
}
@SuppressWarnings("ConstantConditions") @SuppressWarnings("ConstantConditions")
@Override @Override
public void onCreate(Bundle state) { public void onCreate(Bundle state) {
@@ -112,9 +105,16 @@ public class NavDrawerActivity extends BriarFragmentActivity implements
if (isStartupFailed(getIntent())) if (isStartupFailed(getIntent()))
return; return;
// TODO inflate and inject with @ContentView with RoboGuice 3.0 and later
setContentView(R.layout.activity_nav_drawer); setContentView(R.layout.activity_nav_drawer);
RoboGuice.getInjector(this).injectViewMembers(this);
toolbar = (Toolbar)findViewById(R.id.toolbar);
drawerLayout = (DrawerLayout)findViewById(R.id.drawer_layout);
contactButton = (Button)findViewById(R.id.nav_btn_contacts);
forumsButton = (Button)findViewById(R.id.nav_btn_forums);
settingsButton = (Button)findViewById(R.id.nav_btn_settings);
transportsView = (GridView)findViewById(R.id.transportsView);
progressTitle = (TextView)findViewById(R.id.title_progress_bar);
progressViewGroup = (ViewGroup)findViewById(R.id.container_progress);
setSupportActionBar(toolbar); setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setDisplayHomeAsUpEnabled(true);

View File

@@ -34,7 +34,7 @@ import static android.view.View.VISIBLE;
public class PasswordActivity extends BaseActivity { public class PasswordActivity extends BaseActivity {
@Inject @CryptoExecutor private Executor cryptoExecutor; @Inject @CryptoExecutor protected Executor cryptoExecutor;
private Button signInButton; private Button signInButton;
private ProgressBar progress; private ProgressBar progress;
private TextInputLayout input; private TextInputLayout input;
@@ -43,8 +43,8 @@ public class PasswordActivity extends BaseActivity {
private byte[] encrypted; private byte[] encrypted;
// Fields that are accessed from background threads must be volatile // Fields that are accessed from background threads must be volatile
@Inject private volatile CryptoComponent crypto; @Inject protected volatile CryptoComponent crypto;
@Inject private volatile DatabaseConfig databaseConfig; @Inject protected volatile DatabaseConfig databaseConfig;
@Override @Override
public void onCreate(Bundle state) { public void onCreate(Bundle state) {
@@ -74,7 +74,8 @@ public class PasswordActivity extends BaseActivity {
password.addTextChangedListener(new TextWatcher() { password.addTextChangedListener(new TextWatcher() {
@Override @Override
public void beforeTextChanged(CharSequence s, int start, int count, public void beforeTextChanged(CharSequence s, int start, int count,
int after) {} int after) {
}
@Override @Override
public void onTextChanged(CharSequence s, int start, int before, public void onTextChanged(CharSequence s, int start, int before,
@@ -83,10 +84,16 @@ public class PasswordActivity extends BaseActivity {
} }
@Override @Override
public void afterTextChanged(Editable s) {} public void afterTextChanged(Editable s) {
}
}); });
} }
@Override
public void injectActivity(AndroidComponent component) {
component.inject(this);
}
@Override @Override
public void onBackPressed() { public void onBackPressed() {
// Show the home screen rather than another password prompt // Show the home screen rather than another password prompt

View File

@@ -33,8 +33,6 @@ import java.util.logging.Logger;
import javax.inject.Inject; import javax.inject.Inject;
import roboguice.inject.InjectView;
import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK; import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK;
import static android.view.View.INVISIBLE; import static android.view.View.INVISIBLE;
import static android.view.View.VISIBLE; import static android.view.View.VISIBLE;
@@ -50,29 +48,40 @@ public class SetupActivity extends BaseActivity implements OnClickListener,
private static final Logger LOG = private static final Logger LOG =
Logger.getLogger(SetupActivity.class.getName()); Logger.getLogger(SetupActivity.class.getName());
@Inject @CryptoExecutor private Executor cryptoExecutor; @Inject @CryptoExecutor protected Executor cryptoExecutor;
@Inject private PasswordStrengthEstimator strengthEstimator; @Inject protected PasswordStrengthEstimator strengthEstimator;
@InjectView(R.id.nickname_entry_wrapper) TextInputLayout nicknameEntryWrapper;
@InjectView(R.id.password_entry_wrapper) TextInputLayout passwordEntryWrapper;
@InjectView(R.id.password_confirm_wrapper) TextInputLayout passwordConfirmationWrapper;
@InjectView(R.id.nickname_entry) EditText nicknameEntry;
@InjectView(R.id.password_entry) EditText passwordEntry;
@InjectView(R.id.password_confirm) EditText passwordConfirmation;
@InjectView(R.id.strength_meter) StrengthMeter strengthMeter;
@InjectView(R.id.create_account) Button createAccountButton;
@InjectView(R.id.progress_wheel) ProgressBar progress;
// Fields that are accessed from background threads must be volatile // Fields that are accessed from background threads must be volatile
@Inject private volatile CryptoComponent crypto; @Inject protected volatile CryptoComponent crypto;
@Inject private volatile DatabaseConfig databaseConfig; @Inject protected volatile DatabaseConfig databaseConfig;
@Inject private volatile AuthorFactory authorFactory; @Inject protected volatile AuthorFactory authorFactory;
@Inject private volatile ReferenceManager referenceManager; @Inject protected volatile ReferenceManager referenceManager;
TextInputLayout nicknameEntryWrapper;
TextInputLayout passwordEntryWrapper;
TextInputLayout passwordConfirmationWrapper;
EditText nicknameEntry;
EditText passwordEntry;
EditText passwordConfirmation;
StrengthMeter strengthMeter;
Button createAccountButton;
ProgressBar progress;
@Override @Override
public void onCreate(Bundle state) { public void onCreate(Bundle state) {
super.onCreate(state); super.onCreate(state);
setContentView(R.layout.activity_setup); setContentView(R.layout.activity_setup);
nicknameEntryWrapper = (TextInputLayout)findViewById(R.id.nickname_entry_wrapper);
passwordEntryWrapper = (TextInputLayout)findViewById(R.id.password_entry_wrapper);
passwordConfirmationWrapper = (TextInputLayout)findViewById(R.id.password_confirm_wrapper);
nicknameEntry = (EditText)findViewById(R.id.nickname_entry);
passwordEntry = (EditText)findViewById(R.id.password_entry);
passwordConfirmation = (EditText)findViewById(R.id.password_confirm);
strengthMeter = (StrengthMeter)findViewById(R.id.strength_meter);
createAccountButton = (Button)findViewById(R.id.create_account);
progress = (ProgressBar)findViewById(R.id.progress_wheel);
if (PREVENT_SCREENSHOTS) getWindow().addFlags(FLAG_SECURE); if (PREVENT_SCREENSHOTS) getWindow().addFlags(FLAG_SECURE);
TextWatcher tw = new TextWatcher() { TextWatcher tw = new TextWatcher() {
@@ -99,6 +108,11 @@ public class SetupActivity extends BaseActivity implements OnClickListener,
createAccountButton.setOnClickListener(this); createAccountButton.setOnClickListener(this);
} }
@Override
public void injectActivity(AndroidComponent component) {
component.inject(this);
}
private void enableOrDisableContinueButton() { private void enableOrDisableContinueButton() {
if (progress == null) return; // Not created yet if (progress == null) return; // Not created yet
if (passwordEntry.getText().length() > 0 && passwordEntry.hasFocus()) if (passwordEntry.getText().length() > 0 && passwordEntry.hasFocus())

View File

@@ -1,9 +1,11 @@
package org.briarproject.android; package org.briarproject.android;
import android.app.Activity;
import android.content.Intent; import android.content.Intent;
import android.content.SharedPreferences; import android.content.SharedPreferences;
import android.graphics.Color; import android.graphics.Color;
import android.os.Bundle; import android.os.Bundle;
import android.os.Handler;
import android.os.StrictMode; import android.os.StrictMode;
import android.os.StrictMode.ThreadPolicy; import android.os.StrictMode.ThreadPolicy;
import android.os.StrictMode.VmPolicy; import android.os.StrictMode.VmPolicy;
@@ -11,29 +13,22 @@ import android.support.v7.preference.PreferenceManager;
import android.widget.ImageView; import android.widget.ImageView;
import android.widget.LinearLayout; import android.widget.LinearLayout;
import com.google.inject.Injector;
import org.briarproject.R; import org.briarproject.R;
import org.briarproject.android.util.AndroidUtils;
import org.briarproject.android.util.LayoutUtils; import org.briarproject.android.util.LayoutUtils;
import org.briarproject.api.db.DatabaseConfig; import org.briarproject.api.db.DatabaseConfig;
import org.briarproject.api.ui.UiCallback;
import org.briarproject.util.FileUtils;
import java.util.logging.Logger; import java.util.logging.Logger;
import roboguice.RoboGuice; import javax.inject.Inject;
import roboguice.activity.RoboSplashActivity;
import static android.view.Gravity.CENTER; import static android.view.Gravity.CENTER;
import static android.view.WindowManager.LayoutParams.FLAG_SECURE;
import static java.util.logging.Level.INFO;
import static org.briarproject.android.BaseActivity.PREFS_NAME;
import static org.briarproject.android.BaseActivity.PREF_DB_KEY;
import static org.briarproject.android.TestingConstants.DEFAULT_LOG_LEVEL; import static org.briarproject.android.TestingConstants.DEFAULT_LOG_LEVEL;
import static org.briarproject.android.TestingConstants.PREVENT_SCREENSHOTS;
import static org.briarproject.android.TestingConstants.TESTING; import static org.briarproject.android.TestingConstants.TESTING;
import static org.briarproject.android.util.CommonLayoutParams.MATCH_MATCH; import static org.briarproject.android.util.CommonLayoutParams.MATCH_MATCH;
public class SplashScreenActivity extends RoboSplashActivity { public class SplashScreenActivity extends BaseActivity {
private static final Logger LOG = private static final Logger LOG =
Logger.getLogger(SplashScreenActivity.class.getName()); Logger.getLogger(SplashScreenActivity.class.getName());
@@ -43,18 +38,18 @@ public class SplashScreenActivity extends RoboSplashActivity {
private long now = System.currentTimeMillis(); private long now = System.currentTimeMillis();
@Inject
DatabaseConfig dbConfig;
public SplashScreenActivity() { public SplashScreenActivity() {
Logger.getLogger("").setLevel(DEFAULT_LOG_LEVEL); Logger.getLogger("").setLevel(DEFAULT_LOG_LEVEL);
enableStrictMode(); enableStrictMode();
minDisplayMs = 500;
} }
@Override @Override
public void onCreate(Bundle state) { public void onCreate(Bundle state) {
super.onCreate(state); super.onCreate(state);
if (PREVENT_SCREENSHOTS) getWindow().addFlags(FLAG_SECURE);
LinearLayout layout = new LinearLayout(this); LinearLayout layout = new LinearLayout(this);
layout.setLayoutParams(MATCH_MATCH); layout.setLayoutParams(MATCH_MATCH);
layout.setGravity(CENTER); layout.setGravity(CENTER);
@@ -70,28 +65,36 @@ public class SplashScreenActivity extends RoboSplashActivity {
setPreferencesDefaults(); setPreferencesDefaults();
setContentView(layout); setContentView(layout);
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
startNextActivity();
}
}, 500);
} }
@Override @Override
public void injectActivity(AndroidComponent component) {
component.inject(this);
}
protected void startNextActivity() { protected void startNextActivity() {
long duration = System.currentTimeMillis() - now;
if (LOG.isLoggable(INFO))
LOG.info("Guice startup took " + duration + " ms");
if (System.currentTimeMillis() >= EXPIRY_DATE) { if (System.currentTimeMillis() >= EXPIRY_DATE) {
LOG.info("Expired"); LOG.info("Expired");
startActivity(new Intent(this, ExpiredActivity.class)); startActivity(new Intent(this, ExpiredActivity.class));
} else { } else {
SharedPreferences prefs = getSharedPreferences(PREFS_NAME, String hex = getEncryptedDatabaseKey();
MODE_PRIVATE);
String hex = prefs.getString(PREF_DB_KEY, null); if (dbConfig != null) {
Injector i = RoboGuice.getBaseApplicationInjector(getApplication()); if (hex != null && dbConfig.databaseExists()) {
DatabaseConfig databaseConfig = i.getInstance(DatabaseConfig.class); startActivity(new Intent(this, NavDrawerActivity.class));
if (hex != null && databaseConfig.databaseExists()) { } else {
startActivity(new Intent(this, NavDrawerActivity.class)); clearSharedPrefs();
} else { FileUtils.deleteFileOrDir(
prefs.edit().clear().apply(); dbConfig.getDatabaseDirectory());
AndroidUtils.deleteAppData(this); startActivity(new Intent(this, SetupActivity.class));
startActivity(new Intent(this, SetupActivity.class)); }
} }
} }
} }
@@ -114,7 +117,7 @@ public class SplashScreenActivity extends RoboSplashActivity {
@Override @Override
public void run() { public void run() {
PreferenceManager.setDefaultValues(SplashScreenActivity.this, PreferenceManager.setDefaultValues(SplashScreenActivity.this,
R.xml.panic_preferences, false); R.xml.panic_preferences, false);
} }
}.start(); }.start();
} }

View File

@@ -19,6 +19,11 @@ public class StartupFailureActivity extends BaseActivity {
handleIntent(getIntent()); handleIntent(getIntent());
} }
@Override
public void injectActivity(AndroidComponent component) {
}
private void handleIntent(Intent i) { private void handleIntent(Intent i) {
StartResult result = (StartResult) i.getSerializableExtra("briar.START_RESULT"); StartResult result = (StartResult) i.getSerializableExtra("briar.START_RESULT");
int notificationId = i.getIntExtra("briar.FAILURE_NOTIFICATION_ID", -1); int notificationId = i.getIntExtra("briar.FAILURE_NOTIFICATION_ID", -1);

View File

@@ -75,9 +75,9 @@ public class TestingActivity extends BriarActivity implements OnClickListener {
private static final Logger LOG = private static final Logger LOG =
Logger.getLogger(TestingActivity.class.getName()); Logger.getLogger(TestingActivity.class.getName());
@Inject private PluginManager pluginManager; @Inject protected PluginManager pluginManager;
@Inject private LifecycleManager lifecycleManager; @Inject protected LifecycleManager lifecycleManager;
@Inject private TransportPropertyManager transportPropertyManager; @Inject protected TransportPropertyManager transportPropertyManager;
private ScrollView scroll = null; private ScrollView scroll = null;
private ListLoadingProgressBar progress = null; private ListLoadingProgressBar progress = null;
private LinearLayout status = null; private LinearLayout status = null;
@@ -137,6 +137,11 @@ public class TestingActivity extends BriarActivity implements OnClickListener {
setContentView(layout); setContentView(layout);
} }
@Override
public void injectActivity(AndroidComponent component) {
component.inject(this);
}
@Override @Override
public void onResume() { public void onResume() {
super.onResume(); super.onResume();

View File

@@ -10,6 +10,8 @@ import android.view.View;
import android.view.ViewGroup; import android.view.ViewGroup;
import org.briarproject.R; import org.briarproject.R;
import org.briarproject.android.AndroidComponent;
import org.briarproject.android.BriarApplication;
import org.briarproject.android.fragment.BaseEventFragment; import org.briarproject.android.fragment.BaseEventFragment;
import org.briarproject.android.invitation.AddContactActivity; import org.briarproject.android.invitation.AddContactActivity;
import org.briarproject.android.util.BriarRecyclerView; import org.briarproject.android.util.BriarRecyclerView;
@@ -64,19 +66,29 @@ public class ContactListFragment extends BaseEventFragment {
} }
@Inject @Inject
private CryptoComponent crypto; protected CryptoComponent crypto;
@Inject @Inject
private ConnectionRegistry connectionRegistry; protected ConnectionRegistry connectionRegistry;
private ContactListAdapter adapter = null; private ContactListAdapter adapter = null;
private BriarRecyclerView list = null; private BriarRecyclerView list = null;
// Fields that are accessed from background threads must be volatile // Fields that are accessed from background threads must be volatile
@Inject @Inject
private volatile ContactManager contactManager; protected volatile ContactManager contactManager;
@Inject @Inject
private volatile MessagingManager messagingManager; protected volatile MessagingManager messagingManager;
@Inject @Inject
private volatile EventBus eventBus; protected volatile EventBus eventBus;
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public void injectActivity(AndroidComponent component) {
component.inject(this);
}
@Nullable @Nullable
@Override @Override

View File

@@ -17,6 +17,7 @@ import android.widget.ImageButton;
import android.widget.Toast; import android.widget.Toast;
import org.briarproject.R; import org.briarproject.R;
import org.briarproject.android.AndroidComponent;
import org.briarproject.android.BriarActivity; import org.briarproject.android.BriarActivity;
import org.briarproject.android.util.BriarRecyclerView; import org.briarproject.android.util.BriarRecyclerView;
import org.briarproject.api.FormatException; import org.briarproject.api.FormatException;
@@ -71,10 +72,10 @@ public class ConversationActivity extends BriarActivity
private static final Logger LOG = private static final Logger LOG =
Logger.getLogger(ConversationActivity.class.getName()); Logger.getLogger(ConversationActivity.class.getName());
@Inject private CryptoComponent crypto; @Inject protected CryptoComponent crypto;
@Inject private AndroidNotificationManager notificationManager; @Inject protected AndroidNotificationManager notificationManager;
@Inject private ConnectionRegistry connectionRegistry; @Inject protected ConnectionRegistry connectionRegistry;
@Inject @CryptoExecutor private Executor cryptoExecutor; @Inject @CryptoExecutor protected Executor cryptoExecutor;
private Map<MessageId, byte[]> bodyCache = new HashMap<MessageId, byte[]>(); private Map<MessageId, byte[]> bodyCache = new HashMap<MessageId, byte[]>();
private ConversationAdapter adapter = null; private ConversationAdapter adapter = null;
private BriarRecyclerView list = null; private BriarRecyclerView list = null;
@@ -82,10 +83,10 @@ public class ConversationActivity extends BriarActivity
private ImageButton sendButton = null; private ImageButton sendButton = null;
// Fields that are accessed from background threads must be volatile // Fields that are accessed from background threads must be volatile
@Inject private volatile ContactManager contactManager; @Inject protected volatile ContactManager contactManager;
@Inject private volatile MessagingManager messagingManager; @Inject protected volatile MessagingManager messagingManager;
@Inject private volatile EventBus eventBus; @Inject protected volatile EventBus eventBus;
@Inject private volatile PrivateMessageFactory privateMessageFactory; @Inject protected volatile PrivateMessageFactory privateMessageFactory;
private volatile GroupId groupId = null; private volatile GroupId groupId = null;
private volatile ContactId contactId = null; private volatile ContactId contactId = null;
private volatile String contactName = null; private volatile String contactName = null;
@@ -115,6 +116,11 @@ public class ConversationActivity extends BriarActivity
sendButton.setOnClickListener(this); sendButton.setOnClickListener(this);
} }
@Override
public void injectActivity(AndroidComponent component) {
component.inject(this);
}
@Override @Override
public void onResume() { public void onResume() {
super.onResume(); super.onResume();

View File

@@ -8,6 +8,7 @@ import android.widget.ListView;
import android.widget.Toast; import android.widget.Toast;
import org.briarproject.R; import org.briarproject.R;
import org.briarproject.android.AndroidComponent;
import org.briarproject.android.BriarActivity; import org.briarproject.android.BriarActivity;
import org.briarproject.android.util.ListLoadingProgressBar; import org.briarproject.android.util.ListLoadingProgressBar;
import org.briarproject.api.contact.Contact; import org.briarproject.api.contact.Contact;
@@ -47,9 +48,9 @@ implements EventListener, OnItemClickListener {
private ListView list = null; private ListView list = null;
// Fields that are accessed from background threads must be volatile // Fields that are accessed from background threads must be volatile
@Inject private volatile ForumManager forumManager; @Inject protected volatile ForumManager forumManager;
@Inject private volatile ForumSharingManager forumSharingManager; @Inject protected volatile ForumSharingManager forumSharingManager;
@Inject private volatile EventBus eventBus; @Inject protected volatile EventBus eventBus;
@Override @Override
public void onCreate(Bundle state) { public void onCreate(Bundle state) {
@@ -66,6 +67,11 @@ implements EventListener, OnItemClickListener {
setContentView(loading); setContentView(loading);
} }
@Override
public void injectActivity(AndroidComponent component) {
component.inject(this);
}
@Override @Override
public void onResume() { public void onResume() {
super.onResume(); super.onResume();

View File

@@ -14,6 +14,7 @@ import android.widget.TextView.OnEditorActionListener;
import android.widget.Toast; import android.widget.Toast;
import org.briarproject.R; import org.briarproject.R;
import org.briarproject.android.AndroidComponent;
import org.briarproject.android.BriarActivity; import org.briarproject.android.BriarActivity;
import org.briarproject.android.util.LayoutUtils; import org.briarproject.android.util.LayoutUtils;
import org.briarproject.api.db.DbException; import org.briarproject.api.db.DbException;
@@ -51,7 +52,7 @@ implements OnEditorActionListener, OnClickListener {
private TextView feedback = null; private TextView feedback = null;
// Fields that are accessed from background threads must be volatile // Fields that are accessed from background threads must be volatile
@Inject private volatile ForumSharingManager forumSharingManager; @Inject protected volatile ForumSharingManager forumSharingManager;
@Override @Override
public void onCreate(Bundle state) { public void onCreate(Bundle state) {
@@ -102,6 +103,11 @@ implements OnEditorActionListener, OnClickListener {
setContentView(layout); setContentView(layout);
} }
@Override
public void injectActivity(AndroidComponent component) {
component.inject(this);
}
private void enableOrDisableCreateButton() { private void enableOrDisableCreateButton() {
if (progress == null) return; // Not created yet if (progress == null) return; // Not created yet
createForumButton.setEnabled(validateName()); createForumButton.setEnabled(validateName());

View File

@@ -13,6 +13,7 @@ import android.widget.ListView;
import android.widget.TextView; import android.widget.TextView;
import org.briarproject.R; import org.briarproject.R;
import org.briarproject.android.AndroidComponent;
import org.briarproject.android.BriarActivity; import org.briarproject.android.BriarActivity;
import org.briarproject.android.util.ElasticHorizontalSpace; import org.briarproject.android.util.ElasticHorizontalSpace;
import org.briarproject.android.util.HorizontalBorder; import org.briarproject.android.util.HorizontalBorder;
@@ -62,7 +63,7 @@ public class ForumActivity extends BriarActivity implements EventListener,
private static final Logger LOG = private static final Logger LOG =
Logger.getLogger(ForumActivity.class.getName()); Logger.getLogger(ForumActivity.class.getName());
@Inject private AndroidNotificationManager notificationManager; @Inject protected AndroidNotificationManager notificationManager;
private Map<MessageId, byte[]> bodyCache = new HashMap<MessageId, byte[]>(); private Map<MessageId, byte[]> bodyCache = new HashMap<MessageId, byte[]>();
private TextView empty = null; private TextView empty = null;
private ForumAdapter adapter = null; private ForumAdapter adapter = null;
@@ -71,8 +72,8 @@ public class ForumActivity extends BriarActivity implements EventListener,
private ImageButton composeButton = null, shareButton = null; private ImageButton composeButton = null, shareButton = null;
// Fields that are accessed from background threads must be volatile // Fields that are accessed from background threads must be volatile
@Inject private volatile ForumManager forumManager; @Inject protected volatile ForumManager forumManager;
@Inject private volatile EventBus eventBus; @Inject protected volatile EventBus eventBus;
private volatile GroupId groupId = null; private volatile GroupId groupId = null;
private volatile Forum forum = null; private volatile Forum forum = null;
@@ -139,6 +140,11 @@ public class ForumActivity extends BriarActivity implements EventListener,
setContentView(layout); setContentView(layout);
} }
@Override
public void injectActivity(AndroidComponent component) {
component.inject(this);
}
@Override @Override
public void onResume() { public void onResume() {
super.onResume(); super.onResume();

View File

@@ -19,6 +19,7 @@ import android.widget.TextView;
import android.widget.Toast; import android.widget.Toast;
import org.briarproject.R; import org.briarproject.R;
import org.briarproject.android.AndroidComponent;
import org.briarproject.android.fragment.BaseEventFragment; import org.briarproject.android.fragment.BaseEventFragment;
import org.briarproject.android.util.HorizontalBorder; import org.briarproject.android.util.HorizontalBorder;
import org.briarproject.android.util.LayoutUtils; import org.briarproject.android.util.LayoutUtils;
@@ -83,8 +84,8 @@ public class ForumListFragment extends BaseEventFragment implements
private ImageButton newForumButton = null; private ImageButton newForumButton = null;
// Fields that are accessed from background threads must be volatile // Fields that are accessed from background threads must be volatile
@Inject private volatile ForumManager forumManager; @Inject protected volatile ForumManager forumManager;
@Inject private volatile ForumSharingManager forumSharingManager; @Inject protected volatile ForumSharingManager forumSharingManager;
@Nullable @Nullable
@Override @Override
@@ -152,6 +153,11 @@ public class ForumListFragment extends BaseEventFragment implements
return TAG; return TAG;
} }
@Override
public void injectActivity(AndroidComponent component) {
component.inject(this);
}
@Override @Override
public void onResume() { public void onResume() {
super.onResume(); super.onResume();

View File

@@ -12,6 +12,7 @@ import android.widget.ScrollView;
import android.widget.TextView; import android.widget.TextView;
import org.briarproject.R; import org.briarproject.R;
import org.briarproject.android.AndroidComponent;
import org.briarproject.android.BriarActivity; import org.briarproject.android.BriarActivity;
import org.briarproject.android.util.AuthorView; import org.briarproject.android.util.AuthorView;
import org.briarproject.android.util.ElasticHorizontalSpace; import org.briarproject.android.util.ElasticHorizontalSpace;
@@ -59,7 +60,7 @@ implements OnClickListener {
private int position = -1; private int position = -1;
// Fields that are accessed from background threads must be volatile // Fields that are accessed from background threads must be volatile
@Inject private volatile ForumManager forumManager; @Inject protected volatile ForumManager forumManager;
private volatile MessageId messageId = null; private volatile MessageId messageId = null;
@Override @Override
@@ -164,6 +165,11 @@ implements OnClickListener {
setContentView(layout); setContentView(layout);
} }
@Override
public void injectActivity(AndroidComponent component) {
component.inject(this);
}
@Override @Override
public void onPause() { public void onPause() {
super.onPause(); super.onPause();

View File

@@ -11,6 +11,7 @@ import android.widget.RadioButton;
import android.widget.RadioGroup; import android.widget.RadioGroup;
import org.briarproject.R; import org.briarproject.R;
import org.briarproject.android.AndroidComponent;
import org.briarproject.android.BriarActivity; import org.briarproject.android.BriarActivity;
import org.briarproject.android.contact.SelectContactsDialog; import org.briarproject.android.contact.SelectContactsDialog;
import org.briarproject.android.invitation.AddContactActivity; import org.briarproject.android.invitation.AddContactActivity;
@@ -51,8 +52,8 @@ SelectContactsDialog.Listener {
private boolean changed = false; private boolean changed = false;
// Fields that are accessed from background threads must be volatile // Fields that are accessed from background threads must be volatile
@Inject private volatile ContactManager contactManager; @Inject protected volatile ContactManager contactManager;
@Inject private volatile ForumSharingManager forumSharingManager; @Inject protected volatile ForumSharingManager forumSharingManager;
private volatile GroupId groupId = null; private volatile GroupId groupId = null;
private volatile Collection<Contact> contacts = null; private volatile Collection<Contact> contacts = null;
private volatile Collection<ContactId> selected = null; private volatile Collection<ContactId> selected = null;
@@ -109,6 +110,11 @@ SelectContactsDialog.Listener {
setContentView(layout); setContentView(layout);
} }
@Override
public void injectActivity(AndroidComponent component) {
component.inject(this);
}
public void onClick(View view) { public void onClick(View view) {
if (view == shareWithAll) { if (view == shareWithAll) {
changed = true; changed = true;

View File

@@ -16,6 +16,7 @@ import android.widget.TextView;
import android.widget.Toast; import android.widget.Toast;
import org.briarproject.R; import org.briarproject.R;
import org.briarproject.android.AndroidComponent;
import org.briarproject.android.BriarActivity; import org.briarproject.android.BriarActivity;
import org.briarproject.android.identity.CreateIdentityActivity; import org.briarproject.android.identity.CreateIdentityActivity;
import org.briarproject.android.identity.LocalAuthorItem; import org.briarproject.android.identity.LocalAuthorItem;
@@ -67,7 +68,7 @@ implements OnItemSelectedListener, OnClickListener {
private static final Logger LOG = private static final Logger LOG =
Logger.getLogger(WriteForumPostActivity.class.getName()); Logger.getLogger(WriteForumPostActivity.class.getName());
@Inject @CryptoExecutor private Executor cryptoExecutor; @Inject @CryptoExecutor protected Executor cryptoExecutor;
private LocalAuthorSpinnerAdapter adapter = null; private LocalAuthorSpinnerAdapter adapter = null;
private Spinner spinner = null; private Spinner spinner = null;
private ImageButton sendButton = null; private ImageButton sendButton = null;
@@ -76,10 +77,10 @@ implements OnItemSelectedListener, OnClickListener {
private GroupId groupId = null; private GroupId groupId = null;
// Fields that are accessed from background threads must be volatile // Fields that are accessed from background threads must be volatile
@Inject private volatile IdentityManager identityManager; @Inject protected volatile IdentityManager identityManager;
@Inject private volatile ForumManager forumManager; @Inject protected volatile ForumManager forumManager;
@Inject private volatile ForumPostFactory forumPostFactory; @Inject protected volatile ForumPostFactory forumPostFactory;
@Inject private volatile CryptoComponent crypto; @Inject protected volatile CryptoComponent crypto;
private volatile MessageId parentId = null; private volatile MessageId parentId = null;
private volatile long minTimestamp = -1; private volatile long minTimestamp = -1;
private volatile LocalAuthor localAuthor = null; private volatile LocalAuthor localAuthor = null;
@@ -157,6 +158,11 @@ implements OnItemSelectedListener, OnClickListener {
setContentView(layout); setContentView(layout);
} }
@Override
public void injectActivity(AndroidComponent component) {
component.inject(this);
}
@Override @Override
public void onResume() { public void onResume() {
super.onResume(); super.onResume();

View File

@@ -1,12 +1,14 @@
package org.briarproject.android.fragment; package org.briarproject.android.fragment;
import android.content.Context; import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import org.briarproject.android.AndroidComponent;
import org.briarproject.android.BriarActivity; import org.briarproject.android.BriarActivity;
import org.briarproject.android.BriarApplication;
import roboguice.fragment.RoboFragment; public abstract class BaseFragment extends Fragment {
public abstract class BaseFragment extends RoboFragment {
public abstract String getUniqueTag(); public abstract String getUniqueTag();
@@ -25,10 +27,25 @@ public abstract class BaseFragment extends RoboFragment {
} }
} }
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
AndroidComponent component =
((BriarApplication) getActivity().getApplication())
.getApplicationComponent();
injectActivity(component);
}
public abstract void injectActivity(AndroidComponent component);
public interface BaseFragmentListener { public interface BaseFragmentListener {
void showLoadingScreen(boolean isBlocking, int stringId); void showLoadingScreen(boolean isBlocking, int stringId);
void hideLoadingScreen(); void hideLoadingScreen();
void runOnUiThread(Runnable runnable); void runOnUiThread(Runnable runnable);
void runOnDbThread(Runnable runnable); void runOnDbThread(Runnable runnable);
} }

View File

@@ -9,6 +9,7 @@ import android.view.ViewGroup;
import android.widget.GridView; import android.widget.GridView;
import org.briarproject.R; import org.briarproject.R;
import org.briarproject.android.AndroidComponent;
import org.briarproject.api.event.Event; import org.briarproject.api.event.Event;
import org.briarproject.api.plugins.PluginManager; import org.briarproject.api.plugins.PluginManager;
@@ -16,8 +17,6 @@ import java.util.logging.Logger;
import javax.inject.Inject; import javax.inject.Inject;
import roboguice.inject.InjectView;
public class DashboardFragment extends BaseEventFragment { public class DashboardFragment extends BaseEventFragment {
public final static String TAG = "DashboardFragment"; public final static String TAG = "DashboardFragment";
@@ -26,10 +25,7 @@ public class DashboardFragment extends BaseEventFragment {
Logger.getLogger(DashboardFragment.class.getName()); Logger.getLogger(DashboardFragment.class.getName());
@Inject @Inject
private PluginManager pluginManager; protected PluginManager pluginManager;
@InjectView(R.id.transportsView)
private GridView transportsView;
public static DashboardFragment newInstance() { public static DashboardFragment newInstance() {
@@ -59,6 +55,11 @@ public class DashboardFragment extends BaseEventFragment {
return TAG; return TAG;
} }
@Override
public void injectActivity(AndroidComponent component) {
}
@Override @Override
public void eventOccurred(Event e) { public void eventOccurred(Event e) {

View File

@@ -14,6 +14,7 @@ import android.widget.TextView.OnEditorActionListener;
import android.widget.Toast; import android.widget.Toast;
import org.briarproject.R; import org.briarproject.R;
import org.briarproject.android.AndroidComponent;
import org.briarproject.android.BriarActivity; import org.briarproject.android.BriarActivity;
import org.briarproject.android.util.LayoutUtils; import org.briarproject.android.util.LayoutUtils;
import org.briarproject.api.crypto.CryptoComponent; import org.briarproject.api.crypto.CryptoComponent;
@@ -50,16 +51,16 @@ implements OnEditorActionListener, OnClickListener {
private static final Logger LOG = private static final Logger LOG =
Logger.getLogger(CreateIdentityActivity.class.getName()); Logger.getLogger(CreateIdentityActivity.class.getName());
@Inject @CryptoExecutor private Executor cryptoExecutor; @Inject @CryptoExecutor protected Executor cryptoExecutor;
private EditText nicknameEntry = null; private EditText nicknameEntry = null;
private Button createIdentityButton = null; private Button createIdentityButton = null;
private ProgressBar progress = null; private ProgressBar progress = null;
private TextView feedback = null; private TextView feedback = null;
// Fields that are accessed from background threads must be volatile // Fields that are accessed from background threads must be volatile
@Inject private volatile CryptoComponent crypto; @Inject protected volatile CryptoComponent crypto;
@Inject private volatile AuthorFactory authorFactory; @Inject protected volatile AuthorFactory authorFactory;
@Inject private volatile IdentityManager identityManager; @Inject protected volatile IdentityManager identityManager;
@Override @Override
public void onCreate(Bundle state) { public void onCreate(Bundle state) {
@@ -112,6 +113,11 @@ implements OnEditorActionListener, OnClickListener {
setContentView(layout); setContentView(layout);
} }
@Override
public void injectActivity(AndroidComponent component) {
component.inject(this);
}
private void enableOrDisableCreateButton() { private void enableOrDisableCreateButton() {
if (progress == null) return; // Not created yet if (progress == null) return; // Not created yet
createIdentityButton.setEnabled(validateNickname()); createIdentityButton.setEnabled(validateNickname());

View File

@@ -5,6 +5,7 @@ import android.os.Bundle;
import android.widget.Toast; import android.widget.Toast;
import org.briarproject.R; import org.briarproject.R;
import org.briarproject.android.AndroidComponent;
import org.briarproject.android.BriarActivity; import org.briarproject.android.BriarActivity;
import org.briarproject.api.android.ReferenceManager; import org.briarproject.api.android.ReferenceManager;
import org.briarproject.api.crypto.CryptoComponent; import org.briarproject.api.crypto.CryptoComponent;
@@ -38,9 +39,9 @@ implements InvitationListener {
private static final Logger LOG = private static final Logger LOG =
Logger.getLogger(AddContactActivity.class.getName()); Logger.getLogger(AddContactActivity.class.getName());
@Inject private CryptoComponent crypto; @Inject protected CryptoComponent crypto;
@Inject private InvitationTaskFactory invitationTaskFactory; @Inject protected InvitationTaskFactory invitationTaskFactory;
@Inject private ReferenceManager referenceManager; @Inject protected ReferenceManager referenceManager;
private AddContactView view = null; private AddContactView view = null;
private InvitationTask task = null; private InvitationTask task = null;
private long taskHandle = -1; private long taskHandle = -1;
@@ -53,7 +54,7 @@ implements InvitationListener {
private String contactName = null; private String contactName = null;
// Fields that are accessed from background threads must be volatile // Fields that are accessed from background threads must be volatile
@Inject private volatile IdentityManager identityManager; @Inject protected volatile IdentityManager identityManager;
@Override @Override
public void onCreate(Bundle state) { public void onCreate(Bundle state) {
@@ -138,6 +139,11 @@ implements InvitationListener {
} }
} }
@Override
public void injectActivity(AndroidComponent component) {
component.inject(this);
}
private void showToastAndFinish() { private void showToastAndFinish() {
String format = getString(R.string.contact_added_toast); String format = getString(R.string.contact_added_toast);
String text = String.format(format, contactName); String text = String.format(format, contactName);

View File

@@ -24,8 +24,6 @@ import java.util.Collection;
import javax.inject.Inject; import javax.inject.Inject;
import roboguice.RoboGuice;
import static android.bluetooth.BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE; import static android.bluetooth.BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE;
import static android.bluetooth.BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION; import static android.bluetooth.BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION;
import static org.briarproject.android.identity.LocalAuthorItem.NEW; import static org.briarproject.android.identity.LocalAuthorItem.NEW;
@@ -35,7 +33,7 @@ import static org.briarproject.android.invitation.AddContactActivity.REQUEST_CRE
class ChooseIdentityView extends AddContactView class ChooseIdentityView extends AddContactView
implements OnItemSelectedListener, OnClickListener { implements OnItemSelectedListener, OnClickListener {
@Inject private CryptoComponent crypto; @Inject protected CryptoComponent crypto;
private LocalAuthorSpinnerAdapter adapter = null; private LocalAuthorSpinnerAdapter adapter = null;
private Spinner spinner = null; private Spinner spinner = null;
@@ -46,7 +44,8 @@ implements OnItemSelectedListener, OnClickListener {
void populate() { void populate() {
removeAllViews(); removeAllViews();
Context ctx = getContext(); Context ctx = getContext();
RoboGuice.injectMembers(ctx, this); // TODO
// RoboGuice.injectMembers(ctx, this);
LayoutInflater inflater = (LayoutInflater) ctx.getSystemService LayoutInflater inflater = (LayoutInflater) ctx.getSystemService
(Context.LAYOUT_INFLATER_SERVICE); (Context.LAYOUT_INFLATER_SERVICE);

View File

@@ -3,6 +3,7 @@ package org.briarproject.android.panic;
import android.os.Build; import android.os.Build;
import android.os.Bundle; import android.os.Bundle;
import org.briarproject.android.AndroidComponent;
import org.briarproject.android.BaseActivity; import org.briarproject.android.BaseActivity;
import java.util.logging.Logger; import java.util.logging.Logger;
@@ -20,4 +21,9 @@ public class ExitActivity extends BaseActivity {
LOG.info("Exiting"); LOG.info("Exiting");
System.exit(0); System.exit(0);
} }
@Override
public void injectActivity(AndroidComponent component) {
}
} }

View File

@@ -5,6 +5,7 @@ import android.support.v7.app.ActionBar;
import android.view.MenuItem; import android.view.MenuItem;
import org.briarproject.R; import org.briarproject.R;
import org.briarproject.android.AndroidComponent;
import org.briarproject.android.BriarActivity; import org.briarproject.android.BriarActivity;
public class PanicPreferencesActivity extends BriarActivity { public class PanicPreferencesActivity extends BriarActivity {
@@ -22,6 +23,11 @@ public class PanicPreferencesActivity extends BriarActivity {
setContentView(R.layout.activity_panic_preferences); setContentView(R.layout.activity_panic_preferences);
} }
@Override
public void injectActivity(AndroidComponent component) {
component.inject(this);
}
public boolean onOptionsItemSelected(MenuItem item) { public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) { if (item.getItemId() == android.R.id.home) {
onBackPressed(); onBackPressed();

View File

@@ -7,12 +7,16 @@ import android.os.Build;
import android.os.Bundle; import android.os.Bundle;
import android.support.v7.preference.PreferenceManager; import android.support.v7.preference.PreferenceManager;
import org.briarproject.android.AndroidComponent;
import org.briarproject.android.BriarActivity; import org.briarproject.android.BriarActivity;
import org.briarproject.android.util.AndroidUtils; import org.briarproject.api.db.DatabaseConfig;
import org.briarproject.util.FileUtils;
import org.iilab.IilabEngineeringRSA2048Pin; import org.iilab.IilabEngineeringRSA2048Pin;
import java.util.logging.Logger; import java.util.logging.Logger;
import javax.inject.Inject;
import info.guardianproject.GuardianProjectRSA4096; import info.guardianproject.GuardianProjectRSA4096;
import info.guardianproject.panic.Panic; import info.guardianproject.panic.Panic;
import info.guardianproject.panic.PanicResponder; import info.guardianproject.panic.PanicResponder;
@@ -26,6 +30,7 @@ public class PanicResponderActivity extends BriarActivity {
private static final Logger LOG = private static final Logger LOG =
Logger.getLogger(PanicResponderActivity.class.getName()); Logger.getLogger(PanicResponderActivity.class.getName());
@Inject protected DatabaseConfig databaseConfig;
@Override @Override
public void onCreate(Bundle savedInstanceState) { public void onCreate(Bundle savedInstanceState) {
@@ -95,13 +100,20 @@ public class PanicResponderActivity extends BriarActivity {
} }
} }
@Override
public void injectActivity(AndroidComponent component) {
component.inject(this);
}
private void deleteAllData() { private void deleteAllData() {
new Thread() { new Thread() {
@Override @Override
public void run() { public void run() {
clearSharedPrefs(); clearSharedPrefs();
// TODO somehow delete/shred the database more thoroughly // TODO somehow delete/shred the database more thoroughly
AndroidUtils.deleteAppData(PanicResponderActivity.this); FileUtils
.deleteFileOrDir(
databaseConfig.getDatabaseDirectory());
PanicResponder.deleteAllAppData(PanicResponderActivity.this); PanicResponder.deleteAllAppData(PanicResponderActivity.this);
// nothing left to do after everything is deleted, // nothing left to do after everything is deleted,

View File

@@ -16,11 +16,10 @@ import org.briarproject.api.identity.AuthorId;
import javax.inject.Inject; import javax.inject.Inject;
import im.delight.android.identicons.IdenticonDrawable; import im.delight.android.identicons.IdenticonDrawable;
import roboguice.RoboGuice;
public class AuthorView extends FrameLayout { public class AuthorView extends FrameLayout {
@Inject private CryptoComponent crypto; @Inject protected CryptoComponent crypto;
private ImageView avatarView; private ImageView avatarView;
private TextView nameView; private TextView nameView;
private ImageView statusView; private ImageView statusView;
@@ -45,7 +44,6 @@ public class AuthorView extends FrameLayout {
} }
private void initViews() { private void initViews() {
RoboGuice.injectMembers(getContext(), this);
if (isInEditMode()) if (isInEditMode())
return; return;

View File

@@ -3,7 +3,6 @@ package org.briarproject.plugins;
import android.app.Application; import android.app.Application;
import android.content.Context; import android.content.Context;
import com.google.inject.Provides;
import org.briarproject.api.android.AndroidExecutor; import org.briarproject.api.android.AndroidExecutor;
import org.briarproject.api.event.EventBus; import org.briarproject.api.event.EventBus;
@@ -24,6 +23,10 @@ import java.util.Collection;
import java.util.Collections; import java.util.Collections;
import java.util.concurrent.Executor; import java.util.concurrent.Executor;
import dagger.Module;
import dagger.Provides;
@Module
public class AndroidPluginsModule extends PluginsModule { public class AndroidPluginsModule extends PluginsModule {
@Provides @Provides

View File

@@ -6,13 +6,13 @@ import android.content.Context;
import android.telephony.TelephonyManager; import android.telephony.TelephonyManager;
import android.text.TextUtils; import android.text.TextUtils;
import com.google.inject.Inject;
import org.briarproject.api.system.LocationUtils; import org.briarproject.api.system.LocationUtils;
import java.util.Locale; import java.util.Locale;
import java.util.logging.Logger; import java.util.logging.Logger;
import javax.inject.Inject;
import static android.content.Context.TELEPHONY_SERVICE; import static android.content.Context.TELEPHONY_SERVICE;
class AndroidLocationUtils implements LocationUtils { class AndroidLocationUtils implements LocationUtils {

View File

@@ -1,18 +1,37 @@
package org.briarproject.system; package org.briarproject.system;
import com.google.inject.AbstractModule;
import android.app.Application;
import org.briarproject.api.system.Clock; import org.briarproject.api.system.Clock;
import org.briarproject.api.system.LocationUtils; import org.briarproject.api.system.LocationUtils;
import org.briarproject.api.system.SeedProvider; import org.briarproject.api.system.SeedProvider;
import org.briarproject.api.system.Timer; import org.briarproject.api.system.Timer;
public class AndroidSystemModule extends AbstractModule { import dagger.Module;
import dagger.Provides;
protected void configure() { @Module
bind(Clock.class).to(SystemClock.class); public class AndroidSystemModule {
bind(Timer.class).to(SystemTimer.class);
bind(SeedProvider.class).to(AndroidSeedProvider.class); @Provides
bind(LocationUtils.class).to(AndroidLocationUtils.class); Clock provideClock() {
return new SystemClock();
} }
@Provides
Timer provideTimer() {
return new SystemTimer();
}
@Provides
SeedProvider provideSeedProvider(final Application app) {
return new AndroidSeedProvider(app);
}
@Provides
LocationUtils provideLocationUtils(final Application app) {
return new AndroidLocationUtils(app);
}
} }

View File

@@ -9,17 +9,17 @@ repositories {
} }
dependencies { dependencies {
compile "javax.inject:javax.inject:1" compile "com.google.dagger:dagger:2.0.2"
compile "com.google.inject:guice:3.0:no_aop" compile 'com.google.dagger:dagger-compiler:2.0.2'
} }
dependencyVerification { dependencyVerification {
verify = [ verify = [
'javax.inject:javax.inject:91c77044a50c481636c32d916fd89c9118a72195390452c81065080f957de7ff', // 'javax.inject:javax.inject:91c77044a50c481636c32d916fd89c9118a72195390452c81065080f957de7ff',
'com.google.inject:guice:7c0624d0986ae2bd7a8f1cf4789bcaae5b82a042a7e3d27ba3041ed7b7f2cd3a', // 'com.google.inject:guice:7c0624d0986ae2bd7a8f1cf4789bcaae5b82a042a7e3d27ba3041ed7b7f2cd3a',
'aopalliance:aopalliance:0addec670fedcd3f113c5c8091d783280d23f75e3acb841b61a9cdb079376a08', // 'aopalliance:aopalliance:0addec670fedcd3f113c5c8091d783280d23f75e3acb841b61a9cdb079376a08',
'org.sonatype.sisu.inject:cglib:42e1dfb26becbf1a633f25b47e39fcc422b85e77e4c0468d9a44f885f5fa0be2', // 'org.sonatype.sisu.inject:cglib:42e1dfb26becbf1a633f25b47e39fcc422b85e77e4c0468d9a44f885f5fa0be2',
'asm:asm:333ff5369043975b7e031b8b27206937441854738e038c1f47f98d072a20437a', // 'asm:asm:333ff5369043975b7e031b8b27206937441854738e038c1f47f98d072a20437a',
] ]
} }

View File

@@ -5,13 +5,21 @@ import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.PARAMETER; import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.RetentionPolicy.RUNTIME; import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention; import java.lang.annotation.Retention;
import java.lang.annotation.Target; import java.lang.annotation.Target;
import com.google.inject.BindingAnnotation; import javax.inject.Qualifier;
//import com.google.inject.BindingAnnotation;
/** Annotation for injecting the executor for long-running crypto tasks. */ /** Annotation for injecting the executor for long-running crypto tasks. */
@BindingAnnotation //@BindingAnnotation
@Target({ FIELD, METHOD, PARAMETER }) //@Target({ FIELD, METHOD, PARAMETER })
//@Retention(RUNTIME)
//public @interface CryptoExecutor {}
@Qualifier
@Target({FIELD, METHOD, PARAMETER})
@Retention(RUNTIME) @Retention(RUNTIME)
public @interface CryptoExecutor {} public @interface CryptoExecutor {}

View File

@@ -8,7 +8,7 @@ import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Retention; import java.lang.annotation.Retention;
import java.lang.annotation.Target; import java.lang.annotation.Target;
import com.google.inject.BindingAnnotation; import javax.inject.Qualifier;
/** /**
* Annotation for injecting the executor for database tasks. * Annotation for injecting the executor for database tasks.
@@ -17,7 +17,7 @@ import com.google.inject.BindingAnnotation;
* they're submitted, tasks are not executed concurrently, and submitting a * they're submitted, tasks are not executed concurrently, and submitting a
* task will never block. * task will never block.
*/ */
@BindingAnnotation @Qualifier
@Target({ FIELD, METHOD, PARAMETER }) @Target({ FIELD, METHOD, PARAMETER })
@Retention(RUNTIME) @Retention(RUNTIME)
public @interface DatabaseExecutor {} public @interface DatabaseExecutor {}

View File

@@ -8,10 +8,10 @@ import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Retention; import java.lang.annotation.Retention;
import java.lang.annotation.Target; import java.lang.annotation.Target;
import com.google.inject.BindingAnnotation; import javax.inject.Qualifier;
/** Annotation for injecting the executor used by long-lived IO tasks. */ /** Annotation for injecting the executor used by long-lived IO tasks. */
@BindingAnnotation @Qualifier
@Target({ FIELD, METHOD, PARAMETER }) @Target({ FIELD, METHOD, PARAMETER })
@Retention(RUNTIME) @Retention(RUNTIME)
public @interface IoExecutor {} public @interface IoExecutor {}

View File

@@ -1,7 +1,5 @@
package org.briarproject.contact; package org.briarproject.contact;
import com.google.inject.Inject;
import org.briarproject.api.contact.Contact; import org.briarproject.api.contact.Contact;
import org.briarproject.api.contact.ContactId; import org.briarproject.api.contact.ContactId;
import org.briarproject.api.contact.ContactManager; import org.briarproject.api.contact.ContactManager;
@@ -21,7 +19,22 @@ import java.util.Collections;
import java.util.List; import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.CopyOnWriteArrayList;
<<<<<<< 08099714bab27d1ed48a8bee431a35a38098ecec
class ContactManagerImpl implements ContactManager, RemoveIdentityHook { class ContactManagerImpl implements ContactManager, RemoveIdentityHook {
=======
import javax.inject.Inject;
import static java.util.logging.Level.WARNING;
import static org.briarproject.api.db.StorageStatus.ACTIVE;
import static org.briarproject.api.db.StorageStatus.ADDING;
import static org.briarproject.api.db.StorageStatus.REMOVING;
class ContactManagerImpl implements ContactManager, Service,
RemoveIdentityHook {
private static final Logger LOG =
Logger.getLogger(ContactManagerImpl.class.getName());
>>>>>>> Switched Roboguice/Guice out for Dagger 2
private final DatabaseComponent db; private final DatabaseComponent db;
private final KeyManager keyManager; private final KeyManager keyManager;

View File

@@ -1,21 +1,23 @@
package org.briarproject.contact; package org.briarproject.contact;
import com.google.inject.AbstractModule;
import com.google.inject.Provides;
import org.briarproject.api.contact.ContactManager; import org.briarproject.api.contact.ContactManager;
import org.briarproject.api.identity.IdentityManager; import org.briarproject.api.identity.IdentityManager;
import org.briarproject.api.lifecycle.LifecycleManager;
import javax.inject.Singleton; import javax.inject.Singleton;
public class ContactModule extends AbstractModule { import dagger.Module;
import dagger.Provides;
@Override @Module
protected void configure() {} public class ContactModule {
@Provides @Singleton @Provides
ContactManager getContactManager(IdentityManager identityManager, @Singleton
ContactManager getContactManager(LifecycleManager lifecycleManager,
IdentityManager identityManager,
ContactManagerImpl contactManager) { ContactManagerImpl contactManager) {
lifecycleManager.register(contactManager);
identityManager.registerRemoveIdentityHook(contactManager); identityManager.registerRemoveIdentityHook(contactManager);
return contactManager; return contactManager;
} }

View File

@@ -1,14 +1,12 @@
package org.briarproject.crypto; package org.briarproject.crypto;
import com.google.inject.AbstractModule;
import com.google.inject.Provides;
import org.briarproject.api.crypto.CryptoComponent; import org.briarproject.api.crypto.CryptoComponent;
import org.briarproject.api.crypto.CryptoExecutor; import org.briarproject.api.crypto.CryptoExecutor;
import org.briarproject.api.crypto.PasswordStrengthEstimator; import org.briarproject.api.crypto.PasswordStrengthEstimator;
import org.briarproject.api.crypto.StreamDecrypterFactory; import org.briarproject.api.crypto.StreamDecrypterFactory;
import org.briarproject.api.crypto.StreamEncrypterFactory; import org.briarproject.api.crypto.StreamEncrypterFactory;
import org.briarproject.api.lifecycle.LifecycleManager; import org.briarproject.api.lifecycle.LifecycleManager;
import org.briarproject.api.system.SeedProvider;
import java.security.SecureRandom; import java.security.SecureRandom;
import java.util.concurrent.BlockingQueue; import java.util.concurrent.BlockingQueue;
@@ -18,13 +16,20 @@ import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.RejectedExecutionHandler; import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.ThreadPoolExecutor;
import javax.inject.Provider;
import javax.inject.Singleton; import javax.inject.Singleton;
import dagger.Module;
import dagger.Provides;
import static java.util.concurrent.TimeUnit.SECONDS; import static java.util.concurrent.TimeUnit.SECONDS;
public class CryptoModule extends AbstractModule { @Module
public class CryptoModule {
/** The maximum number of executor threads. */ /**
* The maximum number of executor threads.
*/
private static final int MAX_EXECUTOR_THREADS = private static final int MAX_EXECUTOR_THREADS =
Runtime.getRuntime().availableProcessors(); Runtime.getRuntime().availableProcessors();
@@ -41,19 +46,37 @@ public class CryptoModule extends AbstractModule {
60, SECONDS, queue, policy); 60, SECONDS, queue, policy);
} }
@Override @Provides
protected void configure() { AuthenticatedCipher provideAuthenticatedCipher() {
bind(AuthenticatedCipher.class).to( return new XSalsa20Poly1305AuthenticatedCipher();
XSalsa20Poly1305AuthenticatedCipher.class);
bind(CryptoComponent.class).to(
CryptoComponentImpl.class).in(Singleton.class);
bind(PasswordStrengthEstimator.class).to(
PasswordStrengthEstimatorImpl.class);
bind(StreamDecrypterFactory.class).to(StreamDecrypterFactoryImpl.class);
bind(StreamEncrypterFactory.class).to(StreamEncrypterFactoryImpl.class);
} }
@Provides @Singleton @CryptoExecutor @Provides
@Singleton
CryptoComponent provideCryptoComponent(SeedProvider seedProvider) {
return new CryptoComponentImpl(seedProvider);
}
@Provides
PasswordStrengthEstimator providePasswordStrengthEstimator() {
return new PasswordStrengthEstimatorImpl();
}
@Provides
StreamDecrypterFactory provideStreamDecrypterFactory(
Provider<AuthenticatedCipher> cipherProvider) {
return new StreamDecrypterFactoryImpl(cipherProvider);
}
@Provides
StreamEncrypterFactory provideStreamEncrypterFactory(CryptoComponent crypto,
Provider<AuthenticatedCipher> cipherProvider) {
return new StreamEncrypterFactoryImpl(crypto, cipherProvider);
}
@Provides
@Singleton
@CryptoExecutor
Executor getCryptoExecutor(LifecycleManager lifecycleManager) { Executor getCryptoExecutor(LifecycleManager lifecycleManager) {
lifecycleManager.registerForShutdown(cryptoExecutor); lifecycleManager.registerForShutdown(cryptoExecutor);
return cryptoExecutor; return cryptoExecutor;
@@ -63,4 +86,5 @@ public class CryptoModule extends AbstractModule {
SecureRandom getSecureRandom(CryptoComponent crypto) { SecureRandom getSecureRandom(CryptoComponent crypto) {
return crypto.getSecureRandom(); return crypto.getSecureRandom();
} }
} }

View File

@@ -1,19 +1,35 @@
package org.briarproject.data; package org.briarproject.data;
import com.google.inject.AbstractModule;
import org.briarproject.api.data.BdfReaderFactory; import org.briarproject.api.data.BdfReaderFactory;
import org.briarproject.api.data.BdfWriterFactory; import org.briarproject.api.data.BdfWriterFactory;
import org.briarproject.api.data.MetadataEncoder; import org.briarproject.api.data.MetadataEncoder;
import org.briarproject.api.data.MetadataParser; import org.briarproject.api.data.MetadataParser;
public class DataModule extends AbstractModule { import dagger.Module;
import dagger.Provides;
@Override @Module
protected void configure() { public class DataModule {
bind(BdfReaderFactory.class).to(BdfReaderFactoryImpl.class);
bind(BdfWriterFactory.class).to(BdfWriterFactoryImpl.class); @Provides
bind(MetadataParser.class).to(MetadataParserImpl.class); BdfReaderFactory provideBdfReaderFactory() {
bind(MetadataEncoder.class).to(MetadataEncoderImpl.class); return new BdfReaderFactoryImpl();
} }
@Provides
BdfWriterFactory provideBdfWriterFactory() {
return new BdfWriterFactoryImpl();
}
@Provides
MetadataParser provideMetaDataParser() {
return new MetadataParserImpl();
}
@Provides
MetadataEncoder provideMetaDataEncoider() {
return new MetadataEncoderImpl();
}
} }

View File

@@ -1,8 +1,5 @@
package org.briarproject.db; package org.briarproject.db;
import com.google.inject.AbstractModule;
import com.google.inject.Provides;
import org.briarproject.api.db.DatabaseComponent; import org.briarproject.api.db.DatabaseComponent;
import org.briarproject.api.db.DatabaseConfig; import org.briarproject.api.db.DatabaseConfig;
import org.briarproject.api.db.DatabaseExecutor; import org.briarproject.api.db.DatabaseExecutor;
@@ -20,11 +17,16 @@ import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.RejectedExecutionHandler; import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.ThreadPoolExecutor;
import javax.inject.Named;
import javax.inject.Singleton; import javax.inject.Singleton;
import dagger.Module;
import dagger.Provides;
import static java.util.concurrent.TimeUnit.SECONDS; import static java.util.concurrent.TimeUnit.SECONDS;
public class DatabaseModule extends AbstractModule { @Module
public class DatabaseModule {
private final ExecutorService databaseExecutor; private final ExecutorService databaseExecutor;
@@ -39,30 +41,28 @@ public class DatabaseModule extends AbstractModule {
policy); policy);
} }
@Override @Provides
protected void configure() {} @Singleton
Database<Connection> provideDatabase(DatabaseConfig config,
@Provides @Singleton
Database<Connection> getDatabase(DatabaseConfig config,
SecureRandom random, Clock clock) { SecureRandom random, Clock clock) {
return new H2Database(config, random, clock); return new H2Database(config, random, clock);
} }
@Provides @Singleton @Provides @Singleton
DatabaseComponent getDatabaseComponent(Database<Connection> db, DatabaseComponent provideDatabaseComponent(Database<Connection> db,
EventBus eventBus, ShutdownManager shutdown) { EventBus eventBus, ShutdownManager shutdown) {
return new DatabaseComponentImpl<Connection>(db, Connection.class, return new DatabaseComponentImpl<Connection>(db, Connection.class,
eventBus, shutdown); eventBus, shutdown);
} }
@Provides @Singleton @DatabaseExecutor @Provides @Singleton @DatabaseExecutor
ExecutorService getDatabaseExecutor(LifecycleManager lifecycleManager) { ExecutorService provideDatabaseExecutorService(LifecycleManager lifecycleManager) {
lifecycleManager.registerForShutdown(databaseExecutor); lifecycleManager.registerForShutdown(databaseExecutor);
return databaseExecutor; return databaseExecutor;
} }
@Provides @Singleton @DatabaseExecutor @Provides @Singleton @DatabaseExecutor
Executor getDatabaseExecutor(@DatabaseExecutor ExecutorService dbExecutor) { Executor provideDatabaseExecutor(@DatabaseExecutor ExecutorService dbExecutor) {
return dbExecutor; return dbExecutor;
} }
} }

View File

@@ -2,13 +2,17 @@ package org.briarproject.event;
import org.briarproject.api.event.EventBus; import org.briarproject.api.event.EventBus;
import com.google.inject.AbstractModule; import javax.inject.Singleton;
import com.google.inject.Singleton;
public class EventModule extends AbstractModule { import dagger.Module;
import dagger.Provides;
@Override @Module
protected void configure() { public class EventModule {
bind(EventBus.class).to(EventBusImpl.class).in(Singleton.class);
@Provides
@Singleton
EventBus provideEventBus() {
return new EventBusImpl();
} }
} }

View File

@@ -1,14 +1,15 @@
package org.briarproject.forum; package org.briarproject.forum;
import com.google.inject.Inject;
import org.briarproject.api.FormatException; import org.briarproject.api.FormatException;
import org.briarproject.api.clients.ClientHelper;
import org.briarproject.api.contact.Contact; import org.briarproject.api.contact.Contact;
import org.briarproject.api.data.BdfDictionary; import org.briarproject.api.data.BdfDictionary;
import org.briarproject.api.data.BdfList; import org.briarproject.api.data.BdfReader;
import org.briarproject.api.data.BdfReaderFactory;
import org.briarproject.api.data.MetadataEncoder;
import org.briarproject.api.data.MetadataParser;
import org.briarproject.api.db.DatabaseComponent; import org.briarproject.api.db.DatabaseComponent;
import org.briarproject.api.db.DbException; import org.briarproject.api.db.DbException;
import org.briarproject.api.db.Metadata;
import org.briarproject.api.db.Transaction; import org.briarproject.api.db.Transaction;
import org.briarproject.api.forum.Forum; import org.briarproject.api.forum.Forum;
import org.briarproject.api.forum.ForumManager; import org.briarproject.api.forum.ForumManager;
@@ -23,6 +24,8 @@ import org.briarproject.api.sync.GroupId;
import org.briarproject.api.sync.MessageId; import org.briarproject.api.sync.MessageId;
import org.briarproject.util.StringUtils; import org.briarproject.util.StringUtils;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collection; import java.util.Collection;
import java.util.Collections; import java.util.Collections;
@@ -31,10 +34,18 @@ import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Map.Entry; import java.util.Map.Entry;
import java.util.Set; import java.util.Set;
import java.util.logging.Logger;
import javax.inject.Inject;
import static java.util.logging.Level.WARNING;
import static org.briarproject.api.forum.ForumConstants.FORUM_SALT_LENGTH;
import static org.briarproject.api.forum.ForumConstants.MAX_FORUM_NAME_LENGTH;
import static org.briarproject.api.forum.ForumConstants.MAX_FORUM_POST_BODY_LENGTH;
import static org.briarproject.api.identity.Author.Status.ANONYMOUS; import static org.briarproject.api.identity.Author.Status.ANONYMOUS;
import static org.briarproject.api.identity.Author.Status.UNKNOWN; import static org.briarproject.api.identity.Author.Status.UNKNOWN;
import static org.briarproject.api.identity.Author.Status.VERIFIED; import static org.briarproject.api.identity.Author.Status.VERIFIED;
import static org.briarproject.api.sync.SyncConstants.MESSAGE_HEADER_LENGTH;
class ForumManagerImpl implements ForumManager { class ForumManagerImpl implements ForumManager {
@@ -42,13 +53,21 @@ class ForumManagerImpl implements ForumManager {
"859a7be50dca035b64bd6902fb797097" "859a7be50dca035b64bd6902fb797097"
+ "795af837abbf8c16d750b3c2ccc186ea")); + "795af837abbf8c16d750b3c2ccc186ea"));
private static final Logger LOG =
Logger.getLogger(ForumManagerImpl.class.getName());
private final DatabaseComponent db; private final DatabaseComponent db;
private final ClientHelper clientHelper; private final BdfReaderFactory bdfReaderFactory;
private final MetadataEncoder metadataEncoder;
private final MetadataParser metadataParser;
@Inject @Inject
ForumManagerImpl(DatabaseComponent db, ClientHelper clientHelper) { ForumManagerImpl(DatabaseComponent db, BdfReaderFactory bdfReaderFactory,
MetadataEncoder metadataEncoder, MetadataParser metadataParser) {
this.db = db; this.db = db;
this.clientHelper = clientHelper; this.bdfReaderFactory = bdfReaderFactory;
this.metadataEncoder = metadataEncoder;
this.metadataParser = metadataParser;
} }
@Override @Override
@@ -59,21 +78,29 @@ class ForumManagerImpl implements ForumManager {
@Override @Override
public void addLocalPost(ForumPost p) throws DbException { public void addLocalPost(ForumPost p) throws DbException {
try { try {
BdfDictionary meta = new BdfDictionary(); BdfDictionary d = new BdfDictionary();
meta.put("timestamp", p.getMessage().getTimestamp()); d.put("timestamp", p.getMessage().getTimestamp());
if (p.getParent() != null) meta.put("parent", p.getParent()); if (p.getParent() != null)
d.put("parent", p.getParent().getBytes());
if (p.getAuthor() != null) { if (p.getAuthor() != null) {
Author a = p.getAuthor(); Author a = p.getAuthor();
BdfDictionary authorMeta = new BdfDictionary(); BdfDictionary d1 = new BdfDictionary();
authorMeta.put("id", a.getId()); d1.put("id", a.getId().getBytes());
authorMeta.put("name", a.getName()); d1.put("name", a.getName());
authorMeta.put("publicKey", a.getPublicKey()); d1.put("publicKey", a.getPublicKey());
meta.put("author", authorMeta); d.put("author", d1);
}
d.put("contentType", p.getContentType());
d.put("local", true);
d.put("read", true);
Metadata meta = metadataEncoder.encode(d);
Transaction txn = db.startTransaction();
try {
db.addLocalMessage(txn, p.getMessage(), CLIENT_ID, meta, true);
txn.setComplete();
} finally {
db.endTransaction(txn);
} }
meta.put("contentType", p.getContentType());
meta.put("local", true);
meta.put("read", true);
clientHelper.addLocalMessage(p.getMessage(), CLIENT_ID, meta, true);
} catch (FormatException e) { } catch (FormatException e) {
throw new RuntimeException(e); throw new RuntimeException(e);
} }
@@ -118,11 +145,34 @@ class ForumManagerImpl implements ForumManager {
@Override @Override
public byte[] getPostBody(MessageId m) throws DbException { public byte[] getPostBody(MessageId m) throws DbException {
try { try {
// Parent ID, author, content type, forum post body, signature byte[] raw;
BdfList message = clientHelper.getMessageAsList(m); Transaction txn = db.startTransaction();
return message.getRaw(3); try {
raw = db.getRawMessage(txn, m);
txn.setComplete();
} finally {
db.endTransaction(txn);
}
ByteArrayInputStream in = new ByteArrayInputStream(raw,
MESSAGE_HEADER_LENGTH, raw.length - MESSAGE_HEADER_LENGTH);
BdfReader r = bdfReaderFactory.createReader(in);
r.readListStart();
if (r.hasRaw()) r.skipRaw(); // Parent ID
else r.skipNull(); // No parent
if (r.hasList()) r.skipList(); // Author
else r.skipNull(); // No author
r.skipString(); // Content type
byte[] postBody = r.readRaw(MAX_FORUM_POST_BODY_LENGTH);
if (r.hasRaw()) r.skipRaw(); // Signature
else r.skipNull();
r.readListEnd();
if (!r.eof()) throw new FormatException();
return postBody;
} catch (FormatException e) { } catch (FormatException e) {
throw new DbException(e); throw new DbException(e);
} catch (IOException e) {
// Shouldn't happen with ByteArrayInputStream
throw new RuntimeException(e);
} }
} }
@@ -131,7 +181,7 @@ class ForumManagerImpl implements ForumManager {
throws DbException { throws DbException {
Set<AuthorId> localAuthorIds = new HashSet<AuthorId>(); Set<AuthorId> localAuthorIds = new HashSet<AuthorId>();
Set<AuthorId> contactAuthorIds = new HashSet<AuthorId>(); Set<AuthorId> contactAuthorIds = new HashSet<AuthorId>();
Map<MessageId, BdfDictionary> metadata; Map<MessageId, Metadata> metadata;
Transaction txn = db.startTransaction(); Transaction txn = db.startTransaction();
try { try {
// Load the IDs of the user's identities // Load the IDs of the user's identities
@@ -141,22 +191,20 @@ class ForumManagerImpl implements ForumManager {
for (Contact c : db.getContacts(txn)) for (Contact c : db.getContacts(txn))
contactAuthorIds.add(c.getAuthor().getId()); contactAuthorIds.add(c.getAuthor().getId());
// Load the metadata // Load the metadata
metadata = clientHelper.getMessageMetadataAsDictionary(txn, g); metadata = db.getMessageMetadata(txn, g);
txn.setComplete(); txn.setComplete();
} catch (FormatException e) {
throw new DbException(e);
} finally { } finally {
db.endTransaction(txn); db.endTransaction(txn);
} }
// Parse the metadata // Parse the metadata
Collection<ForumPostHeader> headers = new ArrayList<ForumPostHeader>(); Collection<ForumPostHeader> headers = new ArrayList<ForumPostHeader>();
for (Entry<MessageId, BdfDictionary> entry : metadata.entrySet()) { for (Entry<MessageId, Metadata> e : metadata.entrySet()) {
try { try {
BdfDictionary meta = entry.getValue(); BdfDictionary d = metadataParser.parse(e.getValue());
long timestamp = meta.getLong("timestamp"); long timestamp = d.getLong("timestamp");
Author author = null; Author author = null;
Author.Status authorStatus = ANONYMOUS; Author.Status authorStatus = ANONYMOUS;
BdfDictionary d1 = meta.getDictionary("author", null); BdfDictionary d1 = d.getDictionary("author", null);
if (d1 != null) { if (d1 != null) {
AuthorId authorId = new AuthorId(d1.getRaw("id")); AuthorId authorId = new AuthorId(d1.getRaw("id"));
String name = d1.getString("name"); String name = d1.getString("name");
@@ -168,12 +216,13 @@ class ForumManagerImpl implements ForumManager {
authorStatus = VERIFIED; authorStatus = VERIFIED;
else authorStatus = UNKNOWN; else authorStatus = UNKNOWN;
} }
String contentType = meta.getString("contentType"); String contentType = d.getString("contentType");
boolean read = meta.getBoolean("read"); boolean read = d.getBoolean("read");
headers.add(new ForumPostHeader(entry.getKey(), timestamp, headers.add(new ForumPostHeader(e.getKey(), timestamp, author,
author, authorStatus, contentType, read)); authorStatus, contentType, read));
} catch (FormatException e) { } catch (FormatException ex) {
throw new DbException(e); if (LOG.isLoggable(WARNING))
LOG.log(WARNING, ex.toString(), ex);
} }
} }
return headers; return headers;
@@ -182,18 +231,36 @@ class ForumManagerImpl implements ForumManager {
@Override @Override
public void setReadFlag(MessageId m, boolean read) throws DbException { public void setReadFlag(MessageId m, boolean read) throws DbException {
try { try {
BdfDictionary meta = new BdfDictionary(); BdfDictionary d = new BdfDictionary();
meta.put("read", read); d.put("read", read);
clientHelper.mergeMessageMetadata(m, meta); Metadata meta = metadataEncoder.encode(d);
Transaction txn = db.startTransaction();
try {
db.mergeMessageMetadata(txn, m, meta);
txn.setComplete();
} finally {
db.endTransaction(txn);
}
} catch (FormatException e) { } catch (FormatException e) {
throw new RuntimeException(e); throw new RuntimeException(e);
} }
} }
private Forum parseForum(Group g) throws FormatException { private Forum parseForum(Group g) throws FormatException {
byte[] descriptor = g.getDescriptor(); ByteArrayInputStream in = new ByteArrayInputStream(g.getDescriptor());
// Name, salt BdfReader r = bdfReaderFactory.createReader(in);
BdfList forum = clientHelper.toList(descriptor, 0, descriptor.length); try {
return new Forum(g, forum.getString(0), forum.getRaw(1)); r.readListStart();
String name = r.readString(MAX_FORUM_NAME_LENGTH);
byte[] salt = r.readRaw(FORUM_SALT_LENGTH);
r.readListEnd();
if (!r.eof()) throw new FormatException();
return new Forum(g, name, salt);
} catch (FormatException e) {
throw e;
} catch (IOException e) {
// Shouldn't happen with ByteArrayInputStream
throw new RuntimeException(e);
}
} }
} }

View File

@@ -1,54 +1,80 @@
package org.briarproject.forum; package org.briarproject.forum;
import com.google.inject.AbstractModule;
import com.google.inject.Provides;
import org.briarproject.api.clients.ClientHelper;
import org.briarproject.api.contact.ContactManager; import org.briarproject.api.contact.ContactManager;
import org.briarproject.api.crypto.CryptoComponent; import org.briarproject.api.crypto.CryptoComponent;
import org.briarproject.api.data.BdfReaderFactory;
import org.briarproject.api.data.BdfWriterFactory;
import org.briarproject.api.data.MetadataEncoder; import org.briarproject.api.data.MetadataEncoder;
import org.briarproject.api.data.MetadataParser;
import org.briarproject.api.data.ObjectReader;
import org.briarproject.api.db.DatabaseComponent;
import org.briarproject.api.forum.ForumManager; import org.briarproject.api.forum.ForumManager;
import org.briarproject.api.forum.ForumPostFactory; import org.briarproject.api.forum.ForumPostFactory;
import org.briarproject.api.forum.ForumSharingManager; import org.briarproject.api.forum.ForumSharingManager;
import org.briarproject.api.identity.AuthorFactory; import org.briarproject.api.identity.Author;
import org.briarproject.api.sync.MessageFactory;
import org.briarproject.api.sync.ValidationManager; import org.briarproject.api.sync.ValidationManager;
import org.briarproject.api.system.Clock; import org.briarproject.api.system.Clock;
import javax.inject.Singleton; import javax.inject.Singleton;
public class ForumModule extends AbstractModule { import dagger.Module;
import dagger.Provides;
@Override @Module
protected void configure() { public class ForumModule {
bind(ForumManager.class).to(ForumManagerImpl.class).in(Singleton.class);
bind(ForumPostFactory.class).to(ForumPostFactoryImpl.class); @Provides
@Singleton
ForumManager provideForumManager(DatabaseComponent db,
ContactManager contactManager,
BdfReaderFactory bdfReaderFactory, MetadataEncoder metadataEncoder,
MetadataParser metadataParser) {
return new ForumManagerImpl(db, contactManager, bdfReaderFactory,
metadataEncoder, metadataParser);
} }
@Provides @Singleton @Provides
ForumPostValidator getForumPostValidator( ForumPostFactory provideForumPostFactory(CryptoComponent crypto,
MessageFactory messageFactory,
BdfWriterFactory bdfWriterFactory) {
return new ForumPostFactoryImpl(crypto, messageFactory,
bdfWriterFactory);
}
@Provides
@Singleton
ForumPostValidator provideForumPostValidator(
ValidationManager validationManager, CryptoComponent crypto, ValidationManager validationManager, CryptoComponent crypto,
AuthorFactory authorFactory, ClientHelper clientHelper, BdfReaderFactory bdfReaderFactory,
MetadataEncoder metadataEncoder, Clock clock) { BdfWriterFactory bdfWriterFactory,
ObjectReader<Author> authorReader, MetadataEncoder metadataEncoder,
Clock clock) {
ForumPostValidator validator = new ForumPostValidator(crypto, ForumPostValidator validator = new ForumPostValidator(crypto,
authorFactory, clientHelper, metadataEncoder, clock); bdfReaderFactory, bdfWriterFactory, authorReader,
metadataEncoder, clock);
validationManager.registerMessageValidator( validationManager.registerMessageValidator(
ForumManagerImpl.CLIENT_ID, validator); ForumManagerImpl.CLIENT_ID, validator);
return validator; return validator;
} }
@Provides @Singleton @Provides
ForumListValidator getForumListValidator( @Singleton
ValidationManager validationManager, ClientHelper clientHelper, ForumListValidator provideForumListValidator(
MetadataEncoder metadataEncoder, Clock clock) { ValidationManager validationManager,
ForumListValidator validator = new ForumListValidator(clientHelper, BdfReaderFactory bdfReaderFactory,
metadataEncoder, clock); MetadataEncoder metadataEncoder) {
ForumListValidator validator = new ForumListValidator(bdfReaderFactory,
metadataEncoder);
validationManager.registerMessageValidator( validationManager.registerMessageValidator(
ForumSharingManagerImpl.CLIENT_ID, validator); ForumSharingManagerImpl.CLIENT_ID, validator);
return validator; return validator;
} }
@Provides @Singleton @Provides
ForumSharingManager getForumSharingManager(ContactManager contactManager, @Singleton
ForumSharingManager provideForumSharingManager(
ContactManager contactManager,
ValidationManager validationManager, ValidationManager validationManager,
ForumSharingManagerImpl forumSharingManager) { ForumSharingManagerImpl forumSharingManager) {
contactManager.registerAddContactHook(forumSharingManager); contactManager.registerAddContactHook(forumSharingManager);

View File

@@ -1,7 +1,5 @@
package org.briarproject.forum; package org.briarproject.forum;
import com.google.inject.Inject;
import org.briarproject.api.FormatException; import org.briarproject.api.FormatException;
import org.briarproject.api.clients.ClientHelper; import org.briarproject.api.clients.ClientHelper;
import org.briarproject.api.clients.PrivateGroupFactory; import org.briarproject.api.clients.PrivateGroupFactory;
@@ -39,6 +37,12 @@ import java.util.Map;
import java.util.Map.Entry; import java.util.Map.Entry;
import java.util.Set; import java.util.Set;
<<<<<<< 08099714bab27d1ed48a8bee431a35a38098ecec
=======
import javax.inject.Inject;
import static java.util.logging.Level.WARNING;
>>>>>>> Switched Roboguice/Guice out for Dagger 2
import static org.briarproject.api.forum.ForumConstants.FORUM_SALT_LENGTH; import static org.briarproject.api.forum.ForumConstants.FORUM_SALT_LENGTH;
import static org.briarproject.api.forum.ForumConstants.MAX_FORUM_NAME_LENGTH; import static org.briarproject.api.forum.ForumConstants.MAX_FORUM_NAME_LENGTH;
import static org.briarproject.api.sync.SyncConstants.MESSAGE_HEADER_LENGTH; import static org.briarproject.api.sync.SyncConstants.MESSAGE_HEADER_LENGTH;

View File

@@ -1,7 +1,5 @@
package org.briarproject.identity; package org.briarproject.identity;
import com.google.inject.Inject;
import org.briarproject.api.db.DatabaseComponent; import org.briarproject.api.db.DatabaseComponent;
import org.briarproject.api.db.DbException; import org.briarproject.api.db.DbException;
import org.briarproject.api.db.Transaction; import org.briarproject.api.db.Transaction;
@@ -13,7 +11,21 @@ import java.util.Collection;
import java.util.List; import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.CopyOnWriteArrayList;
<<<<<<< 08099714bab27d1ed48a8bee431a35a38098ecec
class IdentityManagerImpl implements IdentityManager { class IdentityManagerImpl implements IdentityManager {
=======
import javax.inject.Inject;
import static java.util.logging.Level.WARNING;
import static org.briarproject.api.db.StorageStatus.ACTIVE;
import static org.briarproject.api.db.StorageStatus.ADDING;
import static org.briarproject.api.db.StorageStatus.REMOVING;
class IdentityManagerImpl implements IdentityManager, Service {
private static final Logger LOG =
Logger.getLogger(IdentityManagerImpl.class.getName());
>>>>>>> Switched Roboguice/Guice out for Dagger 2
private final DatabaseComponent db; private final DatabaseComponent db;
private final List<AddIdentityHook> addHooks; private final List<AddIdentityHook> addHooks;

View File

@@ -1,23 +1,20 @@
package org.briarproject.identity; package org.briarproject.identity;
import com.google.inject.AbstractModule; import org.briarproject.api.db.DatabaseComponent;
import com.google.inject.Provides; import org.briarproject.api.event.EventBus;
import org.briarproject.api.data.ObjectReader;
import org.briarproject.api.identity.Author;
import org.briarproject.api.identity.AuthorFactory;
import org.briarproject.api.identity.IdentityManager; import org.briarproject.api.identity.IdentityManager;
public class IdentityModule extends AbstractModule { import javax.inject.Singleton;
@Override import dagger.Module;
protected void configure() { import dagger.Provides;
bind(AuthorFactory.class).to(AuthorFactoryImpl.class);
bind(IdentityManager.class).to(IdentityManagerImpl.class); @Module
} public class IdentityModule {
@Provides @Provides
ObjectReader<Author> getAuthorReader(AuthorFactory authorFactory) { @Singleton
return new AuthorReader(authorFactory); IdentityManager provideIdendityModule(DatabaseComponent db, EventBus eventBus) {
return new IdentityManagerImpl(db, eventBus);
} }
} }

View File

@@ -2,14 +2,41 @@ package org.briarproject.invitation;
import javax.inject.Singleton; import javax.inject.Singleton;
import org.briarproject.api.contact.ContactManager;
import org.briarproject.api.crypto.CryptoComponent;
import org.briarproject.api.data.BdfReaderFactory;
import org.briarproject.api.data.BdfWriterFactory;
import org.briarproject.api.identity.AuthorFactory;
import org.briarproject.api.identity.IdentityManager;
import org.briarproject.api.invitation.InvitationTaskFactory; import org.briarproject.api.invitation.InvitationTaskFactory;
import org.briarproject.api.plugins.ConnectionManager;
import org.briarproject.api.plugins.PluginManager;
import org.briarproject.api.sync.GroupFactory;
import org.briarproject.api.system.Clock;
import org.briarproject.api.transport.KeyManager;
import org.briarproject.api.transport.StreamReaderFactory;
import org.briarproject.api.transport.StreamWriterFactory;
import com.google.inject.AbstractModule; import dagger.Module;
import dagger.Provides;
public class InvitationModule extends AbstractModule { @Module
public class InvitationModule {
protected void configure() { @Provides
bind(InvitationTaskFactory.class).to( @Singleton
InvitationTaskFactoryImpl.class).in(Singleton.class); InvitationTaskFactory provideInvitationTaskFactory(CryptoComponent crypto,
BdfReaderFactory bdfReaderFactory,
BdfWriterFactory bdfWriterFactory,
StreamReaderFactory streamReaderFactory,
StreamWriterFactory streamWriterFactory,
AuthorFactory authorFactory, GroupFactory groupFactory,
KeyManager keyManager, ConnectionManager connectionManager,
IdentityManager identityManager, ContactManager contactManager,
Clock clock, PluginManager pluginManager) {
return new InvitationTaskFactoryImpl(crypto, bdfReaderFactory,
bdfWriterFactory, streamReaderFactory, streamWriterFactory,
authorFactory, groupFactory, keyManager, connectionManager,
identityManager, contactManager, clock, pluginManager);
} }
} }

View File

@@ -11,14 +11,18 @@ import java.util.concurrent.ThreadPoolExecutor;
import javax.inject.Singleton; import javax.inject.Singleton;
import org.briarproject.api.db.DatabaseComponent;
import org.briarproject.api.event.EventBus;
import org.briarproject.api.lifecycle.IoExecutor; import org.briarproject.api.lifecycle.IoExecutor;
import org.briarproject.api.lifecycle.LifecycleManager; import org.briarproject.api.lifecycle.LifecycleManager;
import org.briarproject.api.lifecycle.ShutdownManager; import org.briarproject.api.lifecycle.ShutdownManager;
import org.briarproject.api.system.Clock;
import com.google.inject.AbstractModule; import dagger.Module;
import com.google.inject.Provides; import dagger.Provides;
public class LifecycleModule extends AbstractModule { @Module
public class LifecycleModule {
private final ExecutorService ioExecutor; private final ExecutorService ioExecutor;
@@ -33,17 +37,25 @@ public class LifecycleModule extends AbstractModule {
60, SECONDS, queue, policy); 60, SECONDS, queue, policy);
} }
@Override @Provides
protected void configure() { @Singleton
bind(LifecycleManager.class).to( ShutdownManager provideShutdownManager() {
LifecycleManagerImpl.class).in(Singleton.class); return new ShutdownManagerImpl();
bind(ShutdownManager.class).to(
ShutdownManagerImpl.class).in(Singleton.class);
} }
@Provides @Singleton @IoExecutor @Provides
@Singleton
LifecycleManager provideLifeCycleManager(Clock clock, DatabaseComponent db,
EventBus eventBus) {
return new LifecycleManagerImpl(clock, db, eventBus);
}
@Provides
@Singleton
@IoExecutor
Executor getIoExecutor(LifecycleManager lifecycleManager) { Executor getIoExecutor(LifecycleManager lifecycleManager) {
lifecycleManager.registerForShutdown(ioExecutor); lifecycleManager.registerForShutdown(ioExecutor);
return ioExecutor; return ioExecutor;
} }
} }

View File

@@ -1,18 +1,19 @@
package org.briarproject.messaging; package org.briarproject.messaging;
import com.google.inject.Inject;
import org.briarproject.api.FormatException; import org.briarproject.api.FormatException;
import org.briarproject.api.clients.ClientHelper;
import org.briarproject.api.clients.PrivateGroupFactory; import org.briarproject.api.clients.PrivateGroupFactory;
import org.briarproject.api.contact.Contact; import org.briarproject.api.contact.Contact;
import org.briarproject.api.contact.ContactId; import org.briarproject.api.contact.ContactId;
import org.briarproject.api.contact.ContactManager.AddContactHook; import org.briarproject.api.contact.ContactManager.AddContactHook;
import org.briarproject.api.contact.ContactManager.RemoveContactHook; import org.briarproject.api.contact.ContactManager.RemoveContactHook;
import org.briarproject.api.data.BdfDictionary; import org.briarproject.api.data.BdfDictionary;
import org.briarproject.api.data.BdfList; import org.briarproject.api.data.BdfReader;
import org.briarproject.api.data.BdfReaderFactory;
import org.briarproject.api.data.MetadataEncoder;
import org.briarproject.api.data.MetadataParser;
import org.briarproject.api.db.DatabaseComponent; import org.briarproject.api.db.DatabaseComponent;
import org.briarproject.api.db.DbException; import org.briarproject.api.db.DbException;
import org.briarproject.api.db.Metadata;
import org.briarproject.api.db.Transaction; import org.briarproject.api.db.Transaction;
import org.briarproject.api.messaging.MessagingManager; import org.briarproject.api.messaging.MessagingManager;
import org.briarproject.api.messaging.PrivateMessage; import org.briarproject.api.messaging.PrivateMessage;
@@ -24,9 +25,18 @@ import org.briarproject.api.sync.MessageId;
import org.briarproject.api.sync.MessageStatus; import org.briarproject.api.sync.MessageStatus;
import org.briarproject.util.StringUtils; import org.briarproject.util.StringUtils;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collection; import java.util.Collection;
import java.util.Map; import java.util.Map;
import java.util.logging.Logger;
import javax.inject.Inject;
import static java.util.logging.Level.WARNING;
import static org.briarproject.api.messaging.MessagingConstants.MAX_PRIVATE_MESSAGE_BODY_LENGTH;
import static org.briarproject.api.sync.SyncConstants.MESSAGE_HEADER_LENGTH;
class MessagingManagerImpl implements MessagingManager, AddContactHook, class MessagingManagerImpl implements MessagingManager, AddContactHook,
RemoveContactHook { RemoveContactHook {
@@ -35,16 +45,25 @@ class MessagingManagerImpl implements MessagingManager, AddContactHook,
"6bcdc006c0910b0f44e40644c3b31f1a" "6bcdc006c0910b0f44e40644c3b31f1a"
+ "8bf9a6d6021d40d219c86b731b903070")); + "8bf9a6d6021d40d219c86b731b903070"));
private static final Logger LOG =
Logger.getLogger(MessagingManagerImpl.class.getName());
private final DatabaseComponent db; private final DatabaseComponent db;
private final ClientHelper clientHelper;
private final PrivateGroupFactory privateGroupFactory; private final PrivateGroupFactory privateGroupFactory;
private final BdfReaderFactory bdfReaderFactory;
private final MetadataEncoder metadataEncoder;
private final MetadataParser metadataParser;
@Inject @Inject
MessagingManagerImpl(DatabaseComponent db, ClientHelper clientHelper, MessagingManagerImpl(DatabaseComponent db,
PrivateGroupFactory privateGroupFactory) { PrivateGroupFactory privateGroupFactory,
BdfReaderFactory bdfReaderFactory, MetadataEncoder metadataEncoder,
MetadataParser metadataParser) {
this.db = db; this.db = db;
this.clientHelper = clientHelper;
this.privateGroupFactory = privateGroupFactory; this.privateGroupFactory = privateGroupFactory;
this.bdfReaderFactory = bdfReaderFactory;
this.metadataEncoder = metadataEncoder;
this.metadataParser = metadataParser;
} }
@Override @Override
@@ -58,7 +77,7 @@ class MessagingManagerImpl implements MessagingManager, AddContactHook,
// Attach the contact ID to the group // Attach the contact ID to the group
BdfDictionary d = new BdfDictionary(); BdfDictionary d = new BdfDictionary();
d.put("contactId", c.getId().getInt()); d.put("contactId", c.getId().getInt());
clientHelper.mergeGroupMetadata(txn, g.getId(), d); db.mergeGroupMetadata(txn, g.getId(), metadataEncoder.encode(d));
} catch (FormatException e) { } catch (FormatException e) {
throw new RuntimeException(e); throw new RuntimeException(e);
} }
@@ -81,13 +100,21 @@ class MessagingManagerImpl implements MessagingManager, AddContactHook,
@Override @Override
public void addLocalMessage(PrivateMessage m) throws DbException { public void addLocalMessage(PrivateMessage m) throws DbException {
try { try {
BdfDictionary meta = new BdfDictionary(); BdfDictionary d = new BdfDictionary();
meta.put("timestamp", m.getMessage().getTimestamp()); d.put("timestamp", m.getMessage().getTimestamp());
if (m.getParent() != null) meta.put("parent", m.getParent()); if (m.getParent() != null)
meta.put("contentType", m.getContentType()); d.put("parent", m.getParent().getBytes());
meta.put("local", true); d.put("contentType", m.getContentType());
meta.put("read", true); d.put("local", true);
clientHelper.addLocalMessage(m.getMessage(), CLIENT_ID, meta, true); d.put("read", true);
Metadata meta = metadataEncoder.encode(d);
Transaction txn = db.startTransaction();
try {
db.addLocalMessage(txn, m.getMessage(), CLIENT_ID, meta, true);
txn.setComplete();
} finally {
db.endTransaction(txn);
}
} catch (FormatException e) { } catch (FormatException e) {
throw new RuntimeException(e); throw new RuntimeException(e);
} }
@@ -96,8 +123,16 @@ class MessagingManagerImpl implements MessagingManager, AddContactHook,
@Override @Override
public ContactId getContactId(GroupId g) throws DbException { public ContactId getContactId(GroupId g) throws DbException {
try { try {
BdfDictionary meta = clientHelper.getGroupMetadataAsDictionary(g); Metadata meta;
return new ContactId(meta.getLong("contactId").intValue()); Transaction txn = db.startTransaction();
try {
meta = db.getGroupMetadata(txn, g);
txn.setComplete();
} finally {
db.endTransaction(txn);
}
BdfDictionary d = metadataParser.parse(meta);
return new ContactId(d.getLong("contactId").intValue());
} catch (FormatException e) { } catch (FormatException e) {
throw new DbException(e); throw new DbException(e);
} }
@@ -119,16 +154,14 @@ class MessagingManagerImpl implements MessagingManager, AddContactHook,
@Override @Override
public Collection<PrivateMessageHeader> getMessageHeaders(ContactId c) public Collection<PrivateMessageHeader> getMessageHeaders(ContactId c)
throws DbException { throws DbException {
Map<MessageId, BdfDictionary> metadata; Map<MessageId, Metadata> metadata;
Collection<MessageStatus> statuses; Collection<MessageStatus> statuses;
Transaction txn = db.startTransaction(); Transaction txn = db.startTransaction();
try { try {
GroupId g = getContactGroup(db.getContact(txn, c)).getId(); GroupId g = getContactGroup(db.getContact(txn, c)).getId();
metadata = clientHelper.getMessageMetadataAsDictionary(txn, g); metadata = db.getMessageMetadata(txn, g);
statuses = db.getMessageStatus(txn, c, g); statuses = db.getMessageStatus(txn, c, g);
txn.setComplete(); txn.setComplete();
} catch (FormatException e) {
throw new DbException(e);
} finally { } finally {
db.endTransaction(txn); db.endTransaction(txn);
} }
@@ -136,17 +169,18 @@ class MessagingManagerImpl implements MessagingManager, AddContactHook,
new ArrayList<PrivateMessageHeader>(); new ArrayList<PrivateMessageHeader>();
for (MessageStatus s : statuses) { for (MessageStatus s : statuses) {
MessageId id = s.getMessageId(); MessageId id = s.getMessageId();
BdfDictionary meta = metadata.get(id); Metadata m = metadata.get(id);
if (meta == null) continue; if (m == null) continue;
try { try {
long timestamp = meta.getLong("timestamp"); BdfDictionary d = metadataParser.parse(m);
String contentType = meta.getString("contentType"); long timestamp = d.getLong("timestamp");
boolean local = meta.getBoolean("local"); String contentType = d.getString("contentType");
boolean read = meta.getBoolean("read"); boolean local = d.getBoolean("local");
boolean read = d.getBoolean("read");
headers.add(new PrivateMessageHeader(id, timestamp, contentType, headers.add(new PrivateMessageHeader(id, timestamp, contentType,
local, read, s.isSent(), s.isSeen())); local, read, s.isSent(), s.isSeen()));
} catch (FormatException e) { } catch (FormatException e) {
throw new DbException(e); if (LOG.isLoggable(WARNING)) LOG.log(WARNING, e.toString(), e);
} }
} }
return headers; return headers;
@@ -154,21 +188,47 @@ class MessagingManagerImpl implements MessagingManager, AddContactHook,
@Override @Override
public byte[] getMessageBody(MessageId m) throws DbException { public byte[] getMessageBody(MessageId m) throws DbException {
byte[] raw;
Transaction txn = db.startTransaction();
try { try {
// Parent ID, content type, private message body raw = db.getRawMessage(txn, m);
BdfList message = clientHelper.getMessageAsList(m); txn.setComplete();
return message.getRaw(2); } finally {
db.endTransaction(txn);
}
ByteArrayInputStream in = new ByteArrayInputStream(raw,
MESSAGE_HEADER_LENGTH, raw.length - MESSAGE_HEADER_LENGTH);
BdfReader r = bdfReaderFactory.createReader(in);
try {
r.readListStart();
if (r.hasRaw()) r.skipRaw(); // Parent ID
else r.skipNull(); // No parent
r.skipString(); // Content type
byte[] messageBody = r.readRaw(MAX_PRIVATE_MESSAGE_BODY_LENGTH);
r.readListEnd();
if (!r.eof()) throw new FormatException();
return messageBody;
} catch (FormatException e) { } catch (FormatException e) {
throw new DbException(e); throw new DbException(e);
} catch (IOException e) {
// Shouldn't happen with ByteArrayInputStream
throw new RuntimeException(e);
} }
} }
@Override @Override
public void setReadFlag(MessageId m, boolean read) throws DbException { public void setReadFlag(MessageId m, boolean read) throws DbException {
try { try {
BdfDictionary meta = new BdfDictionary(); BdfDictionary d = new BdfDictionary();
meta.put("read", read); d.put("read", read);
clientHelper.mergeMessageMetadata(m, meta); Metadata meta = metadataEncoder.encode(d);
Transaction txn = db.startTransaction();
try {
db.mergeMessageMetadata(txn, m, meta);
txn.setComplete();
} finally {
db.endTransaction(txn);
}
} catch (FormatException e) { } catch (FormatException e) {
throw new RuntimeException(e); throw new RuntimeException(e);
} }

View File

@@ -1,38 +1,46 @@
package org.briarproject.messaging; package org.briarproject.messaging;
import com.google.inject.AbstractModule;
import com.google.inject.Provides;
import org.briarproject.api.clients.ClientHelper;
import org.briarproject.api.contact.ContactManager; import org.briarproject.api.contact.ContactManager;
import org.briarproject.api.data.BdfReaderFactory;
import org.briarproject.api.data.BdfWriterFactory;
import org.briarproject.api.data.MetadataEncoder; import org.briarproject.api.data.MetadataEncoder;
import org.briarproject.api.messaging.MessagingManager; import org.briarproject.api.messaging.MessagingManager;
import org.briarproject.api.messaging.PrivateMessageFactory; import org.briarproject.api.messaging.PrivateMessageFactory;
import org.briarproject.api.sync.MessageFactory;
import org.briarproject.api.sync.ValidationManager; import org.briarproject.api.sync.ValidationManager;
import org.briarproject.api.system.Clock; import org.briarproject.api.system.Clock;
import javax.inject.Singleton; import javax.inject.Singleton;
import dagger.Module;
import dagger.Provides;
import static org.briarproject.messaging.MessagingManagerImpl.CLIENT_ID; import static org.briarproject.messaging.MessagingManagerImpl.CLIENT_ID;
public class MessagingModule extends AbstractModule { @Module
public class MessagingModule {
@Override @Provides
protected void configure() { PrivateMessageFactory providePrivateMessageFactory(
bind(PrivateMessageFactory.class).to(PrivateMessageFactoryImpl.class); MessageFactory messageFactory,
BdfWriterFactory bdfWriterFactory) {
return new PrivateMessageFactoryImpl(messageFactory, bdfWriterFactory);
} }
@Provides @Singleton
@Provides
@Singleton
PrivateMessageValidator getValidator(ValidationManager validationManager, PrivateMessageValidator getValidator(ValidationManager validationManager,
ClientHelper clientHelper, MetadataEncoder metadataEncoder, BdfReaderFactory bdfReaderFactory, MetadataEncoder metadataEncoder,
Clock clock) { Clock clock) {
PrivateMessageValidator validator = new PrivateMessageValidator( PrivateMessageValidator validator = new PrivateMessageValidator(
clientHelper, metadataEncoder, clock); bdfReaderFactory, metadataEncoder, clock);
validationManager.registerMessageValidator(CLIENT_ID, validator); validationManager.registerMessageValidator(CLIENT_ID, validator);
return validator; return validator;
} }
@Provides @Singleton @Provides
@Singleton
MessagingManager getMessagingManager(ContactManager contactManager, MessagingManager getMessagingManager(ContactManager contactManager,
MessagingManagerImpl messagingManager) { MessagingManagerImpl messagingManager) {
contactManager.registerAddContactHook(messagingManager); contactManager.registerAddContactHook(messagingManager);

View File

@@ -1,7 +1,5 @@
package org.briarproject.plugins; package org.briarproject.plugins;
import com.google.inject.Inject;
import org.briarproject.api.TransportId; import org.briarproject.api.TransportId;
import org.briarproject.api.contact.ContactId; import org.briarproject.api.contact.ContactId;
import org.briarproject.api.event.ContactConnectedEvent; import org.briarproject.api.event.ContactConnectedEvent;
@@ -19,6 +17,8 @@ import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock; import java.util.concurrent.locks.ReentrantLock;
import java.util.logging.Logger; import java.util.logging.Logger;
import javax.inject.Inject;
import static java.util.logging.Level.INFO; import static java.util.logging.Level.INFO;
class ConnectionRegistryImpl implements ConnectionRegistry { class ConnectionRegistryImpl implements ConnectionRegistry {

View File

@@ -1,28 +1,54 @@
package org.briarproject.plugins; package org.briarproject.plugins;
import com.google.inject.AbstractModule;
import com.google.inject.Provides;
import org.briarproject.api.lifecycle.LifecycleManager;
import org.briarproject.api.plugins.BackoffFactory;
import org.briarproject.api.plugins.ConnectionManager;
import org.briarproject.api.plugins.ConnectionRegistry;
import org.briarproject.api.plugins.PluginManager;
import javax.inject.Singleton; import javax.inject.Singleton;
public class PluginsModule extends AbstractModule { import org.briarproject.api.event.EventBus;
import org.briarproject.api.lifecycle.IoExecutor;
import org.briarproject.api.lifecycle.LifecycleManager;
import org.briarproject.api.plugins.ConnectionManager;
import org.briarproject.api.plugins.ConnectionRegistry;
import org.briarproject.api.plugins.PluginManager;
import org.briarproject.api.sync.SyncSessionFactory;
import org.briarproject.api.system.Timer;
import org.briarproject.api.transport.KeyManager;
import org.briarproject.api.transport.StreamReaderFactory;
import org.briarproject.api.transport.StreamWriterFactory;
@Override import java.util.concurrent.Executor;
protected void configure() {
bind(BackoffFactory.class).to(BackoffFactoryImpl.class); import dagger.Module;
bind(Poller.class).to(PollerImpl.class); import dagger.Provides;
bind(ConnectionManager.class).to(ConnectionManagerImpl.class);
bind(ConnectionRegistry.class).to(
ConnectionRegistryImpl.class).in(Singleton.class); @Module
public class PluginsModule {
@Provides
Poller providePoller(@IoExecutor Executor ioExecutor,
ConnectionRegistry connectionRegistry, Timer timer) {
return new PollerImpl(ioExecutor, connectionRegistry, timer);
} }
@Provides @Singleton @Provides
ConnectionManager provideConnectionManager(
@IoExecutor Executor ioExecutor,
KeyManager keyManager, StreamReaderFactory streamReaderFactory,
StreamWriterFactory streamWriterFactory,
SyncSessionFactory syncSessionFactory,
ConnectionRegistry connectionRegistry) {
return new ConnectionManagerImpl(ioExecutor, keyManager,
streamReaderFactory, streamWriterFactory, syncSessionFactory,
connectionRegistry);
}
@Provides
@Singleton
ConnectionRegistry provideConnectionRegistry(EventBus eventBus) {
return new ConnectionRegistryImpl(eventBus);
}
@Provides
@Singleton
PluginManager getPluginManager(LifecycleManager lifecycleManager, PluginManager getPluginManager(LifecycleManager lifecycleManager,
PluginManagerImpl pluginManager) { PluginManagerImpl pluginManager) {
lifecycleManager.register(pluginManager); lifecycleManager.register(pluginManager);

View File

@@ -1,10 +1,7 @@
package org.briarproject.properties; package org.briarproject.properties;
import com.google.inject.AbstractModule;
import com.google.inject.Provides;
import org.briarproject.api.clients.ClientHelper;
import org.briarproject.api.contact.ContactManager; import org.briarproject.api.contact.ContactManager;
import org.briarproject.api.data.BdfReaderFactory;
import org.briarproject.api.data.MetadataEncoder; import org.briarproject.api.data.MetadataEncoder;
import org.briarproject.api.properties.TransportPropertyManager; import org.briarproject.api.properties.TransportPropertyManager;
import org.briarproject.api.sync.ValidationManager; import org.briarproject.api.sync.ValidationManager;
@@ -12,19 +9,21 @@ import org.briarproject.api.system.Clock;
import javax.inject.Singleton; import javax.inject.Singleton;
import dagger.Module;
import dagger.Provides;
import static org.briarproject.properties.TransportPropertyManagerImpl.CLIENT_ID; import static org.briarproject.properties.TransportPropertyManagerImpl.CLIENT_ID;
public class PropertiesModule extends AbstractModule { @Module
public class PropertiesModule {
@Override @Provides
protected void configure() {} @Singleton
@Provides @Singleton
TransportPropertyValidator getValidator(ValidationManager validationManager, TransportPropertyValidator getValidator(ValidationManager validationManager,
ClientHelper clientHelper, MetadataEncoder metadataEncoder, BdfReaderFactory bdfReaderFactory, MetadataEncoder metadataEncoder,
Clock clock) { Clock clock) {
TransportPropertyValidator validator = new TransportPropertyValidator( TransportPropertyValidator validator = new TransportPropertyValidator(
clientHelper, metadataEncoder, clock); bdfReaderFactory, metadataEncoder, clock);
validationManager.registerMessageValidator(CLIENT_ID, validator); validationManager.registerMessageValidator(CLIENT_ID, validator);
return validator; return validator;
} }

View File

@@ -1,20 +1,23 @@
package org.briarproject.properties; package org.briarproject.properties;
import com.google.inject.Inject;
import org.briarproject.api.DeviceId; import org.briarproject.api.DeviceId;
import org.briarproject.api.FormatException; import org.briarproject.api.FormatException;
import org.briarproject.api.TransportId; import org.briarproject.api.TransportId;
import org.briarproject.api.clients.ClientHelper;
import org.briarproject.api.clients.PrivateGroupFactory; import org.briarproject.api.clients.PrivateGroupFactory;
import org.briarproject.api.contact.Contact; import org.briarproject.api.contact.Contact;
import org.briarproject.api.contact.ContactId; import org.briarproject.api.contact.ContactId;
import org.briarproject.api.contact.ContactManager.AddContactHook; import org.briarproject.api.contact.ContactManager.AddContactHook;
import org.briarproject.api.contact.ContactManager.RemoveContactHook; import org.briarproject.api.contact.ContactManager.RemoveContactHook;
import org.briarproject.api.data.BdfDictionary; import org.briarproject.api.data.BdfDictionary;
import org.briarproject.api.data.BdfList; import org.briarproject.api.data.BdfReader;
import org.briarproject.api.data.BdfReaderFactory;
import org.briarproject.api.data.BdfWriter;
import org.briarproject.api.data.BdfWriterFactory;
import org.briarproject.api.data.MetadataEncoder;
import org.briarproject.api.data.MetadataParser;
import org.briarproject.api.db.DatabaseComponent; import org.briarproject.api.db.DatabaseComponent;
import org.briarproject.api.db.DbException; import org.briarproject.api.db.DbException;
import org.briarproject.api.db.Metadata;
import org.briarproject.api.db.NoSuchGroupException; import org.briarproject.api.db.NoSuchGroupException;
import org.briarproject.api.db.Transaction; import org.briarproject.api.db.Transaction;
import org.briarproject.api.properties.TransportProperties; import org.briarproject.api.properties.TransportProperties;
@@ -24,15 +27,24 @@ import org.briarproject.api.sync.Group;
import org.briarproject.api.sync.GroupFactory; import org.briarproject.api.sync.GroupFactory;
import org.briarproject.api.sync.GroupId; import org.briarproject.api.sync.GroupId;
import org.briarproject.api.sync.Message; import org.briarproject.api.sync.Message;
import org.briarproject.api.sync.MessageFactory;
import org.briarproject.api.sync.MessageId; import org.briarproject.api.sync.MessageId;
import org.briarproject.api.system.Clock; import org.briarproject.api.system.Clock;
import org.briarproject.util.StringUtils; import org.briarproject.util.StringUtils;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Collections; import java.util.Collections;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import java.util.Map.Entry; import java.util.Map.Entry;
import javax.inject.Inject;
import static org.briarproject.api.properties.TransportPropertyConstants.MAX_PROPERTY_LENGTH;
import static org.briarproject.api.sync.SyncConstants.MESSAGE_HEADER_LENGTH;
class TransportPropertyManagerImpl implements TransportPropertyManager, class TransportPropertyManagerImpl implements TransportPropertyManager,
AddContactHook, RemoveContactHook { AddContactHook, RemoveContactHook {
@@ -43,18 +55,28 @@ class TransportPropertyManagerImpl implements TransportPropertyManager,
private static final byte[] LOCAL_GROUP_DESCRIPTOR = new byte[0]; private static final byte[] LOCAL_GROUP_DESCRIPTOR = new byte[0];
private final DatabaseComponent db; private final DatabaseComponent db;
private final ClientHelper clientHelper;
private final PrivateGroupFactory privateGroupFactory; private final PrivateGroupFactory privateGroupFactory;
private final MessageFactory messageFactory;
private final BdfReaderFactory bdfReaderFactory;
private final BdfWriterFactory bdfWriterFactory;
private final MetadataEncoder metadataEncoder;
private final MetadataParser metadataParser;
private final Clock clock; private final Clock clock;
private final Group localGroup; private final Group localGroup;
@Inject @Inject
TransportPropertyManagerImpl(DatabaseComponent db, TransportPropertyManagerImpl(DatabaseComponent db,
ClientHelper clientHelper, GroupFactory groupFactory, GroupFactory groupFactory, PrivateGroupFactory privateGroupFactory,
PrivateGroupFactory privateGroupFactory, Clock clock) { MessageFactory messageFactory, BdfReaderFactory bdfReaderFactory,
BdfWriterFactory bdfWriterFactory, MetadataEncoder metadataEncoder,
MetadataParser metadataParser, Clock clock) {
this.db = db; this.db = db;
this.clientHelper = clientHelper;
this.privateGroupFactory = privateGroupFactory; this.privateGroupFactory = privateGroupFactory;
this.messageFactory = messageFactory;
this.bdfReaderFactory = bdfReaderFactory;
this.bdfWriterFactory = bdfWriterFactory;
this.metadataEncoder = metadataEncoder;
this.metadataParser = metadataParser;
this.clock = clock; this.clock = clock;
localGroup = groupFactory.createGroup(CLIENT_ID, localGroup = groupFactory.createGroup(CLIENT_ID,
LOCAL_GROUP_DESCRIPTOR); LOCAL_GROUP_DESCRIPTOR);
@@ -123,9 +145,8 @@ class TransportPropertyManagerImpl implements TransportPropertyManager,
true); true);
if (latest != null) { if (latest != null) {
// Retrieve and parse the latest local properties // Retrieve and parse the latest local properties
BdfList message = clientHelper.getMessageAsList(txn, byte[] raw = db.getRawMessage(txn, latest.messageId);
latest.messageId); p = parseProperties(raw);
p = parseProperties(message);
} }
txn.setComplete(); txn.setComplete();
} finally { } finally {
@@ -154,9 +175,8 @@ class TransportPropertyManagerImpl implements TransportPropertyManager,
LatestUpdate latest = findLatest(txn, g.getId(), t, false); LatestUpdate latest = findLatest(txn, g.getId(), t, false);
if (latest != null) { if (latest != null) {
// Retrieve and parse the latest remote properties // Retrieve and parse the latest remote properties
BdfList message = clientHelper.getMessageAsList(txn, byte[] raw = db.getRawMessage(txn, latest.messageId);
latest.messageId); remote.put(c.getId(), parseProperties(raw));
remote.put(c.getId(), parseProperties(message));
} }
} }
txn.setComplete(); txn.setComplete();
@@ -186,9 +206,8 @@ class TransportPropertyManagerImpl implements TransportPropertyManager,
merged = p; merged = p;
changed = true; changed = true;
} else { } else {
BdfList message = clientHelper.getMessageAsList(txn, byte[] raw = db.getRawMessage(txn, latest.messageId);
latest.messageId); TransportProperties old = parseProperties(raw);
TransportProperties old = parseProperties(message);
merged = new TransportProperties(old); merged = new TransportProperties(old);
merged.putAll(p); merged.putAll(p);
changed = !merged.equals(old); changed = !merged.equals(old);
@@ -231,9 +250,8 @@ class TransportPropertyManagerImpl implements TransportPropertyManager,
localGroup.getId(), true); localGroup.getId(), true);
// Retrieve and parse the latest local properties // Retrieve and parse the latest local properties
for (Entry<TransportId, LatestUpdate> e : latest.entrySet()) { for (Entry<TransportId, LatestUpdate> e : latest.entrySet()) {
BdfList message = clientHelper.getMessageAsList(txn, byte[] raw = db.getRawMessage(txn, e.getValue().messageId);
e.getValue().messageId); local.put(e.getKey(), parseProperties(raw));
local.put(e.getKey(), parseProperties(message));
} }
return local; return local;
} catch (NoSuchGroupException e) { } catch (NoSuchGroupException e) {
@@ -248,35 +266,48 @@ class TransportPropertyManagerImpl implements TransportPropertyManager,
TransportId t, TransportProperties p, long version, boolean local, TransportId t, TransportProperties p, long version, boolean local,
boolean shared) throws DbException { boolean shared) throws DbException {
try { try {
BdfList body = encodeProperties(dev, t, p, version); byte[] body = encodeProperties(dev, t, p, version);
long now = clock.currentTimeMillis(); long now = clock.currentTimeMillis();
Message m = clientHelper.createMessage(g, now, body); Message m = messageFactory.createMessage(g, now, body);
BdfDictionary meta = new BdfDictionary(); BdfDictionary d = new BdfDictionary();
meta.put("transportId", t.getString()); d.put("transportId", t.getString());
meta.put("version", version); d.put("version", version);
meta.put("local", local); d.put("local", local);
clientHelper.addLocalMessage(txn, m, CLIENT_ID, meta, shared); Metadata meta = metadataEncoder.encode(d);
db.addLocalMessage(txn, m, CLIENT_ID, meta, shared);
} catch (FormatException e) { } catch (FormatException e) {
throw new RuntimeException(e); throw new RuntimeException(e);
} }
} }
private BdfList encodeProperties(DeviceId dev, TransportId t, private byte[] encodeProperties(DeviceId dev, TransportId t,
TransportProperties p, long version) { TransportProperties p, long version) {
return BdfList.of(dev, t.getString(), version, p); ByteArrayOutputStream out = new ByteArrayOutputStream();
BdfWriter w = bdfWriterFactory.createWriter(out);
try {
w.writeListStart();
w.writeRaw(dev.getBytes());
w.writeString(t.getString());
w.writeLong(version);
w.writeDictionary(p);
w.writeListEnd();
} catch (IOException e) {
// Shouldn't happen with ByteArrayOutputStream
throw new RuntimeException(e);
}
return out.toByteArray();
} }
private Map<TransportId, LatestUpdate> findLatest(Transaction txn, private Map<TransportId, LatestUpdate> findLatest(Transaction txn,
GroupId g, boolean local) throws DbException, FormatException { GroupId g, boolean local) throws DbException, FormatException {
Map<TransportId, LatestUpdate> latestUpdates = Map<TransportId, LatestUpdate> latestUpdates =
new HashMap<TransportId, LatestUpdate>(); new HashMap<TransportId, LatestUpdate>();
Map<MessageId, BdfDictionary> metadata = Map<MessageId, Metadata> metadata = db.getMessageMetadata(txn, g);
clientHelper.getMessageMetadataAsDictionary(txn, g); for (Entry<MessageId, Metadata> e : metadata.entrySet()) {
for (Entry<MessageId, BdfDictionary> e : metadata.entrySet()) { BdfDictionary d = metadataParser.parse(e.getValue());
BdfDictionary meta = e.getValue(); if (d.getBoolean("local") == local) {
if (meta.getBoolean("local") == local) { TransportId t = new TransportId(d.getString("transportId"));
TransportId t = new TransportId(meta.getString("transportId")); long version = d.getLong("version");
long version = meta.getLong("version");
LatestUpdate latest = latestUpdates.get(t); LatestUpdate latest = latestUpdates.get(t);
if (latest == null || version > latest.version) if (latest == null || version > latest.version)
latestUpdates.put(t, new LatestUpdate(e.getKey(), version)); latestUpdates.put(t, new LatestUpdate(e.getKey(), version));
@@ -288,13 +319,12 @@ class TransportPropertyManagerImpl implements TransportPropertyManager,
private LatestUpdate findLatest(Transaction txn, GroupId g, TransportId t, private LatestUpdate findLatest(Transaction txn, GroupId g, TransportId t,
boolean local) throws DbException, FormatException { boolean local) throws DbException, FormatException {
LatestUpdate latest = null; LatestUpdate latest = null;
Map<MessageId, BdfDictionary> metadata = Map<MessageId, Metadata> metadata = db.getMessageMetadata(txn, g);
clientHelper.getMessageMetadataAsDictionary(txn, g); for (Entry<MessageId, Metadata> e : metadata.entrySet()) {
for (Entry<MessageId, BdfDictionary> e : metadata.entrySet()) { BdfDictionary d = metadataParser.parse(e.getValue());
BdfDictionary meta = e.getValue(); if (d.getString("transportId").equals(t.getString())
if (meta.getString("transportId").equals(t.getString()) && d.getBoolean("local") == local) {
&& meta.getBoolean("local") == local) { long version = d.getLong("version");
long version = meta.getLong("version");
if (latest == null || version > latest.version) if (latest == null || version > latest.version)
latest = new LatestUpdate(e.getKey(), version); latest = new LatestUpdate(e.getKey(), version);
} }
@@ -302,14 +332,33 @@ class TransportPropertyManagerImpl implements TransportPropertyManager,
return latest; return latest;
} }
private TransportProperties parseProperties(BdfList message) private TransportProperties parseProperties(byte[] raw)
throws FormatException { throws FormatException {
// Device ID, transport ID, version, properties
BdfDictionary dictionary = message.getDictionary(3);
TransportProperties p = new TransportProperties(); TransportProperties p = new TransportProperties();
for (String key : dictionary.keySet()) ByteArrayInputStream in = new ByteArrayInputStream(raw,
p.put(key, dictionary.getString(key)); MESSAGE_HEADER_LENGTH, raw.length - MESSAGE_HEADER_LENGTH);
return p; BdfReader r = bdfReaderFactory.createReader(in);
try {
r.readListStart();
r.skipRaw(); // Device ID
r.skipString(); // Transport ID
r.skipLong(); // Version
r.readDictionaryStart();
while (!r.hasDictionaryEnd()) {
String key = r.readString(MAX_PROPERTY_LENGTH);
String value = r.readString(MAX_PROPERTY_LENGTH);
p.put(key, value);
}
r.readDictionaryEnd();
r.readListEnd();
if (!r.eof()) throw new FormatException();
return p;
} catch (FormatException e) {
throw e;
} catch (IOException e) {
// Shouldn't happen with ByteArrayInputStream
throw new RuntimeException(e);
}
} }
private static class LatestUpdate { private static class LatestUpdate {

View File

@@ -1,14 +1,30 @@
package org.briarproject.reliability; package org.briarproject.reliability;
import org.briarproject.api.lifecycle.IoExecutor;
import org.briarproject.api.reliability.ReliabilityLayerFactory; import org.briarproject.api.reliability.ReliabilityLayerFactory;
import com.google.inject.AbstractModule; import java.util.concurrent.Executor;
public class ReliabilityModule extends AbstractModule { import dagger.Module;
import dagger.Provides;
@Override @Module
protected void configure() { public class ReliabilityModule {
bind(ReliabilityLayerFactory.class).to(
ReliabilityLayerFactoryImpl.class); /*
@Provides
ReliabilityLayerFactory provideReliabilityFactory(@IoExecutor
Executor ioExecutor) {
return new ReliabilityLayerFactoryImpl(ioExecutor);
} }
*/
@Provides
ReliabilityLayerFactory provideReliabilityFactory(
ReliabilityLayerFactoryImpl reliabilityLayerFactory) {
return reliabilityLayerFactory;
}
} }

View File

@@ -1,6 +1,5 @@
package org.briarproject.settings; package org.briarproject.settings;
import com.google.inject.Inject;
import org.briarproject.api.db.DatabaseComponent; import org.briarproject.api.db.DatabaseComponent;
import org.briarproject.api.db.DbException; import org.briarproject.api.db.DbException;
@@ -8,6 +7,8 @@ import org.briarproject.api.db.Transaction;
import org.briarproject.api.settings.Settings; import org.briarproject.api.settings.Settings;
import org.briarproject.api.settings.SettingsManager; import org.briarproject.api.settings.SettingsManager;
import javax.inject.Inject;
class SettingsManagerImpl implements SettingsManager { class SettingsManagerImpl implements SettingsManager {
private final DatabaseComponent db; private final DatabaseComponent db;

View File

@@ -1,13 +1,17 @@
package org.briarproject.settings; package org.briarproject.settings;
import com.google.inject.AbstractModule; import org.briarproject.api.db.DatabaseComponent;
import org.briarproject.api.settings.SettingsManager; import org.briarproject.api.settings.SettingsManager;
public class SettingsModule extends AbstractModule { import dagger.Module;
import dagger.Provides;
@Override @Module
protected void configure() { public class SettingsModule {
bind(SettingsManager.class).to(SettingsManagerImpl.class);
@Provides
SettingsManager provideSettingsManager(DatabaseComponent db) {
return new SettingsManagerImpl(db);
} }
} }

View File

@@ -1,6 +1,5 @@
package org.briarproject.sync; package org.briarproject.sync;
import com.google.inject.Inject;
import org.briarproject.api.UniqueId; import org.briarproject.api.UniqueId;
import org.briarproject.api.crypto.CryptoComponent; import org.briarproject.api.crypto.CryptoComponent;
@@ -10,6 +9,8 @@ import org.briarproject.api.sync.MessageFactory;
import org.briarproject.api.sync.MessageId; import org.briarproject.api.sync.MessageId;
import org.briarproject.util.ByteUtils; import org.briarproject.util.ByteUtils;
import javax.inject.Inject;
import static org.briarproject.api.sync.SyncConstants.MAX_MESSAGE_BODY_LENGTH; import static org.briarproject.api.sync.SyncConstants.MAX_MESSAGE_BODY_LENGTH;
import static org.briarproject.api.sync.SyncConstants.MESSAGE_HEADER_LENGTH; import static org.briarproject.api.sync.SyncConstants.MESSAGE_HEADER_LENGTH;

View File

@@ -1,32 +1,84 @@
package org.briarproject.sync; package org.briarproject.sync;
import com.google.inject.AbstractModule; import org.briarproject.api.crypto.CryptoComponent;
import com.google.inject.Provides; import org.briarproject.api.data.BdfWriterFactory;
import org.briarproject.api.data.ObjectReader;
import org.briarproject.api.db.DatabaseComponent;
import org.briarproject.api.db.DatabaseExecutor;
import org.briarproject.api.event.EventBus; import org.briarproject.api.event.EventBus;
import org.briarproject.api.identity.Author;
import org.briarproject.api.identity.AuthorFactory;
import org.briarproject.api.lifecycle.LifecycleManager; import org.briarproject.api.lifecycle.LifecycleManager;
import org.briarproject.api.sync.Group;
import org.briarproject.api.sync.GroupFactory; import org.briarproject.api.sync.GroupFactory;
import org.briarproject.api.sync.MessageFactory; import org.briarproject.api.sync.MessageFactory;
import org.briarproject.api.sync.PacketReaderFactory; import org.briarproject.api.sync.PacketReaderFactory;
import org.briarproject.api.sync.PacketWriterFactory; import org.briarproject.api.sync.PacketWriterFactory;
import org.briarproject.api.sync.PrivateGroupFactory;
import org.briarproject.api.sync.SyncSessionFactory; import org.briarproject.api.sync.SyncSessionFactory;
import org.briarproject.api.sync.ValidationManager; import org.briarproject.api.sync.ValidationManager;
import org.briarproject.api.system.Clock;
import java.util.concurrent.Executor;
import javax.inject.Singleton; import javax.inject.Singleton;
public class SyncModule extends AbstractModule { import dagger.Module;
import dagger.Provides;
@Override @Module
protected void configure() { public class SyncModule {
bind(GroupFactory.class).to(GroupFactoryImpl.class);
bind(MessageFactory.class).to(MessageFactoryImpl.class); @Provides
bind(PacketReaderFactory.class).to(PacketReaderFactoryImpl.class); AuthorFactory provideAuthFactory(CryptoComponent crypto,
bind(PacketWriterFactory.class).to(PacketWriterFactoryImpl.class); BdfWriterFactory bdfWriterFactory, Clock clock) {
bind(SyncSessionFactory.class).to( return new AuthorFactoryImpl(crypto, bdfWriterFactory, clock);
SyncSessionFactoryImpl.class).in(Singleton.class);
} }
@Provides @Singleton @Provides
GroupFactory provideGroupFactory(CryptoComponent crypto) {
return new GroupFactoryImpl(crypto);
}
@Provides
MessageFactory provideMessageFactory(CryptoComponent crypto) {
return new MessageFactoryImpl(crypto);
}
@Provides
PacketReaderFactory providePacketReaderFactory(CryptoComponent crypto) {
return new PacketReaderFactoryImpl(crypto);
}
@Provides
PacketWriterFactory providePacketWriterFactory() {
return new PacketWriterFactoryImpl();
}
@Provides
PrivateGroupFactory providePrivateGroupFactory(GroupFactory groupFactory,
BdfWriterFactory bdfWriterFactory) {
return new PrivateGroupFactoryImpl(groupFactory, bdfWriterFactory);
}
@Provides
@Singleton
SyncSessionFactory provideSyncSessionFactory(DatabaseComponent db,
@DatabaseExecutor Executor dbExecutor, EventBus eventBus,
Clock clock, PacketReaderFactory packetReaderFactory,
PacketWriterFactory packetWriterFactory) {
return new SyncSessionFactoryImpl(db, dbExecutor, eventBus, clock,
packetReaderFactory, packetWriterFactory);
}
@Provides
ObjectReader<Author> getAuthorReader(AuthorFactory authorFactory) {
return new AuthorReader(authorFactory);
}
@Provides
@Singleton
ValidationManager getValidationManager(LifecycleManager lifecycleManager, ValidationManager getValidationManager(LifecycleManager lifecycleManager,
EventBus eventBus, ValidationManagerImpl validationManager) { EventBus eventBus, ValidationManagerImpl validationManager) {
lifecycleManager.register(validationManager); lifecycleManager.register(validationManager);

View File

@@ -1,7 +1,5 @@
package org.briarproject.sync; package org.briarproject.sync;
import com.google.inject.Inject;
import org.briarproject.api.UniqueId; import org.briarproject.api.UniqueId;
import org.briarproject.api.crypto.CryptoExecutor; import org.briarproject.api.crypto.CryptoExecutor;
import org.briarproject.api.db.DatabaseComponent; import org.briarproject.api.db.DatabaseComponent;
@@ -30,6 +28,8 @@ import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executor; import java.util.concurrent.Executor;
import java.util.logging.Logger; import java.util.logging.Logger;
import javax.inject.Inject;
import static java.util.logging.Level.WARNING; import static java.util.logging.Level.WARNING;
import static org.briarproject.api.sync.SyncConstants.MESSAGE_HEADER_LENGTH; import static org.briarproject.api.sync.SyncConstants.MESSAGE_HEADER_LENGTH;

View File

@@ -1,8 +1,7 @@
package org.briarproject.transport; package org.briarproject.transport;
import com.google.inject.AbstractModule; import org.briarproject.api.crypto.StreamDecrypterFactory;
import com.google.inject.Provides; import org.briarproject.api.crypto.StreamEncrypterFactory;
import org.briarproject.api.event.EventBus; import org.briarproject.api.event.EventBus;
import org.briarproject.api.lifecycle.LifecycleManager; import org.briarproject.api.lifecycle.LifecycleManager;
import org.briarproject.api.transport.KeyManager; import org.briarproject.api.transport.KeyManager;
@@ -11,15 +10,26 @@ import org.briarproject.api.transport.StreamWriterFactory;
import javax.inject.Singleton; import javax.inject.Singleton;
public class TransportModule extends AbstractModule { import dagger.Module;
import dagger.Provides;
@Override @Module
protected void configure() { public class TransportModule {
bind(StreamReaderFactory.class).to(StreamReaderFactoryImpl.class);
bind(StreamWriterFactory.class).to(StreamWriterFactoryImpl.class); @Provides
StreamReaderFactory provideStreamReaderFactory(
StreamDecrypterFactory streamDecrypterFactory) {
return new StreamReaderFactoryImpl(streamDecrypterFactory);
} }
@Provides @Singleton @Provides
StreamWriterFactory provideStreamWriterFactory(
StreamEncrypterFactory streamEncrypterFactory) {
return new StreamWriterFactoryImpl(streamEncrypterFactory);
}
@Provides
@Singleton
KeyManager getKeyManager(LifecycleManager lifecycleManager, KeyManager getKeyManager(LifecycleManager lifecycleManager,
EventBus eventBus, KeyManagerImpl keyManager) { EventBus eventBus, KeyManagerImpl keyManager) {
lifecycleManager.register(keyManager); lifecycleManager.register(keyManager);

View File

@@ -4,10 +4,11 @@ import org.briarproject.api.lifecycle.LifecycleManager;
import org.briarproject.api.lifecycle.ShutdownManager; import org.briarproject.api.lifecycle.ShutdownManager;
import org.briarproject.util.OsUtils; import org.briarproject.util.OsUtils;
import com.google.inject.Singleton;
public class DesktopLifecycleModule extends LifecycleModule { public class DesktopLifecycleModule extends LifecycleModule {
/*
// TODO
@Override @Override
protected void configure() { protected void configure() {
bind(LifecycleManager.class).to( bind(LifecycleManager.class).to(
@@ -20,4 +21,5 @@ public class DesktopLifecycleModule extends LifecycleModule {
ShutdownManagerImpl.class).in(Singleton.class); ShutdownManagerImpl.class).in(Singleton.class);
} }
} }
*/
} }

View File

@@ -1,7 +1,5 @@
package org.briarproject.plugins; package org.briarproject.plugins;
import com.google.inject.Provides;
import org.briarproject.api.lifecycle.IoExecutor; import org.briarproject.api.lifecycle.IoExecutor;
import org.briarproject.api.lifecycle.ShutdownManager; import org.briarproject.api.lifecycle.ShutdownManager;
import org.briarproject.api.plugins.BackoffFactory; import org.briarproject.api.plugins.BackoffFactory;
@@ -22,6 +20,10 @@ import java.util.Collection;
import java.util.Collections; import java.util.Collections;
import java.util.concurrent.Executor; import java.util.concurrent.Executor;
import dagger.Module;
import dagger.Provides;
@Module
public class DesktopPluginsModule extends PluginsModule { public class DesktopPluginsModule extends PluginsModule {
@Provides @Provides

View File

@@ -1,18 +1,19 @@
package org.briarproject.system; package org.briarproject.system;
import com.google.inject.AbstractModule;
import org.briarproject.api.system.Clock; import org.briarproject.api.system.Clock;
import org.briarproject.api.system.SeedProvider; import org.briarproject.api.system.SeedProvider;
import org.briarproject.api.system.Timer; import org.briarproject.api.system.Timer;
import org.briarproject.util.OsUtils; import org.briarproject.util.OsUtils;
public class DesktopSystemModule extends AbstractModule { public class DesktopSystemModule {
/*
// TODO
protected void configure() { protected void configure() {
bind(Clock.class).to(SystemClock.class); bind(Clock.class).to(SystemClock.class);
bind(Timer.class).to(SystemTimer.class); bind(Timer.class).to(SystemTimer.class);
if (OsUtils.isLinux()) if (OsUtils.isLinux())
bind(SeedProvider.class).to(LinuxSeedProvider.class); bind(SeedProvider.class).to(LinuxSeedProvider.class);
} }
*/
} }

View File

@@ -13,7 +13,6 @@ dependencies {
compile project(':briar-core') compile project(':briar-core')
compile fileTree(dir: '../briar-desktop/libs', include: '*.jar') compile fileTree(dir: '../briar-desktop/libs', include: '*.jar')
compile project(':briar-desktop') compile project(':briar-desktop')
compile "junit:junit:4.12" compile "junit:junit:4.12"
compile "org.jmock:jmock:2.8.1" compile "org.jmock:jmock:2.8.1"
compile "org.hamcrest:hamcrest-library:1.3" compile "org.hamcrest:hamcrest-library:1.3"

View File

@@ -1,12 +1,14 @@
package org.briarproject; package org.briarproject;
import com.google.inject.AbstractModule;
import org.briarproject.api.db.DatabaseConfig; import org.briarproject.api.db.DatabaseConfig;
import java.io.File; import java.io.File;
public class TestDatabaseModule extends AbstractModule { import dagger.Module;
import dagger.Provides;
@Module
public class TestDatabaseModule {
private final DatabaseConfig config; private final DatabaseConfig config;
@@ -22,7 +24,9 @@ public class TestDatabaseModule extends AbstractModule {
this.config = new TestDatabaseConfig(dir, maxSize); this.config = new TestDatabaseConfig(dir, maxSize);
} }
protected void configure() { @Provides
bind(DatabaseConfig.class).toInstance(config); DatabaseConfig provideDatabaseConfig() {
return config;
} }
} }

View File

@@ -1,7 +1,5 @@
package org.briarproject; package org.briarproject;
import com.google.inject.AbstractModule;
import org.briarproject.api.lifecycle.IoExecutor; import org.briarproject.api.lifecycle.IoExecutor;
import org.briarproject.api.lifecycle.LifecycleManager; import org.briarproject.api.lifecycle.LifecycleManager;
import org.briarproject.api.lifecycle.Service; import org.briarproject.api.lifecycle.Service;
@@ -11,37 +9,70 @@ import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService; import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors; import java.util.concurrent.Executors;
public class TestLifecycleModule extends AbstractModule { import dagger.Module;
import dagger.Provides;
@Override @Module
protected void configure() { public class TestLifecycleModule {
bind(LifecycleManager.class).toInstance(new LifecycleManager() {
public void register(Service s) {} @Provides
LifecycleManager provideLifecycleManager() {
return new LifecycleManager() {
@Override
public void register(Service s) {
public void registerForShutdown(ExecutorService e) {} }
public StartResult startServices() { return StartResult.SUCCESS; } @Override
public void registerForShutdown(ExecutorService e) {
public void stopServices() {} }
public void waitForDatabase() throws InterruptedException {} @Override
public StartResult startServices() {
return StartResult.SUCCESS;
}
public void waitForStartup() throws InterruptedException {} @Override
public void stopServices() {
public void waitForShutdown() throws InterruptedException {} }
});
bind(ShutdownManager.class).toInstance(new ShutdownManager() {
@Override
public void waitForDatabase() throws InterruptedException {
}
@Override
public void waitForStartup() throws InterruptedException {
}
@Override
public void waitForShutdown() throws InterruptedException {
}
};
}
ShutdownManager provideShutdownManager() {
return new ShutdownManager() {
@Override
public int addShutdownHook(Runnable hook) { public int addShutdownHook(Runnable hook) {
return 0; return 0;
} }
@Override
public boolean removeShutdownHook(int handle) { public boolean removeShutdownHook(int handle) {
return true; return true;
} }
}); };
bind(Executor.class).annotatedWith(IoExecutor.class).toInstance(
Executors.newCachedThreadPool());
} }
@Provides
@IoExecutor
Executor provideExecutor() {
return Executors.newCachedThreadPool();
}
} }

View File

@@ -1,18 +1,29 @@
package org.briarproject; package org.briarproject;
import com.google.inject.AbstractModule;
import org.briarproject.api.system.Clock; import org.briarproject.api.system.Clock;
import org.briarproject.api.system.SeedProvider; import org.briarproject.api.system.SeedProvider;
import org.briarproject.api.system.Timer; import org.briarproject.api.system.Timer;
import org.briarproject.system.SystemClock; import org.briarproject.system.SystemClock;
import org.briarproject.system.SystemTimer; import org.briarproject.system.SystemTimer;
public class TestSystemModule extends AbstractModule { import dagger.Module;
import dagger.Provides;
protected void configure() { @Module
bind(Clock.class).to(SystemClock.class); public class TestSystemModule {
bind(Timer.class).to(SystemTimer.class);
bind(SeedProvider.class).to(TestSeedProvider.class); @Provides
Clock provideClock() {
return new SystemClock();
}
@Provides
Timer provideSystemTimer() {
return new SystemTimer();
}
@Provides
SeedProvider provideSeedProvider() {
return new TestSeedProvider();
} }
} }

View File

@@ -2,9 +2,13 @@
buildscript { buildscript {
repositories { repositories {
mavenCentral() mavenCentral()
maven {
url "https://plugins.gradle.org/m2/"
}
} }
dependencies { dependencies {
classpath 'com.android.tools.build:gradle:1.5.0' classpath 'com.android.tools.build:gradle:1.5.0'
classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'
classpath files('briar-core/libs/gradle-witness.jar') classpath files('briar-core/libs/gradle-witness.jar')
} }
} }

View File

@@ -1,4 +1,4 @@
include ':briar-api' include ':briar-api', ':briar-android-tests'
include ':briar-core' include ':briar-core'
include ':briar-desktop' include ':briar-desktop'
include ':briar-tests' include ':briar-tests'