8d783c5cd3feead7ebc4e158392e3a40c90118e5
[policy/apex-pdp.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2016-2018 Ericsson. All rights reserved.
4  *  Modifications Copyright (C) 2019 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
9  *
10  *      http://www.apache.org/licenses/LICENSE-2.0
11  *
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.
17  *
18  * SPDX-License-Identifier: Apache-2.0
19  * ============LICENSE_END=========================================================
20  */
21
22 package org.onap.policy.apex.plugins.event.carrier.restclient;
23
24 import java.util.Arrays;
25 import java.util.HashSet;
26 import java.util.Set;
27 import java.util.regex.Matcher;
28 import java.util.regex.Pattern;
29 import java.util.regex.PatternSyntaxException;
30
31 import javax.ws.rs.core.MultivaluedHashMap;
32 import javax.ws.rs.core.MultivaluedMap;
33
34 import lombok.Getter;
35 import lombok.Setter;
36 import org.apache.commons.lang3.StringUtils;
37 import org.onap.policy.apex.service.parameters.carriertechnology.CarrierTechnologyParameters;
38 import org.onap.policy.common.parameters.GroupValidationResult;
39 import org.onap.policy.common.parameters.ValidationStatus;
40 import org.onap.policy.common.utils.validation.ParameterValidationUtils;
41 import org.slf4j.Logger;
42 import org.slf4j.LoggerFactory;
43
44 // @formatter:off
45 /**
46  * Apex parameters for REST as an event carrier technology with Apex as a REST client.
47  *
48  * <p>The parameters for this plugin are:
49  * <ol>
50  * <li>url: The URL that the Apex Rest client will connect to over REST for event reception or event sending. This
51  * parameter is mandatory.
52  * <li>httpMethod: The HTTP method to use when sending events over REST, legal values are POST (default) and PUT. When
53  * receiving events, the REST client plugin always uses the HTTP GET method.
54  * <li>httpHeaders, the HTTP headers to send on REST requests, optional parameter, defaults to none.
55  * <li>httpCodeFilter: a regular expression filter for returned HTTP codes, if the returned HTTP code passes this
56  * filter, then the request is assumed to have succeeded by the plugin, optional, defaults to allowing 2xx codes
57  * through, that is a regular expression of "[2][0-9][0-9]"
58  * </ol>
59  *
60  * @author Joss Armstrong (joss.armstrong@ericsson.com)
61  */
62 //@formatter:on
63 @Setter
64 @Getter
65 public class RestClientCarrierTechnologyParameters extends CarrierTechnologyParameters {
66     // Get a reference to the logger
67     private static final Logger LOGGER = LoggerFactory.getLogger(RestClientCarrierTechnologyParameters.class);
68
69     /** The supported HTTP methods. */
70     public enum HttpMethod {
71         GET, PUT, POST, DELETE
72     }
73
74     /** The label of this carrier technology. */
75     public static final String RESTCLIENT_CARRIER_TECHNOLOGY_LABEL = "RESTCLIENT";
76
77     /** The producer plugin class for the REST carrier technology. */
78     public static final String RESTCLIENT_EVENT_PRODUCER_PLUGIN_CLASS = ApexRestClientProducer.class.getName();
79
80     /** The consumer plugin class for the REST carrier technology. */
81     public static final String RESTCLIENT_EVENT_CONSUMER_PLUGIN_CLASS = ApexRestClientConsumer.class.getName();
82
83     /** The default HTTP code filter, allows 2xx HTTP codes through. */
84     public static final String DEFAULT_HTTP_CODE_FILTER = "[2][0-9][0-9]";
85
86     // Commonly occurring strings
87     private static final String HTTP_HEADERS = "httpHeaders";
88     private static final String HTTP_CODE_FILTER = "httpCodeFilter";
89
90     // Regular expression patterns for finding and checking keys in URLs
91     private static final Pattern patternProperKey = Pattern.compile("(?<=\\{)[^}]*(?=\\})");
92     private static final Pattern patternErrorKey =
93             Pattern.compile("(\\{[^\\{}]*.?\\{)|(\\{[^\\{}]*$)|(\\}[^\\{}]*.?\\})|(^[^\\{}]*.?\\})|\\{\\s*\\}");
94
95     private String url = null;
96     private HttpMethod httpMethod = null;
97     private String[][] httpHeaders = null;
98     private String httpCodeFilter = DEFAULT_HTTP_CODE_FILTER;
99
100     /**
101      * Constructor to create a REST carrier technology parameters instance and register the instance with the parameter
102      * service.
103      */
104     public RestClientCarrierTechnologyParameters() {
105         super();
106
107         // Set the carrier technology properties for the web socket carrier technology
108         this.setLabel(RESTCLIENT_CARRIER_TECHNOLOGY_LABEL);
109         this.setEventProducerPluginClass(RESTCLIENT_EVENT_PRODUCER_PLUGIN_CLASS);
110         this.setEventConsumerPluginClass(RESTCLIENT_EVENT_CONSUMER_PLUGIN_CLASS);
111     }
112
113     /**
114      * Check if http headers have been set for the REST request.
115      *
116      * @return true if headers have been set
117      */
118     public boolean checkHttpHeadersSet() {
119         return httpHeaders != null && httpHeaders.length > 0;
120     }
121
122     /**
123      * Gets the http headers for the REST request as a multivalued map.
124      *
125      * @return the headers
126      */
127     public MultivaluedMap<String, Object> getHttpHeadersAsMultivaluedMap() {
128         if (httpHeaders == null) {
129             return null;
130         }
131
132         // Load the HTTP headers into the map
133         MultivaluedMap<String, Object> httpHeaderMap = new MultivaluedHashMap<>();
134
135         for (String[] httpHeader : httpHeaders) {
136             httpHeaderMap.putSingle(httpHeader[0], httpHeader[1]);
137         }
138
139         return httpHeaderMap;
140     }
141
142     /**
143      * Sets the header for the REST request.
144      *
145      * @param httpHeaders the incoming HTTP headers
146      */
147     public void setHttpHeaders(final String[][] httpHeaders) {
148         this.httpHeaders = httpHeaders;
149     }
150
151     /**
152      * Get the tag for the REST Producer Properties.
153      *
154      * @return set of the tags
155      */
156     public Set<String> getKeysFromUrl() {
157         Matcher matcher = patternProperKey.matcher(getUrl());
158         Set<String> key = new HashSet<>();
159         while (matcher.find()) {
160             key.add(matcher.group());
161         }
162         return key;
163     }
164
165     /**
166      * {@inheritDoc}.
167      */
168     @Override
169     public GroupValidationResult validate() {
170         GroupValidationResult result = super.validate();
171
172         result = validateUrl(result);
173
174         result = validateHttpHeaders(result);
175
176         return validateHttpCodeFilter(result);
177     }
178
179     // @formatter:off
180     /**
181      * Validate the URL.
182      *
183      * <p>Checks:
184      * http://www.blah.com/{par1/somethingelse (Missing end tag) use  {[^\\{}]*$
185      * http://www.blah.com/{par1/{some}thingelse (Nested tag) use {[^}]*{
186      * http://www.blah.com/{par1}/some}thingelse (Missing start tag1) use }[^{}]*.}
187      * http://www.blah.com/par1}/somethingelse (Missing start tag2) use }[^{}]*}
188      * http://www.blah.com/{}/somethingelse (Empty tag) use {[\s]*}
189      * @param result the result of the validation
190      */
191     // @formatter:on
192     private GroupValidationResult validateUrl(final GroupValidationResult result) {
193         // Check if the URL has been set for event output
194         if (getUrl() == null) {
195             result.setResult("url", ValidationStatus.INVALID, "no URL has been set for event sending on REST client");
196             return result;
197         }
198
199         Matcher matcher = patternErrorKey.matcher(getUrl());
200         if (matcher.find()) {
201             result.setResult("url", ValidationStatus.INVALID,
202                     "no proper URL has been set for event sending on REST client");
203         }
204
205         return result;
206     }
207
208     /**
209      * Validate the HTTP headers.
210      *
211      * @param result the result of the validation
212      */
213     private GroupValidationResult validateHttpHeaders(final GroupValidationResult result) {
214         if (httpHeaders == null) {
215             return result;
216         }
217
218         for (String[] httpHeader : httpHeaders) {
219             if (httpHeader == null) {
220                 result.setResult(HTTP_HEADERS, ValidationStatus.INVALID, "HTTP header array entry is null");
221             } else if (httpHeader.length != 2) {
222                 result.setResult(HTTP_HEADERS, ValidationStatus.INVALID,
223                         "HTTP header array entries must have one key and one value: "
224                                 + Arrays.deepToString(httpHeader));
225             } else if (!ParameterValidationUtils.validateStringParameter(httpHeader[0])) {
226                 result.setResult(HTTP_HEADERS, ValidationStatus.INVALID,
227                         "HTTP header key is null or blank: " + Arrays.deepToString(httpHeader));
228             } else if (!ParameterValidationUtils.validateStringParameter(httpHeader[1])) {
229                 result.setResult(HTTP_HEADERS, ValidationStatus.INVALID,
230                         "HTTP header value is null or blank: " + Arrays.deepToString(httpHeader));
231             }
232         }
233
234         return result;
235     }
236
237     /**
238      * Validate the HTTP code filter.
239      *
240      * @param result the result of the validation
241      */
242     public GroupValidationResult validateHttpCodeFilter(final GroupValidationResult result) {
243         if (httpCodeFilter == null) {
244             httpCodeFilter = DEFAULT_HTTP_CODE_FILTER;
245
246         } else if (StringUtils.isBlank(httpCodeFilter)) {
247             result.setResult(HTTP_CODE_FILTER, ValidationStatus.INVALID,
248                     "HTTP code filter must be specified as a three digit regular expression");
249         } else {
250             try {
251                 Pattern.compile(httpCodeFilter);
252             } catch (PatternSyntaxException pse) {
253                 String message =
254                         "Invalid HTTP code filter, the filter must be specified as a three digit regular expression: "
255                                 + pse.getMessage();
256                 result.setResult(HTTP_CODE_FILTER, ValidationStatus.INVALID, message);
257                 LOGGER.debug(message, pse);
258             }
259         }
260
261         return result;
262     }
263
264     /**
265      * {@inheritDoc}.
266      */
267     @Override
268     public String toString() {
269         return "RestClientCarrierTechnologyParameters [url=" + url + ", httpMethod=" + httpMethod + ", httpHeaders="
270                 + Arrays.deepToString(httpHeaders) + ", httpCodeFilter=" + httpCodeFilter + "]";
271     }
272 }