2 * ============LICENSE_START=======================================================
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
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 * ECOMP is a trademark and service mark of AT&T Intellectual Property.
22 * ============LICENSE_END=========================================================
25 package org.onap.appc.rest.client;
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;
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;
59 import java.security.*;
60 import java.security.cert.CertificateException;
61 import java.security.cert.X509Certificate;
63 public class RestClientInvoker {
65 public RestClientInvoker(URL url){
68 private RestClientInvoker(){}
71 private String basicAuth=null;
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";
79 * Sets the basic authentication header for the given user and password. If either entry is null then does not set basic auth
81 * @param user The user with optional domain name (for AAF)
82 * @param password The password for the user
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()));
91 public HttpResponse doPost (String path , String body) throws APPCException {
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);
101 if (basicAuth != null) {
102 post.setHeader(HttpHeaders.AUTHORIZATION, "Basic " + basicAuth);
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);
111 HttpClient client = getHttpClient();
114 return client.execute(post);
115 } catch (IOException e) {
116 throw new APPCException(e);
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
127 public HttpResponse doPut (String path, String body) throws APPCException {
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);
135 if (basicAuth != null) {
136 put.setHeader(HttpHeaders.AUTHORIZATION, "Basic " + basicAuth);
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);
146 HttpClient client = getHttpClient();
149 return client.execute(put);
150 } catch (IOException e) {
151 throw new APPCException(e);
155 public HttpResponse doGet (String path) throws APPCException {
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);
163 if (basicAuth != null) {
164 get.setHeader(HttpHeaders.AUTHORIZATION, "Basic " + basicAuth);
167 } catch (Exception e) {
168 throw new APPCException(e);
170 HttpClient client = getHttpClient();
172 return client.execute(get);
173 } catch (IOException e) {
174 throw new APPCException(e);
178 @SuppressWarnings("deprecation")
179 private HttpClient getHttpClient() throws APPCException {
181 switch (url.getProtocol()) {
182 case OPERATION_HTTPS:
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);
189 HttpParams params = new BasicHttpParams();
190 HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
191 HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
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));
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();
207 client = new DefaultHttpClient();
210 throw new APPCException(
211 "The url did not start with http[s]");
215 @SuppressWarnings("deprecation")
216 private static class MySSLSocketFactory extends SSLSocketFactory {
217 private SSLContext sslContext = SSLContext.getInstance("TLS");
219 private MySSLSocketFactory(KeyStore truststore) throws NoSuchAlgorithmException, KeyManagementException,
220 KeyStoreException, UnrecoverableKeyException {
223 TrustManager tm = new X509TrustManager() {
225 public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
226 LOG.debug("Inside checkClientTrusted");
230 public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
231 LOG.debug("Inside checkServerTrusted");
235 public X509Certificate[] getAcceptedIssuers() {
236 return new X509Certificate[1];
240 sslContext.init(null, new TrustManager[]{
246 public Socket createSocket(Socket socket, String host, int port, boolean autoClose)
248 return sslContext.getSocketFactory().createSocket(socket, host, port, autoClose);
252 public Socket createSocket() throws IOException {
253 return sslContext.getSocketFactory().createSocket();