51bad4f30bc90bc1bf7d7eef142429e465a8f5d6
[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) 2019 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 org.apache.commons.codec.binary.Base64;
25 import org.onap.dmaap.dbcapi.aaf.AafDecrypt;
26 import org.onap.dmaap.dbcapi.logging.BaseLoggingClass;
27 import org.onap.dmaap.dbcapi.logging.DmaapbcLogMessageEnum;
28 import org.onap.dmaap.dbcapi.model.ApiError;
29 import org.onap.dmaap.dbcapi.model.MR_Cluster;
30 import org.onap.dmaap.dbcapi.model.Topic;
31 import org.onap.dmaap.dbcapi.util.DmaapConfig;
32
33 import javax.net.ssl.HttpsURLConnection;
34 import java.io.*;
35 import java.net.*;
36 import java.util.Arrays;
37
38 public class MrProvConnection extends BaseLoggingClass{
39             
40         private String provURL;
41         
42         private HttpURLConnection uc;
43
44         
45         private String topicMgrCred;
46         private boolean useAAF;
47         private String  user;
48         private String  encPwd;
49         
50         public MrProvConnection() {
51                 String mechIdProperty = "aaf.TopicMgrUser";
52                 String pwdProperty = "aaf.TopicMgrPassword";
53                 DmaapConfig p = (DmaapConfig)DmaapConfig.getConfig();
54                 user = p.getProperty( mechIdProperty, "noMechId@domain.netset.com" );
55                 encPwd = p.getProperty( pwdProperty, "notSet" );
56                 useAAF= "true".equalsIgnoreCase(p.getProperty("UseAAF", "false"));
57                 topicMgrCred =  getCred();
58                 
59         }
60         
61         private String getCred( ) {
62
63
64                 String pwd = "";
65                 AafDecrypt decryptor = new AafDecrypt();        
66                 pwd = decryptor.decrypt(encPwd);
67                 return user + ":" + pwd;        
68         }
69         
70         
71         public boolean makeTopicConnection( MR_Cluster cluster ) {
72                 logger.info( "connect to cluster: " + cluster.getDcaeLocationName());
73         
74
75                 provURL = cluster.getTopicProtocol() + "://" + cluster.getFqdn() + ":" + cluster.getTopicPort() + "/topics/create";
76
77                 if ( cluster.getTopicProtocol().equals( "https" ) ) {
78                         return makeSecureConnection( provURL );
79                 }
80                 return makeConnection( provURL );
81         }
82
83         private boolean makeSecureConnection( String pURL ) {
84                 logger.info( "makeConnection to " + pURL );
85         
86                 try {
87                         URL u = new URL( pURL );
88                         uc = (HttpsURLConnection) u.openConnection();
89                         uc.setInstanceFollowRedirects(false);
90                         logger.info( "open connect to " + pURL );
91                         return(true);
92                 } catch( UnknownHostException uhe ){
93                 logger.error( "Caught UnknownHostException for " + pURL);
94                 return(false);
95         } catch (Exception e) {
96             logger.error("Unexpected error during openConnection of " + pURL );
97             e.printStackTrace();
98             return(false);
99         } 
100
101         }
102         private boolean makeConnection( String pURL ) {
103                 logger.info( "makeConnection to " + pURL );
104         
105                 try {
106                         URL u = new URL( pURL );
107                         uc = (HttpURLConnection) u.openConnection();
108                         uc.setInstanceFollowRedirects(false);
109                         logger.info( "open connect to " + pURL );
110                         return(true);
111                 } catch( UnknownHostException uhe ){
112                 logger.error( "Caught UnknownHostException for " + pURL);
113                 return(false);
114         } catch (Exception e) {
115             logger.error("Unexpected error during openConnection of " + pURL );
116             e.printStackTrace();
117             return(false);
118         } 
119
120         }
121         
122         static String bodyToString( InputStream is ) {
123                 StringBuilder sb = new StringBuilder();
124                 BufferedReader br = new BufferedReader( new InputStreamReader(is));
125                 String line;
126                 try {
127                         while ((line = br.readLine()) != null ) {
128                                 sb.append( line );
129                         }
130                 } catch (IOException ex ) {
131                         errorLogger.error( "IOexception:" + ex);
132                 }
133                         
134                 return sb.toString();
135         }
136         
137         public String doPostTopic( Topic postTopic, ApiError err ) {
138                 String auth =  "Basic " + Base64.encodeBase64String(topicMgrCred.getBytes());
139
140
141                 String responsemessage = null;
142                 int rc = -1;
143
144
145                 try {
146                         byte[] postData = postTopic.getBytes();
147                         logger.info( "post fields=" + Arrays.toString(postData));
148                         
149                         // when not using AAF, do not attempt Basic Authentication
150                         if ( useAAF ) {
151                                 uc.setRequestProperty("Authorization", auth);
152                                 logger.info( "Authenticating with " + auth );
153                         }
154                         uc.setRequestMethod("POST");
155                         uc.setRequestProperty("Content-Type", "application/json");
156                         uc.setRequestProperty( "charset", "utf-8");
157                         uc.setRequestProperty( "Content-Length", Integer.toString( postData.length ));
158                         uc.setUseCaches(false);
159                         uc.setDoOutput(true);
160                         OutputStream os = null;
161
162                         
163                         try {
164                  uc.connect();
165                  os = uc.getOutputStream();
166                  os.write( postData );
167
168             } catch (ProtocolException pe) {
169                  // Rcvd error instead of 100-Continue
170                  try {
171                      // work around glitch in Java 1.7.0.21 and likely others
172                      // without this, Java will connect multiple times to the server to run the same request
173                      uc.setDoOutput(false);
174                  } catch (Exception e) {
175                  }
176             } catch ( UnknownHostException uhe ) {
177                 errorLogger.error( DmaapbcLogMessageEnum.UNKNOWN_HOST_EXCEPTION , "Unknown Host Exception" , provURL );
178                 err.setCode(500);
179                 err.setMessage("Unknown Host Exception");
180                 err.setFields( uc.getURL().getHost());
181                 return new String( "500: " + uhe.getMessage());
182             }catch ( ConnectException ce ) {
183                 errorLogger.error( DmaapbcLogMessageEnum.HTTP_CONNECTION_EXCEPTION, provURL, "HTTP Connection Exception"  );
184                 err.setCode(500);
185                 err.setMessage("HTTP Connection Exception");
186                 err.setFields( uc.getURL().getHost());
187                 return new String( "500: " + ce.getMessage());
188             }
189                         rc = uc.getResponseCode();
190                         logger.info( "http response code:" + rc );
191                         err.setCode(rc);
192             responsemessage = uc.getResponseMessage();
193             logger.info( "responsemessage=" + responsemessage );
194             err.setMessage(responsemessage);
195
196
197             if (responsemessage == null) {
198                  // work around for glitch in Java 1.7.0.21 and likely others
199                  // When Expect: 100 is set and a non-100 response is received, the response message is not set but the response code is
200                  String h0 = uc.getHeaderField(0);
201                  if (h0 != null) {
202                      int i = h0.indexOf(' ');
203                      int j = h0.indexOf(' ', i + 1);
204                      if (i != -1 && j != -1) {
205                          responsemessage = h0.substring(j + 1);
206                      }
207                  }
208             }
209             if (rc >= 200 && rc < 300 ) {
210                         String responseBody = null;
211                         responseBody = bodyToString( uc.getInputStream() );
212                         logger.info( "responseBody=" + responseBody );
213                         return responseBody;
214
215             } 
216             
217                 } catch (Exception e) {
218                         errorLogger.error("Unable to read response  " );
219            
220         }
221                 finally {
222                         try {
223                                 uc.disconnect();
224                         } catch ( Exception e ) {
225                                 errorLogger.error("Unable to disconnect");
226                         }
227                 }
228                 return new String( rc +": " + responsemessage );
229
230         }
231         
232
233
234                 
235 }