Fix technical debt and reduce lines
[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 import java.util.Map.Entry;
31
32 import org.onap.policy.common.logging.flexlogger.FlexLogger; 
33 import org.onap.policy.common.logging.flexlogger.Logger;
34
35
36 public class ConfigurableRESTUtils  {
37         
38         protected Logger LOGGER = FlexLogger.getLogger(this.getClass());
39
40         //
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
44         //
45         public enum REST_RESPONSE_FORMAT {httpResponseCode, json }
46         public enum RESQUEST_METHOD {
47                   GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS, TRACE;
48                 }
49         
50         private String ERROR_RECEIVED = "ERROR - Unexpected HTTP response: ";
51         
52         public ConfigurableRESTUtils() {
53                 //Default Constructor
54         }
55         
56         
57         /**
58          * Call the RESTful API and return a string containing the result.  The string may be either a httpResponseCode or json body
59          *              
60          * @param fullURI
61          * @param hardCodedHeaders
62          * @param httpResponseCodes
63          * @param responseFormat
64          * @param jsonBody
65          * @param requestMethod
66          * @return String
67          */
68         public String sendRESTRequest(String fullURI, Map<String, String> hardCodedHeaderMap, 
69                         Map<Integer,String> httpResponseCodeMap,
70                         REST_RESPONSE_FORMAT responseFormat,
71                         String jsonBody,
72                         RESQUEST_METHOD requestMethod ){
73                 
74                 String responseString = null;
75                 HttpURLConnection connection = null;
76                 try {
77                         
78                         URL url = new URL(fullURI);
79
80                         //
81                         // Open up the connection
82                         //
83                         connection = (HttpURLConnection)url.openConnection();
84                         //
85                         // Setup our method and headers
86                         //
87             connection.setRequestMethod(requestMethod.toString());
88
89             connection.setUseCaches(false);
90             
91             // add hard-coded headers
92             for (Entry<String, String> entry : hardCodedHeaderMap.entrySet()) {
93                 connection.addRequestProperty(entry.getKey(), entry.getValue());
94             }
95             
96             if (jsonBody != null){
97                 connection.setDoInput(true);
98                 connection.setDoOutput(true);
99                         OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
100                         out.write(jsonBody);
101                         out.flush();
102                         out.close();
103             } else{
104                 connection.connect();
105             }
106             
107             int responseCode = connection.getResponseCode();
108             
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";
115             }
116             
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;
120             }
121             
122             // Need to read the body and return that as the responseString.
123
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() : "";
129                     scanner.close();
130                     LOGGER.debug("RESTful body: " + responseString);
131                     return responseString;
132                     
133                 } catch (Exception e) {
134                         LOGGER.error("HTTP Request/Response from RESTFUL server: " + e);
135                         responseString =  ERROR_RECEIVED + e;
136                 } finally {
137                         // cleanup the connection
138                                 if (connection != null) {
139                                 try {
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;
143                                         try {
144                                                 is = connection.getInputStream();
145                                         } catch (Exception e1) {
146                                                 LOGGER.error("Exception Occured"+e1);
147                                         }
148                                         if (is != null) {
149                                                 is.close();
150                                         }
151
152                                 } catch (IOException ex) {
153                                         LOGGER.error("Failed to close connection: " + ex, ex);
154                                 }
155                                 connection.disconnect();
156                         }
157                 }
158                 return responseString;
159
160         }
161
162 }