2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017-2018 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
13 * http://www.apache.org/licenses/LICENSE-2.0
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.
21 * ============LICENSE_END=========================================================
24 package org.onap.appc.listener.demo.impl;
26 import java.io.IOException;
27 import java.io.UnsupportedEncodingException;
28 import java.net.MalformedURLException;
29 import java.net.Socket;
31 import java.net.UnknownHostException;
32 import java.security.KeyManagementException;
33 import java.security.KeyStore;
34 import java.security.KeyStoreException;
35 import java.security.NoSuchAlgorithmException;
36 import java.security.UnrecoverableKeyException;
37 import java.security.cert.CertificateException;
38 import java.security.cert.X509Certificate;
40 import javax.net.ssl.SSLContext;
41 import javax.net.ssl.TrustManager;
42 import javax.net.ssl.X509TrustManager;
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.json.JSONObject;
63 import org.onap.appc.exceptions.APPCException;
64 import org.onap.appc.listener.demo.model.IncomingMessage;
65 import org.onap.appc.listener.util.Mapper;
67 import com.att.eelf.configuration.EELFLogger;
68 import com.att.eelf.configuration.EELFManager;
70 public class ProviderOperations {
72 private static final EELFLogger LOG = EELFManager.getInstance().getLogger(ProviderOperations.class);
74 private static URL url;
76 private static String basic_auth;
79 @SuppressWarnings("nls")
80 private final static String TEMPLATE = "{\"input\": {\"common-request-header\": {\"service-request-id\": \"%s\"},\"config-payload\": {\"config-url\": \"%s\",\"config-json\":\"%s\"}}}";
84 * Calls the AppcProvider to run a topology directed graph
87 * The incoming message to be run
88 * @return True if the result is success. Never returns false and throws an exception instead.
89 * @throws UnsupportedEncodingException
91 * if there was a failure processing the request. The exception message is the failure reason.
93 @SuppressWarnings("nls")
94 public static boolean topologyDG(IncomingMessage msg) throws APPCException {
96 throw new APPCException("Provided message was null");
101 // Concatenate the "action" on the end of the URL
102 String path = url.getPath() + ":" + msg.getAction().getValue();
103 URL serviceUrl = new URL(url.getProtocol(), url.getHost(), url.getPort(), path);
105 post = new HttpPost(serviceUrl.toExternalForm());
106 post.setHeader("Content-Type", "application/json");
107 post.setHeader("Accept", "application/json");
110 if (basic_auth != null) {
111 post.setHeader("Authorization", "Basic " + basic_auth);
114 //String body = buildReqest(msg.getId(), msg.getUrl(), msg.getIdentityUrl());
115 String body = buildReqest(msg.getHeader().getRequestID(), msg.getPayload().getGenericVnfId(), msg.getPayload().getPgStreams());
116 StringEntity entity = new StringEntity(body);
117 entity.setContentType("application/json");
118 post.setEntity(new StringEntity(body));
119 } catch (UnsupportedEncodingException | MalformedURLException e) {
120 throw new APPCException(e);
123 HttpClient client = getHttpClient();
126 String respBody = null;
128 HttpResponse response = client.execute(post);
129 httpCode = response.getStatusLine().getStatusCode();
130 respBody = IOUtils.toString(response.getEntity().getContent());
131 } catch (IOException e) {
132 throw new APPCException(e);
135 if (httpCode == 200 && respBody != null) {
138 json = Mapper.toJsonObject(respBody);
139 } catch (Exception e) {
140 LOG.error("Error prcoessing response from provider. Could not map response to json", e);
141 throw new APPCException("APPC has an unknown RPC error");
146 JSONObject header = json.getJSONObject("output").getJSONObject("common-response-header");
147 success = header.getBoolean("success");
148 reason = header.getString("reason");
149 } catch (Exception e) {
150 LOG.error("Unknown error prcoessing failed response from provider. Json not in expected format", e);
151 throw new APPCException("APPC has an unknown RPC error");
156 String reasonStr = reason == null ? "Unknown" : reason;
157 LOG.warn(String.format("Topology Operation [%s] failed. Reason: %s", msg.getHeader().getRequestID(), reasonStr));
158 throw new APPCException(reasonStr);
161 throw new APPCException(String.format("Unexpected response from endpoint: [%d] - %s ", httpCode, respBody));
165 * Updates the static var URL and returns the value;
167 * @return The new value of URL
169 public static String getUrl() {
170 return url.toExternalForm();
173 public static void setUrl(String newUrl) {
175 url = new URL(newUrl);
176 } catch (MalformedURLException e) {
182 * Sets the basic authentication header for the given user and password. If either entry is null then set basic auth
186 * The user with optional domain name
188 * The password for the user
189 * @return The new value of the basic auth string that will be used in the request headers
191 public static String setAuthentication(String user, String password) {
192 if (user != null && password != null) {
193 String authStr = user + ":" + password;
194 basic_auth = new String(Base64.encodeBase64(authStr.getBytes()));
202 * Builds the request body for a topology operation
210 * The streams to send to the traffic generator
212 * @return A String containing the request body
214 private static String buildReqest(String id, String url, String pgstreams) {
216 return String.format(TEMPLATE, id, url, pgstreams);
219 @SuppressWarnings("deprecation")
220 private static HttpClient getHttpClient() throws APPCException {
222 if (url.getProtocol().equals("https")) {
224 KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
225 trustStore.load(null, null);
226 MySSLSocketFactory sf = new MySSLSocketFactory(trustStore);
227 sf.setHostnameVerifier(MySSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
229 HttpParams params = new BasicHttpParams();
230 HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
231 HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
233 SchemeRegistry registry = new SchemeRegistry();
234 registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
235 registry.register(new Scheme("https", sf, 443));
236 registry.register(new Scheme("https", sf, 8443));
237 registry.register(new Scheme("http", sf, 8181));
239 ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);
240 client = new DefaultHttpClient(ccm, params);
241 } catch (Exception e) {
242 client = new DefaultHttpClient();
244 } else if (url.getProtocol().equals("http")) {
245 client = new DefaultHttpClient();
247 throw new APPCException(
248 "The provider.topology.url property is invalid. The url did not start with http[s]");
253 @SuppressWarnings("deprecation")
254 public static class MySSLSocketFactory extends SSLSocketFactory {
255 private SSLContext sslContext = SSLContext.getInstance("TLS");
257 public MySSLSocketFactory(KeyStore truststore) throws NoSuchAlgorithmException, KeyManagementException,
258 KeyStoreException, UnrecoverableKeyException {
261 TrustManager tm = new X509TrustManager() {
263 public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
267 public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
271 public X509Certificate[] getAcceptedIssuers() {
276 sslContext.init(null, new TrustManager[] {
282 public Socket createSocket(Socket socket, String host, int port, boolean autoClose)
283 throws IOException, UnknownHostException {
284 return sslContext.getSocketFactory().createSocket(socket, host, port, autoClose);
288 public Socket createSocket() throws IOException {
289 return sslContext.getSocketFactory().createSocket();