[POLICY-73] replace openecomp for policy-engine
[policy/engine.git] / POLICY-SDK-APP / src / main / java / org / onap / policy / utils / ConfigurableRESTUtils.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP Policy Engine
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
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
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=========================================================
19  */
20
21 package org.onap.policy.utils;
22
23
24 import java.io.IOException;
25 import java.io.InputStream;
26 import java.io.OutputStreamWriter;
27 import java.net.HttpURLConnection;
28 import java.net.URL;
29 import java.util.Map;
30
31 import org.onap.policy.common.logging.flexlogger.FlexLogger; 
32 import org.onap.policy.common.logging.flexlogger.Logger;
33
34
35 public class ConfigurableRESTUtils  {
36         
37         protected Logger LOGGER = FlexLogger.getLogger(this.getClass());
38
39         //
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
43         //
44         public enum REST_RESPONSE_FORMAT {httpResponseCode, json }
45         public enum RESQUEST_METHOD {
46                   GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS, TRACE;
47                 }
48         
49         private String ERROR_RECEIVED = "ERROR - Unexpected HTTP response: ";
50         
51         public ConfigurableRESTUtils() {
52                 //Default Constructor
53         }
54         
55         
56         /**
57          * Call the RESTful API and return a string containing the result.  The string may be either a httpResponseCode or json body
58          *              
59          * @param fullURI
60          * @param hardCodedHeaders
61          * @param httpResponseCodes
62          * @param responseFormat
63          * @param jsonBody
64          * @param requestMethod
65          * @return String
66          */
67         public String sendRESTRequest(String fullURI, Map<String, String> hardCodedHeaderMap, 
68                         Map<Integer,String> httpResponseCodeMap,
69                         REST_RESPONSE_FORMAT responseFormat,
70                         String jsonBody,
71                         RESQUEST_METHOD requestMethod ){
72                 
73                 String responseString = null;
74                 HttpURLConnection connection = null;
75                 try {
76                         
77                         URL url = new URL(fullURI);
78
79                         //
80                         // Open up the connection
81                         //
82                         connection = (HttpURLConnection)url.openConnection();
83                         //
84                         // Setup our method and headers
85                         //
86             connection.setRequestMethod(requestMethod.toString());
87
88             connection.setUseCaches(false);
89             
90             // add hard-coded headers
91             for (String headerName : hardCodedHeaderMap.keySet()) {
92                 connection.addRequestProperty(headerName, hardCodedHeaderMap.get(headerName));
93             }
94
95             
96             
97             if (jsonBody != null){
98                 connection.setDoInput(true);
99                 connection.setDoOutput(true);
100                         OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
101                         out.write(jsonBody);
102                         out.flush();
103                         out.close();
104             } else{
105                 connection.connect();
106             }
107             
108             int responseCode = connection.getResponseCode();
109             
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";
116             }
117             
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;
121             }
122             
123             // Need to read the body and return that as the responseString.
124
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() : "";
130                     scanner.close();
131                     LOGGER.debug("RESTful body: " + responseString);
132                     return responseString;
133                     
134                 } catch (Exception e) {
135                         LOGGER.error("HTTP Request/Response from RESTFUL server: " + e);
136                         responseString =  ERROR_RECEIVED + e;
137                 } finally {
138                         // cleanup the connection
139                                 if (connection != null) {
140                                 try {
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;
144                                         try {
145                                                 is = connection.getInputStream();
146                                         } catch (Exception e1) {
147                                                 LOGGER.error("Exception Occured"+e1);
148                                         }
149                                         if (is != null) {
150                                                 is.close();
151                                         }
152
153                                 } catch (IOException ex) {
154                                         LOGGER.error("Failed to close connection: " + ex, ex);
155                                 }
156                                 connection.disconnect();
157                         }
158                 }
159                 return responseString;
160
161         }
162
163 }