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 boolean hostnameVerify;
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"));
66 private String getCred( ) {
70 AafDecrypt decryptor = new AafDecrypt();
71 pwd = decryptor.decrypt(encPwd);
72 return user + ":" + pwd;
76 public boolean makeTopicConnection( MR_Cluster cluster ) {
77 logger.info( "connect to cluster: " + cluster.getDcaeLocationName());
80 provURL = cluster.getTopicProtocol() + "://" + cluster.getFqdn() + ":" + cluster.getTopicPort() + "/topics/create";
82 if ( cluster.getTopicProtocol().equals( "https" ) ) {
83 return makeSecureConnection( provURL );
85 return makeConnection( provURL );
88 private boolean makeSecureConnection( String pURL ) {
89 logger.info( "makeConnection to " + pURL );
93 HostnameVerifier hostnameVerifier = new HostnameVerifier() {
95 public boolean verify( String hostname, SSLSession session ) {
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);
107 logger.info( "open secure connect to " + pURL );
109 } catch( UnknownHostException uhe ){
110 logger.error( "Caught UnknownHostException for " + pURL);
112 } catch (Exception e) {
113 logger.error("Unexpected error during openConnection of " + pURL );
114 logger.error("Unexpected error during openConnection of ",e );
119 private boolean makeConnection( String pURL ) {
120 logger.info( "makeConnection to " + pURL );
123 URL u = new URL( pURL );
124 uc = (HttpURLConnection) u.openConnection();
125 uc.setInstanceFollowRedirects(false);
127 logger.info( "open connect to " + pURL );
129 } catch( UnknownHostException uhe ){
130 logger.error( "Caught UnknownHostException for " + pURL);
132 } catch (Exception e) {
133 logger.error("Unexpected error during openConnection of " + pURL );
134 logger.error("Unexpected error during openConnection of ",e );
140 static String bodyToString( InputStream is ) {
141 StringBuilder sb = new StringBuilder();
142 BufferedReader br = new BufferedReader( new InputStreamReader(is));
145 while ((line = br.readLine()) != null ) {
148 } catch (IOException ex ) {
149 errorLogger.error( "IOexception:" + ex);
152 return sb.toString();
155 public String doPostTopic( Topic postTopic, ApiError err ) {
156 String auth = "Basic " + Base64.encodeBase64String(topicMgrCred.getBytes());
159 String responsemessage = null;
164 byte[] postData = postTopic.getBytes();
165 logger.info( "post fields=" + Arrays.toString(postData));
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.");
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;
184 os = uc.getOutputStream();
185 os.write( postData );
187 } catch (ProtocolException pe) {
188 // Rcvd error instead of 100-Continue
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) {
195 } catch ( UnknownHostException uhe ) {
196 errorLogger.error( DmaapbcLogMessageEnum.UNKNOWN_HOST_EXCEPTION , "Unknown Host Exception" , provURL );
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" );
204 err.setMessage("HTTP Connection Exception");
205 err.setFields( uc.getURL().getHost());
206 return new String( "500: " + ce.getMessage());
208 rc = uc.getResponseCode();
209 logger.info( "http response code:" + rc );
211 responsemessage = uc.getResponseMessage();
212 logger.info( "responsemessage=" + responsemessage );
213 err.setMessage(responsemessage);
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);
221 int i = h0.indexOf(' ');
222 int j = h0.indexOf(' ', i + 1);
223 if (i != -1 && j != -1) {
224 responsemessage = h0.substring(j + 1);
228 if (rc >= 200 && rc < 300 ) {
229 String responseBody = null;
230 responseBody = bodyToString( uc.getInputStream() );
231 logger.info( "responseBody=" + responseBody );
236 } catch (Exception e) {
237 errorLogger.error("Unable to read response: " + e.getMessage() );
243 } catch ( Exception e ) {
244 errorLogger.error("Unable to disconnect");
247 return new String( rc +": " + responsemessage );