bebb6703dc524ae8b56991cf0c59d738ff0b0a24
[clamp.git] / src / main / java / org / onap / clamp / clds / client / DcaeHttpConnectionManager.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP CLAMP
4  * ================================================================================
5  * Copyright (C) 2017 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  * ===================================================================
21  * 
22  */
23
24 package org.onap.clamp.clds.client;
25
26 import com.att.eelf.configuration.EELFLogger;
27 import com.att.eelf.configuration.EELFManager;
28
29 import java.io.BufferedReader;
30 import java.io.DataOutputStream;
31 import java.io.IOException;
32 import java.io.InputStreamReader;
33 import java.net.HttpURLConnection;
34 import java.net.URL;
35
36 import javax.net.ssl.HttpsURLConnection;
37 import javax.ws.rs.BadRequestException;
38
39 import org.apache.commons.io.IOUtils;
40 import org.onap.clamp.clds.util.LoggingUtils;
41
42 /**
43  * 
44  * This class manages the HTTP and HTTPS connections to DCAE.
45  *
46  */
47 public class DcaeHttpConnectionManager {
48     protected static final EELFLogger logger                  = EELFManager.getInstance()
49             .getLogger(DcaeHttpConnectionManager.class);
50     protected static final EELFLogger metricsLogger           = EELFManager.getInstance().getMetricsLogger();
51     private static final String       DCAE_REQUEST_FAILED_LOG = "Request Failed - response payload=";
52
53     private DcaeHttpConnectionManager() {
54     }
55
56     private static String doHttpsQuery(URL url, String requestMethod, String payload, String contentType)
57             throws IOException {
58         logger.info("Using HTTPS URL to contact DCAE:" + url.toString());
59         HttpsURLConnection secureConnection = (HttpsURLConnection) url.openConnection();
60         secureConnection.setRequestMethod(requestMethod);
61         secureConnection.setRequestProperty("X-ECOMP-RequestID", LoggingUtils.getRequestId());
62         if (payload != null && contentType != null) {
63             secureConnection.setRequestProperty("Content-Type", contentType);
64             secureConnection.setDoOutput(true);
65             try (DataOutputStream wr = new DataOutputStream(secureConnection.getOutputStream())) {
66                 wr.writeBytes(payload);
67                 wr.flush();
68             }
69         }
70         int responseCode = secureConnection.getResponseCode();
71         logger.info("Response Code: " + responseCode);
72         if (responseCode < 400) {
73             try (BufferedReader reader = new BufferedReader(new InputStreamReader(secureConnection.getInputStream()))) {
74                 String responseStr = IOUtils.toString(reader);
75                 logger.info("Response Content: " + responseStr);
76                 return responseStr;
77             }
78         } else {
79             // In case of connection failure just check whether there is a
80             // content or not
81             try (BufferedReader reader = new BufferedReader(new InputStreamReader(secureConnection.getErrorStream()))) {
82                 String responseStr = IOUtils.toString(reader);
83                 logger.error(DCAE_REQUEST_FAILED_LOG + responseStr);
84                 throw new BadRequestException(responseStr);
85             }
86         }
87     }
88
89     private static String doHttpQuery(URL url, String requestMethod, String payload, String contentType)
90             throws IOException {
91         LoggingUtils utils = new LoggingUtils (logger);
92         logger.info("Using HTTP URL to contact DCAE:" + url);
93         HttpURLConnection connection = (HttpURLConnection) url.openConnection();
94         connection = utils.invoke(connection,"DCAE", requestMethod);
95         connection.setRequestMethod(requestMethod);
96         connection.setRequestProperty("X-ECOMP-RequestID", LoggingUtils.getRequestId());
97         if (payload != null && contentType != null) {
98             connection.setRequestProperty("Content-Type", contentType);
99             connection.setDoOutput(true);
100             try (DataOutputStream wr = new DataOutputStream(connection.getOutputStream())) {
101                 wr.writeBytes(payload);
102                 wr.flush();
103             }
104         }
105         int responseCode = connection.getResponseCode();
106         logger.info("Response Code: " + responseCode);
107         if (responseCode < 400) {
108             try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
109                 String responseStr = IOUtils.toString(reader);
110                 logger.info("Response Content: " + responseStr);
111                 utils.invokeReturn();
112                 return responseStr;
113             }
114         } else {
115             // In case of connection failure just check whether there is a
116             // content or not
117             try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getErrorStream()))) {
118                 String responseStr = IOUtils.toString(reader);
119                 logger.error(DCAE_REQUEST_FAILED_LOG + responseStr);
120                 utils.invokeReturn();
121                 throw new BadRequestException(responseStr);
122             }
123         }
124     }
125
126     /**
127      * This method does a HTTP/HTTPS query to DCAE with parameters specified.
128      * 
129      * @param url
130      *            The string HTTP or HTTPS that mustr be used to connect
131      * @param requestMethod
132      *            The Request Method (PUT, POST, GET, DELETE, etc ...)
133      * @param payload
134      *            The payload if any, in that case an ouputstream is opened
135      * @param contentType
136      *            The "application/json or application/xml, or whatever"
137      * @return The payload of the answer
138      * @throws IOException
139      *             In case of issue with the streams
140      */
141     public static String doDcaeHttpQuery(String url, String requestMethod, String payload, String contentType)
142             throws IOException {
143         URL urlObj = new URL(url);
144         if (url.contains("https://")) { // Support for HTTPS
145             return doHttpsQuery(urlObj, requestMethod, payload, contentType);
146         } else { // Support for HTTP
147             return doHttpQuery(urlObj, requestMethod, payload, contentType);
148         }
149     }
150 }