f8fd1467d663a270e80d9f070f27fe53d597b268
[appc.git] /
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.sdc.listener;
25
26 import java.io.IOException;
27 import java.io.UnsupportedEncodingException;
28 import java.net.Socket;
29 import java.net.URL;
30 import java.net.UnknownHostException;
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 java.util.Map;
39 import java.util.Map.Entry;
40
41 import javax.net.ssl.SSLContext;
42 import javax.net.ssl.TrustManager;
43 import javax.net.ssl.X509TrustManager;
44
45 import org.apache.commons.codec.binary.Base64;
46 import org.apache.commons.io.IOUtils;
47 import org.apache.http.HttpResponse;
48 import org.apache.http.HttpVersion;
49 import org.apache.http.client.HttpClient;
50 import org.apache.http.client.methods.HttpPost;
51 import org.apache.http.conn.ClientConnectionManager;
52 import org.apache.http.conn.scheme.PlainSocketFactory;
53 import org.apache.http.conn.scheme.Scheme;
54 import org.apache.http.conn.scheme.SchemeRegistry;
55 import org.apache.http.conn.ssl.SSLSocketFactory;
56 import org.apache.http.entity.StringEntity;
57 import org.apache.http.impl.client.DefaultHttpClient;
58 import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
59 import org.apache.http.params.BasicHttpParams;
60 import org.apache.http.params.HttpParams;
61 import org.apache.http.params.HttpProtocolParams;
62 import org.apache.http.protocol.HTTP;
63 import org.onap.appc.exceptions.APPCException;
64 import com.att.eelf.configuration.EELFLogger;
65 import com.att.eelf.configuration.EELFManager;
66
67 public class ProviderOperations {
68
69     private static final EELFLogger LOG = EELFManager.getInstance().getLogger(ProviderOperations.class);
70
71     private static String basic_auth;
72
73     public static ProviderResponse post(URL url, String json, Map<String, String> adtl_headers) throws APPCException {
74         if (json == null) {
75             throw new APPCException("Provided message was null");
76         }
77
78         HttpPost post = null;
79         try {
80             post = new HttpPost(url.toExternalForm());
81             post.setHeader("Content-Type", "application/json");
82             post.setHeader("Accept", "application/json");
83
84             // Set Auth
85             if (basic_auth != null) {
86                 post.setHeader("Authorization", "Basic " + basic_auth);
87             }
88
89             if (adtl_headers != null) {
90                 for (Entry<String, String> header : adtl_headers.entrySet()) {
91                     post.setHeader(header.getKey(), header.getValue());
92                 }
93             }
94
95             StringEntity entity = new StringEntity(json);
96             entity.setContentType("application/json");
97             post.setEntity(new StringEntity(json));
98         } catch (UnsupportedEncodingException e) {
99             throw new APPCException(e);
100         }
101
102         HttpClient client = getHttpClient(url);
103
104         int httpCode = 0;
105         String respBody = null;
106         try {
107             HttpResponse response = client.execute(post);
108             httpCode = response.getStatusLine().getStatusCode();
109             respBody = IOUtils.toString(response.getEntity().getContent());
110             return new ProviderResponse(httpCode, respBody);
111         } catch (IOException e) {
112             throw new APPCException(e);
113         }
114     }
115
116     /**
117      * Sets the basic authentication header for the given user and password. If either entry is null then set basic auth
118      * to null
119      *
120      * @param user
121      *            The user with optional domain name (for AAF)
122      * @param password
123      *            The password for the user
124      * @return The new value of the basic auth string that will be used in the request headers
125      */
126     public static String setAuthentication(String user, String password) {
127         if (user != null && password != null) {
128             String authStr = user + ":" + password;
129             basic_auth = new String(Base64.encodeBase64(authStr.getBytes()));
130         } else {
131             basic_auth = null;
132         }
133         return basic_auth;
134     }
135
136     @SuppressWarnings("deprecation")
137     private static HttpClient getHttpClient(URL url) throws APPCException {
138         HttpClient client;
139         if (url.getProtocol().equals("https")) {
140             try {
141                 KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
142                 trustStore.load(null, null);
143                 MySSLSocketFactory sf = new MySSLSocketFactory(trustStore);
144                 sf.setHostnameVerifier(MySSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
145
146                 HttpParams params = new BasicHttpParams();
147                 HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
148                 HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
149
150                 SchemeRegistry registry = new SchemeRegistry();
151                 registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
152                 registry.register(new Scheme("https", sf, 443));
153                 registry.register(new Scheme("https", sf, 8443));
154                 registry.register(new Scheme("http", sf, 8181));
155
156                 ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);
157                 client = new DefaultHttpClient(ccm, params);
158             } catch (Exception e) {
159                 client = new DefaultHttpClient();
160             }
161         } else if (url.getProtocol().equals("http")) {
162             client = new DefaultHttpClient();
163         } else {
164             throw new APPCException(
165                 "The provider.topology.url property is invalid. The url did not start with http[s]");
166         }
167         return client;
168     }
169
170     @SuppressWarnings("deprecation")
171     public static class MySSLSocketFactory extends SSLSocketFactory {
172         private SSLContext sslContext = SSLContext.getInstance("TLSv1.2");
173
174         public MySSLSocketFactory(KeyStore truststore) throws NoSuchAlgorithmException, KeyManagementException,
175                         KeyStoreException, UnrecoverableKeyException {
176             super(truststore);
177
178             TrustManager tm = new X509TrustManager() {
179                 @Override
180                 public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
181                 }
182
183                 @Override
184                 public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
185                 }
186
187                 @Override
188                 public X509Certificate[] getAcceptedIssuers() {
189                     return null;
190                 }
191             };
192
193             sslContext.init(null, new TrustManager[] {
194                 tm
195             }, null);
196         }
197
198         @Override
199         public Socket createSocket(Socket socket, String host, int port, boolean autoClose)
200             throws IOException, UnknownHostException {
201             return sslContext.getSocketFactory().createSocket(socket, host, port, autoClose);
202         }
203
204         @Override
205         public Socket createSocket() throws IOException {
206             return sslContext.getSocketFactory().createSocket();
207         }
208     }
209
210 }