[DMAAP-BC] Consolidate bus controller repos
[dmaap/buscontroller.git] / dmaap-bc / src / main / java / org / onap / dmaap / dbcapi / client / MrProvConnection.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * org.onap.dmaap
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * Modifications Copyright (C) 2019 IBM.
7  * ================================================================================
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  * 
12  *      http://www.apache.org/licenses/LICENSE-2.0
13  * 
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  * ============LICENSE_END=========================================================
20  */
21
22 package org.onap.dmaap.dbcapi.client;
23
24 import org.apache.commons.codec.binary.Base64;
25 import org.onap.dmaap.dbcapi.aaf.AafDecrypt;
26 import org.onap.dmaap.dbcapi.logging.BaseLoggingClass;
27 import org.onap.dmaap.dbcapi.logging.DmaapbcLogMessageEnum;
28 import org.onap.dmaap.dbcapi.model.ApiError;
29 import org.onap.dmaap.dbcapi.model.MR_Cluster;
30 import org.onap.dmaap.dbcapi.model.Topic;
31 import org.onap.dmaap.dbcapi.util.DmaapConfig;
32
33 import javax.net.ssl.HostnameVerifier;
34 import javax.net.ssl.HttpsURLConnection;
35 import javax.net.ssl.SSLSession;
36
37 import java.io.*;
38 import java.net.*;
39 import java.util.Arrays;
40
41 public class MrProvConnection extends BaseLoggingClass{
42         
43     private String provURL;
44     
45     private HttpURLConnection uc;
46
47     
48     private String topicMgrCred;
49     private String authMethod;
50     private    String    user;
51     private    String    encPwd;
52     private     String  unit_test;
53     private boolean hostnameVerify;
54     
55     public MrProvConnection() {
56         String mechIdProperty = "aaf.TopicMgrUser";
57         String pwdProperty = "aaf.TopicMgrPassword";
58         DmaapConfig p = (DmaapConfig)DmaapConfig.getConfig();
59         user = p.getProperty( mechIdProperty, "noMechId@domain.netset.com" );
60         encPwd = p.getProperty( pwdProperty, "notSet" );
61         authMethod = p.getProperty("MR.authentication", "none");
62         topicMgrCred =  getCred();
63         hostnameVerify= "true".equalsIgnoreCase(p.getProperty("MR.hostnameVerify", "true"));
64         unit_test = p.getProperty( "UnitTest", "No" );
65         
66     }
67     
68     private String getCred( ) {
69
70
71         String pwd = "";
72         AafDecrypt decryptor = new AafDecrypt();    
73         pwd = decryptor.decrypt(encPwd);
74         return user + ":" + pwd;    
75     }
76     
77     
78     public boolean makeTopicConnection( MR_Cluster cluster ) {
79         boolean rc = false;
80         logger.info( "connect to cluster: " + cluster.getDcaeLocationName());
81         
82
83         provURL = cluster.getTopicProtocol() + "://" + cluster.getFqdn() + ":" + cluster.getTopicPort() + "/topics/create";
84
85         if ( cluster.getTopicProtocol().equals( "https" ) ) {
86             rc = makeSecureConnection( provURL );
87         } else {
88                 rc = makeConnection( provURL );
89         }
90         if ( rc  && unit_test.equals( "Yes" ) ) {
91                 // set timeouts low so we don't hold up unit tests in build process
92             uc.setReadTimeout(5);
93             uc.setConnectTimeout(5);            
94         }
95         return rc;
96         
97     }
98
99     private boolean makeSecureConnection( String pURL ) {
100         logger.info( "makeConnection to " + pURL );
101     
102         try {
103         
104                         HostnameVerifier hostnameVerifier = new HostnameVerifier() {
105                                 @Override
106                                 public boolean verify( String hostname, SSLSession session ) {
107                                         return true;
108                                 }
109                         
110                         };
111             URL u = new URL( pURL );
112             uc = (HttpsURLConnection) u.openConnection();
113             uc.setInstanceFollowRedirects(false);
114             if ( ! hostnameVerify ) {
115                                 HttpsURLConnection ucs = (HttpsURLConnection) uc;
116                                 ucs.setHostnameVerifier(hostnameVerifier);
117                         }
118             logger.info( "open secure connect to " + pURL );
119             return(true);
120         } catch( UnknownHostException uhe ){
121             logger.error( "Caught UnknownHostException for " + pURL);
122             return(false);
123         } catch (Exception e) {
124             logger.error("Unexpected error during openConnection of " + pURL );
125             logger.error("Unexpected error during openConnection of ",e );
126             return(false);
127         } 
128
129     }
130     private boolean makeConnection( String pURL ) {
131         logger.info( "makeConnection to " + pURL );
132     
133         try {
134             URL u = new URL( pURL );
135             uc = (HttpURLConnection) u.openConnection();
136             uc.setInstanceFollowRedirects(false);                       
137
138             logger.info( "open connect to " + pURL );
139             return(true);
140         } catch( UnknownHostException uhe ){
141             logger.error( "Caught UnknownHostException for " + pURL);
142             return(false);
143         } catch (Exception e) {
144             logger.error("Unexpected error during openConnection of " + pURL );
145             logger.error("Unexpected error during openConnection of ",e );
146             return(false);
147         } 
148
149     }
150     
151     static String bodyToString( InputStream is ) {
152         StringBuilder sb = new StringBuilder();
153         BufferedReader br = new BufferedReader( new InputStreamReader(is));
154         String line;
155         try {
156             while ((line = br.readLine()) != null ) {
157                 sb.append( line );
158             }
159         } catch (IOException ex ) {
160             errorLogger.error( "IOexception:" + ex);
161         }
162             
163         return sb.toString();
164     }
165     
166     public String doPostTopic( Topic postTopic, ApiError err ) {
167         String auth =  "Basic " + Base64.encodeBase64String(topicMgrCred.getBytes());
168
169
170         String responsemessage = null;
171         int rc = -1;
172
173
174         try {
175             byte[] postData = postTopic.getBytes();
176             logger.info( "post fields=" + Arrays.toString(postData));
177             
178                         if ( authMethod.equalsIgnoreCase("basicAuth") ) {
179                                 uc.setRequestProperty("Authorization", auth);
180                                 logger.info( "Authenticating with " + auth );
181                         } else if ( authMethod.equalsIgnoreCase("cert")) {
182                                 logger.error( "MR.authentication set for client certificate.  Not supported yet.");
183                         }
184             uc.setRequestMethod("POST");
185             uc.setRequestProperty("Content-Type", "application/json");
186             uc.setRequestProperty( "charset", "utf-8");
187             uc.setRequestProperty( "Content-Length", Integer.toString( postData.length ));
188             uc.setUseCaches(false);
189             uc.setDoOutput(true);
190             OutputStream os = null;
191
192             
193             try {
194                  uc.connect();
195                  os = uc.getOutputStream();
196                  os.write( postData );
197
198             } catch (ProtocolException pe) {
199                  // Rcvd error instead of 100-Continue
200                  try {
201                      // work around glitch in Java 1.7.0.21 and likely others
202                      // without this, Java will connect multiple times to the server to run the same request
203                      uc.setDoOutput(false);
204                  } catch (Exception e) {
205                  }
206             } catch ( UnknownHostException uhe ) {
207                 errorLogger.error( DmaapbcLogMessageEnum.UNKNOWN_HOST_EXCEPTION , "Unknown Host Exception" , provURL );
208                 err.setCode(500);
209                 err.setMessage("Unknown Host Exception");
210                 err.setFields( uc.getURL().getHost());
211                 return new String( "500: " + uhe.getMessage());
212             }catch ( ConnectException ce ) {
213                 if ( unit_test.equals( "Yes" ) ) {
214                                 err.setCode(200);
215                                 err.setMessage( "simulated response");
216                                 logger.info( "artificial 200 response from doPostMessage because unit_test =" + unit_test );
217                 } else { 
218                         errorLogger.error( DmaapbcLogMessageEnum.HTTP_CONNECTION_EXCEPTION, provURL, "HTTP Connection Exception"  );
219                         err.setCode(500);
220                         err.setMessage("HTTP Connection Exception");
221                         err.setFields( uc.getURL().getHost());
222                 return new String( "500: " + ce.getMessage());
223                 }
224             }
225             rc = uc.getResponseCode();
226             logger.info( "http response code:" + rc );
227             err.setCode(rc);
228             responsemessage = uc.getResponseMessage();
229             logger.info( "responsemessage=" + responsemessage );
230             err.setMessage(responsemessage);
231
232
233             if (responsemessage == null) {
234                  // work around for glitch in Java 1.7.0.21 and likely others
235                  // When Expect: 100 is set and a non-100 response is received, the response message is not set but the response code is
236                  String h0 = uc.getHeaderField(0);
237                  if (h0 != null) {
238                      int i = h0.indexOf(' ');
239                      int j = h0.indexOf(' ', i + 1);
240                      if (i != -1 && j != -1) {
241                          responsemessage = h0.substring(j + 1);
242                      }
243                  }
244             }
245             if (rc >= 200 && rc < 300 ) {
246                 String responseBody = null;
247                  responseBody = bodyToString( uc.getInputStream() );
248                 logger.info( "responseBody=" + responseBody );
249                 return responseBody;
250
251             } 
252             
253         } catch (Exception e) {
254             errorLogger.error("Unable to read response:  " + e.getMessage() );
255            
256         }
257         finally {
258             try {
259                 uc.disconnect();
260             } catch ( Exception e ) {
261                 errorLogger.error("Unable to disconnect");
262             }
263         }
264         return new String( rc +": " + responsemessage );
265
266     }
267     
268
269
270         
271 }