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