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