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