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);
184 * @see org.onap.policy.apex.service.engine.event.ApexEventConsumer#start()
187 public void start() {
188 // Configure and start the event reception thread
189 final String threadName = this.getClass().getName() + ":" + this.name;
190 consumerThread = new ApplicationThreadFactory(threadName).newThread(this);
191 consumerThread.setDaemon(true);
192 consumerThread.start();
198 * @see org.onap.policy.apex.service.engine.event.ApexEventConsumer#getName()
201 public String getName() {
206 * Get the number of events received to date.
208 * @return the number of events received
210 public int getEventsReceived() {
211 return eventsReceived;
217 * @see org.onap.policy.apex.service.engine.event.ApexEventConsumer#getPeeredReference(org.onap.
218 * policy.apex.service. parameters.eventhandler.EventHandlerPeeredMode)
221 public PeeredReference getPeeredReference(final EventHandlerPeeredMode peeredMode) {
222 return peerReferenceMap.get(peeredMode);
228 * @see org.onap.policy.apex.service.engine.event.ApexEventConsumer#setPeeredReference(org.onap.
229 * policy.apex.service. parameters.eventhandler.EventHandlerPeeredMode,
230 * 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 = incomingRestRequestQueue.poll(REST_REQUESTOR_WAIT_SLEEP_TIME,
249 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
261 final RestRequestRunner restRequestRunner = new RestRequestRunner(restRequest);
262 ongoingRestRequestMap.put(restRequest, restRequestRunner);
264 // Start execution of the request
265 final Thread restRequestRunnerThread = new Thread(restRequestRunner);
266 restRequestRunnerThread.setName("RestRequestRunner_" + nextRequestRunnerThreadNo);
267 restRequestRunnerThread.start();
268 } catch (final InterruptedException e) {
269 LOGGER.debug("Thread interrupted, Reason {}", e.getMessage());
270 Thread.currentThread().interrupt();
278 * This method times out REST requests that have expired.
280 private void timeoutExpiredRequests() {
281 // Hold a list of timed out requests
282 final List<ApexRestRequest> timedoutRequestList = new ArrayList<>();
284 // Check for timeouts
285 for (final Entry<ApexRestRequest, RestRequestRunner> requestEntry : ongoingRestRequestMap.entrySet()) {
286 if (System.currentTimeMillis() - requestEntry.getKey().getTimestamp() > restRequestTimeout) {
287 requestEntry.getValue().stop();
288 timedoutRequestList.add(requestEntry.getKey());
292 // Interrupt timed out requests and remove them from the ongoing map
293 for (final ApexRestRequest timedoutRequest : timedoutRequestList) {
294 final String errorMessage = "REST Requestor consumer (" + this.name + "), REST request timed out: "
296 LOGGER.warn(errorMessage);
298 ongoingRestRequestMap.remove(timedoutRequest);
305 * @see org.onap.policy.apex.apps.uservice.producer.ApexEventConsumer#stop()
309 stopOrderedFlag = true;
311 while (consumerThread.isAlive()) {
312 ThreadUtilities.sleep(REST_REQUESTOR_WAIT_SLEEP_TIME);
317 * This class is used to start a thread for each request issued.
319 * @author Liam Fallon (liam.fallon@ericsson.com)
321 private class RestRequestRunner implements Runnable {
322 private static final String APPLICATION_JSON = "application/json";
324 // The REST request being processed by this thread
325 private final ApexRestRequest request;
327 // The thread executing the REST request
328 private Thread restRequestThread;
331 * Constructor, initialise the request runner with the request.
333 * @param request the request this runner will issue
335 private RestRequestRunner(final ApexRestRequest request) {
336 this.request = request;
342 * @see java.lang.Runnable#run()
346 // Get the thread for the request
347 restRequestThread = Thread.currentThread();
350 // Execute the REST request
351 final Response response = sendEventAsRestRequest();
353 // Check that the event request worked
354 if (!Response.Status.Family.familyOf(response.getStatus()).equals(Response.Status.Family.SUCCESSFUL)) {
355 final String errorMessage = "reception of response to \"" + request + "\" from URL \""
356 + restConsumerProperties.getUrl() + "\" failed with status code "
357 + response.getStatus() + " and message \"" + response.readEntity(String.class)
359 throw new ApexEventRuntimeException(errorMessage);
362 // Get the event we received
363 final String eventJsonString = response.readEntity(String.class);
365 // Check there is content
366 if (eventJsonString == null || eventJsonString.trim().length() == 0) {
367 final String errorMessage = "received an enpty response to \"" + request + "\" from URL \""
368 + restConsumerProperties.getUrl() + "\"";
369 throw new ApexEventRuntimeException(errorMessage);
372 // Send the event into Apex
373 eventReceiver.receiveEvent(request.getExecutionId(), null, eventJsonString);
375 synchronized (eventsReceivedLock) {
378 } catch (final Exception e) {
379 LOGGER.warn("error receiving events on thread {}", consumerThread.getName(), e);
381 // Remove the request from the map of ongoing requests
382 ongoingRestRequestMap.remove(request);
387 * Stop the REST request.
389 private void stop() {
390 restRequestThread.interrupt();
394 * Execute the REST request.
397 * @return the response to the REST request
399 public Response sendEventAsRestRequest() {
400 switch (restConsumerProperties.getHttpMethod()) {
402 return client.target(restConsumerProperties.getUrl()).request(APPLICATION_JSON)
403 .headers(restConsumerProperties.getHttpHeadersAsMultivaluedMap()).get();
406 return client.target(restConsumerProperties.getUrl()).request(APPLICATION_JSON)
407 .headers(restConsumerProperties.getHttpHeadersAsMultivaluedMap())
408 .put(Entity.json(request.getEvent()));
411 return client.target(restConsumerProperties.getUrl()).request(APPLICATION_JSON)
412 .headers(restConsumerProperties.getHttpHeadersAsMultivaluedMap())
413 .post(Entity.json(request.getEvent()));
416 return client.target(restConsumerProperties.getUrl()).request(APPLICATION_JSON)
417 .headers(restConsumerProperties.getHttpHeadersAsMultivaluedMap()).delete();