Manage SSL connection to MR
[dmaap/dbcapi.git] / 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 boolean hostnameVerify;
53     
54     public MrProvConnection() {
55         String mechIdProperty = "aaf.TopicMgrUser";
56         String pwdProperty = "aaf.TopicMgrPassword";
57         DmaapConfig p = (DmaapConfig)DmaapConfig.getConfig();
58         user = p.getProperty( mechIdProperty, "noMechId@domain.netset.com" );
59         encPwd = p.getProperty( pwdProperty, "notSet" );
60         authMethod = p.getProperty("MR.authentication", "none");
61         topicMgrCred =  getCred();
62         hostnameVerify= "true".equalsIgnoreCase(p.getProperty("MR.hostnameVerify", "true"));
63         
64     }
65     
66     private String getCred( ) {
67
68
69         String pwd = "";
70         AafDecrypt decryptor = new AafDecrypt();    
71         pwd = decryptor.decrypt(encPwd);
72         return user + ":" + pwd;    
73     }
74     
75     
76     public boolean makeTopicConnection( MR_Cluster cluster ) {
77         logger.info( "connect to cluster: " + cluster.getDcaeLocationName());
78     
79
80         provURL = cluster.getTopicProtocol() + "://" + cluster.getFqdn() + ":" + cluster.getTopicPort() + "/topics/create";
81
82         if ( cluster.getTopicProtocol().equals( "https" ) ) {
83             return makeSecureConnection( provURL );
84         }
85         return makeConnection( provURL );
86     }
87
88     private boolean makeSecureConnection( String pURL ) {
89         logger.info( "makeConnection to " + pURL );
90     
91         try {
92         
93                         HostnameVerifier hostnameVerifier = new HostnameVerifier() {
94                                 @Override
95                                 public boolean verify( String hostname, SSLSession session ) {
96                                         return true;
97                                 }
98                         
99                         };
100             URL u = new URL( pURL );
101             uc = (HttpsURLConnection) u.openConnection();
102             uc.setInstanceFollowRedirects(false);
103             if ( ! hostnameVerify ) {
104                                 HttpsURLConnection ucs = (HttpsURLConnection) uc;
105                                 ucs.setHostnameVerifier(hostnameVerifier);
106                         }
107             logger.info( "open secure connect to " + pURL );
108             return(true);
109         } catch( UnknownHostException uhe ){
110             logger.error( "Caught UnknownHostException for " + pURL);
111             return(false);
112         } catch (Exception e) {
113             logger.error("Unexpected error during openConnection of " + pURL );
114             logger.error("Unexpected error during openConnection of ",e );
115             return(false);
116         } 
117
118     }
119     private boolean makeConnection( String pURL ) {
120         logger.info( "makeConnection to " + pURL );
121     
122         try {
123             URL u = new URL( pURL );
124             uc = (HttpURLConnection) u.openConnection();
125             uc.setInstanceFollowRedirects(false);                       
126
127             logger.info( "open connect to " + pURL );
128             return(true);
129         } catch( UnknownHostException uhe ){
130             logger.error( "Caught UnknownHostException for " + pURL);
131             return(false);
132         } catch (Exception e) {
133             logger.error("Unexpected error during openConnection of " + pURL );
134             logger.error("Unexpected error during openConnection of ",e );
135             return(false);
136         } 
137
138     }
139     
140     static String bodyToString( InputStream is ) {
141         StringBuilder sb = new StringBuilder();
142         BufferedReader br = new BufferedReader( new InputStreamReader(is));
143         String line;
144         try {
145             while ((line = br.readLine()) != null ) {
146                 sb.append( line );
147             }
148         } catch (IOException ex ) {
149             errorLogger.error( "IOexception:" + ex);
150         }
151             
152         return sb.toString();
153     }
154     
155     public String doPostTopic( Topic postTopic, ApiError err ) {
156         String auth =  "Basic " + Base64.encodeBase64String(topicMgrCred.getBytes());
157
158
159         String responsemessage = null;
160         int rc = -1;
161
162
163         try {
164             byte[] postData = postTopic.getBytes();
165             logger.info( "post fields=" + Arrays.toString(postData));
166             
167                         if ( authMethod.equalsIgnoreCase("basicAuth") ) {
168                                 uc.setRequestProperty("Authorization", auth);
169                                 logger.info( "Authenticating with " + auth );
170                         } else if ( authMethod.equalsIgnoreCase("cert")) {
171                                 logger.error( "MR.authentication set for client certificate.  Not supported yet.");
172                         }
173             uc.setRequestMethod("POST");
174             uc.setRequestProperty("Content-Type", "application/json");
175             uc.setRequestProperty( "charset", "utf-8");
176             uc.setRequestProperty( "Content-Length", Integer.toString( postData.length ));
177             uc.setUseCaches(false);
178             uc.setDoOutput(true);
179             OutputStream os = null;
180
181             
182             try {
183                  uc.connect();
184                  os = uc.getOutputStream();
185                  os.write( postData );
186
187             } catch (ProtocolException pe) {
188                  // Rcvd error instead of 100-Continue
189                  try {
190                      // work around glitch in Java 1.7.0.21 and likely others
191                      // without this, Java will connect multiple times to the server to run the same request
192                      uc.setDoOutput(false);
193                  } catch (Exception e) {
194                  }
195             } catch ( UnknownHostException uhe ) {
196                 errorLogger.error( DmaapbcLogMessageEnum.UNKNOWN_HOST_EXCEPTION , "Unknown Host Exception" , provURL );
197                 err.setCode(500);
198                 err.setMessage("Unknown Host Exception");
199                 err.setFields( uc.getURL().getHost());
200                 return new String( "500: " + uhe.getMessage());
201             }catch ( ConnectException ce ) {
202                 errorLogger.error( DmaapbcLogMessageEnum.HTTP_CONNECTION_EXCEPTION, provURL, "HTTP Connection Exception"  );
203                 err.setCode(500);
204                 err.setMessage("HTTP Connection Exception");
205                 err.setFields( uc.getURL().getHost());
206                 return new String( "500: " + ce.getMessage());
207             }
208             rc = uc.getResponseCode();
209             logger.info( "http response code:" + rc );
210             err.setCode(rc);
211             responsemessage = uc.getResponseMessage();
212             logger.info( "responsemessage=" + responsemessage );
213             err.setMessage(responsemessage);
214
215
216             if (responsemessage == null) {
217                  // work around for glitch in Java 1.7.0.21 and likely others
218                  // When Expect: 100 is set and a non-100 response is received, the response message is not set but the response code is
219                  String h0 = uc.getHeaderField(0);
220                  if (h0 != null) {
221                      int i = h0.indexOf(' ');
222                      int j = h0.indexOf(' ', i + 1);
223                      if (i != -1 && j != -1) {
224                          responsemessage = h0.substring(j + 1);
225                      }
226                  }
227             }
228             if (rc >= 200 && rc < 300 ) {
229                 String responseBody = null;
230                  responseBody = bodyToString( uc.getInputStream() );
231                 logger.info( "responseBody=" + responseBody );
232                 return responseBody;
233
234             } 
235             
236         } catch (Exception e) {
237             errorLogger.error("Unable to read response:  " + e.getMessage() );
238            
239         }
240         finally {
241             try {
242                 uc.disconnect();
243             } catch ( Exception e ) {
244                 errorLogger.error("Unable to disconnect");
245             }
246         }
247         return new String( rc +": " + responsemessage );
248
249     }
250     
251
252
253         
254 }