2 * ============LICENSE_START=======================================================
3 * Copyright (C) 2016-2018 Ericsson. All rights reserved.
4 * ================================================================================
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
9 * http://www.apache.org/licenses/LICENSE-2.0
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
17 * SPDX-License-Identifier: Apache-2.0
18 * ============LICENSE_END=========================================================
21 package org.onap.policy.apex.plugins.event.carrier.restrequestor;
24 import java.util.ArrayList;
25 import java.util.EnumMap;
26 import java.util.List;
28 import java.util.Map.Entry;
29 import java.util.concurrent.BlockingQueue;
30 import java.util.concurrent.ConcurrentHashMap;
31 import java.util.concurrent.LinkedBlockingQueue;
32 import java.util.concurrent.TimeUnit;
34 import javax.ws.rs.client.Client;
35 import javax.ws.rs.client.ClientBuilder;
36 import javax.ws.rs.client.Entity;
37 import javax.ws.rs.core.Response;
39 import org.onap.policy.apex.core.infrastructure.threading.ApplicationThreadFactory;
40 import org.onap.policy.apex.core.infrastructure.threading.ThreadUtilities;
41 import org.onap.policy.apex.plugins.event.carrier.restrequestor.RESTRequestorCarrierTechnologyParameters.HTTP_METHOD;
42 import org.onap.policy.apex.service.engine.event.ApexEventConsumer;
43 import org.onap.policy.apex.service.engine.event.ApexEventException;
44 import org.onap.policy.apex.service.engine.event.ApexEventReceiver;
45 import org.onap.policy.apex.service.engine.event.ApexEventRuntimeException;
46 import org.onap.policy.apex.service.engine.event.PeeredReference;
47 import org.onap.policy.apex.service.parameters.eventhandler.EventHandlerParameters;
48 import org.onap.policy.apex.service.parameters.eventhandler.EventHandlerPeeredMode;
49 import org.slf4j.Logger;
50 import org.slf4j.LoggerFactory;
53 * This class implements an Apex event consumer that issues a REST request and returns the REST response to APEX as an
56 * @author Liam Fallon (liam.fallon@ericsson.com)
58 public class ApexRestRequestorConsumer implements ApexEventConsumer, Runnable {
59 // Get a reference to the logger
60 private static final Logger LOGGER = LoggerFactory.getLogger(ApexRestRequestorConsumer.class);
62 // The amount of time to wait in milliseconds between checks that the consumer thread has stopped
63 private static final long REST_REQUESTOR_WAIT_SLEEP_TIME = 50;
65 // The REST parameters read from the parameter service
66 private RESTRequestorCarrierTechnologyParameters restConsumerProperties;
68 // The timeout for REST requests
69 private long restRequestTimeout = RESTRequestorCarrierTechnologyParameters.DEFAULT_REST_REQUEST_TIMEOUT;
71 // The event receiver that will receive events from this consumer
72 private ApexEventReceiver eventReceiver;
74 // The HTTP client that makes a REST call to get an input event for Apex
75 private Client client;
77 // The name for this consumer
78 private String name = null;
80 // The peer references for this event handler
81 private Map<EventHandlerPeeredMode, PeeredReference> peerReferenceMap = new EnumMap<>(EventHandlerPeeredMode.class);
83 // The consumer thread and stopping flag
84 private Thread consumerThread;
85 private boolean stopOrderedFlag = false;
87 // Temporary request holder for incoming REST requests
88 private final BlockingQueue<ApexRestRequest> incomingRestRequestQueue = new LinkedBlockingQueue<>();
90 // Map of ongoing REST request threads indexed by the time they started at
91 private final Map<ApexRestRequest, RestRequestRunner> ongoingRestRequestMap = new ConcurrentHashMap<>();
93 // The number of events received to date
94 private Object eventsReceivedLock = new Object();
95 private Integer eventsReceived = 0;
97 // The number of the next request runner thread
98 private static long nextRequestRunnerThreadNo = 0;
101 public void init(final String consumerName, final EventHandlerParameters consumerParameters,
102 final ApexEventReceiver incomingEventReceiver) throws ApexEventException {
103 this.eventReceiver = incomingEventReceiver;
104 this.name = consumerName;
106 // Check and get the REST Properties
107 if (!(consumerParameters
108 .getCarrierTechnologyParameters() instanceof RESTRequestorCarrierTechnologyParameters)) {
109 final String errorMessage =
110 "specified consumer properties are not applicable to REST Requestor consumer (" + this.name + ")";
111 LOGGER.warn(errorMessage);
112 throw new ApexEventException(errorMessage);
114 restConsumerProperties =
115 (RESTRequestorCarrierTechnologyParameters) consumerParameters.getCarrierTechnologyParameters();
117 // Check if we are in peered mode
118 if (!consumerParameters.isPeeredMode(EventHandlerPeeredMode.REQUESTOR)) {
119 final String errorMessage = "REST Requestor consumer (" + this.name
120 + ") must run in peered requestor mode with a REST Requestor producer";
121 LOGGER.warn(errorMessage);
122 throw new ApexEventException(errorMessage);
125 // Check if the HTTP method has been set
126 if (restConsumerProperties.getHttpMethod() == null) {
127 restConsumerProperties
128 .setHttpMethod(RESTRequestorCarrierTechnologyParameters.DEFAULT_REQUESTOR_HTTP_METHOD);
131 if (!(restConsumerProperties.getHttpMethod() instanceof HTTP_METHOD)) {
132 final String errorMessage = "specified HTTP method of \"" + restConsumerProperties.getHttpMethod()
133 + "\" is invalid, only HTTP methods " + HTTP_METHOD.values()
134 + " are valid on REST Requestor consumer (" + this.name + ")";
135 LOGGER.warn(errorMessage);
136 throw new ApexEventException(errorMessage);
139 // Check if the HTTP URL has been set
140 if (restConsumerProperties.getURL() == null) {
141 final String errorMessage = "no URL has been specified on REST Requestor consumer (" + this.name + ")";
142 LOGGER.warn(errorMessage);
143 throw new ApexEventException(errorMessage);
146 // Check if the HTTP URL is valid
148 new URL(restConsumerProperties.getURL());
149 } catch (final Exception e) {
150 final String errorMessage = "invalid URL has been specified on REST Requestor consumer (" + this.name + ")";
151 LOGGER.warn(errorMessage);
152 throw new ApexEventException(errorMessage, e);
155 // Set the peer timeout to the default value if its not set
156 if (consumerParameters.getPeerTimeout(EventHandlerPeeredMode.REQUESTOR) != 0) {
157 restRequestTimeout = consumerParameters.getPeerTimeout(EventHandlerPeeredMode.REQUESTOR);
160 // Initialize the HTTP client
161 client = ClientBuilder.newClient();
165 * Receive an incoming REST request from the peered REST Requestor producer and queue it
167 * @param restRequest the incoming rest request to queue
168 * @throws ApexEventRuntimeException on queueing errors
170 public void processRestRequest(final ApexRestRequest restRequest) {
171 // Push the event onto the queue for handling
173 incomingRestRequestQueue.add(restRequest);
174 } catch (final Exception e) {
175 final String errorMessage =
176 "could not queue request \"" + restRequest + "\" on REST Requestor consumer (" + this.name + ")";
177 LOGGER.warn(errorMessage);
178 throw new ApexEventRuntimeException(errorMessage);
185 * @see org.onap.policy.apex.service.engine.event.ApexEventConsumer#start()
188 public void start() {
189 // Configure and start the event reception thread
190 final String threadName = this.getClass().getName() + ":" + this.name;
191 consumerThread = new ApplicationThreadFactory(threadName).newThread(this);
192 consumerThread.setDaemon(true);
193 consumerThread.start();
199 * @see org.onap.policy.apex.service.engine.event.ApexEventConsumer#getName()
202 public String getName() {
207 * Get the number of events received to date
209 * @return the number of events received
211 public int getEventsReceived() {
212 return eventsReceived;
218 * @see org.onap.policy.apex.service.engine.event.ApexEventConsumer#getPeeredReference(org.onap.policy.apex.service.
219 * parameters.eventhandler.EventHandlerPeeredMode)
222 public PeeredReference getPeeredReference(final EventHandlerPeeredMode peeredMode) {
223 return peerReferenceMap.get(peeredMode);
229 * @see org.onap.policy.apex.service.engine.event.ApexEventConsumer#setPeeredReference(org.onap.policy.apex.service.
230 * parameters.eventhandler.EventHandlerPeeredMode, org.onap.policy.apex.service.engine.event.PeeredReference)
233 public void setPeeredReference(final EventHandlerPeeredMode peeredMode, final PeeredReference peeredReference) {
234 peerReferenceMap.put(peeredMode, peeredReference);
240 * @see java.lang.Runnable#run()
244 // The endless loop that receives events using REST calls
245 while (consumerThread.isAlive() && !stopOrderedFlag) {
247 // Take the next event from the queue
248 final ApexRestRequest restRequest =
249 incomingRestRequestQueue.poll(REST_REQUESTOR_WAIT_SLEEP_TIME, TimeUnit.MILLISECONDS);
250 if (restRequest == null) {
251 // Poll timed out, check for request timeouts
252 timeoutExpiredRequests();
256 // Set the time stamp of the REST request
257 restRequest.setTimestamp(System.currentTimeMillis());
259 // Create a thread to process the REST request and place it on the map of ongoing requests
260 final RestRequestRunner restRequestRunner = new RestRequestRunner(restRequest);
261 ongoingRestRequestMap.put(restRequest, restRequestRunner);
263 // Start execution of the request
264 final Thread restRequestRunnerThread = new Thread(restRequestRunner);
265 restRequestRunnerThread.setName("RestRequestRunner_" + nextRequestRunnerThreadNo);
266 restRequestRunnerThread.start();
267 } catch (final InterruptedException e) {
268 LOGGER.debug("Thread interrupted, Reason {}", e.getMessage());
269 Thread.currentThread().interrupt();
277 * This method times out REST requests that have expired
279 private void timeoutExpiredRequests() {
280 // Hold a list of timed out requests
281 final List<ApexRestRequest> timedoutRequestList = new ArrayList<>();
283 // Check for timeouts
284 for (final Entry<ApexRestRequest, RestRequestRunner> requestEntry : ongoingRestRequestMap.entrySet()) {
285 if (System.currentTimeMillis() - requestEntry.getKey().getTimestamp() > restRequestTimeout) {
286 requestEntry.getValue().stop();
287 timedoutRequestList.add(requestEntry.getKey());
291 // Interrupt timed out requests and remove them from the ongoing map
292 for (final ApexRestRequest timedoutRequest : timedoutRequestList) {
293 final String errorMessage =
294 "REST Requestor consumer (" + this.name + "), REST request timed out: " + timedoutRequest;
295 LOGGER.warn(errorMessage);
297 ongoingRestRequestMap.remove(timedoutRequest);
304 * @see org.onap.policy.apex.apps.uservice.producer.ApexEventConsumer#stop()
308 stopOrderedFlag = true;
310 while (consumerThread.isAlive()) {
311 ThreadUtilities.sleep(REST_REQUESTOR_WAIT_SLEEP_TIME);
316 * This class is used to start a thread for each request issued.
318 * @author Liam Fallon (liam.fallon@ericsson.com)
320 private class RestRequestRunner implements Runnable {
321 private static final String APPLICATION_JSON = "application/json";
323 // The REST request being processed by this thread
324 private final ApexRestRequest request;
326 // The thread executing the REST request
327 private Thread restRequestThread;
330 * Constructor, initialise the request runner with the request
332 * @param request the request this runner will issue
334 private RestRequestRunner(final ApexRestRequest request) {
335 this.request = request;
341 * @see java.lang.Runnable#run()
345 // Get the thread for the request
346 restRequestThread = Thread.currentThread();
349 // Execute the REST request
350 final Response response = sendEventAsRESTRequest();
352 // Check that the event request worked
353 if (response.getStatus() != Response.Status.OK.getStatusCode()) {
354 final String errorMessage = "reception of response to \"" + request + "\" from URL \""
355 + restConsumerProperties.getURL() + "\" failed with status code " + response.getStatus()
356 + " and message \"" + response.readEntity(String.class) + "\"";
357 throw new ApexEventRuntimeException(errorMessage);
360 // Get the event we received
361 final String eventJSONString = response.readEntity(String.class);
363 // Check there is content
364 if (eventJSONString == null || eventJSONString.trim().length() == 0) {
365 final String errorMessage = "received an enpty response to \"" + request + "\" from URL \""
366 + restConsumerProperties.getURL() + "\"";
367 throw new ApexEventRuntimeException(errorMessage);
370 // Send the event into Apex
371 eventReceiver.receiveEvent(request.getExecutionId(), eventJSONString);
373 synchronized (eventsReceivedLock) {
376 } catch (final Exception e) {
377 LOGGER.warn("error receiving events on thread {}", consumerThread.getName(), e);
379 // Remove the request from the map of ongoing requests
380 ongoingRestRequestMap.remove(request);
385 * Stop the REST request
387 private void stop() {
388 restRequestThread.interrupt();
392 * Execute the REST request.
394 * @return the response to the REST request
396 public Response sendEventAsRESTRequest() {
397 switch (restConsumerProperties.getHttpMethod()) {
399 return client.target(restConsumerProperties.getURL()).request(APPLICATION_JSON).get();
402 return client.target(restConsumerProperties.getURL()).request(APPLICATION_JSON)
403 .put(Entity.json(request.getEvent()));
406 return client.target(restConsumerProperties.getURL()).request(APPLICATION_JSON)
407 .post(Entity.json(request.getEvent()));
410 return client.target(restConsumerProperties.getURL()).request(APPLICATION_JSON).delete();