diff --git a/ass3-messaging/src/main/java/dst/ass3/messaging/impl/RequestGateway.java b/ass3-messaging/src/main/java/dst/ass3/messaging/impl/RequestGateway.java new file mode 100644 index 0000000..75471dd --- /dev/null +++ b/ass3-messaging/src/main/java/dst/ass3/messaging/impl/RequestGateway.java @@ -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(); + } +}