aboutsummaryrefslogtreecommitdiffstats
path: root/ecomp-sdk-app/src/main/java/org/openecomp/policy/utils/ConfigurableRESTUtils.java
blob: eafd2196d501a291571c12d8aa683d2ea565be79 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
/*-
 * ============LICENSE_START=======================================================
 * ECOMP Policy Engine
 * ================================================================================
 * 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.policy.utils;


import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;

import org.openecomp.policy.common.logging.flexlogger.FlexLogger; 
import org.openecomp.policy.common.logging.flexlogger.Logger;


public class ConfigurableRESTUtils  {
	
	protected Logger logger	= FlexLogger.getLogger(this.getClass());

	//
	// How the value is returned from the RESTful server
	//		httpResponseCode means the result is simply the HTTP Response code (e.g. 200, 505, etc.)
	//		other values identify the encoding used for the string in the body of the HTTP response
	//
	public enum REST_RESPONSE_FORMAT {httpResponseCode, json }
	public enum RESQUEST_METHOD {
		  GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS, TRACE;
		}
	
	public String ERROR_RECEIVED = "ERROR - Unexpected HTTP response: ";
	
	public ConfigurableRESTUtils() {

	}
	
	
	/**
	 * Call the RESTful API and return a string containing the result.  The string may be either a httpResponseCode or json body
	 * 		
	 * @param fullURI
	 * @param hardCodedHeaders
	 * @param httpResponseCodes
	 * @param responseFormat
	 * @param jsonBody
	 * @param requestMethod
	 * @return String
	 */
	public String sendRESTRequest(String fullURI, Map<String, String> hardCodedHeaderMap, 
			Map<Integer,String> httpResponseCodeMap,
			REST_RESPONSE_FORMAT responseFormat,
			String jsonBody,
			RESQUEST_METHOD requestMethod ){
		
		String responseString = null;
		HttpURLConnection connection = null;
		try {
			
			URL url = new URL(fullURI);

			//
			// Open up the connection
			//
			connection = (HttpURLConnection)url.openConnection();
			//
			// Setup our method and headers
			//
            connection.setRequestMethod(requestMethod.toString());

            connection.setUseCaches(false);
            
            // add hard-coded headers
            for (String headerName : hardCodedHeaderMap.keySet()) {
            	connection.addRequestProperty(headerName, hardCodedHeaderMap.get(headerName));
            }

            
            
            if (jsonBody != null){
            	connection.setDoInput(true);
            	connection.setDoOutput(true);
    			OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
    			out.write(jsonBody);
    			out.flush();
    			out.close();
            } else{
            	connection.connect();
            }
            
            int responseCode = connection.getResponseCode();
            
            // check that the response is one we expected (and get the associated value at the same time)
            responseString = httpResponseCodeMap.get(responseCode);
            if (responseString == null) {
            	// the response was not configured, meaning it is unexpected and therefore an error
            	logger.error("Unexpected HTTP response code '" + responseCode + "' from RESTful Server");
            	return ERROR_RECEIVED +  " code" + responseCode + " from RESTful Server";
            }
            
            // if the response is contained only in the http code we are done.  Otherwise we need to read the body
            if (responseFormat == REST_RESPONSE_FORMAT.httpResponseCode) {
            	return responseString;
            }
            
            // Need to read the body and return that as the responseString.

            responseString = null;
			// read the inputStream into a buffer (trick found online scans entire input looking for end-of-file)
		    java.util.Scanner scanner = new java.util.Scanner(connection.getInputStream());
		    scanner.useDelimiter("\\A");
		    responseString =  scanner.hasNext() ? scanner.next() : "";
		    scanner.close();
		    logger.debug("RESTful body: " + responseString);
		    return responseString;
		    
		} catch (Exception e) {
			logger.error("HTTP Request/Response from RESTFUL server: " + e);
			responseString =  ERROR_RECEIVED + e;
		} finally {
			// cleanup the connection
				if (connection != null) {
				try {
					// For some reason trying to get the inputStream from the connection
					// throws an exception rather than returning null when the InputStream does not exist.
					InputStream is = null;
					try {
						is = connection.getInputStream();
					} catch (Exception e1) {
						// ignore this
					}
					if (is != null) {
						is.close();
					}

				} catch (IOException ex) {
					logger.error("Failed to close connection: " + ex, ex);
				}
				connection.disconnect();
			}
		}
		return responseString;

	}

}