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