2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6 * ================================================================================
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ============LICENSE_END=========================================================
21 package org.openecomp.policy.utils;
24 import java.io.IOException;
25 import java.io.InputStream;
26 import java.io.OutputStreamWriter;
27 import java.net.HttpURLConnection;
31 import org.openecomp.policy.common.logging.flexlogger.FlexLogger;
32 import org.openecomp.policy.common.logging.flexlogger.Logger;
35 public class ConfigurableRESTUtils {
37 protected Logger LOGGER = FlexLogger.getLogger(this.getClass());
40 // How the value is returned from the RESTful server
41 // httpResponseCode means the result is simply the HTTP Response code (e.g. 200, 505, etc.)
42 // other values identify the encoding used for the string in the body of the HTTP response
44 public enum REST_RESPONSE_FORMAT {httpResponseCode, json }
45 public enum RESQUEST_METHOD {
46 GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS, TRACE;
49 public String ERROR_RECEIVED = "ERROR - Unexpected HTTP response: ";
51 public ConfigurableRESTUtils() {
57 * Call the RESTful API and return a string containing the result. The string may be either a httpResponseCode or json body
60 * @param hardCodedHeaders
61 * @param httpResponseCodes
62 * @param responseFormat
64 * @param requestMethod
67 public String sendRESTRequest(String fullURI, Map<String, String> hardCodedHeaderMap,
68 Map<Integer,String> httpResponseCodeMap,
69 REST_RESPONSE_FORMAT responseFormat,
71 RESQUEST_METHOD requestMethod ){
73 String responseString = null;
74 HttpURLConnection connection = null;
77 URL url = new URL(fullURI);
80 // Open up the connection
82 connection = (HttpURLConnection)url.openConnection();
84 // Setup our method and headers
86 connection.setRequestMethod(requestMethod.toString());
88 connection.setUseCaches(false);
90 // add hard-coded headers
91 for (String headerName : hardCodedHeaderMap.keySet()) {
92 connection.addRequestProperty(headerName, hardCodedHeaderMap.get(headerName));
97 if (jsonBody != null){
98 connection.setDoInput(true);
99 connection.setDoOutput(true);
100 OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
105 connection.connect();
108 int responseCode = connection.getResponseCode();
110 // check that the response is one we expected (and get the associated value at the same time)
111 responseString = httpResponseCodeMap.get(responseCode);
112 if (responseString == null) {
113 // the response was not configured, meaning it is unexpected and therefore an error
114 LOGGER.error("Unexpected HTTP response code '" + responseCode + "' from RESTful Server");
115 return ERROR_RECEIVED + " code" + responseCode + " from RESTful Server";
118 // if the response is contained only in the http code we are done. Otherwise we need to read the body
119 if (responseFormat == REST_RESPONSE_FORMAT.httpResponseCode) {
120 return responseString;
123 // Need to read the body and return that as the responseString.
125 responseString = null;
126 // read the inputStream into a buffer (trick found online scans entire input looking for end-of-file)
127 java.util.Scanner scanner = new java.util.Scanner(connection.getInputStream());
128 scanner.useDelimiter("\\A");
129 responseString = scanner.hasNext() ? scanner.next() : "";
131 LOGGER.debug("RESTful body: " + responseString);
132 return responseString;
134 } catch (Exception e) {
135 LOGGER.error("HTTP Request/Response from RESTFUL server: " + e);
136 responseString = ERROR_RECEIVED + e;
138 // cleanup the connection
139 if (connection != null) {
141 // For some reason trying to get the inputStream from the connection
142 // throws an exception rather than returning null when the InputStream does not exist.
143 InputStream is = null;
145 is = connection.getInputStream();
146 } catch (Exception e1) {
153 } catch (IOException ex) {
154 LOGGER.error("Failed to close connection: " + ex, ex);
156 connection.disconnect();
159 return responseString;