Fix cluster object to use http port
[dmaap/dbcapi.git] / src / main / java / org / onap / dmaap / dbcapi / client / MrProvConnection.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * org.onap.dmaap
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
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
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=========================================================
19  */
20
21 package org.onap.dmaap.dbcapi.client;
22
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;
31 import java.net.URL;
32 import java.net.UnknownHostException;
33
34 import javax.net.ssl.HttpsURLConnection;
35
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;
48
49 public class MrProvConnection extends BaseLoggingClass{
50             
51         private String provURL;
52         
53         private HttpURLConnection uc;
54
55         
56         private String topicMgrCred;
57         private boolean useAAF;
58         private String  user;
59         private String  encPwd;
60         
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();
69                 
70         }
71         
72         private String getCred( ) {
73
74
75                 String pwd = "";
76                 AafDecrypt decryptor = new AafDecrypt();        
77                 pwd = decryptor.decrypt(encPwd);
78                 return user + ":" + pwd;        
79         }
80         
81         
82         public boolean makeTopicConnection( MR_Cluster cluster ) {
83                 logger.info( "connect to cluster: " + cluster.getDcaeLocationName());
84         
85
86                 provURL = cluster.getTopicProtocol() + "://" + cluster.getFqdn() + ":" + cluster.getTopicPort() + "/topics/create";
87
88                 if ( cluster.getTopicProtocol().equals( "https" ) ) {
89                         return makeSecureConnection( provURL );
90                 }
91                 return makeConnection( provURL );
92         }
93
94         private boolean makeSecureConnection( String pURL ) {
95                 logger.info( "makeConnection to " + pURL );
96         
97                 try {
98                         URL u = new URL( pURL );
99                         uc = (HttpsURLConnection) u.openConnection();
100                         uc.setInstanceFollowRedirects(false);
101                         logger.info( "open connect to " + pURL );
102                         return(true);
103                 } catch( UnknownHostException uhe ){
104                 logger.error( "Caught UnknownHostException for " + pURL);
105                 return(false);
106         } catch (Exception e) {
107             logger.error("Unexpected error during openConnection of " + pURL );
108             e.printStackTrace();
109             return(false);
110         } 
111
112         }
113         private boolean makeConnection( String pURL ) {
114                 logger.info( "makeConnection to " + pURL );
115         
116                 try {
117                         URL u = new URL( pURL );
118                         uc = (HttpURLConnection) u.openConnection();
119                         uc.setInstanceFollowRedirects(false);
120                         logger.info( "open connect to " + pURL );
121                         return(true);
122                 } catch( UnknownHostException uhe ){
123                 logger.error( "Caught UnknownHostException for " + pURL);
124                 return(false);
125         } catch (Exception e) {
126             logger.error("Unexpected error during openConnection of " + pURL );
127             e.printStackTrace();
128             return(false);
129         } 
130
131         }
132         
133         static String bodyToString( InputStream is ) {
134                 StringBuilder sb = new StringBuilder();
135                 BufferedReader br = new BufferedReader( new InputStreamReader(is));
136                 String line;
137                 try {
138                         while ((line = br.readLine()) != null ) {
139                                 sb.append( line );
140                         }
141                 } catch (IOException ex ) {
142                         errorLogger.error( "IOexception:" + ex);
143                 }
144                         
145                 return sb.toString();
146         }
147         
148         public String doPostTopic( Topic postTopic, ApiError err ) {
149                 String auth =  "Basic " + Base64.encodeBase64String(topicMgrCred.getBytes());
150
151
152                 String responsemessage = null;
153                 int rc = -1;
154
155
156                 try {
157                         byte[] postData = postTopic.getBytes();
158                         logger.info( "post fields=" + postData.toString() );
159                         
160                         // when not using AAF, do not attempt Basic Authentication
161                         if ( useAAF ) {
162                                 uc.setRequestProperty("Authorization", auth);
163                                 logger.info( "Authenticating with " + auth );
164                         }
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;
172
173                         
174                         try {
175                  uc.connect();
176                  os = uc.getOutputStream();
177                  os.write( postData );
178
179             } catch (ProtocolException pe) {
180                  // Rcvd error instead of 100-Continue
181                  try {
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) {
186                  }
187             } catch ( UnknownHostException uhe ) {
188                 errorLogger.error( DmaapbcLogMessageEnum.UNKNOWN_HOST_EXCEPTION , "Unknown Host Exception" , provURL );
189                 err.setCode(500);
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"  );
195                 err.setCode(500);
196                 err.setMessage("HTTP Connection Exception");
197                 err.setFields( uc.getURL().getHost());
198                 return new String( "500: " + ce.getMessage());
199             }
200                         rc = uc.getResponseCode();
201                         logger.info( "http response code:" + rc );
202                         err.setCode(rc);
203             responsemessage = uc.getResponseMessage();
204             logger.info( "responsemessage=" + responsemessage );
205             err.setMessage(responsemessage);
206
207
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);
212                  if (h0 != null) {
213                      int i = h0.indexOf(' ');
214                      int j = h0.indexOf(' ', i + 1);
215                      if (i != -1 && j != -1) {
216                          responsemessage = h0.substring(j + 1);
217                      }
218                  }
219             }
220             if (rc >= 200 && rc < 300 ) {
221                         String responseBody = null;
222                         responseBody = bodyToString( uc.getInputStream() );
223                         logger.info( "responseBody=" + responseBody );
224                         return responseBody;
225
226             } 
227             
228                 } catch (Exception e) {
229             System.err.println("Unable to read response  " );
230             e.printStackTrace();
231         }
232                 finally {
233                         try {
234                                 uc.disconnect();
235                         } catch ( Exception e ) {}
236                 }
237                 return new String( rc +": " + responsemessage );
238
239         }
240         
241
242
243                 
244 }