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