import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Properties;

import org.postgresql.Driver;
import org.postgresql.ssl.ValidatingFactory;


/**
 * An example class which makes used of a custom keystore to validate the
 * authenticity of the server.
 * <p>
 * Assuming your server's certificate has been signed by the CA whose 
 * key is located in rootca.crt, then you can create a trust key store
 * by running the following command:
 * 
 *   keytool -import -trustcacerts -file rootca.crt -keystore /home/user/trust.jks
 *   
 * This will create a new keystore with the root certificate only. You'll 
 * need to supply a password.
 * 
 * Then execute this class to see if it works. Note that if the root certificate
 * is in you database directory, then the database server will attempt to 
 * perform client validation, and this class does not support that.
 */
public class ServerValidate {

	/**
	 * @param args
	 */
	public static void main(String[] args) throws Exception {
		// TODO Auto-generated method stub
		Properties props = new Properties();
		// these properties are most likely required, depending on your
		// database set up.
		props.setProperty("user","testuser");
		props.setProperty("password","dbpassword");

		// Indicate that you want SSL.
		props.setProperty("ssl", "true");
		// Specify the Validating factory provided with the patch.
		props.setProperty("sslfactory", ValidatingFactory.class.getName());
		
		// No key manager is required since client authentication is not desired.
		// this option is required for this scenario.
		props.setProperty(ValidatingFactory.SSL_USE_DEFAULT_KEY_MANAGER, "");
		
		// Specify the file which contains the Certificat Authority keys.
		// /home/user/.postgresql/postgresql.jks will be used if this option
		// is not supplied.
		props.setProperty(ValidatingFactory.SSL_TRUSTSTORE_FILE, "/home/user/trust.jks");
		// The password to decrypt the keystore in question. If this is not
		// supplied, then an empty password will be used. I haven't figured out
		// how to create a keystore with no password, so this option is effectively
		// required.
		props.setProperty(ValidatingFactory.SSL_TRUSTSTORE_PASSWORD, "PASSWORD");


		// connect, query, go wild....
		Class c = Driver.class;
		String url = "jdbc:postgresql://host/testdb";
		Connection conn = DriverManager.getConnection(url, props);
	
		Statement st = conn.createStatement();
		ResultSet rs = st.executeQuery("SELECT version();");
		while (rs.next()) {
			System.out.println(rs.getString(1));
		}
		rs.close();
		st.close();
		conn.close();		
	}

}
