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