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

View File

@@ -1,162 +0,0 @@
package org.briarproject;
import com.google.inject.Guice;
import com.google.inject.Injector;
import org.briarproject.api.TransportId;
import org.briarproject.api.contact.ContactId;
import org.briarproject.api.crypto.SecretKey;
import org.briarproject.api.sync.Ack;
import org.briarproject.api.sync.ClientId;
import org.briarproject.api.sync.Group;
import org.briarproject.api.sync.GroupFactory;
import org.briarproject.api.sync.Message;
import org.briarproject.api.sync.MessageFactory;
import org.briarproject.api.sync.MessageId;
import org.briarproject.api.sync.Offer;
import org.briarproject.api.sync.PacketReader;
import org.briarproject.api.sync.PacketReaderFactory;
import org.briarproject.api.sync.PacketWriter;
import org.briarproject.api.sync.PacketWriterFactory;
import org.briarproject.api.sync.Request;
import org.briarproject.api.transport.StreamContext;
import org.briarproject.api.transport.StreamReaderFactory;
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 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.transport.TransportConstants.TAG_LENGTH;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class ProtocolIntegrationTest extends BriarTestCase {
private final StreamReaderFactory streamReaderFactory;
private final StreamWriterFactory streamWriterFactory;
private final PacketReaderFactory packetReaderFactory;
private final PacketWriterFactory packetWriterFactory;
private final ContactId contactId;
private final TransportId transportId;
private final SecretKey tagKey, headerKey;
private final Message message, message1;
private final Collection<MessageId> messageIds;
public ProtocolIntegrationTest() throws Exception {
Injector i = Guice.createInjector(new TestDatabaseModule(),
new TestLifecycleModule(), new TestSystemModule(),
new CryptoModule(), new DatabaseModule(), new EventModule(),
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);
transportId = new TransportId("id");
// Create the transport keys
tagKey = TestUtils.createSecretKey();
headerKey = TestUtils.createSecretKey();
// Create a group
GroupFactory groupFactory = i.getInstance(GroupFactory.class);
ClientId clientId = new ClientId(TestUtils.getRandomId());
byte[] descriptor = new byte[MAX_GROUP_DESCRIPTOR_LENGTH];
Group group = groupFactory.createGroup(clientId, descriptor);
// Add two messages to the group
MessageFactory messageFactory = i.getInstance(MessageFactory.class);
long timestamp = System.currentTimeMillis();
String messageBody = "Hello world";
message = messageFactory.createMessage(group.getId(), timestamp,
messageBody.getBytes("UTF-8"));
message1 = messageFactory.createMessage(group.getId(), timestamp,
messageBody.getBytes("UTF-8"));
messageIds = Arrays.asList(message.getId(), message1.getId());
}
@Test
public void testWriteAndRead() throws Exception {
read(write());
}
private byte[] write() throws Exception {
ByteArrayOutputStream out = new ByteArrayOutputStream();
StreamContext ctx = new StreamContext(contactId, transportId, tagKey,
headerKey, 0);
OutputStream streamWriter =
streamWriterFactory.createStreamWriter(out, ctx);
PacketWriter packetWriter = packetWriterFactory.createPacketWriter(
streamWriter);
packetWriter.writeAck(new Ack(messageIds));
packetWriter.writeMessage(message.getRaw());
packetWriter.writeMessage(message1.getRaw());
packetWriter.writeOffer(new Offer(messageIds));
packetWriter.writeRequest(new Request(messageIds));
streamWriter.flush();
return out.toByteArray();
}
private void read(byte[] connectionData) throws Exception {
InputStream in = new ByteArrayInputStream(connectionData);
byte[] tag = new byte[TAG_LENGTH];
assertEquals(TAG_LENGTH, in.read(tag, 0, TAG_LENGTH));
// FIXME: Check that the expected tag was received
StreamContext ctx = new StreamContext(contactId, transportId, tagKey,
headerKey, 0);
InputStream streamReader =
streamReaderFactory.createStreamReader(in, ctx);
PacketReader packetReader = packetReaderFactory.createPacketReader(
streamReader);
// Read the ack
assertTrue(packetReader.hasAck());
Ack a = packetReader.readAck();
assertEquals(messageIds, a.getMessageIds());
// Read and verify the messages
assertTrue(packetReader.hasMessage());
Message m = packetReader.readMessage();
checkMessageEquality(message, m);
assertTrue(packetReader.hasMessage());
m = packetReader.readMessage();
checkMessageEquality(message1, m);
assertFalse(packetReader.hasMessage());
// Read the offer
assertTrue(packetReader.hasOffer());
Offer o = packetReader.readOffer();
assertEquals(messageIds, o.getMessageIds());
// Read the request
assertTrue(packetReader.hasRequest());
Request req = packetReader.readRequest();
assertEquals(messageIds, req.getMessageIds());
in.close();
}
private void checkMessageEquality(Message m1, Message m2) {
assertEquals(m1.getId(), m2.getId());
assertEquals(m1.getTimestamp(), m2.getTimestamp());
assertArrayEquals(m1.getRaw(), m2.getRaw());
}
}

