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