6739d82a9219b7a02718b6f8f2169f87a39bfaae
[policy/apex-pdp.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2016-2018 Ericsson. All rights reserved.
4  * ================================================================================
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  *      http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  *
17  * SPDX-License-Identifier: Apache-2.0
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.policy.apex.plugins.event.carrier.restclient;
22
23 import java.util.EnumMap;
24 import java.util.Map;
25 import java.util.Properties;
26
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
32 import org.onap.policy.apex.service.engine.event.ApexEventException;
33 import org.onap.policy.apex.service.engine.event.ApexEventProducer;
34 import org.onap.policy.apex.service.engine.event.ApexEventRuntimeException;
35 import org.onap.policy.apex.service.engine.event.PeeredReference;
36 import org.onap.policy.apex.service.engine.event.SynchronousEventCache;
37 import org.onap.policy.apex.service.parameters.eventhandler.EventHandlerParameters;
38 import org.onap.policy.apex.service.parameters.eventhandler.EventHandlerPeeredMode;
39 import org.slf4j.Logger;
40 import org.slf4j.LoggerFactory;
41
42 /**
43  * Concrete implementation of an Apex event producer that sends events using REST.
44  *
45  * @author Joss Armstrong (joss.armstrong@ericsson.com)
46  *
47  */
48 public class ApexRestClientProducer implements ApexEventProducer {
49     private static final Logger LOGGER = LoggerFactory.getLogger(ApexRestClientProducer.class);
50
51     // The HTTP client that makes a REST call with an event from Apex
52     private Client client;
53
54     // The REST carrier properties
55     private RestClientCarrierTechnologyParameters restProducerProperties;
56
57     // The name for this producer
58     private String name = null;
59
60     // The peer references for this event handler
61     private Map<EventHandlerPeeredMode, PeeredReference> peerReferenceMap = new EnumMap<>(EventHandlerPeeredMode.class);
62
63     /**
64      * {@inheritDoc}.
65      */
66     @Override
67     public void init(final String producerName, final EventHandlerParameters producerParameters)
68             throws ApexEventException {
69         this.name = producerName;
70
71         // Check and get the REST Properties
72         if (!(producerParameters.getCarrierTechnologyParameters() instanceof RestClientCarrierTechnologyParameters)) {
73             final String errorMessage =
74                     "specified producer properties are not applicable to REST client producer (" + this.name + ")";
75             LOGGER.warn(errorMessage);
76             throw new ApexEventException(errorMessage);
77         }
78         restProducerProperties =
79                 (RestClientCarrierTechnologyParameters) producerParameters.getCarrierTechnologyParameters();
80
81         // Check if the HTTP method has been set
82         if (restProducerProperties.getHttpMethod() == null) {
83             restProducerProperties.setHttpMethod(RestClientCarrierTechnologyParameters.HttpMethod.POST);
84         }
85
86         if (!RestClientCarrierTechnologyParameters.HttpMethod.POST.equals(restProducerProperties.getHttpMethod())
87                 && !RestClientCarrierTechnologyParameters.HttpMethod.PUT
88                         .equals(restProducerProperties.getHttpMethod())) {
89             final String errorMessage = "specified HTTP method of \"" + restProducerProperties.getHttpMethod()
90                     + "\" is invalid, only HTTP methods \"POST\" and \"PUT\" are supproted "
91                     + "for event sending on REST client producer (" + this.name + ")";
92             LOGGER.warn(errorMessage);
93             throw new ApexEventException(errorMessage);
94         }
95
96         // Initialize the HTTP client
97         client = ClientBuilder.newClient();
98     }
99
100     /**
101      * {@inheritDoc}.
102      */
103     @Override
104     public String getName() {
105         return name;
106     }
107
108     /**
109      * {@inheritDoc}.
110      */
111     @Override
112     public PeeredReference getPeeredReference(final EventHandlerPeeredMode peeredMode) {
113         return peerReferenceMap.get(peeredMode);
114     }
115
116     /**
117      * {@inheritDoc}.
118      */
119     @Override
120     public void setPeeredReference(final EventHandlerPeeredMode peeredMode, final PeeredReference peeredReference) {
121         peerReferenceMap.put(peeredMode, peeredReference);
122     }
123
124     /**
125      * {@inheritDoc}.
126      */
127     @Override
128     public void sendEvent(final long executionId, final Properties executionProperties, final String eventName,
129             final Object event) {
130         // Check if this is a synchronized event, if so we have received a reply
131         final SynchronousEventCache synchronousEventCache =
132                 (SynchronousEventCache) peerReferenceMap.get(EventHandlerPeeredMode.SYNCHRONOUS);
133         if (synchronousEventCache != null) {
134             synchronousEventCache.removeCachedEventToApexIfExists(executionId);
135         }
136
137         // Send the event as a REST request
138         final Response response = sendEventAsRestRequest((String) event);
139
140         // Check that the request worked
141         if (response.getStatus() != Response.Status.OK.getStatusCode()) {
142             final String errorMessage = "send of event to URL \"" + restProducerProperties.getUrl() + "\" using HTTP \""
143                     + restProducerProperties.getHttpMethod() + "\" failed with status code " + response.getStatus()
144                     + " and message \"" + response.readEntity(String.class) + "\", event:\n" + event;
145             LOGGER.warn(errorMessage);
146             throw new ApexEventRuntimeException(errorMessage);
147         }
148
149         if (LOGGER.isTraceEnabled()) {
150             LOGGER.trace("event sent from engine using {} to URL {} with HTTP {} : {} and response {} ", this.name,
151                     restProducerProperties.getUrl(), restProducerProperties.getHttpMethod(), event, response);
152         }
153     }
154
155     /**
156      * {@inheritDoc}.
157      */
158     @Override
159     public void stop() {
160         // Close the HTTP session
161         client.close();
162     }
163
164     /**
165      * Send the event as a JSON string as a REST request.
166      *
167      * @param event the event to send
168      * @return the response to the JSON request
169      */
170     private Response sendEventAsRestRequest(final String event) {
171         // We have already checked that it is a PUT or POST request
172         if (RestClientCarrierTechnologyParameters.HttpMethod.POST.equals(restProducerProperties.getHttpMethod())) {
173             return client.target(restProducerProperties.getUrl()).request("application/json")
174                     .headers(restProducerProperties.getHttpHeadersAsMultivaluedMap()).post(Entity.json(event));
175         } else {
176             return client.target(restProducerProperties.getUrl()).request("application/json")
177                     .headers(restProducerProperties.getHttpHeadersAsMultivaluedMap()).put(Entity.json(event));
178         }
179     }
180
181     /**
182      * Hook for unit test mocking of HTTP client.
183      *
184      * @param client the mocked client
185      */
186     protected void setClient(final Client client) {
187         this.client = client;
188     }
189 }