Change nexus values to properties
[appc.git] / appc-asdc-listener / appc-asdc-listener-bundle / src / main / java / org / openecomp / appc / sdc / listener / ProviderOperations.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * openECOMP : APP-C
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights
6  *                                              reserved.
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  */
21
22 package org.openecomp.appc.sdc.listener;
23
24 import java.io.IOException;
25 import java.io.UnsupportedEncodingException;
26 import java.net.Socket;
27 import java.net.URL;
28 import java.net.UnknownHostException;
29 import java.security.KeyManagementException;
30 import java.security.KeyStore;
31 import java.security.KeyStoreException;
32 import java.security.NoSuchAlgorithmException;
33 import java.security.UnrecoverableKeyException;
34 import java.security.cert.CertificateException;
35 import java.security.cert.X509Certificate;
36 import java.util.Map;
37 import java.util.Map.Entry;
38
39 import javax.net.ssl.SSLContext;
40 import javax.net.ssl.TrustManager;
41 import javax.net.ssl.X509TrustManager;
42
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.openecomp.appc.exceptions.APPCException;
62 import com.att.eelf.configuration.EELFLogger;
63 import com.att.eelf.configuration.EELFManager;
64
65 public class ProviderOperations {
66
67     private static final EELFLogger LOG = EELFManager.getInstance().getLogger(ProviderOperations.class);
68
69     private static String basic_auth;
70
71     public static ProviderResponse post(URL url, String json, Map<String, String> adtl_headers) throws APPCException {
72         if (json == null) {
73             throw new APPCException("Provided message was null");
74         }
75
76         HttpPost post = null;
77         try {
78             post = new HttpPost(url.toExternalForm());
79             post.setHeader("Content-Type", "application/json");
80             post.setHeader("Accept", "application/json");
81
82             // Set Auth
83             if (basic_auth != null) {
84                 post.setHeader("Authorization", "Basic " + basic_auth);
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 then set basic auth
116      * to null
117      *
118      * @param user
119      *            The user with optional domain name (for AAF)
120      * @param password
121      *            The password for the user
122      * @return The new value of the basic auth string that will be used in the request headers
123      */
124     public static String setAuthentication(String user, String password) {
125         if (user != null && password != null) {
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     @SuppressWarnings("deprecation")
135     private static HttpClient getHttpClient(URL url) throws APPCException {
136         HttpClient client;
137         if (url.getProtocol().equals("https")) {
138             try {
139                 KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
140                 trustStore.load(null, null);
141                 MySSLSocketFactory sf = new MySSLSocketFactory(trustStore);
142                 sf.setHostnameVerifier(MySSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
143
144                 HttpParams params = new BasicHttpParams();
145                 HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
146                 HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
147
148                 SchemeRegistry registry = new SchemeRegistry();
149                 registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
150                 registry.register(new Scheme("https", sf, 443));
151                 registry.register(new Scheme("https", sf, 8443));
152                 registry.register(new Scheme("http", sf, 8181));
153
154                 ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);
155                 client = new DefaultHttpClient(ccm, params);
156             } catch (Exception e) {
157                 client = new DefaultHttpClient();
158             }
159         } else if (url.getProtocol().equals("http")) {
160             client = new DefaultHttpClient();
161         } else {
162             throw new APPCException(
163                 "The provider.topology.url property is invalid. The url did not start with http[s]");
164         }
165         return client;
166     }
167
168     @SuppressWarnings("deprecation")
169     public static class MySSLSocketFactory extends SSLSocketFactory {
170         private SSLContext sslContext = SSLContext.getInstance("TLSv1.2");
171
172         public MySSLSocketFactory(KeyStore truststore) throws NoSuchAlgorithmException, KeyManagementException,
173                         KeyStoreException, UnrecoverableKeyException {
174             super(truststore);
175
176             TrustManager tm = new X509TrustManager() {
177                 @Override
178                 public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
179                 }
180
181                 @Override
182                 public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
183                 }
184
185                 @Override
186                 public X509Certificate[] getAcceptedIssuers() {
187                     return null;
188                 }
189             };
190
191             sslContext.init(null, new TrustManager[] {
192                 tm
193             }, null);
194         }
195
196         @Override
197         public Socket createSocket(Socket socket, String host, int port, boolean autoClose)
198             throws IOException, UnknownHostException {
199             return sslContext.getSocketFactory().createSocket(socket, host, port, autoClose);
200         }
201
202         @Override
203         public Socket createSocket() throws IOException {
204             return sslContext.getSocketFactory().createSocket();
205         }
206     }
207
208 }