Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  package org.safehaus.chop.api;
  
  
  import java.io.File;
 import java.util.Set;
 
 
 
 
 import static org.safehaus.chop.api.Constants.RUNNER_WAR;


General useful utility methods used in the Chop System.
 
 public class ChopUtils {
 
     static {
         System.setProperty"javax.net.ssl.trustStore""jssecacerts" );
     }
 
     private static final Logger LOG = LoggerFactory.getLoggerChopUtils.class );
     private static final char[] HEX_DIGITS = "0123456789abcdef".toCharArray();
     private static final Set<StringtrustedHosts = new HashSet<String>();
     private static final Object lock = new Object();
     private static File certStore;


    
Calculates the testBase: the portion of the key or the path to the test's runner.war but not including it. This usually has the 'tests' container/folder in it followed by the shortened version UUID: for example a project whose war is tests/70a4673b/runner.war will have the testBase of tests/70a4673b/. The last '/' will always be included.

Parameters:
project the project who's testBase to calculate
Returns:
the testBase of the project
Throws:
java.lang.NullPointerException if the project is null or it's loadKey property is null
 
     public static String getTestBaseProject project ) {
         Preconditions.checkNotNullproject"The project cannot be null." );
         return getTestBaseproject.getLoadKey() );
     }


    
Calculates the testBase: the portion of the key or the path to the test's runner.war but not including it. This usually has the 'tests' container/folder in it followed by the shortened version UUID: for example a project whose war is 'tests/70a4673b/runner.war' will have the testBase of tests/70a4673b/. The last '/' will always be included.

Parameters:
loadKey the loadKey of a project: i.e. 'tests/70a4673b/runner.war'
Returns:
the testBase of the project
Throws:
java.lang.NullPointerException if the loadKey is null
 
     public static String getTestBaseString loadKey ) {
         Preconditions.checkNotNullloadKey"The loadKey argument cannot be null." );
         return loadKey.substring( 0, loadKey.length() - .length() );
     }
 
 
     public static boolean isTrustedString hostname ) {
         synchronized (  ) {
             return .containshostname );
         }
     }
 
 
     public static boolean isTrustedRunner runner ) {
         synchronized (  ) {
             return .containsrunner.getHostname() );
         }
    }
    public static boolean isStoreInitialized() {
        return  != null;
    }
    public static void installRunnerKeychar[] passphraseRunner... runners ) throws Exception {
    }
    public static void installRunnerKeychar[] passphraseString... hostnames ) throws Exception {
        if ( passphrase == null ) {
            passphrase = "changeit".toCharArray();
        }
        File file;
        if (  != null ) {
            file = ;
        }
        else {
            file = new File"jssecacerts" );
        }
        if ( ! file.isFile() ) {
            char SEP = .;
            File dir = new File( System.getProperty"java.home" ) + SEP + "lib" + SEP + "security" );
            file = new Filedir"jssecacerts" );
            if ( !file.isFile() ) {
                file = new Filedir"cacerts" );
            }
        }
         = file;
        .debug"Loading KeyStore {}"file );
        InputStream in = new FileInputStreamfile );
        KeyStore ks = KeyStore.getInstance( KeyStore.getDefaultType() );
        ks.loadinpassphrase );
        in.close();
        CertificateFactory cf = CertificateFactory.getInstance"X.509" );
        Certificate cert =  cf.generateCertificategetCertificateStream() );
        for ( String hostname : hostnames ) {
            ks.setCertificateEntryhostnamecert );
            .debug"Added certificate to keystore 'jssecacerts' using alias '" + hostname + "'" );
        }
        OutputStream out = new FileOutputStream"jssecacerts" );
        ks.storeoutpassphrase );
        out.close();
        synchronized (  ) {
            Collections.addAllhostnames );
        }
    }
    private static InputStream getCertificateStream () throws IOException {
        InputStream in = ChopUtils.class.getClassLoader().getResourceAsStream"runner.cer" );
        DataInputStream dis = new DataInputStreamin );
        byte[] bytes = new bytedis.available() ];
        dis.readFullybytes );
        return new ByteArrayInputStreambytes );
    }



    
Installs a certificate from the server into a local certificate store.

