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