2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6 * Modifications Copyright (C) 2018 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 java.io.BufferedReader;
25 import java.io.IOException;
26 import java.io.InputStream;
27 import java.io.InputStreamReader;
28 import java.io.OutputStream;
29 import java.net.ConnectException;
30 import java.net.HttpURLConnection;
31 import java.net.ProtocolException;
33 import java.net.UnknownHostException;
34 import java.util.Arrays;
36 import javax.net.ssl.HttpsURLConnection;
38 import org.apache.commons.codec.binary.Base64;
39 import org.apache.log4j.Logger;
40 import org.onap.dmaap.dbcapi.aaf.AafDecrypt;
41 import org.onap.dmaap.dbcapi.logging.BaseLoggingClass;
42 import org.onap.dmaap.dbcapi.logging.DmaapbcLogMessageEnum;
43 import org.onap.dmaap.dbcapi.model.ApiError;
44 import org.onap.dmaap.dbcapi.model.MR_Cluster;
45 import org.onap.dmaap.dbcapi.model.Topic;
46 import org.onap.dmaap.dbcapi.util.DmaapConfig;
48 public class MrProvConnection extends BaseLoggingClass{
50 private String provURL;
52 private HttpURLConnection uc;
55 private String topicMgrCred;
56 private boolean useAAF;
58 private String encPwd;
60 public MrProvConnection() {
61 String mechIdProperty = "aaf.TopicMgrUser";
62 String pwdProperty = "aaf.TopicMgrPassword";
63 DmaapConfig p = (DmaapConfig)DmaapConfig.getConfig();
64 user = p.getProperty( mechIdProperty, "noMechId@domain.netset.com" );
65 encPwd = p.getProperty( pwdProperty, "notSet" );
66 useAAF= "true".equalsIgnoreCase(p.getProperty("UseAAF", "false"));
67 topicMgrCred = getCred();
71 private String getCred( ) {
75 AafDecrypt decryptor = new AafDecrypt();
76 pwd = decryptor.decrypt(encPwd);
77 return user + ":" + pwd;
81 public boolean makeTopicConnection( MR_Cluster cluster ) {
82 logger.info( "connect to cluster: " + cluster.getDcaeLocationName());
85 provURL = cluster.getTopicProtocol() + "://" + cluster.getFqdn() + ":" + cluster.getTopicPort() + "/topics/create";
87 if ( cluster.getTopicProtocol().equals( "https" ) ) {
88 return makeSecureConnection( provURL );
90 return makeConnection( provURL );
93 private boolean makeSecureConnection( String pURL ) {
94 logger.info( "makeConnection to " + pURL );
97 URL u = new URL( pURL );
98 uc = (HttpsURLConnection) u.openConnection();
99 uc.setInstanceFollowRedirects(false);
100 logger.info( "open connect to " + pURL );
102 } catch( UnknownHostException uhe ){
103 logger.error( "Caught UnknownHostException for " + pURL);
105 } catch (Exception e) {
106 logger.error("Unexpected error during openConnection of " + pURL );
112 private boolean makeConnection( String pURL ) {
113 logger.info( "makeConnection to " + pURL );
116 URL u = new URL( pURL );
117 uc = (HttpURLConnection) u.openConnection();
118 uc.setInstanceFollowRedirects(false);
119 logger.info( "open connect to " + pURL );
121 } catch( UnknownHostException uhe ){
122 logger.error( "Caught UnknownHostException for " + pURL);
124 } catch (Exception e) {
125 logger.error("Unexpected error during openConnection of " + pURL );
132 static String bodyToString( InputStream is ) {
133 StringBuilder sb = new StringBuilder();
134 BufferedReader br = new BufferedReader( new InputStreamReader(is));
137 while ((line = br.readLine()) != null ) {
140 } catch (IOException ex ) {
141 errorLogger.error( "IOexception:" + ex);
144 return sb.toString();
147 public String doPostTopic( Topic postTopic, ApiError err ) {
148 String auth = "Basic " + Base64.encodeBase64String(topicMgrCred.getBytes());
151 String responsemessage = null;
156 byte[] postData = postTopic.getBytes();
157 logger.info( "post fields=" + Arrays.toString(postData));
159 // when not using AAF, do not attempt Basic Authentication
161 uc.setRequestProperty("Authorization", auth);
162 logger.info( "Authenticating with " + auth );
164 uc.setRequestMethod("POST");
165 uc.setRequestProperty("Content-Type", "application/json");
166 uc.setRequestProperty( "charset", "utf-8");
167 uc.setRequestProperty( "Content-Length", Integer.toString( postData.length ));
168 uc.setUseCaches(false);
169 uc.setDoOutput(true);
170 OutputStream os = null;
175 os = uc.getOutputStream();
176 os.write( postData );
178 } catch (ProtocolException pe) {
179 // Rcvd error instead of 100-Continue
181 // work around glitch in Java 1.7.0.21 and likely others
182 // without this, Java will connect multiple times to the server to run the same request
183 uc.setDoOutput(false);
184 } catch (Exception e) {
186 } catch ( UnknownHostException uhe ) {
187 errorLogger.error( DmaapbcLogMessageEnum.UNKNOWN_HOST_EXCEPTION , "Unknown Host Exception" , provURL );
189 err.setMessage("Unknown Host Exception");
190 err.setFields( uc.getURL().getHost());
191 return new String( "500: " + uhe.getMessage());
192 }catch ( ConnectException ce ) {
193 errorLogger.error( DmaapbcLogMessageEnum.HTTP_CONNECTION_EXCEPTION, provURL, "HTTP Connection Exception" );
195 err.setMessage("HTTP Connection Exception");
196 err.setFields( uc.getURL().getHost());
197 return new String( "500: " + ce.getMessage());
199 rc = uc.getResponseCode();
200 logger.info( "http response code:" + rc );
202 responsemessage = uc.getResponseMessage();
203 logger.info( "responsemessage=" + responsemessage );
204 err.setMessage(responsemessage);
207 if (responsemessage == null) {
208 // work around for glitch in Java 1.7.0.21 and likely others
209 // When Expect: 100 is set and a non-100 response is received, the response message is not set but the response code is
210 String h0 = uc.getHeaderField(0);
212 int i = h0.indexOf(' ');
213 int j = h0.indexOf(' ', i + 1);
214 if (i != -1 && j != -1) {
215 responsemessage = h0.substring(j + 1);
219 if (rc >= 200 && rc < 300 ) {
220 String responseBody = null;
221 responseBody = bodyToString( uc.getInputStream() );
222 logger.info( "responseBody=" + responseBody );
227 } catch (Exception e) {
228 errorLogger.error("Unable to read response " );
234 } catch ( Exception e ) {
235 errorLogger.error("Unable to disconnect");
238 return new String( rc +": " + responsemessage );