565587f62d364e3ff5eb01b4cb1e4a3a16716928
[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.Optional;
26 import java.util.Properties;
27 import java.util.Set;
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 import org.onap.policy.apex.service.engine.event.ApexEventException;
33 import org.onap.policy.apex.service.engine.event.ApexEventRuntimeException;
34 import org.onap.policy.apex.service.engine.event.ApexPluginsEventProducer;
35 import org.onap.policy.apex.service.parameters.carriertechnology.RestPluginCarrierTechnologyParameters;
36 import org.onap.policy.apex.service.parameters.eventhandler.EventHandlerParameters;
37 import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure;
38 import org.onap.policy.common.endpoints.utils.NetLoggerUtil;
39 import org.onap.policy.common.endpoints.utils.NetLoggerUtil.EventType;
40 import org.slf4j.Logger;
41 import org.slf4j.LoggerFactory;
42
43 /**
44  * Concrete implementation of an Apex event producer that sends events using REST.
45  *
46  * @author Joss Armstrong (joss.armstrong@ericsson.com)
47  *
48  */
49 public class ApexRestClientProducer extends ApexPluginsEventProducer {
50     private static final Logger LOGGER = LoggerFactory.getLogger(ApexRestClientProducer.class);
51
52     // The HTTP client that makes a REST call with an event from Apex
53     private Client client;
54
55     // The REST carrier properties
56     private RestClientCarrierTechnologyParameters restProducerProperties;
57
58     /**
59      * {@inheritDoc}.
60      */
61     @Override
62     public void init(final String producerName, final EventHandlerParameters producerParameters)
63             throws ApexEventException {
64         this.name = producerName;
65
66         // Check and get the REST Properties
67         if (!(producerParameters.getCarrierTechnologyParameters() instanceof RestClientCarrierTechnologyParameters)) {
68             final String errorMessage =
69                     "specified producer properties are not applicable to REST client producer (" + this.name + ")";
70             LOGGER.warn(errorMessage);
71             throw new ApexEventException(errorMessage);
72         }
73         restProducerProperties =
74                 (RestClientCarrierTechnologyParameters) producerParameters.getCarrierTechnologyParameters();
75
76         // Check if the HTTP method has been set
77         if (restProducerProperties.getHttpMethod() == null) {
78             restProducerProperties.setHttpMethod(RestPluginCarrierTechnologyParameters.HttpMethod.POST);
79         }
80
81         if (!RestPluginCarrierTechnologyParameters.HttpMethod.POST.equals(restProducerProperties.getHttpMethod())
82                 && !RestPluginCarrierTechnologyParameters.HttpMethod.PUT
83                         .equals(restProducerProperties.getHttpMethod())) {
84             final String errorMessage = "specified HTTP method of \"" + restProducerProperties.getHttpMethod()
85                     + "\" is invalid, only HTTP methods \"POST\" and \"PUT\" are supported "
86                     + "for event sending on REST client producer (" + this.name + ")";
87             LOGGER.warn(errorMessage);
88             throw new ApexEventException(errorMessage);
89         }
90
91         // Initialize the HTTP client
92         client = ClientBuilder.newClient();
93     }
94
95     /**
96      * {@inheritDoc}.
97      */
98     @Override
99     public void sendEvent(final long executionId, final Properties executionProperties, final String eventName,
100             final Object event) {
101         super.sendEvent(executionId, executionProperties, eventName, event);
102
103         String untaggedUrl = restProducerProperties.getUrl();
104         if (executionProperties != null) {
105             Set<String> names = restProducerProperties.getKeysFromUrl();
106             Set<String> inputProperty = executionProperties.stringPropertyNames();
107
108             // @formatter:off
109             names.stream().map(Optional::of).forEach(op ->
110                 op.filter(inputProperty::contains)
111                     .orElseThrow(() -> new ApexEventRuntimeException(
112                         "key \"" + op.get() + "\" specified on url \"" + restProducerProperties.getUrl()
113                         + "\" not found in execution properties passed by the current policy"))
114             );
115
116             untaggedUrl = names.stream().reduce(untaggedUrl,
117                 (acc, str) -> acc.replace("{" + str + "}", (String) executionProperties.get(str)));
118             // @formatter:on
119         }
120
121         NetLoggerUtil.log(EventType.OUT, CommInfrastructure.REST, untaggedUrl, event.toString());
122         // Send the event as a REST request
123         final Response response = sendEventAsRestRequest(untaggedUrl, (String) event);
124
125         NetLoggerUtil.log(EventType.IN, CommInfrastructure.REST, untaggedUrl, response.readEntity(String.class));
126
127         // Check that the request worked
128         if (response.getStatus() != Response.Status.OK.getStatusCode()) {
129             final String errorMessage = "send of event to URL \"" + untaggedUrl + "\" using HTTP \""
130                     + restProducerProperties.getHttpMethod() + "\" failed with status code " + response.getStatus();
131             throw new ApexEventRuntimeException(errorMessage);
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 }