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
10 * http://www.apache.org/licenses/LICENSE-2.0
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.
18 * SPDX-License-Identifier: Apache-2.0
19 * ============LICENSE_END=========================================================
22 package org.onap.policy.apex.plugins.event.carrier.restclient;
24 import java.util.EnumMap;
26 import java.util.Optional;
27 import java.util.Properties;
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;
35 import org.onap.policy.apex.service.engine.event.ApexEventException;
36 import org.onap.policy.apex.service.engine.event.ApexPluginsEventProducer;
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;
46 * Concrete implementation of an Apex event producer that sends events using REST.
48 * @author Joss Armstrong (joss.armstrong@ericsson.com)
51 public class ApexRestClientProducer extends ApexPluginsEventProducer {
52 private static final Logger LOGGER = LoggerFactory.getLogger(ApexRestClientProducer.class);
54 // The HTTP client that makes a REST call with an event from Apex
55 private Client client;
57 // The REST carrier properties
58 private RestClientCarrierTechnologyParameters restProducerProperties;
64 public void init(final String producerName, final EventHandlerParameters producerParameters)
65 throws ApexEventException {
66 this.name = producerName;
68 // Check and get the REST Properties
69 if (!(producerParameters.getCarrierTechnologyParameters() instanceof RestClientCarrierTechnologyParameters)) {
70 final String errorMessage =
71 "specified producer properties are not applicable to REST client producer (" + this.name + ")";
72 LOGGER.warn(errorMessage);
73 throw new ApexEventException(errorMessage);
75 restProducerProperties =
76 (RestClientCarrierTechnologyParameters) producerParameters.getCarrierTechnologyParameters();
78 // Check if the HTTP method has been set
79 if (restProducerProperties.getHttpMethod() == null) {
80 restProducerProperties.setHttpMethod(RestClientCarrierTechnologyParameters.HttpMethod.POST);
83 if (!RestClientCarrierTechnologyParameters.HttpMethod.POST.equals(restProducerProperties.getHttpMethod())
84 && !RestClientCarrierTechnologyParameters.HttpMethod.PUT
85 .equals(restProducerProperties.getHttpMethod())) {
86 final String errorMessage = "specified HTTP method of \"" + restProducerProperties.getHttpMethod()
87 + "\" is invalid, only HTTP methods \"POST\" and \"PUT\" are supproted "
88 + "for event sending on REST client producer (" + this.name + ")";
89 LOGGER.warn(errorMessage);
90 throw new ApexEventException(errorMessage);
93 // Initialize the HTTP client
94 client = ClientBuilder.newClient();
100 public void sendEvent(final long executionId, final Properties executionProperties, final String eventName,
101 final Object event) {
102 super.sendEvent(executionId, executionProperties, eventName, event);
104 String untaggedUrl = restProducerProperties.getUrl();
105 if (executionProperties != null) {
106 Set<String> names = restProducerProperties.getKeysFromUrl();
107 Set<String> inputProperty = executionProperties.stringPropertyNames();
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"))
116 untaggedUrl = names.stream().reduce(untaggedUrl,
117 (acc, str) -> acc.replace("{" + str + "}", (String) executionProperties.get(str)));
120 // Send the event as a REST request
121 final Response response = sendEventAsRestRequest(untaggedUrl, (String) event);
123 // Check that the request worked
124 if (response.getStatus() != Response.Status.OK.getStatusCode()) {
125 final String errorMessage = "send of event to URL \"" + untaggedUrl + "\" using HTTP \""
126 + restProducerProperties.getHttpMethod() + "\" failed with status code " + response.getStatus()
127 + " and message \"" + response.readEntity(String.class) + "\", event:\n" + event;
128 LOGGER.warn(errorMessage);
129 throw new ApexEventRuntimeException(errorMessage);
132 if (LOGGER.isTraceEnabled()) {
133 LOGGER.trace("event sent from engine using {} to URL {} with HTTP {} : {} and response {} ", this.name,
134 untaggedUrl, restProducerProperties.getHttpMethod(), event, response);
143 // Close the HTTP session
148 * Send the event as a JSON string as a REST request.
150 * @param event the event to send
151 * @return the response to the JSON request
153 private Response sendEventAsRestRequest(final String untaggedUrl, final String event) {
154 // We have already checked that it is a PUT or POST request
155 if (RestClientCarrierTechnologyParameters.HttpMethod.POST.equals(restProducerProperties.getHttpMethod())) {
156 return client.target(untaggedUrl).request("application/json")
157 .headers(restProducerProperties.getHttpHeadersAsMultivaluedMap()).post(Entity.json(event));
159 return client.target(untaggedUrl).request("application/json")
160 .headers(restProducerProperties.getHttpHeadersAsMultivaluedMap()).put(Entity.json(event));
165 * Hook for unit test mocking of HTTP client.
167 * @param client the mocked client
169 protected void setClient(final Client client) {
170 this.client = client;