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