ede5150640b5d67e068e0f6fb52f3874718b10c0
[ccsdk/apps.git] / sdnr / wireless-transport / code-Carbon-SR1 / apps / devicemanager / impl / src / main / java / org / opendaylight / mwtn / dcaeConnector / impl / DcaeSenderImpl.java
1 /**
2  * Client for ECOMP notification server
3  *
4  * Reference: @link http://stackoverflow.com/questions/13022717/java-and-https-url-connection-without-downloading-certificate
5  *
6  * @author herbert
7  */
8 package org.opendaylight.mwtn.dcaeConnector.impl;
9
10 import java.io.BufferedReader;
11 import java.io.IOException;
12 import java.io.InputStream;
13 import java.io.InputStreamReader;
14 import java.io.OutputStream;
15 import java.io.Reader;
16 import java.net.HttpURLConnection;
17 import java.net.URL;
18 import java.net.URLConnection;
19 import java.security.KeyManagementException;
20 import java.security.KeyStoreException;
21 import java.security.NoSuchAlgorithmException;
22 import java.security.UnrecoverableKeyException;
23 import java.security.cert.CertificateException;
24 import java.security.spec.InvalidKeySpecException;
25 import java.util.Base64;
26
27 import javax.net.ssl.SSLContext;
28
29 import org.opendaylight.mwtn.base.http.BaseHTTPClient;
30 import org.slf4j.Logger;
31 import org.slf4j.LoggerFactory;
32
33 public class DcaeSenderImpl implements DcaeSender {
34
35     private static final Logger LOG = LoggerFactory.getLogger(DcaeSenderImpl.class);
36     private static String EMPTY = "";
37     private static final String charset = "UTF-8";
38
39     private final String urlString;
40     private final String basicAuth;
41
42         private SSLContext sc = null;
43     private URL url = null;
44     private HttpURLConnection connection = null;
45
46     public DcaeSenderImpl( String url, String userCredentials)  {
47
48         LOG.info("DcaeSenderImpl setup start with {} {}", url, userCredentials);
49
50         this.urlString = url;
51         this.basicAuth = "Basic " + new String(Base64.getEncoder().encode(userCredentials.getBytes()));
52
53         if (urlString != null && !urlString.equals("off")) {
54                 try {
55                         this.url = new URL(url);
56                         sc = BaseHTTPClient.setupSsl(true);
57                 } catch (KeyManagementException | NoSuchAlgorithmException | UnrecoverableKeyException | CertificateException | KeyStoreException | InvalidKeySpecException | IOException e) {
58                         LOG.warn("SSL setup failed: {}", e.getMessage());
59                 }
60         }
61         LOG.info("DcaeSenderImpl setup ends");
62     }
63
64     /**
65      * Send message to ECOMP Server
66      * @param body for POST message
67      */
68     @Override
69     public String sendDcaePost(String body) {
70
71         if (url != null) {
72             try {
73                 connection = DcaeMessages.openConnection(url, basicAuth, true, sc);
74                 if (connection != null) {
75                     return processPost(connection, body);
76                 } else {
77                                 LOG.warn("No SSL context available");
78                 }
79             } catch (IOException e) {
80                 LOG.warn("Dcae post failed {}", e.getMessage());
81             }
82         }
83         return EMPTY;
84     }
85
86     /**
87      * Connect to Server and expect answer.
88      * @return with answer body
89      */
90     public String testConnectServer() {
91
92        if (url != null) {
93             try {
94                 connection = DcaeMessages.openConnection(url, null, false, sc);
95                 if (connection != null) {
96                     return receiveInitialAnswer(connection);
97                 }
98             } catch (IOException e) {
99                 LOG.warn("Dcae post failed {}", e.getMessage());
100             }
101         }
102         return EMPTY;
103     }
104
105     /**
106      * Show status in readable form for testing
107      * @return String with result
108      */
109     public String getStatusAsString() {
110         StringBuffer sb = new StringBuffer();
111
112         sb.append("URL: "+ url.getPath() +" "+ url.getPort() + " Host: "+ url.getHost());
113         sb.append("\n");
114         if (connection != null) {
115             sb.append("Connection setup: ");
116             sb.append(connection.getClass().getName());
117             sb.append(" ");
118          } else {
119             sb.append("Connection setup: No connection (server problem or switched off)");
120         }
121         return sb.toString();
122
123     }
124
125
126     /*------------------------------------------------------------------------------
127      * Private functions
128      */
129
130
131     /**
132      * Send Post and wait for answer
133      * @param connection
134      * @param body
135      * @return
136      * @throws IOException
137      */
138     private static String processPost( HttpURLConnection connection, String body ) throws IOException {
139
140         LOG.debug("Post message: {}", connection.getURL().toString());
141         if (LOG.isTraceEnabled()) {
142                 LOG.trace("Body: {} ", body);
143         }
144
145         //Send the message to destination
146         try (OutputStream output = connection.getOutputStream()) {
147             output.write(body.getBytes(charset));
148         }
149
150         //Receive answer
151                 try {
152                         int responseCode = connection.getResponseCode();
153                     LOG.debug("Response code: {}", String.valueOf(responseCode));
154
155                     InputStream response= null;
156                         if (responseCode >= 200 && responseCode < 300)
157                                 response = connection.getInputStream();
158                         else {
159                                 response = connection.getErrorStream();
160                                 if (response == null)
161                                         response = connection.getInputStream();
162                         }
163
164                         if (response != null) {
165                             BufferedReader rd = new BufferedReader(new InputStreamReader(response));
166                             String line;
167                             StringBuilder result = new StringBuilder();
168                             while ((line = rd.readLine()) != null) {
169                                 result.append(line);
170                             }
171                             rd.close();
172                             if (LOG.isTraceEnabled()) {
173                                 LOG.trace("Result: {} ", result.toString());
174                             }
175                             return result.toString();
176                         }
177                 } catch (IOException e) {
178                         LOG.debug("No response received: {}", e.getMessage());
179                 }
180                 return EMPTY;
181     }
182
183
184
185
186     /**
187      * Read initial answer from Server after connect
188      * @param connection that was opened
189      * @return String with answer message
190      * @throws IOException
191      */
192     private static String receiveInitialAnswer(URLConnection iConnection) throws IOException {
193
194
195         final StringBuffer response = new StringBuffer();
196
197         if (iConnection != null) {
198
199             final Reader reader = new InputStreamReader(iConnection.getInputStream());
200             final BufferedReader br = new BufferedReader(reader);
201             String line = "";
202             while ((line = br.readLine()) != null) {
203                 response.append(line);
204                 response.append("\n");
205             }
206             br.close();
207         }
208
209         return response.toString();
210     }
211 }