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