01d103d0eb85c1fb6dd0097d59f474b352689ea2
[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.service.DmaapService;
44 import org.onap.dmaap.dbcapi.util.DmaapConfig;
45
46
47 public class AafConnection extends BaseLoggingClass {
48
49
50            
51    
52
53         private String aafCred;
54         private String unit_test;
55
56         
57         private HttpsURLConnection uc;
58
59
60         public AafConnection( String cred ) {
61                 aafCred = cred;
62                 DmaapConfig p = (DmaapConfig)DmaapConfig.getConfig();
63         unit_test = p.getProperty( "UnitTest", "No" );
64
65         }
66         
67
68         private boolean makeConnection( String pURL ) {
69         
70                 try {
71                         URL u = new URL( pURL );
72                         uc = (HttpsURLConnection) u.openConnection();
73                         uc.setInstanceFollowRedirects(false);
74                         logger.info( "successful connect to " + pURL );
75                         return(true);
76                 } catch ( UnknownHostException uhe ) {
77                 errorLogger.error(DmaapbcLogMessageEnum.UNKNOWN_HOST_EXCEPTION,  pURL, uhe.getMessage() );
78             uhe.printStackTrace();
79             return(false);
80                 } catch (Exception 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());
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                  // Rcvd error instead of 100-Continue
141                  try {
142                      // work around glitch in Java 1.7.0.21 and likely others
143                      // without this, Java will connect multiple times to the server to run the same request
144                      uc.setDoOutput(false);
145                  } catch (Exception e) {
146                  }
147             } catch ( SSLHandshakeException she ) {
148                 errorLogger.error( DmaapbcLogMessageEnum.SSL_HANDSHAKE_ERROR, pURL);
149                         } catch ( UnknownHostException uhe ) {
150                                 errorLogger.error(DmaapbcLogMessageEnum.UNKNOWN_HOST_EXCEPTION,  pURL, uhe.getMessage() );
151                 rc = 500;
152                 return rc;
153             } catch ( ConnectException ce ) {
154                                 if ( unit_test.equals( "Yes" ) ) {
155                                         rc = 201;
156                                         return rc;
157                                 }
158                                 errorLogger.error(DmaapbcLogMessageEnum.HTTP_CONNECTION_EXCEPTION,  pURL, ce.getMessage() );
159                 rc = 500;
160                 return rc;
161                         } 
162                         try {
163                                 rc = uc.getResponseCode();
164                         } catch ( SSLHandshakeException she ) {
165                                 errorLogger.error( DmaapbcLogMessageEnum.SSL_HANDSHAKE_ERROR, pURL);
166                 rc = 500;
167                 return rc;
168             }
169                         logger.info( "http response code:" + rc );
170             responsemessage = uc.getResponseMessage();
171             logger.info( "responsemessage=" + responsemessage );
172
173             if (responsemessage == null) {
174                  // work around for glitch in Java 1.7.0.21 and likely others
175                  // When Expect: 100 is set and a non-100 response is received, the response message is not set but the response code is
176                  String h0 = uc.getHeaderField(0);
177                  if (h0 != null) {
178                      int i = h0.indexOf(' ');
179                      int j = h0.indexOf(' ', i + 1);
180                      if (i != -1 && j != -1) {
181                          responsemessage = h0.substring(j + 1);
182                      }
183                  }
184             }
185             if ( rc >= 200 && rc < 300 ) {
186                 responseBody = bodyToString( uc.getInputStream() );
187                 logger.info( "responseBody=" + responseBody );
188             } else {
189                         logger.warn( "Unsuccessful response: " + responsemessage );
190             } 
191             
192                 } catch (Exception e) {
193             System.err.println("Unable to read response  " );
194             e.printStackTrace();
195         }
196                 finally {
197                         try {
198                                 uc.disconnect();
199                         } catch ( Exception e ) {}
200                 }
201                 //return responseBody;
202         
203                 return rc;
204                 
205         }
206         
207         public int delAaf(AafObject obj, String pURL) {
208                 logger.info( "entry: delAaf() to  " + pURL  );
209                 String auth =  "Basic " + Base64.encodeBase64String(aafCred.getBytes());
210                 int rc = -1;
211
212                 
213                 if ( ! makeConnection( pURL ) ) {
214                         return rc;
215                 };
216                 
217
218                 byte[] postData = obj.getBytes();
219                 //logger.info( "post fields=" + postData );  //byte isn't very readable
220                 String responsemessage = null;
221                 String responseBody = null;
222
223                 try {
224                         if (auth != null) {
225                                 uc.setRequestProperty("Authorization", auth);
226                 }
227                         uc.setRequestMethod("DELETE");
228                         uc.setRequestProperty("Content-Type", "application/json");
229                         uc.setRequestProperty( "charset", "utf-8");
230                         uc.setRequestProperty( "Content-Length", Integer.toString( postData.length ));
231                         uc.setUseCaches(false);
232                         uc.setDoOutput(true);
233                         OutputStream os = null;
234
235                         
236                         try {
237                  uc.connect();
238                  os = uc.getOutputStream();
239                  os.write( postData );
240
241             } catch (ProtocolException pe) {
242                  // Rcvd error instead of 100-Continue
243                  try {
244                      // work around glitch in Java 1.7.0.21 and likely others
245                      // without this, Java will connect multiple times to the server to run the same request
246                      uc.setDoOutput(false);
247                  } catch (Exception e) {
248                  }
249             } catch ( SSLHandshakeException she ) {
250                 errorLogger.error( DmaapbcLogMessageEnum.SSL_HANDSHAKE_ERROR, pURL);
251             }
252                         try {
253                                 rc = uc.getResponseCode();
254                         } catch ( SSLHandshakeException 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             System.err.println("Unable to read response  " );
284             e.printStackTrace();
285         }
286                 //return responseBody;
287         
288                 return rc;
289                 
290         }
291         
292
293 }