Add sdnr wt devicemanager
[ccsdk/features.git] / sdnr / wt / devicemanager / provider / src / main / java / org / onap / ccsdk / features / sdnr / wt / devicemanager / dcaeconnector / impl / DcaeSenderImpl.java
1 /*******************************************************************************
2  * ============LICENSE_START========================================================================
3  * ONAP : ccsdk feature sdnr wt
4  * =================================================================================================
5  * Copyright (C) 2019 highstreet technologies GmbH Intellectual Property. All rights reserved.
6  * =================================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
8  * in compliance with the License. You may obtain a copy of the License at
9  *
10  * http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing, software distributed under the License
13  * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
14  * or implied. See the License for the specific language governing permissions and limitations under
15  * the License.
16  * ============LICENSE_END==========================================================================
17  ******************************************************************************/
18 /**
19  * Client for ECOMP notification server
20  *
21  * Reference: @link
22  * http://stackoverflow.com/questions/13022717/java-and-https-url-connection-without-downloading-certificate
23  *
24  * @author herbert
25  */
26 package org.onap.ccsdk.features.sdnr.wt.devicemanager.dcaeconnector.impl;
27
28 import java.io.BufferedReader;
29 import java.io.IOException;
30 import java.io.InputStream;
31 import java.io.InputStreamReader;
32 import java.io.OutputStream;
33 import java.io.Reader;
34 import java.net.HttpURLConnection;
35 import java.net.URL;
36 import java.net.URLConnection;
37 import java.security.KeyManagementException;
38 import java.security.KeyStoreException;
39 import java.security.NoSuchAlgorithmException;
40 import java.security.UnrecoverableKeyException;
41 import java.security.cert.CertificateException;
42 import java.security.spec.InvalidKeySpecException;
43 import java.util.Base64;
44 import javax.net.ssl.SSLContext;
45 import org.onap.ccsdk.features.sdnr.wt.devicemanager.base.http.BaseHTTPClient;
46 import org.slf4j.Logger;
47 import org.slf4j.LoggerFactory;
48
49 public class DcaeSenderImpl implements DcaeSender {
50
51     private static final Logger LOG = LoggerFactory.getLogger(DcaeSenderImpl.class);
52     private static final String EMPTY = "";
53     private static final String charset = "UTF-8";
54
55     private final String urlString;
56     private final String basicAuth;
57
58     private SSLContext sc = null;
59     private URL url = null;
60     private HttpURLConnection connection = null;
61
62     public DcaeSenderImpl(String url, String userCredentials) {
63
64         LOG.info("DcaeSenderImpl setup start with {} {}", url, userCredentials);
65
66         this.urlString = url;
67         this.basicAuth = "Basic " + new String(Base64.getEncoder().encode(userCredentials.getBytes()));
68
69         if (urlString != null && !urlString.equals("off")) {
70             try {
71                 this.url = new URL(url);
72                 sc = BaseHTTPClient.setupSsl(true);
73             } catch (KeyManagementException | NoSuchAlgorithmException | UnrecoverableKeyException
74                     | CertificateException | KeyStoreException | InvalidKeySpecException | IOException e) {
75                 LOG.warn("SSL setup failed: {}", e.getMessage());
76             }
77         }
78         LOG.info("DcaeSenderImpl setup ends");
79     }
80
81     /**
82      * Send message to ECOMP Server
83      *
84      * @param body for POST message
85      */
86     @Override
87     public String sendDcaePost(String body) {
88
89         if (url != null) {
90             try {
91                 connection = DcaeMessages.openConnection(url, basicAuth, true, sc);
92                 if (connection != null) {
93                     return processPost(connection, body);
94                 } else {
95                     LOG.warn("No SSL context available");
96                 }
97             } catch (IOException e) {
98                 LOG.warn("Dcae post failed {}", e.getMessage());
99             }
100         }
101         return EMPTY;
102     }
103
104     /**
105      * Connect to Server and expect answer.
106      *
107      * @return with answer body
108      */
109     public String testConnectServer() {
110
111         if (url != null) {
112             try {
113                 connection = DcaeMessages.openConnection(url, null, false, sc);
114                 if (connection != null) {
115                     return receiveInitialAnswer(connection);
116                 }
117             } catch (IOException e) {
118                 LOG.warn("Dcae post failed {}", e.getMessage());
119             }
120         }
121         return EMPTY;
122     }
123
124     /**
125      * Show status in readable form for testing
126      *
127      * @return String with result
128      */
129     public String getStatusAsString() {
130         StringBuffer sb = new StringBuffer();
131
132         sb.append("URL: " + url.getPath() + " " + url.getPort() + " Host: " + url.getHost());
133         sb.append("\n");
134         if (connection != null) {
135             sb.append("Connection setup: ");
136             sb.append(connection.getClass().getName());
137             sb.append(" ");
138         } else {
139             sb.append("Connection setup: No connection (server problem or switched off)");
140         }
141         return sb.toString();
142
143     }
144
145
146     /*------------------------------------------------------------------------------
147      * Private functions
148      */
149
150
151     /**
152      * Send Post and wait for answer
153      *
154      * @param connection
155      * @param body
156      * @return
157      * @throws IOException
158      */
159     private static String processPost(HttpURLConnection connection, String body) throws IOException {
160
161         LOG.debug("Post message: {}", connection.getURL().toString());
162         if (LOG.isTraceEnabled()) {
163             LOG.trace("Body: {} ", body);
164         }
165
166         // Send the message to destination
167         try (OutputStream output = connection.getOutputStream()) {
168             output.write(body.getBytes(charset));
169         }
170
171         // Receive answer
172         InputStream response = null;
173         BufferedReader rd = null;
174         StringBuilder result = new StringBuilder();
175
176         try {
177             int responseCode = connection.getResponseCode();
178             LOG.debug("Response code: {}", String.valueOf(responseCode));
179
180             if (responseCode >= 200 && responseCode < 300) {
181                 response = connection.getInputStream();
182             } else {
183                 response = connection.getErrorStream();
184                 if (response == null) {
185                     response = connection.getInputStream();
186                 }
187             }
188             if (response != null) {
189                 rd = new BufferedReader(new InputStreamReader(response));
190                 String line;
191                 while ((line = rd.readLine()) != null) {
192                     result.append(line);
193                 }
194             }
195         } catch (IOException e) {
196             LOG.debug("No response received: {}", e.getMessage());
197         } finally {
198             if (response != null) {
199                 response.close();
200             }
201             if (rd != null) {
202                 rd.close();
203             }
204         }
205
206         LOG.trace("Result: {} ", result);
207         return result.toString();
208     }
209
210     /**
211      * Read initial answer from Server after connect
212      *
213      * @param connection that was opened
214      * @return String with answer message
215      * @throws IOException
216      */
217     private static String receiveInitialAnswer(URLConnection iConnection) throws IOException {
218
219
220         final StringBuffer response = new StringBuffer();
221
222         if (iConnection != null) {
223
224             final Reader reader = new InputStreamReader(iConnection.getInputStream());
225             final BufferedReader br = new BufferedReader(reader);
226             String line = "";
227             while ((line = br.readLine()) != null) {
228                 response.append(line);
229                 response.append("\n");
230             }
231             br.close();
232         }
233
234         return response.toString();
235     }
236 }