2 * ============LICENSE_START=======================================================
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
12 * http://www.apache.org/licenses/LICENSE-2.0
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.
23 package org.openecomp.appc.listener.LCM.operation;
25 import com.fasterxml.jackson.databind.JsonNode;
26 import org.apache.commons.codec.binary.Base64;
27 import org.apache.commons.io.IOUtils;
28 import org.apache.http.HttpHeaders;
29 import org.apache.http.HttpResponse;
30 import org.apache.http.HttpVersion;
31 import org.apache.http.client.HttpClient;
32 import org.apache.http.client.methods.HttpPost;
33 import org.apache.http.conn.ClientConnectionManager;
34 import org.apache.http.conn.scheme.PlainSocketFactory;
35 import org.apache.http.conn.scheme.Scheme;
36 import org.apache.http.conn.scheme.SchemeRegistry;
37 import org.apache.http.conn.ssl.SSLSocketFactory;
38 import org.apache.http.entity.StringEntity;
39 import org.apache.http.impl.client.DefaultHttpClient;
40 import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
41 import org.apache.http.params.BasicHttpParams;
42 import org.apache.http.params.HttpParams;
43 import org.apache.http.params.HttpProtocolParams;
44 import org.apache.http.protocol.HTTP;
45 import org.openecomp.appc.exceptions.APPCException;
46 import org.openecomp.appc.listener.LCM.model.ResponseStatus;
47 import org.openecomp.appc.listener.util.Mapper;
49 import com.att.eelf.configuration.EELFLogger;
50 import com.att.eelf.configuration.EELFManager;
52 import javax.net.ssl.SSLContext;
53 import javax.net.ssl.TrustManager;
54 import javax.net.ssl.X509TrustManager;
55 import java.io.IOException;
56 import java.io.UnsupportedEncodingException;
57 import java.net.MalformedURLException;
58 import java.net.Socket;
60 import java.net.UnknownHostException;
61 import java.security.*;
62 import java.security.cert.CertificateException;
63 import java.security.cert.X509Certificate;
65 public class ProviderOperations {
67 private static final EELFLogger LOG = EELFManager.getInstance().getLogger(ProviderOperations.class);
70 private String basic_auth;
72 private static ProviderOperationRequestFormatter requestFormatter = new GenericProviderOperationRequestFormatter();
75 * Calls the AppcProvider to run a topology directed graph
77 * @param msg The incoming message to be run
78 * @return True if the result is success. Never returns false and throws an exception instead.
79 * @throws UnsupportedEncodingException
80 * @throws Exception if there was a failure processing the request. The exception message is the failure reason.
82 @SuppressWarnings("nls")
83 public JsonNode topologyDG(String rpcName, JsonNode msg) throws APPCException {
85 throw new APPCException("Provided message was null");
91 // Concatenate the "action" on the end of the URL
92 String path = requestFormatter.buildPath(url, rpcName);
93 URL serviceUrl = new URL(url.getProtocol(), url.getHost(), url.getPort(), path);
95 post = new HttpPost(serviceUrl.toExternalForm());
96 post.setHeader(HttpHeaders.CONTENT_TYPE, "application/json");
97 post.setHeader(HttpHeaders.ACCEPT, "application/json");
100 if (basic_auth != null) {
101 post.setHeader(HttpHeaders.AUTHORIZATION, "Basic " + basic_auth);
104 String body = Mapper.toJsonString(msg);
105 StringEntity entity = new StringEntity(body);
106 entity.setContentType("application/json");
107 post.setEntity(new StringEntity(body));
108 } catch (UnsupportedEncodingException | MalformedURLException e) {
109 throw new APPCException(e);
112 HttpClient client = getHttpClient();
115 String respBody = null;
117 HttpResponse response = client.execute(post);
118 httpCode = response.getStatusLine().getStatusCode();
119 respBody = IOUtils.toString(response.getEntity().getContent());
120 } catch (IOException e) {
121 throw new APPCException(e);
124 if (httpCode >= 200 && httpCode < 300 && respBody != null) {
127 json = Mapper.toJsonNodeFromJsonString(respBody);
128 } catch (Exception e) {
129 LOG.error("Error processing response from provider. Could not map response to json", e);
130 throw new APPCException("APPC has an unknown RPC error");
133 ResponseStatus responseStatus = requestFormatter.getResponseStatus(json);
135 if (!isSucceeded(responseStatus.getCode())) {
136 LOG.warn(String.format("Operation failed [%s]", msg.toString()));
142 throw new APPCException(String.format("Unexpected response from endpoint: [%d] - %s ", httpCode, respBody));
146 * Updates the static var URL and returns the value;
148 * @return The new value of URL
150 public String getUrl() {
151 return url.toExternalForm();
154 public void setUrl(String newUrl) {
156 url = new URL(newUrl);
157 } catch (MalformedURLException e) {
163 * Sets the basic authentication header for the given user and password. If either entry is null then set basic auth
166 * @param user The user with optional domain name
167 * @param password The password for the user
168 * @return The new value of the basic auth string that will be used in the request headers
170 public String setAuthentication(String user, String password) {
171 if (user != null && password != null) {
172 String authStr = user + ":" + password;
173 basic_auth = new String(Base64.encodeBase64(authStr.getBytes()));
180 @SuppressWarnings("deprecation")
181 private HttpClient getHttpClient() throws APPCException {
183 if (url.getProtocol().equals("https")) {
185 KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
186 trustStore.load(null, null);
187 MySSLSocketFactory sf = new MySSLSocketFactory(trustStore);
188 sf.setHostnameVerifier(MySSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
190 HttpParams params = new BasicHttpParams();
191 HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
192 HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
194 SchemeRegistry registry = new SchemeRegistry();
195 registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
196 registry.register(new Scheme("https", sf, 443));
197 registry.register(new Scheme("https", sf, 8443));
198 registry.register(new Scheme("http", sf, 8181));
200 ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);
201 client = new DefaultHttpClient(ccm, params);
202 } catch (Exception e) {
203 client = new DefaultHttpClient();
205 } else if (url.getProtocol().equals("http")) {
206 client = new DefaultHttpClient();
208 throw new APPCException(
209 "The provider.topology.url property is invalid. The url did not start with http[s]");
214 @SuppressWarnings("deprecation")
215 public static class MySSLSocketFactory extends SSLSocketFactory {
216 private SSLContext sslContext = SSLContext.getInstance("TLS");
218 public MySSLSocketFactory(KeyStore truststore) throws NoSuchAlgorithmException, KeyManagementException,
219 KeyStoreException, UnrecoverableKeyException {
222 TrustManager tm = new X509TrustManager() {
224 public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
228 public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
232 public X509Certificate[] getAcceptedIssuers() {
237 sslContext.init(null, new TrustManager[]{
243 public Socket createSocket(Socket socket, String host, int port, boolean autoClose)
244 throws IOException, UnknownHostException {
245 return sslContext.getSocketFactory().createSocket(socket, host, port, autoClose);
249 public Socket createSocket() throws IOException {
250 return sslContext.getSocketFactory().createSocket();
254 public static boolean isSucceeded(Integer code) {
258 return ((code == 100) || (code == 400)); // only 100 & 400 statuses are success