4f95c5636ee57db59202ed90a064fcedc2d7a037
[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  * ================================================================================
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
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
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.
18  *
19  * SPDX-License-Identifier: Apache-2.0
20  * ============LICENSE_END=========================================================
21  */
22
23 package org.onap.policy.apex.plugins.event.carrier.restclient;
24
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;
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 REST parameters read from the parameter service
55     private RestClientCarrierTechnologyParameters restConsumerProperties;
56
57     // The event receiver that will receive events from this consumer
58     private ApexEventReceiver eventReceiver;
59
60     // The HTTP client that makes a REST call to get an input event for Apex
61     private Client client;
62
63     // The pattern for filtering status code
64     private Pattern httpCodeFilterPattern = null;
65
66     @Override
67     public void init(final String consumerName, final EventHandlerParameters consumerParameters,
68             final ApexEventReceiver incomingEventReceiver) throws ApexEventException {
69         this.eventReceiver = incomingEventReceiver;
70         this.name = consumerName;
71
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);
78         }
79         restConsumerProperties =
80                 (RestClientCarrierTechnologyParameters) consumerParameters.getCarrierTechnologyParameters();
81
82         this.httpCodeFilterPattern = Pattern.compile(restConsumerProperties.getHttpCodeFilter());
83
84         // Check if the HTTP method has been set
85         if (restConsumerProperties.getHttpMethod() == null) {
86             restConsumerProperties.setHttpMethod(RestPluginCarrierTechnologyParameters.HttpMethod.GET);
87         }
88
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);
95         }
96
97         // Initialize the HTTP client
98         client = ClientBuilder.newClient();
99     }
100
101     /**
102      * {@inheritDoc}.
103      */
104     @Override
105     public void run() {
106         // The RequestRunner thread runs the get request for the event
107         Thread requestRunnerThread = null;
108
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();
115             }
116
117             ThreadUtilities.sleep(REST_CLIENT_WAIT_SLEEP_TIME);
118         }
119
120         client.close();
121     }
122
123     /**
124      * {@inheritDoc}.
125      */
126     @Override
127     public void stop() {
128         stopOrderedFlag = true;
129
130         while (consumerThread.isAlive()) {
131             ThreadUtilities.sleep(REST_CLIENT_WAIT_SLEEP_TIME);
132         }
133     }
134
135     /**
136      * This class is used to start a thread for each request issued.
137      *
138      * @author Liam Fallon (liam.fallon@ericsson.com)
139      */
140     private class RequestRunner implements Runnable {
141         /**
142          * {@inheritDoc}.
143          */
144         @Override
145         public void run() {
146             try {
147                 final Response response = client.target(restConsumerProperties.getUrl()).request("application/json")
148                         .headers(restConsumerProperties.getHttpHeadersAsMultivaluedMap()).get();
149
150                 // Match the return code
151                 Matcher isPass = httpCodeFilterPattern.matcher(String.valueOf(response.getStatus()));
152
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);
160                 }
161
162                 // Get the event we received
163                 final String eventJsonString = response.readEntity(String.class);
164
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);
170                 }
171
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);
176             }
177         }
178     }
179
180     /**
181      * Hook for unit test mocking of HTTP client.
182      *
183      * @param client the mocked client
184      */
185     protected void setClient(final Client client) {
186         this.client = client;
187     }
188 }