d583b790e44505ea2cad705ddd2d5ebc54289ab5
[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
30 import javax.ws.rs.core.MultivaluedHashMap;
31 import javax.ws.rs.core.MultivaluedMap;
32
33 import org.onap.policy.apex.service.parameters.carriertechnology.CarrierTechnologyParameters;
34 import org.onap.policy.common.parameters.GroupValidationResult;
35 import org.onap.policy.common.parameters.ValidationStatus;
36 import org.onap.policy.common.utils.validation.ParameterValidationUtils;
37
38 // @formatter:off
39 /**
40  * Apex parameters for REST as an event carrier technology with Apex issuing a REST request and receiving a REST
41  * response.
42  *
43  * <p>The parameters for this plugin are:
44  * <ol>
45  * <li>url: The URL that the Apex Rest Requestor will connect to over REST for REST request sending.
46  * This parameter is mandatory.
47  * <li>httpMethod: The HTTP method to use when making requests over REST, legal values are GET (default),
48  *  POST, PUT, and DELETE.
49  * <li>restRequestTimeout: The time in milliseconds to wait for a REST request to complete.
50  * <li>restRequestHeader: The necessary header needed
51  * </ol>
52  *
53  * @author Liam Fallon (liam.fallon@ericsson.com)
54  */
55 //@formatter:on
56 public class RestRequestorCarrierTechnologyParameters extends CarrierTechnologyParameters {
57     /** The supported HTTP methods. */
58     public enum HttpMethod {
59         GET, PUT, POST, DELETE
60     }
61
62     /** The label of this carrier technology. */
63     public static final String RESTREQUESTOR_CARRIER_TECHNOLOGY_LABEL = "RESTREQUESTOR";
64
65     /** The producer plugin class for the REST carrier technology. */
66     public static final String RESTREQUSTOR_EVENT_PRODUCER_PLUGIN_CLASS = ApexRestRequestorProducer.class
67                     .getCanonicalName();
68
69     /** The consumer plugin class for the REST carrier technology. */
70     public static final String RESTREQUSTOR_EVENT_CONSUMER_PLUGIN_CLASS = ApexRestRequestorConsumer.class
71                     .getCanonicalName();
72
73     /** The default HTTP method for request events. */
74     public static final HttpMethod DEFAULT_REQUESTOR_HTTP_METHOD = HttpMethod.GET;
75
76     /** The default timeout for REST requests. */
77     public static final long DEFAULT_REST_REQUEST_TIMEOUT = 500;
78
79     // Commonly occurring strings
80     private static final String HTTP_HEADERS = "httpHeaders";
81
82     private String url = null;
83     private HttpMethod httpMethod = null;
84     private String[][] httpHeaders = null;
85
86     private static final Pattern patternProperKey = Pattern.compile("(?<=\\{)[^}]*(?=\\})");
87     private static final Pattern patternErrorKey = Pattern.compile(
88         "(\\{[^\\{}]*.?\\{)|(\\{[^\\{}]*$)|(\\}[^\\{}]*.?\\})|(^[^\\{}]*.?\\})|\\{\\s*\\}");
89
90     /**
91      * Constructor to create a REST carrier technology parameters instance and register the instance with the
92      * parameter service.
93      */
94     public RestRequestorCarrierTechnologyParameters() {
95         super();
96
97         // Set the carrier technology properties for the web socket carrier technology
98         this.setLabel(RESTREQUESTOR_CARRIER_TECHNOLOGY_LABEL);
99         this.setEventProducerPluginClass(RESTREQUSTOR_EVENT_PRODUCER_PLUGIN_CLASS);
100         this.setEventConsumerPluginClass(RESTREQUSTOR_EVENT_CONSUMER_PLUGIN_CLASS);
101     }
102
103     /**
104      * Gets the URL for the REST request.
105      *
106      * @return the URL
107      */
108     public String getUrl() {
109         return url;
110     }
111
112     /**
113      * Sets the URL for the REST request.
114      *
115      * @param incomingUrl the URL
116      */
117     public void setUrl(final String incomingUrl) {
118         this.url = incomingUrl;
119     }
120
121     /**
122      * Gets the HTTP method to use for the REST request.
123      *
124      * @return the HTTP method
125      */
126     public HttpMethod getHttpMethod() {
127         return httpMethod;
128     }
129
130     /**
131      * Sets the HTTP method to use for the REST request.
132      *
133      * @param httpMethod the HTTP method
134      */
135     public void setHttpMethod(final HttpMethod httpMethod) {
136         this.httpMethod = httpMethod;
137     }
138
139     /**
140      * Check if http headers have been set for the REST request.
141      *
142      * @return true if headers have beenset
143      */
144     public boolean checkHttpHeadersSet() {
145         return httpHeaders != null && httpHeaders.length > 0;
146     }
147
148     /**
149      * Gets the http headers for the REST request.
150      *
151      * @return the headers
152      */
153     public String[][] getHttpHeaders() {
154         return httpHeaders;
155     }
156
157     /**
158      * Gets the http headers for the REST request as a multivalued map.
159      *
160      * @return the headers
161      */
162     public MultivaluedMap<String, Object> getHttpHeadersAsMultivaluedMap() {
163         if (httpHeaders == null) {
164             return null;
165         }
166
167         // Load the HTTP headers into the map
168         MultivaluedMap<String, Object> httpHeaderMap = new MultivaluedHashMap<>();
169
170         for (String[] httpHeader : httpHeaders) {
171             httpHeaderMap.putSingle(httpHeader[0], httpHeader[1]);
172         }
173
174         return httpHeaderMap;
175     }
176
177     /**
178      * Sets the header for the REST request.
179      *
180      * @param httpHeaders the incoming HTTP headers
181      */
182     public void setHttpHeaders(final String[][] httpHeaders) {
183         this.httpHeaders = httpHeaders;
184     }
185
186     /**
187      * Get the tag for the REST Producer Properties.
188      *
189      * @return set of the tags
190      */
191     public Set<String> getKeysFromUrl() {
192         Matcher matcher = patternProperKey.matcher(this.url);
193         Set<String> key = new HashSet<>();
194         while (matcher.find()) {
195             key.add(matcher.group());
196         }
197         return key;
198     }
199
200     /**
201      * Validate tags in url.
202      * http://www.blah.com/{par1/somethingelse (Missing end tag) use  {[^\\{}]*$
203      * http://www.blah.com/{par1/{some}thingelse (Missing end tag2) use {[^}]*{
204      * http://www.blah.com/{par1}/some}thingelse (Missing start tag1) use }[^{}]*.}
205      * http://www.blah.com/par1}/somethingelse (Missing start tag2) use }[^{}]*}
206      * http://www.blah.com/{}/somethingelse (Empty tag) use {[\s]*}
207      *
208      * @return if url is legal
209      */
210     public boolean validateTagInUrl() {
211         // Check url tag syntax error
212         Matcher matcher = patternErrorKey.matcher(this.url);
213         return (!matcher.find());
214     }
215
216     /**
217      * {@inheritDoc}.
218      */
219     @Override
220     public GroupValidationResult validate() {
221         final GroupValidationResult result = super.validate();
222
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         if (!validateTagInUrl()) {
244             result.setResult("url", ValidationStatus.INVALID,
245                 "no proper URL has been set for event sending on REST client");
246         }
247
248
249         return result;
250     }
251
252     /**
253      * {@inheritDoc}.
254      */
255     @Override
256     public String toString() {
257         return "RESTRequestorCarrierTechnologyParameters [url=" + url + ", httpMethod=" + httpMethod + ", httpHeaders="
258                         + Arrays.deepToString(httpHeaders) + "]";
259     }
260 }