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;
34 import javax.net.ssl.HttpsURLConnection;
36 import org.apache.commons.codec.binary.Base64;
37 import org.apache.log4j.Logger;
38 import org.onap.dmaap.dbcapi.aaf.AafDecrypt;
39 import org.onap.dmaap.dbcapi.aaf.AafService;
40 import org.onap.dmaap.dbcapi.aaf.DecryptionInterface;
41 import org.onap.dmaap.dbcapi.aaf.AafService.ServiceType;
42 import org.onap.dmaap.dbcapi.logging.BaseLoggingClass;
43 import org.onap.dmaap.dbcapi.logging.DmaapbcLogMessageEnum;
44 import org.onap.dmaap.dbcapi.model.ApiError;
45 import org.onap.dmaap.dbcapi.model.MR_Cluster;
46 import org.onap.dmaap.dbcapi.model.Topic;
47 import org.onap.dmaap.dbcapi.util.DmaapConfig;
49 public class MrProvConnection extends BaseLoggingClass{
51 private String provURL;
53 private HttpURLConnection uc;
56 private String topicMgrCred;
57 private boolean useAAF;
59 private String encPwd;
61 public MrProvConnection() {
62 String mechIdProperty = "aaf.TopicMgrUser";
63 String pwdProperty = "aaf.TopicMgrPassword";
64 DmaapConfig p = (DmaapConfig)DmaapConfig.getConfig();
65 user = p.getProperty( mechIdProperty, "noMechId@domain.netset.com" );
66 encPwd = p.getProperty( pwdProperty, "notSet" );
67 useAAF= "true".equalsIgnoreCase(p.getProperty("UseAAF", "false"));
68 topicMgrCred = getCred();
72 private String getCred( ) {
76 AafDecrypt decryptor = new AafDecrypt();
77 pwd = decryptor.decrypt(encPwd);
78 return user + ":" + pwd;
82 public boolean makeTopicConnection( MR_Cluster cluster ) {
83 logger.info( "connect to cluster: " + cluster.getDcaeLocationName());
86 provURL = cluster.getTopicProtocol() + "://" + cluster.getFqdn() + ":" + cluster.getTopicPort() + "/topics/create";
88 if ( cluster.getTopicProtocol().equals( "https" ) ) {
89 return makeSecureConnection( provURL );
91 return makeConnection( provURL );
94 private boolean makeSecureConnection( String pURL ) {
95 logger.info( "makeConnection to " + pURL );
98 URL u = new URL( pURL );
99 uc = (HttpsURLConnection) u.openConnection();
100 uc.setInstanceFollowRedirects(false);
101 logger.info( "open connect to " + pURL );
103 } catch( UnknownHostException uhe ){
104 logger.error( "Caught UnknownHostException for " + pURL);
106 } catch (Exception e) {
107 logger.error("Unexpected error during openConnection of " + pURL );
113 private boolean makeConnection( String pURL ) {
114 logger.info( "makeConnection to " + pURL );
117 URL u = new URL( pURL );
118 uc = (HttpURLConnection) u.openConnection();
119 uc.setInstanceFollowRedirects(false);
120 logger.info( "open connect to " + pURL );
122 } catch( UnknownHostException uhe ){
123 logger.error( "Caught UnknownHostException for " + pURL);
125 } catch (Exception e) {
126 logger.error("Unexpected error during openConnection of " + pURL );
133 static String bodyToString( InputStream is ) {
134 StringBuilder sb = new StringBuilder();
135 BufferedReader br = new BufferedReader( new InputStreamReader(is));
138 while ((line = br.readLine()) != null ) {
141 } catch (IOException ex ) {
142 errorLogger.error( "IOexception:" + ex);
145 return sb.toString();
148 public String doPostTopic( Topic postTopic, ApiError err ) {
149 String auth = "Basic " + Base64.encodeBase64String(topicMgrCred.getBytes());
152 String responsemessage = null;
157 byte[] postData = postTopic.getBytes();
158 logger.info( "post fields=" + postData.toString() );
160 // when not using AAF, do not attempt Basic Authentication
162 uc.setRequestProperty("Authorization", auth);
163 logger.info( "Authenticating with " + auth );
165 uc.setRequestMethod("POST");
166 uc.setRequestProperty("Content-Type", "application/json");
167 uc.setRequestProperty( "charset", "utf-8");
168 uc.setRequestProperty( "Content-Length", Integer.toString( postData.length ));
169 uc.setUseCaches(false);
170 uc.setDoOutput(true);
171 OutputStream os = null;
176 os = uc.getOutputStream();
177 os.write( postData );
179 } catch (ProtocolException pe) {
180 // Rcvd error instead of 100-Continue
182 // work around glitch in Java 1.7.0.21 and likely others
183 // without this, Java will connect multiple times to the server to run the same request
184 uc.setDoOutput(false);
185 } catch (Exception e) {
187 } catch ( UnknownHostException uhe ) {
188 errorLogger.error( DmaapbcLogMessageEnum.UNKNOWN_HOST_EXCEPTION , "Unknown Host Exception" , provURL );
190 err.setMessage("Unknown Host Exception");
191 err.setFields( uc.getURL().getHost());
192 return new String( "500: " + uhe.getMessage());
193 }catch ( ConnectException ce ) {
194 errorLogger.error( DmaapbcLogMessageEnum.HTTP_CONNECTION_EXCEPTION, provURL, "HTTP Connection Exception" );
196 err.setMessage("HTTP Connection Exception");
197 err.setFields( uc.getURL().getHost());
198 return new String( "500: " + ce.getMessage());
200 rc = uc.getResponseCode();
201 logger.info( "http response code:" + rc );
203 responsemessage = uc.getResponseMessage();
204 logger.info( "responsemessage=" + responsemessage );
205 err.setMessage(responsemessage);
208 if (responsemessage == null) {
209 // work around for glitch in Java 1.7.0.21 and likely others
210 // When Expect: 100 is set and a non-100 response is received, the response message is not set but the response code is
211 String h0 = uc.getHeaderField(0);
213 int i = h0.indexOf(' ');
214 int j = h0.indexOf(' ', i + 1);
215 if (i != -1 && j != -1) {
216 responsemessage = h0.substring(j + 1);
220 if (rc >= 200 && rc < 300 ) {
221 String responseBody = null;
222 responseBody = bodyToString( uc.getInputStream() );
223 logger.info( "responseBody=" + responseBody );
228 } catch (Exception e) {
229 System.err.println("Unable to read response " );
235 } catch ( Exception e ) {}
237 return new String( rc +": " + responsemessage );