/
ConsumersResource.java
327 lines (288 loc) · 11 KB
/
ConsumersResource.java
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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
/*
* Copyright 2005-2014 Red Hat, Inc.
* Red Hat licenses this file to you under the Apache License, version
* 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package org.hornetq.rest.queue;
import javax.ws.rs.DELETE;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.HEAD;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriBuilder;
import javax.ws.rs.core.UriInfo;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;
import org.hornetq.api.core.HornetQException;
import org.hornetq.api.core.client.ClientSessionFactory;
import org.hornetq.rest.HornetQRestLogger;
import org.hornetq.rest.util.TimeoutTask;
/**
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $
*/
public class ConsumersResource implements TimeoutTask.Callback
{
protected ConcurrentHashMap<String, QueueConsumer> queueConsumers = new ConcurrentHashMap<String, QueueConsumer>();
protected ClientSessionFactory sessionFactory;
protected String destination;
protected final String startup = Long.toString(System.currentTimeMillis());
protected AtomicLong sessionCounter = new AtomicLong(1);
protected int consumerTimeoutSeconds;
protected DestinationServiceManager serviceManager;
protected static final int ACKNOWLEDGED = 0x01;
protected static final int SELECTOR_SET = 0x02;
public DestinationServiceManager getServiceManager()
{
return serviceManager;
}
public void setServiceManager(DestinationServiceManager serviceManager)
{
this.serviceManager = serviceManager;
}
public ClientSessionFactory getSessionFactory()
{
return sessionFactory;
}
public void setSessionFactory(ClientSessionFactory sessionFactory)
{
this.sessionFactory = sessionFactory;
}
public String getDestination()
{
return destination;
}
public void setDestination(String destination)
{
this.destination = destination;
}
public int getConsumerTimeoutSeconds()
{
return consumerTimeoutSeconds;
}
public void setConsumerTimeoutSeconds(int consumerTimeoutSeconds)
{
this.consumerTimeoutSeconds = consumerTimeoutSeconds;
}
public boolean testTimeout(String target, boolean autoShutdown)
{
QueueConsumer consumer = queueConsumers.get(target);
if (consumer == null) return false;
if (System.currentTimeMillis() - consumer.getLastPingTime() > consumerTimeoutSeconds * 1000)
{
HornetQRestLogger.LOGGER.shutdownRestConsumer(consumer.getId());
if (autoShutdown)
{
shutdown(consumer);
}
return true;
}
else
{
return false;
}
}
public void shutdown(String target)
{
QueueConsumer consumer = queueConsumers.get(target);
if (consumer == null) return;
shutdown(consumer);
}
private void shutdown(QueueConsumer consumer)
{
synchronized (consumer)
{
consumer.shutdown();
queueConsumers.remove(consumer.getId());
}
}
public void stop()
{
for (QueueConsumer consumer : queueConsumers.values())
{
consumer.shutdown();
}
}
@POST
public Response createSubscription(@FormParam("autoAck") @DefaultValue("true") boolean autoAck,
@FormParam("selector") String selector,
@Context UriInfo uriInfo)
{
HornetQRestLogger.LOGGER.debug("Handling POST request for \"" + uriInfo.getPath() + "\"");
try
{
QueueConsumer consumer = null;
int attributes = 0;
if (selector != null)
{
attributes = attributes | SELECTOR_SET;
}
if (autoAck)
{
consumer = createConsumer(selector);
}
else
{
attributes |= ACKNOWLEDGED;
consumer = createAcknowledgedConsumer(selector);
}
String attributesSegment = "attributes-" + attributes;
UriBuilder location = uriInfo.getAbsolutePathBuilder();
location.path(attributesSegment);
location.path(consumer.getId());
Response.ResponseBuilder builder = Response.created(location.build());
if (autoAck)
{
QueueConsumer.setConsumeNextLink(serviceManager.getLinkStrategy(), builder, uriInfo, uriInfo.getMatchedURIs().get(0) + "/" + attributesSegment + "/" + consumer.getId(), "-1");
}
else
{
AcknowledgedQueueConsumer.setAcknowledgeNextLink(serviceManager.getLinkStrategy(), builder, uriInfo, uriInfo.getMatchedURIs().get(0) + "/" + attributesSegment + "/" + consumer.getId(), "-1");
}
return builder.build();
}
catch (HornetQException e)
{
throw new RuntimeException(e);
}
finally
{
}
}
protected void addConsumer(QueueConsumer consumer)
{
queueConsumers.put(consumer.getId(), consumer);
serviceManager.getTimeoutTask().add(this, consumer.getId());
}
public QueueConsumer createConsumer(String selector) throws HornetQException
{
String genId = sessionCounter.getAndIncrement() + "-queue-" + destination + "-" + startup;
QueueConsumer consumer = new QueueConsumer(sessionFactory, destination, genId, serviceManager, selector);
addConsumer(consumer);
return consumer;
}
public QueueConsumer createAcknowledgedConsumer(String selector) throws HornetQException
{
String genId = sessionCounter.getAndIncrement() + "-queue-" + destination + "-" + startup;
QueueConsumer consumer = new AcknowledgedQueueConsumer(sessionFactory, destination, genId, serviceManager, selector);
addConsumer(consumer);
return consumer;
}
@Path("attributes-{attributes}/{consumer-id}")
@GET
public Response getConsumer(@PathParam("attributes") int attributes,
@PathParam("consumer-id") String consumerId,
@Context UriInfo uriInfo) throws Exception
{
HornetQRestLogger.LOGGER.debug("Handling GET request for \"" + uriInfo.getPath() + "\"");
return headConsumer(attributes, consumerId, uriInfo);
}
@Path("attributes-{attributes}/{consumer-id}")
@HEAD
public Response headConsumer(@PathParam("attributes") int attributes,
@PathParam("consumer-id") String consumerId,
@Context UriInfo uriInfo) throws Exception
{
HornetQRestLogger.LOGGER.debug("Handling HEAD request for \"" + uriInfo.getPath() + "\"");
QueueConsumer consumer = findConsumer(attributes, consumerId, uriInfo);
Response.ResponseBuilder builder = Response.noContent();
// we synchronize just in case a failed request is still processing
synchronized (consumer)
{
if ((attributes & ACKNOWLEDGED) > 0)
{
AcknowledgedQueueConsumer ackedConsumer = (AcknowledgedQueueConsumer) consumer;
Acknowledgement ack = ackedConsumer.getAck();
if (ack == null || ack.wasSet())
{
AcknowledgedQueueConsumer.setAcknowledgeNextLink(serviceManager.getLinkStrategy(), builder, uriInfo, uriInfo.getMatchedURIs().get(1) + "/attributes-" + attributes + "/" + consumer.getId(), Long.toString(consumer.getConsumeIndex()));
}
else
{
ackedConsumer.setAcknowledgementLink(builder, uriInfo, uriInfo.getMatchedURIs().get(1) + "/attributes-" + attributes + "/" + consumer.getId());
}
}
else
{
QueueConsumer.setConsumeNextLink(serviceManager.getLinkStrategy(), builder, uriInfo, uriInfo.getMatchedURIs().get(1) + "/attributes-" + attributes + "/" + consumer.getId(), Long.toString(consumer.getConsumeIndex()));
}
}
return builder.build();
}
@Path("attributes-{attributes}/{consumer-id}")
public QueueConsumer findConsumer(
@PathParam("attributes") int attributes,
@PathParam("consumer-id") String consumerId,
@Context UriInfo uriInfo) throws Exception
{
QueueConsumer consumer = queueConsumers.get(consumerId);
if (consumer == null)
{
if ((attributes & SELECTOR_SET) > 0)
{
Response.ResponseBuilder builder = Response.status(Response.Status.GONE)
.entity("Cannot reconnect to selector-based consumer. You must recreate the consumer session.")
.type("text/plain");
UriBuilder uriBuilder = uriInfo.getBaseUriBuilder();
uriBuilder.path(uriInfo.getMatchedURIs().get(1));
serviceManager.getLinkStrategy().setLinkHeader(builder, "pull-consumers", "pull-consumers", uriBuilder.build().toString(), null);
throw new WebApplicationException(builder.build());
}
if ((attributes & ACKNOWLEDGED) > 0)
{
QueueConsumer tmp = new AcknowledgedQueueConsumer(sessionFactory, destination, consumerId, serviceManager, null);
consumer = addReconnectedConsumerToMap(consumerId, tmp);
}
else
{
QueueConsumer tmp = new QueueConsumer(sessionFactory, destination, consumerId, serviceManager, null);
consumer = addReconnectedConsumerToMap(consumerId, tmp);
}
}
return consumer;
}
private QueueConsumer addReconnectedConsumerToMap(String consumerId, QueueConsumer tmp)
{
QueueConsumer consumer;
consumer = queueConsumers.putIfAbsent(consumerId, tmp);
if (consumer != null)
{
tmp.shutdown();
}
else
{
consumer = tmp;
serviceManager.getTimeoutTask().add(this, consumer.getId());
}
return consumer;
}
@Path("attributes-{attributes}/{consumer-id}")
@DELETE
public void closeSession(
@PathParam("consumer-id") String consumerId,
@Context UriInfo uriInfo)
{
HornetQRestLogger.LOGGER.debug("Handling DELETE request for \"" + uriInfo.getPath() + "\"");
QueueConsumer consumer = queueConsumers.remove(consumerId);
if (consumer == null)
{
throw new WebApplicationException(Response.status(Response.Status.NOT_FOUND)
.entity("Failed to match a consumer to URL" + consumerId)
.type("text/plain").build());
}
consumer.shutdown();
}
}