View File

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

View File

@@ -1,7 +1,5 @@
package org.briarproject;
import com.google.inject.AbstractModule;
import org.briarproject.api.lifecycle.IoExecutor;
import org.briarproject.api.lifecycle.LifecycleManager;
import org.briarproject.api.lifecycle.Service;
@@ -11,37 +9,70 @@ import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class TestLifecycleModule extends AbstractModule {
import dagger.Module;
import dagger.Provides;
@Override
protected void configure() {
bind(LifecycleManager.class).toInstance(new LifecycleManager() {
@Module
public class TestLifecycleModule {
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) {
return 0;
}
@Override
public boolean removeShutdownHook(int handle) {
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;
import com.google.inject.AbstractModule;
import org.briarproject.api.system.Clock;
import org.briarproject.api.system.SeedProvider;
import org.briarproject.api.system.Timer;
import org.briarproject.system.SystemClock;
import org.briarproject.system.SystemTimer;
public class TestSystemModule extends AbstractModule {
import dagger.Module;
import dagger.Provides;
protected void configure() {
bind(Clock.class).to(SystemClock.class);
bind(Timer.class).to(SystemTimer.class);
bind(SeedProvider.class).to(TestSeedProvider.class);
@Module
public class TestSystemModule {
@Provides
Clock provideClock() {
return new SystemClock();
}
@Provides
Timer provideSystemTimer() {
return new SystemTimer();
}
@Provides
SeedProvider provideSeedProvider() {
return new TestSeedProvider();
}
}

View File

@@ -1,145 +0,0 @@
package org.briarproject.sync;
import com.google.inject.Guice;
import com.google.inject.Injector;
import org.briarproject.BriarTestCase;
import org.briarproject.TestDatabaseModule;
import org.briarproject.TestLifecycleModule;
import org.briarproject.TestSystemModule;
import org.briarproject.TestUtils;
import org.briarproject.api.UniqueId;
import org.briarproject.api.crypto.CryptoComponent;
import org.briarproject.api.crypto.KeyPair;
import org.briarproject.api.crypto.PrivateKey;
import org.briarproject.api.crypto.Signature;
import org.briarproject.api.forum.ForumConstants;
import org.briarproject.api.forum.ForumPost;
import org.briarproject.api.forum.ForumPostFactory;
import org.briarproject.api.identity.Author;
import org.briarproject.api.identity.AuthorFactory;
import org.briarproject.api.messaging.MessagingConstants;
import org.briarproject.api.messaging.PrivateMessage;
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.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_SIGNATURE_LENGTH;
import static org.briarproject.api.messaging.MessagingConstants.MAX_PRIVATE_MESSAGE_BODY_LENGTH;
import static org.briarproject.api.sync.SyncConstants.MAX_PACKET_PAYLOAD_LENGTH;
import static org.junit.Assert.assertTrue;
public class ConstantsTest extends BriarTestCase {
// TODO: Break this up into tests that are relevant for each package
private final CryptoComponent crypto;
private final AuthorFactory authorFactory;
private final PrivateMessageFactory privateMessageFactory;
private final ForumPostFactory forumPostFactory;
public ConstantsTest() throws Exception {
Injector i = Guice.createInjector(new TestDatabaseModule(),
new TestLifecycleModule(), new TestSystemModule(),
new ClientsModule(), new ContactModule(), new CryptoModule(),
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
public void testAgreementPublicKeys() throws Exception {
// Generate 10 agreement key pairs
for (int i = 0; i < 10; i++) {
KeyPair keyPair = crypto.generateSignatureKeyPair();
// Check the length of the public key
byte[] publicKey = keyPair.getPublic().getEncoded();
assertTrue(publicKey.length <= MAX_PUBLIC_KEY_LENGTH);
}
}
@Test
public void testSignaturePublicKeys() throws Exception {
Random random = new Random();
Signature sig = crypto.getSignature();
// Generate 10 signature key pairs
for (int i = 0; i < 10; i++) {
KeyPair keyPair = crypto.generateSignatureKeyPair();
// Check the length of the public key
byte[] publicKey = keyPair.getPublic().getEncoded();
assertTrue(publicKey.length <= MAX_PUBLIC_KEY_LENGTH);
// Sign some random data and check the length of the signature
byte[] toBeSigned = new byte[1234];
random.nextBytes(toBeSigned);
sig.initSign(keyPair.getPrivate());
sig.update(toBeSigned);
byte[] signature = sig.sign();
assertTrue(signature.length <= MAX_SIGNATURE_LENGTH);
}
}
@Test
public void testPrivateMessageFitsIntoPacket() throws Exception {
// Create a maximum-length private message
GroupId groupId = new GroupId(TestUtils.getRandomId());
long timestamp = Long.MAX_VALUE;
MessageId parent = new MessageId(TestUtils.getRandomId());
String contentType = TestUtils.createRandomString(
MessagingConstants.MAX_CONTENT_TYPE_LENGTH);
byte[] body = new byte[MAX_PRIVATE_MESSAGE_BODY_LENGTH];
PrivateMessage message = privateMessageFactory.createPrivateMessage(
groupId, timestamp, parent, contentType, body);
// Check the size of the serialised message
int length = message.getMessage().getRaw().length;
assertTrue(length > UniqueId.LENGTH + 8 + UniqueId.LENGTH
+ MessagingConstants.MAX_CONTENT_TYPE_LENGTH
+ MAX_PRIVATE_MESSAGE_BODY_LENGTH);
assertTrue(length <= MAX_PACKET_PAYLOAD_LENGTH);
}
@Test
public void testForumPostFitsIntoPacket() throws Exception {
// Create a maximum-length author
String authorName = TestUtils.createRandomString(
MAX_AUTHOR_NAME_LENGTH);
byte[] authorPublic = new byte[MAX_PUBLIC_KEY_LENGTH];
Author author = authorFactory.createAuthor(authorName, authorPublic);
// Create a maximum-length forum post
GroupId groupId = new GroupId(TestUtils.getRandomId());
long timestamp = Long.MAX_VALUE;
MessageId parent = new MessageId(TestUtils.getRandomId());
String contentType = TestUtils.createRandomString(
ForumConstants.MAX_CONTENT_TYPE_LENGTH);
byte[] body = new byte[MAX_FORUM_POST_BODY_LENGTH];
PrivateKey privateKey = crypto.generateSignatureKeyPair().getPrivate();
ForumPost post = forumPostFactory.createPseudonymousPost(groupId,
timestamp, parent, author, contentType, body, privateKey);
// Check the size of the serialised message
int length = post.getMessage().getRaw().length;
assertTrue(length > UniqueId.LENGTH + 8 + UniqueId.LENGTH
+ MAX_AUTHOR_NAME_LENGTH + MAX_PUBLIC_KEY_LENGTH
+ ForumConstants.MAX_CONTENT_TYPE_LENGTH
+ MAX_FORUM_POST_BODY_LENGTH);
assertTrue(length <= MAX_PACKET_PAYLOAD_LENGTH);
}
}

View File

@@ -1,255 +0,0 @@
package org.briarproject.sync;
import com.google.inject.Guice;
import com.google.inject.Injector;
import org.briarproject.BriarTestCase;
import org.briarproject.ImmediateExecutor;
import org.briarproject.TestDatabaseModule;
import org.briarproject.TestSystemModule;
import org.briarproject.TestUtils;
import org.briarproject.api.TransportId;
import org.briarproject.api.contact.ContactId;
import org.briarproject.api.contact.ContactManager;
import org.briarproject.api.crypto.SecretKey;
import org.briarproject.api.db.DatabaseComponent;
import org.briarproject.api.db.Transaction;
import org.briarproject.api.event.Event;
import org.briarproject.api.event.EventBus;
import org.briarproject.api.event.EventListener;
import org.briarproject.api.event.MessageAddedEvent;
import org.briarproject.api.identity.Author;
import org.briarproject.api.identity.AuthorId;
import org.briarproject.api.identity.IdentityManager;
import org.briarproject.api.identity.LocalAuthor;
import org.briarproject.api.lifecycle.LifecycleManager;
import org.briarproject.api.messaging.MessagingManager;
import org.briarproject.api.messaging.PrivateMessage;
import org.briarproject.api.messaging.PrivateMessageFactory;
import org.briarproject.api.sync.GroupId;
import org.briarproject.api.sync.PacketReader;
import org.briarproject.api.sync.PacketReaderFactory;
import org.briarproject.api.sync.PacketWriter;
import org.briarproject.api.sync.PacketWriterFactory;
import org.briarproject.api.sync.SyncSession;
import org.briarproject.api.transport.KeyManager;
import org.briarproject.api.transport.StreamContext;
import org.briarproject.api.transport.StreamReaderFactory;
import org.briarproject.api.transport.StreamWriterFactory;
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.identity.IdentityModule;
import org.briarproject.lifecycle.LifecycleModule;
import org.briarproject.messaging.MessagingModule;
import org.briarproject.transport.TransportModule;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.InputStream;
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 {
private static final int MAX_LATENCY = 2 * 60 * 1000; // 2 minutes
private final File testDir = TestUtils.getTestDirectory();
private final File aliceDir = new File(testDir, "alice");
private final File bobDir = new File(testDir, "bob");
private final TransportId transportId = new TransportId("id");
private final SecretKey master = TestUtils.createSecretKey();
private final long timestamp = System.currentTimeMillis();
private final AuthorId aliceId = new AuthorId(TestUtils.getRandomId());
private final AuthorId bobId = new AuthorId(TestUtils.getRandomId());
private Injector alice, bob;
@Before
public void setUp() {
assertTrue(testDir.mkdirs());
alice = createInjector(aliceDir);
bob = createInjector(bobDir);
}
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
public void testWriteAndRead() throws Exception {
read(write());
}
private byte[] write() throws Exception {
// Instantiate Alice's services
LifecycleManager lifecycleManager =
alice.getInstance(LifecycleManager.class);
DatabaseComponent db = alice.getInstance(DatabaseComponent.class);
IdentityManager identityManager =
alice.getInstance(IdentityManager.class);
ContactManager contactManager = alice.getInstance(ContactManager.class);
MessagingManager messagingManager =
alice.getInstance(MessagingManager.class);
KeyManager keyManager = alice.getInstance(KeyManager.class);
PrivateMessageFactory privateMessageFactory =
alice.getInstance(PrivateMessageFactory.class);
PacketWriterFactory packetWriterFactory =
alice.getInstance(PacketWriterFactory.class);
EventBus eventBus = alice.getInstance(EventBus.class);
StreamWriterFactory streamWriterFactory =
alice.getInstance(StreamWriterFactory.class);
// Start the lifecycle manager
lifecycleManager.startServices();
lifecycleManager.waitForStartup();
// Add a transport
Transaction txn = db.startTransaction();
try {
db.addTransport(txn, transportId, MAX_LATENCY);
txn.setComplete();
} finally {
db.endTransaction(txn);
}
// Add an identity for Alice
LocalAuthor aliceAuthor = new LocalAuthor(aliceId, "Alice",
new byte[MAX_PUBLIC_KEY_LENGTH], new byte[123], timestamp);
identityManager.addLocalAuthor(aliceAuthor);
// Add Bob as a contact
Author bobAuthor = new Author(bobId, "Bob",
new byte[MAX_PUBLIC_KEY_LENGTH]);
ContactId contactId = contactManager.addContact(bobAuthor, aliceId,
master, timestamp, true, true);
// Send Bob a message
GroupId groupId = messagingManager.getConversationId(contactId);
byte[] body = "Hi Bob!".getBytes("UTF-8");
PrivateMessage message = privateMessageFactory.createPrivateMessage(
groupId, timestamp, null, "text/plain", body);
messagingManager.addLocalMessage(message);
// Get a stream context
StreamContext ctx = keyManager.getStreamContext(contactId, transportId);
assertNotNull(ctx);
// Create a stream writer
ByteArrayOutputStream out = new ByteArrayOutputStream();
OutputStream streamWriter = streamWriterFactory.createStreamWriter(
out, ctx);
// Create an outgoing sync session
PacketWriter packetWriter = packetWriterFactory.createPacketWriter(
streamWriter);
SyncSession session = new SimplexOutgoingSession(db,
new ImmediateExecutor(), eventBus, contactId, transportId,
MAX_LATENCY, packetWriter);
// Write whatever needs to be written
session.run();
streamWriter.close();
// Clean up
lifecycleManager.stopServices();
lifecycleManager.waitForShutdown();
// Return the contents of the stream
return out.toByteArray();
}
private void read(byte[] stream) throws Exception {
// Instantiate Bob's services
LifecycleManager lifecycleManager =
bob.getInstance(LifecycleManager.class);
DatabaseComponent db = bob.getInstance(DatabaseComponent.class);
IdentityManager identityManager =
bob.getInstance(IdentityManager.class);
ContactManager contactManager = bob.getInstance(ContactManager.class);
KeyManager keyManager = bob.getInstance(KeyManager.class);
StreamReaderFactory streamReaderFactory =
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.getInstance(MessagingManager.class);
// Start the lifecyle manager
lifecycleManager.startServices();
lifecycleManager.waitForStartup();
// Add a transport
Transaction txn = db.startTransaction();
try {
db.addTransport(txn, transportId, MAX_LATENCY);
txn.setComplete();
} finally {
db.endTransaction(txn);
}
// Add an identity for Bob
LocalAuthor bobAuthor = new LocalAuthor(bobId, "Bob",
new byte[MAX_PUBLIC_KEY_LENGTH], new byte[123], timestamp);
identityManager.addLocalAuthor(bobAuthor);
// Add Alice as a contact
Author aliceAuthor = new Author(aliceId, "Alice",
new byte[MAX_PUBLIC_KEY_LENGTH]);
ContactId contactId = contactManager.addContact(aliceAuthor, bobId,
master, timestamp, false, true);
// Set up an event listener
MessageListener listener = new MessageListener();
bob.getInstance(EventBus.class).addListener(listener);
// Read and recognise the tag
ByteArrayInputStream in = new ByteArrayInputStream(stream);
byte[] tag = new byte[TAG_LENGTH];
int read = in.read(tag);
assertEquals(tag.length, read);
StreamContext ctx = keyManager.getStreamContext(transportId, tag);
assertNotNull(ctx);
// Create a stream reader
InputStream streamReader = streamReaderFactory.createStreamReader(
in, ctx);
// Create an incoming sync session
PacketReader packetReader = packetReaderFactory.createPacketReader(
streamReader);
SyncSession session = new IncomingSession(db, new ImmediateExecutor(),
eventBus, contactId, transportId, packetReader);
// No messages should have been added yet
assertFalse(listener.messageAdded);
// Read whatever needs to be read
session.run();
streamReader.close();
// The private message from Alice should have been added
assertTrue(listener.messageAdded);
// Clean up
lifecycleManager.stopServices();
lifecycleManager.waitForShutdown();
}
@After
public void tearDown() {
TestUtils.deleteTestDirectory(testDir);
}
private static class MessageListener implements EventListener {
private volatile boolean messageAdded = false;
public void eventOccurred(Event e) {
if (e instanceof MessageAddedEvent) messageAdded = true;
}
}
}