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.LCM.operation;
26 import com.att.eelf.configuration.EELFLogger;
27 import com.att.eelf.configuration.EELFManager;
28 import com.fasterxml.jackson.databind.JsonNode;
29 import java.io.IOException;
30 import java.io.UnsupportedEncodingException;
31 import java.net.MalformedURLException;
32 import java.net.Socket;
34 import java.security.KeyManagementException;
35 import java.security.KeyStore;
36 import java.security.KeyStoreException;
37 import java.security.NoSuchAlgorithmException;
38 import java.security.UnrecoverableKeyException;
39 import java.security.cert.CertificateException;
40 import java.security.cert.X509Certificate;
41 import javax.net.ssl.SSLContext;
42 import javax.net.ssl.TrustManager;
43 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.HttpHeaders;
47 import org.apache.http.HttpResponse;
48 import org.apache.http.HttpVersion;
49 import org.apache.http.client.HttpClient;
50 import org.apache.http.client.methods.HttpPost;
51 import org.apache.http.conn.ClientConnectionManager;
52 import org.apache.http.conn.scheme.PlainSocketFactory;
53 import org.apache.http.conn.scheme.Scheme;
54 import org.apache.http.conn.scheme.SchemeRegistry;
55 import org.apache.http.conn.ssl.SSLSocketFactory;
56 import org.apache.http.entity.StringEntity;
57 import org.apache.http.impl.client.DefaultHttpClient;
58 import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
59 import org.apache.http.params.BasicHttpParams;
60 import org.apache.http.params.HttpParams;
61 import org.apache.http.params.HttpProtocolParams;
62 import org.apache.http.protocol.HTTP;
63 import org.onap.appc.exceptions.APPCException;
64 import org.onap.appc.listener.LCM.model.ResponseStatus;
65 import org.onap.appc.listener.util.Mapper;
67 public class ProviderOperations {
69 private final EELFLogger LOG = EELFManager.getInstance().getLogger(ProviderOperations.class);
72 private String basicAuth;
74 private static ProviderOperationRequestFormatter requestFormatter = new GenericProviderOperationRequestFormatter();
77 public ProviderOperations(String url, String username, String password){
78 setAuthentication(username, password);
80 this.url = new URL(url);
81 } catch (MalformedURLException e) {
82 LOG.error("An error occurred while building url", e);
87 * Calls the AppcProvider to run a topology directed graph
89 * @param message The incoming message to be run
90 * @return True if the result is success. Never returns false and throws an exception instead.
91 * @throws UnsupportedEncodingException
92 * @throws Exception if there was a failure processing the request. The exception message is the failure reason.
94 @SuppressWarnings("nls")
95 public JsonNode topologyDG(String rpcName, JsonNode message) throws APPCException {
96 if (message == null) {
97 throw new APPCException("Provided message was null");
100 HttpPost postRequest = buildPostRequest(rpcName, message);
101 return getJsonNode(message, postRequest);
104 private HttpPost buildPostRequest(String rpcName, JsonNode message) throws APPCException {
108 // Concatenate the "action" on the end of the URL
109 String path = requestFormatter.buildPath(url, rpcName);
110 URL serviceUrl = new URL(url.getProtocol(), url.getHost(), url.getPort(), path);
112 post = new HttpPost(serviceUrl.toExternalForm());
113 post.setHeader(HttpHeaders.CONTENT_TYPE, "application/json");
114 post.setHeader(HttpHeaders.ACCEPT, "application/json");
117 if (basicAuth != null) {
118 post.setHeader(HttpHeaders.AUTHORIZATION, "Basic " + basicAuth);
121 String body = Mapper.toJsonString(message);
122 StringEntity entity = new StringEntity(body);
123 entity.setContentType("application/json");
124 post.setEntity(entity);
125 } catch (UnsupportedEncodingException | MalformedURLException e) {
126 throw new APPCException(e);
131 private JsonNode getJsonNode(JsonNode message, HttpPost post) throws APPCException {
132 HttpClient client = getHttpClient();
137 HttpResponse response = client.execute(post);
138 httpCode = response.getStatusLine().getStatusCode();
139 respBody = IOUtils.toString(response.getEntity().getContent());
140 } catch (IOException e) {
141 throw new APPCException(e);
144 if (httpCode >= 200 && httpCode < 300 && respBody != null) {
147 json = Mapper.toJsonNodeFromJsonString(respBody);
148 } catch (Exception e) {
149 LOG.error("Error processing response from provider. Could not map response to json", e);
150 throw new APPCException("APPC has an unknown RPC error");
152 ResponseStatus responseStatus = requestFormatter.getResponseStatus(json);
153 if (!isSucceeded(responseStatus.getCode())) {
154 LOG.warn(String.format("Operation failed [%s]", message.toString()));
158 throw new APPCException(String.format("Unexpected response from endpoint: [%d] - %s ", httpCode, respBody));
162 * Updates the static var URL and returns the value;
164 * @return The new value of URL
166 public String getUrl() {
167 return url.toExternalForm();
170 public void setUrl(String newUrl) {
172 url = new URL(newUrl);
173 } catch (MalformedURLException e) {
174 LOG.error("An error occurred while building url", e);
179 * Sets the basic authentication header for the given user and password. If either entry is null then set basic auth
182 * @param user The user with optional domain name
183 * @param password The password for the user
184 * @return The new value of the basic auth string that will be used in the request headers
186 public String setAuthentication(String user, String password) {
187 if (user != null && password != null) {
188 String authStr = user + ":" + password;
189 basicAuth = new String(Base64.encodeBase64(authStr.getBytes()));
196 @SuppressWarnings("deprecation")
197 private HttpClient getHttpClient() throws APPCException {
199 switch (url.getProtocol()) {
202 KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
203 trustStore.load(null, null);
204 MySSLSocketFactory sf = new MySSLSocketFactory(trustStore);
205 sf.setHostnameVerifier(MySSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
207 HttpParams params = new BasicHttpParams();
208 HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
209 HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
211 SchemeRegistry registry = new SchemeRegistry();
212 registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
213 registry.register(new Scheme("https", sf, 443));
214 registry.register(new Scheme("https", sf, 8443));
215 registry.register(new Scheme("http", sf, 8181));
217 ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);
218 client = new DefaultHttpClient(ccm, params);
219 } catch (Exception e) {
220 client = new DefaultHttpClient();
224 client = new DefaultHttpClient();
227 throw new APPCException(
228 "The provider.topology.url property is invalid. The url did not start with http[s]");
233 @SuppressWarnings("deprecation")
234 public static class MySSLSocketFactory extends SSLSocketFactory {
235 private SSLContext sslContext = SSLContext.getInstance("TLS");
237 public MySSLSocketFactory(KeyStore truststore) throws NoSuchAlgorithmException, KeyManagementException,
238 KeyStoreException, UnrecoverableKeyException {
241 TrustManager tm = new X509TrustManager() {
243 public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
247 public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
251 public X509Certificate[] getAcceptedIssuers() {
256 sslContext.init(null, new TrustManager[]{
262 public Socket createSocket(Socket socket, String host, int port, boolean autoClose)
264 return sslContext.getSocketFactory().createSocket(socket, host, port, autoClose);
268 public Socket createSocket() throws IOException {
269 return sslContext.getSocketFactory().createSocket();
273 public static boolean isSucceeded(Integer code) {
275 //FIXME is it working as intended?
276 return code != null && ((code == 100) || (code == 400));