Changes for checkstyle 8.32
[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 / ApexRestClientProducer.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.Optional;
25 import java.util.Properties;
26 import java.util.Set;
27 import javax.ws.rs.client.Client;
28 import javax.ws.rs.client.ClientBuilder;
29 import javax.ws.rs.client.Entity;
30 import javax.ws.rs.core.Response;
31 import org.onap.policy.apex.service.engine.event.ApexEventException;
32 import org.onap.policy.apex.service.engine.event.ApexEventRuntimeException;
33 import org.onap.policy.apex.service.engine.event.ApexPluginsEventProducer;
34 import org.onap.policy.apex.service.parameters.carriertechnology.RestPluginCarrierTechnologyParameters;
35 import org.onap.policy.apex.service.parameters.eventhandler.EventHandlerParameters;
36 import org.slf4j.Logger;
37 import org.slf4j.LoggerFactory;
38
39 /**
40  * Concrete implementation of an Apex event producer that sends events using REST.
41  *
42  * @author Joss Armstrong (joss.armstrong@ericsson.com)
43  *
44  */
45 public class ApexRestClientProducer extends ApexPluginsEventProducer {
46     private static final Logger LOGGER = LoggerFactory.getLogger(ApexRestClientProducer.class);
47
48     // The HTTP client that makes a REST call with an event from Apex
49     private Client client;
50
51     // The REST carrier properties
52     private RestClientCarrierTechnologyParameters restProducerProperties;
53
54     /**
55      * {@inheritDoc}.
56      */
57     @Override
58     public void init(final String producerName, final EventHandlerParameters producerParameters)
59             throws ApexEventException {
60         this.name = producerName;
61
62         // Check and get the REST Properties
63         if (!(producerParameters.getCarrierTechnologyParameters() instanceof RestClientCarrierTechnologyParameters)) {
64             final String errorMessage =
65                     "specified producer properties are not applicable to REST client producer (" + this.name + ")";
66             LOGGER.warn(errorMessage);
67             throw new ApexEventException(errorMessage);
68         }
69         restProducerProperties =
70                 (RestClientCarrierTechnologyParameters) producerParameters.getCarrierTechnologyParameters();
71
72         // Check if the HTTP method has been set
73         if (restProducerProperties.getHttpMethod() == null) {
74             restProducerProperties.setHttpMethod(RestPluginCarrierTechnologyParameters.HttpMethod.POST);
75         }
76
77         if (!RestPluginCarrierTechnologyParameters.HttpMethod.POST.equals(restProducerProperties.getHttpMethod())
78                 && !RestPluginCarrierTechnologyParameters.HttpMethod.PUT
79                         .equals(restProducerProperties.getHttpMethod())) {
80             final String errorMessage = "specified HTTP method of \"" + restProducerProperties.getHttpMethod()
81                     + "\" is invalid, only HTTP methods \"POST\" and \"PUT\" are supported "
82                     + "for event sending on REST client producer (" + this.name + ")";
83             LOGGER.warn(errorMessage);
84             throw new ApexEventException(errorMessage);
85         }
86
87         // Initialize the HTTP client
88         client = ClientBuilder.newClient();
89     }
90
91     /**
92      * {@inheritDoc}.
93      */
94     @Override
95     public void sendEvent(final long executionId, final Properties executionProperties, final String eventName,
96             final Object event) {
97         super.sendEvent(executionId, executionProperties, eventName, event);
98
99         String untaggedUrl = restProducerProperties.getUrl();
100         if (executionProperties != null) {
101             Set<String> names = restProducerProperties.getKeysFromUrl();
102             Set<String> inputProperty = executionProperties.stringPropertyNames();
103
104             // @formatter:off
105             names.stream().map(Optional::of).forEach(op ->
106                 op.filter(inputProperty::contains)
107                     .orElseThrow(() -> new ApexEventRuntimeException(
108                         "key \"" + op.get() + "\" specified on url \"" + restProducerProperties.getUrl()
109                         + "\" not found in execution properties passed by the current policy"))
110             );
111
112             untaggedUrl = names.stream().reduce(untaggedUrl,
113                 (acc, str) -> acc.replace("{" + str + "}", (String) executionProperties.get(str)));
114             // @formatter:on
115         }
116
117         // Send the event as a REST request
118         final Response response = sendEventAsRestRequest(untaggedUrl, (String) event);
119
120         // Check that the request worked
121         if (response.getStatus() != Response.Status.OK.getStatusCode()) {
122             final String errorMessage = "send of event to URL \"" + untaggedUrl + "\" using HTTP \""
123                     + restProducerProperties.getHttpMethod() + "\" failed with status code " + response.getStatus()
124                     + " and message \"" + response.readEntity(String.class) + "\", event:\n" + event;
125             LOGGER.warn(errorMessage);
126             throw new ApexEventRuntimeException(errorMessage);
127         }
128
129         if (LOGGER.isTraceEnabled()) {
130             LOGGER.trace("event sent from engine using {} to URL {} with HTTP {} : {} and response {} ", this.name,
131                     untaggedUrl, restProducerProperties.getHttpMethod(), event, response);
132         }
133     }
134
135     /**
136      * {@inheritDoc}.
137      */
138     @Override
139     public void stop() {
140         // Close the HTTP session
141         client.close();
142     }
143
144     /**
145      * Send the event as a JSON string as a REST request.
146      *
147      * @param event the event to send
148      * @return the response to the JSON request
149      */
150     private Response sendEventAsRestRequest(final String untaggedUrl, final String event) {
151         // We have already checked that it is a PUT or POST request
152         if (RestPluginCarrierTechnologyParameters.HttpMethod.POST.equals(restProducerProperties.getHttpMethod())) {
153             return client.target(untaggedUrl).request("application/json")
154                     .headers(restProducerProperties.getHttpHeadersAsMultivaluedMap()).post(Entity.json(event));
155         } else {
156             return client.target(untaggedUrl).request("application/json")
157                     .headers(restProducerProperties.getHttpHeadersAsMultivaluedMap()).put(Entity.json(event));
158         }
159     }
160
161     /**
162      * Hook for unit test mocking of HTTP client.
163      *
164      * @param client the mocked client
165      */
166     protected void setClient(final Client client) {
167         this.client = client;
168     }
169 }