From 5a6a6de6f1a26a1897e4917a0df613e25a24eb70 Mon Sep 17 00:00:00 2001 From: "Benjamin, Max (mb388a)" Date: Mon, 30 Jul 2018 15:56:09 -0400 Subject: Containerization feature of SO Change-Id: I95381232eeefcd247a66a5cec370a8ce1c288e18 Issue-ID: SO-670 Signed-off-by: Benjamin, Max (mb388a) --- bpmn/MSORESTClient/pom.xml | 2 +- .../main/java/org/onap/so/rest/APIResponse.java | 145 +++++ .../java/org/onap/so/rest/HostNameVerifier.java | 49 ++ .../src/main/java/org/onap/so/rest/HttpHeader.java | 65 +++ .../src/main/java/org/onap/so/rest/RESTClient.java | 623 +++++++++++++++++++++ .../src/main/java/org/onap/so/rest/RESTConfig.java | 131 +++++ .../main/java/org/onap/so/rest/RESTException.java | 85 +++ .../java/org/openecomp/mso/rest/APIResponse.java | 145 ----- .../org/openecomp/mso/rest/HostNameVerifier.java | 49 -- .../java/org/openecomp/mso/rest/HttpHeader.java | 65 --- .../java/org/openecomp/mso/rest/RESTClient.java | 614 -------------------- .../java/org/openecomp/mso/rest/RESTConfig.java | 131 ----- .../java/org/openecomp/mso/rest/RESTException.java | 85 --- .../java/org/onap/so/rest/APIResponseTest.java | 57 ++ .../test/java/org/onap/so/rest/HttpHeaderTest.java | 40 ++ .../test/java/org/onap/so/rest/RESTClientTest.java | 195 +++++++ .../test/java/org/onap/so/rest/RESTConfigTest.java | 42 ++ .../java/org/onap/so/rest/RESTExceptionTest.java | 40 ++ .../org/openecomp/mso/rest/APIResponseTest.java | 57 -- .../org/openecomp/mso/rest/HttpHeaderTest.java | 34 -- .../org/openecomp/mso/rest/RESTClientTest.java | 50 -- .../org/openecomp/mso/rest/RESTConfigTest.java | 42 -- .../org/openecomp/mso/rest/RESTExceptionTest.java | 37 -- 23 files changed, 1473 insertions(+), 1310 deletions(-) create mode 100644 bpmn/MSORESTClient/src/main/java/org/onap/so/rest/APIResponse.java create mode 100644 bpmn/MSORESTClient/src/main/java/org/onap/so/rest/HostNameVerifier.java create mode 100644 bpmn/MSORESTClient/src/main/java/org/onap/so/rest/HttpHeader.java create mode 100644 bpmn/MSORESTClient/src/main/java/org/onap/so/rest/RESTClient.java create mode 100644 bpmn/MSORESTClient/src/main/java/org/onap/so/rest/RESTConfig.java create mode 100644 bpmn/MSORESTClient/src/main/java/org/onap/so/rest/RESTException.java delete mode 100644 bpmn/MSORESTClient/src/main/java/org/openecomp/mso/rest/APIResponse.java delete mode 100644 bpmn/MSORESTClient/src/main/java/org/openecomp/mso/rest/HostNameVerifier.java delete mode 100644 bpmn/MSORESTClient/src/main/java/org/openecomp/mso/rest/HttpHeader.java delete mode 100644 bpmn/MSORESTClient/src/main/java/org/openecomp/mso/rest/RESTClient.java delete mode 100644 bpmn/MSORESTClient/src/main/java/org/openecomp/mso/rest/RESTConfig.java delete mode 100644 bpmn/MSORESTClient/src/main/java/org/openecomp/mso/rest/RESTException.java create mode 100644 bpmn/MSORESTClient/src/test/java/org/onap/so/rest/APIResponseTest.java create mode 100644 bpmn/MSORESTClient/src/test/java/org/onap/so/rest/HttpHeaderTest.java create mode 100644 bpmn/MSORESTClient/src/test/java/org/onap/so/rest/RESTClientTest.java create mode 100644 bpmn/MSORESTClient/src/test/java/org/onap/so/rest/RESTConfigTest.java create mode 100644 bpmn/MSORESTClient/src/test/java/org/onap/so/rest/RESTExceptionTest.java delete mode 100644 bpmn/MSORESTClient/src/test/java/org/openecomp/mso/rest/APIResponseTest.java delete mode 100644 bpmn/MSORESTClient/src/test/java/org/openecomp/mso/rest/HttpHeaderTest.java delete mode 100644 bpmn/MSORESTClient/src/test/java/org/openecomp/mso/rest/RESTClientTest.java delete mode 100644 bpmn/MSORESTClient/src/test/java/org/openecomp/mso/rest/RESTConfigTest.java delete mode 100644 bpmn/MSORESTClient/src/test/java/org/openecomp/mso/rest/RESTExceptionTest.java (limited to 'bpmn/MSORESTClient') diff --git a/bpmn/MSORESTClient/pom.xml b/bpmn/MSORESTClient/pom.xml index 6f2f007e5f..ee5bdff485 100644 --- a/bpmn/MSORESTClient/pom.xml +++ b/bpmn/MSORESTClient/pom.xml @@ -6,7 +6,7 @@ org.onap.so bpmn - 1.2.0-SNAPSHOT + 1.3.0-SNAPSHOT MSORESTClient diff --git a/bpmn/MSORESTClient/src/main/java/org/onap/so/rest/APIResponse.java b/bpmn/MSORESTClient/src/main/java/org/onap/so/rest/APIResponse.java new file mode 100644 index 0000000000..b77c90b215 --- /dev/null +++ b/bpmn/MSORESTClient/src/main/java/org/onap/so/rest/APIResponse.java @@ -0,0 +1,145 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.rest; + +import java.io.IOException; +import java.util.Arrays; + +import org.apache.http.Header; +import org.apache.http.HttpResponse; +import org.apache.http.util.EntityUtils; + +/** + * An immutable class that encapsulates an API response. + * + * @version 1.0 + * @since 1.0 + */ +public class APIResponse { + private final int statusCode; + private final byte[] responseBody; + private final HttpHeader[] headers; + + /** + * Internal method used to create http headers using the specified + * HttpResponse object. + * + * @param httpResponse used to create headers + * @return http headers + */ + private static HttpHeader[] buildHeaders(final HttpResponse httpResponse) { + final Header[] headers = httpResponse.getAllHeaders(); + + HttpHeader[] httpHeaders = new HttpHeader[headers.length]; + for (int i = 0; i < headers.length; ++i) { + final Header header = headers[i]; + final String name = header.getName(); + final String value = header.getValue(); + final HttpHeader httpHeader = new HttpHeader(name, value); + httpHeaders[i] = httpHeader; + } + + return httpHeaders; + } + + /** + * Create an APIResponse object using the specified HttpResponse object. + * + * @param httpResponse used to create the APIResponse + * + * @throws RESTException if unable to read from the HttpResponse object + */ + public APIResponse(final HttpResponse httpResponse) throws RESTException { + try { + this.statusCode = httpResponse.getStatusLine().getStatusCode(); + + if (httpResponse.getEntity() == null) + { + this.responseBody = null; + } + else + { + this.responseBody = EntityUtils.toByteArray(httpResponse.getEntity()); + } + + this.headers = buildHeaders(httpResponse); + } catch (IOException ioe) { + throw new RESTException(ioe); + } + } + + /** + * Gets the http status code returned by the api server. + *

+ * For example, status code 200 represents 'OK.' + * + * @return status code + */ + public int getStatusCode() { + return this.statusCode; + } + + /** + * Gets the http response body as a byte array. + * + * @return http response body + */ + public byte[] getResponseBodyAsByteArray() { + // avoid exposing internals, create copy + if (this.responseBody != null) { + return Arrays.copyOf(this.responseBody, this.responseBody.length); + } else { + return null; + } + } + + /** + * Gets the http response body as a string. + * + * @return http response body + */ + public String getResponseBodyAsString() { + if (this.responseBody != null) { + return new String(this.responseBody); + } else { + return ""; + } + } + + /** + * Gets a list of all the headers returned by the API response. + * + * @return an array of all the HttpHeaders + */ + public HttpHeader[] getAllHeaders() { + // avoid exposing internals, create copy + return Arrays.copyOf(this.headers, this.headers.length); + } + + public String getFirstHeader(String name) { + for (HttpHeader header : headers) { + if (header.getName().equals(name)) { + return header.getValue(); + } + } + return null; + } +} diff --git a/bpmn/MSORESTClient/src/main/java/org/onap/so/rest/HostNameVerifier.java b/bpmn/MSORESTClient/src/main/java/org/onap/so/rest/HostNameVerifier.java new file mode 100644 index 0000000000..3d10c0391d --- /dev/null +++ b/bpmn/MSORESTClient/src/main/java/org/onap/so/rest/HostNameVerifier.java @@ -0,0 +1,49 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017 Huawei Technologies Co., Ltd. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.rest; + +import javax.net.ssl.SSLException; + +import org.apache.http.conn.ssl.AbstractVerifier; +import org.onap.so.logger.MsoLogger; + +/** + * @version 1.0 + * Place holder to validate host name, for now just invokes the super class method + * + */ +public class HostNameVerifier extends AbstractVerifier { + + private static final MsoLogger LOGGER = MsoLogger.getMsoLogger (MsoLogger.Catalog.RA, HostNameVerifier.class); + + public final void verify( + final String host, + final String[] cns, + final String[] subjectAlts) throws SSLException { + try { + verify(host, cns, subjectAlts, true); + } catch (SSLException sex) { + LOGGER.debug("Exception:", sex); + } + } + +} diff --git a/bpmn/MSORESTClient/src/main/java/org/onap/so/rest/HttpHeader.java b/bpmn/MSORESTClient/src/main/java/org/onap/so/rest/HttpHeader.java new file mode 100644 index 0000000000..a96793334d --- /dev/null +++ b/bpmn/MSORESTClient/src/main/java/org/onap/so/rest/HttpHeader.java @@ -0,0 +1,65 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.rest; + +/** + * An immutable class used to wrap an http header. + * + * @version 1.0 + * @since 1.0 + */ +public class HttpHeader { + private final String name; + private final String value; + + /** + * Create an http header using the specified name and value + * + * @param name name of http header + * @param value value of http header + */ + public HttpHeader(final String name, final String value) { + if (name == null) { + throw new IllegalArgumentException("Name may not be null."); + } + + this.name = name; + this.value = value; + } + + /** + * Gets the header name. + * + * @return header name + */ + public String getName() { + return this.name; + } + + /** + * Gets the header value. + * + * @return header value + */ + public String getValue() { + return this.value; + } +} diff --git a/bpmn/MSORESTClient/src/main/java/org/onap/so/rest/RESTClient.java b/bpmn/MSORESTClient/src/main/java/org/onap/so/rest/RESTClient.java new file mode 100644 index 0000000000..fc6266d917 --- /dev/null +++ b/bpmn/MSORESTClient/src/main/java/org/onap/so/rest/RESTClient.java @@ -0,0 +1,623 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017 Huawei Technologies Co., Ltd. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.rest; + +import java.io.IOException; +import java.io.UnsupportedEncodingException; +import java.net.URI; +import java.net.URLEncoder; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import javax.net.ssl.SSLSocketFactory; + +import org.apache.http.HttpEntity; +import org.apache.http.HttpHost; +import org.apache.http.HttpResponse; +import org.apache.http.client.config.RequestConfig; +import org.apache.http.client.methods.HttpEntityEnclosingRequestBase; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpPatch; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.client.methods.HttpPut; +import org.apache.http.config.Registry; +import org.apache.http.config.RegistryBuilder; +import org.apache.http.conn.socket.ConnectionSocketFactory; +import org.apache.http.conn.socket.PlainConnectionSocketFactory; +import org.apache.http.conn.ssl.SSLConnectionSocketFactory; +import org.apache.http.entity.StringEntity; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClientBuilder; +import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; +import org.apache.http.message.AbstractHttpMessage; +import org.apache.http.util.EntityUtils; +import org.onap.so.logger.MsoLogger; +/** + * Client used to send RESTFul requests. + *

+ * Many of the methods return a reference to the 'this,' thereby allowing + * method chaining. + *
+ * An example of usage can be found below: + *

+ * RESTClient client;
+ * try {
+ *     client = new RESTClient("http://www.openecomp.org");
+ *     APIResponse response = client
+ *         .setHeader("Accept", "application/json")
+ *         .setHeader("Clientid", "clientid")
+ *         .setHeader("header", "value")
+ *         .httpPost("postbody");
+ *     if (response.getStatusCode() == 200) {
+ *         System.out.println("Success!");
+ *     }
+ *  } catch (RESTException re) {
+ *      // Handle Exception
+ *  }
+ * 
+ * + * @version 1.0 + * @since 1.0 + */ +public class RESTClient { + + private static final MsoLogger LOGGER = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL,RESTClient.class); + private final String proxyHost; + private final int proxyPort; + + private final String url; + + private final Map> headers; + private final Map> parameters; + + + + private HttpEntity httpEntity; + + /** + * Internal method used to build an APIResponse using the specified + * HttpResponse object. + * + * @param response response wrapped inside an APIResponse object + * @return api response + */ + private APIResponse buildResponse(HttpResponse response) + throws RESTException { + + return new APIResponse(response); + } + + /** + * Used to release any resources used by the connection. + * @param response HttpResponse object used for releasing the connection + * @throws RESTException if unable to release connection + * + */ + private void releaseConnection(HttpResponse response) throws RESTException { + try { + EntityUtils.consume(response.getEntity()); + } catch (IOException ioe) { + throw new RESTException(ioe); + } + } + + /** + * Sets headers to the http message. + * + * @param httpMsg http message to set headers for + */ + private void addInternalHeaders(AbstractHttpMessage httpMsg) { + if (headers.isEmpty()) { + return; + } + + final Set keySet = headers.keySet(); + for (final String key : keySet) { + final List values = headers.get(key); + for (final String value : values) { + httpMsg.addHeader(key, value); + } + } + } + + /** + * Builds the query part of a URL. + * + * @return query + */ + private String buildQuery() { + if (this.parameters.size() == 0) { + return ""; + } + + StringBuilder sb = new StringBuilder(); + String charSet = "UTF-8"; + try { + Iterator keyitr = this.parameters.keySet().iterator(); + for (int i = 0; keyitr.hasNext(); ++i) { + if (i > 0) { + sb.append("&"); + } + + final String name = keyitr.next(); + final List values = this.parameters.get(name); + for(final String value : values) { + sb.append(URLEncoder.encode(name, charSet)); + sb.append("="); + sb.append(URLEncoder.encode(value, charSet)); + } + } + } catch (UnsupportedEncodingException e) { + LOGGER.debug("Exception :", e); + } + return sb.toString(); + } + + /** + * Creates an http client that can be used for sending http requests. + * + * @return created http client + * + * @throws RESTException if unable to create http client. + */ + private CloseableHttpClient createClient() throws RESTException { + HttpClientBuilder clientBuilder; + try { + SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory( + (SSLSocketFactory) SSLSocketFactory.getDefault(), + new HostNameVerifier()); + Registry registry = RegistryBuilder + . create() + .register("http", PlainConnectionSocketFactory.getSocketFactory()) + .register("https", sslSocketFactory).build(); + PoolingHttpClientConnectionManager manager = new PoolingHttpClientConnectionManager(registry); + clientBuilder = HttpClientBuilder.create().setConnectionManager(manager); + } catch (Exception ex) { + LOGGER.debug("Exception :", ex); + throw new RESTException(ex.getMessage()); + } + clientBuilder.disableRedirectHandling(); + + if ((this.proxyHost != null) && (this.proxyPort != -1)) { + HttpHost proxy = new HttpHost(this.proxyHost, this.proxyPort); + clientBuilder.setProxy(proxy); + } + int timeoutInSeconds = 300; + RequestConfig requestConfig = RequestConfig.custom() + .setConnectTimeout(timeoutInSeconds * 1000) + .setConnectionRequestTimeout(timeoutInSeconds * 1000) + .setSocketTimeout(timeoutInSeconds * 1000).build(); + return clientBuilder.setDefaultRequestConfig(requestConfig).build(); + } + + + + + + /** + * Creates a RESTClient with the specified URL, proxy host, and proxy port. + * + * @param url URL to send request to + * @param proxyHost proxy host to use for sending request + * @param proxyPort proxy port to use for sendin request + * + * @throws RESTException if unable to create a RESTClient + */ + public RESTClient(String url, String proxyHost, int proxyPort) { + this(new RESTConfig(url, proxyHost, proxyPort)); + } + + /** + * Creates a RESTClient with the specified URL. No proxy host nor port will + * be used. + * + * @param url URL to send request to + * + * @throws RESTException if unable to create a RESTClient + */ + public RESTClient(String url) { + this(new RESTConfig(url)); + } + + /** + * Creates a RESTClient with the RESTConfig object. + * + * @param restConfig config to use for sending request + * + * @throws RESTException if unable to create a RESTClient + */ + public RESTClient(RESTConfig restConfig) { + this.headers = new LinkedHashMap<>(); + this.parameters = new LinkedHashMap<>(); + this.url = restConfig.getURL(); + this.proxyHost = restConfig.getProxyHost(); + this.proxyPort = restConfig.getProxyPort(); + } + + /** + * Adds parameter to be sent during http request. + *

+ * Does not remove any parameters with the same name, thus allowing + * duplicates. + * + * @param name name of parameter + * @param value value of parametr + * @return a reference to 'this', which can be used for method chaining + */ + public RESTClient addParameter(String name, String value) { + if (!parameters.containsKey(name)) { + parameters.put(name, new ArrayList<>()); + } + + List values = parameters.get(name); + values.add(value); + + return this; + } + + /** + * Sets parameter to be sent during http request. + *

+ * Removes any parameters with the same name, thus disallowing duplicates. + * + * @param name name of parameter + * @param value value of parametr + * @return a reference to 'this', which can be used for method chaining + */ + public RESTClient setParameter(String name, String value) { + if (parameters.containsKey(name)) { + parameters.get(name).clear(); + } + + addParameter(name, value); + + return this; + } + + /** + * Adds http header to be sent during http request. + *

+ * Does not remove any headers with the same name, thus allowing + * duplicates. + * + * @param name name of header + * @param value value of header + * @return a reference to 'this', which can be used for method chaining + */ + public RESTClient addHeader(String name, String value) { + if (!headers.containsKey(name)) { + headers.put(name, new ArrayList<>()); + } + + List values = headers.get(name); + values.add(value); + + return this; + } + + /** + * Sets http header to be sent during http request. + *

+ * Does not remove any headers with the same name, thus allowing + * duplicates. + * + * @param name name of header + * @param value value of header + * @return a reference to 'this', which can be used for method chaining + */ + public RESTClient setHeader(String name, String value) { + if (headers.containsKey(name)) { + headers.get(name).clear(); + } + + addHeader(name, value); + + return this; + } + + /** + * Convenience method for adding the authorization header using the + * specified OAuthToken object. + * + * @param token token to use for setting authorization + * @return a reference to 'this,' which can be used for method chaining + */ + public RESTClient addAuthorizationHeader(String token) { + this.addHeader("Authorization", token); + return this; + } + + /** + * Alias for httpGet(). + * + * @see RESTClient#httpGet() + */ + public APIResponse get() throws RESTException { + return httpGet(); + } + + /** + * Sends an http GET request using the parameters and headers previously + * set. + * + * @return api response + * + * @throws RESTException if request was unsuccessful + */ + public APIResponse httpGet() throws RESTException { + HttpResponse response = null; + + try (CloseableHttpClient httpClient = createClient()) { + String query = ""; + if (!buildQuery().equals("")) { + query = "?" + buildQuery(); + } + HttpGet httpGet = new HttpGet(this.getURL() + query); + addInternalHeaders(httpGet); + + LOGGER.debug("Executing GET to url: " + this.getURL() + query); + + response = httpClient.execute(httpGet); + + return buildResponse(response); + } catch (IOException ioe) { + throw new RESTException(ioe); + } finally { + if (response != null) { + this.releaseConnection(response); + } + } + } + + /** + * Alias for httpPost() + * + * @see RESTClient#httpPost() + */ + public APIResponse post() throws RESTException { + return httpPost(); + } + + /** + * Sends an http POST request. + *

+ * POST body will be set to the values set using add/setParameter() + * + * @return api response + * + * @throws RESTException if POST was unsuccessful + */ + public APIResponse httpPost() throws RESTException { + return httpPost(buildQuery()); + } + + /** + * Sends an http POST request using the specified body. + * + * @return api response + * + * @throws RESTException if POST was unsuccessful + */ + public APIResponse httpPost(String body) throws RESTException { + HttpResponse response = null; + try (CloseableHttpClient httpClient = createClient()) { + HttpPost httpPost = new HttpPost(this.getURL()); + addInternalHeaders(httpPost); + if (body != null && !body.equals("")) { + httpEntity = new StringEntity(body); + httpPost.setEntity(new StringEntity(body)); + } + LOGGER.debug("Executing POST to url: " + this.getURL()); + + response = httpClient.execute(httpPost); + + return buildResponse(response); + + } catch (IOException e) { + throw new RESTException(e); + } finally { + if (response != null) { + this.releaseConnection(response); + } + } + } + + /** + * + * @param body Data to PUT + * @return API response + * @throws RESTException + */ + public APIResponse httpPut(String body) throws RESTException { + HttpResponse response = null; + try (CloseableHttpClient httpClient = createClient()) { + + String query = ""; + if (!buildQuery().equals("")) { + query = "?" + buildQuery(); + } + HttpPut httpPut = new HttpPut(this.getURL() + query); + addInternalHeaders(httpPut); + if (body != null && !body.equals("")) { + httpEntity = new StringEntity(body); + httpPut.setEntity(httpEntity); + } + LOGGER.debug("Executing PUT to url: " + this.getURL() + query); + + response = httpClient.execute(httpPut); + + return buildResponse(response); + } catch (IOException e) { + throw new RESTException(e); + } finally { + if (response != null) { + this.releaseConnection(response); + } + } + } + + /** + * Alias for httpPatch(). + * + * @see RESTClient#httpPatch() + */ + public APIResponse patch(String body) throws RESTException { + return httpPatch(body); + } + + /** + * + * @param body Data to PATCH + * @return API response + * @throws RESTException + */ + public APIResponse httpPatch(String body) throws RESTException { + HttpResponse response = null; + try (CloseableHttpClient httpClient = createClient()) { + String query = ""; + if (!buildQuery().equals("")) { + query = "?" + buildQuery(); + } + HttpPatch httpPatch = new HttpPatch(this.getURL() + query); + addInternalHeaders(httpPatch); + if (body != null && !body.equals("")) { + httpEntity = new StringEntity(body); + httpPatch.setEntity(httpEntity); + } + LOGGER.debug("Executing PATCH to url: " + this.getURL() + query); + + response = httpClient.execute(httpPatch); + + return buildResponse(response); + } catch (IOException e) { + throw new RESTException(e); + } finally { + if (response != null) { + this.releaseConnection(response); + } + } + } + + /** + * Alias for httpDelete(). + * + * @see RESTClient#httpDelete() + */ + public APIResponse delete() throws RESTException { + return httpDelete(); + } + + /** + * Sends an http DELETE request using the parameters and headers previously + * set. + * + * @return api response + * + * @throws RESTException if request was unsuccessful + */ + public APIResponse httpDelete() throws RESTException { + return httpDelete(null); + } + + /** + * Sends an http DELETE request with a body, using the parameters and headers + * previously set. + * + * @return api response + * + * @throws RESTException if request was unsuccessful + */ + public APIResponse httpDelete(String body) throws RESTException { + HttpResponse response = null; + + try (CloseableHttpClient httpClient = createClient()){ + + String query = ""; + if (!buildQuery().equals("")) { + query = "?" + buildQuery(); + } + HttpDeleteWithBody httpDelete = new HttpDeleteWithBody(this.getURL() + query); + addInternalHeaders(httpDelete); + + if (body != null && !body.equals("")) { + httpEntity = new StringEntity(body); + httpDelete.setEntity(httpEntity); + } + + LOGGER.debug("Executing DELETE to url: " + this.getURL() + query); + + response = httpClient.execute(httpDelete); + + return buildResponse(response); + } catch (IOException ioe) { + throw new RESTException(ioe); + } finally { + if (response != null) { + this.releaseConnection(response); + } + } + } + + public String getURL() { + return url; + } + public Map> getHeaders() { + return headers; + } + public Map> getParameters() { + return parameters; + } + public HttpEntity getHttpEntity() { + return httpEntity; + } + + + /** + * Allows inclusion of a request body with DELETE. + */ + private class HttpDeleteWithBody extends HttpEntityEnclosingRequestBase { + public static final String METHOD_NAME = "DELETE"; + + @Override + public String getMethod() { + return METHOD_NAME; + } + + public HttpDeleteWithBody(final String uri) { + super(); + setURI(URI.create(uri)); + } + + public HttpDeleteWithBody(final URI uri) { + super(); + setURI(uri); + } + + public HttpDeleteWithBody() { + super(); + } + } +} diff --git a/bpmn/MSORESTClient/src/main/java/org/onap/so/rest/RESTConfig.java b/bpmn/MSORESTClient/src/main/java/org/onap/so/rest/RESTConfig.java new file mode 100644 index 0000000000..b5fecbdb87 --- /dev/null +++ b/bpmn/MSORESTClient/src/main/java/org/onap/so/rest/RESTConfig.java @@ -0,0 +1,131 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.rest; + +/** + * Configuration values to be used by the RESTClient. + * + * @version 1.0 + * + */ +public class RESTConfig { + private final String URL; + + private final boolean trustAllCerts; + private final String proxyHost; + private final int proxyPort; + + /** + * Creates a RESTConfig with the specified URL. + *

+ * By default, no proxy will be used, and only valid certificates will + * be used. + * + * @param URL url to set + */ + public RESTConfig(final String URL) { + this(URL, null, -1, false); + } + + /** + * Creates a RESTConfig with the specified URL and whether to trust all + * certificates. + *

+ * Trusting all certificates is useful for testing self-signed + * certificates. By default, no proxy will be used. + * + * @param URL url to set + * @param trustAllCerts whether to trust all certificates + */ + public RESTConfig(final String URL, final boolean trustAllCerts) { + this(URL, null, -1, trustAllCerts); + } + + /** + * Creates a RESTConfig with the specified URL and proxy. + *

+ * By default, only valid certificates will be allowed. + * + * @param URL url to set + * @param proxyHost proxy host to set + * @param proxyPort proxy port to set + */ + public RESTConfig(final String URL, final String proxyHost, + final int proxyPort) { + + this(URL, proxyHost, proxyPort, false); + } + + /** + * Creates a RESTConfig object with the specified URL, proxy host, proxy + * port, and whether to trust all certificates. Allowing all certificates + * is useful for testing self-signed certificates. + * + * @param URL url to set + * @param proxyHost proxy host to set + * @param proxyPort porxy port to set + * @param trustAllCerts whether to trust all certificates + */ + public RESTConfig(final String URL, final String proxyHost, + final int proxyPort, boolean trustAllCerts) { + + this.URL = URL; + this.proxyHost = proxyHost; + this.proxyPort = proxyPort; + this.trustAllCerts = trustAllCerts; + } + + /** + * Gets the URL to use. + * + * @return URL to use + */ + public String getURL() { + return this.URL; + } + + /** + * Gets whether to trust all certificates. + * + * @return true if to trust all certificates, false otherwise + */ + public boolean trustAllCerts() { + return this.trustAllCerts; + } + + /** + * Gets proxy host or null if proxy host has not been set. + * + * @return proxy host + */ + public String getProxyHost() { + return this.proxyHost; + } + + /** + * Gets proxy port or -1 if no proxy port has been set. + * + * @return proxy port + */ + public int getProxyPort() { + return this.proxyPort; + } +} diff --git a/bpmn/MSORESTClient/src/main/java/org/onap/so/rest/RESTException.java b/bpmn/MSORESTClient/src/main/java/org/onap/so/rest/RESTException.java new file mode 100644 index 0000000000..579927c2ce --- /dev/null +++ b/bpmn/MSORESTClient/src/main/java/org/onap/so/rest/RESTException.java @@ -0,0 +1,85 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.rest; + +/** + * A custom exception class. + * + * @version 1.0 + * + */ +public class RESTException extends Exception { + private static final long serialVersionUID = -6874042744590915838L; + // http status code + private final int statusCode; + + // error message + private final String errorMessage; + + /** + * {@inheritDoc} + * @see Exception#RESTException(String) + */ + public RESTException(final String errorMessage) { + this(-1, errorMessage); + } + + /** + * {@inheritDoc} + * @see Exception#RESTException(Throwable) + */ + public RESTException(final Throwable cause) { + super(cause); + this.statusCode = -1; + this.errorMessage = cause.getMessage(); + } + + /** + * Creates a RESTException with the specified status code and error + * message. + * + * @param statusCode http status code + * @param errorMessage http error message + */ + public RESTException(final int statusCode, final String errorMessage) { + super(statusCode + ":" + errorMessage); + this.statusCode = statusCode; + this.errorMessage = errorMessage; + } + + /** + * Gets the status code or -1 if none has been set. + * + * @return status code + */ + public int getStatusCode() { + return this.statusCode; + } + + /** + * Gets the error message. + * + * @return error message + */ + public String getErrorMessage() { + return this.errorMessage; + } +} diff --git a/bpmn/MSORESTClient/src/main/java/org/openecomp/mso/rest/APIResponse.java b/bpmn/MSORESTClient/src/main/java/org/openecomp/mso/rest/APIResponse.java deleted file mode 100644 index d85a790841..0000000000 --- a/bpmn/MSORESTClient/src/main/java/org/openecomp/mso/rest/APIResponse.java +++ /dev/null @@ -1,145 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.mso.rest; - -import java.io.IOException; -import java.util.Arrays; - -import org.apache.http.Header; -import org.apache.http.HttpResponse; -import org.apache.http.util.EntityUtils; - -/** - * An immutable class that encapsulates an API response. - * - * @version 1.0 - * @since 1.0 - */ -public class APIResponse { - private final int statusCode; - private final byte[] responseBody; - private final HttpHeader[] headers; - - /** - * Internal method used to create http headers using the specified - * HttpResponse object. - * - * @param httpResponse used to create headers - * @return http headers - */ - private static HttpHeader[] buildHeaders(final HttpResponse httpResponse) { - final Header[] headers = httpResponse.getAllHeaders(); - - HttpHeader[] httpHeaders = new HttpHeader[headers.length]; - for (int i = 0; i < headers.length; ++i) { - final Header header = headers[i]; - final String name = header.getName(); - final String value = header.getValue(); - final HttpHeader httpHeader = new HttpHeader(name, value); - httpHeaders[i] = httpHeader; - } - - return httpHeaders; - } - - /** - * Create an APIResponse object using the specified HttpResponse object. - * - * @param httpResponse used to create the APIResponse - * - * @throws RESTException if unable to read from the HttpResponse object - */ - public APIResponse(final HttpResponse httpResponse) throws RESTException { - try { - this.statusCode = httpResponse.getStatusLine().getStatusCode(); - - if (httpResponse.getEntity() == null) - { - this.responseBody = null; - } - else - { - this.responseBody = EntityUtils.toByteArray(httpResponse.getEntity()); - } - - this.headers = buildHeaders(httpResponse); - } catch (IOException ioe) { - throw new RESTException(ioe); - } - } - - /** - * Gets the http status code returned by the api server. - *

- * For example, status code 200 represents 'OK.' - * - * @return status code - */ - public int getStatusCode() { - return this.statusCode; - } - - /** - * Gets the http response body as a byte array. - * - * @return http response body - */ - public byte[] getResponseBodyAsByteArray() { - // avoid exposing internals, create copy - if (this.responseBody != null) { - return Arrays.copyOf(this.responseBody, this.responseBody.length); - } else { - return null; - } - } - - /** - * Gets the http response body as a string. - * - * @return http response body - */ - public String getResponseBodyAsString() { - if (this.responseBody != null) { - return new String(this.responseBody); - } else { - return ""; - } - } - - /** - * Gets a list of all the headers returned by the API response. - * - * @return an array of all the HttpHeaders - */ - public HttpHeader[] getAllHeaders() { - // avoid exposing internals, create copy - return Arrays.copyOf(this.headers, this.headers.length); - } - - public String getFirstHeader(String name) { - for (HttpHeader header : headers) { - if (header.getName().equals(name)) { - return header.getValue(); - } - } - return null; - } -} diff --git a/bpmn/MSORESTClient/src/main/java/org/openecomp/mso/rest/HostNameVerifier.java b/bpmn/MSORESTClient/src/main/java/org/openecomp/mso/rest/HostNameVerifier.java deleted file mode 100644 index ffef5f9385..0000000000 --- a/bpmn/MSORESTClient/src/main/java/org/openecomp/mso/rest/HostNameVerifier.java +++ /dev/null @@ -1,49 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * Copyright (C) 2017 Huawei Technologies Co., Ltd. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.mso.rest; - -import javax.net.ssl.SSLException; - -import org.apache.http.conn.ssl.AbstractVerifier; -import org.openecomp.mso.logger.MsoLogger; - -/** - * @version 1.0 - * Place holder to validate host name, for now just invokes the super class method - * - */ -public class HostNameVerifier extends AbstractVerifier { - - private static final MsoLogger LOGGER = MsoLogger.getMsoLogger (MsoLogger.Catalog.RA); - - public final void verify( - final String host, - final String[] cns, - final String[] subjectAlts) throws SSLException { - try { - verify(host, cns, subjectAlts, true); - } catch (SSLException sex) { - LOGGER.debug("Exception:", sex); - } - } - -} diff --git a/bpmn/MSORESTClient/src/main/java/org/openecomp/mso/rest/HttpHeader.java b/bpmn/MSORESTClient/src/main/java/org/openecomp/mso/rest/HttpHeader.java deleted file mode 100644 index 79eea08dac..0000000000 --- a/bpmn/MSORESTClient/src/main/java/org/openecomp/mso/rest/HttpHeader.java +++ /dev/null @@ -1,65 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.mso.rest; - -/** - * An immutable class used to wrap an http header. - * - * @version 1.0 - * @since 1.0 - */ -public class HttpHeader { - private final String name; - private final String value; - - /** - * Create an http header using the specified name and value - * - * @param name name of http header - * @param value value of http header - */ - public HttpHeader(final String name, final String value) { - if (name == null) { - throw new IllegalArgumentException("Name may not be null."); - } - - this.name = name; - this.value = value; - } - - /** - * Gets the header name. - * - * @return header name - */ - public String getName() { - return this.name; - } - - /** - * Gets the header value. - * - * @return header value - */ - public String getValue() { - return this.value; - } -} diff --git a/bpmn/MSORESTClient/src/main/java/org/openecomp/mso/rest/RESTClient.java b/bpmn/MSORESTClient/src/main/java/org/openecomp/mso/rest/RESTClient.java deleted file mode 100644 index 3170e49371..0000000000 --- a/bpmn/MSORESTClient/src/main/java/org/openecomp/mso/rest/RESTClient.java +++ /dev/null @@ -1,614 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * Copyright (C) 2017 Huawei Technologies Co., Ltd. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.mso.rest; - -import java.io.Closeable; -import java.io.IOException; -import java.io.UnsupportedEncodingException; -import java.net.URI; -import java.net.URLEncoder; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Set; - -import javax.net.ssl.SSLSocketFactory; - -import org.apache.http.HttpEntity; -import org.apache.http.HttpHost; -import org.apache.http.HttpResponse; -import org.apache.http.client.HttpClient; -import org.apache.http.client.methods.HttpEntityEnclosingRequestBase; -import org.apache.http.client.methods.HttpGet; -import org.apache.http.client.methods.HttpPatch; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.client.methods.HttpPut; -import org.apache.http.config.Registry; -import org.apache.http.config.RegistryBuilder; -import org.apache.http.conn.socket.ConnectionSocketFactory; -import org.apache.http.conn.socket.PlainConnectionSocketFactory; -import org.apache.http.conn.ssl.SSLConnectionSocketFactory; -import org.apache.http.entity.StringEntity; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClientBuilder; -import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; -import org.apache.http.message.AbstractHttpMessage; -import org.apache.http.util.EntityUtils; - -import org.openecomp.mso.logger.MsoLogger; -/** - * Client used to send RESTFul requests. - *

- * Many of the methods return a reference to the 'this,' thereby allowing - * method chaining. - *
- * An example of usage can be found below: - *

- * RESTClient client;
- * try {
- *     client = new RESTClient("http://www.openecomp.org");
- *     APIResponse response = client
- *         .setHeader("Accept", "application/json")
- *         .setHeader("Clientid", "clientid")
- *         .setHeader("header", "value")
- *         .httpPost("postbody");
- *     if (response.getStatusCode() == 200) {
- *         System.out.println("Success!");
- *     }
- *  } catch (RESTException re) {
- *      // Handle Exception
- *  }
- * 
- * - * @version 1.0 - * @since 1.0 - */ -public class RESTClient { - - private static final MsoLogger LOGGER = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL); - private final String proxyHost; - private final int proxyPort; - - private final String URL; - - private final LinkedHashMap> headers; - private final LinkedHashMap> parameters; - - private HttpEntity httpEntity; - - /** - * Internal method used to build an APIResponse using the specified - * HttpResponse object. - * - * @param response response wrapped inside an APIResponse object - * @return api response - */ - private APIResponse buildResponse(HttpResponse response) - throws RESTException { - - return new APIResponse(response); - } - - /** - * Used to release any resources used by the connection. - * @param response HttpResponse object used for releasing the connection - * @throws RESTException if unable to release connection - * - */ - private void releaseConnection(HttpResponse response) throws RESTException { - try { - EntityUtils.consume(response.getEntity()); - } catch (IOException ioe) { - throw new RESTException(ioe); - } - } - - /** - * Sets headers to the http message. - * - * @param httpMsg http message to set headers for - */ - private void addInternalHeaders(AbstractHttpMessage httpMsg) { - if (headers.isEmpty()) { - return; - } - - final Set keySet = headers.keySet(); - for (final String key : keySet) { - final List values = headers.get(key); - for (final String value : values) { - httpMsg.addHeader(key, value); - } - } - } - - /** - * Builds the query part of a URL. - * - * @return query - */ - private String buildQuery() { - if (this.parameters.size() == 0) { - return ""; - } - - StringBuilder sb = new StringBuilder(); - String charSet = "UTF-8"; - try { - Iterator keyitr = this.parameters.keySet().iterator(); - for (int i = 0; keyitr.hasNext(); ++i) { - if (i > 0) { - sb.append("&"); - } - - final String name = keyitr.next(); - final List values = this.parameters.get(name); - for(final String value : values) { - sb.append(URLEncoder.encode(name, charSet)); - sb.append("="); - sb.append(URLEncoder.encode(value, charSet)); - } - } - } catch (UnsupportedEncodingException e) { - LOGGER.debug("Exception :", e); - } - return sb.toString(); - } - - /** - * Creates an http client that can be used for sending http requests. - * - * @return created http client - * - * @throws RESTException if unable to create http client. - */ - private CloseableHttpClient createClient() throws RESTException { - //TODO - we may want to trust self signed certificate at some point - add implementation here - HttpClientBuilder clientBuilder; - - try { - SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory( - (SSLSocketFactory) SSLSocketFactory.getDefault(), - new HostNameVerifier()); - Registry registry = RegistryBuilder - . create() - .register("http", - PlainConnectionSocketFactory.getSocketFactory()) - .register("https", sslSocketFactory).build(); - PoolingHttpClientConnectionManager manager = new PoolingHttpClientConnectionManager( - registry); - clientBuilder = HttpClientBuilder.create().setConnectionManager( - manager); - } catch (Exception ex) { - LOGGER.debug("Exception :", ex); - throw new RESTException(ex.getMessage()); - } - clientBuilder.disableRedirectHandling(); - - if ((this.proxyHost != null) && (this.proxyPort != -1)) { - HttpHost proxy = new HttpHost(this.proxyHost, this.proxyPort); - clientBuilder.setProxy(proxy); - } - - return clientBuilder.build(); - } - - /** - * Creates a RESTClient with the specified URL, proxy host, and proxy port. - * - * @param URL URL to send request to - * @param proxyHost proxy host to use for sending request - * @param proxyPort proxy port to use for sendin request - * - * @throws RESTException if unable to create a RESTClient - */ - public RESTClient(String URL, String proxyHost, int proxyPort) - throws RESTException { - this(new RESTConfig(URL, proxyHost, proxyPort)); - } - - /** - * Creates a RESTClient with the specified URL. No proxy host nor port will - * be used. - * - * @param URL URL to send request to - * - * @throws RESTException if unable to create a RESTClient - */ - public RESTClient(String URL) throws RESTException { - this(new RESTConfig(URL)); - } - - /** - * Creates a RESTClient with the RESTConfig object. - * - * @param restConfig config to use for sending request - * - * @throws RESTException if unable to create a RESTClient - */ - public RESTClient(RESTConfig restConfig) throws RESTException { - this.headers = new LinkedHashMap<>(); - this.parameters = new LinkedHashMap<>(); - this.URL = restConfig.getURL(); - this.proxyHost = restConfig.getProxyHost(); - this.proxyPort = restConfig.getProxyPort(); - } - - /** - * Adds parameter to be sent during http request. - *

- * Does not remove any parameters with the same name, thus allowing - * duplicates. - * - * @param name name of parameter - * @param value value of parametr - * @return a reference to 'this', which can be used for method chaining - */ - public RESTClient addParameter(String name, String value) { - if (!parameters.containsKey(name)) { - parameters.put(name, new ArrayList<>()); - } - - List values = parameters.get(name); - values.add(value); - - return this; - } - - /** - * Sets parameter to be sent during http request. - *

- * Removes any parameters with the same name, thus disallowing duplicates. - * - * @param name name of parameter - * @param value value of parametr - * @return a reference to 'this', which can be used for method chaining - */ - public RESTClient setParameter(String name, String value) { - if (parameters.containsKey(name)) { - parameters.get(name).clear(); - } - - addParameter(name, value); - - return this; - } - - /** - * Adds http header to be sent during http request. - *

- * Does not remove any headers with the same name, thus allowing - * duplicates. - * - * @param name name of header - * @param value value of header - * @return a reference to 'this', which can be used for method chaining - */ - public RESTClient addHeader(String name, String value) { - if (!headers.containsKey(name)) { - headers.put(name, new ArrayList<>()); - } - - List values = headers.get(name); - values.add(value); - - return this; - } - - /** - * Sets http header to be sent during http request. - *

- * Does not remove any headers with the same name, thus allowing - * duplicates. - * - * @param name name of header - * @param value value of header - * @return a reference to 'this', which can be used for method chaining - */ - public RESTClient setHeader(String name, String value) { - if (headers.containsKey(name)) { - headers.get(name).clear(); - } - - addHeader(name, value); - - return this; - } - - /** - * Convenience method for adding the authorization header using the - * specified OAuthToken object. - * - * @param token token to use for setting authorization - * @return a reference to 'this,' which can be used for method chaining - */ - public RESTClient addAuthorizationHeader(String token) { - this.addHeader("Authorization", token); - return this; - } - - /** - * Alias for httpGet(). - * - * @see RESTClient#httpGet() - */ - public APIResponse get() throws RESTException { - return httpGet(); - } - - /** - * Sends an http GET request using the parameters and headers previously - * set. - * - * @return api response - * - * @throws RESTException if request was unsuccessful - */ - public APIResponse httpGet() throws RESTException { - HttpResponse response = null; - - try (CloseableHttpClient httpClient = createClient()) { - String query = ""; - if (!buildQuery().equals("")) { - query = "?" + buildQuery(); - } - HttpGet httpGet = new HttpGet(this.getURL() + query); - addInternalHeaders(httpGet); - - response = httpClient.execute(httpGet); - - APIResponse apiResponse = buildResponse(response); - return apiResponse; - } catch (IOException ioe) { - throw new RESTException(ioe); - } finally { - if (response != null) { - this.releaseConnection(response); - } - } - } - - /** - * Alias for httpPost() - * - * @see RESTClient#httpPost() - */ - public APIResponse post() throws RESTException { - return httpPost(); - } - - /** - * Sends an http POST request. - *

- * POST body will be set to the values set using add/setParameter() - * - * @return api response - * - * @throws RESTException if POST was unsuccessful - */ - public APIResponse httpPost() throws RESTException { - APIResponse response = httpPost(buildQuery()); - return response; - } - - /** - * Sends an http POST request using the specified body. - * - * @return api response - * - * @throws RESTException if POST was unsuccessful - */ - public APIResponse httpPost(String body) throws RESTException { - HttpResponse response = null; - try (CloseableHttpClient httpClient = createClient()) { - HttpPost httpPost = new HttpPost(this.getURL()); - addInternalHeaders(httpPost); - if (body != null && !body.equals("")) { - httpEntity = new StringEntity(body); - httpPost.setEntity(new StringEntity(body)); - } - - response = httpClient.execute(httpPost); - - return buildResponse(response); - } catch (IOException e) { - throw new RESTException(e); - } finally { - if (response != null) { - this.releaseConnection(response); - } - } - } - - /** - * - * @param body Data to PUT - * @return API response - * @throws RESTException - */ - public APIResponse httpPut(String body) throws RESTException { - HttpResponse response = null; - try (CloseableHttpClient httpClient = createClient()) { - - String query = ""; - if (!buildQuery().equals("")) { - query = "?" + buildQuery(); - } - HttpPut httpPut = new HttpPut(this.getURL() + query); - addInternalHeaders(httpPut); - if (body != null && !body.equals("")) { - httpEntity = new StringEntity(body); - httpPut.setEntity(httpEntity); - } - - response = httpClient.execute(httpPut); - - return buildResponse(response); - } catch (IOException e) { - throw new RESTException(e); - } finally { - if (response != null) { - this.releaseConnection(response); - } - } - } - - /** - * Alias for httpPatch(). - * - * @see RESTClient#httpPatch() - */ - public APIResponse patch(String body) throws RESTException { - return httpPatch(body); - } - - /** - * - * @param body Data to PATCH - * @return API response - * @throws RESTException - */ - public APIResponse httpPatch(String body) throws RESTException { - HttpResponse response = null; - try (CloseableHttpClient httpClient = createClient()) { - String query = ""; - if (!buildQuery().equals("")) { - query = "?" + buildQuery(); - } - HttpPatch httpPatch = new HttpPatch(this.getURL() + query); - addInternalHeaders(httpPatch); - if (body != null && !body.equals("")) { - httpEntity = new StringEntity(body); - httpPatch.setEntity(httpEntity); - } - - response = httpClient.execute(httpPatch); - - return buildResponse(response); - } catch (IOException e) { - throw new RESTException(e); - } finally { - if (response != null) { - this.releaseConnection(response); - } - } - } - - /** - * Alias for httpDelete(). - * - * @see RESTClient#httpDelete() - */ - public APIResponse delete() throws RESTException { - return httpDelete(); - } - - /** - * Sends an http DELETE request using the parameters and headers previously - * set. - * - * @return api response - * - * @throws RESTException if request was unsuccessful - */ - public APIResponse httpDelete() throws RESTException { - return httpDelete(null); - } - - /** - * Sends an http DELETE request with a body, using the parameters and headers - * previously set. - * - * @return api response - * - * @throws RESTException if request was unsuccessful - */ - public APIResponse httpDelete(String body) throws RESTException { - HttpResponse response = null; - - try (CloseableHttpClient httpClient = createClient()){ - - String query = ""; - if (!buildQuery().equals("")) { - query = "?" + buildQuery(); - } - HttpDeleteWithBody httpDelete = new HttpDeleteWithBody(this.getURL() + query); - addInternalHeaders(httpDelete); - - if (body != null && !body.equals("")) { - httpEntity = new StringEntity(body); - httpDelete.setEntity(httpEntity); - } - - response = httpClient.execute(httpDelete); - - APIResponse apiResponse = buildResponse(response); - return apiResponse; - } catch (IOException ioe) { - throw new RESTException(ioe); - } finally { - if (response != null) { - this.releaseConnection(response); - } - } - } - - public String getURL() { - return URL; - } - public LinkedHashMap> getHeaders() { - return headers; - } - public LinkedHashMap> getParameters() { - return parameters; - } - public HttpEntity getHttpEntity() { - return httpEntity; - } - - - /** - * Allows inclusion of a request body with DELETE. - */ - private class HttpDeleteWithBody extends HttpEntityEnclosingRequestBase { - public static final String METHOD_NAME = "DELETE"; - - public String getMethod() { - return METHOD_NAME; - } - - public HttpDeleteWithBody(final String uri) { - super(); - setURI(URI.create(uri)); - } - - public HttpDeleteWithBody(final URI uri) { - super(); - setURI(uri); - } - - public HttpDeleteWithBody() { - super(); - } - } -} diff --git a/bpmn/MSORESTClient/src/main/java/org/openecomp/mso/rest/RESTConfig.java b/bpmn/MSORESTClient/src/main/java/org/openecomp/mso/rest/RESTConfig.java deleted file mode 100644 index 0e4681824a..0000000000 --- a/bpmn/MSORESTClient/src/main/java/org/openecomp/mso/rest/RESTConfig.java +++ /dev/null @@ -1,131 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.mso.rest; - -/** - * Configuration values to be used by the RESTClient. - * - * @version 1.0 - * - */ -public class RESTConfig { - private final String URL; - - private final boolean trustAllCerts; - private final String proxyHost; - private final int proxyPort; - - /** - * Creates a RESTConfig with the specified URL. - *

- * By default, no proxy will be used, and only valid certificates will - * be used. - * - * @param URL url to set - */ - public RESTConfig(final String URL) { - this(URL, null, -1, false); - } - - /** - * Creates a RESTConfig with the specified URL and whether to trust all - * certificates. - *

- * Trusting all certificates is useful for testing self-signed - * certificates. By default, no proxy will be used. - * - * @param URL url to set - * @param trustAllCerts whether to trust all certificates - */ - public RESTConfig(final String URL, final boolean trustAllCerts) { - this(URL, null, -1, trustAllCerts); - } - - /** - * Creates a RESTConfig with the specified URL and proxy. - *

- * By default, only valid certificates will be allowed. - * - * @param URL url to set - * @param proxyHost proxy host to set - * @param proxyPort proxy port to set - */ - public RESTConfig(final String URL, final String proxyHost, - final int proxyPort) { - - this(URL, proxyHost, proxyPort, false); - } - - /** - * Creates a RESTConfig object with the specified URL, proxy host, proxy - * port, and whether to trust all certificates. Allowing all certificates - * is useful for testing self-signed certificates. - * - * @param URL url to set - * @param proxyHost proxy host to set - * @param proxyPort porxy port to set - * @param trustAllCerts whether to trust all certificates - */ - public RESTConfig(final String URL, final String proxyHost, - final int proxyPort, boolean trustAllCerts) { - - this.URL = URL; - this.proxyHost = proxyHost; - this.proxyPort = proxyPort; - this.trustAllCerts = trustAllCerts; - } - - /** - * Gets the URL to use. - * - * @return URL to use - */ - public String getURL() { - return this.URL; - } - - /** - * Gets whether to trust all certificates. - * - * @return true if to trust all certificates, false otherwise - */ - public boolean trustAllCerts() { - return this.trustAllCerts; - } - - /** - * Gets proxy host or null if proxy host has not been set. - * - * @return proxy host - */ - public String getProxyHost() { - return this.proxyHost; - } - - /** - * Gets proxy port or -1 if no proxy port has been set. - * - * @return proxy port - */ - public int getProxyPort() { - return this.proxyPort; - } -} diff --git a/bpmn/MSORESTClient/src/main/java/org/openecomp/mso/rest/RESTException.java b/bpmn/MSORESTClient/src/main/java/org/openecomp/mso/rest/RESTException.java deleted file mode 100644 index 88fa16f736..0000000000 --- a/bpmn/MSORESTClient/src/main/java/org/openecomp/mso/rest/RESTException.java +++ /dev/null @@ -1,85 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.mso.rest; - -/** - * A custom exception class. - * - * @version 1.0 - * - */ -public class RESTException extends Exception { - private static final long serialVersionUID = -6874042744590915838L; - // http status code - private final int statusCode; - - // error message - private final String errorMessage; - - /** - * {@inheritDoc} - * @see Exception#RESTException(String) - */ - public RESTException(final String errorMessage) { - this(-1, errorMessage); - } - - /** - * {@inheritDoc} - * @see Exception#RESTException(Throwable) - */ - public RESTException(final Throwable cause) { - super(cause); - this.statusCode = -1; - this.errorMessage = cause.getMessage(); - } - - /** - * Creates a RESTException with the specified status code and error - * message. - * - * @param statusCode http status code - * @param errorMessage http error message - */ - public RESTException(final int statusCode, final String errorMessage) { - super(statusCode + ":" + errorMessage); - this.statusCode = statusCode; - this.errorMessage = errorMessage; - } - - /** - * Gets the status code or -1 if none has been set. - * - * @return status code - */ - public int getStatusCode() { - return this.statusCode; - } - - /** - * Gets the error message. - * - * @return error message - */ - public String getErrorMessage() { - return this.errorMessage; - } -} diff --git a/bpmn/MSORESTClient/src/test/java/org/onap/so/rest/APIResponseTest.java b/bpmn/MSORESTClient/src/test/java/org/onap/so/rest/APIResponseTest.java new file mode 100644 index 0000000000..2c81fda32b --- /dev/null +++ b/bpmn/MSORESTClient/src/test/java/org/onap/so/rest/APIResponseTest.java @@ -0,0 +1,57 @@ +/* +* ============LICENSE_START======================================================= + * ONAP : SO + * ================================================================================ + * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= +*/ + +package org.onap.so.rest; + +import static org.junit.Assert.assertEquals; + +import org.json.JSONObject; +import org.junit.Test; + +import org.apache.http.HttpResponse; +import org.apache.http.ProtocolVersion; +import org.apache.http.HttpEntity; +import org.apache.http.entity.ContentType; +import org.apache.http.entity.StringEntity; +import org.apache.http.message.BasicHttpResponse; + +public class APIResponseTest { + + @Test + public void test() throws Exception { + JSONObject jsonObject = new JSONObject(); + jsonObject.put("firstName", "firstName1"); + jsonObject.put("lastName", "lastName1"); + String jsonObjectAsString= jsonObject.toString(); + HttpEntity entity = new StringEntity(jsonObjectAsString, ContentType.APPLICATION_JSON); + ProtocolVersion ver = new ProtocolVersion("HTTP", 1, 1); + HttpResponse response = new BasicHttpResponse(ver, 1, "Ok"); + response.setStatusLine(ver, 200); + response.setEntity(entity); + response.setHeader("name", "value"); + response.setStatusCode(200); + APIResponse apiResponse = new APIResponse(response); + assertEquals(200, apiResponse.getStatusCode()); + assertEquals(jsonObject.toString(), apiResponse.getResponseBodyAsString()); + assertEquals("value", apiResponse.getFirstHeader("name")); + assertEquals(1, apiResponse.getAllHeaders().length); + assertEquals(49, apiResponse.getResponseBodyAsByteArray().length); + } +} diff --git a/bpmn/MSORESTClient/src/test/java/org/onap/so/rest/HttpHeaderTest.java b/bpmn/MSORESTClient/src/test/java/org/onap/so/rest/HttpHeaderTest.java new file mode 100644 index 0000000000..bc096687b7 --- /dev/null +++ b/bpmn/MSORESTClient/src/test/java/org/onap/so/rest/HttpHeaderTest.java @@ -0,0 +1,40 @@ +/* +* ============LICENSE_START======================================================= + * ONAP : SO + * ================================================================================ + * Copyright (C) 2018 TechMahindra + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= +*/ + +package org.onap.so.rest; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; + +public class HttpHeaderTest { + + @Test + public void test() { + HttpHeader hth= new HttpHeader("name", "value"); + assertEquals("name", hth.getName()); + assertEquals("value", hth.getValue()); + } + + @Test (expected = IllegalArgumentException.class) + public void testException() { + HttpHeader httpHeader = new HttpHeader(null, "value"); //null + } +} diff --git a/bpmn/MSORESTClient/src/test/java/org/onap/so/rest/RESTClientTest.java b/bpmn/MSORESTClient/src/test/java/org/onap/so/rest/RESTClientTest.java new file mode 100644 index 0000000000..bbdaa94581 --- /dev/null +++ b/bpmn/MSORESTClient/src/test/java/org/onap/so/rest/RESTClientTest.java @@ -0,0 +1,195 @@ +/* +* ============LICENSE_START======================================================= + * ONAP : SO + * ================================================================================ + * Copyright (C) 2018 TechMahindra + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= +*/ + +package org.onap.so.rest; + +import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; +import static com.github.tomakehurst.wiremock.client.WireMock.delete; +import static com.github.tomakehurst.wiremock.client.WireMock.get; +import static com.github.tomakehurst.wiremock.client.WireMock.patch; +import static com.github.tomakehurst.wiremock.client.WireMock.post; +import static com.github.tomakehurst.wiremock.client.WireMock.put; +import static com.github.tomakehurst.wiremock.client.WireMock.urlPathMatching; +import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig; +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.spy; + +import org.json.JSONObject; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.springframework.http.HttpStatus; + +import com.github.tomakehurst.wiremock.junit.WireMockRule; + +public class RESTClientTest { + + private RESTClient restClient; + private JSONObject jsonPayload; + private JSONObject jsonResponse; + private String jsonObjectAsString; + private String jsonResponseAsString; + + @Rule + public WireMockRule wireMockRule = new WireMockRule(wireMockConfig().port(28090)); + + @Before + public void before() throws Exception { + jsonPayload = new JSONObject(); + jsonPayload.put("firstName", "firstName1"); + jsonPayload.put("lastName", "lastName1"); + jsonObjectAsString = jsonPayload.toString(); + jsonResponse = new JSONObject(); + jsonResponse.put("response", "responseValue"); + jsonResponseAsString = jsonResponse.toString(); + restClient = new RESTClient("http://localhost:28090/example", "localhost", 28090); + } + + @Test + public void testHeadersParameters() throws Exception { + restClient.setHeader("name", "value"); + restClient.setParameter("name", "value"); + assertEquals("[value]", restClient.getParameters().get("name").toString()); + assertEquals("[value]", restClient.getHeaders().get("name").toString()); + restClient.setHeader("name", "value2"); + assertEquals("[value2]", restClient.getHeaders().get("name").toString()); + restClient.setParameter("name", "value2"); + assertEquals("[value2]", restClient.getParameters().get("name").toString()); + restClient.addParameter("name", "value"); + assertEquals(1, restClient.getParameters().size()); + restClient.addAuthorizationHeader("token"); + assertEquals("[token]", restClient.getHeaders().get("Authorization").toString()); + assertEquals("http://localhost:28090/example", restClient.getURL()); + restClient = new RESTClient("http://localhost:28090/example1"); + assertEquals("http://localhost:28090/example1", restClient.getURL()); + } + + @Test + public void testHttpPost() throws Exception { + RESTClient restClientMock = mock(RESTClient.class); + restClientMock = spy(restClient); + wireMockRule.stubFor(post(urlPathMatching("/example/*")) + .willReturn(aResponse().withHeader("Content-Type", "application/json").withStatus(HttpStatus.OK.value()).withBody(jsonResponseAsString))); + APIResponse apiResponse = restClientMock.httpPost(jsonObjectAsString); + assertEquals(200, apiResponse.getStatusCode()); + assertEquals(jsonResponseAsString, apiResponse.getResponseBodyAsString()); + assertEquals("application/json", apiResponse.getFirstHeader("Content-Type")); + verify(restClientMock, times(2)).getURL(); + } + + @Test + public void testPost() throws Exception { + wireMockRule.stubFor(post(urlPathMatching("/example/*")) + .willReturn(aResponse().withHeader("Content-Type", "application/json").withStatus(HttpStatus.OK.value()).withBody(jsonResponseAsString))); + APIResponse apiResponse = restClient.post(); + assertEquals(200, apiResponse.getStatusCode()); + assertEquals(jsonResponseAsString, apiResponse.getResponseBodyAsString()); + assertEquals("application/json", apiResponse.getFirstHeader("Content-Type")); + } + + @Test + public void testHttpPut() throws Exception { + wireMockRule.stubFor(put(urlPathMatching("/example/*")) + .willReturn(aResponse().withHeader("Content-Type", "application/json").withStatus(HttpStatus.OK.value()).withBody(jsonResponseAsString))); + restClient.setParameter("name", "value"); + APIResponse apiResponse = restClient.httpPut(jsonObjectAsString); + assertEquals(200, apiResponse.getStatusCode()); + assertEquals(jsonResponseAsString, apiResponse.getResponseBodyAsString()); + assertEquals("application/json", apiResponse.getFirstHeader("Content-Type")); + + } + + @Test + public void testHttpPatch() throws Exception { + wireMockRule.stubFor(patch(urlPathMatching("/example/*")) + .willReturn(aResponse().withHeader("Content-Type", "application/json").withStatus(HttpStatus.OK.value()).withBody(jsonResponseAsString))); + APIResponse apiResponse = restClient.httpPatch(jsonObjectAsString); + assertEquals(200, apiResponse.getStatusCode()); + assertEquals(jsonResponseAsString, apiResponse.getResponseBodyAsString()); + assertEquals("application/json", apiResponse.getFirstHeader("Content-Type")); + } + + @Test + public void testPatch_withParameter() throws Exception { + wireMockRule.stubFor(patch(urlPathMatching("/example/*")) + .willReturn(aResponse().withHeader("Content-Type", "application/json").withStatus(HttpStatus.OK.value()).withBody(jsonResponseAsString))); + restClient.setParameter("name", "value"); + APIResponse apiResponse = restClient.patch(jsonObjectAsString); + assertEquals(200, apiResponse.getStatusCode()); + assertEquals(jsonResponseAsString, apiResponse.getResponseBodyAsString()); + assertEquals("application/json", apiResponse.getFirstHeader("Content-Type")); + } + + @Test + public void testHttpDelete_withPayload() throws Exception { + wireMockRule.stubFor(delete(urlPathMatching("/example/*")) + .willReturn(aResponse().withHeader("Content-Type", "application/json").withStatus(HttpStatus.OK.value()).withBody(jsonResponseAsString))); + APIResponse apiResponse = restClient.httpDelete(jsonObjectAsString); + assertEquals(200, apiResponse.getStatusCode()); + assertEquals(jsonResponseAsString, apiResponse.getResponseBodyAsString()); + assertEquals("application/json", apiResponse.getFirstHeader("Content-Type")); + } + + @Test + public void testHttpDelete() throws Exception { + wireMockRule.stubFor(delete(urlPathMatching("/example/*")) + .willReturn(aResponse().withHeader("Content-Type", "application/json").withStatus(HttpStatus.OK.value()).withBody(jsonResponseAsString))); + APIResponse apiResponse = restClient.httpDelete(); + assertEquals(200, apiResponse.getStatusCode()); + assertEquals(jsonResponseAsString, apiResponse.getResponseBodyAsString()); + assertEquals("application/json", apiResponse.getFirstHeader("Content-Type")); + } + + @Test + public void testDelete() throws Exception { + wireMockRule.stubFor(delete(urlPathMatching("/example/*")) + .willReturn(aResponse().withHeader("Content-Type", "application/json").withStatus(HttpStatus.OK.value()).withBody(jsonResponseAsString))); + APIResponse apiResponse = restClient.delete(); + assertEquals(200, apiResponse.getStatusCode()); + assertEquals(jsonResponseAsString, apiResponse.getResponseBodyAsString()); + assertEquals("application/json", apiResponse.getFirstHeader("Content-Type")); + } + + @Test + public void testHttpGet() throws Exception { + wireMockRule.stubFor(get(urlPathMatching("/example/*")) + .willReturn(aResponse().withHeader("Content-Type", "application/json").withStatus(HttpStatus.OK.value()).withBody(jsonResponseAsString))); + APIResponse apiResponse = restClient.httpGet(); + assertEquals(200, apiResponse.getStatusCode()); + assertEquals(jsonResponseAsString, apiResponse.getResponseBodyAsString()); + assertEquals("application/json", apiResponse.getFirstHeader("Content-Type")); + } + + @Test + public void testGet_withParameter() throws Exception { + wireMockRule.stubFor(get(urlPathMatching("/example/*")) + .willReturn(aResponse().withHeader("Content-Type", "application/json").withStatus(HttpStatus.OK.value()).withBody(jsonResponseAsString))); + restClient.setParameter("name", "value"); + restClient.setParameter("type", "valueType"); + APIResponse apiResponse = restClient.get(); + assertEquals(200, apiResponse.getStatusCode()); + assertEquals(jsonResponseAsString, apiResponse.getResponseBodyAsString()); + assertEquals("application/json", apiResponse.getFirstHeader("Content-Type")); + } + +} diff --git a/bpmn/MSORESTClient/src/test/java/org/onap/so/rest/RESTConfigTest.java b/bpmn/MSORESTClient/src/test/java/org/onap/so/rest/RESTConfigTest.java new file mode 100644 index 0000000000..82c3c37be0 --- /dev/null +++ b/bpmn/MSORESTClient/src/test/java/org/onap/so/rest/RESTConfigTest.java @@ -0,0 +1,42 @@ +/* +* ============LICENSE_START======================================================= + * ONAP : SO + * ================================================================================ + * Copyright (C) 2018 TechMahindra + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= +*/ + +package org.onap.so.rest; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.mock; +import org.junit.Test; + +public class RESTConfigTest { + + @Test + public void test() { + RESTConfig rcfg=mock(RESTConfig.class); + RESTConfig rcf=new RESTConfig("URL"); + RESTConfig rcfi=new RESTConfig("URL", true); + RESTConfig rcfo=new RESTConfig("URL", "10.2.3.101", 5020); + RESTConfig rcfn=new RESTConfig("URL", "10.2.3.101", 5020, true); + assert(rcfo.getProxyHost().equals("10.2.3.101")); + assertEquals(5020,rcfn.getProxyPort()); + assert(rcf.getURL().equals("URL")); + assertTrue(rcfn.trustAllCerts()); + } +} diff --git a/bpmn/MSORESTClient/src/test/java/org/onap/so/rest/RESTExceptionTest.java b/bpmn/MSORESTClient/src/test/java/org/onap/so/rest/RESTExceptionTest.java new file mode 100644 index 0000000000..19339a187d --- /dev/null +++ b/bpmn/MSORESTClient/src/test/java/org/onap/so/rest/RESTExceptionTest.java @@ -0,0 +1,40 @@ +/* +* ============LICENSE_START======================================================= + * ONAP : SO + * ================================================================================ + * Copyright (C) 2018 TechMahindra + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= +*/ + +package org.onap.so.rest; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.mock; +import org.junit.Test; + +public class RESTExceptionTest { + + @Test + public void test() { + RESTException rexm=mock(RESTException.class); + RESTException rex=new RESTException("Error"); + RESTException recpt=new RESTException(200, "Error"); + assert(rex.getErrorMessage().equals("Error")); + assertEquals(200,recpt.getStatusCode()); + Throwable throwable = mock(Throwable.class); + RESTException restException = new RESTException(throwable); + assertEquals(-1, restException.getStatusCode()); + } +} diff --git a/bpmn/MSORESTClient/src/test/java/org/openecomp/mso/rest/APIResponseTest.java b/bpmn/MSORESTClient/src/test/java/org/openecomp/mso/rest/APIResponseTest.java deleted file mode 100644 index 166a2ff52f..0000000000 --- a/bpmn/MSORESTClient/src/test/java/org/openecomp/mso/rest/APIResponseTest.java +++ /dev/null @@ -1,57 +0,0 @@ -/* -* ============LICENSE_START======================================================= -* ONAP : SO -* ================================================================================ -* Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. -*================================================================================= -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -* ============LICENSE_END========================================================= -*/ - -package org.openecomp.mso.rest; - -import static org.junit.Assert.assertEquals; - -import org.json.JSONObject; -import org.junit.Test; - -import org.apache.http.HttpResponse; -import org.apache.http.ProtocolVersion; -import org.apache.http.HttpEntity; -import org.apache.http.entity.ContentType; -import org.apache.http.entity.StringEntity; -import org.apache.http.message.BasicHttpResponse; - -public class APIResponseTest { - - @Test - public void test() throws Exception { - JSONObject jsonObject = new JSONObject(); - jsonObject.put("firstName", "firstName1"); - jsonObject.put("lastName", "lastName1"); - String jsonObjectAsString= jsonObject.toString(); - HttpEntity entity = new StringEntity(jsonObjectAsString, ContentType.APPLICATION_JSON); - ProtocolVersion ver = new ProtocolVersion("HTTP", 1, 1); - HttpResponse response = new BasicHttpResponse(ver, 1, "Ok"); - response.setStatusLine(ver, 200); - response.setEntity(entity); - response.setHeader("name", "value"); - response.setStatusCode(200); - APIResponse apiResponse = new APIResponse(response); - assertEquals(200, apiResponse.getStatusCode()); - assertEquals(jsonObject.toString(), apiResponse.getResponseBodyAsString()); - assertEquals("value", apiResponse.getFirstHeader("name")); - assertEquals(1, apiResponse.getAllHeaders().length); - assertEquals(49, apiResponse.getResponseBodyAsByteArray().length); - } -} \ No newline at end of file diff --git a/bpmn/MSORESTClient/src/test/java/org/openecomp/mso/rest/HttpHeaderTest.java b/bpmn/MSORESTClient/src/test/java/org/openecomp/mso/rest/HttpHeaderTest.java deleted file mode 100644 index 29b7e15364..0000000000 --- a/bpmn/MSORESTClient/src/test/java/org/openecomp/mso/rest/HttpHeaderTest.java +++ /dev/null @@ -1,34 +0,0 @@ -/* -* ============LICENSE_START======================================================= -* ONAP : SO -* ================================================================================ -* Copyright 2018 TechMahindra -*================================================================================= -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -* ============LICENSE_END========================================================= -*/ - -package org.openecomp.mso.rest; - -import static org.junit.Assert.assertEquals; -import org.junit.Test; - -public class HttpHeaderTest { - - @Test - public void test() { - HttpHeader hth= new HttpHeader("name", "value"); - assertEquals("name", hth.getName()); - assertEquals("value", hth.getValue()); - } -} diff --git a/bpmn/MSORESTClient/src/test/java/org/openecomp/mso/rest/RESTClientTest.java b/bpmn/MSORESTClient/src/test/java/org/openecomp/mso/rest/RESTClientTest.java deleted file mode 100644 index d3fd4f9ea5..0000000000 --- a/bpmn/MSORESTClient/src/test/java/org/openecomp/mso/rest/RESTClientTest.java +++ /dev/null @@ -1,50 +0,0 @@ -/* -* ============LICENSE_START======================================================= -* ONAP : SO -* ================================================================================ -* Copyright 2018 TechMahindra -*================================================================================= -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -* ============LICENSE_END========================================================= -*/ - -package org.openecomp.mso.rest; - -import static org.mockito.Mockito.mock; -import java.util.ArrayList; -import java.util.LinkedHashMap; -import java.util.List; -import org.apache.http.HttpResponse; -import org.apache.http.message.AbstractHttpMessage; -import org.junit.Test; - -public class RESTClientTest { - - @Test - public void test()throws Exception{ - APIResponse apr=mock(APIResponse.class); - HttpResponse response=mock(HttpResponse.class); - AbstractHttpMessage httpMsg=mock(AbstractHttpMessage.class); - RESTClient cle=mock(RESTClient.class); - RESTClient rcl=new RESTClient("URL"); - RESTClient rcle=new RESTClient("URL", "10.5.3.126", 5020); - LinkedHashMap> headers=new LinkedHashMap<>() ; - Listlist=new ArrayList<>(); - list.add("value"); - headers.put("name", list); - rcle.setHeader("name", "value"); - rcle.setParameter("name", "value"); - assert(rcle.getHeaders()!=null); - assert(rcle.getParameters()!=null); - } -} diff --git a/bpmn/MSORESTClient/src/test/java/org/openecomp/mso/rest/RESTConfigTest.java b/bpmn/MSORESTClient/src/test/java/org/openecomp/mso/rest/RESTConfigTest.java deleted file mode 100644 index a64f112234..0000000000 --- a/bpmn/MSORESTClient/src/test/java/org/openecomp/mso/rest/RESTConfigTest.java +++ /dev/null @@ -1,42 +0,0 @@ -/* -* ============LICENSE_START======================================================= -* ONAP : SO -* ================================================================================ -* Copyright 2018 TechMahindra -*================================================================================= -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -* ============LICENSE_END========================================================= -*/ - -package org.openecomp.mso.rest; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.mock; -import org.junit.Test; - -public class RESTConfigTest { - - @Test - public void test() { - RESTConfig rcfg=mock(RESTConfig.class); - RESTConfig rcf=new RESTConfig("URL"); - RESTConfig rcfi=new RESTConfig("URL", true); - RESTConfig rcfo=new RESTConfig("URL", "10.2.3.101", 5020); - RESTConfig rcfn=new RESTConfig("URL", "10.2.3.101", 5020, true); - assert(rcfo.getProxyHost().equals("10.2.3.101")); - assertEquals(5020,rcfn.getProxyPort()); - assert(rcf.getURL().equals("URL")); - assertTrue(rcfn.trustAllCerts()); - } -} diff --git a/bpmn/MSORESTClient/src/test/java/org/openecomp/mso/rest/RESTExceptionTest.java b/bpmn/MSORESTClient/src/test/java/org/openecomp/mso/rest/RESTExceptionTest.java deleted file mode 100644 index de2cd0f608..0000000000 --- a/bpmn/MSORESTClient/src/test/java/org/openecomp/mso/rest/RESTExceptionTest.java +++ /dev/null @@ -1,37 +0,0 @@ -/* -* ============LICENSE_START======================================================= -* ONAP : SO -* ================================================================================ -* Copyright 2018 TechMahindra -*================================================================================= -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -* ============LICENSE_END========================================================= -*/ - -package org.openecomp.mso.rest; - -import static org.junit.Assert.assertEquals; -import static org.mockito.Mockito.mock; -import org.junit.Test; - -public class RESTExceptionTest { - - @Test - public void test() { - RESTException rexm=mock(RESTException.class); - RESTException rex=new RESTException("Error"); - RESTException recpt=new RESTException(200, "Error"); - assert(rex.getErrorMessage().equals("Error")); - assertEquals(200,recpt.getStatusCode()); - } -} -- cgit 1.2.3-korg