2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6 * ================================================================================
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ============LICENSE_END=========================================================
21 package org.onap.dmaap.dbcapi.client;
23 import java.io.BufferedReader;
24 import java.io.IOException;
25 import java.io.InputStream;
26 import java.io.InputStreamReader;
27 import java.io.OutputStream;
28 import java.net.ConnectException;
29 import java.net.HttpURLConnection;
30 import java.net.ProtocolException;
32 import java.net.UnknownHostException;
33 import java.util.Arrays;
35 import javax.net.ssl.HttpsURLConnection;
37 import org.apache.commons.codec.binary.Base64;
38 import org.apache.log4j.Logger;
39 import org.onap.dmaap.dbcapi.aaf.AafDecrypt;
40 import org.onap.dmaap.dbcapi.aaf.AafService;
41 import org.onap.dmaap.dbcapi.aaf.DecryptionInterface;
42 import org.onap.dmaap.dbcapi.aaf.AafService.ServiceType;
43 import org.onap.dmaap.dbcapi.logging.BaseLoggingClass;
44 import org.onap.dmaap.dbcapi.logging.DmaapbcLogMessageEnum;
45 import org.onap.dmaap.dbcapi.model.ApiError;
46 import org.onap.dmaap.dbcapi.model.MR_Cluster;
47 import org.onap.dmaap.dbcapi.model.Topic;
48 import org.onap.dmaap.dbcapi.util.DmaapConfig;
50 public class MrProvConnection extends BaseLoggingClass{
52 private String provURL;
54 private HttpURLConnection uc;
57 private String topicMgrCred;
58 private boolean useAAF;
60 private String encPwd;
62 public MrProvConnection() {
63 String mechIdProperty = "aaf.TopicMgrUser";
64 String pwdProperty = "aaf.TopicMgrPassword";
65 DmaapConfig p = (DmaapConfig)DmaapConfig.getConfig();
66 user = p.getProperty( mechIdProperty, "noMechId@domain.netset.com" );
67 encPwd = p.getProperty( pwdProperty, "notSet" );
68 useAAF= "true".equalsIgnoreCase(p.getProperty("UseAAF", "false"));
69 topicMgrCred = getCred();
73 private String getCred( ) {
77 AafDecrypt decryptor = new AafDecrypt();
78 pwd = decryptor.decrypt(encPwd);
79 return user + ":" + pwd;
83 public boolean makeTopicConnection( MR_Cluster cluster ) {
84 logger.info( "connect to cluster: " + cluster.getDcaeLocationName());
87 provURL = cluster.getTopicProtocol() + "://" + cluster.getFqdn() + ":" + cluster.getTopicPort() + "/topics/create";
89 if ( cluster.getTopicProtocol().equals( "https" ) ) {
90 return makeSecureConnection( provURL );
92 return makeConnection( provURL );
95 private boolean makeSecureConnection( String pURL ) {
96 logger.info( "makeConnection to " + pURL );
99 URL u = new URL( pURL );
100 uc = (HttpsURLConnection) u.openConnection();
101 uc.setInstanceFollowRedirects(false);
102 logger.info( "open connect to " + pURL );
104 } catch( UnknownHostException uhe ){
105 logger.error( "Caught UnknownHostException for " + pURL);
107 } catch (Exception e) {
108 logger.error("Unexpected error during openConnection of " + pURL );
114 private boolean makeConnection( String pURL ) {
115 logger.info( "makeConnection to " + pURL );
118 URL u = new URL( pURL );
119 uc = (HttpURLConnection) u.openConnection();
120 uc.setInstanceFollowRedirects(false);
121 logger.info( "open connect to " + pURL );
123 } catch( UnknownHostException uhe ){
124 logger.error( "Caught UnknownHostException for " + pURL);
126 } catch (Exception e) {
127 logger.error("Unexpected error during openConnection of " + pURL );
134 static String bodyToString( InputStream is ) {
135 StringBuilder sb = new StringBuilder();
136 BufferedReader br = new BufferedReader( new InputStreamReader(is));
139 while ((line = br.readLine()) != null ) {
142 } catch (IOException ex ) {
143 errorLogger.error( "IOexception:" + ex);
146 return sb.toString();
149 public String doPostTopic( Topic postTopic, ApiError err ) {
150 String auth = "Basic " + Base64.encodeBase64String(topicMgrCred.getBytes());
153 String responsemessage = null;
158 byte[] postData = postTopic.getBytes();
159 logger.info( "post fields=" + Arrays.toString(postData));
161 // when not using AAF, do not attempt Basic Authentication
163 uc.setRequestProperty("Authorization", auth);
164 logger.info( "Authenticating with " + auth );
166 uc.setRequestMethod("POST");
167 uc.setRequestProperty("Content-Type", "application/json");
168 uc.setRequestProperty( "charset", "utf-8");
169 uc.setRequestProperty( "Content-Length", Integer.toString( postData.length ));
170 uc.setUseCaches(false);
171 uc.setDoOutput(true);
172 OutputStream os = null;
177 os = uc.getOutputStream();
178 os.write( postData );
180 } catch (ProtocolException pe) {
181 // Rcvd error instead of 100-Continue
183 // work around glitch in Java 1.7.0.21 and likely others
184 // without this, Java will connect multiple times to the server to run the same request
185 uc.setDoOutput(false);
186 } catch (Exception e) {
188 } catch ( UnknownHostException uhe ) {
189 errorLogger.error( DmaapbcLogMessageEnum.UNKNOWN_HOST_EXCEPTION , "Unknown Host Exception" , provURL );
191 err.setMessage("Unknown Host Exception");
192 err.setFields( uc.getURL().getHost());
193 return new String( "500: " + uhe.getMessage());
194 }catch ( ConnectException ce ) {
195 errorLogger.error( DmaapbcLogMessageEnum.HTTP_CONNECTION_EXCEPTION, provURL, "HTTP Connection Exception" );
197 err.setMessage("HTTP Connection Exception");
198 err.setFields( uc.getURL().getHost());
199 return new String( "500: " + ce.getMessage());
201 rc = uc.getResponseCode();
202 logger.info( "http response code:" + rc );
204 responsemessage = uc.getResponseMessage();
205 logger.info( "responsemessage=" + responsemessage );
206 err.setMessage(responsemessage);
209 if (responsemessage == null) {
210 // work around for glitch in Java 1.7.0.21 and likely others
211 // When Expect: 100 is set and a non-100 response is received, the response message is not set but the response code is
212 String h0 = uc.getHeaderField(0);
214 int i = h0.indexOf(' ');
215 int j = h0.indexOf(' ', i + 1);
216 if (i != -1 && j != -1) {
217 responsemessage = h0.substring(j + 1);
221 if (rc >= 200 && rc < 300 ) {
222 String responseBody = null;
223 responseBody = bodyToString( uc.getInputStream() );
224 logger.info( "responseBody=" + responseBody );
229 } catch (Exception e) {
230 System.err.println("Unable to read response " );
236 } catch ( Exception e ) {}
238 return new String( rc +": " + responsemessage );