2 * ============LICENSE_START=======================================================
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
12 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
22 package org.onap.dmaap.dbcapi.client;
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;
33 import javax.net.ssl.HostnameVerifier;
34 import javax.net.ssl.HttpsURLConnection;
35 import javax.net.ssl.SSLSession;
39 import java.util.Arrays;
41 public class MrProvConnection extends BaseLoggingClass{
43 private String provURL;
45 private HttpURLConnection uc;
48 private String topicMgrCred;
49 private String authMethod;
51 private String encPwd;
52 private String unit_test;
53 private boolean hostnameVerify;
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" );
68 private String getCred( ) {
72 AafDecrypt decryptor = new AafDecrypt();
73 pwd = decryptor.decrypt(encPwd);
74 return user + ":" + pwd;
78 public boolean makeTopicConnection( MR_Cluster cluster ) {
79 logger.info( "connect to cluster: " + cluster.getDcaeLocationName());
82 provURL = cluster.getTopicProtocol() + "://" + cluster.getFqdn() + ":" + cluster.getTopicPort() + "/topics/create";
84 if ( cluster.getTopicProtocol().equals( "https" ) ) {
85 return makeSecureConnection( provURL );
87 return makeConnection( provURL );
90 private boolean makeSecureConnection( String pURL ) {
91 logger.info( "makeConnection to " + pURL );
95 HostnameVerifier hostnameVerifier = new HostnameVerifier() {
97 public boolean verify( String hostname, SSLSession session ) {
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);
109 logger.info( "open secure connect to " + pURL );
111 } catch( UnknownHostException uhe ){
112 logger.error( "Caught UnknownHostException for " + pURL);
114 } catch (Exception e) {
115 logger.error("Unexpected error during openConnection of " + pURL );
116 logger.error("Unexpected error during openConnection of ",e );
121 private boolean makeConnection( String pURL ) {
122 logger.info( "makeConnection to " + pURL );
125 URL u = new URL( pURL );
126 uc = (HttpURLConnection) u.openConnection();
127 uc.setInstanceFollowRedirects(false);
129 logger.info( "open connect to " + pURL );
131 } catch( UnknownHostException uhe ){
132 logger.error( "Caught UnknownHostException for " + pURL);
134 } catch (Exception e) {
135 logger.error("Unexpected error during openConnection of " + pURL );
136 logger.error("Unexpected error during openConnection of ",e );
142 static String bodyToString( InputStream is ) {
143 StringBuilder sb = new StringBuilder();
144 BufferedReader br = new BufferedReader( new InputStreamReader(is));
147 while ((line = br.readLine()) != null ) {
150 } catch (IOException ex ) {
151 errorLogger.error( "IOexception:" + ex);
154 return sb.toString();
157 public String doPostTopic( Topic postTopic, ApiError err ) {
158 String auth = "Basic " + Base64.encodeBase64String(topicMgrCred.getBytes());
161 String responsemessage = null;
166 byte[] postData = postTopic.getBytes();
167 logger.info( "post fields=" + Arrays.toString(postData));
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.");
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;
186 os = uc.getOutputStream();
187 os.write( postData );
189 } catch (ProtocolException pe) {
190 // Rcvd error instead of 100-Continue
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) {
197 } catch ( UnknownHostException uhe ) {
198 errorLogger.error( DmaapbcLogMessageEnum.UNKNOWN_HOST_EXCEPTION , "Unknown Host Exception" , provURL );
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" ) ) {
206 err.setMessage( "simulated response");
207 logger.info( "artificial 200 response from doPostMessage because unit_test =" + unit_test );
209 errorLogger.error( DmaapbcLogMessageEnum.HTTP_CONNECTION_EXCEPTION, provURL, "HTTP Connection Exception" );
211 err.setMessage("HTTP Connection Exception");
212 err.setFields( uc.getURL().getHost());
213 return new String( "500: " + ce.getMessage());
216 rc = uc.getResponseCode();
217 logger.info( "http response code:" + rc );
219 responsemessage = uc.getResponseMessage();
220 logger.info( "responsemessage=" + responsemessage );
221 err.setMessage(responsemessage);
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);
229 int i = h0.indexOf(' ');
230 int j = h0.indexOf(' ', i + 1);
231 if (i != -1 && j != -1) {
232 responsemessage = h0.substring(j + 1);
236 if (rc >= 200 && rc < 300 ) {
237 String responseBody = null;
238 responseBody = bodyToString( uc.getInputStream() );
239 logger.info( "responseBody=" + responseBody );
244 } catch (Exception e) {
245 errorLogger.error("Unable to read response: " + e.getMessage() );
251 } catch ( Exception e ) {
252 errorLogger.error("Unable to disconnect");
255 return new String( rc +": " + responsemessage );