a3d273dfd19fe605766b93a8a10ca83c512d2e9f
[policy/apex-pdp.git] / plugins / plugins-event / plugins-event-carrier / plugins-event-carrier-restclient / src / main / java / org / onap / policy / apex / plugins / event / carrier / restclient / ApexRestClientConsumer.java
1 /*-
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2016-2018 Ericsson. All rights reserved.
4  *  Modifications Copyright (C) 2019-2020 Nordix Foundation.
5  * ================================================================================
6  * Licensed under the Apache License, Version 2.0 (the "License");
7  * you may not use this file except in compliance with the License.
8  * You may obtain a copy of the License at
9  *
10  *      http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing, software
13  * distributed under the License is distributed on an "AS IS" BASIS,
14  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  * See the License for the specific language governing permissions and
16  * limitations under the License.
17  *
18  * SPDX-License-Identifier: Apache-2.0
19  * ============LICENSE_END=========================================================
20  */
21
22 package org.onap.policy.apex.plugins.event.carrier.restclient;
23
24 import java.util.Properties;
25 import java.util.regex.Matcher;
26 import java.util.regex.Pattern;
27
28 import javax.ws.rs.client.Client;
29 import javax.ws.rs.client.ClientBuilder;
30 import javax.ws.rs.core.Response;
31
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 Key for property
56     private static final String HTTP_CODE_STATUS = "HTTP_CODE_STATUS";
57
58     // The REST parameters read from the parameter service
59     private RestClientCarrierTechnologyParameters restConsumerProperties;
60
61     // The event receiver that will receive events from this consumer
62     private ApexEventReceiver eventReceiver;
63
64     // The HTTP client that makes a REST call to get an input event for Apex
65     private Client client;
66
67     // The pattern for filtering status code
68     private Pattern httpCodeFilterPattern = null;
69
70     @Override
71     public void init(final String consumerName, final EventHandlerParameters consumerParameters,
72             final ApexEventReceiver incomingEventReceiver) throws ApexEventException {
73         this.eventReceiver = incomingEventReceiver;
74         this.name = consumerName;
75
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);
82         }
83         restConsumerProperties =
84                 (RestClientCarrierTechnologyParameters) consumerParameters.getCarrierTechnologyParameters();
85
86         this.httpCodeFilterPattern = Pattern.compile(restConsumerProperties.getHttpCodeFilter());
87
88         // Check if the HTTP method has been set
89         if (restConsumerProperties.getHttpMethod() == null) {
90             restConsumerProperties.setHttpMethod(RestPluginCarrierTechnologyParameters.HttpMethod.GET);
91         }
92
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);
99         }
100
101         // Initialize the HTTP client
102         client = ClientBuilder.newClient();
103     }
104
105     /**
106      * {@inheritDoc}.
107      */
108     @Override
109     public void run() {
110         // The RequestRunner thread runs the get request for the event
111         Thread requestRunnerThread = null;
112
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();
119             }
120
121             ThreadUtilities.sleep(REST_CLIENT_WAIT_SLEEP_TIME);
122         }
123
124         client.close();
125     }
126
127     /**
128      * {@inheritDoc}.
129      */
130     @Override
131     public void stop() {
132         stopOrderedFlag = true;
133
134         while (consumerThread.isAlive()) {
135             ThreadUtilities.sleep(REST_CLIENT_WAIT_SLEEP_TIME);
136         }
137     }
138
139     /**
140      * This class is used to start a thread for each request issued.
141      *
142      * @author Liam Fallon (liam.fallon@ericsson.com)
143      */
144     private class RequestRunner implements Runnable {
145         /**
146          * {@inheritDoc}.
147          */
148         @Override
149         public void run() {
150             try {
151                 final Response response = client.target(restConsumerProperties.getUrl()).request("application/json")
152                         .headers(restConsumerProperties.getHttpHeadersAsMultivaluedMap()).get();
153
154                 // Match the return code
155                 Matcher isPass = httpCodeFilterPattern.matcher(String.valueOf(response.getStatus()));
156
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);
164                 }
165
166                 // Get the event we received
167                 final String eventJsonString = response.readEntity(String.class);
168
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);
174                 }
175
176                 // build a key and value property in excutionProperties
177                 Properties executionProperties = new Properties();
178                 executionProperties.put(HTTP_CODE_STATUS, response.getStatus());
179
180                 // Send the event into Apex
181                 eventReceiver.receiveEvent(executionProperties, eventJsonString);
182             } catch (final Exception e) {
183                 LOGGER.warn("error receiving events on thread {}", consumerThread.getName(), e);
184             }
185         }
186     }
187
188     /**
189      * Hook for unit test mocking of HTTP client.
190      *
191      * @param client the mocked client
192      */
193     protected void setClient(final Client client) {
194         this.client = client;
195     }
196 }