2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
6 * ================================================================================
7 * Copyright (C) 2017 Amdocs
8 * ================================================================================
9 * Modifications Copyright (C) 2019 Ericsson
10 * =============================================================================
11 * Licensed under the Apache License, Version 2.0 (the "License");
12 * you may not use this file except in compliance with the License.
13 * You may obtain a copy of the License at
15 * http://www.apache.org/licenses/LICENSE-2.0
17 * Unless required by applicable law or agreed to in writing, software
18 * distributed under the License is distributed on an "AS IS" BASIS,
19 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20 * See the License for the specific language governing permissions and
21 * limitations under the License.
23 * ============LICENSE_END=========================================================
26 package org.onap.appc.listener.LCM.operation;
28 import com.att.eelf.configuration.EELFLogger;
29 import com.att.eelf.configuration.EELFManager;
30 import com.fasterxml.jackson.databind.JsonNode;
31 import java.io.IOException;
32 import java.io.UnsupportedEncodingException;
33 import java.net.MalformedURLException;
34 import java.net.Socket;
36 import java.security.KeyManagementException;
37 import java.security.KeyStore;
38 import java.security.KeyStoreException;
39 import java.security.NoSuchAlgorithmException;
40 import java.security.UnrecoverableKeyException;
41 import java.security.cert.CertificateException;
42 import java.security.cert.X509Certificate;
43 import javax.net.ssl.SSLContext;
44 import javax.net.ssl.TrustManager;
45 import javax.net.ssl.X509TrustManager;
46 import org.apache.commons.codec.binary.Base64;
47 import org.apache.commons.io.IOUtils;
48 import org.apache.http.HttpHeaders;
49 import org.apache.http.HttpResponse;
50 import org.apache.http.HttpVersion;
51 import org.apache.http.client.HttpClient;
52 import org.apache.http.client.methods.HttpPost;
53 import org.apache.http.conn.ClientConnectionManager;
54 import org.apache.http.conn.scheme.PlainSocketFactory;
55 import org.apache.http.conn.scheme.Scheme;
56 import org.apache.http.conn.scheme.SchemeRegistry;
57 import org.apache.http.conn.ssl.SSLSocketFactory;
58 import org.apache.http.entity.StringEntity;
59 import org.apache.http.impl.client.DefaultHttpClient;
60 import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
61 import org.apache.http.params.BasicHttpParams;
62 import org.apache.http.params.HttpParams;
63 import org.apache.http.params.HttpProtocolParams;
64 import org.apache.http.protocol.HTTP;
65 import org.onap.appc.exceptions.APPCException;
66 import org.onap.appc.listener.LCM.model.ResponseStatus;
67 import org.onap.appc.listener.util.Mapper;
69 public class ProviderOperations {
71 private final EELFLogger LOG = EELFManager.getInstance().getLogger(ProviderOperations.class);
74 private String basicAuth;
76 private static ProviderOperationRequestFormatter requestFormatter = new GenericProviderOperationRequestFormatter();
79 public ProviderOperations(String url, String username, String password){
80 setAuthentication(username, password);
82 this.url = new URL(url);
83 } catch (MalformedURLException e) {
84 LOG.error("An error occurred while building url", e);
89 * Calls the AppcProvider to run a topology directed graph
91 * @param message The incoming message to be run
92 * @return True if the result is success. Never returns false and throws an exception instead.
93 * @throws UnsupportedEncodingException
94 * @throws Exception if there was a failure processing the request. The exception message is the failure reason.
96 @SuppressWarnings("nls")
97 public JsonNode topologyDG(String rpcName, JsonNode message) throws APPCException {
98 if (message == null) {
99 throw new APPCException("Provided message was null");
102 HttpPost postRequest = buildPostRequest(rpcName, message);
103 return getJsonNode(message, postRequest);
106 private HttpPost buildPostRequest(String rpcName, JsonNode message) throws APPCException {
110 // Concatenate the "action" on the end of the URL
111 String path = requestFormatter.buildPath(url, rpcName);
112 URL serviceUrl = new URL(url.getProtocol(), url.getHost(), url.getPort(), path);
114 post = new HttpPost(serviceUrl.toExternalForm());
115 post.setHeader(HttpHeaders.CONTENT_TYPE, "application/json");
116 post.setHeader(HttpHeaders.ACCEPT, "application/json");
119 if (basicAuth != null) {
120 post.setHeader(HttpHeaders.AUTHORIZATION, "Basic " + basicAuth);
123 String body = Mapper.toJsonString(message);
124 StringEntity entity = new StringEntity(body);
125 entity.setContentType("application/json");
126 post.setEntity(entity);
127 } catch (UnsupportedEncodingException | MalformedURLException e) {
128 throw new APPCException(e);
133 private JsonNode getJsonNode(JsonNode message, HttpPost post) throws APPCException {
134 HttpClient client = getHttpClient();
139 HttpResponse response = client.execute(post);
140 httpCode = response.getStatusLine().getStatusCode();
141 respBody = IOUtils.toString(response.getEntity().getContent());
142 } catch (IOException e) {
143 throw new APPCException(e);
146 if (httpCode >= 200 && httpCode < 300 && respBody != null) {
149 json = Mapper.toJsonNodeFromJsonString(respBody);
150 } catch (Exception e) {
151 LOG.error("Error processing response from provider. Could not map response to json", e);
152 throw new APPCException("APPC has an unknown RPC error");
154 ResponseStatus responseStatus = requestFormatter.getResponseStatus(json);
155 if (!isSucceeded(responseStatus.getCode())) {
156 LOG.warn(String.format("Operation failed [%s]", message.toString()));
160 throw new APPCException(String.format("Unexpected response from endpoint: [%d] - %s ", httpCode, respBody));
164 * Updates the static var URL and returns the value;
166 * @return The new value of URL
168 public String getUrl() {
169 return url.toExternalForm();
172 public void setUrl(String newUrl) {
174 url = new URL(newUrl);
175 } catch (MalformedURLException e) {
176 LOG.error("An error occurred while building url", e);
181 * Sets the basic authentication header for the given user and password. If either entry is null then set basic auth
184 * @param user The user with optional domain name
185 * @param password The password for the user
186 * @return The new value of the basic auth string that will be used in the request headers
188 public String setAuthentication(String user, String password) {
189 if (user != null && password != null) {
190 String authStr = user + ":" + password;
191 basicAuth = new String(Base64.encodeBase64(authStr.getBytes()));
198 @SuppressWarnings("deprecation")
199 protected HttpClient getHttpClient() throws APPCException {
201 switch (url.getProtocol()) {
204 KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
205 trustStore.load(null, null);
206 MySSLSocketFactory sf = new MySSLSocketFactory(trustStore);
207 sf.setHostnameVerifier(MySSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
209 HttpParams params = new BasicHttpParams();
210 HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
211 HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
213 SchemeRegistry registry = new SchemeRegistry();
214 registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
215 registry.register(new Scheme("https", sf, 443));
216 registry.register(new Scheme("https", sf, 8443));
217 registry.register(new Scheme("http", sf, 8181));
219 ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);
220 client = new DefaultHttpClient(ccm, params);
221 } catch (Exception e) {
222 LOG.error("Error getting HTTP Client", e);
223 client = new DefaultHttpClient();
227 client = new DefaultHttpClient();
230 throw new APPCException(
231 "The provider.topology.url property is invalid. The url did not start with http[s]");
236 @SuppressWarnings("deprecation")
237 public static class MySSLSocketFactory extends SSLSocketFactory {
238 private SSLContext sslContext = SSLContext.getInstance("TLS");
240 public MySSLSocketFactory(KeyStore truststore) throws NoSuchAlgorithmException, KeyManagementException,
241 KeyStoreException, UnrecoverableKeyException {
244 TrustManager tm = new X509TrustManager() {
246 public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
250 public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
254 public X509Certificate[] getAcceptedIssuers() {
259 sslContext.init(null, new TrustManager[]{
265 public Socket createSocket(Socket socket, String host, int port, boolean autoClose)
267 return sslContext.getSocketFactory().createSocket(socket, host, port, autoClose);
271 public Socket createSocket() throws IOException {
272 return sslContext.getSocketFactory().createSocket();
276 public static boolean isSucceeded(Integer code) {
278 //FIXME is it working as intended?
279 return code != null && ((code == 100) || (code == 400));