035bd6524e34eb6e592c80c298f57b1851c5c4d0
[policy/apex-pdp.git] /
1 /*-
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  *  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 javax.ws.rs.client.Client;
30 import javax.ws.rs.client.ClientBuilder;
31 import javax.ws.rs.client.Entity;
32 import javax.ws.rs.core.Response;
33 import lombok.AccessLevel;
34 import lombok.Setter;
35 import org.onap.policy.apex.service.engine.event.ApexEventException;
36 import org.onap.policy.apex.service.engine.event.ApexEventRuntimeException;
37 import org.onap.policy.apex.service.engine.event.ApexPluginsEventProducer;
38 import org.onap.policy.apex.service.parameters.carriertechnology.RestPluginCarrierTechnologyParameters;
39 import org.onap.policy.apex.service.parameters.eventhandler.EventHandlerParameters;
40 import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure;
41 import org.onap.policy.common.endpoints.utils.NetLoggerUtil;
42 import org.onap.policy.common.endpoints.utils.NetLoggerUtil.EventType;
43 import org.slf4j.Logger;
44 import org.slf4j.LoggerFactory;
45
46 /**
47  * Concrete implementation of an Apex event producer that sends events using REST.
48  *
49  * @author Joss Armstrong (joss.armstrong@ericsson.com)
50  *
51  */
52 public class ApexRestClientProducer extends ApexPluginsEventProducer {
53     private static final Logger LOGGER = LoggerFactory.getLogger(ApexRestClientProducer.class);
54
55     // The HTTP client that makes a REST call with an event from Apex
56     @Setter(AccessLevel.PROTECTED)
57     private Client client;
58
59     // The REST carrier properties
60     private RestClientCarrierTechnologyParameters restProducerProperties;
61
62     /**
63      * {@inheritDoc}.
64      */
65     @Override
66     public void init(final String producerName, final EventHandlerParameters producerParameters)
67             throws ApexEventException {
68         this.name = producerName;
69
70         // Check and get the REST Properties
71         if (!(producerParameters.getCarrierTechnologyParameters() instanceof RestClientCarrierTechnologyParameters)) {
72             final String errorMessage =
73                     "specified producer properties are not applicable to REST client producer (" + this.name + ")";
74             LOGGER.warn(errorMessage);
75             throw new ApexEventException(errorMessage);
76         }
77         restProducerProperties =
78                 (RestClientCarrierTechnologyParameters) producerParameters.getCarrierTechnologyParameters();
79
80         // Check if the HTTP method has been set
81         if (restProducerProperties.getHttpMethod() == null) {
82             restProducerProperties.setHttpMethod(RestPluginCarrierTechnologyParameters.HttpMethod.POST);
83         }
84
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             LOGGER.warn(errorMessage);
92             throw new ApexEventException(errorMessage);
93         }
94
95         // Initialize the HTTP client
96         client = ClientBuilder.newClient();
97     }
98
99     /**
100      * {@inheritDoc}.
101      */
102     @Override
103     public void sendEvent(final long executionId, final Properties executionProperties, final String eventName,
104             final Object event) {
105         super.sendEvent(executionId, executionProperties, eventName, event);
106
107         String untaggedUrl = restProducerProperties.getUrl();
108         if (executionProperties != null) {
109             Set<String> names = restProducerProperties.getKeysFromUrl();
110             Set<String> inputProperty = executionProperties.stringPropertyNames();
111
112             // @formatter:off
113             names.stream().map(Optional::of).forEach(op ->
114                 op.filter(inputProperty::contains)
115                     .orElseThrow(() -> new ApexEventRuntimeException(
116                         "key \"" + op.get() + "\" specified on url \"" + restProducerProperties.getUrl()
117                         + "\" not found in execution properties passed by the current policy"))
118             );
119
120             untaggedUrl = names.stream().reduce(untaggedUrl,
121                 (acc, str) -> acc.replace("{" + str + "}", (String) executionProperties.get(str)));
122             // @formatter:on
123         }
124
125         NetLoggerUtil.log(EventType.OUT, CommInfrastructure.REST, untaggedUrl, event.toString());
126         // Send the event as a REST request
127         final var response = sendEventAsRestRequest(untaggedUrl, (String) event);
128
129         NetLoggerUtil.log(EventType.IN, CommInfrastructure.REST, untaggedUrl, response.readEntity(String.class));
130
131         // Check that the request worked
132         if (response.getStatus() != Response.Status.OK.getStatusCode()) {
133             final String errorMessage = "send of event to URL \"" + untaggedUrl + "\" using HTTP \""
134                     + restProducerProperties.getHttpMethod() + "\" failed with status code " + response.getStatus();
135             throw new ApexEventRuntimeException(errorMessage);
136         }
137     }
138
139     /**
140      * {@inheritDoc}.
141      */
142     @Override
143     public void stop() {
144         // Close the HTTP session
145         client.close();
146     }
147
148     /**
149      * Send the event as a JSON string as a REST request.
150      *
151      * @param event the event to send
152      * @return the response to the JSON request
153      */
154     private Response sendEventAsRestRequest(final String untaggedUrl, final String event) {
155         // We have already checked that it is a PUT or POST request
156         if (RestPluginCarrierTechnologyParameters.HttpMethod.POST.equals(restProducerProperties.getHttpMethod())) {
157             return client.target(untaggedUrl).request("application/json")
158                     .headers(restProducerProperties.getHttpHeadersAsMultivaluedMap()).post(Entity.json(event));
159         } else {
160             return client.target(untaggedUrl).request("application/json")
161                     .headers(restProducerProperties.getHttpHeadersAsMultivaluedMap()).put(Entity.json(event));
162         }
163     }
164 }