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 * Modifications Copyright (C) 2021 AT&T Intellectual Property. All rights reserved.
7 * ================================================================================
8 * Licensed under the Apache License, Version 2.0 (the "License");
9 * you may not use this file except in compliance with the License.
10 * You may obtain a copy of the License at
12 * http://www.apache.org/licenses/LICENSE-2.0
14 * Unless required by applicable law or agreed to in writing, software
15 * distributed under the License is distributed on an "AS IS" BASIS,
16 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 * See the License for the specific language governing permissions and
18 * limitations under the License.
20 * SPDX-License-Identifier: Apache-2.0
21 * ============LICENSE_END=========================================================
24 package org.onap.policy.apex.plugins.event.carrier.restclient;
26 import java.util.Properties;
27 import java.util.regex.Matcher;
28 import java.util.regex.Pattern;
29 import javax.ws.rs.client.Client;
30 import javax.ws.rs.client.ClientBuilder;
31 import javax.ws.rs.core.Response;
32 import lombok.AccessLevel;
34 import org.apache.commons.lang3.StringUtils;
35 import org.onap.policy.apex.core.infrastructure.threading.ThreadUtilities;
36 import org.onap.policy.apex.service.engine.event.ApexEventException;
37 import org.onap.policy.apex.service.engine.event.ApexEventReceiver;
38 import org.onap.policy.apex.service.engine.event.ApexEventRuntimeException;
39 import org.onap.policy.apex.service.engine.event.ApexPluginsEventConsumer;
40 import org.onap.policy.apex.service.parameters.carriertechnology.RestPluginCarrierTechnologyParameters;
41 import org.onap.policy.apex.service.parameters.eventhandler.EventHandlerParameters;
42 import org.slf4j.Logger;
43 import org.slf4j.LoggerFactory;
46 * This class implements an Apex event consumer that receives events from a REST server.
48 * @author Liam Fallon (liam.fallon@ericsson.com)
50 public class ApexRestClientConsumer extends ApexPluginsEventConsumer {
51 // Get a reference to the logger
52 private static final Logger LOGGER = LoggerFactory.getLogger(ApexRestClientConsumer.class);
54 // The amount of time to wait in milliseconds between checks that the consumer thread has stopped
55 private static final long REST_CLIENT_WAIT_SLEEP_TIME = 50;
57 // The REST parameters read from the parameter service
58 private RestClientCarrierTechnologyParameters restConsumerProperties;
60 // The event receiver that will receive events from this consumer
61 private ApexEventReceiver eventReceiver;
63 // The HTTP client that makes a REST call to get an input event for Apex
64 @Setter(AccessLevel.PROTECTED)
65 private Client client;
67 // The pattern for filtering status code
68 private Pattern httpCodeFilterPattern = null;
71 public void init(final String consumerName, final EventHandlerParameters consumerParameters,
72 final ApexEventReceiver incomingEventReceiver) throws ApexEventException {
73 this.eventReceiver = incomingEventReceiver;
74 this.name = consumerName;
76 // Check and get the REST Properties
77 if (!(consumerParameters.getCarrierTechnologyParameters() instanceof RestClientCarrierTechnologyParameters)) {
78 final String errorMessage =
79 "specified consumer properties are not applicable to REST client consumer (" + this.name + ")";
80 LOGGER.warn(errorMessage);
81 throw new ApexEventException(errorMessage);
83 restConsumerProperties =
84 (RestClientCarrierTechnologyParameters) consumerParameters.getCarrierTechnologyParameters();
86 this.httpCodeFilterPattern = Pattern.compile(restConsumerProperties.getHttpCodeFilter());
88 // Check if the HTTP method has been set
89 if (restConsumerProperties.getHttpMethod() == null) {
90 restConsumerProperties.setHttpMethod(RestPluginCarrierTechnologyParameters.HttpMethod.GET);
93 if (!RestPluginCarrierTechnologyParameters.HttpMethod.GET.equals(restConsumerProperties.getHttpMethod())) {
94 final String errorMessage = "specified HTTP method of \"" + restConsumerProperties.getHttpMethod()
95 + "\" is invalid, only HTTP method \"GET\" "
96 + "is supported for event reception on REST client consumer (" + this.name + ")";
97 LOGGER.warn(errorMessage);
98 throw new ApexEventException(errorMessage);
101 // Initialize the HTTP client
102 client = ClientBuilder.newClient();
110 // The RequestRunner thread runs the get request for the event
111 Thread requestRunnerThread = null;
113 // The endless loop that receives events using REST calls
114 while (consumerThread.isAlive() && !stopOrderedFlag) {
115 // Create a new request if one is not in progress
116 if (requestRunnerThread == null || !requestRunnerThread.isAlive()) {
117 requestRunnerThread = new Thread(new RequestRunner());
118 requestRunnerThread.start();
121 ThreadUtilities.sleep(REST_CLIENT_WAIT_SLEEP_TIME);
132 stopOrderedFlag = true;
134 while (consumerThread.isAlive()) {
135 ThreadUtilities.sleep(REST_CLIENT_WAIT_SLEEP_TIME);
140 * This class is used to start a thread for each request issued.
142 * @author Liam Fallon (liam.fallon@ericsson.com)
144 private class RequestRunner implements Runnable {
151 final Response response = client.target(restConsumerProperties.getUrl()).request("application/json")
152 .headers(restConsumerProperties.getHttpHeadersAsMultivaluedMap()).get();
154 // Match the return code
155 Matcher isPass = httpCodeFilterPattern.matcher(String.valueOf(response.getStatus()));
157 // Check that status code
158 if (!isPass.matches()) {
159 final String errorMessage = "reception of event from URL \"" + restConsumerProperties.getUrl()
160 + "\" failed with status code " + response.getStatus() + " and message \""
161 + response.readEntity(String.class) + "\"";
162 LOGGER.warn(errorMessage);
163 throw new ApexEventRuntimeException(errorMessage);
166 // Get the event we received
167 final String eventJsonString = response.readEntity(String.class);
169 // Check there is content
170 if (StringUtils.isBlank(eventJsonString)) {
171 final String errorMessage =
172 "received an empty event from URL \"" + restConsumerProperties.getUrl() + "\"";
173 throw new ApexEventRuntimeException(errorMessage);
176 // Send the event into Apex
177 eventReceiver.receiveEvent(new Properties(), eventJsonString);
178 } catch (final Exception e) {
179 LOGGER.debug("error receiving events on thread {}", consumerThread.getName(), e);