956345cd4331094bb3b3e6a2a39fcd1ca541f191
[policy/apex-pdp.git] /
1 /*-
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
11  *
12  *      http://www.apache.org/licenses/LICENSE-2.0
13  *
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.
19  *
20  * SPDX-License-Identifier: Apache-2.0
21  * ============LICENSE_END=========================================================
22  */
23
24 package org.onap.policy.apex.plugins.event.carrier.restclient;
25
26 import java.util.Properties;
27 import java.util.regex.Pattern;
28 import javax.ws.rs.client.Client;
29 import javax.ws.rs.client.ClientBuilder;
30 import lombok.AccessLevel;
31 import lombok.Setter;
32 import org.apache.commons.lang3.StringUtils;
33 import org.onap.policy.apex.core.infrastructure.threading.ThreadUtilities;
34 import org.onap.policy.apex.service.engine.event.ApexEventException;
35 import org.onap.policy.apex.service.engine.event.ApexEventReceiver;
36 import org.onap.policy.apex.service.engine.event.ApexEventRuntimeException;
37 import org.onap.policy.apex.service.engine.event.ApexPluginsEventConsumer;
38 import org.onap.policy.apex.service.parameters.carriertechnology.RestPluginCarrierTechnologyParameters;
39 import org.onap.policy.apex.service.parameters.eventhandler.EventHandlerParameters;
40 import org.slf4j.Logger;
41 import org.slf4j.LoggerFactory;
42
43 /**
44  * This class implements an Apex event consumer that receives events from a REST server.
45  *
46  * @author Liam Fallon (liam.fallon@ericsson.com)
47  */
48 public class ApexRestClientConsumer extends ApexPluginsEventConsumer {
49     // Get a reference to the logger
50     private static final Logger LOGGER = LoggerFactory.getLogger(ApexRestClientConsumer.class);
51
52     // The amount of time to wait in milliseconds between checks that the consumer thread has stopped
53     private static final long REST_CLIENT_WAIT_SLEEP_TIME = 50;
54
55     // The REST parameters read from the parameter service
56     private RestClientCarrierTechnologyParameters restConsumerProperties;
57
58     // The event receiver that will receive events from this consumer
59     private ApexEventReceiver eventReceiver;
60
61     // The HTTP client that makes a REST call to get an input event for Apex
62     @Setter(AccessLevel.PROTECTED)
63     private Client client;
64
65     // The pattern for filtering status code
66     private Pattern httpCodeFilterPattern = null;
67
68     @Override
69     public void init(final String consumerName, final EventHandlerParameters consumerParameters,
70             final ApexEventReceiver incomingEventReceiver) throws ApexEventException {
71         this.eventReceiver = incomingEventReceiver;
72         this.name = consumerName;
73
74         // Check and get the REST Properties
75         if (!(consumerParameters.getCarrierTechnologyParameters() instanceof RestClientCarrierTechnologyParameters)) {
76             final String errorMessage =
77                     "specified consumer properties are not applicable to REST client consumer (" + this.name + ")";
78             LOGGER.warn(errorMessage);
79             throw new ApexEventException(errorMessage);
80         }
81         restConsumerProperties =
82                 (RestClientCarrierTechnologyParameters) consumerParameters.getCarrierTechnologyParameters();
83
84         this.httpCodeFilterPattern = Pattern.compile(restConsumerProperties.getHttpCodeFilter());
85
86         // Check if the HTTP method has been set
87         if (restConsumerProperties.getHttpMethod() == null) {
88             restConsumerProperties.setHttpMethod(RestPluginCarrierTechnologyParameters.HttpMethod.GET);
89         }
90
91         if (!RestPluginCarrierTechnologyParameters.HttpMethod.GET.equals(restConsumerProperties.getHttpMethod())) {
92             final String errorMessage = "specified HTTP method of \"" + restConsumerProperties.getHttpMethod()
93                     + "\" is invalid, only HTTP method \"GET\" "
94                     + "is supported for event reception on REST client consumer (" + this.name + ")";
95             LOGGER.warn(errorMessage);
96             throw new ApexEventException(errorMessage);
97         }
98
99         // Initialize the HTTP client
100         client = ClientBuilder.newClient();
101     }
102
103     /**
104      * {@inheritDoc}.
105      */
106     @Override
107     public void run() {
108         // The RequestRunner thread runs the get request for the event
109         Thread requestRunnerThread = null;
110
111         // The endless loop that receives events using REST calls
112         while (consumerThread.isAlive() && !stopOrderedFlag) {
113             // Create a new request if one is not in progress
114             if (requestRunnerThread == null || !requestRunnerThread.isAlive()) {
115                 requestRunnerThread = new Thread(new RequestRunner());
116                 requestRunnerThread.start();
117             }
118
119             ThreadUtilities.sleep(REST_CLIENT_WAIT_SLEEP_TIME);
120         }
121
122         client.close();
123     }
124
125     /**
126      * {@inheritDoc}.
127      */
128     @Override
129     public void stop() {
130         stopOrderedFlag = true;
131
132         while (consumerThread.isAlive()) {
133             ThreadUtilities.sleep(REST_CLIENT_WAIT_SLEEP_TIME);
134         }
135     }
136
137     /**
138      * This class is used to start a thread for each request issued.
139      *
140      * @author Liam Fallon (liam.fallon@ericsson.com)
141      */
142     private class RequestRunner implements Runnable {
143         /**
144          * {@inheritDoc}.
145          */
146         @Override
147         public void run() {
148             try {
149                 final var response = client.target(restConsumerProperties.getUrl()).request("application/json")
150                         .headers(restConsumerProperties.getHttpHeadersAsMultivaluedMap()).get();
151
152                 // Match the return code
153                 var isPass = httpCodeFilterPattern.matcher(String.valueOf(response.getStatus()));
154
155                 // Check that status code
156                 if (!isPass.matches()) {
157                     final String errorMessage = "reception of event from URL \"" + restConsumerProperties.getUrl()
158                             + "\" failed with status code " + response.getStatus() + " and message \""
159                             + response.readEntity(String.class) + "\"";
160                     LOGGER.warn(errorMessage);
161                     throw new ApexEventRuntimeException(errorMessage);
162                 }
163
164                 // Get the event we received
165                 final var eventJsonString = response.readEntity(String.class);
166
167                 // Check there is content
168                 if (StringUtils.isBlank(eventJsonString)) {
169                     final String errorMessage =
170                             "received an empty event from URL \"" + restConsumerProperties.getUrl() + "\"";
171                     throw new ApexEventRuntimeException(errorMessage);
172                 }
173
174                 // Send the event into Apex
175                 eventReceiver.receiveEvent(new Properties(), eventJsonString);
176             } catch (final Exception e) {
177                 LOGGER.debug("error receiving events on thread {}", consumerThread.getName(), e);
178             }
179         }
180     }
181 }