2 * ============LICENSE_START=======================================================
3 * Copyright (C) 2016-2018 Ericsson. All rights reserved.
4 * Modifications Copyright (C) 2019-2020 Nordix Foundation.
5 * Modifications Copyright (C) 2021 Bell Canada. All rights reserved.
6 * ================================================================================
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
19 * SPDX-License-Identifier: Apache-2.0
20 * ============LICENSE_END=========================================================
23 package org.onap.policy.apex.plugins.event.carrier.restclient;
25 import java.util.Properties;
26 import java.util.regex.Matcher;
27 import java.util.regex.Pattern;
28 import javax.ws.rs.client.Client;
29 import javax.ws.rs.client.ClientBuilder;
30 import javax.ws.rs.core.Response;
31 import org.apache.commons.lang3.StringUtils;
32 import org.onap.policy.apex.core.infrastructure.threading.ThreadUtilities;
33 import org.onap.policy.apex.service.engine.event.ApexEventException;
34 import org.onap.policy.apex.service.engine.event.ApexEventReceiver;
35 import org.onap.policy.apex.service.engine.event.ApexEventRuntimeException;
36 import org.onap.policy.apex.service.engine.event.ApexPluginsEventConsumer;
37 import org.onap.policy.apex.service.parameters.carriertechnology.RestPluginCarrierTechnologyParameters;
38 import org.onap.policy.apex.service.parameters.eventhandler.EventHandlerParameters;
39 import org.slf4j.Logger;
40 import org.slf4j.LoggerFactory;
43 * This class implements an Apex event consumer that receives events from a REST server.
45 * @author Liam Fallon (liam.fallon@ericsson.com)
47 public class ApexRestClientConsumer extends ApexPluginsEventConsumer {
48 // Get a reference to the logger
49 private static final Logger LOGGER = LoggerFactory.getLogger(ApexRestClientConsumer.class);
51 // The amount of time to wait in milliseconds between checks that the consumer thread has stopped
52 private static final long REST_CLIENT_WAIT_SLEEP_TIME = 50;
54 // The REST parameters read from the parameter service
55 private RestClientCarrierTechnologyParameters restConsumerProperties;
57 // The event receiver that will receive events from this consumer
58 private ApexEventReceiver eventReceiver;
60 // The HTTP client that makes a REST call to get an input event for Apex
61 private Client client;
63 // The pattern for filtering status code
64 private Pattern httpCodeFilterPattern = null;
67 public void init(final String consumerName, final EventHandlerParameters consumerParameters,
68 final ApexEventReceiver incomingEventReceiver) throws ApexEventException {
69 this.eventReceiver = incomingEventReceiver;
70 this.name = consumerName;
72 // Check and get the REST Properties
73 if (!(consumerParameters.getCarrierTechnologyParameters() instanceof RestClientCarrierTechnologyParameters)) {
74 final String errorMessage =
75 "specified consumer properties are not applicable to REST client consumer (" + this.name + ")";
76 LOGGER.warn(errorMessage);
77 throw new ApexEventException(errorMessage);
79 restConsumerProperties =
80 (RestClientCarrierTechnologyParameters) consumerParameters.getCarrierTechnologyParameters();
82 this.httpCodeFilterPattern = Pattern.compile(restConsumerProperties.getHttpCodeFilter());
84 // Check if the HTTP method has been set
85 if (restConsumerProperties.getHttpMethod() == null) {
86 restConsumerProperties.setHttpMethod(RestPluginCarrierTechnologyParameters.HttpMethod.GET);
89 if (!RestPluginCarrierTechnologyParameters.HttpMethod.GET.equals(restConsumerProperties.getHttpMethod())) {
90 final String errorMessage = "specified HTTP method of \"" + restConsumerProperties.getHttpMethod()
91 + "\" is invalid, only HTTP method \"GET\" "
92 + "is supported for event reception on REST client consumer (" + this.name + ")";
93 LOGGER.warn(errorMessage);
94 throw new ApexEventException(errorMessage);
97 // Initialize the HTTP client
98 client = ClientBuilder.newClient();
106 // The RequestRunner thread runs the get request for the event
107 Thread requestRunnerThread = null;
109 // The endless loop that receives events using REST calls
110 while (consumerThread.isAlive() && !stopOrderedFlag) {
111 // Create a new request if one is not in progress
112 if (requestRunnerThread == null || !requestRunnerThread.isAlive()) {
113 requestRunnerThread = new Thread(new RequestRunner());
114 requestRunnerThread.start();
117 ThreadUtilities.sleep(REST_CLIENT_WAIT_SLEEP_TIME);
128 stopOrderedFlag = true;
130 while (consumerThread.isAlive()) {
131 ThreadUtilities.sleep(REST_CLIENT_WAIT_SLEEP_TIME);
136 * This class is used to start a thread for each request issued.
138 * @author Liam Fallon (liam.fallon@ericsson.com)
140 private class RequestRunner implements Runnable {
147 final Response response = client.target(restConsumerProperties.getUrl()).request("application/json")
148 .headers(restConsumerProperties.getHttpHeadersAsMultivaluedMap()).get();
150 // Match the return code
151 Matcher isPass = httpCodeFilterPattern.matcher(String.valueOf(response.getStatus()));
153 // Check that status code
154 if (!isPass.matches()) {
155 final String errorMessage = "reception of event from URL \"" + restConsumerProperties.getUrl()
156 + "\" failed with status code " + response.getStatus() + " and message \""
157 + response.readEntity(String.class) + "\"";
158 LOGGER.warn(errorMessage);
159 throw new ApexEventRuntimeException(errorMessage);
162 // Get the event we received
163 final String eventJsonString = response.readEntity(String.class);
165 // Check there is content
166 if (StringUtils.isBlank(eventJsonString)) {
167 final String errorMessage =
168 "received an empty event from URL \"" + restConsumerProperties.getUrl() + "\"";
169 throw new ApexEventRuntimeException(errorMessage);
172 // Send the event into Apex
173 eventReceiver.receiveEvent(new Properties(), eventJsonString);
174 } catch (final Exception e) {
175 LOGGER.debug("error receiving events on thread {}", consumerThread.getName(), e);
181 * Hook for unit test mocking of HTTP client.
183 * @param client the mocked client
185 protected void setClient(final Client client) {
186 this.client = client;