d60dca7741a9911c8bea430b8e25b549da102cd7
[appc.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  * APPC
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * Copyright (C) 2017 Amdocs
7  * ================================================================================
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  * 
12  *      http://www.apache.org/licenses/LICENSE-2.0
13  * 
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  * ============LICENSE_END=========================================================
20  * ECOMP is a trademark and service mark of AT&T Intellectual Property.
21  */
22
23 package org.openecomp.appc.sdc.listener;
24
25 import java.io.IOException;
26 import java.io.UnsupportedEncodingException;
27 import java.net.Socket;
28 import java.net.URL;
29 import java.net.UnknownHostException;
30 import java.security.KeyManagementException;
31 import java.security.KeyStore;
32 import java.security.KeyStoreException;
33 import java.security.NoSuchAlgorithmException;
34 import java.security.UnrecoverableKeyException;
35 import java.security.cert.CertificateException;
36 import java.security.cert.X509Certificate;
37 import java.util.Map;
38 import java.util.Map.Entry;
39
40 import javax.net.ssl.SSLContext;
41 import javax.net.ssl.TrustManager;
42 import javax.net.ssl.X509TrustManager;
43
44 import org.apache.commons.codec.binary.Base64;
45 import org.apache.commons.io.IOUtils;
46 import org.apache.http.HttpResponse;
47 import org.apache.http.HttpVersion;
48 import org.apache.http.client.HttpClient;
49 import org.apache.http.client.methods.HttpPost;
50 import org.apache.http.conn.ClientConnectionManager;
51 import org.apache.http.conn.scheme.PlainSocketFactory;
52 import org.apache.http.conn.scheme.Scheme;
53 import org.apache.http.conn.scheme.SchemeRegistry;
54 import org.apache.http.conn.ssl.SSLSocketFactory;
55 import org.apache.http.entity.StringEntity;
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.openecomp.appc.exceptions.APPCException;
63 import com.att.eelf.configuration.EELFLogger;
64 import com.att.eelf.configuration.EELFManager;
65
66 public class ProviderOperations {
67
68     private static final EELFLogger LOG = EELFManager.getInstance().getLogger(ProviderOperations.class);
69
70     private static String basic_auth;
71
72     public static ProviderResponse post(URL url, String json, Map<String, String> adtl_headers) throws APPCException {
73         if (json == null) {
74             throw new APPCException("Provided message was null");
75         }
76
77         HttpPost post = null;
78         try {
79             post = new HttpPost(url.toExternalForm());
80             post.setHeader("Content-Type", "application/json");
81             post.setHeader("Accept", "application/json");
82
83             // Set Auth
84             if (basic_auth != null) {
85                 post.setHeader("Authorization", "Basic " + basic_auth);
86             }
87
88             if (adtl_headers != null) {
89                 for (Entry<String, String> header : adtl_headers.entrySet()) {
90                     post.setHeader(header.getKey(), header.getValue());
91                 }
92             }
93
94             StringEntity entity = new StringEntity(json);
95             entity.setContentType("application/json");
96             post.setEntity(new StringEntity(json));
97         } catch (UnsupportedEncodingException e) {
98             throw new APPCException(e);
99         }
100
101         HttpClient client = getHttpClient(url);
102
103         int httpCode = 0;
104         String respBody = null;
105         try {
106             HttpResponse response = client.execute(post);
107             httpCode = response.getStatusLine().getStatusCode();
108             respBody = IOUtils.toString(response.getEntity().getContent());
109             return new ProviderResponse(httpCode, respBody);
110         } catch (IOException e) {
111             throw new APPCException(e);
112         }
113     }
114
115     /**
116      * Sets the basic authentication header for the given user and password. If either entry is null then set basic auth
117      * to null
118      *
119      * @param user
120      *            The user with optional domain name (for AAF)
121      * @param password
122      *            The password for the user
123      * @return The new value of the basic auth string that will be used in the request headers
124      */
125     public static String setAuthentication(String user, String password) {
126         if (user != null && password != null) {
127             String authStr = user + ":" + password;
128             basic_auth = new String(Base64.encodeBase64(authStr.getBytes()));
129         } else {
130             basic_auth = null;
131         }
132         return basic_auth;
133     }
134
135     @SuppressWarnings("deprecation")
136     private static HttpClient getHttpClient(URL url) throws APPCException {
137         HttpClient client;
138         if (url.getProtocol().equals("https")) {
139             try {
140                 KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
141                 trustStore.load(null, null);
142                 MySSLSocketFactory sf = new MySSLSocketFactory(trustStore);
143                 sf.setHostnameVerifier(MySSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
144
145                 HttpParams params = new BasicHttpParams();
146                 HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
147                 HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
148
149                 SchemeRegistry registry = new SchemeRegistry();
150                 registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
151                 registry.register(new Scheme("https", sf, 443));
152                 registry.register(new Scheme("https", sf, 8443));
153                 registry.register(new Scheme("http", sf, 8181));
154
155                 ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);
156                 client = new DefaultHttpClient(ccm, params);
157             } catch (Exception e) {
158                 client = new DefaultHttpClient();
159             }
160         } else if (url.getProtocol().equals("http")) {
161             client = new DefaultHttpClient();
162         } else {
163             throw new APPCException(
164                 "The provider.topology.url property is invalid. The url did not start with http[s]");
165         }
166         return client;
167     }
168
169     @SuppressWarnings("deprecation")
170     public static class MySSLSocketFactory extends SSLSocketFactory {
171         private SSLContext sslContext = SSLContext.getInstance("TLSv1.2");
172
173         public MySSLSocketFactory(KeyStore truststore) throws NoSuchAlgorithmException, KeyManagementException,
174                         KeyStoreException, UnrecoverableKeyException {
175             super(truststore);
176
177             TrustManager tm = new X509TrustManager() {
178                 @Override
179                 public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
180                 }
181
182                 @Override
183                 public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
184                 }
185
186                 @Override
187                 public X509Certificate[] getAcceptedIssuers() {
188                     return null;
189                 }
190             };
191
192             sslContext.init(null, new TrustManager[] {
193                 tm
194             }, null);
195         }
196
197         @Override
198         public Socket createSocket(Socket socket, String host, int port, boolean autoClose)
199             throws IOException, UnknownHostException {
200             return sslContext.getSocketFactory().createSocket(socket, host, port, autoClose);
201         }
202
203         @Override
204         public Socket createSocket() throws IOException {
205             return sslContext.getSocketFactory().createSocket();
206         }
207     }
208
209 }