Fix Sonar vulnerabilities
[clamp.git] / src / main / java / org / onap / clamp / util / HttpConnectionManager.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP CLAMP
4  * ================================================================================
5  * Copyright (C) 2019 AT&T Intellectual Property. All rights
6  *                             reserved.
7  * ================================================================================
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  *
12  * http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  * ============LICENSE_END============================================
20  * Modifications copyright (c) 2018 Nokia
21  * ===================================================================
22  *
23  */
24
25 package org.onap.clamp.util;
26
27 import com.att.eelf.configuration.EELFLogger;
28 import com.att.eelf.configuration.EELFManager;
29
30 import java.io.BufferedReader;
31 import java.io.DataOutputStream;
32 import java.io.IOException;
33 import java.io.InputStreamReader;
34 import java.net.HttpURLConnection;
35 import java.net.URL;
36 import java.nio.charset.StandardCharsets;
37 import java.util.Base64;
38
39 import javax.net.ssl.HttpsURLConnection;
40 import javax.ws.rs.BadRequestException;
41
42 import org.apache.commons.io.IOUtils;
43 import org.onap.clamp.clds.util.LoggingUtils;
44 import org.springframework.stereotype.Component;
45
46 /**
47  * This class manages the HTTP and HTTPS connections.
48  */
49 @Component
50 public class HttpConnectionManager {
51     protected static final EELFLogger logger = EELFManager.getInstance().getLogger(HttpConnectionManager.class);
52     protected static final EELFLogger metricsLogger = EELFManager.getInstance().getMetricsLogger();
53     private static final String REQUEST_FAILED_LOG = "Request Failed - response payload=";
54
55     private String doHttpsQuery(URL url, String requestMethod, String payload, String contentType, String target,
56         String userName, String password) throws IOException {
57         LoggingUtils utils = new LoggingUtils(logger);
58         logger.info("Using HTTPS URL:" + url.toString());
59         HttpsURLConnection secureConnection = (HttpsURLConnection) url.openConnection();
60         secureConnection = utils.invokeHttps(secureConnection, target, requestMethod);
61         secureConnection.setRequestMethod(requestMethod);
62         if (userName != null && password != null) {
63             secureConnection.setRequestProperty("Authorization", "Basic "
64                 + Base64.getEncoder().encodeToString((userName + ":" + password).getBytes(StandardCharsets.UTF_8)));
65         }
66         if (payload != null && contentType != null) {
67             secureConnection.setRequestProperty("Content-Type", contentType);
68             secureConnection.setDoOutput(true);
69             try (DataOutputStream wr = new DataOutputStream(secureConnection.getOutputStream())) {
70                 wr.writeBytes(payload);
71                 wr.flush();
72             }
73         }
74         int responseCode = secureConnection.getResponseCode();
75         logger.info("Response Code: " + responseCode);
76         if (responseCode < 400) {
77             try (BufferedReader reader = new BufferedReader(new InputStreamReader(secureConnection.getInputStream()))) {
78                 String responseStr = IOUtils.toString(reader);
79                 logger.info("Response Content: " + responseStr);
80                 return responseStr;
81             }
82         } else {
83             // In case of connection failure just check whether there is a
84             // content or not
85             try (BufferedReader reader = new BufferedReader(new InputStreamReader(secureConnection.getErrorStream()))) {
86                 String responseStr = IOUtils.toString(reader);
87                 logger.error(REQUEST_FAILED_LOG + responseStr);
88                 throw new BadRequestException(responseStr);
89             }
90         }
91     }
92
93     private String doHttpQuery(URL url, String requestMethod, String payload, String contentType, String target,
94         String userName, String password) throws IOException {
95         LoggingUtils utils = new LoggingUtils(logger);
96         logger.info("Using HTTP URL:" + url);
97         HttpURLConnection connection = (HttpURLConnection) url.openConnection();
98         connection = utils.invoke(connection, target, requestMethod);
99         connection.setRequestMethod(requestMethod);
100         if (userName != null && password != null) {
101             connection.setRequestProperty("Authorization", "Basic "
102                 + Base64.getEncoder().encodeToString((userName + ":" + password).getBytes(StandardCharsets.UTF_8)));
103         }
104         if (payload != null && contentType != null) {
105             connection.setRequestProperty("Content-Type", contentType);
106             connection.setDoOutput(true);
107             try (DataOutputStream wr = new DataOutputStream(connection.getOutputStream())) {
108                 wr.writeBytes(payload);
109                 wr.flush();
110             }
111         }
112         int responseCode = connection.getResponseCode();
113         logger.info("Response Code: " + responseCode);
114         if (responseCode < 400) {
115             try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
116                 String responseStr = IOUtils.toString(reader);
117                 logger.info("Response Content: " + responseStr);
118                 utils.invokeReturn();
119                 return responseStr;
120             }
121         } else {
122             // In case of connection failure just check whether there is a
123             // content or not
124             try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getErrorStream()))) {
125                 String responseStr = IOUtils.toString(reader);
126                 logger.error(REQUEST_FAILED_LOG + responseStr);
127                 utils.invokeReturn();
128                 throw new BadRequestException(responseStr);
129             }
130         }
131     }
132
133     /**
134      * This method does a HTTP/HTTPS query with parameters specified.
135      *
136      * @param url
137      *        The string HTTP or HTTPS that mustr be used to connect
138      * @param requestMethod
139      *        The Request Method (PUT, POST, GET, DELETE, etc ...)
140      * @param payload
141      *        The payload if any, in that case an ouputstream is opened
142      * @param contentType
143      *        The "application/json or application/xml, or whatever"
144      * @return The payload of the answer
145      * @throws IOException
146      *         In case of issue with the streams
147      */
148     public String doHttpRequest(String url, String requestMethod, String payload, String contentType, String target,
149         String userName, String password) throws IOException {
150         URL urlObj = new URL(url);
151         if (url.contains("https://")) { // Support for HTTPS
152             return doHttpsQuery(urlObj, requestMethod, payload, contentType, target, userName, password);
153         } else { // Support for HTTP
154             return doHttpQuery(urlObj, requestMethod, payload, contentType, target, userName, password);
155         }
156     }
157 }