Rework the submit operation
[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 sun.misc.BASE64Encoder;
31
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;
37 import java.net.URL;
38 import java.security.GeneralSecurityException;
39
40 import javax.net.ssl.HttpsURLConnection;
41 import javax.ws.rs.BadRequestException;
42
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;
48
49 /**
50  * This class manages the HTTP and HTTPS connections.
51  */
52 @Component
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=";
57
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));
66         }
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);
72                 wr.flush();
73             }
74         }
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);
81                 return responseStr;
82             }
83         } else {
84             // In case of connection failure just check whether there is a
85             // content or not
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);
90             }
91         }
92     }
93
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));
102         }
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);
108                 wr.flush();
109             }
110         }
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();
118                 return responseStr;
119             }
120         } else {
121             // In case of connection failure just check whether there is a
122             // content or not
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);
128             }
129         }
130     }
131
132     /**
133      * This method does a HTTP/HTTPS query with parameters specified.
134      *
135      * @param url
136      *        The string HTTP or HTTPS that mustr be used to connect
137      * @param requestMethod
138      *        The Request Method (PUT, POST, GET, DELETE, etc ...)
139      * @param payload
140      *        The payload if any, in that case an ouputstream is opened
141      * @param contentType
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
146      */
147     public String doGeneralHttpQuery(String url, String requestMethod, String payload, String contentType, String target, String userName, String password)
148         throws IOException {
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);
154         }
155     }
156
157     private String generateBasicAuth(String userName, String encodedPassword) {
158         String password = "";
159         try {
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);
165         }
166         BASE64Encoder enc = new sun.misc.BASE64Encoder();
167         String userpassword = userName + ":" + password;
168         return enc.encode( userpassword.getBytes() );
169     }
170 }