ea60e391524ad4ca5171371c3d061cb79a0093ea
[policy/apex-pdp.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2016-2018 Ericsson. All rights reserved.
4  *  Modifications Copyright (C) 2019 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.EnumMap;
25 import java.util.Map;
26 import java.util.Optional;
27 import java.util.Properties;
28 import java.util.Set;
29
30 import javax.ws.rs.client.Client;
31 import javax.ws.rs.client.ClientBuilder;
32 import javax.ws.rs.client.Entity;
33 import javax.ws.rs.core.Response;
34
35 import org.onap.policy.apex.service.engine.event.ApexEventException;
36 import org.onap.policy.apex.service.engine.event.ApexEventProducer;
37 import org.onap.policy.apex.service.engine.event.ApexEventRuntimeException;
38 import org.onap.policy.apex.service.engine.event.PeeredReference;
39 import org.onap.policy.apex.service.engine.event.SynchronousEventCache;
40 import org.onap.policy.apex.service.parameters.eventhandler.EventHandlerParameters;
41 import org.onap.policy.apex.service.parameters.eventhandler.EventHandlerPeeredMode;
42 import org.slf4j.Logger;
43 import org.slf4j.LoggerFactory;
44
45 /**
46  * Concrete implementation of an Apex event producer that sends events using REST.
47  *
48  * @author Joss Armstrong (joss.armstrong@ericsson.com)
49  *
50  */
51 public class ApexRestClientProducer implements ApexEventProducer {
52     private static final Logger LOGGER = LoggerFactory.getLogger(ApexRestClientProducer.class);
53
54     // The HTTP client that makes a REST call with an event from Apex
55     private Client client;
56
57     // The REST carrier properties
58     private RestClientCarrierTechnologyParameters restProducerProperties;
59
60     // The name for this producer
61     private String name = null;
62
63     // The peer references for this event handler
64     private Map<EventHandlerPeeredMode, PeeredReference> peerReferenceMap = new EnumMap<>(EventHandlerPeeredMode.class);
65
66     /**
67      * {@inheritDoc}.
68      */
69     @Override
70     public void init(final String producerName, final EventHandlerParameters producerParameters)
71             throws ApexEventException {
72         this.name = producerName;
73
74         // Check and get the REST Properties
75         if (!(producerParameters.getCarrierTechnologyParameters() instanceof RestClientCarrierTechnologyParameters)) {
76             final String errorMessage =
77                     "specified producer properties are not applicable to REST client producer (" + this.name + ")";
78             LOGGER.warn(errorMessage);
79             throw new ApexEventException(errorMessage);
80         }
81         restProducerProperties =
82                 (RestClientCarrierTechnologyParameters) producerParameters.getCarrierTechnologyParameters();
83
84         // Check if the HTTP method has been set
85         if (restProducerProperties.getHttpMethod() == null) {
86             restProducerProperties.setHttpMethod(RestClientCarrierTechnologyParameters.HttpMethod.POST);
87         }
88
89         if (!RestClientCarrierTechnologyParameters.HttpMethod.POST.equals(restProducerProperties.getHttpMethod())
90                 && !RestClientCarrierTechnologyParameters.HttpMethod.PUT
91                         .equals(restProducerProperties.getHttpMethod())) {
92             final String errorMessage = "specified HTTP method of \"" + restProducerProperties.getHttpMethod()
93                     + "\" is invalid, only HTTP methods \"POST\" and \"PUT\" are supproted "
94                     + "for event sending on REST client producer (" + this.name + ")";
95             LOGGER.warn(errorMessage);
96             throw new ApexEventException(errorMessage);
97         }
98
99         // Initialize the HTTP client
100         client = ClientBuilder.newClient();
101     }
102
103     /**
104      * {@inheritDoc}.
105      */
106     @Override
107     public String getName() {
108         return name;
109     }
110
111     /**
112      * {@inheritDoc}.
113      */
114     @Override
115     public PeeredReference getPeeredReference(final EventHandlerPeeredMode peeredMode) {
116         return peerReferenceMap.get(peeredMode);
117     }
118
119     /**
120      * {@inheritDoc}.
121      */
122     @Override
123     public void setPeeredReference(final EventHandlerPeeredMode peeredMode, final PeeredReference peeredReference) {
124         peerReferenceMap.put(peeredMode, peeredReference);
125     }
126
127     /**
128      * {@inheritDoc}.
129      */
130     @Override
131     public void sendEvent(final long executionId, final Properties executionProperties, final String eventName,
132             final Object event) {
133         // Check if this is a synchronized event, if so we have received a reply
134         final SynchronousEventCache synchronousEventCache =
135                 (SynchronousEventCache) peerReferenceMap.get(EventHandlerPeeredMode.SYNCHRONOUS);
136         if (synchronousEventCache != null) {
137             synchronousEventCache.removeCachedEventToApexIfExists(executionId);
138         }
139
140         String untaggedUrl = restProducerProperties.getUrl();
141         if (executionProperties != null) {
142             Set<String> names = restProducerProperties.getKeysFromUrl();
143             Set<String> inputProperty = executionProperties.stringPropertyNames();
144
145             names.stream().map(Optional::of).forEach(op ->
146                 op.filter(inputProperty::contains)
147                     .orElseThrow(() -> new ApexEventRuntimeException(
148                         "key\"" + op.get() + "\"specified on url \"" + restProducerProperties.getUrl()
149                         + "\"not found in execution properties passed by the current policy"))
150             );
151
152             untaggedUrl = names.stream().reduce(untaggedUrl,
153                 (acc, str) -> acc.replace("{" + str + "}", (String) executionProperties.get(str)));
154         }
155
156         // Send the event as a REST request
157         final Response response = sendEventAsRestRequest(untaggedUrl, (String) event);
158
159         // Check that the request worked
160         if (response.getStatus() != Response.Status.OK.getStatusCode()) {
161             final String errorMessage = "send of event to URL \"" + untaggedUrl + "\" using HTTP \""
162                     + restProducerProperties.getHttpMethod() + "\" failed with status code " + response.getStatus()
163                     + " and message \"" + response.readEntity(String.class) + "\", event:\n" + event;
164             LOGGER.warn(errorMessage);
165             throw new ApexEventRuntimeException(errorMessage);
166         }
167
168         if (LOGGER.isTraceEnabled()) {
169             LOGGER.trace("event sent from engine using {} to URL {} with HTTP {} : {} and response {} ", this.name,
170                 untaggedUrl, restProducerProperties.getHttpMethod(), event, response);
171         }
172     }
173
174     /**
175      * {@inheritDoc}.
176      */
177     @Override
178     public void stop() {
179         // Close the HTTP session
180         client.close();
181     }
182
183     /**
184      * Send the event as a JSON string as a REST request.
185      *
186      * @param event the event to send
187      * @return the response to the JSON request
188      */
189     private Response sendEventAsRestRequest(final String untaggedUrl, final String event) {
190         // We have already checked that it is a PUT or POST request
191         if (RestClientCarrierTechnologyParameters.HttpMethod.POST.equals(restProducerProperties.getHttpMethod())) {
192             return client.target(untaggedUrl).request("application/json")
193                     .headers(restProducerProperties.getHttpHeadersAsMultivaluedMap()).post(Entity.json(event));
194         } else {
195             return client.target(untaggedUrl).request("application/json")
196                     .headers(restProducerProperties.getHttpHeadersAsMultivaluedMap()).put(Entity.json(event));
197         }
198     }
199
200     /**
201      * Hook for unit test mocking of HTTP client.
202      *
203      * @param client the mocked client
204      */
205     protected void setClient(final Client client) {
206         this.client = client;
207     }
208 }