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 ) {
80 logger.info( "connect to cluster: " + cluster.getDcaeLocationName());
83 provURL = cluster.getTopicProtocol() + "://" + cluster.getFqdn() + ":" + cluster.getTopicPort() + "/topics/create";
85 if ( cluster.getTopicProtocol().equals( "https" ) ) {
86 rc = makeSecureConnection( provURL );
88 rc = makeConnection( provURL );
90 if ( rc && unit_test.equals( "Yes" ) ) {
91 // set timeouts low so we don't hold up unit tests in build process
93 uc.setConnectTimeout(5);
99 private boolean makeSecureConnection( String pURL ) {
100 logger.info( "makeConnection to " + pURL );
104 HostnameVerifier hostnameVerifier = new HostnameVerifier() {
106 public boolean verify( String hostname, SSLSession session ) {
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);
118 logger.info( "open secure connect to " + pURL );
120 } catch( UnknownHostException uhe ){
121 logger.error( "Caught UnknownHostException for " + pURL);
123 } catch (Exception e) {
124 logger.error("Unexpected error during openConnection of " + pURL );
125 logger.error("Unexpected error during openConnection of ",e );
130 private boolean makeConnection( String pURL ) {
131 logger.info( "makeConnection to " + pURL );
134 URL u = new URL( pURL );
135 uc = (HttpURLConnection) u.openConnection();
136 uc.setInstanceFollowRedirects(false);
138 logger.info( "open connect to " + pURL );
140 } catch( UnknownHostException uhe ){
141 logger.error( "Caught UnknownHostException for " + pURL);
143 } catch (Exception e) {
144 logger.error("Unexpected error during openConnection of " + pURL );
145 logger.error("Unexpected error during openConnection of ",e );
151 static String bodyToString( InputStream is ) {
152 StringBuilder sb = new StringBuilder();
153 BufferedReader br = new BufferedReader( new InputStreamReader(is));
156 while ((line = br.readLine()) != null ) {
159 } catch (IOException ex ) {
160 errorLogger.error( "IOexception:" + ex);
163 return sb.toString();
166 public String doPostTopic( Topic postTopic, ApiError err ) {
167 String auth = "Basic " + Base64.encodeBase64String(topicMgrCred.getBytes());
170 String responsemessage = null;
175 byte[] postData = postTopic.getBytes();
176 logger.info( "post fields=" + Arrays.toString(postData));
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.");
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;
195 os = uc.getOutputStream();
196 os.write( postData );
198 } catch (ProtocolException pe) {
199 // Rcvd error instead of 100-Continue
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) {
206 } catch ( UnknownHostException uhe ) {
207 errorLogger.error( DmaapbcLogMessageEnum.UNKNOWN_HOST_EXCEPTION , "Unknown Host Exception" , provURL );
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" ) ) {
215 err.setMessage( "simulated response");
216 logger.info( "artificial 200 response from doPostMessage because unit_test =" + unit_test );
218 errorLogger.error( DmaapbcLogMessageEnum.HTTP_CONNECTION_EXCEPTION, provURL, "HTTP Connection Exception" );
220 err.setMessage("HTTP Connection Exception");
221 err.setFields( uc.getURL().getHost());
222 return new String( "500: " + ce.getMessage());
225 rc = uc.getResponseCode();
226 logger.info( "http response code:" + rc );
228 responsemessage = uc.getResponseMessage();
229 logger.info( "responsemessage=" + responsemessage );
230 err.setMessage(responsemessage);
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);
238 int i = h0.indexOf(' ');
239 int j = h0.indexOf(' ', i + 1);
240 if (i != -1 && j != -1) {
241 responsemessage = h0.substring(j + 1);
245 if (rc >= 200 && rc < 300 ) {
246 String responseBody = null;
247 responseBody = bodyToString( uc.getInputStream() );
248 logger.info( "responseBody=" + responseBody );
253 } catch (Exception e) {
254 errorLogger.error("Unable to read response: " + e.getMessage() );
260 } catch ( Exception e ) {
261 errorLogger.error("Unable to disconnect");
264 return new String( rc +": " + responsemessage );