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