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