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