org.apache.hadoop.io.crypto.bee.RestClient.java Source code

Java tutorial

Introduction

Here is the source code for org.apache.hadoop.io.crypto.bee.RestClient.java

Source

/**
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.apache.hadoop.io.crypto.bee;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.URL;
import java.net.URLConnection;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class RestClient {
    private static final Log LOG = LogFactory.getLog(RestClient.class);
    private URL url = null;

    public RestClient(URL url) {
        URL newUrl = null;
        try {
            String host = InetAddress.getByName(url.getHost()).getCanonicalHostName();
            if (!host.isEmpty() && host.compareTo(url.getHost()) != 0) {
                newUrl = new URL(url.getProtocol() + "://" + host + ":" + url.getPort() + url.getPath());
            }
        } catch (Exception e) {
            LOG.warn("Fail to get the FQDN for host" + url.getHost() + ":" + e.getMessage());
        }

        if (newUrl == null) {
            this.url = url;
        } else {
            this.url = newUrl;
        }
    }

    private boolean isHttpsCertificateEnabled() {
        if (new File(BeeConstants.BEE_HTTPS_CERTIFICATE_DEFAULT_PATH).exists()) {
            return true;
        }

        return false;
    }

    private InputStream httpsWithCertificate(final URL url) throws KeyStoreException, NoSuchAlgorithmException,
            CertificateException, IOException, KeyManagementException {
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null);// Make an empty store

        CertificateFactory cf = CertificateFactory.getInstance("X.509");

        FileInputStream fis = new FileInputStream(BeeConstants.BEE_HTTPS_CERTIFICATE_DEFAULT_PATH);
        BufferedInputStream bis = new BufferedInputStream(fis);
        while (bis.available() > 0) {
            Certificate cert = cf.generateCertificate(bis);
            // System.out.println(cert.getPublicKey().toString());
            trustStore.setCertificateEntry("jetty" + bis.available(), cert);
        }

        TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(trustStore);
        SSLContext ctx = SSLContext.getInstance("TLS");
        ctx.init(null, tmf.getTrustManagers(), null);
        SSLSocketFactory sslFactory = ctx.getSocketFactory();

        // Create all-trusting host name verifier
        HostnameVerifier allHostsValid = new HostnameVerifier() {
            @Override
            public boolean verify(String hostname, SSLSession session) {
                if (0 == hostname.compareToIgnoreCase(url.getHost())) {
                    return true;
                }
                return false;
            }
        };
        // Install the all-trusting host verifier
        HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);

        HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection();
        urlConnection.setSSLSocketFactory(sslFactory);

        return urlConnection.getInputStream();
    }

    private InputStream httpsIgnoreCertificate(final URL url) throws IOException {
        // Create a trust manager that does not validate certificate chains
        TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }

            public void checkClientTrusted(X509Certificate[] certs, String authType) {
            }

            public void checkServerTrusted(X509Certificate[] certs, String authType) {
            }
        } };

        // Create all-trusting host name verifier
        HostnameVerifier allHostsValid = new HostnameVerifier() {
            @Override
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        };

        // Install the all-trusting host verifier
        HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);

        try {
            SSLContext sc = SSLContext.getInstance("TLS");
            sc.init(null, trustAllCerts, new SecureRandom());
            HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
        } catch (Exception e) {
            ;
        }

        HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection();
        return urlConnection.getInputStream();

    }

    public StringBuffer getResult() throws Exception {
        InputStream is = null;
        InputStreamReader isr = null;
        try {
            LOG.info("Try to establish connection to " + url.toString());
            if ("https".compareTo(url.getProtocol()) == 0) {
                if (this.isHttpsCertificateEnabled()) {
                    is = this.httpsWithCertificate(url);
                } else {
                    is = httpsIgnoreCertificate(url);
                }

            } else {
                URLConnection urlConnection = url.openConnection();
                is = urlConnection.getInputStream();
            }

            isr = new InputStreamReader(is);
            StringBuffer sb = new StringBuffer();
            int numCharsRead;
            char[] charArray = new char[1024];
            while ((numCharsRead = isr.read(charArray)) > 0) {
                sb.append(charArray, 0, numCharsRead);
            }

            return sb;

        } finally {
            if (isr != null)
                isr.close();
        }

    }
}