707dcb10444166cecb3e924c7246e51cbcb08661
[policy/apex-pdp.git] / services / services-engine / src / main / java / org / onap / policy / apex / service / parameters / carriertechnology / RestPluginCarrierTechnologyParameters.java
1 /*-
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2016-2018 Ericsson. All rights reserved.
4  *  Modifications Copyright (C) 2019-2020 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.service.parameters.carriertechnology;
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
37 import org.apache.commons.lang3.StringUtils;
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 plugin parameters for REST as an event carrier technology with Apex.
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 Ning Xi(ning.xi@ericsson.com)
61  */
62 //@formatter:on
63 @Setter
64 @Getter
65 public class RestPluginCarrierTechnologyParameters extends CarrierTechnologyParameters {
66     // Get a reference to the logger
67     private static final Logger LOGGER = LoggerFactory.getLogger(RestPluginCarrierTechnologyParameters.class);
68
69     /** The supported HTTP methods. */
70     public enum HttpMethod {
71         GET,
72         PUT,
73         POST,
74         DELETE
75     }
76
77     /** The default HTTP code filter, allows 2xx HTTP codes through. */
78     public static final String DEFAULT_HTTP_CODE_FILTER = "[2][0-9][0-9]";
79
80     // Commonly occurring strings
81     private static final String HTTP_HEADERS = "httpHeaders";
82     private static final String HTTP_CODE_FILTER = "httpCodeFilter";
83
84     // Regular expression patterns for finding and checking keys in URLs
85     private static final Pattern patternProperKey = Pattern.compile("(?<=\\{)[^}]*(?=\\})");
86     protected static final Pattern patternErrorKey =
87             Pattern.compile("(\\{[^\\{}]*.?\\{)|(\\{[^\\{}]*$)|(\\}[^\\{}]*.?\\})|(^[^\\{}]*.?\\})|\\{\\s*\\}");
88
89     // variable
90     protected String url = null;
91     protected HttpMethod httpMethod = null;
92     protected String[][] httpHeaders = null;
93     protected String httpCodeFilter = DEFAULT_HTTP_CODE_FILTER;
94
95     /**
96      * Constructor to create a REST carrier technology parameters instance and register the instance with the parameter
97      * service.
98      */
99     public RestPluginCarrierTechnologyParameters() {
100         super();
101     }
102
103     /**
104      * Check if http headers have been set for the REST request.
105      *
106      * @return true if headers have been set
107      */
108     public boolean checkHttpHeadersSet() {
109         return httpHeaders != null && httpHeaders.length > 0;
110     }
111
112     /**
113      * Gets the http headers for the REST request as a multivalued map.
114      *
115      * @return the headers
116      */
117     public MultivaluedMap<String, Object> getHttpHeadersAsMultivaluedMap() {
118         if (httpHeaders == null) {
119             return null;
120         }
121
122         // Load the HTTP headers into the map
123         MultivaluedMap<String, Object> httpHeaderMap = new MultivaluedHashMap<>();
124
125         for (String[] httpHeader : httpHeaders) {
126             httpHeaderMap.putSingle(httpHeader[0], httpHeader[1]);
127         }
128
129         return httpHeaderMap;
130     }
131
132     /**
133      * Sets the header for the REST request.
134      *
135      * @param httpHeaders the incoming HTTP headers
136      */
137     public void setHttpHeaders(final String[][] httpHeaders) {
138         this.httpHeaders = httpHeaders;
139     }
140
141     /**
142      * Get the tag for the REST Producer Properties.
143      *
144      * @return set of the tags
145      */
146     public Set<String> getKeysFromUrl() {
147         Matcher matcher = patternProperKey.matcher(getUrl());
148         Set<String> key = new HashSet<>();
149         while (matcher.find()) {
150             key.add(matcher.group());
151         }
152         return key;
153     }
154
155     /**
156      * {@inheritDoc}.
157      */
158     @Override
159     public GroupValidationResult validate() {
160         GroupValidationResult result = super.validate();
161
162         validateUrl(result);
163         validateHttpHeaders(result);
164
165         return validateHttpCodeFilter(result);
166     }
167
168     // @formatter:off
169     /**
170      * Validate the URL.
171      *
172      * <p>Checks:
173      * http://www.blah.com/{par1/somethingelse (Missing end tag) use  {[^\\{}]*$
174      * http://www.blah.com/{par1/{some}thingelse (Nested tag) use {[^}]*{
175      * http://www.blah.com/{par1}/some}thingelse (Missing start tag1) use }[^{}]*.}
176      * http://www.blah.com/par1}/somethingelse (Missing start tag2) use }[^{}]*}
177      * http://www.blah.com/{}/somethingelse (Empty tag) use {[\s]*}
178      * @param result the result of the validation
179      */
180     // @formatter:on
181     public GroupValidationResult validateUrl(final GroupValidationResult result) {
182         // Check if the URL has been set for event output
183         String urlErrorMessage = "no URL has been set for event sending on " + getLabel();
184         if (getUrl() == null) {
185             result.setResult("url", ValidationStatus.INVALID, urlErrorMessage);
186             return result;
187         }
188
189         Matcher matcher = patternErrorKey.matcher(getUrl());
190         if (matcher.find()) {
191             result.setResult("url", ValidationStatus.INVALID, urlErrorMessage);
192         }
193
194         return result;
195     }
196
197     /**
198      * Validate the HTTP headers.
199      *
200      * @param result the result of the validation
201      */
202     private GroupValidationResult validateHttpHeaders(final GroupValidationResult result) {
203         if (httpHeaders == null) {
204             return result;
205         }
206
207         for (String[] httpHeader : httpHeaders) {
208             if (httpHeader == null) {
209                 result.setResult(HTTP_HEADERS, ValidationStatus.INVALID, "HTTP header array entry is null");
210             } else if (httpHeader.length != 2) {
211                 result.setResult(HTTP_HEADERS, ValidationStatus.INVALID,
212                         "HTTP header array entries must have one key and one value: "
213                                 + Arrays.deepToString(httpHeader));
214             } else if (!ParameterValidationUtils.validateStringParameter(httpHeader[0])) {
215                 result.setResult(HTTP_HEADERS, ValidationStatus.INVALID,
216                         "HTTP header key is null or blank: " + Arrays.deepToString(httpHeader));
217             } else if (!ParameterValidationUtils.validateStringParameter(httpHeader[1])) {
218                 result.setResult(HTTP_HEADERS, ValidationStatus.INVALID,
219                         "HTTP header value is null or blank: " + Arrays.deepToString(httpHeader));
220             }
221         }
222
223         return result;
224     }
225
226     /**
227      * Validate the HTTP code filter.
228      *
229      * @param result the result of the validation
230      */
231     public GroupValidationResult validateHttpCodeFilter(final GroupValidationResult result) {
232         if (httpCodeFilter == null) {
233             httpCodeFilter = DEFAULT_HTTP_CODE_FILTER;
234
235         } else if (StringUtils.isBlank(httpCodeFilter)) {
236             result.setResult(HTTP_CODE_FILTER, ValidationStatus.INVALID,
237                     "HTTP code filter must be specified as a three digit regular expression");
238         } else {
239             try {
240                 Pattern.compile(httpCodeFilter);
241             } catch (PatternSyntaxException pse) {
242                 String message =
243                         "Invalid HTTP code filter, the filter must be specified as a three digit regular expression: "
244                                 + pse.getMessage();
245                 result.setResult(HTTP_CODE_FILTER, ValidationStatus.INVALID, message);
246                 LOGGER.debug(message, pse);
247             }
248         }
249
250         return result;
251     }
252
253     /**
254      * {@inheritDoc}.
255      */
256     @Override
257     public String toString() {
258         return getLabel() + "CarrierTechnologyParameters [url=" + url + ", httpMethod=" + httpMethod + ", httpHeaders="
259                 + Arrays.deepToString(httpHeaders) + ", httpCodeFilter=" + httpCodeFilter + "]";
260     }
261 }