@ -202,6 +202,38 @@ public class MongoProperties {
public MongoClient createMongoClient ( MongoClientOptions options ,
Environment environment ) throws UnknownHostException {
try {
Integer embeddedPort = getEmbeddedPort ( environment ) ;
if ( embeddedPort ! = null ) {
return createEmbeddedMongoClient ( options , embeddedPort ) ;
}
return createNetworkMongoClient ( options ) ;
}
finally {
clearPassword ( ) ;
}
}
private Integer getEmbeddedPort ( Environment environment ) {
if ( environment ! = null ) {
String localPort = environment . getProperty ( "local.mongo.port" ) ;
if ( localPort ! = null ) {
return Integer . valueOf ( localPort ) ;
}
}
return null ;
}
private MongoClient createEmbeddedMongoClient ( MongoClientOptions options , int port ) {
if ( options = = null ) {
options = MongoClientOptions . builder ( ) . build ( ) ;
}
String host = this . host = = null ? "localhost" : this . host ;
return new MongoClient (
Collections . singletonList ( new ServerAddress ( host , port ) ) ,
Collections . < MongoCredential > emptyList ( ) , options ) ;
}
private MongoClient createNetworkMongoClient ( MongoClientOptions options ) {
if ( hasCustomAddress ( ) | | hasCustomCredentials ( ) ) {
if ( this . uri ! = null ) {
throw new IllegalStateException ( "Invalid mongo configuration, "
@ -218,7 +250,7 @@ public class MongoProperties {
database , this . password ) ) ;
}
String host = this . host = = null ? "localhost" : this . host ;
int port = determinePort ( environment ) ;
int port = this . port ! = null ? this . port : DEFAULT_PORT ;
return new MongoClient (
Collections . singletonList ( new ServerAddress ( host , port ) ) ,
credentials , options ) ;
@ -226,10 +258,6 @@ public class MongoProperties {
// The options and credentials are in the URI
return new MongoClient ( new MongoClientURI ( determineUri ( ) , builder ( options ) ) ) ;
}
finally {
clearPassword ( ) ;
}
}
private boolean hasCustomAddress ( ) {
return this . host ! = null | | this . port ! = null ;
@ -239,24 +267,6 @@ public class MongoProperties {
return this . username ! = null & & this . password ! = null ;
}
private int determinePort ( Environment environment ) {
if ( this . port = = null ) {
return DEFAULT_PORT ;
}
if ( this . port = = 0 ) {
if ( environment ! = null ) {
String localPort = environment . getProperty ( "local.mongo.port" ) ;
if ( localPort ! = null ) {
return Integer . valueOf ( localPort ) ;
}
}
throw new IllegalStateException (
"spring.data.mongodb.port=0 and no local mongo port configuration "
+ "is available" ) ;
}
return this . port ;
}
private Builder builder ( MongoClientOptions options ) {
if ( options ! = null ) {
return MongoClientOptions . builder ( options ) ;