forked from rabbitinaction/sourcecode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathServer.java
More file actions
102 lines (87 loc) · 2.43 KB
/
Server.java
File metadata and controls
102 lines (87 loc) · 2.43 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.QueueingConsumer;
import com.rabbitmq.client.QueueingConsumer.Delivery;
import com.rabbitmq.client.AMQP.BasicProperties;
import org.json.JSONObject;
public class Server
{
private Connection connection;
private Channel channel;
private QueueingConsumer consumer;
public Server Server(){
return this;
}
public Server init()
throws Exception {
ConnectionFactory factory = new ConnectionFactory();
factory.setUsername("rpc_user");
factory.setPassword("rpcme");
connection = factory.newConnection();
channel = connection.createChannel();
channel.exchangeDeclare("rpc", "direct");
channel.queueDeclare("ping", false, false, false, null);
channel.queueBind("ping", "rpc", "ping");
consumer = new QueueingConsumer(channel);
channel.basicConsume("ping", false, "ping", consumer);
System.out.println(
"Waiting for RPC calls..."
);
return this;
}
public void closeConnection() {
if (connection != null) {
try {
connection.close();
}
catch (Exception ignore) {}
}
}
public void serveRequests() {
while (true) {
try {
Delivery delivery = consumer.nextDelivery();
BasicProperties props = delivery.getProperties();
channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
System.out.println(
"Received API call...replying..."
);
channel.basicPublish(
"",
props.getReplyTo(),
null,
getResponse(delivery).getBytes("UTF-8")
);
} catch (Exception e){
System.out.println(e.toString());
}
}
}
private String getResponse(Delivery delivery) {
String response = null;
try {
String message = new String(delivery.getBody(), "UTF-8");
JSONObject jsonobject = new JSONObject(message);
response = "Pong!" + jsonobject.getString("time");
}
catch (Exception e){
System.out.println(e.toString());
response = "";
}
return response;
}
public static void main(String[] args) {
Server server = null;
try {
server = new Server();
server.init().serveRequests();
} catch(Exception e) {
e.printStackTrace();
} finally {
if(server != null) {
server.closeConnection();
}
}
}
}