Fix DCAE connection issue
[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  * ECOMP is a trademark and service mark of AT&T Intellectual Property.
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 import java.security.KeyManagementException;
36 import java.security.NoSuchAlgorithmException;
37 import java.security.cert.CertificateException;
38 import java.security.cert.X509Certificate;
39
40 import javax.net.ssl.HostnameVerifier;
41 import javax.net.ssl.HttpsURLConnection;
42 import javax.net.ssl.SSLContext;
43 import javax.net.ssl.SSLSession;
44 import javax.net.ssl.TrustManager;
45 import javax.net.ssl.X509TrustManager;
46 import javax.ws.rs.BadRequestException;
47
48 import org.apache.commons.io.IOUtils;
49 import org.onap.clamp.clds.util.LoggingUtils;
50
51 public class DcaeHttpConnectionManager {
52     protected static final EELFLogger logger                  = EELFManager.getInstance()
53             .getLogger(DcaeHttpConnectionManager.class);
54     protected static final EELFLogger metricsLogger           = EELFManager.getInstance().getMetricsLogger();
55     private static final String       DCAE_REQUEST_FAILED_LOG = "Request Failed - response payload=";
56
57     private DcaeHttpConnectionManager() {
58     }
59
60     static TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
61         @Override
62         public java.security.cert.X509Certificate[] getAcceptedIssuers() {
63             return null;
64         }
65
66         @Override
67         public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
68         }
69
70         @Override
71         public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
72         }
73     } };
74
75     private static void enableSslNoCheck() {
76         try {
77             SSLContext sc = SSLContext.getInstance("SSL");
78             sc.init(null, trustAllCerts, new java.security.SecureRandom());
79             HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
80             HostnameVerifier allHostsValid = new HostnameVerifier() {
81                 @Override
82                 public boolean verify(String hostname, SSLSession session) {
83                     return true;
84                 }
85             };
86             // set the allTrusting verifier
87             HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
88         } catch (KeyManagementException | NoSuchAlgorithmException e) {
89             logger.error("Error when disabling security on SSL", e);
90         }
91     }
92
93     private static String doHttpsQuery(URL url, String requestMethod, String payload, String contentType)
94             throws IOException {
95         logger.info("Using HTTPS URL to contact DCAE:" + url.toString());
96         HttpsURLConnection secureConnection = (HttpsURLConnection) url.openConnection();
97         secureConnection.setRequestMethod(requestMethod);
98         secureConnection.setRequestProperty("X-ECOMP-RequestID", LoggingUtils.getRequestId());
99         if (payload != null && contentType != null) {
100             secureConnection.setRequestProperty("Content-Type", contentType);
101             secureConnection.setDoOutput(true);
102             try (DataOutputStream wr = new DataOutputStream(secureConnection.getOutputStream())) {
103                 wr.writeBytes(payload);
104                 wr.flush();
105             }
106         }
107         int responseCode = secureConnection.getResponseCode();
108         logger.info("Response Code: " + responseCode);
109         if (responseCode < 400) {
110             try (BufferedReader reader = new BufferedReader(new InputStreamReader(secureConnection.getInputStream()))) {
111                 String responseStr = IOUtils.toString(reader);
112                 logger.info("Response Content: " + responseStr);
113                 return responseStr;
114             }
115         } else {
116             // In case of connection failure just check whether there is a
117             // content or not
118             try (BufferedReader reader = new BufferedReader(new InputStreamReader(secureConnection.getErrorStream()))) {
119                 String responseStr = IOUtils.toString(reader);
120                 logger.error(DCAE_REQUEST_FAILED_LOG + responseStr);
121                 throw new BadRequestException(responseStr);
122             }
123         }
124     }
125
126     private static String doHttpQuery(URL url, String requestMethod, String payload, String contentType)
127             throws IOException {
128         logger.info("Using HTTP URL to contact DCAE:" + url);
129         HttpURLConnection connection = (HttpURLConnection) url.openConnection();
130         connection.setRequestMethod(requestMethod);
131         connection.setRequestProperty("X-ECOMP-RequestID", LoggingUtils.getRequestId());
132         if (payload != null && contentType != null) {
133             connection.setRequestProperty("Content-Type", contentType);
134             connection.setDoOutput(true);
135             try (DataOutputStream wr = new DataOutputStream(connection.getOutputStream())) {
136                 wr.writeBytes(payload);
137                 wr.flush();
138             }
139         }
140         int responseCode = connection.getResponseCode();
141         logger.info("Response Code: " + responseCode);
142         if (responseCode < 400) {
143             try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
144                 String responseStr = IOUtils.toString(reader);
145                 logger.info("Response Content: " + responseStr);
146                 return responseStr;
147             }
148         } else {
149             // In case of connection failure just check whether there is a
150             // content or not
151             try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getErrorStream()))) {
152                 String responseStr = IOUtils.toString(reader);
153                 logger.error(DCAE_REQUEST_FAILED_LOG + responseStr);
154                 throw new BadRequestException(responseStr);
155             }
156         }
157     }
158
159     /**
160      * This method does a HTTP query to DCAE with parameters specified.
161      * 
162      * @param url
163      *            The string HTTP or HTTPS that mustr be used to connect
164      * @param requestMethod
165      *            The Request Method (PUT, POST, GET, DELETE, etc ...)
166      * @param payload
167      *            The payload if any, in that case an ouputstream is opened
168      * @param contentType
169      *            The "application/json or application/xml, or whatever"
170      * @return The payload of the answer
171      * @throws IOException
172      *             In case of issue with the streams
173      */
174     public static String doDcaeHttpQuery(String url, String requestMethod, String payload, String contentType)
175             throws IOException {
176         return doDcaeHttpQuery(url, requestMethod, payload, contentType, false);
177     }
178
179     /**
180      * This method does a HTTP/HTTPS query to DCAE with parameters specified.
181      * 
182      * @param url
183      *            The string HTTP or HTTPS that mustr be used to connect
184      * @param requestMethod
185      *            The Request Method (PUT, POST, GET, DELETE, etc ...)
186      * @param payload
187      *            The payload if any, in that case an ouputstream is opened
188      * @param contentType
189      *            The "application/json or application/xml, or whatever"
190      * @param withoutSecurity
191      *            Disable or not the SSL security (certificate,hostname, etc...)
192      * @return The payload of the answer
193      * @throws IOException
194      *             In case of issue with the streams
195      */
196     public static String doDcaeHttpQuery(String url, String requestMethod, String payload, String contentType,
197             boolean withoutSecurity) throws IOException {
198         URL urlObj = new URL(url);
199         if (url.contains("https://")) { // Support for HTTPS
200             if (withoutSecurity) {
201                 enableSslNoCheck();
202             }
203             return doHttpsQuery(urlObj, requestMethod, payload, contentType);
204         } else { // Support for HTTP
205             return doHttpQuery(urlObj, requestMethod, payload, contentType);
206         }
207     }
208 }