2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017 AT&T Intellectual Property. All rights
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=========================================================
22 package org.openecomp.appc.listener.demo.impl;
24 import java.io.IOException;
25 import java.io.UnsupportedEncodingException;
26 import java.net.MalformedURLException;
27 import java.net.Socket;
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;
38 import javax.net.ssl.SSLContext;
39 import javax.net.ssl.TrustManager;
40 import javax.net.ssl.X509TrustManager;
42 import org.apache.commons.codec.binary.Base64;
43 import org.apache.commons.io.IOUtils;
44 import org.apache.http.HttpResponse;
45 import org.apache.http.HttpVersion;
46 import org.apache.http.client.HttpClient;
47 import org.apache.http.client.methods.HttpPost;
48 import org.apache.http.conn.ClientConnectionManager;
49 import org.apache.http.conn.scheme.PlainSocketFactory;
50 import org.apache.http.conn.scheme.Scheme;
51 import org.apache.http.conn.scheme.SchemeRegistry;
52 import org.apache.http.conn.ssl.SSLSocketFactory;
53 import org.apache.http.entity.StringEntity;
54 import org.apache.http.impl.client.DefaultHttpClient;
55 import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
56 import org.apache.http.params.BasicHttpParams;
57 import org.apache.http.params.HttpParams;
58 import org.apache.http.params.HttpProtocolParams;
59 import org.apache.http.protocol.HTTP;
60 import org.json.JSONObject;
61 import org.openecomp.appc.exceptions.APPCException;
62 import org.openecomp.appc.listener.demo.model.IncomingMessage;
63 import org.openecomp.appc.listener.util.Mapper;
65 import com.att.eelf.configuration.EELFLogger;
66 import com.att.eelf.configuration.EELFManager;
68 public class ProviderOperations {
70 private static final EELFLogger LOG = EELFManager.getInstance().getLogger(ProviderOperations.class);
72 private static URL url;
74 private static String basic_auth;
77 @SuppressWarnings("nls")
78 private final static String TEMPLATE = "{\"input\": {\"common-request-header\": {\"service-request-id\": \"%s\"},\"config-payload\": {\"config-url\": \"%s\",\"config-json\":\"%s\"}}}";
82 * Calls the AppcProvider to run a topology directed graph
85 * The incoming message to be run
86 * @return True if the result is success. Never returns false and throws an exception instead.
87 * @throws UnsupportedEncodingException
89 * if there was a failure processing the request. The exception message is the failure reason.
91 @SuppressWarnings("nls")
92 public static boolean topologyDG(IncomingMessage msg) throws APPCException {
94 throw new APPCException("Provided message was null");
99 // Concatenate the "action" on the end of the URL
100 String path = url.getPath() + ":" + msg.getAction().getValue();
101 URL serviceUrl = new URL(url.getProtocol(), url.getHost(), url.getPort(), path);
103 post = new HttpPost(serviceUrl.toExternalForm());
104 post.setHeader("Content-Type", "application/json");
105 post.setHeader("Accept", "application/json");
108 if (basic_auth != null) {
109 post.setHeader("Authorization", "Basic " + basic_auth);
112 //String body = buildReqest(msg.getId(), msg.getUrl(), msg.getIdentityUrl());
113 String body = buildReqest(msg.getHeader().getRequestID(), msg.getPayload().getGenericVnfId(), msg.getPayload().getPgStreams());
114 StringEntity entity = new StringEntity(body);
115 entity.setContentType("application/json");
116 post.setEntity(new StringEntity(body));
117 } catch (UnsupportedEncodingException | MalformedURLException e) {
118 throw new APPCException(e);
121 HttpClient client = getHttpClient();
124 String respBody = null;
126 HttpResponse response = client.execute(post);
127 httpCode = response.getStatusLine().getStatusCode();
128 respBody = IOUtils.toString(response.getEntity().getContent());
129 } catch (IOException e) {
130 throw new APPCException(e);
133 if (httpCode == 200 && respBody != null) {
136 json = Mapper.toJsonObject(respBody);
137 } catch (Exception e) {
138 LOG.error("Error prcoessing response from provider. Could not map response to json", e);
139 throw new APPCException("APPC has an unknown RPC error");
144 JSONObject header = json.getJSONObject("output").getJSONObject("common-response-header");
145 success = header.getBoolean("success");
146 reason = header.getString("reason");
147 } catch (Exception e) {
148 LOG.error("Unknown error prcoessing failed response from provider. Json not in expected format", e);
149 throw new APPCException("APPC has an unknown RPC error");
154 String reasonStr = reason == null ? "Unknown" : reason;
155 LOG.warn(String.format("Topology Operation [%s] failed. Reason: %s", msg.getHeader().getRequestID(), reasonStr));
156 throw new APPCException(reasonStr);
159 throw new APPCException(String.format("Unexpected response from endpoint: [%d] - %s ", httpCode, respBody));
163 * Updates the static var URL and returns the value;
165 * @return The new value of URL
167 public static String getUrl() {
168 return url.toExternalForm();
171 public static void setUrl(String newUrl) {
173 url = new URL(newUrl);
174 } catch (MalformedURLException e) {
180 * Sets the basic authentication header for the given user and password. If either entry is null then set basic auth
184 * The user with optional domain name
186 * The password for the user
187 * @return The new value of the basic auth string that will be used in the request headers
189 public static String setAuthentication(String user, String password) {
190 if (user != null && password != null) {
191 String authStr = user + ":" + password;
192 basic_auth = new String(Base64.encodeBase64(authStr.getBytes()));
200 * Builds the request body for a topology operation
208 * The streams to send to the traffic generator
210 * @return A String containing the request body
212 private static String buildReqest(String id, String url, String pgstreams) {
214 return String.format(TEMPLATE, id, url, pgstreams);
217 @SuppressWarnings("deprecation")
218 private static HttpClient getHttpClient() throws APPCException {
220 if (url.getProtocol().equals("https")) {
222 KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
223 trustStore.load(null, null);
224 MySSLSocketFactory sf = new MySSLSocketFactory(trustStore);
225 sf.setHostnameVerifier(MySSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
227 HttpParams params = new BasicHttpParams();
228 HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
229 HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
231 SchemeRegistry registry = new SchemeRegistry();
232 registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
233 registry.register(new Scheme("https", sf, 443));
234 registry.register(new Scheme("https", sf, 8443));
235 registry.register(new Scheme("http", sf, 8181));
237 ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);
238 client = new DefaultHttpClient(ccm, params);
239 } catch (Exception e) {
240 client = new DefaultHttpClient();
242 } else if (url.getProtocol().equals("http")) {
243 client = new DefaultHttpClient();
245 throw new APPCException(
246 "The provider.topology.url property is invalid. The url did not start with http[s]");
251 @SuppressWarnings("deprecation")
252 public static class MySSLSocketFactory extends SSLSocketFactory {
253 private SSLContext sslContext = SSLContext.getInstance("TLS");
255 public MySSLSocketFactory(KeyStore truststore) throws NoSuchAlgorithmException, KeyManagementException,
256 KeyStoreException, UnrecoverableKeyException {
259 TrustManager tm = new X509TrustManager() {
261 public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
265 public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
269 public X509Certificate[] getAcceptedIssuers() {
274 sslContext.init(null, new TrustManager[] {
280 public Socket createSocket(Socket socket, String host, int port, boolean autoClose)
281 throws IOException, UnknownHostException {
282 return sslContext.getSocketFactory().createSocket(socket, host, port, autoClose);
286 public Socket createSocket() throws IOException {
287 return sslContext.getSocketFactory().createSocket();