42006018e663bd3b6f5125763c202beea3ca8581
[appc.git] / appc-sdc-listener / appc-sdc-listener-bundle / src / main / java / org / onap / appc / sdc / listener / ProviderOperations.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP : APPC
4  * ================================================================================
5  * Copyright (C) 2017-2019 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     private static URL defaultUrl;
73
74     public static ProviderResponse post(URL url, String json, Map<String, String> adtl_headers) throws APPCException {
75         if (json == null) {
76             throw new APPCException("Provided message was null");
77         }
78
79         HttpPost post = null;
80         try {
81             post = new HttpPost(url.toExternalForm());
82             post.setHeader("Content-Type", "application/json");
83             post.setHeader("Accept", "application/json");
84
85             // Set Auth
86             if (basic_auth != null) {
87                 post.setHeader("Authorization", "Basic " + basic_auth);
88             }
89
90             if (adtl_headers != null) {
91                 for (Entry<String, String> header : adtl_headers.entrySet()) {
92                     post.setHeader(header.getKey(), header.getValue());
93                 }
94             }
95
96             StringEntity entity = new StringEntity(json);
97             entity.setContentType("application/json");
98             post.setEntity(new StringEntity(json));
99         } catch (UnsupportedEncodingException e) {
100             throw new APPCException(e);
101         }
102
103         HttpClient client = getHttpClient(url);
104
105         int httpCode = 0;
106         String respBody = null;
107         try {
108             HttpResponse response = client.execute(post);
109             httpCode = response.getStatusLine().getStatusCode();
110             respBody = IOUtils.toString(response.getEntity().getContent());
111             return new ProviderResponse(httpCode, respBody);
112         } catch (IOException e) {
113             throw new APPCException(e);
114         }
115     }
116
117     /**
118      * Sets the basic authentication header for the given user and password. If either entry is null then set basic auth
119      * to null
120      *
121      * @param user
122      *            The user with optional domain name (for AAF)
123      * @param password
124      *            The password for the user
125      * @return The new value of the basic auth string that will be used in the request headers
126      */
127     public static String setAuthentication(String user, String password) {
128         if (user != null && password != null) {
129             String authStr = user + ":" + password;
130             basic_auth = new String(Base64.encodeBase64(authStr.getBytes()));
131         } else {
132             basic_auth = null;
133         }
134         return basic_auth;
135     }
136
137     /**
138      * Sets the default Provider URL to the provided URL. If the entry is null then sets to null.
139      *
140      * @param URL The URL
141      */
142     public static void setDefaultUrl(URL URL) {
143         if (URL != null) {
144             defaultUrl = URL;
145         } else {
146             defaultUrl = null;
147         }
148     }
149     @SuppressWarnings("deprecation")
150     private static HttpClient getHttpClient(URL url) throws APPCException {
151         HttpClient client;
152         if (url.getProtocol().equals("https")) {
153             try {
154                 KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
155                 trustStore.load(null, null);
156                 MySSLSocketFactory sf = new MySSLSocketFactory(trustStore);
157                 sf.setHostnameVerifier(MySSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
158
159                 HttpParams params = new BasicHttpParams();
160                 HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
161                 HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
162
163                 SchemeRegistry registry = new SchemeRegistry();
164                 registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
165                 registry.register(new Scheme("https", sf, 443));
166                 registry.register(new Scheme("https", sf, 8443));
167                 registry.register(new Scheme("http", sf, 8181));
168
169                 ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);
170                 client = new DefaultHttpClient(ccm, params);
171             } catch (Exception e) {
172                 client = new DefaultHttpClient();
173             }
174         } else if (url.getProtocol().equals("http")) {
175             client = new DefaultHttpClient();
176         } else {
177             throw new APPCException(
178                 "The provider.topology.url property is invalid. The url did not start with http[s]");
179         }
180         return client;
181     }
182
183     @SuppressWarnings("deprecation")
184     public static class MySSLSocketFactory extends SSLSocketFactory {
185         private SSLContext sslContext = SSLContext.getInstance("TLSv1.2");
186
187         public MySSLSocketFactory(KeyStore truststore) throws NoSuchAlgorithmException, KeyManagementException,
188                         KeyStoreException, UnrecoverableKeyException {
189             super(truststore);
190
191             TrustManager tm = new X509TrustManager() {
192                 @Override
193                 public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
194                 }
195
196                 @Override
197                 public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
198                 }
199
200                 @Override
201                 public X509Certificate[] getAcceptedIssuers() {
202                     return null;
203                 }
204             };
205
206             sslContext.init(null, new TrustManager[] {
207                 tm
208             }, null);
209         }
210
211         @Override
212         public Socket createSocket(Socket socket, String host, int port, boolean autoClose)
213             throws IOException, UnknownHostException {
214             return sslContext.getSocketFactory().createSocket(socket, host, port, autoClose);
215         }
216
217         @Override
218         public Socket createSocket() throws IOException {
219             return sslContext.getSocketFactory().createSocket();
220         }
221     }
222
223 }