]> git.somenet.org - pub/jan/dst18.git/blob - ass3-messaging/src/main/java/dst/ass3/messaging/impl/RequestGateway.java
[3.2-java] der meh part. like srsly docker-java? -.-
[pub/jan/dst18.git] / ass3-messaging / src / main / java / dst / ass3 / messaging / impl / RequestGateway.java
1 package dst.ass3.messaging.impl;
2
3 import com.fasterxml.jackson.databind.ObjectMapper;
4 import com.rabbitmq.client.Channel;
5 import com.rabbitmq.client.Connection;
6 import com.rabbitmq.client.ConnectionFactory;
7 import com.rabbitmq.client.MessageProperties;
8 import dst.ass3.messaging.Constants;
9 import dst.ass3.messaging.IRequestGateway;
10 import dst.ass3.messaging.UploadRequest;
11
12 import java.io.IOException;
13 import java.util.concurrent.TimeoutException;
14
15 public class RequestGateway implements IRequestGateway {
16     Connection conn;
17     Channel channel;
18
19     public RequestGateway() {
20         ConnectionFactory factory = new ConnectionFactory();
21         factory.setHost(Constants.RMQ_HOST);
22         factory.setPort(Integer.parseInt(Constants.RMQ_PORT));
23         factory.setUsername(Constants.RMQ_USER);
24         factory.setPassword(Constants.RMQ_PASSWORD);
25
26         try {
27             conn = factory.newConnection();
28             channel = conn.createChannel();
29         } catch (IOException | TimeoutException e) {
30             throw new RuntimeException("Irrecoverable error", e); // Fail horribly
31         }
32     }
33
34     @Override
35     public void uploadRequest(UploadRequest request) {
36         String routingKey = null;
37         switch (request.getType()) {
38             case DOCUMENT:
39                 routingKey = Constants.QUEUE_DOCUMENT;
40                 break;
41             case QUIZ:
42                 routingKey = Constants.QUEUE_QUIZ;
43                 break;
44             case VIDEO:
45                 routingKey = Constants.QUEUE_VIDEO;
46                 break;
47         }
48
49         ObjectMapper mapper = new ObjectMapper();
50         try {
51             channel.basicPublish("", routingKey, false, false, MessageProperties.BASIC, mapper.writeValueAsBytes(request));
52         } catch (IOException e) {
53             e.printStackTrace(); // TODO: may be recoverable?
54         }
55     }
56
57     @Override
58     public void close() throws IOException {
59         try {
60             channel.close();
61         } catch (TimeoutException ignored) {
62         }
63         conn.close();
64     }
65 }