Fix cluster object to use http port
[dmaap/dbcapi.git] / src / main / java / org / onap / dmaap / dbcapi / client / MrTopicConnection.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.ProtocolException;
29 import java.net.URL;
30 import java.net.HttpURLConnection;
31
32 import javax.net.ssl.HttpsURLConnection;
33 import javax.net.ssl.SSLException;
34
35 import org.apache.commons.codec.binary.Base64;
36 import org.apache.log4j.Logger;
37 import org.onap.dmaap.dbcapi.logging.BaseLoggingClass;
38 import org.onap.dmaap.dbcapi.model.ApiError;
39 import org.onap.dmaap.dbcapi.model.MR_Cluster;
40 import org.onap.dmaap.dbcapi.util.DmaapConfig;
41
42 public class MrTopicConnection extends BaseLoggingClass  {
43         private String topicURL;
44         
45         private HttpURLConnection uc;
46
47         
48         private  String mmProvCred; 
49         private String unit_test;
50         private boolean useAAF;
51
52
53         public MrTopicConnection(String user, String pwd ) {
54                 mmProvCred = new String( user + ":" + pwd );
55                 DmaapConfig p = (DmaapConfig)DmaapConfig.getConfig();
56         unit_test = p.getProperty( "UnitTest", "No" );
57         useAAF= "true".equalsIgnoreCase(p.getProperty("UseAAF", "false"));
58         }
59         
60         public boolean makeTopicConnection( MR_Cluster cluster, String topic, String overrideFqdn ) {
61                 String fqdn = overrideFqdn != null ? overrideFqdn : cluster.getFqdn();
62                 logger.info( "connect to cluster: " + fqdn + " for topic: " + topic );
63         
64
65                 topicURL = cluster.getTopicProtocol() + "://" + fqdn + ":" + cluster.getTopicPort() + "/events/" + topic ;
66
67                 if ( cluster.getTopicProtocol().equals( "https")) {
68                         return makeSecureConnection( topicURL );
69                 }
70                 return makeConnection( topicURL );
71         }
72
73         private boolean makeSecureConnection( String pURL ) {
74                 logger.info( "makeConnection to " + pURL );
75         
76                 try {
77                         URL u = new URL( pURL );
78                         uc = (HttpsURLConnection) u.openConnection();
79                         uc.setInstanceFollowRedirects(false);
80                         logger.info( "open connection to " + pURL );
81                         return(true);
82                 } catch (Exception e) {
83             logger.error("Unexpected error during openConnection of " + pURL );
84             e.printStackTrace();
85             return(false);
86         }
87
88         }
89         private boolean makeConnection( String pURL ) {
90                 logger.info( "makeConnection to " + pURL );
91         
92                 try {
93                         URL u = new URL( pURL );
94                         uc = (HttpURLConnection) u.openConnection();
95                         uc.setInstanceFollowRedirects(false);
96                         logger.info( "open connection to " + pURL );
97                         return(true);
98                 } catch (Exception e) {
99             logger.error("Unexpected error during openConnection of " + pURL );
100             e.printStackTrace();
101             return(false);
102         }
103
104         }
105         
106         static String bodyToString( InputStream is ) {
107                 StringBuilder sb = new StringBuilder();
108                 BufferedReader br = new BufferedReader( new InputStreamReader(is));
109                 String line;
110                 try {
111                         while ((line = br.readLine()) != null ) {
112                                 sb.append( line );
113                         }
114                 } catch (IOException ex ) {
115                         errorLogger.error( "IOexception:" + ex);
116                 }
117                         
118                 return sb.toString();
119         }
120         
121         public ApiError doPostMessage( String postMessage ) {
122                 ApiError response = new ApiError();
123                 String auth =  "Basic " + Base64.encodeBase64String(mmProvCred.getBytes());
124
125
126
127                 try {
128                         byte[] postData = postMessage.getBytes();
129                         logger.info( "post fields=" + postMessage );
130                         if ( useAAF ) {
131                                 uc.setRequestProperty("Authorization", auth);
132                                 logger.info( "Authenticating with " + auth );
133                         }
134                         uc.setRequestMethod("POST");
135                         uc.setRequestProperty("Content-Type", "application/json");
136                         uc.setRequestProperty( "charset", "utf-8");
137                         uc.setRequestProperty( "Content-Length", Integer.toString( postData.length ));
138                         uc.setUseCaches(false);
139                         uc.setDoOutput(true);
140                         OutputStream os = null;
141
142                         
143                         try {
144                  uc.connect();
145                  os = uc.getOutputStream();
146                  os.write( postData );
147
148             } catch (ProtocolException pe) {
149                  // Rcvd error instead of 100-Continue
150                  try {
151                      // work around glitch in Java 1.7.0.21 and likely others
152                      // without this, Java will connect multiple times to the server to run the same request
153                      uc.setDoOutput(false);
154                  } catch (Exception e) {
155                  }
156             }  catch ( SSLException se ) {
157                         response.setCode(500);
158                         response.setMessage( se.getMessage());
159                         return response;
160                 
161             }
162                         response.setCode( uc.getResponseCode());
163                         logger.info( "http response code:" + response.getCode());
164             response.setMessage( uc.getResponseMessage() ); 
165             logger.info( "response message=" + response.getMessage() );
166
167
168             if ( response.getMessage() == null) {
169                  // work around for glitch in Java 1.7.0.21 and likely others
170                  // When Expect: 100 is set and a non-100 response is received, the response message is not set but the response code is
171                  String h0 = uc.getHeaderField(0);
172                  if (h0 != null) {
173                      int i = h0.indexOf(' ');
174                      int j = h0.indexOf(' ', i + 1);
175                      if (i != -1 && j != -1) {
176                          response.setMessage( h0.substring(j + 1) );
177                      }
178                  }
179             }
180             if ( response.is2xx() ) {
181                         response.setFields( bodyToString( uc.getInputStream() ) );
182                         logger.info( "responseBody=" + response.getFields() );
183                         return response;
184
185             } 
186             
187                 } catch (Exception e) {
188                 if ( unit_test.equals( "Yes" ) ) {
189                                 response.setCode(200);
190                                 response.setMessage( "simulated response");
191                                 logger.info( "artificial 200 response from doPostMessage because unit_test =" + unit_test );
192                 } else {
193
194                                 response.setCode(500);
195                                 response.setMessage( "Unable to read response");
196                                 logger.warn( response.getMessage() );
197                 e.printStackTrace();
198                         }
199         }
200                 finally {
201                         try {
202                                 uc.disconnect();
203                         } catch ( Exception e ) {}
204                 }
205                 return response;
206
207         }
208
209 }