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