81aa1a74a289446ab76b6b1a75e62bf66607977d
[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.restrequestor;
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 issuing a REST request and receiving a REST
47  * response.
48  *
49  * <p>The parameters for this plugin are:
50  * <ol>
51  * <li>url: The URL that the Apex Rest Requestor will connect to over REST for REST request sending.
52  * This parameter is mandatory.
53  * <li>httpMethod: The HTTP method to use when making requests over REST, legal values are GET (default),
54  *  POST, PUT, and DELETE.
55  * <li>httpHeaders, the HTTP headers to send on REST requests, optional parameter, defaults to none.
56  * <li>httpCodeFilter: a regular expression filter for returned HTTP codes, if the returned HTTP code passes this
57  * filter, then the request is assumed to have succeeded by the plugin, optional, defaults to allowing 2xx codes
58  * through, that is a regular expression of "[2][0-9][0-9]"
59  * </ol>
60  *
61  * @author Liam Fallon (liam.fallon@ericsson.com)
62  */
63 //@formatter:on
64 @Getter
65 @Setter
66 public class RestRequestorCarrierTechnologyParameters extends CarrierTechnologyParameters {
67     // Get a reference to the logger
68     private static final Logger LOGGER = LoggerFactory.getLogger(RestRequestorCarrierTechnologyParameters.class);
69
70     /** The supported HTTP methods. */
71     public enum HttpMethod {
72         GET, PUT, POST, DELETE
73     }
74
75     /** The label of this carrier technology. */
76     public static final String RESTREQUESTOR_CARRIER_TECHNOLOGY_LABEL = "RESTREQUESTOR";
77
78     /** The producer plugin class for the REST carrier technology. */
79     public static final String RESTREQUSTOR_EVENT_PRODUCER_PLUGIN_CLASS =
80             ApexRestRequestorProducer.class.getCanonicalName();
81
82     /** The consumer plugin class for the REST carrier technology. */
83     public static final String RESTREQUSTOR_EVENT_CONSUMER_PLUGIN_CLASS =
84             ApexRestRequestorConsumer.class.getCanonicalName();
85
86     /** The default HTTP method for request events. */
87     public static final HttpMethod DEFAULT_REQUESTOR_HTTP_METHOD = HttpMethod.GET;
88
89     /** The default timeout for REST requests. */
90     public static final long DEFAULT_REST_REQUEST_TIMEOUT = 500;
91
92     /** The default HTTP code filter, allows 2xx HTTP codes through. */
93     public static final String DEFAULT_HTTP_CODE_FILTER = "[2][0-9][0-9]";
94
95     // Commonly occurring strings
96     private static final String HTTP_HEADERS = "httpHeaders";
97     private static final String HTTP_CODE_FILTER = "httpCodeFilter";
98
99     // Regular expression patterns for finding and checking keys in URLs
100     private static final Pattern patternProperKey = Pattern.compile("(?<=\\{)[^}]*(?=\\})");
101     private static final Pattern patternErrorKey =
102             Pattern.compile("(\\{[^\\{}]*.?\\{)|(\\{[^\\{}]*$)|(\\}[^\\{}]*.?\\})|(^[^\\{}]*.?\\})|\\{\\s*\\}");
103
104     private String url = null;
105     private HttpMethod httpMethod = null;
106     private String[][] httpHeaders = null;
107     private String httpCodeFilter = DEFAULT_HTTP_CODE_FILTER;
108
109     /**
110      * Constructor to create a REST carrier technology parameters instance and register the instance with the parameter
111      * service.
112      */
113     public RestRequestorCarrierTechnologyParameters() {
114         super();
115
116         // Set the carrier technology properties for the web socket carrier technology
117         this.setLabel(RESTREQUESTOR_CARRIER_TECHNOLOGY_LABEL);
118         this.setEventProducerPluginClass(RESTREQUSTOR_EVENT_PRODUCER_PLUGIN_CLASS);
119         this.setEventConsumerPluginClass(RESTREQUSTOR_EVENT_CONSUMER_PLUGIN_CLASS);
120     }
121
122     /**
123      * Check if http headers have been set for the REST request.
124      *
125      * @return true if headers have beenset
126      */
127     public boolean checkHttpHeadersSet() {
128         return httpHeaders != null && httpHeaders.length > 0;
129     }
130
131     /**
132      * Gets the http headers for the REST request as a multivalued map.
133      *
134      * @return the headers
135      */
136     public MultivaluedMap<String, Object> getHttpHeadersAsMultivaluedMap() {
137         if (httpHeaders == null) {
138             return null;
139         }
140
141         // Load the HTTP headers into the map
142         MultivaluedMap<String, Object> httpHeaderMap = new MultivaluedHashMap<>();
143
144         for (String[] httpHeader : httpHeaders) {
145             httpHeaderMap.putSingle(httpHeader[0], httpHeader[1]);
146         }
147
148         return httpHeaderMap;
149     }
150
151     /**
152      * Sets the header for the REST request.
153      *
154      * @param httpHeaders the incoming HTTP headers
155      */
156     public void setHttpHeaders(final String[][] httpHeaders) {
157         this.httpHeaders = httpHeaders;
158     }
159
160     /**
161      * Get the tag for the REST Producer Properties.
162      *
163      * @return set of the tags
164      */
165     public Set<String> getKeysFromUrl() {
166         Matcher matcher = patternProperKey.matcher(getUrl());
167         Set<String> key = new HashSet<>();
168         while (matcher.find()) {
169             key.add(matcher.group());
170         }
171         return key;
172     }
173
174
175     /**
176      * {@inheritDoc}.
177      */
178     @Override
179     public GroupValidationResult validate() {
180         GroupValidationResult result = super.validate();
181
182         result = validateUrl(result);
183
184         result = validateHttpHeaders(result);
185
186         return validateHttpCodeFilter(result);
187     }
188
189     // @formatter:off
190     /**
191      * Validate the URL.
192      *
193      * <p>Checks:
194      * http://www.blah.com/{par1/somethingelse (Missing end tag) use  {[^\\{}]*$
195      * http://www.blah.com/{par1/{some}thingelse (Nested tag) use {[^}]*{
196      * http://www.blah.com/{par1}/some}thingelse (Missing start tag1) use }[^{}]*.}
197      * http://www.blah.com/par1}/somethingelse (Missing start tag2) use }[^{}]*}
198      * http://www.blah.com/{}/somethingelse (Empty tag) use {[\s]*}
199      * @param result the result of the validation
200      */
201     // @formatter:on
202     private GroupValidationResult validateUrl(final GroupValidationResult result) {
203         // URL is only set on Requestor consumers
204         if (getUrl() == null) {
205             return result;
206         }
207
208         Matcher matcher = patternErrorKey.matcher(getUrl());
209         if (matcher.find()) {
210             result.setResult("url", ValidationStatus.INVALID,
211                     "no proper URL has been set for event sending on REST requestor");
212         }
213
214         return result;
215     }
216
217     /**
218      * Validate the HTTP headers.
219      *
220      * @param result the result of the validation
221      */
222     private GroupValidationResult validateHttpHeaders(final GroupValidationResult result) {
223         if (httpHeaders == null) {
224             return result;
225         }
226
227         for (String[] httpHeader : httpHeaders) {
228             if (httpHeader == null) {
229                 result.setResult(HTTP_HEADERS, ValidationStatus.INVALID, "HTTP header array entry is null");
230             } else if (httpHeader.length != 2) {
231                 result.setResult(HTTP_HEADERS, ValidationStatus.INVALID,
232                         "HTTP header array entries must have one key and one value: "
233                                 + Arrays.deepToString(httpHeader));
234             } else if (!ParameterValidationUtils.validateStringParameter(httpHeader[0])) {
235                 result.setResult(HTTP_HEADERS, ValidationStatus.INVALID,
236                         "HTTP header key is null or blank: " + Arrays.deepToString(httpHeader));
237             } else if (!ParameterValidationUtils.validateStringParameter(httpHeader[1])) {
238                 result.setResult(HTTP_HEADERS, ValidationStatus.INVALID,
239                         "HTTP header value is null or blank: " + Arrays.deepToString(httpHeader));
240             }
241         }
242
243         return result;
244     }
245
246     /**
247      * Validate the HTTP code filter.
248      *
249      * @param result the result of the validation
250      */
251     public GroupValidationResult validateHttpCodeFilter(final GroupValidationResult result) {
252         if (httpCodeFilter == null) {
253             httpCodeFilter = DEFAULT_HTTP_CODE_FILTER;
254
255         } else if (StringUtils.isBlank(httpCodeFilter)) {
256             result.setResult(HTTP_CODE_FILTER, ValidationStatus.INVALID,
257                     "HTTP code filter must be specified as a three digit regular expression");
258         } else {
259             try {
260                 Pattern.compile(httpCodeFilter);
261             } catch (PatternSyntaxException pse) {
262                 String message =
263                         "Invalid HTTP code filter, the filter must be specified as a three digit regular expression: "
264                                 + pse.getMessage();
265                 result.setResult(HTTP_CODE_FILTER, ValidationStatus.INVALID, message);
266                 LOGGER.debug(message, pse);
267             }
268         }
269
270         return result;
271     }
272
273     /**
274      * {@inheritDoc}.
275      */
276     @Override
277     public String toString() {
278         return "RESTRequestorCarrierTechnologyParameters [url=" + url + ", httpMethod=" + httpMethod + ", httpHeaders="
279                 + Arrays.deepToString(httpHeaders) + ", httpCodeFilter=" + httpCodeFilter + "]";
280     }
281 }