Parameters:
host the HTTPS base server host to get the certificate from
port the port of the server
passphrase the passphrase to access/set the cert store if it does not exist, defaults to "changeit" if null is provided
Throws:
java.lang.Exception if something goes wrong
    public static void installCertString hostint portchar[] passphrase ) throws Exception {
        if ( passphrase == null ) {
            passphrase = "changeit".toCharArray();
        }
        File file;
        if (  != null ) {
            file = ;
        }
        else {
            file = new File"jssecacerts" );
        }
        if ( ! file.isFile() ) {
            char SEP = .;
            File dir = new File( System.getProperty"java.home" ) + SEP + "lib" + SEP + "security" );
            file = new Filedir"jssecacerts" );
            if ( !file.isFile() ) {
                file = new Filedir"cacerts" );
            }
        }
         = file;
        .debug"Loading KeyStore {}"file );
        InputStream in = new FileInputStreamfile );
        KeyStore ks = KeyStore.getInstance( KeyStore.getDefaultType() );
        ks.loadinpassphrase );
        in.close();
        SSLContext context = SSLContext.getInstance"TLS" );
        TrustManagerFactory tmf = TrustManagerFactory.getInstance( TrustManagerFactory.getDefaultAlgorithm() );
        tmf.initks );
        X509TrustManager defaultTrustManager = ( X509TrustManager ) tmf.getTrustManagers()[0];
        SavingTrustManager tm = new SavingTrustManagerdefaultTrustManager );
        context.initnullnew TrustManager[] { tm }, null );
        SSLSocketFactory factory = context.getSocketFactory();
        // Try to reconnect in case there are newly launched instances and they're not fully up yet
        SSLSocket socket = null;
        int trial = 0;
        boolean success = false;
        ConnectException connectException = null;
        do {
            try {
                .info"Opening connection to {}:{}"hostport );
                socket = ( SSLSocket ) factory.createSockethostport );
                socket.setSoTimeout( 10000 );
                success = true;
            }
            catch ( ConnectException e ) {
                connectException = e;
                Thread.sleep( 1500 );
            }
        }
        while ( !success && trial++ < 10 );
        if( !success ) {
            throw connectException;
        }
        try {
            .debug"Starting SSL handshake..." );
            socket.startHandshake();
            socket.close();
            .debug"No errors, certificate is already trusted" );
        }
        catch ( SSLException e ) {
            .debug"Cert is NOT trusted: {}"e.getMessage() );
        }
        X509Certificate[] chain = tm.chain;
        if ( chain == null ) {
            .warn"Could not obtain server certificate chain" );
            return;
        }
        .debug"Server sent " + chain.length + " certificate(s):" );
        MessageDigest sha1 = MessageDigest.getInstance"SHA1" );
        MessageDigest md5 = MessageDigest.getInstance"MD5" );
        for ( int i = 0; i < chain.lengthi++ ) {
            X509Certificate cert = chain[i];
            .debug" " + ( i + 1 ) + " Subject " + cert.getSubjectDN() );
            .debug"   Issuer  " + cert.getIssuerDN() );
            sha1.updatecert.getEncoded() );
            .debug"   sha1    " + toHexStringsha1.digest() ) );
            md5.updatecert.getEncoded() );
            .debug"   md5     " + toHexStringmd5.digest() ) );
        }
        int k = 0;
        X509Certificate cert = chain[k];
        // now just using the hostname instead of : String alias = host + "-" + ( k + 1 );
        ks.setCertificateEntryhostcert );
        OutputStream out = new FileOutputStream"jssecacerts" );
        ks.storeoutpassphrase );
        out.close();
        .debug"cert = {}"cert );
        .debug"Added certificate to keystore 'jssecacerts' using alias '" + host + "'" );
    }
    private static String toHexStringbyte[] bytes ) {
        StringBuilder sb = new StringBuilderbytes.length * 3 );
        for ( int b : bytes ) {
            b &= 0xff;
            sb.append[b >> 4] );
            sb.append[b & 15] );
            sb.append' ' );
        }
        return sb.toString();
    }
    private static class SavingTrustManager implements X509TrustManager {
        private final X509TrustManager tm;
        private X509Certificate[] chain;
        SavingTrustManagerX509TrustManager tm ) {
            this. = tm;
        }
        public X509Certificate[] getAcceptedIssuers() {
            throw new UnsupportedOperationException();
        }
        public void checkClientTrustedX509Certificate[] chainString authType ) throws CertificateException {
            throw new UnsupportedOperationException();
        }
        public void checkServerTrustedX509Certificate[] chainString authType ) throws CertificateException {
            this. = chain;
            .checkServerTrustedchainauthType );
        }
    }
New to GrepCode? Check out our FAQ X