2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2019 AT&T Intellectual Property. All rights
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
12 * http://www.apache.org/licenses/LICENSE-2.0
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 * ===================================================================
25 package org.onap.clamp.util;
27 import com.att.eelf.configuration.EELFLogger;
28 import com.att.eelf.configuration.EELFManager;
30 import sun.misc.BASE64Encoder;
32 import java.io.BufferedReader;
33 import java.io.DataOutputStream;
34 import java.io.IOException;
35 import java.io.InputStreamReader;
36 import java.net.HttpURLConnection;
38 import java.security.GeneralSecurityException;
40 import javax.net.ssl.HttpsURLConnection;
41 import javax.ws.rs.BadRequestException;
43 import org.apache.commons.codec.DecoderException;
44 import org.apache.commons.io.IOUtils;
45 import org.onap.clamp.clds.util.CryptoUtils;
46 import org.onap.clamp.clds.util.LoggingUtils;
47 import org.springframework.stereotype.Component;
50 * This class manages the HTTP and HTTPS connections.
53 public class HttpConnectionManager {
54 protected static final EELFLogger logger = EELFManager.getInstance().getLogger(HttpConnectionManager.class);
55 protected static final EELFLogger metricsLogger = EELFManager.getInstance().getMetricsLogger();
56 private static final String REQUEST_FAILED_LOG = "Request Failed - response payload=";
58 private String doHttpsQuery(URL url, String requestMethod, String payload, String contentType, String target, String userName, String password) throws IOException {
59 LoggingUtils utils = new LoggingUtils(logger);
60 logger.info("Using HTTPS URL:" + url.toString());
61 HttpsURLConnection secureConnection = (HttpsURLConnection) url.openConnection();
62 secureConnection = utils.invokeHttps(secureConnection, target, requestMethod);
63 secureConnection.setRequestMethod(requestMethod);
64 if (userName != null && password != null) {
65 secureConnection.setRequestProperty("Authorization", "Basic " + generateBasicAuth(userName, password));
67 if (payload != null && contentType != null) {
68 secureConnection.setRequestProperty("Content-Type", contentType);
69 secureConnection.setDoOutput(true);
70 try (DataOutputStream wr = new DataOutputStream(secureConnection.getOutputStream())) {
71 wr.writeBytes(payload);
75 int responseCode = secureConnection.getResponseCode();
76 logger.info("Response Code: " + responseCode);
77 if (responseCode < 400) {
78 try (BufferedReader reader = new BufferedReader(new InputStreamReader(secureConnection.getInputStream()))) {
79 String responseStr = IOUtils.toString(reader);
80 logger.info("Response Content: " + responseStr);
84 // In case of connection failure just check whether there is a
86 try (BufferedReader reader = new BufferedReader(new InputStreamReader(secureConnection.getErrorStream()))) {
87 String responseStr = IOUtils.toString(reader);
88 logger.error(REQUEST_FAILED_LOG + responseStr);
89 throw new BadRequestException(responseStr);
94 private String doHttpQuery(URL url, String requestMethod, String payload, String contentType, String target, 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 " + generateBasicAuth(userName, password));
103 if (payload != null && contentType != null) {
104 connection.setRequestProperty("Content-Type", contentType);
105 connection.setDoOutput(true);
106 try (DataOutputStream wr = new DataOutputStream(connection.getOutputStream())) {
107 wr.writeBytes(payload);
111 int responseCode = connection.getResponseCode();
112 logger.info("Response Code: " + responseCode);
113 if (responseCode < 400) {
114 try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
115 String responseStr = IOUtils.toString(reader);
116 logger.info("Response Content: " + responseStr);
117 utils.invokeReturn();
121 // In case of connection failure just check whether there is a
123 try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getErrorStream()))) {
124 String responseStr = IOUtils.toString(reader);
125 logger.error(REQUEST_FAILED_LOG + responseStr);
126 utils.invokeReturn();
127 throw new BadRequestException(responseStr);
133 * This method does a HTTP/HTTPS query with parameters specified.
136 * The string HTTP or HTTPS that mustr be used to connect
137 * @param requestMethod
138 * The Request Method (PUT, POST, GET, DELETE, etc ...)
140 * The payload if any, in that case an ouputstream is opened
142 * The "application/json or application/xml, or whatever"
143 * @return The payload of the answer
144 * @throws IOException
145 * In case of issue with the streams
147 public String doGeneralHttpQuery(String url, String requestMethod, String payload, String contentType, String target, String userName, String password)
149 URL urlObj = new URL(url);
150 if (url.contains("https://")) { // Support for HTTPS
151 return doHttpsQuery(urlObj, requestMethod, payload, contentType, target, userName, password);
152 } else { // Support for HTTP
153 return doHttpQuery(urlObj, requestMethod, payload, contentType, target, userName, password);
157 private String generateBasicAuth(String userName, String encodedPassword) {
158 String password = "";
160 password = CryptoUtils.decrypt(encodedPassword);
161 } catch (GeneralSecurityException e) {
162 logger.error("Unable to decrypt the password", e);
163 } catch (DecoderException e) {
164 logger.error("Exception caught when decoding the HEX String Key for encryption", e);
166 BASE64Encoder enc = new sun.misc.BASE64Encoder();
167 String userpassword = userName + ":" + password;
168 return enc.encode( userpassword.getBytes() );