2 * ============LICENSE_START=======================================================
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
13 * http://www.apache.org/licenses/LICENSE-2.0
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.
21 * ============LICENSE_END=========================================================
24 package org.onap.appc.rest.client;
26 import java.io.IOException;
27 import java.io.UnsupportedEncodingException;
28 import java.net.MalformedURLException;
29 import java.net.Socket;
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;
66 @SuppressWarnings("deprecation")
67 public class RestClientInvoker {
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 ";
74 private URL url = null;
75 private String basicAuth = null;
77 public RestClientInvoker(URL url) {
82 * Sets the basic authentication header for the given user and password. If either entry is null
83 * then does not set basic auth
85 * @param user The user with optional domain name (for AAF)
86 * @param password The password for the user
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()));
95 public HttpResponse doPost(String path, String body) throws APPCException {
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);
105 if (basicAuth != null) {
106 post.setHeader(HttpHeaders.AUTHORIZATION, BASIC + basicAuth);
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);
115 HttpClient client = getHttpClient();
118 return client.execute(post);
119 } catch (IOException e) {
120 throw new APPCException(e);
125 * This is Generic method that can be used to perform REST Put operation
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
132 public HttpResponse doPut(String path, String body) throws APPCException {
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);
140 if (basicAuth != null) {
141 put.setHeader(HttpHeaders.AUTHORIZATION, BASIC + basicAuth);
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);
151 HttpClient client = getHttpClient();
154 return client.execute(put);
155 } catch (IOException e) {
156 throw new APPCException(e);
160 public HttpResponse doGet(String path) throws APPCException {
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);
168 if (basicAuth != null) {
169 get.setHeader(HttpHeaders.AUTHORIZATION, BASIC + basicAuth);
172 } catch (Exception e) {
173 throw new APPCException(e);
176 try (CloseableHttpClient client = getHttpClient()) {
177 return client.execute(get);
178 } catch (IOException e) {
179 throw new APPCException(e);
183 private CloseableHttpClient getHttpClient() throws APPCException {
184 switch (url.getProtocol()) {
185 case OPERATION_HTTPS:
186 return createHttpsClient();
188 return new DefaultHttpClient();
190 throw new APPCException("The url did not start with http[s]");
195 private CloseableHttpClient createHttpsClient() {
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);
202 HttpParams params = new BasicHttpParams();
203 HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
204 HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
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));
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();
220 private static class MySSLSocketFactory extends SSLSocketFactory {
221 private SSLContext sslContext = SSLContext.getInstance("TLS");
223 private MySSLSocketFactory(KeyStore truststore)
224 throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException {
227 TrustManager tm = new X509TrustManager() {
229 public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
230 LOG.debug("Inside checkClientTrusted");
234 public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
235 LOG.debug("Inside checkServerTrusted");
239 public X509Certificate[] getAcceptedIssuers() {
240 return new X509Certificate[1];
244 sslContext.init(null, new TrustManager[] {tm}, null);
248 public Socket createSocket(Socket socket, String host, int port, boolean autoClose) throws IOException {
249 return sslContext.getSocketFactory().createSocket(socket, host, port, autoClose);
253 public Socket createSocket() throws IOException {
254 return sslContext.getSocketFactory().createSocket();