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.Arrays;
26 import java.util.EnumMap;
27 import java.util.List;
29 import java.util.Map.Entry;
30 import java.util.concurrent.BlockingQueue;
31 import java.util.concurrent.ConcurrentHashMap;
32 import java.util.concurrent.LinkedBlockingQueue;
33 import java.util.concurrent.TimeUnit;
35 import javax.ws.rs.client.Client;
36 import javax.ws.rs.client.ClientBuilder;
37 import javax.ws.rs.client.Entity;
38 import javax.ws.rs.core.Response;
40 import org.onap.policy.apex.core.infrastructure.threading.ApplicationThreadFactory;
41 import org.onap.policy.apex.core.infrastructure.threading.ThreadUtilities;
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
64 private static final long REST_REQUESTOR_WAIT_SLEEP_TIME = 50;
66 // The REST parameters read from the parameter service
67 private RestRequestorCarrierTechnologyParameters restConsumerProperties;
69 // The timeout for REST requests
70 private long restRequestTimeout = RestRequestorCarrierTechnologyParameters.DEFAULT_REST_REQUEST_TIMEOUT;
72 // The event receiver that will receive events from this consumer
73 private ApexEventReceiver eventReceiver;
75 // The HTTP client that makes a REST call to get an input event for Apex
76 private Client client;
78 // The name for this consumer
79 private String name = null;
81 // The peer references for this event handler
82 private Map<EventHandlerPeeredMode, PeeredReference> peerReferenceMap = new EnumMap<>(EventHandlerPeeredMode.class);
84 // The consumer thread and stopping flag
85 private Thread consumerThread;
86 private boolean stopOrderedFlag = false;
88 // Temporary request holder for incoming REST requests
89 private final BlockingQueue<ApexRestRequest> incomingRestRequestQueue = new LinkedBlockingQueue<>();
91 // Map of ongoing REST request threads indexed by the time they started at
92 private final Map<ApexRestRequest, RestRequestRunner> ongoingRestRequestMap = new ConcurrentHashMap<>();
94 // The number of events received to date
95 private Object eventsReceivedLock = new Object();
96 private Integer eventsReceived = 0;
98 // The number of the next request runner thread
99 private static long nextRequestRunnerThreadNo = 0;
102 public void init(final String consumerName, final EventHandlerParameters consumerParameters,
103 final ApexEventReceiver incomingEventReceiver) throws ApexEventException {
104 this.eventReceiver = incomingEventReceiver;
105 this.name = consumerName;
107 // Check and get the REST Properties
108 if (!(consumerParameters
109 .getCarrierTechnologyParameters() instanceof RestRequestorCarrierTechnologyParameters)) {
110 final String errorMessage = "specified consumer properties are not applicable to REST Requestor consumer ("
112 LOGGER.warn(errorMessage);
113 throw new ApexEventException(errorMessage);
115 restConsumerProperties = (RestRequestorCarrierTechnologyParameters) consumerParameters
116 .getCarrierTechnologyParameters();
118 // Check if we are in peered mode
119 if (!consumerParameters.isPeeredMode(EventHandlerPeeredMode.REQUESTOR)) {
120 final String errorMessage = "REST Requestor consumer (" + this.name
121 + ") must run in peered requestor mode with a REST Requestor producer";
122 LOGGER.warn(errorMessage);
123 throw new ApexEventException(errorMessage);
126 // Check if the HTTP method has been set
127 if (restConsumerProperties.getHttpMethod() == null) {
128 restConsumerProperties
129 .setHttpMethod(RestRequestorCarrierTechnologyParameters.DEFAULT_REQUESTOR_HTTP_METHOD);
132 // Check if the HTTP URL has been set
133 if (restConsumerProperties.getUrl() == null) {
134 final String errorMessage = "no URL has been specified on REST Requestor consumer (" + this.name + ")";
135 LOGGER.warn(errorMessage);
136 throw new ApexEventException(errorMessage);
139 // Check if the HTTP URL is valid
141 new URL(restConsumerProperties.getUrl());
142 } catch (final Exception e) {
143 final String errorMessage = "invalid URL has been specified on REST Requestor consumer (" + this.name + ")";
144 LOGGER.warn(errorMessage);
145 throw new ApexEventException(errorMessage, e);
148 // Set the requestor timeout
149 if (consumerParameters.getPeerTimeout(EventHandlerPeeredMode.REQUESTOR) != 0) {
150 restRequestTimeout = consumerParameters.getPeerTimeout(EventHandlerPeeredMode.REQUESTOR);
153 // Check if HTTP headers has been set
154 if (restConsumerProperties.checkHttpHeadersSet()) {
155 LOGGER.debug("REST Requestor consumer has http headers ({}): {}", this.name,
156 Arrays.deepToString(restConsumerProperties.getHttpHeaders()));
159 // Initialize the HTTP client
160 client = ClientBuilder.newClient();
164 * Receive an incoming REST request from the peered REST Requestor producer and queue it.
166 * @param restRequest the incoming rest request to queue
167 * @throws ApexEventRuntimeException on queueing errors
169 public void processRestRequest(final ApexRestRequest restRequest) {
170 // Push the event onto the queue for handling
172 incomingRestRequestQueue.add(restRequest);
173 } catch (final Exception requestException) {
174 final String errorMessage = "could not queue request \"" + restRequest + "\" on REST Requestor consumer ("
176 LOGGER.warn(errorMessage, requestException);
177 throw new ApexEventRuntimeException(errorMessage);
185 public void start() {
186 // Configure and start the event reception thread
187 final String threadName = this.getClass().getName() + ":" + this.name;
188 consumerThread = new ApplicationThreadFactory(threadName).newThread(this);
189 consumerThread.setDaemon(true);
190 consumerThread.start();
197 public String getName() {
202 * Get the number of events received to date.
204 * @return the number of events received
206 public int getEventsReceived() {
207 return eventsReceived;
214 public PeeredReference getPeeredReference(final EventHandlerPeeredMode peeredMode) {
215 return peerReferenceMap.get(peeredMode);
222 public void setPeeredReference(final EventHandlerPeeredMode peeredMode, final PeeredReference peeredReference) {
223 peerReferenceMap.put(peeredMode, peeredReference);
231 // The endless loop that receives events using REST calls
232 while (consumerThread.isAlive() && !stopOrderedFlag) {
234 // Take the next event from the queue
235 final ApexRestRequest restRequest = incomingRestRequestQueue.poll(REST_REQUESTOR_WAIT_SLEEP_TIME,
236 TimeUnit.MILLISECONDS);
237 if (restRequest == null) {
238 // Poll timed out, check for request timeouts
239 timeoutExpiredRequests();
243 // Set the time stamp of the REST request
244 restRequest.setTimestamp(System.currentTimeMillis());
246 // Create a thread to process the REST request and place it on the map of ongoing
248 final RestRequestRunner restRequestRunner = new RestRequestRunner(restRequest);
249 ongoingRestRequestMap.put(restRequest, restRequestRunner);
251 // Start execution of the request
252 final Thread restRequestRunnerThread = new Thread(restRequestRunner);
253 restRequestRunnerThread.setName("RestRequestRunner_" + nextRequestRunnerThreadNo);
254 restRequestRunnerThread.start();
255 } catch (final InterruptedException e) {
256 LOGGER.debug("Thread interrupted, Reason {}", e.getMessage());
257 Thread.currentThread().interrupt();
265 * This method times out REST requests that have expired.
267 private void timeoutExpiredRequests() {
268 // Hold a list of timed out requests
269 final List<ApexRestRequest> timedoutRequestList = new ArrayList<>();
271 // Check for timeouts
272 for (final Entry<ApexRestRequest, RestRequestRunner> requestEntry : ongoingRestRequestMap.entrySet()) {
273 if (System.currentTimeMillis() - requestEntry.getKey().getTimestamp() > restRequestTimeout) {
274 requestEntry.getValue().stop();
275 timedoutRequestList.add(requestEntry.getKey());
279 // Interrupt timed out requests and remove them from the ongoing map
280 for (final ApexRestRequest timedoutRequest : timedoutRequestList) {
281 final String errorMessage = "REST Requestor consumer (" + this.name + "), REST request timed out: "
283 LOGGER.warn(errorMessage);
285 ongoingRestRequestMap.remove(timedoutRequest);
294 stopOrderedFlag = true;
296 while (consumerThread.isAlive()) {
297 ThreadUtilities.sleep(REST_REQUESTOR_WAIT_SLEEP_TIME);
302 * This class is used to start a thread for each request issued.
304 * @author Liam Fallon (liam.fallon@ericsson.com)
306 private class RestRequestRunner implements Runnable {
307 private static final String APPLICATION_JSON = "application/json";
309 // The REST request being processed by this thread
310 private final ApexRestRequest request;
312 // The thread executing the REST request
313 private Thread restRequestThread;
316 * Constructor, initialise the request runner with the request.
318 * @param request the request this runner will issue
320 private RestRequestRunner(final ApexRestRequest request) {
321 this.request = request;
329 // Get the thread for the request
330 restRequestThread = Thread.currentThread();
333 // Execute the REST request
334 final Response response = sendEventAsRestRequest();
336 // Check that the event request worked
337 if (!Response.Status.Family.familyOf(response.getStatus()).equals(Response.Status.Family.SUCCESSFUL)) {
338 final String errorMessage = "reception of response to \"" + request + "\" from URL \""
339 + restConsumerProperties.getUrl() + "\" failed with status code "
340 + response.getStatus() + " and message \"" + response.readEntity(String.class)
342 throw new ApexEventRuntimeException(errorMessage);
345 // Get the event we received
346 final String eventJsonString = response.readEntity(String.class);
348 // Check there is content
349 if (eventJsonString == null || eventJsonString.trim().length() == 0) {
350 final String errorMessage = "received an enpty response to \"" + request + "\" from URL \""
351 + restConsumerProperties.getUrl() + "\"";
352 throw new ApexEventRuntimeException(errorMessage);
355 // Send the event into Apex
356 eventReceiver.receiveEvent(request.getExecutionId(), null, eventJsonString);
358 synchronized (eventsReceivedLock) {
361 } catch (final Exception e) {
362 LOGGER.warn("error receiving events on thread {}", consumerThread.getName(), e);
364 // Remove the request from the map of ongoing requests
365 ongoingRestRequestMap.remove(request);
370 * Stop the REST request.
372 private void stop() {
373 restRequestThread.interrupt();
377 * Execute the REST request.
380 * @return the response to the REST request
382 public Response sendEventAsRestRequest() {
383 switch (restConsumerProperties.getHttpMethod()) {
385 return client.target(restConsumerProperties.getUrl()).request(APPLICATION_JSON)
386 .headers(restConsumerProperties.getHttpHeadersAsMultivaluedMap()).get();
389 return client.target(restConsumerProperties.getUrl()).request(APPLICATION_JSON)
390 .headers(restConsumerProperties.getHttpHeadersAsMultivaluedMap())
391 .put(Entity.json(request.getEvent()));
394 return client.target(restConsumerProperties.getUrl()).request(APPLICATION_JSON)
395 .headers(restConsumerProperties.getHttpHeadersAsMultivaluedMap())
396 .post(Entity.json(request.getEvent()));
399 return client.target(restConsumerProperties.getUrl()).request(APPLICATION_JSON)
400 .headers(restConsumerProperties.getHttpHeadersAsMultivaluedMap()).delete();