2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017 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 * ECOMP is a trademark and service mark of AT&T Intellectual Property.
22 * ============LICENSE_END=========================================================
25 package org.onap.appc.listener.LCM.operation;
27 import com.att.eelf.configuration.EELFLogger;
28 import com.att.eelf.configuration.EELFManager;
29 import com.fasterxml.jackson.databind.JsonNode;
30 import java.io.IOException;
31 import java.io.UnsupportedEncodingException;
32 import java.net.MalformedURLException;
33 import java.net.Socket;
35 import java.security.KeyManagementException;
36 import java.security.KeyStore;
37 import java.security.KeyStoreException;
38 import java.security.NoSuchAlgorithmException;
39 import java.security.UnrecoverableKeyException;
40 import java.security.cert.CertificateException;
41 import java.security.cert.X509Certificate;
42 import javax.net.ssl.SSLContext;
43 import javax.net.ssl.TrustManager;
44 import javax.net.ssl.X509TrustManager;
45 import org.apache.commons.codec.binary.Base64;
46 import org.apache.commons.io.IOUtils;
47 import org.apache.http.HttpHeaders;
48 import org.apache.http.HttpResponse;
49 import org.apache.http.HttpVersion;
50 import org.apache.http.client.HttpClient;
51 import org.apache.http.client.methods.HttpPost;
52 import org.apache.http.conn.ClientConnectionManager;
53 import org.apache.http.conn.scheme.PlainSocketFactory;
54 import org.apache.http.conn.scheme.Scheme;
55 import org.apache.http.conn.scheme.SchemeRegistry;
56 import org.apache.http.conn.ssl.SSLSocketFactory;
57 import org.apache.http.entity.StringEntity;
58 import org.apache.http.impl.client.DefaultHttpClient;
59 import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
60 import org.apache.http.params.BasicHttpParams;
61 import org.apache.http.params.HttpParams;
62 import org.apache.http.params.HttpProtocolParams;
63 import org.apache.http.protocol.HTTP;
64 import org.onap.appc.exceptions.APPCException;
65 import org.onap.appc.listener.LCM.model.ResponseStatus;
66 import org.onap.appc.listener.util.Mapper;
68 public class ProviderOperations {
70 private final EELFLogger LOG = EELFManager.getInstance().getLogger(ProviderOperations.class);
73 private String basicAuth;
75 private static ProviderOperationRequestFormatter requestFormatter = new GenericProviderOperationRequestFormatter();
78 public ProviderOperations(String url, String username, String password){
79 setAuthentication(username, password);
81 this.url = new URL(url);
82 } catch (MalformedURLException e) {
83 LOG.error("An error occurred while building url", e);
88 * Calls the AppcProvider to run a topology directed graph
90 * @param message The incoming message to be run
91 * @return True if the result is success. Never returns false and throws an exception instead.
92 * @throws UnsupportedEncodingException
93 * @throws Exception if there was a failure processing the request. The exception message is the failure reason.
95 @SuppressWarnings("nls")
96 public JsonNode topologyDG(String rpcName, JsonNode message) throws APPCException {
97 if (message == null) {
98 throw new APPCException("Provided message was null");
101 HttpPost postRequest = buildPostRequest(rpcName, message);
102 return getJsonNode(message, postRequest);
105 private HttpPost buildPostRequest(String rpcName, JsonNode message) throws APPCException {
109 // Concatenate the "action" on the end of the URL
110 String path = requestFormatter.buildPath(url, rpcName);
111 URL serviceUrl = new URL(url.getProtocol(), url.getHost(), url.getPort(), path);
113 post = new HttpPost(serviceUrl.toExternalForm());
114 post.setHeader(HttpHeaders.CONTENT_TYPE, "application/json");
115 post.setHeader(HttpHeaders.ACCEPT, "application/json");
118 if (basicAuth != null) {
119 post.setHeader(HttpHeaders.AUTHORIZATION, "Basic " + basicAuth);
122 String body = Mapper.toJsonString(message);
123 StringEntity entity = new StringEntity(body);
124 entity.setContentType("application/json");
125 post.setEntity(entity);
126 } catch (UnsupportedEncodingException | MalformedURLException e) {
127 throw new APPCException(e);
132 private JsonNode getJsonNode(JsonNode message, HttpPost post) throws APPCException {
133 HttpClient client = getHttpClient();
138 HttpResponse response = client.execute(post);
139 httpCode = response.getStatusLine().getStatusCode();
140 respBody = IOUtils.toString(response.getEntity().getContent());
141 } catch (IOException e) {
142 throw new APPCException(e);
145 if (httpCode >= 200 && httpCode < 300 && respBody != null) {
148 json = Mapper.toJsonNodeFromJsonString(respBody);
149 } catch (Exception e) {
150 LOG.error("Error processing response from provider. Could not map response to json", e);
151 throw new APPCException("APPC has an unknown RPC error");
153 ResponseStatus responseStatus = requestFormatter.getResponseStatus(json);
154 if (!isSucceeded(responseStatus.getCode())) {
155 LOG.warn(String.format("Operation failed [%s]", message.toString()));
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 String getUrl() {
168 return url.toExternalForm();
171 public void setUrl(String newUrl) {
173 url = new URL(newUrl);
174 } catch (MalformedURLException e) {
175 LOG.error("An error occurred while building url", e);
180 * Sets the basic authentication header for the given user and password. If either entry is null then set basic auth
183 * @param user The user with optional domain name
184 * @param password The password for the user
185 * @return The new value of the basic auth string that will be used in the request headers
187 public String setAuthentication(String user, String password) {
188 if (user != null && password != null) {
189 String authStr = user + ":" + password;
190 basicAuth = new String(Base64.encodeBase64(authStr.getBytes()));
197 @SuppressWarnings("deprecation")
198 private HttpClient getHttpClient() throws APPCException {
200 switch (url.getProtocol()) {
203 KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
204 trustStore.load(null, null);
205 MySSLSocketFactory sf = new MySSLSocketFactory(trustStore);
206 sf.setHostnameVerifier(MySSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
208 HttpParams params = new BasicHttpParams();
209 HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
210 HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
212 SchemeRegistry registry = new SchemeRegistry();
213 registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
214 registry.register(new Scheme("https", sf, 443));
215 registry.register(new Scheme("https", sf, 8443));
216 registry.register(new Scheme("http", sf, 8181));
218 ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);
219 client = new DefaultHttpClient(ccm, params);
220 } catch (Exception e) {
221 client = new DefaultHttpClient();
225 client = new DefaultHttpClient();
228 throw new APPCException(
229 "The provider.topology.url property is invalid. The url did not start with http[s]");
234 @SuppressWarnings("deprecation")
235 public static class MySSLSocketFactory extends SSLSocketFactory {
236 private SSLContext sslContext = SSLContext.getInstance("TLS");
238 public MySSLSocketFactory(KeyStore truststore) throws NoSuchAlgorithmException, KeyManagementException,
239 KeyStoreException, UnrecoverableKeyException {
242 TrustManager tm = new X509TrustManager() {
244 public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
248 public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
252 public X509Certificate[] getAcceptedIssuers() {
257 sslContext.init(null, new TrustManager[]{
263 public Socket createSocket(Socket socket, String host, int port, boolean autoClose)
265 return sslContext.getSocketFactory().createSocket(socket, host, port, autoClose);
269 public Socket createSocket() throws IOException {
270 return sslContext.getSocketFactory().createSocket();
274 public static boolean isSucceeded(Integer code) {
276 //FIXME is it working as intended?
277 return code != null && ((code == 100) || (code == 400));