15b6dd3dd3ab2e30aa0014d1a95882a9de634958
[policy/apex-pdp.git] / plugins / plugins-event / plugins-event-carrier / plugins-event-carrier-restclient / src / main / java / org / onap / policy / apex / plugins / event / carrier / restclient / ApexRestClientProducer.java
1 /*-
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
11  *
12  *      http://www.apache.org/licenses/LICENSE-2.0
13  *
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.
19  *
20  * SPDX-License-Identifier: Apache-2.0
21  * ============LICENSE_END=========================================================
22  */
23
24 package org.onap.policy.apex.plugins.event.carrier.restclient;
25
26 import java.util.Optional;
27 import java.util.Properties;
28 import java.util.Set;
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;
35 import lombok.Setter;
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;
44 import org.slf4j.Logger;
45 import org.slf4j.LoggerFactory;
46
47 /**
48  * Concrete implementation of an Apex event producer that sends events using REST.
49  *
50  * @author Joss Armstrong (joss.armstrong@ericsson.com)
51  *
52  */
53 public class ApexRestClientProducer extends ApexPluginsEventProducer {
54     private static final Logger LOGGER = LoggerFactory.getLogger(ApexRestClientProducer.class);
55
56     // The HTTP client that makes a REST call with an event from Apex
57     @Setter(AccessLevel.PROTECTED)
58     private Client client;
59
60     // The REST carrier properties
61     private RestClientCarrierTechnologyParameters restProducerProperties;
62
63     private Pattern httpCodeFilterPattern = null;
64
65     /**
66      * {@inheritDoc}.
67      */
68     @Override
69     public void init(final String producerName, final EventHandlerParameters producerParameters)
70             throws ApexEventException {
71         this.name = producerName;
72
73         // Check and get the REST Properties
74         if (!(producerParameters.getCarrierTechnologyParameters() instanceof RestClientCarrierTechnologyParameters)) {
75             final String errorMessage =
76                     "specified producer properties are not applicable to REST client producer (" + this.name + ")";
77             throw new ApexEventException(errorMessage);
78         }
79         restProducerProperties =
80                 (RestClientCarrierTechnologyParameters) producerParameters.getCarrierTechnologyParameters();
81
82         this.httpCodeFilterPattern = Pattern.compile(restProducerProperties.getHttpCodeFilter());
83
84         // Check if the HTTP method has been set
85         if (restProducerProperties.getHttpMethod() == null) {
86             restProducerProperties.setHttpMethod(RestPluginCarrierTechnologyParameters.HttpMethod.POST);
87         }
88
89         if (!RestPluginCarrierTechnologyParameters.HttpMethod.POST.equals(restProducerProperties.getHttpMethod())
90                 && !RestPluginCarrierTechnologyParameters.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 supported "
94                     + "for event sending on REST client producer (" + this.name + ")";
95             throw new ApexEventException(errorMessage);
96         }
97
98         // Initialize the HTTP client
99         client = ClientBuilder.newClient();
100     }
101
102     /**
103      * {@inheritDoc}.
104      */
105     @Override
106     public void sendEvent(final long executionId, final Properties executionProperties, final String eventName,
107             final Object event) {
108         super.sendEvent(executionId, executionProperties, eventName, event);
109
110         String untaggedUrl = restProducerProperties.getUrl();
111         if (executionProperties != null) {
112             Set<String> names = restProducerProperties.getKeysFromUrl();
113             Set<String> inputProperty = executionProperties.stringPropertyNames();
114
115             // @formatter:off
116             names.stream().map(Optional::of).forEach(op ->
117                 op.filter(inputProperty::contains)
118                     .orElseThrow(() -> new ApexEventRuntimeException(
119                         "key \"" + op.get() + "\" specified on url \"" + restProducerProperties.getUrl()
120                         + "\" not found in execution properties passed by the current policy"))
121             );
122
123             untaggedUrl = names.stream().reduce(untaggedUrl,
124                 (acc, str) -> acc.replace("{" + str + "}", (String) executionProperties.get(str)));
125             // @formatter:on
126         }
127
128         NetLoggerUtil.log(EventType.OUT, CommInfrastructure.REST, untaggedUrl, event.toString());
129         // Send the event as a REST request
130         final var response = sendEventAsRestRequest(untaggedUrl, (String) event);
131
132         NetLoggerUtil.log(EventType.IN, CommInfrastructure.REST, untaggedUrl, response.readEntity(String.class));
133
134
135         // Match the return code
136         var isPass = httpCodeFilterPattern.matcher(String.valueOf(response.getStatus()));
137
138         // Check that status code
139         if (!isPass.matches()) {
140             final String errorMessage = "send of event to URL \"" + untaggedUrl + "\" using HTTP \""
141                     + restProducerProperties.getHttpMethod() + "\" failed with status code " + response.getStatus();
142             throw new ApexEventRuntimeException(errorMessage);
143         }
144     }
145
146     /**
147      * {@inheritDoc}.
148      */
149     @Override
150     public void stop() {
151         // Close the HTTP session
152         client.close();
153     }
154
155     /**
156      * Send the event as a JSON string as a REST request.
157      *
158      * @param event the event to send
159      * @return the response to the JSON request
160      */
161     private Response sendEventAsRestRequest(final String untaggedUrl, final String event) {
162         // We have already checked that it is a PUT or POST request
163         if (RestPluginCarrierTechnologyParameters.HttpMethod.POST.equals(restProducerProperties.getHttpMethod())) {
164             return client.target(untaggedUrl).request("application/json")
165                     .headers(restProducerProperties.getHttpHeadersAsMultivaluedMap()).post(Entity.json(event));
166         } else {
167             return client.target(untaggedUrl).request("application/json")
168                     .headers(restProducerProperties.getHttpHeadersAsMultivaluedMap()).put(Entity.json(event));
169         }
170     }
171 }