Example usage for com.mongodb MongoClientURI MongoClientURI

List of usage examples for com.mongodb MongoClientURI MongoClientURI

Introduction

In this page you can find the example usage for com.mongodb MongoClientURI MongoClientURI.

Prototype

public MongoClientURI(final String uri, final MongoClientOptions.Builder builder) 

Source Link

Document

Creates a MongoURI from the given URI string, and MongoClientOptions.Builder.

Usage

From source file:org.jooby.mongodb.Mongodb.java

License:Apache License

protected void configure(final Env env, final Config config, final Binder binder,
        final BiConsumer<MongoClientURI, MongoClient> callback) {
    MongoClientOptions.Builder options = options(mongodb(config));

    if (this.options != null) {
        this.options.accept(options, config);
    }//from  w w w .  ja va2 s . c  o  m

    MongoClientURI uri = new MongoClientURI(config.getString(db), options);
    String database = uri.getDatabase();
    checkArgument(database != null, "Database not found: " + uri);
    MongoClient client = new MongoClient(uri);

    ServiceKey serviceKey = env.serviceKey();
    serviceKey.generate(MongoClientURI.class, database, k -> binder.bind(k).toInstance(uri));

    serviceKey.generate(MongoClient.class, database, k -> binder.bind(k).toInstance(client));

    MongoDatabase mongodb = client.getDatabase(database);
    serviceKey.generate(MongoDatabase.class, database, k -> binder.bind(k).toInstance(mongodb));

    env.onStop(client::close);

    callback.accept(uri, client);
}

From source file:org.mule.module.mongo.MongoCloudConnector.java

License:Open Source License

private MongoClientURI getMongoClientURI(final String username, final String password, final String database) {
    List<String> hostsWithPort = new LinkedList<String>();
    for (String hostname : host.split(",\\s?")) {
        hostsWithPort.add(hostname + ":" + port);
    }//w  w w.j  av  a 2s  .com
    return new MongoClientURI(MongoURI.MONGODB_PREFIX +
    //                        username + ":" + password + "@" +
            StringUtils.join(hostsWithPort, ",") + "/" + database, getMongoOptions(database));
}

From source file:org.nuxeo.directory.mongodb.MongoDBConnectionHelper.java

License:Apache License

/**
 * Initialize a connection to the MongoDB server
 *
 * @param server the server url//  w ww. j  av  a  2 s.co m
 * @return the MongoDB client
 */
public static MongoClient newMongoClient(String server) {
    if (StringUtils.isBlank(server)) {
        throw new NuxeoException("Missing <server> in MongoDB repository descriptor");
    }
    MongoClientOptions.Builder optionsBuilder = MongoClientOptions.builder()
            // Can help to prevent firewall disconnects
            // inactive connection, option not available from URI
            .socketKeepAlive(true)
            // don't wait for ever by default,
            // can be overridden using URI options
            .connectTimeout(MONGODB_OPTION_CONNECTION_TIMEOUT_MS)
            .socketTimeout(MONGODB_OPTION_SOCKET_TIMEOUT_MS).description("Nuxeo");
    MongoClient client;
    if (server.startsWith("mongodb://")) {
        // allow mongodb:// URI syntax for the server, to pass everything in one string
        client = new MongoClient(new MongoClientURI(server, optionsBuilder));
    } else {
        client = new MongoClient(new ServerAddress(server), optionsBuilder.build());
    }
    if (log.isDebugEnabled()) {
        log.debug("MongoClient initialized with options: " + client.getMongoClientOptions().toString());
    }
    return client;
}

From source file:org.nuxeo.ecm.core.storage.mongodb.MongoDBChecker.java

License:Apache License

@Override
public void check(ConfigurationGenerator cg) throws ConfigurationException {
    MongoClient ret = null;//from   www  .j a  va2  s. c o m
    String serverName = cg.getUserConfig().getProperty(ConfigurationGenerator.PARAM_MONGODB_SERVER);
    String dbName = cg.getUserConfig().getProperty(ConfigurationGenerator.PARAM_MONGODB_NAME);

    MongoClientOptions.Builder optionsBuilder = MongoClientOptions.builder()
            .serverSelectionTimeout((int) TimeUnit.SECONDS.toMillis(1)).description("Nuxeo DB Check");
    if (serverName.startsWith("mongodb://")) {
        // allow mongodb:// URI syntax for the server, to pass everything in one string
        ret = new MongoClient(new MongoClientURI(serverName, optionsBuilder));
    } else {
        ret = new MongoClient(new ServerAddress(serverName), optionsBuilder.build());
    }
    try {
        Document ping = new Document("ping", "1");
        ret.getDatabase(dbName).runCommand(ping);
    } catch (MongoTimeoutException e) {
        throw new ConfigurationException(
                String.format("Unable to connect to MongoDB at %s, please check your connection", serverName));
    } finally {
        ret.close();
    }
}

