Merge pull request #14 from informatik-ag-ngl/f/contacts

Finished handshake implementation
This commit is contained in:
Kai S. K. Engelbart 2020-01-29 17:10:42 +01:00 committed by GitHub
commit f8fba0d48c
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
13 changed files with 321 additions and 128 deletions

View File

@ -1,39 +1,32 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="src" output="target/classes" path="src/main/java">
<attributes>
<attribute name="optional" value="true"/>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="src" output="target/test-classes" path="src/test/java">
<attributes>
<attribute name="optional" value="true"/>
<attribute name="maven.pomderived" value="true"/>
<attribute name="test" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.8">
<attributes>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="con" path="org.eclipse.m2e.MAVEN2_CLASSPATH_CONTAINER">
<attributes>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="src" path="/envoy-common"/>
<classpathentry excluding="**" kind="src" output="target/classes" path="src/main/resources">
<attributes>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry excluding="**" kind="src" output="target/test-classes" path="src/test/resources">
<attributes>
<attribute name="maven.pomderived" value="true"/>
<attribute name="test" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="output" path="target/classes"/>
</classpath>
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.8">
<attributes>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="con" path="org.eclipse.m2e.MAVEN2_CLASSPATH_CONTAINER">
<attributes>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry excluding="**" kind="src" output="target/classes" path="src/main/resources">
<attributes>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="src" output="target/classes" path="src/main/java">
<attributes>
<attribute name="optional" value="true"/>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="src" output="target/test-classes" path="src/test/java">
<attributes>
<attribute name="optional" value="true"/>
<attribute name="maven.pomderived" value="true"/>
<attribute name="test" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="output" path="target/classes"/>
</classpath>

View File

@ -28,7 +28,7 @@
<dependency>
<groupId>com.github.informatik-ag-ngl</groupId>
<artifactId>envoy-common</artifactId>
<version>develop-SNAPSHOT</version><!-- <version>0.2-alpha</version> -->
<version>develop-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>com.github.informatik-ag-ngl</groupId>
@ -49,5 +49,10 @@
<build>
<finalName>envoy-server-standalone</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
</resource>
</resources>
</build>
</project>

View File

