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
10 * http://www.apache.org/licenses/LICENSE-2.0
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.
18 * SPDX-License-Identifier: Apache-2.0
19 * ============LICENSE_END=========================================================
22 package org.onap.policy.apex.plugins.event.carrier.restrequestor;
24 import java.util.Arrays;
25 import java.util.HashSet;
27 import java.util.regex.Matcher;
28 import java.util.regex.Pattern;
29 import java.util.regex.PatternSyntaxException;
31 import javax.ws.rs.core.MultivaluedHashMap;
32 import javax.ws.rs.core.MultivaluedMap;
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;
46 * Apex parameters for REST as an event carrier technology with Apex issuing a REST request and receiving a REST
49 * <p>The parameters for this plugin are:
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]"
61 * @author Liam Fallon (liam.fallon@ericsson.com)
66 public class RestRequestorCarrierTechnologyParameters extends CarrierTechnologyParameters {
67 // Get a reference to the logger
68 private static final Logger LOGGER = LoggerFactory.getLogger(RestRequestorCarrierTechnologyParameters.class);
70 /** The supported HTTP methods. */
71 public enum HttpMethod {
72 GET, PUT, POST, DELETE
75 /** The label of this carrier technology. */
76 public static final String RESTREQUESTOR_CARRIER_TECHNOLOGY_LABEL = "RESTREQUESTOR";
78 /** The producer plugin class for the REST carrier technology. */
79 public static final String RESTREQUSTOR_EVENT_PRODUCER_PLUGIN_CLASS =
80 ApexRestRequestorProducer.class.getCanonicalName();
82 /** The consumer plugin class for the REST carrier technology. */
83 public static final String RESTREQUSTOR_EVENT_CONSUMER_PLUGIN_CLASS =
84 ApexRestRequestorConsumer.class.getCanonicalName();
86 /** The default HTTP method for request events. */
87 public static final HttpMethod DEFAULT_REQUESTOR_HTTP_METHOD = HttpMethod.GET;
89 /** The default timeout for REST requests. */
90 public static final long DEFAULT_REST_REQUEST_TIMEOUT = 500;
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]";
95 // Commonly occurring strings
96 private static final String HTTP_HEADERS = "httpHeaders";
97 private static final String HTTP_CODE_FILTER = "httpCodeFilter";
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*\\}");
104 private String url = null;
105 private HttpMethod httpMethod = null;
106 private String[][] httpHeaders = null;
107 private String httpCodeFilter = DEFAULT_HTTP_CODE_FILTER;
110 * Constructor to create a REST carrier technology parameters instance and register the instance with the parameter
113 public RestRequestorCarrierTechnologyParameters() {
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);
123 * Check if http headers have been set for the REST request.
125 * @return true if headers have beenset
127 public boolean checkHttpHeadersSet() {
128 return httpHeaders != null && httpHeaders.length > 0;
132 * Gets the http headers for the REST request as a multivalued map.
134 * @return the headers
136 public MultivaluedMap<String, Object> getHttpHeadersAsMultivaluedMap() {
137 if (httpHeaders == null) {
141 // Load the HTTP headers into the map
142 MultivaluedMap<String, Object> httpHeaderMap = new MultivaluedHashMap<>();
144 for (String[] httpHeader : httpHeaders) {
145 httpHeaderMap.putSingle(httpHeader[0], httpHeader[1]);
148 return httpHeaderMap;
152 * Sets the header for the REST request.
154 * @param httpHeaders the incoming HTTP headers
156 public void setHttpHeaders(final String[][] httpHeaders) {
157 this.httpHeaders = httpHeaders;
161 * Get the tag for the REST Producer Properties.
163 * @return set of the tags
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());
179 public GroupValidationResult validate() {
180 GroupValidationResult result = super.validate();
182 result = validateUrl(result);
184 result = validateHttpHeaders(result);
186 return validateHttpCodeFilter(result);
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
202 private GroupValidationResult validateUrl(final GroupValidationResult result) {
203 // URL is only set on Requestor consumers
204 if (getUrl() == null) {
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");
218 * Validate the HTTP headers.
220 * @param result the result of the validation
222 private GroupValidationResult validateHttpHeaders(final GroupValidationResult result) {
223 if (httpHeaders == null) {
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));
247 * Validate the HTTP code filter.
249 * @param result the result of the validation
251 public GroupValidationResult validateHttpCodeFilter(final GroupValidationResult result) {
252 if (httpCodeFilter == null) {
253 httpCodeFilter = DEFAULT_HTTP_CODE_FILTER;
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");
260 Pattern.compile(httpCodeFilter);
261 } catch (PatternSyntaxException pse) {
263 "Invalid HTTP code filter, the filter must be specified as a three digit regular expression: "
265 result.setResult(HTTP_CODE_FILTER, ValidationStatus.INVALID, message);
266 LOGGER.debug(message, pse);
277 public String toString() {
278 return "RESTRequestorCarrierTechnologyParameters [url=" + url + ", httpMethod=" + httpMethod + ", httpHeaders="
279 + Arrays.deepToString(httpHeaders) + ", httpCodeFilter=" + httpCodeFilter + "]";