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.LCM.operation;
 
  24 import com.fasterxml.jackson.databind.JsonNode;
 
  25 import org.apache.commons.codec.binary.Base64;
 
  26 import org.apache.commons.io.IOUtils;
 
  27 import org.apache.http.HttpHeaders;
 
  28 import org.apache.http.HttpResponse;
 
  29 import org.apache.http.HttpVersion;
 
  30 import org.apache.http.client.HttpClient;
 
  31 import org.apache.http.client.methods.HttpPost;
 
  32 import org.apache.http.conn.ClientConnectionManager;
 
  33 import org.apache.http.conn.scheme.PlainSocketFactory;
 
  34 import org.apache.http.conn.scheme.Scheme;
 
  35 import org.apache.http.conn.scheme.SchemeRegistry;
 
  36 import org.apache.http.conn.ssl.SSLSocketFactory;
 
  37 import org.apache.http.entity.StringEntity;
 
  38 import org.apache.http.impl.client.DefaultHttpClient;
 
  39 import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
 
  40 import org.apache.http.params.BasicHttpParams;
 
  41 import org.apache.http.params.HttpParams;
 
  42 import org.apache.http.params.HttpProtocolParams;
 
  43 import org.apache.http.protocol.HTTP;
 
  44 import org.openecomp.appc.exceptions.APPCException;
 
  45 import org.openecomp.appc.listener.LCM.model.ResponseStatus;
 
  46 import org.openecomp.appc.listener.util.Mapper;
 
  48 import com.att.eelf.configuration.EELFLogger;
 
  49 import com.att.eelf.configuration.EELFManager;
 
  51 import javax.net.ssl.SSLContext;
 
  52 import javax.net.ssl.TrustManager;
 
  53 import javax.net.ssl.X509TrustManager;
 
  54 import java.io.IOException;
 
  55 import java.io.UnsupportedEncodingException;
 
  56 import java.net.MalformedURLException;
 
  57 import java.net.Socket;
 
  59 import java.net.UnknownHostException;
 
  60 import java.security.*;
 
  61 import java.security.cert.CertificateException;
 
  62 import java.security.cert.X509Certificate;
 
  64 public class ProviderOperations {
 
  66     private static final EELFLogger LOG = EELFManager.getInstance().getLogger(ProviderOperations.class);
 
  68     private static URL url;
 
  69     private static String basic_auth;
 
  71     private static ProviderOperationRequestFormatter requestFormatter = new GenericProviderOperationRequestFormatter();
 
  74      * Calls the AppcProvider to run a topology directed graph
 
  76      * @param msg The incoming message to be run
 
  77      * @return True if the result is success. Never returns false and throws an exception instead.
 
  78      * @throws UnsupportedEncodingException
 
  79      * @throws Exception                    if there was a failure processing the request. The exception message is the failure reason.
 
  81     @SuppressWarnings("nls")
 
  82     public static JsonNode topologyDG(String rpcName, JsonNode msg) throws APPCException {
 
  84             throw new APPCException("Provided message was null");
 
  90             // Concatenate the "action" on the end of the URL
 
  91             String path = requestFormatter.buildPath(url, rpcName);
 
  92             URL serviceUrl = new URL(url.getProtocol(), url.getHost(), url.getPort(), path);
 
  94             post = new HttpPost(serviceUrl.toExternalForm());
 
  95             post.setHeader(HttpHeaders.CONTENT_TYPE, "application/json");
 
  96             post.setHeader(HttpHeaders.ACCEPT, "application/json");
 
  99             if (basic_auth != null) {
 
 100                 post.setHeader(HttpHeaders.AUTHORIZATION, "Basic " + basic_auth);
 
 103             String body = Mapper.toJsonString(msg);
 
 104             StringEntity entity = new StringEntity(body);
 
 105             entity.setContentType("application/json");
 
 106             post.setEntity(new StringEntity(body));
 
 107         } catch (UnsupportedEncodingException | MalformedURLException e) {
 
 108             throw new APPCException(e);
 
 111         HttpClient client = getHttpClient();
 
 114         String respBody = null;
 
 116             HttpResponse response = client.execute(post);
 
 117             httpCode = response.getStatusLine().getStatusCode();
 
 118             respBody = IOUtils.toString(response.getEntity().getContent());
 
 119         } catch (IOException e) {
 
 120             throw new APPCException(e);
 
 123         if (httpCode >= 200 && httpCode < 300 && respBody != null) {
 
 126                 json = Mapper.toJsonNodeFromJsonString(respBody);
 
 127             } catch (Exception e) {
 
 128                 LOG.error("Error processing response from provider. Could not map response to json", e);
 
 129                 throw new APPCException("APPC has an unknown RPC error");
 
 132             ResponseStatus responseStatus = requestFormatter.getResponseStatus(json);
 
 134             if (!isSucceeded(responseStatus.getCode())) {
 
 135                 LOG.warn(String.format("Operation failed [%s]", msg.toString()));
 
 141         throw new APPCException(String.format("Unexpected response from endpoint: [%d] - %s ", httpCode, respBody));
 
 145      * Updates the static var URL and returns the value;
 
 147      * @return The new value of URL
 
 149     public static String getUrl() {
 
 150         return url.toExternalForm();
 
 153     public static void setUrl(String newUrl) {
 
 155             url = new URL(newUrl);
 
 156         } catch (MalformedURLException e) {
 
 162      * Sets the basic authentication header for the given user and password. If either entry is null then set basic auth
 
 165      * @param user     The user with optional domain name
 
 166      * @param password The password for the user
 
 167      * @return The new value of the basic auth string that will be used in the request headers
 
 169     public static String setAuthentication(String user, String password) {
 
 170         if (user != null && password != null) {
 
 171             String authStr = user + ":" + password;
 
 172             basic_auth = new String(Base64.encodeBase64(authStr.getBytes()));
 
 179     @SuppressWarnings("deprecation")
 
 180     private static HttpClient getHttpClient() throws APPCException {
 
 182         if (url.getProtocol().equals("https")) {
 
 184                 KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
 
 185                 trustStore.load(null, null);
 
 186                 MySSLSocketFactory sf = new MySSLSocketFactory(trustStore);
 
 187                 sf.setHostnameVerifier(MySSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
 
 189                 HttpParams params = new BasicHttpParams();
 
 190                 HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
 
 191                 HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
 
 193                 SchemeRegistry registry = new SchemeRegistry();
 
 194                 registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
 
 195                 registry.register(new Scheme("https", sf, 443));
 
 196                 registry.register(new Scheme("https", sf, 8443));
 
 197                 registry.register(new Scheme("http", sf, 8181));
 
 199                 ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);
 
 200                 client = new DefaultHttpClient(ccm, params);
 
 201             } catch (Exception e) {
 
 202                 client = new DefaultHttpClient();
 
 204         } else if (url.getProtocol().equals("http")) {
 
 205             client = new DefaultHttpClient();
 
 207             throw new APPCException(
 
 208                     "The provider.topology.url property is invalid. The url did not start with http[s]");
 
 213     @SuppressWarnings("deprecation")
 
 214     public static class MySSLSocketFactory extends SSLSocketFactory {
 
 215         private SSLContext sslContext = SSLContext.getInstance("TLS");
 
 217         public MySSLSocketFactory(KeyStore truststore) throws NoSuchAlgorithmException, KeyManagementException,
 
 218                 KeyStoreException, UnrecoverableKeyException {
 
 221             TrustManager tm = new X509TrustManager() {
 
 223                 public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
 
 227                 public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
 
 231                 public X509Certificate[] getAcceptedIssuers() {
 
 236             sslContext.init(null, new TrustManager[]{
 
 242         public Socket createSocket(Socket socket, String host, int port, boolean autoClose)
 
 243                 throws IOException, UnknownHostException {
 
 244             return sslContext.getSocketFactory().createSocket(socket, host, port, autoClose);
 
 248         public Socket createSocket() throws IOException {
 
 249             return sslContext.getSocketFactory().createSocket();
 
 253     public static boolean isSucceeded(Integer code) {
 
 257         return ((code == 100) || (code == 400)); // only 100 & 400 statuses are success