2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
7 * Modifications Copyright (C) 2019 IBM.
8 * ================================================================================
9 * Licensed under the Apache License, Version 2.0 (the "License");
10 * you may not use this file except in compliance with the License.
11 * You may obtain a copy of the License at
13 * http://www.apache.org/licenses/LICENSE-2.0
15 * Unless required by applicable law or agreed to in writing, software
16 * distributed under the License is distributed on an "AS IS" BASIS,
17 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18 * See the License for the specific language governing permissions and
19 * limitations under the License.
20 * ============LICENSE_END=========================================================
23 package org.onap.dmaap.dbcapi.client;
25 import java.io.BufferedReader;
26 import java.io.IOException;
27 import java.io.InputStream;
28 import java.io.InputStreamReader;
29 import java.io.OutputStream;
30 import java.net.ProtocolException;
32 import java.net.HttpURLConnection;
34 import javax.net.ssl.HostnameVerifier;
35 import javax.net.ssl.HttpsURLConnection;
36 import javax.net.ssl.SSLException;
37 import javax.net.ssl.SSLSession;
39 import org.apache.commons.codec.binary.Base64;
40 import org.onap.dmaap.dbcapi.logging.BaseLoggingClass;
41 import org.onap.dmaap.dbcapi.model.ApiError;
42 import org.onap.dmaap.dbcapi.model.MR_Cluster;
43 import org.onap.dmaap.dbcapi.util.DmaapConfig;
45 public class MrTopicConnection extends BaseLoggingClass {
46 private String topicURL;
48 private HttpURLConnection uc;
51 private String mmProvCred;
52 private String unit_test;
53 private String authMethod;
54 private boolean hostnameVerify;
56 public MrTopicConnection(String user, String pwd ) {
57 mmProvCred = new String( user + ":" + pwd );
58 DmaapConfig p = (DmaapConfig)DmaapConfig.getConfig();
59 unit_test = p.getProperty( "UnitTest", "No" );
60 authMethod = p.getProperty("MR.authentication", "none");
61 hostnameVerify= "true".equalsIgnoreCase(p.getProperty("MR.hostnameVerify", "true"));
64 public boolean makeTopicConnection( MR_Cluster cluster, String topic, String overrideFqdn ) {
65 String fqdn = overrideFqdn != null ? overrideFqdn : cluster.getFqdn();
66 logger.info( "connect to cluster: " + fqdn + " for topic: " + topic );
69 topicURL = cluster.getTopicProtocol() + "://" + fqdn + ":" + cluster.getTopicPort() + "/events/" + topic ;
71 if ( "https".equals(cluster.getTopicProtocol())) {
72 return makeSecureConnection( topicURL );
74 return makeConnection( topicURL );
78 private boolean makeSecureConnection( String pURL ) {
79 logger.info( "makeConnection to " + pURL );
82 HostnameVerifier hostnameVerifier = new HostnameVerifier() {
84 public boolean verify( String hostname, SSLSession session ) {
91 URL u = new URL( pURL );
92 uc = (HttpsURLConnection) u.openConnection();
93 uc.setInstanceFollowRedirects(false);
94 if ( ! hostnameVerify ) {
95 HttpsURLConnection ucs = (HttpsURLConnection) uc;
96 ucs.setHostnameVerifier(hostnameVerifier);
99 logger.info( "open connection to " + pURL );
101 } catch (Exception e) {
102 logger.error("Unexpected error during openConnection of " + pURL );
103 logger.error("Error", e);;
108 private boolean makeConnection( String pURL ) {
109 logger.info( "makeConnection to " + pURL );
112 URL u = new URL( pURL );
113 uc = (HttpURLConnection) u.openConnection();
114 uc.setInstanceFollowRedirects(false);
115 logger.info( "open connection to " + pURL );
117 } catch (Exception e) {
118 logger.error("Unexpected error during openConnection of " + pURL );
119 logger.error("error", e);
125 static String bodyToString( InputStream is ) {
126 StringBuilder sb = new StringBuilder();
127 BufferedReader br = new BufferedReader( new InputStreamReader(is));
130 while ((line = br.readLine()) != null ) {
133 } catch (IOException ex ) {
134 errorLogger.error( "IOexception:" + ex);
137 return sb.toString();
140 public ApiError doPostMessage( String postMessage ) {
141 ApiError response = new ApiError();
142 String auth = "Basic " + Base64.encodeBase64String(mmProvCred.getBytes());
147 byte[] postData = postMessage.getBytes();
148 logger.info( "post fields=" + postMessage );
149 if ( authMethod.equalsIgnoreCase("basicAuth") ) {
150 uc.setRequestProperty("Authorization", auth);
151 logger.info( "Authenticating with " + auth );
152 } else if ( authMethod.equalsIgnoreCase("cert")) {
153 logger.error( "MR.authentication set for client certificate. Not supported yet.");
155 uc.setRequestMethod("POST");
156 uc.setRequestProperty("Content-Type", "application/json");
157 uc.setRequestProperty( "charset", "utf-8");
158 uc.setRequestProperty( "Content-Length", Integer.toString( postData.length ));
159 uc.setUseCaches(false);
160 uc.setDoOutput(true);
161 OutputStream os = null;
166 os = uc.getOutputStream();
167 os.write( postData );
169 } catch (ProtocolException pe) {
170 // Rcvd error instead of 100-Continue
171 callSetDoOutputOnError();
173 } catch ( SSLException se ) {
174 logger.error("Error", se);
175 response.setCode(500);
176 response.setMessage( se.getMessage());
180 response.setCode( uc.getResponseCode());
181 logger.info( "http response code:" + response.getCode());
182 response.setMessage( uc.getResponseMessage() );
183 logger.info( "response message=" + response.getMessage() );
186 if ( response.getMessage() == null) {
187 // work around for glitch in Java 1.7.0.21 and likely others
188 // When Expect: 100 is set and a non-100 response is received, the response message is not set but the response code is
189 String h0 = uc.getHeaderField(0);
191 int i = h0.indexOf(' ');
192 int j = h0.indexOf(' ', i + 1);
193 if (i != -1 && j != -1) {
194 response.setMessage( h0.substring(j + 1) );
198 if ( response.is2xx() ) {
199 response.setFields( bodyToString( uc.getInputStream() ) );
200 logger.info( "responseBody=" + response.getFields() );
205 } catch (Exception e) {
206 if ( unit_test.equals( "Yes" ) ) {
207 response.setCode(201);
208 response.setMessage( "simulated response");
209 logger.info( "artificial 201 response from doPostMessage because unit_test =" + unit_test );
212 response.setCode(500);
213 response.setMessage( "Unable to read response");
214 logger.warn( response.getMessage() );
215 logger.error("Error", e);
221 } catch ( Exception e ) {
222 logger.error("Error", e);
229 public void callSetDoOutputOnError() {
231 // work around glitch in Java 1.7.0.21 and likely others
232 // without this, Java will connect multiple times to the server to run the same request
233 uc.setDoOutput(false);
234 } catch (Exception e) {
235 logger.error("Error", e);