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
11 * http://www.apache.org/licenses/LICENSE-2.0
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.
19 * SPDX-License-Identifier: Apache-2.0
20 * ============LICENSE_END=========================================================
23 package org.onap.policy.apex.plugins.event.carrier.restclient;
25 import java.util.Optional;
26 import java.util.Properties;
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;
44 * Concrete implementation of an Apex event producer that sends events using REST.
46 * @author Joss Armstrong (joss.armstrong@ericsson.com)
49 public class ApexRestClientProducer extends ApexPluginsEventProducer {
50 private static final Logger LOGGER = LoggerFactory.getLogger(ApexRestClientProducer.class);
52 // The HTTP client that makes a REST call with an event from Apex
53 private Client client;
55 // The REST carrier properties
56 private RestClientCarrierTechnologyParameters restProducerProperties;
62 public void init(final String producerName, final EventHandlerParameters producerParameters)
63 throws ApexEventException {
64 this.name = producerName;
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);
73 restProducerProperties =
74 (RestClientCarrierTechnologyParameters) producerParameters.getCarrierTechnologyParameters();
76 // Check if the HTTP method has been set
77 if (restProducerProperties.getHttpMethod() == null) {
78 restProducerProperties.setHttpMethod(RestPluginCarrierTechnologyParameters.HttpMethod.POST);
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);
91 // Initialize the HTTP client
92 client = ClientBuilder.newClient();
99 public void sendEvent(final long executionId, final Properties executionProperties, final String eventName,
100 final Object event) {
101 super.sendEvent(executionId, executionProperties, eventName, event);
103 String untaggedUrl = restProducerProperties.getUrl();
104 if (executionProperties != null) {
105 Set<String> names = restProducerProperties.getKeysFromUrl();
106 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)));
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);
125 NetLoggerUtil.log(EventType.IN, CommInfrastructure.REST, untaggedUrl, response.readEntity(String.class));
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);
140 // Close the HTTP session
145 * Send the event as a JSON string as a REST request.
147 * @param event the event to send
148 * @return the response to the JSON request
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));
156 return client.target(untaggedUrl).request("application/json")
157 .headers(restProducerProperties.getHttpHeadersAsMultivaluedMap()).put(Entity.json(event));
162 * Hook for unit test mocking of HTTP client.
164 * @param client the mocked client
166 protected void setClient(final Client client) {
167 this.client = client;