aa8185fdbf33f57808644fcfcf4315d95736e4e4
[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  * ================================================================================
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
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
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.eventhandler.EventHandlerParameters;
39 import org.slf4j.Logger;
40 import org.slf4j.LoggerFactory;
41
42 /**
43  * This class implements an Apex event consumer that receives events from a REST server.
44  *
45  * @author Liam Fallon (liam.fallon@ericsson.com)
46  */
47 public class ApexRestClientConsumer extends ApexPluginsEventConsumer {
48     // Get a reference to the logger
49     private static final Logger LOGGER = LoggerFactory.getLogger(ApexRestClientConsumer.class);
50
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;
53
54     // The Key for property
55     private static final String HTTP_CODE_STATUS = "HTTP_CODE_STATUS";
56
57     // The REST parameters read from the parameter service
58     private RestClientCarrierTechnologyParameters restConsumerProperties;
59
60     // The event receiver that will receive events from this consumer
61     private ApexEventReceiver eventReceiver;
62
63     // The HTTP client that makes a REST call to get an input event for Apex
64     private Client client;
65
66     // The pattern for filtering status code
67     private Pattern httpCodeFilterPattern = null;
68
69     @Override
70     public void init(final String consumerName, final EventHandlerParameters consumerParameters,
71             final ApexEventReceiver incomingEventReceiver) throws ApexEventException {
72         this.eventReceiver = incomingEventReceiver;
73         this.name = consumerName;
74
75         // Check and get the REST Properties
76         if (!(consumerParameters.getCarrierTechnologyParameters() instanceof RestClientCarrierTechnologyParameters)) {
77             final String errorMessage =
78                     "specified consumer properties are not applicable to REST client consumer (" + this.name + ")";
79             LOGGER.warn(errorMessage);
80             throw new ApexEventException(errorMessage);
81         }
82         restConsumerProperties =
83                 (RestClientCarrierTechnologyParameters) consumerParameters.getCarrierTechnologyParameters();
84
85         this.httpCodeFilterPattern = Pattern.compile(restConsumerProperties.getHttpCodeFilter());
86
87         // Check if the HTTP method has been set
88         if (restConsumerProperties.getHttpMethod() == null) {
89             restConsumerProperties.setHttpMethod(RestClientCarrierTechnologyParameters.HttpMethod.GET);
90         }
91
92         if (!RestClientCarrierTechnologyParameters.HttpMethod.GET.equals(restConsumerProperties.getHttpMethod())) {
93             final String errorMessage = "specified HTTP method of \"" + restConsumerProperties.getHttpMethod()
94                     + "\" is invalid, only HTTP method \"GET\" "
95                     + "is supported for event reception on REST client consumer (" + this.name + ")";
96             LOGGER.warn(errorMessage);
97             throw new ApexEventException(errorMessage);
98         }
99
100         // Initialize the HTTP client
101         client = ClientBuilder.newClient();
102     }
103
104     /**
105      * {@inheritDoc}.
106      */
107     @Override
108     public void run() {
109         // The RequestRunner thread runs the get request for the event
110         Thread requestRunnerThread = null;
111
112         // The endless loop that receives events using REST calls
113         while (consumerThread.isAlive() && !stopOrderedFlag) {
114             // Create a new request if one is not in progress
115             if (requestRunnerThread == null || !requestRunnerThread.isAlive()) {
116                 requestRunnerThread = new Thread(new RequestRunner());
117                 requestRunnerThread.start();
118             }
119
120             ThreadUtilities.sleep(REST_CLIENT_WAIT_SLEEP_TIME);
121         }
122
123         client.close();
124     }
125
126     /**
127      * {@inheritDoc}.
128      */
129     @Override
130     public void stop() {
131         stopOrderedFlag = true;
132
133         while (consumerThread.isAlive()) {
134             ThreadUtilities.sleep(REST_CLIENT_WAIT_SLEEP_TIME);
135         }
136     }
137
138     /**
139      * This class is used to start a thread for each request issued.
140      *
141      * @author Liam Fallon (liam.fallon@ericsson.com)
142      */
143     private class RequestRunner implements Runnable {
144         /**
145          * {@inheritDoc}.
146          */
147         @Override
148         public void run() {
149             try {
150                 final Response response = client.target(restConsumerProperties.getUrl()).request("application/json")
151                         .headers(restConsumerProperties.getHttpHeadersAsMultivaluedMap()).get();
152
153                 // Match the return code
154                 Matcher isPass = httpCodeFilterPattern.matcher(String.valueOf(response.getStatus()));
155
156                 // Check that status code
157                 if (!isPass.matches()) {
158                     final String errorMessage = "reception of event from URL \"" + restConsumerProperties.getUrl()
159                             + "\" failed with status code " + response.getStatus() + " and message \""
160                             + response.readEntity(String.class) + "\"";
161                     LOGGER.warn(errorMessage);
162                     throw new ApexEventRuntimeException(errorMessage);
163                 }
164
165                 // Get the event we received
166                 final String eventJsonString = response.readEntity(String.class);
167
168                 // Check there is content
169                 if (StringUtils.isBlank(eventJsonString)) {
170                     final String errorMessage =
171                             "received an empty event from URL \"" + restConsumerProperties.getUrl() + "\"";
172                     throw new ApexEventRuntimeException(errorMessage);
173                 }
174
175                 // build a key and value property in excutionProperties
176                 Properties executionProperties = new Properties();
177                 executionProperties.put(HTTP_CODE_STATUS, response.getStatus());
178
179                 // Send the event into Apex
180                 eventReceiver.receiveEvent(executionProperties, eventJsonString);
181             } catch (final Exception e) {
182                 LOGGER.warn("error receiving events on thread {}", consumerThread.getName(), e);
183             }
184         }
185     }
186
187     /**
188      * Hook for unit test mocking of HTTP client.
189      *
190      * @param client the mocked client
191      */
192     protected void setClient(final Client client) {
193         this.client = client;
194     }
195 }