a92dbc7e63a4a6d56c6aeadee293be2a12304c44
[dmaap/dbcapi.git] / src / main / java / org / onap / dmaap / dbcapi / client / MrTopicConnection.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.client;
24
25 import java.io.BufferedReader;
26 import java.io.IOException;
27 import java.io.InputStream;
28 import java.io.InputStreamReader;
29 import java.io.OutputStream;
30 import java.net.ProtocolException;
31 import java.net.URL;
32 import java.net.HttpURLConnection;
33
34 import javax.net.ssl.HttpsURLConnection;
35 import javax.net.ssl.SSLException;
36
37 import org.apache.commons.codec.binary.Base64;
38 import org.onap.dmaap.dbcapi.logging.BaseLoggingClass;
39 import org.onap.dmaap.dbcapi.model.ApiError;
40 import org.onap.dmaap.dbcapi.model.MR_Cluster;
41 import org.onap.dmaap.dbcapi.util.DmaapConfig;
42
43 public class MrTopicConnection extends BaseLoggingClass  {
44         private String topicURL;
45         
46         private HttpURLConnection uc;
47
48         
49         private  String mmProvCred; 
50         private String unit_test;
51         private boolean useAAF;
52
53
54         public MrTopicConnection(String user, String pwd ) {
55                 mmProvCred = new String( user + ":" + pwd );
56                 DmaapConfig p = (DmaapConfig)DmaapConfig.getConfig();
57         unit_test = p.getProperty( "UnitTest", "No" );
58         useAAF= "true".equalsIgnoreCase(p.getProperty("UseAAF", "false"));
59         }
60         
61         public boolean makeTopicConnection( MR_Cluster cluster, String topic, String overrideFqdn ) {
62                 String fqdn = overrideFqdn != null ? overrideFqdn : cluster.getFqdn();
63                 logger.info( "connect to cluster: " + fqdn + " for topic: " + topic );
64         
65
66                 topicURL = cluster.getTopicProtocol() + "://" + fqdn + ":" + cluster.getTopicPort() + "/events/" + topic ;
67
68                 if ( "https".equals(cluster.getTopicProtocol())) {
69                         return makeSecureConnection( topicURL );
70                 }
71                 return makeConnection( topicURL );
72         }
73
74         private boolean makeSecureConnection( String pURL ) {
75                 logger.info( "makeConnection to " + pURL );
76         
77                 try {
78                         URL u = new URL( pURL );
79                         uc = (HttpsURLConnection) u.openConnection();
80                         uc.setInstanceFollowRedirects(false);
81                         logger.info( "open connection to " + pURL );
82                         return(true);
83                 } catch (Exception e) {
84             logger.error("Unexpected error during openConnection of " + pURL );
85             logger.error("Error", e);;
86             return(false);
87         }
88
89         }
90         private boolean makeConnection( String pURL ) {
91                 logger.info( "makeConnection to " + pURL );
92         
93                 try {
94                         URL u = new URL( pURL );
95                         uc = (HttpURLConnection) u.openConnection();
96                         uc.setInstanceFollowRedirects(false);
97                         logger.info( "open connection to " + pURL );
98                         return(true);
99                 } catch (Exception e) {
100             logger.error("Unexpected error during openConnection of " + pURL );
101             logger.error("error", e);
102             return(false);
103         }
104
105         }
106         
107         static String bodyToString( InputStream is ) {
108                 StringBuilder sb = new StringBuilder();
109                 BufferedReader br = new BufferedReader( new InputStreamReader(is));
110                 String line;
111                 try {
112                         while ((line = br.readLine()) != null ) {
113                                 sb.append( line );
114                         }
115                 } catch (IOException ex ) {
116                         errorLogger.error( "IOexception:" + ex);
117                 }
118                         
119                 return sb.toString();
120         }
121         
122         public ApiError doPostMessage( String postMessage ) {
123                 ApiError response = new ApiError();
124                 String auth =  "Basic " + Base64.encodeBase64String(mmProvCred.getBytes());
125
126
127
128                 try {
129                         byte[] postData = postMessage.getBytes();
130                         logger.info( "post fields=" + postMessage );
131                         if ( useAAF ) {
132                                 uc.setRequestProperty("Authorization", auth);
133                                 logger.info( "Authenticating with " + auth );
134                         }
135                         uc.setRequestMethod("POST");
136                         uc.setRequestProperty("Content-Type", "application/json");
137                         uc.setRequestProperty( "charset", "utf-8");
138                         uc.setRequestProperty( "Content-Length", Integer.toString( postData.length ));
139                         uc.setUseCaches(false);
140                         uc.setDoOutput(true);
141                         OutputStream os = null;
142
143                         
144                         try {
145                  uc.connect();
146                  os = uc.getOutputStream();
147                  os.write( postData );
148
149             } catch (ProtocolException pe) {
150                  // Rcvd error instead of 100-Continue
151                 callSetDoOutputOnError();
152                  
153             }  catch ( SSLException se ) {
154                 logger.error("Error", se);
155                         response.setCode(500);
156                         response.setMessage( se.getMessage());
157                         return response;
158                 
159             }
160                         response.setCode( uc.getResponseCode());
161                         logger.info( "http response code:" + response.getCode());
162             response.setMessage( uc.getResponseMessage() ); 
163             logger.info( "response message=" + response.getMessage() );
164
165
166             if ( response.getMessage() == null) {
167                  // work around for glitch in Java 1.7.0.21 and likely others
168                  // When Expect: 100 is set and a non-100 response is received, the response message is not set but the response code is
169                  String h0 = uc.getHeaderField(0);
170                  if (h0 != null) {
171                      int i = h0.indexOf(' ');
172                      int j = h0.indexOf(' ', i + 1);
173                      if (i != -1 && j != -1) {
174                          response.setMessage( h0.substring(j + 1) );
175                      }
176                  }
177             }
178             if ( response.is2xx() ) {
179                         response.setFields( bodyToString( uc.getInputStream() ) );
180                         logger.info( "responseBody=" + response.getFields() );
181                         return response;
182
183             } 
184             
185                 } catch (Exception e) {
186                 if ( unit_test.equals( "Yes" ) ) {
187                                 response.setCode(200);
188                                 response.setMessage( "simulated response");
189                                 logger.info( "artificial 200 response from doPostMessage because unit_test =" + unit_test );
190                 } else {
191
192                                 response.setCode(500);
193                                 response.setMessage( "Unable to read response");
194                                 logger.warn( response.getMessage() );
195                 logger.error("Error", e);
196                         }
197         }
198                 finally {
199                         try {
200                                 uc.disconnect();
201                         } catch ( Exception e ) {
202                                 logger.error("Error", e);
203                         }
204                 }
205                 return response;
206
207         }
208         
209         public void callSetDoOutputOnError() {
210                 try {
211             // work around glitch in Java 1.7.0.21 and likely others
212             // without this, Java will connect multiple times to the server to run the same request
213             uc.setDoOutput(false);
214         } catch (Exception e) {
215                 logger.error("Error", e);
216         }
217         }
218
219 }