From source file:org.nuxeo.ecm.core.storage.mongodb.MongoDBRepository.java

License:Apache License

public static MongoClient newMongoClient(MongoDBRepositoryDescriptor descriptor) throws UnknownHostException {
    MongoClient ret;// ww  w  .j av a2 s.  co m
    String server = descriptor.server;
    if (StringUtils.isBlank(server)) {
        throw new NuxeoException("Missing <server> in MongoDB repository descriptor");
    }
    MongoClientOptions.Builder optionsBuilder = MongoClientOptions.builder()
            // Can help to prevent firewall disconnects inactive connection, option not available from URI
            .socketKeepAlive(true)
            // don't wait for ever by default, can be overridden using URI options
            .connectTimeout(MONGODB_OPTION_CONNECTION_TIMEOUT_MS)
            .socketTimeout(MONGODB_OPTION_SOCKET_TIMEOUT_MS).description("Nuxeo");
    if (server.startsWith("mongodb://")) {
        // allow mongodb:// URI syntax for the server, to pass everything in one string
        ret = new MongoClient(new MongoClientURI(server, optionsBuilder));
    } else {
        ret = new MongoClient(new ServerAddress(server), optionsBuilder.build());
    }
    if (log.isDebugEnabled()) {
        log.debug("MongoClient initialized with options: " + ret.getMongoClientOptions().toString());
    }
    return ret;
}

From source file:org.springframework.boot.autoconfigure.mongo.MongoClientFactory.java

License:Apache License

private MongoClient createMongoClient(String uri, MongoClientOptions options) {
    return new MongoClient(new MongoClientURI(uri, builder(options)));
}

From source file:org.springframework.boot.autoconfigure.mongo.MongoProperties.java

License:Apache License

/**
 * Creates a {@link MongoClient} using the given {@code options} and
 * {@code environment}. If the configured port is zero, the value of the
 * {@code local.mongo.port} property retrieved from the {@code environment} is used to
 * configure the client.//w ww .j av  a 2s . co  m
 *
 * @param options the options
 * @param environment the environment
 * @return the Mongo client
 * @throws UnknownHostException if the configured host is unknown
 */
public MongoClient createMongoClient(MongoClientOptions options, Environment environment)
        throws UnknownHostException {
    try {
        if (hasCustomAddress() || hasCustomCredentials()) {
            if (options == null) {
                options = MongoClientOptions.builder().build();
            }
            List<MongoCredential> credentials = null;
            if (hasCustomCredentials()) {
                String database = this.authenticationDatabase == null ? getMongoClientDatabase()
                        : this.authenticationDatabase;
                credentials = Arrays
                        .asList(MongoCredential.createCredential(this.username, database, this.password));
            }
            String host = this.host == null ? "localhost" : this.host;
            int port = determinePort(environment);
            return new MongoClient(Arrays.asList(new ServerAddress(host, port)), credentials, options);
        }
        // The options and credentials are in the URI
        return new MongoClient(new MongoClientURI(this.uri, builder(options)));
    } finally {
        clearPassword();
    }
}

From source file:org.wso2.carbon.datasource.reader.mongo.MongoDataSourceReaderUtil.java

License:Open Source License

