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