private static boolean validateMongoConnection ( ExternalTestService mongoService ) { String method = "validateMongoConnection" ; MongoClient mongoClient = null ; String host = mongoService . getAddress ( ) ; int port = mongoService . getPort ( ) ; File trustStore = null ; MongoClientOptions . Builder optionsBuilder = new MongoClientOptions . Builder ( ) . connectTimeout ( 30000 ) ; try { trustStore = File . createTempFile ( "mongoTrustStore" , "jks" ) ; Map < String , String > serviceProperties = mongoService . getProperties ( ) ; String password = serviceProperties . get ( TEST_USERNAME + "_password" ) ; // will be null if there's no auth for this server SSLSocketFactory sslSocketFactory = null ; try { mongoService . writePropertyAsFile ( "ca_truststore" , trustStore ) ; sslSocketFactory = getSocketFactory ( trustStore ) ; } catch ( IllegalStateException e ) { // Ignore exception thrown if truststore is not present for this server // This indicates that we are not using SSL for this server and sslSocketFactory will be null } if ( sslSocketFactory != null ) { optionsBuilder . socketFactory ( sslSocketFactory ) ; } MongoClientOptions clientOptions = optionsBuilder . build ( ) ; List < MongoCredential > credentials = Collections . emptyList ( ) ; if ( password != null ) { MongoCredential credential = MongoCredential . createCredential ( TEST_USERNAME , TEST_DATABASE , password . toCharArray ( ) ) ; credentials = Collections . singletonList ( credential ) ; } Log . info ( c , method , "Attempting to contact server " + host + ":" + port + " with password " + ( password != null ? "set" : "not set" ) + " and truststore " + ( sslSocketFactory != null ? "set" : "not set" ) ) ; mongoClient = new MongoClient ( new ServerAddress ( host , port ) , credentials , clientOptions ) ; mongoClient . getDB ( "default" ) . getCollectionNames ( ) ; mongoClient . close ( ) ; } catch ( Exception e ) { Log . info ( c , method , "Couldn't create a connection to " + mongoService . getServiceName ( ) + " on " + mongoService . getAddress ( ) + ". " + e . toString ( ) ) ; mongoService . reportUnhealthy ( "Couldn't connect to server. Exception: " + e . toString ( ) ) ; return false ; } finally { if ( trustStore != null ) { trustStore . delete ( ) ; } } return true ; }
Creates a connection to the mongo server at the given location using the mongo java client .