Platform hardening for common bundle
[appc.git] / appc-common / src / main / java / org / onap / appc / rest / client / RestClientInvoker.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP : APPC
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Copyright (C) 2017 Amdocs
8  * =============================================================================
9  * Licensed under the Apache License, Version 2.0 (the "License");
10  * you may not use this file except in compliance with the License.
11  * You may obtain a copy of the License at
12  * 
13  *      http://www.apache.org/licenses/LICENSE-2.0
14  * 
15  * Unless required by applicable law or agreed to in writing, software
16  * distributed under the License is distributed on an "AS IS" BASIS,
17  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18  * See the License for the specific language governing permissions and
19  * limitations under the License.
20  * 
21  * ECOMP is a trademark and service mark of AT&T Intellectual Property.
22  * ============LICENSE_END=========================================================
23  */
24
25 package org.onap.appc.rest.client;
26
27 import com.att.eelf.configuration.EELFLogger;
28 import com.att.eelf.configuration.EELFManager;
29 import org.apache.commons.codec.binary.Base64;
30 import org.apache.http.HttpHeaders;
31 import org.apache.http.HttpResponse;
32 import org.apache.http.HttpVersion;
33 import org.apache.http.client.HttpClient;
34 import org.apache.http.client.methods.HttpGet;
35 import org.apache.http.client.methods.HttpPost;
36 import org.apache.http.client.methods.HttpPut;
37 import org.apache.http.conn.ClientConnectionManager;
38 import org.apache.http.conn.scheme.PlainSocketFactory;
39 import org.apache.http.conn.scheme.Scheme;
40 import org.apache.http.conn.scheme.SchemeRegistry;
41 import org.apache.http.conn.ssl.SSLSocketFactory;
42 import org.apache.http.entity.StringEntity;
43 import org.apache.http.impl.client.DefaultHttpClient;
44 import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
45 import org.apache.http.params.BasicHttpParams;
46 import org.apache.http.params.HttpParams;
47 import org.apache.http.params.HttpProtocolParams;
48 import org.apache.http.protocol.HTTP;
49 import org.onap.appc.exceptions.APPCException;
50
51 import javax.net.ssl.SSLContext;
52 import javax.net.ssl.TrustManager;
53 import javax.net.ssl.X509TrustManager;
54 import java.io.IOException;
55 import java.io.UnsupportedEncodingException;
56 import java.net.MalformedURLException;
57 import java.net.Socket;
58 import java.net.URL;
59 import java.security.*;
60 import java.security.cert.CertificateException;
61 import java.security.cert.X509Certificate;
62
63 public class RestClientInvoker {
64
65     public RestClientInvoker(URL url){
66         this.url=url;
67     }
68     private RestClientInvoker(){}
69
70     private URL url=null;
71     private String basicAuth=null;
72
73     private static final EELFLogger LOG = EELFManager.getInstance().getLogger(RestClientInvoker.class);
74     private static final String OPERATION_HTTPS="https";
75     private static final String OPERATION_APPLICATION_JSON= " application/json";
76
77
78     /**
79      * Sets the basic authentication header for the given user and password. If either entry is null then does not set basic auth
80      *
81      * @param user     The user with optional domain name (for AAF)
82      * @param password The password for the user
83      */
84     public void setAuthentication(String user, String password) {
85         if (user != null && password != null) {
86             String authStr = user + ":" + password;
87             basicAuth = new String(Base64.encodeBase64(authStr.getBytes()));
88         }
89     }
90
91     public HttpResponse doPost (String path , String body) throws APPCException {
92         HttpPost post;
93
94         try {
95
96             URL postUrl = new URL(url.getProtocol(), url.getHost(), url.getPort(), path);
97             post = new HttpPost(postUrl.toExternalForm());
98             post.setHeader(HttpHeaders.CONTENT_TYPE, OPERATION_APPLICATION_JSON);
99             post.setHeader(HttpHeaders.ACCEPT, OPERATION_APPLICATION_JSON);
100
101             if (basicAuth != null) {
102                 post.setHeader(HttpHeaders.AUTHORIZATION, "Basic " + basicAuth);
103             }
104
105             StringEntity entity = new StringEntity(body);
106             entity.setContentType(OPERATION_APPLICATION_JSON);
107             post.setEntity(new StringEntity(body));
108         } catch (MalformedURLException | UnsupportedEncodingException e) {
109             throw new APPCException(e);
110         }
111         HttpClient client = getHttpClient();
112
113         try {
114             return client.execute(post);
115         } catch (IOException e) {
116             throw new APPCException(e);
117         }
118     }
119
120     /**
121      * This is Generic method that can be used to perform REST Put operation
122      * @param path - path for put
123      * @param body - payload for put action which will be sent as request body.
124      * @return - HttpResponse object which is returned from put REST call.
125      * @throws APPCException when error occurs
126      */
127     public HttpResponse doPut (String path, String body) throws APPCException {
128         HttpPut put;
129         try {
130             URL putUrl = new URL(url.getProtocol(), url.getHost(), url.getPort(), path);
131             put = new HttpPut(putUrl.toExternalForm());
132             put.setHeader(HttpHeaders.CONTENT_TYPE, OPERATION_APPLICATION_JSON);
133             put.setHeader(HttpHeaders.ACCEPT, OPERATION_APPLICATION_JSON);
134
135             if (basicAuth != null) {
136                 put.setHeader(HttpHeaders.AUTHORIZATION, "Basic " + basicAuth);
137             }
138
139             StringEntity entity = new StringEntity(body);
140             entity.setContentType(OPERATION_APPLICATION_JSON);
141             put.setEntity(new StringEntity(body));
142         } catch (UnsupportedEncodingException | MalformedURLException e) {
143             throw new APPCException(e);
144         }
145
146         HttpClient client = getHttpClient();
147
148         try {
149             return client.execute(put);
150         } catch (IOException e) {
151             throw new APPCException(e);
152         }
153     }
154
155     public HttpResponse doGet (String path) throws APPCException {
156         HttpGet get;
157         try {
158             URL getUrl = new URL(url.getProtocol(), url.getHost(), url.getPort(), path);
159             get = new HttpGet(getUrl.toExternalForm());
160             get.setHeader(HttpHeaders.CONTENT_TYPE, OPERATION_APPLICATION_JSON);
161             get.setHeader(HttpHeaders.ACCEPT, OPERATION_APPLICATION_JSON);
162
163             if (basicAuth != null) {
164                 get.setHeader(HttpHeaders.AUTHORIZATION, "Basic " + basicAuth);
165             }
166
167         } catch (Exception e) {
168             throw new APPCException(e);
169         }
170         HttpClient client = getHttpClient();
171         try {
172             return client.execute(get);
173         } catch (IOException e) {
174             throw new APPCException(e);
175         }
176     }
177
178     @SuppressWarnings("deprecation")
179     private HttpClient getHttpClient() throws APPCException {
180         HttpClient client;
181         switch (url.getProtocol()) {
182             case OPERATION_HTTPS:
183                 try {
184                     KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
185                     trustStore.load(null, null);
186                     MySSLSocketFactory sf = new MySSLSocketFactory(trustStore);
187                     sf.setHostnameVerifier(MySSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
188
189                     HttpParams params = new BasicHttpParams();
190                     HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
191                     HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
192
193                     SchemeRegistry registry = new SchemeRegistry();
194                     registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
195                     registry.register(new Scheme(OPERATION_HTTPS, sf, 443));
196                     registry.register(new Scheme(OPERATION_HTTPS, sf, 8443));
197                     registry.register(new Scheme("http", sf, 8181));
198
199                     ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);
200                     client = new DefaultHttpClient(ccm, params);
201                 } catch (Exception e) {
202                     LOG.error("Error creating HTTP Client. Creating default client.", e);
203                     client = new DefaultHttpClient();
204                 }
205                 break;
206             case "http":
207                 client = new DefaultHttpClient();
208                 break;
209             default:
210                 throw new APPCException(
211                         "The url did not start with http[s]");
212         }
213         return client;
214     }
215     @SuppressWarnings("deprecation")
216     private static class MySSLSocketFactory extends SSLSocketFactory {
217         private SSLContext sslContext = SSLContext.getInstance("TLS");
218
219         private MySSLSocketFactory(KeyStore truststore) throws NoSuchAlgorithmException, KeyManagementException,
220                 KeyStoreException, UnrecoverableKeyException {
221             super(truststore);
222
223             TrustManager tm = new X509TrustManager() {
224                 @Override
225                 public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
226                     LOG.debug("Inside checkClientTrusted");
227                 }
228
229                 @Override
230                 public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
231                     LOG.debug("Inside checkServerTrusted");
232                 }
233
234                 @Override
235                 public X509Certificate[] getAcceptedIssuers() {
236                     return new X509Certificate[1];
237                 }
238             };
239
240             sslContext.init(null, new TrustManager[]{
241                     tm
242             }, null);
243         }
244
245         @Override
246         public Socket createSocket(Socket socket, String host, int port, boolean autoClose)
247                 throws IOException  {
248             return sslContext.getSocketFactory().createSocket(socket, host, port, autoClose);
249         }
250
251         @Override
252         public Socket createSocket() throws IOException {
253             return sslContext.getSocketFactory().createSocket();
254         }
255     }
256
257 }