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