/*
 * Copyright 2006 Perry Nguyen <pfnguyen@hanhuy.com>
 * Licensed 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.
 */
import java.io.IOException;
import java.io.InputStream;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Enumeration;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;

public class SIPBTrustManager implements X509TrustManager {
    private X509TrustManager trustManager;
    private final static char[] KEY_STORE_PASSWORD =
        { 'f', 'o', 'o', 'b', 'a', 'r' };
    private final static String KEY_STORE_RESOURCE =
        "trust.store";

    private KeyStore loadKeyStore() throws Exception {
        InputStream in = getClass().getClassLoader().getResourceAsStream(
                KEY_STORE_RESOURCE);
        KeyStore ks = null;
        try {
            if (in == null) {
                //log.severe("Unable to open KeyStore");
                throw new NullPointerException();
            }
            ks = KeyStore.getInstance(KeyStore.getDefaultType());
            ks.load(in, KEY_STORE_PASSWORD);
	    /*if (log.isLoggable(Level.FINEST)) {
                for (Enumeration<String> aliases = ks.aliases();
                aliases.hasMoreElements();) {
                    String alias = aliases.nextElement();
                    log.finest("ALIAS: " + alias);
                }
		}*/
        } catch (NoSuchAlgorithmException e) {
            throwError(e);
        } catch (CertificateException e) {
            throwError(e);
        } catch (IOException e) {
            throwError(e);
        } catch (KeyStoreException e) {
            throwError(e);
        } finally {
            try {
                if (in != null)
                    in.close();
            }
            catch (IOException e) { } // ignore
        }
        return ks;
    }
    private void createTrustManager() {
	try {
	    try {
		KeyStore keystore = loadKeyStore();
		TrustManagerFactory factory = TrustManagerFactory.getInstance(
									      TrustManagerFactory.getDefaultAlgorithm());
		factory.init(keystore);
		TrustManager[] trustManagers = factory.getTrustManagers();
		if (trustManagers.length == 0)
		    throw new IllegalStateException("No trust manager found");
		setTrustManager((X509TrustManager) trustManagers[0]);
	    } catch (NoSuchAlgorithmException e) {
		throwError(e);
	    } catch (KeyStoreException e) {
		throwError(e);
	    }
	} catch (Exception e) {
	    e.printStackTrace();
	}
    }
    private void throwError(Exception e) throws Exception {
        //HttpClientError error = new HttpClientError(e.getMessage());
        //error.initCause(e);
        throw e;
    }
    public X509TrustManager getTrustManager() {
        if (trustManager == null)
            createTrustManager();
        return trustManager;
    }

    public void setTrustManager(X509TrustManager trustManager) {
        this.trustManager = trustManager;
    }

    public void checkClientTrusted(X509Certificate[] chain, String authType)
            throws CertificateException {
        getTrustManager().checkClientTrusted(chain, authType);
    }

    public void checkServerTrusted(X509Certificate[] chain, String authType)
            throws CertificateException {
        getTrustManager().checkServerTrusted(chain, authType);

    }

    public X509Certificate[] getAcceptedIssuers() {
        return getTrustManager().getAcceptedIssuers();
    }

}