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