899d4de11f837b78da3ccdfaba2f7d27a7525bd5
[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             throw new ApexEventException(errorMessage);
79         }
80         restConsumerProperties =
81                 (RestClientCarrierTechnologyParameters) consumerParameters.getCarrierTechnologyParameters();
82
83         this.httpCodeFilterPattern = Pattern.compile(restConsumerProperties.getHttpCodeFilter());
84
85         // Check if the HTTP method has been set
86         if (restConsumerProperties.getHttpMethod() == null) {
87             restConsumerProperties.setHttpMethod(RestPluginCarrierTechnologyParameters.HttpMethod.GET);
88         }
89
90         if (!RestPluginCarrierTechnologyParameters.HttpMethod.GET.equals(restConsumerProperties.getHttpMethod())) {
91             final String errorMessage = "specified HTTP method of \"" + restConsumerProperties.getHttpMethod()
92                     + "\" is invalid, only HTTP method \"GET\" "
93                     + "is supported for event reception on REST client consumer (" + this.name + ")";
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 var response = client.target(restConsumerProperties.getUrl()).request("application/json")
148                         .headers(restConsumerProperties.getHttpHeadersAsMultivaluedMap()).get();
149
150                 // Match the return code
151                 var 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                     throw new ApexEventRuntimeException(errorMessage);
159                 }
160
161                 // Get the event we received
162                 final var eventJsonString = response.readEntity(String.class);
163
164                 // Check there is content
165                 if (StringUtils.isBlank(eventJsonString)) {
166                     final String errorMessage =
167                             "received an empty event from URL \"" + restConsumerProperties.getUrl() + "\"";
168                     throw new ApexEventRuntimeException(errorMessage);
169                 }
170
171                 // Send the event into Apex
172                 eventReceiver.receiveEvent(new Properties(), eventJsonString);
173             } catch (final Exception e) {
174                 LOGGER.debug("error receiving events on thread {}", consumerThread.getName(), e);
175             }
176         }
177     }
178 }