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