This repository has been archived on 2021-12-05. You can view files and clone it, but cannot push or open issues or pull requests.
envoy/src/main/java/envoy/server/net/ObjectMessageProcessor.java

71 lines
2.3 KiB
Java

package envoy.server.net;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Set;
import com.jenkov.nioserver.IMessageProcessor;
import com.jenkov.nioserver.Message;
import com.jenkov.nioserver.WriteProxy;
import envoy.server.ObjectProcessor;
/**
* Handles incoming objects.<br>
* <br>
* Project: <strong>envoy-server-standalone</strong><br>
* File: <strong>ObjectMessageProcessor.java</strong><br>
* Created: <strong>28.12.2019</strong><br>
*
* @author Kai S. K. Engelbart
* @since Envoy Server Standalone v0.1-alpha
*/
public class ObjectMessageProcessor implements IMessageProcessor {
private final Set<ObjectProcessor<?, ?>> processors;
/**
* The constructor to set the {@link ObjectProcessor}s.
*
* @param processors the {@link ObjectProcessor} to set
* @since Envoy Server Standalone v0.1-alpha
*/
public ObjectMessageProcessor(Set<ObjectProcessor<?, ?>> processors) {
this.processors = processors;
}
@SuppressWarnings("unchecked")
@Override
public void process(Message message, WriteProxy writeProxy) {
try (ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(message.sharedArray, message.offset + 4, message.length - 4))) {
Object obj = in.readObject();
System.out.println("Read object: " + obj.toString());
// Process object
processors.stream().filter(p -> p.getInputClass().isInstance(obj)).forEach((@SuppressWarnings("rawtypes") ObjectProcessor p) -> {
Object responseObj = p.process(p.getInputClass().cast(obj), message.socketId);
if (responseObj != null) {
// Create message targeted at the client
Message response = writeProxy.getMessage();
response.socketId = message.socketId;
// Serialize object to byte array
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try (ObjectOutputStream oout = new ObjectOutputStream(baos)) {
oout.writeObject(responseObj);
} catch (IOException e) {
e.printStackTrace();
}
byte[] objBytes = baos.toByteArray();
response.writeToMessage(objBytes);
writeProxy.enqueue(response);
}
});
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
}