public static MongoClient loadConfiguration(String xmlConfiguration) throws DataSourceException {
    ByteArrayInputStream baos = null;
    try {//from w ww .  j a v  a2  s . co  m
        xmlConfiguration = CarbonUtils.replaceSystemVariablesInXml(xmlConfiguration);
        JAXBContext ctx = JAXBContext.newInstance(MongoDataSourceConfiguration.class);
        baos = new ByteArrayInputStream(xmlConfiguration.getBytes());
        MongoDataSourceConfiguration fileConfig = (MongoDataSourceConfiguration) ctx.createUnmarshaller()
                .unmarshal(baos);
        MongoClient result = null;
        MongoClientOptions.Builder builder = MongoClientOptions.builder();
        if (fileConfig.getUrl() != null) {
            if (fileConfig.getSslInvalidHostNameAllowed() != null) {
                builder.sslInvalidHostNameAllowed(fileConfig.getSslInvalidHostNameAllowed());
            }
            MongoClientURI uri = new MongoClientURI(fileConfig.getUrl(), builder);
            result = new MongoClient(uri);
        } else {
            List<ServerAddress> addressList = new ArrayList<ServerAddress>();
            if (fileConfig.getReplicaSetConfig() != null) {
                ServerAddress address1 = new ServerAddress(fileConfig.getReplicaSetConfig().getHost1(),
                        Integer.parseInt(fileConfig.getReplicaSetConfig().getPort1()));
                addressList.add(address1);
                if (fileConfig.getReplicaSetConfig().getHost2() != null
                        && fileConfig.getReplicaSetConfig().getPort2() != null) {
                    ServerAddress address2 = new ServerAddress(fileConfig.getReplicaSetConfig().getHost2(),
                            Integer.parseInt(fileConfig.getReplicaSetConfig().getPort2()));
                    addressList.add(address2);
                }
                if (fileConfig.getReplicaSetConfig().getHost3() != null
                        && fileConfig.getReplicaSetConfig().getPort3() != null) {
                    ServerAddress address3 = new ServerAddress(fileConfig.getReplicaSetConfig().getHost3(),
                            Integer.parseInt(fileConfig.getReplicaSetConfig().getPort3()));
                    addressList.add(address3);
                }
            } else {
                ServerAddress address = new ServerAddress(fileConfig.getHost(),
                        Integer.parseInt(fileConfig.getPort()));
                addressList.add(address);
            }
            MongoCredential credential = null;
            if (fileConfig.getWithSSL() != null) {
                builder.sslEnabled(fileConfig.getWithSSL());
            }
            if (fileConfig.getSslInvalidHostNameAllowed() != null) {
                builder.sslInvalidHostNameAllowed(fileConfig.getSslInvalidHostNameAllowed());
            }
            if (fileConfig.getAuthenticationMethodEnum() != null && fileConfig.getUsername() != null) {
                credential = createCredentials(fileConfig);
            }
            if (credential != null) {
                result = new MongoClient(addressList, Arrays.asList(new MongoCredential[] { credential }),
                        builder.build());
            } else {
                result = new MongoClient(addressList, builder.build());
            }
        }
        return result;
    } catch (Exception e) {
        throw new DataSourceException("Error loading Mongo Datasource configuration: " + e.getMessage(), e);
    } finally {
        if (baos != null) {
            try {
                baos.close();
            } catch (IOException ignore) {
                // ignore
            }
        }
    }
}

From source file:org.wso2.extension.siddhi.store.mongodb.MongoDBEventTable.java

License:Open Source License

/**
 * Method for initializing mongoClientURI and database name.
 *
 * @param storeAnnotation the source annotation which contains the needed parameters.
 * @param configReader    {@link ConfigReader} ConfigurationReader.
 * @throws MongoTableException when store annotation does not contain mongodb.uri or contains an illegal
 *                             argument for mongodb.uri
 *///from   w  ww.java  2 s  .  c  o  m
private void initializeConnectionParameters(Annotation storeAnnotation, ConfigReader configReader) {
    String mongoClientURI = storeAnnotation.getElement(MongoTableConstants.ANNOTATION_ELEMENT_URI);
    if (mongoClientURI != null) {
        MongoClientOptions.Builder mongoClientOptionsBuilder = MongoTableUtils
                .extractMongoClientOptionsBuilder(storeAnnotation, configReader);
        try {
            this.mongoClientURI = new MongoClientURI(mongoClientURI, mongoClientOptionsBuilder);
            this.databaseName = this.mongoClientURI.getDatabase();
        } catch (IllegalArgumentException e) {
            throw new SiddhiAppCreationException("Annotation '" + storeAnnotation.getName() + "' contains "
                    + "illegal value for 'mongodb.uri' as '" + mongoClientURI
                    + "'. Please check your query and " + "try again.", e);
        }
    } else {
        throw new SiddhiAppCreationException("Annotation '" + storeAnnotation.getName()
                + "' must contain the element 'mongodb.uri'. Please check your query and try again.");
    }
}