Implement RequestGateway (3.1.2)

This commit is contained in:
Tobias Eidelpes 2021-05-17 16:04:00 +02:00
parent 8cb4304abc
commit 6aab14cb71

View File

@ -0,0 +1,59 @@
package dst.ass3.messaging.impl;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import dst.ass3.messaging.Constants;
import dst.ass3.messaging.IRequestGateway;
import dst.ass3.messaging.Region;
import dst.ass3.messaging.TripRequest;
import java.io.IOException;
import java.util.concurrent.TimeoutException;
public class RequestGateway implements IRequestGateway {
Connection connection;
Channel channel;
@Override
public void submitRequest(TripRequest request) {
ConnectionFactory factory = new ConnectionFactory();
factory.setHost(Constants.RMQ_HOST);
factory.setUsername(Constants.RMQ_USER);
factory.setPassword(Constants.RMQ_PASSWORD);
try {
connection = factory.newConnection();
} catch (IOException | TimeoutException e) {
e.printStackTrace();
}
try {
channel = connection.createChannel();
ObjectMapper mapper = new ObjectMapper();
if (request.getRegion() == Region.AT_VIENNA)
channel.basicPublish(Constants.QUEUE_AT_VIENNA, Constants.ROUTING_KEY_AT_VIENNA, null, mapper.writeValueAsString(request).getBytes());
else if (request.getRegion() == Region.AT_LINZ)
channel.basicPublish(Constants.QUEUE_AT_LINZ, Constants.ROUTING_KEY_AT_LINZ, null, mapper.writeValueAsString(request).getBytes());
else if (request.getRegion() == Region.DE_BERLIN)
channel.basicPublish(Constants.QUEUE_DE_BERLIN, Constants.ROUTING_KEY_DE_BERLIN, null, mapper.writeValueAsString(request).getBytes());
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void close() throws IOException {
try {
if (channel != null)
channel.close();
} catch (TimeoutException e) {
e.printStackTrace();
}
if (connection != null)
connection.close();
}
}