CADI authentication and authorization filters
[dmaap/dbcapi.git] / src / main / java / org / onap / dmaap / dbcapi / aaf / AafConnection.java
1 /*-
2  * ============LICENSE_START=======================================================
3   * org.onap.dmaap
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  *
7  * Modifications Copyright (C) 2019 IBM.
8  * ================================================================================
9  * Licensed under the Apache License, Version 2.0 (the "License");
10  * you may not use this file except in compliance with the License.
11  * You may obtain a copy of the License at
12  * 
13  *      http://www.apache.org/licenses/LICENSE-2.0
14  * 
15  * Unless required by applicable law or agreed to in writing, software
16  * distributed under the License is distributed on an "AS IS" BASIS,
17  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18  * See the License for the specific language governing permissions and
19  * limitations under the License.
20  * ============LICENSE_END=========================================================
21  */
22
23 package org.onap.dmaap.dbcapi.aaf;
24
25
26
27
28
29 import java.io.BufferedReader;
30 import java.io.IOException;
31 import java.io.InputStream;
32 import java.io.InputStreamReader;
33 import java.io.OutputStream;
34 import java.net.ProtocolException;
35 import java.net.URL;
36 import java.net.UnknownHostException;
37 import java.net.ConnectException;
38
39 import javax.net.ssl.HttpsURLConnection;
40 import javax.net.ssl.SSLContext;
41 import javax.net.ssl.SSLHandshakeException;
42
43 import javax.net.ssl.TrustManager;
44 import javax.net.ssl.X509TrustManager;
45 import org.apache.commons.codec.binary.Base64;
46 import org.onap.dmaap.dbcapi.logging.BaseLoggingClass;
47 import org.onap.dmaap.dbcapi.logging.DmaapbcLogMessageEnum;
48 import org.onap.dmaap.dbcapi.util.DmaapConfig;
49
50
51 public class AafConnection extends BaseLoggingClass {
52
53
54
55
56
57         private String aafCred;
58         private String unit_test;
59
60
61         private HttpsURLConnection uc;
62
63
64         public AafConnection( String cred ) {
65                 aafCred = cred;
66                 DmaapConfig p = (DmaapConfig)DmaapConfig.getConfig();
67         unit_test = p.getProperty( "UnitTest", "No" );
68
69         }
70
71
72         private boolean makeConnection( String pURL ) {
73
74                 try {
75                         URL u = new URL( pURL );
76                         uc = (HttpsURLConnection) u.openConnection();
77                         uc.setInstanceFollowRedirects(false);
78                         logger.info( "successful connect to " + pURL );
79                         return(true);
80                 } catch ( UnknownHostException uhe ) {                  
81                 errorLogger.error(DmaapbcLogMessageEnum.UNKNOWN_HOST_EXCEPTION,  pURL, uhe.getMessage() );
82                 logger.error("Error", uhe);
83             return(false);
84                 } catch (Exception e) {
85                         logger.error("Error", e);
86                 errorLogger.error(DmaapbcLogMessageEnum.HTTP_CONNECTION_ERROR,  pURL, e.getMessage());
87             return(false);
88         }
89
90         }
91         
92         static String bodyToString( InputStream is ) {
93                 StringBuilder sb = new StringBuilder();
94                 BufferedReader br = new BufferedReader( new InputStreamReader(is));
95                 String line;
96                 try {
97                         while ((line = br.readLine()) != null ) {
98                                 sb.append( line );
99                         }
100                 } catch (IOException ex ) {
101                         errorLogger.error( DmaapbcLogMessageEnum.IO_EXCEPTION + ex.getMessage(),ex);
102                 }
103
104                 return sb.toString();
105         }
106         
107
108
109         public int postAaf( AafObject obj, String pURL ) {
110                 logger.info( "entry: postAaf() to  " + pURL  );
111                 String auth =  "Basic " + Base64.encodeBase64String(aafCred.getBytes());
112                 int rc = -1;
113
114
115                 if ( ! makeConnection( pURL ) ) {
116                         return rc;
117                 };
118
119
120                 byte[] postData = obj.getBytes();
121                 //logger.info( "post fields=" + postData );  //byte isn't very readable
122                 String responsemessage = null;
123                 String responseBody = null;
124
125                 try {
126                         if (auth != null) {
127                                 uc.setRequestProperty("Authorization", auth);
128                 }
129                         uc.setRequestMethod("POST");
130                         uc.setRequestProperty("Content-Type", "application/json");
131                         uc.setRequestProperty( "charset", "utf-8");
132                         uc.setRequestProperty( "Content-Length", Integer.toString( postData.length ));
133                         uc.setUseCaches(false);
134                         uc.setDoOutput(true);
135
136                         SSLContext sc = SSLContext.getInstance("SSL");
137                         sc.init(null, trustAllCerts, new java.security.SecureRandom());
138                         uc.setSSLSocketFactory(sc.getSocketFactory());
139                         OutputStream os = null;
140
141                         
142                         try {
143                  uc.connect();
144                  os = uc.getOutputStream();
145                  os.write( postData );
146
147             } catch (ProtocolException pe) {
148                 logger.error("Error", pe);
149                  // Rcvd error instead of 100-Continue
150                  try {
151                      // work around glitch in Java 1.7.0.21 and likely others
152                      // without this, Java will connect multiple times to the server to run the same request
153                      uc.setDoOutput(false);
154                  } catch (Exception e) {
155                          logger.error("Error", e);
156                  }
157             } catch ( SSLHandshakeException she ) {
158                 logger.error("Error", she);
159                 errorLogger.error( DmaapbcLogMessageEnum.SSL_HANDSHAKE_ERROR, pURL);
160                         } catch ( UnknownHostException uhe ) {
161                                 logger.error("Error", uhe);
162                                 errorLogger.error(DmaapbcLogMessageEnum.UNKNOWN_HOST_EXCEPTION,  pURL, uhe.getMessage() );
163                 rc = 500;
164                 return rc;
165             } catch ( ConnectException ce ) {
166                 logger.error("Error", ce);
167                                 if ( "Yes".equals(unit_test) ) {
168                                         rc = 201;
169                                         return rc;
170                                 }
171                                 errorLogger.error(DmaapbcLogMessageEnum.HTTP_CONNECTION_EXCEPTION,  pURL, ce.getMessage() );
172                 rc = 500;
173                 return rc;
174                         } 
175                         try {
176                                 rc = uc.getResponseCode();
177                         } catch ( SSLHandshakeException she ) {
178                                 logger.error("Error", she);
179                                 errorLogger.error( DmaapbcLogMessageEnum.SSL_HANDSHAKE_ERROR, pURL);
180                 rc = 500;
181                 return rc;
182             }
183                         logger.info( "http response code:" + rc );
184             responsemessage = uc.getResponseMessage();
185             logger.info( "responsemessage=" + responsemessage );
186
187             if (responsemessage == null) {
188                  // work around for glitch in Java 1.7.0.21 and likely others
189                  // When Expect: 100 is set and a non-100 response is received, the response message is not set but the response code is
190                  String h0 = uc.getHeaderField(0);
191                  if (h0 != null) {
192                      int i = h0.indexOf(' ');
193                      int j = h0.indexOf(' ', i + 1);
194                      if (i != -1 && j != -1) {
195                          responsemessage = h0.substring(j + 1);
196                      }
197                  }
198             }
199             if ( rc >= 200 && rc < 300 ) {
200                 responseBody = bodyToString( uc.getInputStream() );
201                 logger.info( "responseBody=" + responseBody );
202             } else {
203                         logger.warn( "Unsuccessful response: " + responsemessage );
204             } 
205             
206                 } catch (Exception e) {
207             logger.error("Unable to read response  ");
208             logger.error("Error", e);
209         }
210                 finally {
211                         try {
212                                 uc.disconnect();
213                         } catch ( Exception e ) {
214                                 logger.error("Error", e);
215                         }
216                 }       
217                 return rc;
218                 
219         }
220         
221         public int delAaf(AafObject obj, String pURL) {
222                 logger.info( "entry: delAaf() to  " + pURL  );
223                 String auth =  "Basic " + Base64.encodeBase64String(aafCred.getBytes());
224                 int rc = -1;
225
226                 
227                 if ( ! makeConnection( pURL ) ) {
228                         return rc;
229                 };
230                 
231
232                 byte[] postData = obj.getBytes();
233                 //logger.info( "post fields=" + postData );  //byte isn't very readable
234                 String responsemessage = null;
235                 String responseBody = null;
236
237                 try {
238                         if (auth != null) {
239                                 uc.setRequestProperty("Authorization", auth);
240                 }
241                         uc.setRequestMethod("DELETE");
242                         uc.setRequestProperty("Content-Type", "application/json");
243                         uc.setRequestProperty( "charset", "utf-8");
244                         uc.setRequestProperty( "Content-Length", Integer.toString( postData.length ));
245                         uc.setUseCaches(false);
246                         uc.setDoOutput(true);
247                         OutputStream os = null;
248
249                         
250                         try {
251                  uc.connect();
252                  os = uc.getOutputStream();
253                  os.write( postData );
254
255             } catch (ProtocolException pe) {
256                 logger.error("Error", pe);
257                  // Rcvd error instead of 100-Continue
258                  try {
259                      // work around glitch in Java 1.7.0.21 and likely others
260                      // without this, Java will connect multiple times to the server to run the same request
261                      uc.setDoOutput(false);
262                  } catch (Exception e) {
263                          logger.error("Error", e);
264                  }
265             } catch ( SSLHandshakeException she ) {
266                 errorLogger.error( DmaapbcLogMessageEnum.SSL_HANDSHAKE_ERROR +"For:- "+pURL,she);
267             }
268                         try {
269                                 rc = uc.getResponseCode();
270                         } catch ( SSLHandshakeException she ) {
271                                 logger.error("Error", she);
272                                 errorLogger.error( DmaapbcLogMessageEnum.SSL_HANDSHAKE_ERROR, pURL);
273                 rc = 500;
274                 return rc;
275             }
276                         logger.info( "http response code:" + rc );
277             responsemessage = uc.getResponseMessage();
278             logger.info( "responsemessage=" + responsemessage );
279
280             if (responsemessage == null) {
281                  // work around for glitch in Java 1.7.0.21 and likely others
282                  // When Expect: 100 is set and a non-100 response is received, the response message is not set but the response code is
283                  String h0 = uc.getHeaderField(0);
284                  if (h0 != null) {
285                      int i = h0.indexOf(' ');
286                      int j = h0.indexOf(' ', i + 1);
287                      if (i != -1 && j != -1) {
288                          responsemessage = h0.substring(j + 1);
289                      }
290                  }
291             }
292             if ( rc >= 200 && rc < 300 ) {
293                 responseBody = bodyToString( uc.getInputStream() );
294                 logger.info( "responseBody=" + responseBody );
295             } else {
296                         logger.warn( "Unsuccessful response: " + responsemessage );
297             } 
298             
299                 } catch (Exception e) {
300             logger.error("Unable to read response  ");
301             logger.error("Error", e);
302         }       
303                 return rc;
304                 
305         }
306
307         private TrustManager[] trustAllCerts = new TrustManager[]{
308                 new X509TrustManager() {
309
310                         @Override
311                         public java.security.cert.X509Certificate[] getAcceptedIssuers()
312                         {
313                                 return null;
314                         }
315                         @Override
316                         public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType)
317                         {
318                                 //No need to implement.
319                         }
320                         @Override
321                         public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType)
322                         {
323                                 //No need to implement.
324                         }
325                 }
326         };
327         
328
329 }