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.service.engine.event.ApexEventConsumer;
42 import org.onap.policy.apex.service.engine.event.ApexEventException;
43 import org.onap.policy.apex.service.engine.event.ApexEventReceiver;
44 import org.onap.policy.apex.service.engine.event.ApexEventRuntimeException;
45 import org.onap.policy.apex.service.engine.event.PeeredReference;
46 import org.onap.policy.apex.service.parameters.eventhandler.EventHandlerParameters;
47 import org.onap.policy.apex.service.parameters.eventhandler.EventHandlerPeeredMode;
48 import org.slf4j.Logger;
49 import org.slf4j.LoggerFactory;
52 * This class implements an Apex event consumer that issues a REST request and returns the REST response to APEX as an
55 * @author Liam Fallon (liam.fallon@ericsson.com)
57 public class ApexRestRequestorConsumer implements ApexEventConsumer, Runnable {
58 // Get a reference to the logger
59 private static final Logger LOGGER = LoggerFactory.getLogger(ApexRestRequestorConsumer.class);
61 // The amount of time to wait in milliseconds between checks that the consumer thread has
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 = "specified consumer properties are not applicable to REST Requestor consumer ("
111 LOGGER.warn(errorMessage);
112 throw new ApexEventException(errorMessage);
114 restConsumerProperties = (RestRequestorCarrierTechnologyParameters) consumerParameters
115 .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 // Check if the HTTP URL has been set
132 if (restConsumerProperties.getUrl() == null) {
133 final String errorMessage = "no URL has been specified on REST Requestor consumer (" + this.name + ")";
134 LOGGER.warn(errorMessage);
135 throw new ApexEventException(errorMessage);
138 // Check if the HTTP URL is valid
140 new URL(restConsumerProperties.getUrl());
141 } catch (final Exception e) {
142 final String errorMessage = "invalid URL has been specified on REST Requestor consumer (" + this.name + ")";
143 LOGGER.warn(errorMessage);
144 throw new ApexEventException(errorMessage, e);
147 // Set the peer timeout to the default value if its not set
148 if (consumerParameters.getPeerTimeout(EventHandlerPeeredMode.REQUESTOR) != 0) {
149 restRequestTimeout = consumerParameters.getPeerTimeout(EventHandlerPeeredMode.REQUESTOR);
152 // Initialize the HTTP client
153 client = ClientBuilder.newClient();
157 * Receive an incoming REST request from the peered REST Requestor producer and queue it.
159 * @param restRequest the incoming rest request to queue
160 * @throws ApexEventRuntimeException on queueing errors
162 public void processRestRequest(final ApexRestRequest restRequest) {
163 // Push the event onto the queue for handling
165 incomingRestRequestQueue.add(restRequest);
166 } catch (final Exception e) {
167 final String errorMessage = "could not queue request \"" + restRequest + "\" on REST Requestor consumer ("
169 LOGGER.warn(errorMessage, e);
170 throw new ApexEventRuntimeException(errorMessage);
177 * @see org.onap.policy.apex.service.engine.event.ApexEventConsumer#start()
180 public void start() {
181 // Configure and start the event reception thread
182 final String threadName = this.getClass().getName() + ":" + this.name;
183 consumerThread = new ApplicationThreadFactory(threadName).newThread(this);
184 consumerThread.setDaemon(true);
185 consumerThread.start();
191 * @see org.onap.policy.apex.service.engine.event.ApexEventConsumer#getName()
194 public String getName() {
199 * Get the number of events received to date.
201 * @return the number of events received
203 public int getEventsReceived() {
204 return eventsReceived;
210 * @see org.onap.policy.apex.service.engine.event.ApexEventConsumer#getPeeredReference(org.onap.
211 * policy.apex.service. parameters.eventhandler.EventHandlerPeeredMode)
214 public PeeredReference getPeeredReference(final EventHandlerPeeredMode peeredMode) {
215 return peerReferenceMap.get(peeredMode);
221 * @see org.onap.policy.apex.service.engine.event.ApexEventConsumer#setPeeredReference(org.onap.
222 * policy.apex.service. parameters.eventhandler.EventHandlerPeeredMode,
223 * org.onap.policy.apex.service.engine.event.PeeredReference)
226 public void setPeeredReference(final EventHandlerPeeredMode peeredMode, final PeeredReference peeredReference) {
227 peerReferenceMap.put(peeredMode, peeredReference);
233 * @see java.lang.Runnable#run()
237 // The endless loop that receives events using REST calls
238 while (consumerThread.isAlive() && !stopOrderedFlag) {
240 // Take the next event from the queue
241 final ApexRestRequest restRequest = incomingRestRequestQueue.poll(REST_REQUESTOR_WAIT_SLEEP_TIME,
242 TimeUnit.MILLISECONDS);
243 if (restRequest == null) {
244 // Poll timed out, check for request timeouts
245 timeoutExpiredRequests();
249 // Set the time stamp of the REST request
250 restRequest.setTimestamp(System.currentTimeMillis());
252 // Create a thread to process the REST request and place it on the map of ongoing
254 final RestRequestRunner restRequestRunner = new RestRequestRunner(restRequest);
255 ongoingRestRequestMap.put(restRequest, restRequestRunner);
257 // Start execution of the request
258 final Thread restRequestRunnerThread = new Thread(restRequestRunner);
259 restRequestRunnerThread.setName("RestRequestRunner_" + nextRequestRunnerThreadNo);
260 restRequestRunnerThread.start();
261 } catch (final InterruptedException e) {
262 LOGGER.debug("Thread interrupted, Reason {}", e.getMessage());
263 Thread.currentThread().interrupt();
271 * This method times out REST requests that have expired.
273 private void timeoutExpiredRequests() {
274 // Hold a list of timed out requests
275 final List<ApexRestRequest> timedoutRequestList = new ArrayList<>();
277 // Check for timeouts
278 for (final Entry<ApexRestRequest, RestRequestRunner> requestEntry : ongoingRestRequestMap.entrySet()) {
279 if (System.currentTimeMillis() - requestEntry.getKey().getTimestamp() > restRequestTimeout) {
280 requestEntry.getValue().stop();
281 timedoutRequestList.add(requestEntry.getKey());
285 // Interrupt timed out requests and remove them from the ongoing map
286 for (final ApexRestRequest timedoutRequest : timedoutRequestList) {
287 final String errorMessage = "REST Requestor consumer (" + this.name + "), REST request timed out: "
289 LOGGER.warn(errorMessage);
291 ongoingRestRequestMap.remove(timedoutRequest);
298 * @see org.onap.policy.apex.apps.uservice.producer.ApexEventConsumer#stop()
302 stopOrderedFlag = true;
304 while (consumerThread.isAlive()) {
305 ThreadUtilities.sleep(REST_REQUESTOR_WAIT_SLEEP_TIME);
310 * This class is used to start a thread for each request issued.
312 * @author Liam Fallon (liam.fallon@ericsson.com)
314 private class RestRequestRunner implements Runnable {
315 private static final String APPLICATION_JSON = "application/json";
317 // The REST request being processed by this thread
318 private final ApexRestRequest request;
320 // The thread executing the REST request
321 private Thread restRequestThread;
324 * Constructor, initialise the request runner with the request.
326 * @param request the request this runner will issue
328 private RestRequestRunner(final ApexRestRequest request) {
329 this.request = request;
335 * @see java.lang.Runnable#run()
339 // Get the thread for the request
340 restRequestThread = Thread.currentThread();
343 // Execute the REST request
344 final Response response = sendEventAsRestRequest();
346 // Check that the event request worked
347 if (response.getStatus() != Response.Status.OK.getStatusCode()) {
348 final String errorMessage = "reception of response to \"" + request + "\" from URL \""
349 + restConsumerProperties.getUrl() + "\" failed with status code "
350 + response.getStatus() + " and message \"" + response.readEntity(String.class)
352 throw new ApexEventRuntimeException(errorMessage);
355 // Get the event we received
356 final String eventJsonString = response.readEntity(String.class);
358 // Check there is content
359 if (eventJsonString == null || eventJsonString.trim().length() == 0) {
360 final String errorMessage = "received an enpty response to \"" + request + "\" from URL \""
361 + restConsumerProperties.getUrl() + "\"";
362 throw new ApexEventRuntimeException(errorMessage);
365 // Send the event into Apex
366 eventReceiver.receiveEvent(request.getExecutionId(), eventJsonString);
368 synchronized (eventsReceivedLock) {
371 } catch (final Exception e) {
372 LOGGER.warn("error receiving events on thread {}", consumerThread.getName(), e);
374 // Remove the request from the map of ongoing requests
375 ongoingRestRequestMap.remove(request);
380 * Stop the REST request.
382 private void stop() {
383 restRequestThread.interrupt();
387 * Execute the REST request.
389 * @return the response to the REST request
391 public Response sendEventAsRestRequest() {
392 switch (restConsumerProperties.getHttpMethod()) {
394 return client.target(restConsumerProperties.getUrl()).request(APPLICATION_JSON).get();
397 return client.target(restConsumerProperties.getUrl()).request(APPLICATION_JSON)
398 .put(Entity.json(request.getEvent()));
401 return client.target(restConsumerProperties.getUrl()).request(APPLICATION_JSON)
402 .post(Entity.json(request.getEvent()));
405 return client.target(restConsumerProperties.getUrl()).request(APPLICATION_JSON).delete();