Split Client#onlineInit method up into performHandshake and initReceiver

This commit is contained in:
Kai S. K. Engelbart 2020-02-12 07:53:24 +01:00
parent 511146c98e
commit 9498bf216d
3 changed files with 42 additions and 11 deletions

View File

@ -28,7 +28,7 @@
<dependency> <dependency>
<groupId>com.github.informatik-ag-ngl</groupId> <groupId>com.github.informatik-ag-ngl</groupId>
<artifactId>envoy-common</artifactId> <artifactId>envoy-common</artifactId>
<version>develop-SNAPSHOT</version> <version>f~advanced_login-SNAPSHOT</version>
</dependency> </dependency>
</dependencies> </dependencies>

View File

@ -42,6 +42,7 @@ public class Client implements Closeable {
// Asynchronously initialized during handshake // Asynchronously initialized during handshake
private volatile User sender; private volatile User sender;
private volatile Contacts contacts; private volatile Contacts contacts;
private volatile boolean rejected;
// Configuration and logging // Configuration and logging
private static final Config config = Config.getInstance(); private static final Config config = Config.getInstance();
@ -54,16 +55,19 @@ public class Client implements Closeable {
* an exception is thrown. * an exception is thrown.
* *
* @param credentials the login credentials of the user * @param credentials the login credentials of the user
* @param localDb the local database used to persist the current
* {@link IdGenerator}
* @param receivedMessageCache a message cache containing all unread messages * @param receivedMessageCache a message cache containing all unread messages
* from the server that can be relayed after * from the server that can be relayed after
* initialization * initialization
* @throws Exception if the online mode could not be entered or the request * @throws TimeLimitExceededException if the server could not be reached
* failed for some other reason * @throws IOException if the login credentials could not be
* @since Envoy v0.2-alpha * written
* @throws InterruptedException if the current thread is interrupted while
* waiting for the handshake response
*/ */
public void onlineInit(LoginCredentials credentials, LocalDb localDb, Cache<Message> receivedMessageCache) throws Exception { public void performHandshake(LoginCredentials credentials, Cache<Message> receivedMessageCache)
throws TimeLimitExceededException, IOException, InterruptedException {
if (online) throw new IllegalStateException("Handshake has already been performed successfully");
// Establish TCP connection // Establish TCP connection
logger.info(String.format("Attempting connection to server %s:%d...", config.getServer(), config.getPort())); logger.info(String.format("Attempting connection to server %s:%d...", config.getServer(), config.getPort()));
socket = new Socket(config.getServer(), config.getPort()); socket = new Socket(config.getServer(), config.getPort());
@ -76,7 +80,9 @@ public class Client implements Closeable {
receiver.registerProcessor(User.class, sender -> { logger.info("Acquired user object " + sender); this.sender = sender; }); receiver.registerProcessor(User.class, sender -> { logger.info("Acquired user object " + sender); this.sender = sender; });
receiver.registerProcessor(Contacts.class, contacts -> { logger.info("Acquired contacts object " + contacts); this.contacts = contacts; }); receiver.registerProcessor(Contacts.class, contacts -> { logger.info("Acquired contacts object " + contacts); this.contacts = contacts; });
receiver.registerProcessor(Message.class, receivedMessageCache); receiver.registerProcessor(Message.class, receivedMessageCache);
receiver.registerProcessor(HandshakeRejectionEvent.class, EventBus.getInstance()::dispatch); receiver.registerProcessor(HandshakeRejectionEvent.class, evt -> { rejected = true; EventBus.getInstance().dispatch(evt); });
rejected = false;
// Start receiver // Start receiver
new Thread(receiver).start(); new Thread(receiver).start();
@ -88,6 +94,15 @@ public class Client implements Closeable {
// Wait for a maximum of five seconds to acquire the sender object // Wait for a maximum of five seconds to acquire the sender object
long start = System.currentTimeMillis(); long start = System.currentTimeMillis();
while (sender == null || contacts == null) { while (sender == null || contacts == null) {
// Quit immediately after handshake rejection
// This method can then be called again
if (rejected) {
socket.close();
receiver.removeAllProcessors();
return;
}
if (System.currentTimeMillis() - start > 5000) throw new TimeLimitExceededException("Did not log in after 5 seconds"); if (System.currentTimeMillis() - start > 5000) throw new TimeLimitExceededException("Did not log in after 5 seconds");
Thread.sleep(500); Thread.sleep(500);
} }
@ -97,8 +112,23 @@ public class Client implements Closeable {
// Remove user creation processor // Remove user creation processor
receiver.removeAllProcessors(); receiver.removeAllProcessors();
}
// Register processors for message and status handling /**
* Initializes the {@link Receiver} used to process data sent from the server to
* this client.
*
* @param localDb the local database used to persist the current
* {@link IdGenerator}
* @param receivedMessageCache a message cache containing all unread messages
* from the server that can be relayed after
* initialization
* @throws IOException if no {@link IdGenerator} is present and none could be
* requested from the server
* @since Envoy v0.2-alpha
*/
public void initReceiver(LocalDb localDb, Cache<Message> receivedMessageCache) throws IOException {
checkOnline();
// Process incoming messages // Process incoming messages
final ReceivedMessageProcessor receivedMessageProcessor = new ReceivedMessageProcessor(); final ReceivedMessageProcessor receivedMessageProcessor = new ReceivedMessageProcessor();

View File

@ -62,7 +62,7 @@ public class Startup {
if (args.length > 0) config.load(args); if (args.length > 0) config.load(args);
// Check if all mandatory configuration values have been initialized // Check if all mandatory configuration values have been initialized
if (!config.isInitialized()) throw new EnvoyException("Server or port are not defined"); if (!config.isInitialized()) throw new EnvoyException("Configuration is not fully initialized");
} catch (Exception e) { } catch (Exception e) {
JOptionPane JOptionPane
.showMessageDialog(null, "Error loading configuration values:\n" + e.toString(), "Configuration error", JOptionPane.ERROR_MESSAGE); .showMessageDialog(null, "Error loading configuration values:\n" + e.toString(), "Configuration error", JOptionPane.ERROR_MESSAGE);
@ -109,7 +109,8 @@ public class Startup {
try { try {
// Try entering online mode first // Try entering online mode first
localDb.loadIdGenerator(); localDb.loadIdGenerator();
client.onlineInit(credentials, localDb, cache); client.performHandshake(credentials, cache);
client.initReceiver(localDb, cache);
} catch (Exception e1) { } catch (Exception e1) {
logger.warning("Could not connect to server. Trying offline mode..."); logger.warning("Could not connect to server. Trying offline mode...");
e1.printStackTrace(); e1.printStackTrace();