import java.io.StringReader;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
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.TrustManager;

import org.dom4j.DocumentException;
import org.dom4j.io.SAXReader;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.filter.HTTPBasicAuthFilter;

/*
 * This sample demonstrates how to connect to QuickBuild server via https protocol.
 * 
 * IMPORTANT: Make sure to check QuickBuild server log if you get exceptions reporting 
 * a 500 response status.
 */
public class HttpsSample {
	public static void main(String[] args) throws DocumentException {
		// skip server certificate validation 
		trustAll();

		Client client = Client.create();
        client.addFilter(new HTTPBasicAuthFilter("admin", "admin"));
        String configurationId = client.resource("https://localhost:9910/rest/ids")
        		.queryParam("configuration_path", "root/test").get(String.class);

        String buildId = client.resource("https://localhost:9910/rest/ids")
        		.queryParam("build_name", configurationId + ":latest_successful").get(String.class);

        String buildXML = client.resource("https://localhost:9910/rest/builds/" + buildId).get(String.class);
        String buildVersion = new SAXReader().read(new StringReader(buildXML))
		        .getRootElement().elementTextTrim("version");
		System.out.println("Latest successful build in configuration 'root/test' is '" + 
				buildVersion + "'.");
	}
	
	private static void trustAll() {
	    TrustManager[] trustAllCerts = new TrustManager[1];
	    trustAllCerts[0] = new TrustAllManager();

	    SSLContext sc;
		try {
			sc = javax.net.ssl.SSLContext.getInstance("SSL");
			sc.init(null, trustAllCerts, null);
		} catch (KeyManagementException e) {
			throw new RuntimeException(e);
		} catch (NoSuchAlgorithmException e) {
			throw new RuntimeException(e);
		}
	    HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

	    HostnameVerifier hv = new HostnameVerifier() {
			
	        public boolean verify(String urlHostName, SSLSession session) {
	            return true;
	        }
	        
	    };
	    HttpsURLConnection.setDefaultHostnameVerifier(hv);
	}
	
	public static class TrustAllManager implements javax.net.ssl.TrustManager,
			javax.net.ssl.X509TrustManager {
		public X509Certificate[] getAcceptedIssuers() {
			return null;
		}
		
		public boolean isServerTrusted(X509Certificate[] certs) {
			return true;
		}
		
		public boolean isClientTrusted(X509Certificate[] certs) {
			return true;
		}
		
		public void checkServerTrusted(X509Certificate[] certs, String authType)
				throws java.security.cert.CertificateException {
			return;
		}
		
		public void checkClientTrusted(X509Certificate[] certs, String authType)
				throws java.security.cert.CertificateException {
			return;
		}
	}

}