@ -60,7 +60,7 @@ public class ConnectionManager implements ISocketIdListener {
*/
public void registerUser(long userId, long socketId) {
sockets.put(userId, socketId);
pendingSockets.remove(userId);
pendingSockets.remove(socketId);
}
/**

View File

@ -6,11 +6,11 @@ import java.util.Set;
import com.jenkov.nioserver.Server;
import envoy.server.data.ConfigItem;
import envoy.server.database.PersistenceManager;
import envoy.server.net.ObjectMessageProcessor;
import envoy.server.net.ObjectMessageReader;
import envoy.server.processors.EventProcessor;
import envoy.server.processors.LoginCredentialProcessor;
import envoy.server.processors.MessageProcessor;
import envoy.server.processors.*;
/**
* Starts the server.<br>
@ -36,9 +36,17 @@ public class Startup {
processors.add(new LoginCredentialProcessor());
processors.add(new MessageProcessor());
processors.add(new EventProcessor());
// new PersistenceManager();
processors.add(new IdGeneratorRequestProcessor());
Server server = new Server(8080, () -> new ObjectMessageReader(), new ObjectMessageProcessor(processors));
initializeCurrentMessageId();
server.start();
server.getSocketProcessor().registerSocketIdListener(ConnectionManager.getInstance());
}
private static void initializeCurrentMessageId() {
PersistenceManager persMan = PersistenceManager.getPersistenceManager();
if (persMan.getConfigItemById("currentMessageId") == null) persMan.addConfigItem(new ConfigItem("currentMessageId", "0"));
}
}

View File

@ -0,0 +1,65 @@
package envoy.server.data;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
/**
* Project: <strong>envoy-server-standalone</strong><br>
* File: <strong>ConfigItem.java</strong><br>
* Created: <strong>28 Jan 2020</strong><br>
*
* @author Kai S. K. Engelbart
* @since Envoy Server Standalone v0.1-alpha
*/
@Entity
@Table(name = "configuration")
public class ConfigItem {
@Id
private String key;
private String value;
/**
* Creates an instance of @link{ConfigItem}.
*
* @since Envoy Server Standalone v0.1-alpha
*/
public ConfigItem() {}
/**
* Creates an instance of @link{ConfigItem}.
*
* @param key
* @param value
* @since Envoy Server Standalone v0.1-alpha
*/
public ConfigItem(String key, String value) {
this.key = key;
this.value = value;
}
/**
* @return the key
* @since Envoy Server Standalone v0.1-alpha
*/
public String getKey() { return key; }
/**
* @param key the key to set
* @since Envoy Server Standalone v0.1-alpha
*/
public void setKey(String key) { this.key = key; }
/**
* @return the value
* @since Envoy Server Standalone v0.1-alpha
*/
public String getValue() { return value; }
/**
* @param value the value to set
* @since Envoy Server Standalone v0.1-alpha
*/
public void setValue(String value) { this.value = value; }
}

View File

@ -2,14 +2,7 @@ package envoy.server.data;
import java.util.Date;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.*;
import envoy.data.MessageBuilder;
import envoy.server.database.PersistenceManager;
@ -33,20 +26,17 @@ import envoy.server.database.PersistenceManager;
{ @NamedQuery(
query = "SELECT m FROM Message m WHERE m.recipient =:recipient AND m.status = envoy.data.Message$MessageStatus.SENT",
name = "getUnreadMessages"
), @NamedQuery(
query = "SELECT m FROM Message m WHERE m.sender =:sender AND m.status = :status",
name = "find read messages"// TODO do we need this namedQuery?
), @NamedQuery(query = "SELECT m FROM Message m WHERE m.id = :messageId", name = "getMessageById") }
) }
)
public class Message {
@Id
private long id;
@ManyToOne
@ManyToOne(cascade = { CascadeType.PERSIST })
private User sender;
@ManyToOne
@ManyToOne(cascade = { CascadeType.PERSIST })
private User recipient;
@Temporal(TemporalType.TIMESTAMP)
@ -93,7 +83,7 @@ public class Message {
*/
public envoy.data.Message toCommonMessage() {
// TODO: Attachment, dates
return new MessageBuilder(sender.getId(), recipient.getId()).setText(text).setDate(creationDate).setStatus(status).build();
return new MessageBuilder(sender.getId(), recipient.getId(), id).setText(text).setDate(creationDate).setStatus(status).build();
}
/**

View File

@ -3,15 +3,7 @@ package envoy.server.data;
import java.util.Date;
import java.util.List;
import javax.persistence.ElementCollection;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.*;
/**
* This class serves as a way to let Hibernate communicate with the server
@ -28,7 +20,11 @@ import javax.persistence.TemporalType;
*/
@Entity
@Table(name = "users")
@NamedQuery(query = "SELECT u FROM User u WHERE u.id = :id", name = "getUserById")
@NamedQueries(
{ @NamedQuery(query = "SELECT u FROM User u WHERE u.name = :name", name = "getUserByName"),
@NamedQuery(query = "SELECT u.contacts FROM User u WHERE u = :user", name = "getContactsOfUser")// not tested
}
)
public class User {
@Id
@ -41,7 +37,7 @@ public class User {
private Date lastSeen;
private envoy.data.User.UserStatus status;
@ElementCollection
@OneToMany(targetEntity = User.class, cascade = CascadeType.ALL, orphanRemoval = true)
private List<User> contacts;
/**
@ -68,7 +64,7 @@ public class User {
* @return a database {@link User} converted into an {@link envoy.data.User}
* @since Envoy Server Standalone v0.1-alpha
*/
public envoy.data.User toCommonUser() { return new envoy.data.User(this.id, this.name); }
public envoy.data.User toCommonUser() { return new envoy.data.User(id, name); }
/**
* @return the id of a {link envoy.data.User}

View File

@ -5,8 +5,7 @@ import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Persistence;
import org.hibernate.Session;
import envoy.server.data.ConfigItem;
import envoy.server.data.Message;
import envoy.server.data.User;
@ -43,7 +42,11 @@ public class PersistenceManager {
* @param User the {@link User} to add to the database
* @since Envoy Server Standalone v0.1-alpha
*/
public void addUser(User User) { entityManager.persist(User); }
public void addUser(User User) {
entityManager.getTransaction().begin();
entityManager.persist(User);
entityManager.getTransaction().commit();
}
/**
* Adds a {@link Message} to the database.
@ -51,7 +54,23 @@ public class PersistenceManager {
* @param message the {@link Message} to add to the database
* @since Envoy Server Standalone v0.1-alpha
*/
public void addMessage(Message message) { entityManager.persist(message); }
public void addMessage(Message message) {
entityManager.getTransaction().begin();
entityManager.persist(message);
entityManager.getTransaction().commit();
}
/**
* Adds a {@link ConfigItem} to the database.
*
* @param configItem the {@link ConfigItem} to add to the database
* @since Envoy Server Standalone v0.1-alpha
*/
public void addConfigItem(ConfigItem configItem) {
entityManager.getTransaction().begin();
entityManager.persist(configItem);
entityManager.getTransaction().commit();
}
/**
* Updates a {@link User} in the database
@ -59,7 +78,11 @@ public class PersistenceManager {
* @param user the {@link User} to add to the database
* @since Envoy Server Standalone v0.1-alpha
*/
public void updateUser(User user) { entityManager.unwrap(Session.class).merge(user); }
public void updateUser(User user) {
entityManager.getTransaction().begin();
entityManager.merge(user);
entityManager.getTransaction().commit();
}
/**
* Updates a {@link Message} in the database.
@ -67,27 +90,54 @@ public class PersistenceManager {
* @param message the message to update
* @since Envoy Server Standalone v0.1-alpha
*/
public void updateMessage(Message message) { entityManager.unwrap(Session.class).merge(message); }
public void updateMessage(Message message) {
entityManager.getTransaction().begin();
entityManager.merge(message);
entityManager.getTransaction().commit();
}
/**
* Updates a {@link ConfigItem} in the database.
*
* @param configItem the configItem to update
* @since Envoy Server Standalone v0.1-alpha
*/
public void updateConfigItem(ConfigItem configItem) {
entityManager.getTransaction().begin();
entityManager.merge(configItem);
entityManager.getTransaction().commit();
}
/**
* Searches for a {@link User} with a specific id.
*
* @param id - the id to search for
* @param id the id to search for
* @return the user with the specified id
* @since Envoy Server Standalone v0.1-alpha
*/
public User getUserById(long id) { return (User) entityManager.createNamedQuery("getUserById").setParameter("id", id).getSingleResult(); }
public User getUserById(long id) { return entityManager.find(User.class, id); }
/**
* Searched for a {@link User} with a specific name.
*
* @param name the name of the user
* @return the user with the specified name
* @since Envoy Server Standalone v0.1-alpha
*/
public User getUserByName(String name) {
return (User) entityManager.createNamedQuery("getUserByName").setParameter("name", name).getSingleResult();
}
/**
* Searches for a {@link Message} with a specific id.
*
* @param id - the id to search for
* @param id the id to search for
* @return the message with the specified id
* @since Envoy Server Standalone v0.1-alpha
*/
public Message getMessageById(long id) {
return (Message) entityManager.createNamedQuery("getMessageById").setParameter("id", id).getSingleResult();
}
public Message getMessageById(long id) { return entityManager.find(Message.class, id); }
public ConfigItem getConfigItemById(String key) { return entityManager.find(ConfigItem.class, key); }
/**
* Returns all messages received while being offline.
@ -96,9 +146,17 @@ public class PersistenceManager {
* @return all messages that the client does not yet have (unread messages)
* @since Envoy Server Standalone v0.1-alpha
*/
@SuppressWarnings("unchecked")
public List<Message> getUnreadMessages(User user) {
// TODO may need to be changed to clientId
return entityManager.createNamedQuery("getUnreadMessages").setParameter("recipient", user).getResultList();
}
/**
* @param user the User whose contacts should be retrieved
* @return the contacts of this User - currently everyone using Envoy
* @since Envoy Server Standalone v0.1-alpha
*/
public List<User> getContacts(User user) { return entityManager.createQuery("FROM User").getResultList(); }
// TODO current solution gets all users, not just contacts. Should be changed to
// entityManager.createNamedQuery("getContactsOfUser").setParameter("user",
// user).getResultList();
}

View File

@ -5,7 +5,10 @@ import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
import com.jenkov.nioserver.*;
import com.jenkov.nioserver.IMessageReader;
import com.jenkov.nioserver.Message;
import com.jenkov.nioserver.MessageBuffer;
import com.jenkov.nioserver.Socket;
import envoy.util.SerializationUtils;
@ -45,18 +48,27 @@ public class ObjectMessageReader implements IMessageReader {
}
nextMessage.writeToMessage(buffer);
buffer.clear();
// Get message length
if (nextMessage.length - nextMessage.offset < 4) return;
if (nextMessage.length < 4) return;
int length = SerializationUtils.bytesToInt(nextMessage.sharedArray, nextMessage.offset) + 4;
do {
if (nextMessage.length - nextMessage.offset >= length) {
Message message = messageBuffer.getMessage();
message.writePartialMessageToMessage(nextMessage, nextMessage.offset + length);
completeMessages.add(nextMessage);
nextMessage = message;
}
// Separate first complete message
if (nextMessage.length >= length) {
Message message = messageBuffer.getMessage();
message.writePartialMessageToMessage(nextMessage, length);
message.length = nextMessage.length - length;
nextMessage.length = length;
completeMessages.add(nextMessage);
nextMessage = message;
}
buffer.clear();
// Get message length
if (nextMessage.length < 4) return;
length = SerializationUtils.bytesToInt(nextMessage.sharedArray, nextMessage.offset) + 4;
} while (nextMessage.length >= length);
}
}

View File

@ -20,9 +20,8 @@ import envoy.server.net.ObjectWriteProxy;
* @author Leon Hofmeister
* @since Envoy Server Standalone v0.1-alpha
*/
public class EventProcessor implements ObjectProcessor<Event<?>> {
private Event<?> event;
@SuppressWarnings("rawtypes")
public class EventProcessor implements ObjectProcessor<Event> {
/**
* Creates an instance of @link{EventProcessor}.
@ -31,15 +30,13 @@ public class EventProcessor implements ObjectProcessor<Event<?>> {
*/
public EventProcessor() {}
@SuppressWarnings("unchecked")
@Override
public Class<Event<?>> getInputClass() { return (Class<Event<?>>) event.getClass(); }
public Class<Event> getInputClass() { return Event.class; }
@Override
public void process(Event<?> input, long socketId, ObjectWriteProxy writeProxy) throws IOException {
event = input;
if (event instanceof MessageStatusChangeEvent) try {
applyMessageStatusChange((MessageStatusChangeEvent) event, writeProxy);
public void process(Event input, long socketId, ObjectWriteProxy writeProxy) throws IOException {
if (input instanceof MessageStatusChangeEvent) try {
applyMessageStatusChange((MessageStatusChangeEvent) input, writeProxy);
} catch (EnvoyException e) {
e.printStackTrace();
}
@ -49,7 +46,8 @@ public class EventProcessor implements ObjectProcessor<Event<?>> {
* Redirects messageStatus changes to the database and to the recipient of the
* {@link Message}.
*
* @param event the {@link MessageStatusChangeEvent} to adjust
* @param event the {@link MessageStatusChangeEvent} to adjust
* @param writeProxy allows sending objects to clients
* @throws EnvoyException if the {@link Message} has an invalid state
* @since Envoy Server Standalone v0.1-alpha
*/
@ -71,7 +69,5 @@ public class EventProcessor implements ObjectProcessor<Event<?>> {
e.printStackTrace();
}
perMan.updateMessage(msg);
}
}

View File

@ -0,0 +1,39 @@
package envoy.server.processors;
import java.io.IOException;
import envoy.data.IdGenerator;
import envoy.event.IdGeneratorRequest;
import envoy.server.ObjectProcessor;
import envoy.server.data.ConfigItem;
import envoy.server.database.PersistenceManager;
import envoy.server.net.ObjectWriteProxy;
/**
* Project: <strong>envoy-server-standalone</strong><br>
* File: <strong>IdGeneratorRequestProcessor.java</strong><br>
* Created: <strong>28 Jan 2020</strong><br>
*
* @author Kai S. K. Engelbart
* @since Envoy Server Standalone v0.1-alpha
*/
public class IdGeneratorRequestProcessor implements ObjectProcessor<IdGeneratorRequest> {
private static final long ID_RANGE = 2;
@Override
public Class<IdGeneratorRequest> getInputClass() { return IdGeneratorRequest.class; }
@Override
public void process(IdGeneratorRequest input, long socketId, ObjectWriteProxy writeProxy) throws IOException {
System.out.println("Received id generation request.");
ConfigItem currentId = PersistenceManager.getPersistenceManager().getConfigItemById("currentMessageId");
IdGenerator generator = new IdGenerator(Integer.parseInt(currentId.getValue()), ID_RANGE);
currentId.setValue(String.valueOf(Integer.parseInt(currentId.getValue()) + ID_RANGE));
PersistenceManager.getPersistenceManager().updateConfigItem(currentId);
System.out.println("Sending new id generator " + generator);
writeProxy.write(socketId, generator);
}
}

View File

@ -1,9 +1,10 @@
package envoy.server.processors;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
import envoy.data.Contacts;
import envoy.data.LoginCredentials;
@ -23,12 +24,12 @@ import envoy.server.net.ObjectWriteProxy;
* Created: <strong>30.12.2019</strong><br>
*
* @author Kai S. K. Engelbart
* @author Maximilian K&auml;fer
* @since Envoy Server Standalone v0.1-alpha
*/
public class LoginCredentialProcessor implements ObjectProcessor<LoginCredentials> {
// TODO: Acquire user IDs from database
private static long currentUserId = 1;
private PersistenceManager persistenceManager = PersistenceManager.getPersistenceManager();
@Override
public Class<LoginCredentials> getInputClass() { return LoginCredentials.class; }
@ -37,25 +38,57 @@ public class LoginCredentialProcessor implements ObjectProcessor<LoginCredential
public void process(LoginCredentials input, long socketId, ObjectWriteProxy writeProxy) throws IOException {
System.out.println(String.format("Received login credentials %s from socket ID %d", input, socketId));
// Create user
User user = new User(currentUserId++, input.getName());
ConnectionManager.getInstance().registerUser(socketId, user.getId());
envoy.server.data.User user = getUser(input);
// Not logged in successfully
if (user == null) {
return;
}
ConnectionManager.getInstance().registerUser(user.getId(), socketId);
// Create contacts
Contacts contacts = new Contacts(user.getId(), new ArrayList<>());
List<User> users = PersistenceManager.getPersistenceManager()
.getContacts(user)
.stream()
.map(envoy.server.data.User::toCommonUser)
.collect(Collectors.toList());
Contacts contacts = new Contacts(user.getId(), users);
// Complete handshake
System.out.println("Sending user...");
writeProxy.write(socketId, user);
writeProxy.write(socketId, user.toCommonUser());
System.out.println("Sending contacts...");
writeProxy.write(socketId, contacts);
System.out.println("Sending unread messages and updating them in the database...");
List<Message> pendingMessages = PersistenceManager.getPersistenceManager().getUnreadMessages(new envoy.server.data.User(user));
pendingMessages.forEach((msg) -> {
System.out.println("Acquiring pending messages for the client...");
List<Message> pendingMessages = PersistenceManager.getPersistenceManager().getUnreadMessages(user);
for (Message msg : pendingMessages) {
System.out.println("Sending message " + msg.toString());
writeProxy.write(socketId, msg);
msg.setReceivedDate(new Date());
msg.setStatus(MessageStatus.RECEIVED);
PersistenceManager.getPersistenceManager().updateMessage(msg);
});
writeProxy.write(socketId, pendingMessages);
}
}
private envoy.server.data.User getUser(LoginCredentials credentials) {
envoy.server.data.User user;
if (credentials.isRegistration()) {
user = new envoy.server.data.User();
user.setName(credentials.getName());
user.setLastSeen(new Date());
user.setStatus(User.UserStatus.ONLINE);
user.setPasswordHash(credentials.getPasswordHash());
persistenceManager.addUser(user);
} else {
user = persistenceManager.getUserByName(credentials.getName());
// TODO: Implement error when user does not exist
if (!Arrays.equals(credentials.getPasswordHash(), user.getPasswordHash())) {
// TODO: Wrong Password Response
return null;
}
}
return user;
}
}

View File

@ -4,7 +4,6 @@ import java.io.IOException;
import java.util.Date;
import envoy.data.Message;
import envoy.event.MessageStatusChangeEvent;
import envoy.server.ConnectionManager;
import envoy.server.ObjectProcessor;
import envoy.server.database.PersistenceManager;
@ -30,18 +29,17 @@ public class MessageProcessor implements ObjectProcessor<Message> {
ConnectionManager connectionManager = ConnectionManager.getInstance();
message.nextStatus();
if (connectionManager.isOnline(message.getRecipientId())) try {// if recipient is online, he receives the message directly
if (connectionManager.isOnline(message.getRecipientId())) try {
// If recipient is online, send the message directly
writeProxy.write(connectionManager.getSocketId(message.getRecipientId()), message);
// Update the message status to RECEIVED
message.setReceivedDate(new Date());
message.nextStatus();
} catch (IOException e) {
System.err.println("Recipient online. Failed to send message" + message.getId());
e.printStackTrace();
}
try {// sender receives confirmation that the server received the message
writeProxy.write(connectionManager.getSocketId(message.getSenderId()),
new MessageStatusChangeEvent(message.getId(), message.getStatus(), new Date()));
} catch (IOException e) {
e.printStackTrace();
}
PersistenceManager.getPersistenceManager().addMessage(new envoy.server.data.Message(message));
}
}