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