2 * ============LICENSE_START=======================================================
3 * Copyright (C) 2016-2018 Ericsson. All rights reserved.
4 * Modifications Copyright (C) 2019-2021 Nordix Foundation.
5 * Modifications Copyright (C) 2021 Bell Canada. All rights reserved.
6 * Modifications Copyright (C) 2021 AT&T Intellectual Property. All rights reserved.
7 * ================================================================================
8 * Licensed under the Apache License, Version 2.0 (the "License");
9 * you may not use this file except in compliance with the License.
10 * You may obtain a copy of the License at
12 * http://www.apache.org/licenses/LICENSE-2.0
14 * Unless required by applicable law or agreed to in writing, software
15 * distributed under the License is distributed on an "AS IS" BASIS,
16 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 * See the License for the specific language governing permissions and
18 * limitations under the License.
20 * SPDX-License-Identifier: Apache-2.0
21 * ============LICENSE_END=========================================================
24 package org.onap.policy.apex.plugins.event.carrier.restclient;
26 import java.util.Optional;
27 import java.util.Properties;
29 import java.util.regex.Pattern;
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 import lombok.AccessLevel;
36 import org.onap.policy.apex.service.engine.event.ApexEventException;
37 import org.onap.policy.apex.service.engine.event.ApexEventRuntimeException;
38 import org.onap.policy.apex.service.engine.event.ApexPluginsEventProducer;
39 import org.onap.policy.apex.service.parameters.carriertechnology.RestPluginCarrierTechnologyParameters;
40 import org.onap.policy.apex.service.parameters.eventhandler.EventHandlerParameters;
41 import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure;
42 import org.onap.policy.common.endpoints.utils.NetLoggerUtil;
43 import org.onap.policy.common.endpoints.utils.NetLoggerUtil.EventType;
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 // The HTTP client that makes a REST call with an event from Apex
53 @Setter(AccessLevel.PROTECTED)
54 private Client client;
56 // The REST carrier properties
57 private RestClientCarrierTechnologyParameters restProducerProperties;
59 private Pattern httpCodeFilterPattern = null;
65 public void init(final String producerName, final EventHandlerParameters producerParameters)
66 throws ApexEventException {
67 this.name = producerName;
69 // Check and get the REST Properties
70 if (!(producerParameters.getCarrierTechnologyParameters() instanceof RestClientCarrierTechnologyParameters)) {
71 final String errorMessage =
72 "specified producer properties are not applicable to REST client producer (" + this.name + ")";
73 throw new ApexEventException(errorMessage);
75 restProducerProperties =
76 (RestClientCarrierTechnologyParameters) producerParameters.getCarrierTechnologyParameters();
78 this.httpCodeFilterPattern = Pattern.compile(restProducerProperties.getHttpCodeFilter());
80 // Check if the HTTP method has been set
81 if (restProducerProperties.getHttpMethod() == null) {
82 restProducerProperties.setHttpMethod(RestPluginCarrierTechnologyParameters.HttpMethod.POST);
85 if (!RestPluginCarrierTechnologyParameters.HttpMethod.POST.equals(restProducerProperties.getHttpMethod())
86 && !RestPluginCarrierTechnologyParameters.HttpMethod.PUT
87 .equals(restProducerProperties.getHttpMethod())) {
88 final String errorMessage = "specified HTTP method of \"" + restProducerProperties.getHttpMethod()
89 + "\" is invalid, only HTTP methods \"POST\" and \"PUT\" are supported "
90 + "for event sending on REST client producer (" + this.name + ")";
91 throw new ApexEventException(errorMessage);
94 // Initialize the HTTP client
95 client = ClientBuilder.newClient();
102 public void sendEvent(final long executionId, final Properties executionProperties, final String eventName,
103 final Object event) {
104 super.sendEvent(executionId, executionProperties, eventName, event);
106 String untaggedUrl = restProducerProperties.getUrl();
107 if (executionProperties != null) {
108 Set<String> names = restProducerProperties.getKeysFromUrl();
109 Set<String> inputProperty = executionProperties.stringPropertyNames();
112 names.stream().map(Optional::of).forEach(op ->
113 op.filter(inputProperty::contains)
114 .orElseThrow(() -> new ApexEventRuntimeException(
115 "key \"" + op.get() + "\" specified on url \"" + restProducerProperties.getUrl()
116 + "\" not found in execution properties passed by the current policy"))
119 untaggedUrl = names.stream().reduce(untaggedUrl,
120 (acc, str) -> acc.replace("{" + str + "}", (String) executionProperties.get(str)));
124 NetLoggerUtil.log(EventType.OUT, CommInfrastructure.REST, untaggedUrl, event.toString());
125 // Send the event as a REST request
126 final var response = sendEventAsRestRequest(untaggedUrl, (String) event);
128 NetLoggerUtil.log(EventType.IN, CommInfrastructure.REST, untaggedUrl, response.readEntity(String.class));
131 // Match the return code
132 var isPass = httpCodeFilterPattern.matcher(String.valueOf(response.getStatus()));
134 // Check that status code
135 if (!isPass.matches()) {
136 final String errorMessage = "send of event to URL \"" + untaggedUrl + "\" using HTTP \""
137 + restProducerProperties.getHttpMethod() + "\" failed with status code " + response.getStatus();
138 throw new ApexEventRuntimeException(errorMessage);
147 // Close the HTTP session
152 * Send the event as a JSON string as a REST request.
154 * @param event the event to send
155 * @return the response to the JSON request
157 private Response sendEventAsRestRequest(final String untaggedUrl, final String event) {
158 // We have already checked that it is a PUT or POST request
159 if (RestPluginCarrierTechnologyParameters.HttpMethod.POST.equals(restProducerProperties.getHttpMethod())) {
160 return client.target(untaggedUrl).request("application/json")
161 .headers(restProducerProperties.getHttpHeadersAsMultivaluedMap()).post(Entity.json(event));
163 return client.target(untaggedUrl).request("application/json")
164 .headers(restProducerProperties.getHttpHeadersAsMultivaluedMap()).put(Entity.json(event));