f548f636af60c5c79af018d62ca8f42557e176fd
[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.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 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 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, PUT, POST, DELETE
72     }
73
74     /** The label of this carrier technology. */
75     protected String CARRIER_TECHNOLOGY_LABEL;
76
77     /** The producer plugin class for the REST carrier technology. */
78     protected String EVENT_PRODUCER_PLUGIN_CLASS;
79
80     /** The consumer plugin class for the REST carrier technology. */
81     protected String EVENT_CONSUMER_PLUGIN_CLASS;
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     protected static final Pattern patternErrorKey =
93             Pattern.compile("(\\{[^\\{}]*.?\\{)|(\\{[^\\{}]*$)|(\\}[^\\{}]*.?\\})|(^[^\\{}]*.?\\})|\\{\\s*\\}");
94
95     //variable
96     protected String url = null;
97     protected HttpMethod httpMethod = null;
98     protected String[][] httpHeaders = null;
99     protected String httpCodeFilter = DEFAULT_HTTP_CODE_FILTER;
100
101     /**
102      * Constructor to create a REST carrier technology parameters instance and register the instance with the parameter
103      * service.
104      */
105     public RestPluginCarrierTechnologyParameters() {
106         super();
107
108         // Set the carrier technology properties for the web socket carrier technology
109         CARRIER_TECHNOLOGY_LABEL = "RESTPLUGIN";
110         EVENT_PRODUCER_PLUGIN_CLASS = "PRODUCER";
111         EVENT_CONSUMER_PLUGIN_CLASS = "CONSUMER";
112         this.setLabel(CARRIER_TECHNOLOGY_LABEL);
113         this.setEventProducerPluginClass(EVENT_PRODUCER_PLUGIN_CLASS);
114         this.setEventConsumerPluginClass(EVENT_CONSUMER_PLUGIN_CLASS);
115     }
116
117     /**
118      * Check if http headers have been set for the REST request.
119      *
120      * @return true if headers have been set
121      */
122     public boolean checkHttpHeadersSet() {
123         return httpHeaders != null && httpHeaders.length > 0;
124     }
125
126     /**
127      * Gets the http headers for the REST request as a multivalued map.
128      *
129      * @return the headers
130      */
131     public MultivaluedMap<String, Object> getHttpHeadersAsMultivaluedMap() {
132         if (httpHeaders == null) {
133             return null;
134         }
135
136         // Load the HTTP headers into the map
137         MultivaluedMap<String, Object> httpHeaderMap = new MultivaluedHashMap<>();
138
139         for (String[] httpHeader : httpHeaders) {
140             httpHeaderMap.putSingle(httpHeader[0], httpHeader[1]);
141         }
142
143         return httpHeaderMap;
144     }
145
146     /**
147      * Sets the header for the REST request.
148      *
149      * @param httpHeaders the incoming HTTP headers
150      */
151     public void setHttpHeaders(final String[][] httpHeaders) {
152         this.httpHeaders = httpHeaders;
153     }
154
155     /**
156      * Get the tag for the REST Producer Properties.
157      *
158      * @return set of the tags
159      */
160     public Set<String> getKeysFromUrl() {
161         Matcher matcher = patternProperKey.matcher(getUrl());
162         Set<String> key = new HashSet<>();
163         while (matcher.find()) {
164             key.add(matcher.group());
165         }
166         return key;
167     }
168
169     /**
170      * {@inheritDoc}.
171      */
172     @Override
173     public GroupValidationResult validate() {
174         GroupValidationResult result = super.validate();
175
176         result = validateUrl(result);
177
178         result = validateHttpHeaders(result);
179
180         return validateHttpCodeFilter(result);
181     }
182
183     // @formatter:off
184     /**
185      * Validate the URL.
186      *
187      * <p>Checks:
188      * http://www.blah.com/{par1/somethingelse (Missing end tag) use  {[^\\{}]*$
189      * http://www.blah.com/{par1/{some}thingelse (Nested tag) use {[^}]*{
190      * http://www.blah.com/{par1}/some}thingelse (Missing start tag1) use }[^{}]*.}
191      * http://www.blah.com/par1}/somethingelse (Missing start tag2) use }[^{}]*}
192      * http://www.blah.com/{}/somethingelse (Empty tag) use {[\s]*}
193      * @param result the result of the validation
194      */
195     // @formatter:on
196     public GroupValidationResult validateUrl(final GroupValidationResult result) {
197         // Check if the URL has been set for event output
198         String URL_ERROR_MSG = "no URL has been set for event sending on " + CARRIER_TECHNOLOGY_LABEL;
199         if (getUrl() == null) {
200             result.setResult("url", ValidationStatus.INVALID, URL_ERROR_MSG);
201             return result;
202         }
203
204         Matcher matcher = patternErrorKey.matcher(getUrl());
205         if (matcher.find()) {
206             result.setResult("url", ValidationStatus.INVALID,
207                     URL_ERROR_MSG);
208         }
209
210         return result;
211     }
212
213     /**
214      * Validate the HTTP headers.
215      *
216      * @param result the result of the validation
217      */
218     private GroupValidationResult validateHttpHeaders(final GroupValidationResult result) {
219         if (httpHeaders == null) {
220             return result;
221         }
222
223         for (String[] httpHeader : httpHeaders) {
224             if (httpHeader == null) {
225                 result.setResult(HTTP_HEADERS, ValidationStatus.INVALID, "HTTP header array entry is null");
226             } else if (httpHeader.length != 2) {
227                 result.setResult(HTTP_HEADERS, ValidationStatus.INVALID,
228                         "HTTP header array entries must have one key and one value: "
229                                 + Arrays.deepToString(httpHeader));
230             } else if (!ParameterValidationUtils.validateStringParameter(httpHeader[0])) {
231                 result.setResult(HTTP_HEADERS, ValidationStatus.INVALID,
232                         "HTTP header key is null or blank: " + Arrays.deepToString(httpHeader));
233             } else if (!ParameterValidationUtils.validateStringParameter(httpHeader[1])) {
234                 result.setResult(HTTP_HEADERS, ValidationStatus.INVALID,
235                         "HTTP header value is null or blank: " + Arrays.deepToString(httpHeader));
236             }
237         }
238
239         return result;
240     }
241
242     /**
243      * Validate the HTTP code filter.
244      *
245      * @param result the result of the validation
246      */
247     public GroupValidationResult validateHttpCodeFilter(final GroupValidationResult result) {
248         if (httpCodeFilter == null) {
249             httpCodeFilter = DEFAULT_HTTP_CODE_FILTER;
250
251         } else if (StringUtils.isBlank(httpCodeFilter)) {
252             result.setResult(HTTP_CODE_FILTER, ValidationStatus.INVALID,
253                     "HTTP code filter must be specified as a three digit regular expression");
254         } else {
255             try {
256                 Pattern.compile(httpCodeFilter);
257             } catch (PatternSyntaxException pse) {
258                 String message =
259                         "Invalid HTTP code filter, the filter must be specified as a three digit regular expression: "
260                                 + pse.getMessage();
261                 result.setResult(HTTP_CODE_FILTER, ValidationStatus.INVALID, message);
262                 LOGGER.debug(message, pse);
263             }
264         }
265
266         return result;
267     }
268
269     /**
270      * {@inheritDoc}.
271      */
272     @Override
273     public String toString() {
274         return CARRIER_TECHNOLOGY_LABEL +"CarrierTechnologyParameters [url=" + url + ", httpMethod=" + httpMethod + ", httpHeaders="
275                 + Arrays.deepToString(httpHeaders) + ", httpCodeFilter=" + httpCodeFilter + "]";
276     }
277 }