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.onap.policy.utils;
24 import java.io.IOException;
25 import java.io.InputStream;
26 import java.io.OutputStreamWriter;
27 import java.net.HttpURLConnection;
30 import java.util.Map.Entry;
32 import org.onap.policy.common.logging.flexlogger.FlexLogger;
33 import org.onap.policy.common.logging.flexlogger.Logger;
36 public class ConfigurableRESTUtils {
38 protected Logger LOGGER = FlexLogger.getLogger(this.getClass());
41 // How the value is returned from the RESTful server
42 // httpResponseCode means the result is simply the HTTP Response code (e.g. 200, 505, etc.)
43 // other values identify the encoding used for the string in the body of the HTTP response
45 public enum REST_RESPONSE_FORMAT {httpResponseCode, json }
46 public enum RESQUEST_METHOD {
47 GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS, TRACE;
50 private String ERROR_RECEIVED = "ERROR - Unexpected HTTP response: ";
52 public ConfigurableRESTUtils() {
58 * Call the RESTful API and return a string containing the result. The string may be either a httpResponseCode or json body
61 * @param hardCodedHeaders
62 * @param httpResponseCodes
63 * @param responseFormat
65 * @param requestMethod
68 public String sendRESTRequest(String fullURI, Map<String, String> hardCodedHeaderMap,
69 Map<Integer,String> httpResponseCodeMap,
70 REST_RESPONSE_FORMAT responseFormat,
72 RESQUEST_METHOD requestMethod ){
74 String responseString = null;
75 HttpURLConnection connection = null;
78 URL url = new URL(fullURI);
81 // Open up the connection
83 connection = (HttpURLConnection)url.openConnection();
85 // Setup our method and headers
87 connection.setRequestMethod(requestMethod.toString());
89 connection.setUseCaches(false);
91 // add hard-coded headers
92 for (Entry<String, String> entry : hardCodedHeaderMap.entrySet()) {
93 connection.addRequestProperty(entry.getKey(), entry.getValue());
96 if (jsonBody != null){
97 connection.setDoInput(true);
98 connection.setDoOutput(true);
99 OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
104 connection.connect();
107 int responseCode = connection.getResponseCode();
109 // check that the response is one we expected (and get the associated value at the same time)
110 responseString = httpResponseCodeMap.get(responseCode);
111 if (responseString == null) {
112 // the response was not configured, meaning it is unexpected and therefore an error
113 LOGGER.error("Unexpected HTTP response code '" + responseCode + "' from RESTful Server");
114 return ERROR_RECEIVED + " code" + responseCode + " from RESTful Server";
117 // if the response is contained only in the http code we are done. Otherwise we need to read the body
118 if (responseFormat == REST_RESPONSE_FORMAT.httpResponseCode) {
119 return responseString;
122 // Need to read the body and return that as the responseString.
124 responseString = null;
125 // read the inputStream into a buffer (trick found online scans entire input looking for end-of-file)
126 java.util.Scanner scanner = new java.util.Scanner(connection.getInputStream());
127 scanner.useDelimiter("\\A");
128 responseString = scanner.hasNext() ? scanner.next() : "";
130 LOGGER.debug("RESTful body: " + responseString);
131 return responseString;
133 } catch (Exception e) {
134 LOGGER.error("HTTP Request/Response from RESTFUL server: " + e);
135 responseString = ERROR_RECEIVED + e;
137 // cleanup the connection
138 if (connection != null) {
140 // For some reason trying to get the inputStream from the connection
141 // throws an exception rather than returning null when the InputStream does not exist.
142 InputStream is = null;
144 is = connection.getInputStream();
145 } catch (Exception e1) {
146 LOGGER.error("Exception Occured"+e1);
152 } catch (IOException ex) {
153 LOGGER.error("Failed to close connection: " + ex, ex);
155 connection.disconnect();
158 return responseString;