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:cn.cnic.bigdatalab.flume.sink.mongodb.MongoSink.java

License:Apache License

/**
 * {@inheritDoc}//from   w w  w.  ja  va 2  s  .  com
 *
 * @param context
 */
@Override
public void configure(Context context) {
    try {
        if (!"INJECTED".equals(context.getString(CONF_URI))) {
            this.mongoClientURI = new MongoClientURI(context.getString(CONF_URI),
                    MongoClientOptions.builder().writeConcern(WriteConcern.SAFE));
            this.mongoClient = new MongoClient(mongoClientURI);
            if (mongoClientURI.getDatabase() != null) {
                this.mongoDefaultDb = mongoClient.getDB(mongoClientURI.getDatabase());
            }
            if (mongoClientURI.getCollection() != null) {
                this.mongoDefaultCollection = mongoDefaultDb.getCollection(mongoClientURI.getCollection());
            }
        }
        final String mappingFilename = context.getString(CONF_MAPPING_FILE);
        this.eventParser = (mappingFilename == null) ? new EventParser()
                : new EventParser(MappingDefinition.load(mappingFilename));

        this.isDynamicMode = context.getBoolean(CONF_DYNAMIC, DEFAULT_DYNAMIC);
        if (!isDynamicMode && mongoDefaultCollection == null) {
            throw new MongoSinkException(
                    "Default MongoDB collection must be specified unless dynamic mode is enabled");
        }
        this.dynamicDBField = context.getString(CONF_DYNAMIC_DB_FIELD, DEFAULT_DYNAMIC_DB_FIELD);
        this.dynamicCollectionField = context.getString(CONF_DYNAMIC_COLLECTION_FIELD,
                DEFAULT_DYNAMIC_COLLECTION_FIELD);

        this.sinkCounter = new SinkCounter(this.getName());
        this.batchSize = context.getInteger(CONF_BATCH_SIZE, DEFAULT_BATCH_SIZE);

        this.updateInsteadReplace = context.getBoolean(CONF_UPDATE_INSTEAD_REPLACE,
                DEFAULT_UPDATE_INSTEAD_REPLACE);

    } catch (IOException ex) {
        throw new MongoSinkException(ex);
    }
}

From source file:com.apifest.oauth20.MongoUtil.java

License:Apache License

public static MongoClient getMongoClient() {
    if (mongoClient == null) {
        try {//from   w ww .  j  a  v a2  s .  c o  m
            MongoClientOptions.Builder options = new MongoClientOptions.Builder().connectionsPerHost(100)
                    .connectTimeout(2).threadsAllowedToBlockForConnectionMultiplier(1);
            final MongoClientURI mongoClientURI = new MongoClientURI(OAuthServer.getDbURI(), options);
            mongoClient = new MongoClient(mongoClientURI);

            if (mongoClientURI.getDatabase() != null) {
                database = mongoClientURI.getDatabase();
            }
        } catch (UnknownHostException e) {
            log.error("Cannot connect to DB", e);
        }
    }
    return mongoClient;
}

From source file:com.apifest.oauth20.persistence.mongodb.MongoUtil.java

License:Apache License

public static MongoClient getMongoClient(String uri) {
    if (mongoClient == null) {
        try {/*from   www .jav a2 s  .  c om*/
            MongoClientOptions.Builder options = new MongoClientOptions.Builder().connectionsPerHost(100)
                    .connectTimeout(2000).threadsAllowedToBlockForConnectionMultiplier(1);
            final MongoClientURI mongoClientURI = new MongoClientURI(uri, options);
            mongoClient = new MongoClient(mongoClientURI);

            if (mongoClientURI.getDatabase() != null) {
                database = mongoClientURI.getDatabase();
            }
        } catch (UnknownHostException e) {
            log.error("Cannot connect to DB", e);
        }
    }
    return mongoClient;
}

From source file:com.bnrc.sdn.properties.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  w w. j ava 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.createMongoCRCredential(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  
        System.out.println("uri=" + uri);
        return new MongoClient(new MongoClientURI(this.uri, builder(options)));
    } finally {
        clearPassword();
    }
}

From source file:com.ricardolorenzo.identity.user.impl.UserIdentityManagerMongoDB.java

License:Open Source License

public UserIdentityManagerMongoDB(final Properties conf) throws UnknownHostException {
    this.properties = conf;

    this.databaseUsers = new Boolean(this.properties.getProperty("mongodb.databaseUsers", "true"));

    WriteConcern writeConcern = WriteConcern.MAJORITY;
    String writeConcernType = conf.getProperty("mongodb.writeConcern", "majority").toLowerCase();
    if ("majority".equals(writeConcernType)) {
        writeConcern = WriteConcern.UNACKNOWLEDGED;
    } else if ("unacknowledged".equals(writeConcernType)) {
        writeConcern = WriteConcern.UNACKNOWLEDGED;
    } else if ("acknowledged".equals(writeConcernType)) {
        writeConcern = WriteConcern.ACKNOWLEDGED;
    } else if ("journaled".equals(writeConcernType)) {
        writeConcern = WriteConcern.JOURNALED;
    } else if ("replica_acknowledged".equals(writeConcernType)) {
        writeConcern = WriteConcern.REPLICA_ACKNOWLEDGED;
    }//from w  w  w.  j  a  va2 s. c o  m

    ReadPreference readPreference = null;
    String readPreferenceType = conf.getProperty("mongodb.readPreference", "primary").toLowerCase();
    if ("primary".equals(readPreferenceType)) {
        readPreference = ReadPreference.primary();
    } else if ("primary_preferred".equals(readPreferenceType)) {
        readPreference = ReadPreference.primaryPreferred();
    } else if ("secondary".equals(readPreferenceType)) {
        readPreference = ReadPreference.secondary();
    } else if ("secondary_preferred".equals(readPreferenceType)) {
        readPreference = ReadPreference.secondaryPreferred();
    } else if ("nearest".equals(readPreferenceType)) {
        readPreference = ReadPreference.nearest();
    }

    MongoClientOptions.Builder options = MongoClientOptions.builder();
    options.writeConcern(writeConcern);
    options.readPreference(readPreference);
    try {
        options.connectionsPerHost(Integer.parseInt(conf.getProperty("mongodb.threads", "100")));
    } catch (NumberFormatException e) {
        options.connectionsPerHost(100);
    }

    MongoClientURI mongoClientURI = new MongoClientURI(
            conf.getProperty("mongodb.url", "mongodb://localhost:27017"), options);
    if (!this.properties.containsKey("mongodb.database")) {
        if (mongoClientURI.getDatabase() != null && !mongoClientURI.getDatabase().isEmpty()) {
            this.properties.setProperty("mongodb.database", mongoClientURI.getDatabase());
        } else {
            this.properties.setProperty("mongodb.database", DEFAULT_DATABASE);
        }
    }
    mongoClient = new MongoClient(mongoClientURI);
}

From source file:com.stratio.ingestion.morphline.checkpointfilter.handler.MongoCheckpointFilterHandler.java

License:Apache License

private void initMongo(String mongoUri) {
    this.mongoClientURI = new MongoClientURI(mongoUri,
            MongoClientOptions.builder().writeConcern(WriteConcern.SAFE));
    try {//from w  ww  .ja  va 2s  . c o  m
        this.mongoClient = new MongoClient(mongoClientURI);
    } catch (UnknownHostException e) {
        e.printStackTrace();
    }
    if (mongoClientURI.getDatabase() != null) {
        this.mongoDb = mongoClient.getDB(mongoClientURI.getDatabase());
    }
    if (mongoClientURI.getCollection() != null) {
        this.mongoCollection = mongoDb.getCollection(mongoClientURI.getCollection());
    }
}

From source file:com.stratio.ingestion.source.rest.url.filter.MongoFilterHandler.java

License:Apache License

protected void initMongo(String mongoUri) {
    try {//from  w  w  w  .  ja va 2  s  .  c  om
        this.mongoClientURI = new MongoClientURI(mongoUri,
                MongoClientOptions.builder().writeConcern(WriteConcern.SAFE));
        this.mongoClient = new MongoClient(mongoClientURI);
        this.mongoDb = mongoClient
                .getDB(checkNotNull(mongoClientURI.getDatabase(), "Non-null database expected"));
        this.mongoCollection = mongoDb.getCollection(
                checkNotNull(mongoClientURI.getCollection(), "Non-null " + "collection expected"));
    } catch (UnknownHostException e) {
        throw new MongoFilterException("mongo host could not be reached", e);
    } catch (IllegalArgumentException e) {
        throw new MongoFilterException("Valid mongo uri expected.", e);
    } catch (NullPointerException e) {
        throw new MongoFilterException("Non-null db/collection expected", e);
    }
}

From source file:com.streamsets.pipeline.stage.common.mongodb.MongoDBConfig.java

License:Apache License

private MongoClient createClient(Stage.Context context, List<Stage.ConfigIssue> issues,
        ReadPreference readPreference, WriteConcern writeConcern) {
    MongoClientOptions.Builder optionBuilder = new MongoClientOptions.Builder()
            .connectionsPerHost(connectionsPerHost).connectTimeout(connectTimeout)
            .cursorFinalizerEnabled(cursorFinalizerEnabled).heartbeatConnectTimeout(heartbeatConnectTimeout)
            .heartbeatFrequency(heartbeatFrequency).heartbeatSocketTimeout(heartbeatSocketTimeout)
            .localThreshold(localThreshold).maxConnectionIdleTime(maxConnectionIdleTime)
            .maxConnectionLifeTime(maxConnectionLifeTime).maxWaitTime(maxWaitTime)
            .minConnectionsPerHost(minConnectionsPerHost).minHeartbeatFrequency(minHeartbeatFrequency)
            .serverSelectionTimeout(serverSelectionTimeout).socketKeepAlive(socketKeepAlive)
            .socketTimeout(socketTimeout).sslEnabled(sslEnabled)
            .sslInvalidHostNameAllowed(sslInvalidHostNameAllowed)
            .threadsAllowedToBlockForConnectionMultiplier(threadsAllowedToBlockForConnectionMultiplier);

    // the default value of requiredReplicaSetName is null, so it should be set only if a non-empty string is provided
    if (!requiredReplicaSetName.isEmpty()) {
        optionBuilder = optionBuilder.requiredReplicaSetName(requiredReplicaSetName);
    }//from   w w w .  j  a va 2 s . c o m
    // read preference is only set by the source
    if (readPreference != null) {
        optionBuilder = optionBuilder.readPreference(readPreference);
    }
    // write concern is only set by the target
    if (writeConcern != null) {
        optionBuilder = optionBuilder.writeConcern(writeConcern);
    }

    MongoClientURI mongoURI;
    List<ServerAddress> servers = new ArrayList<>();
    try {
        mongoURI = new MongoClientURI(connectionString, optionBuilder);
    } catch (IllegalArgumentException e) {
        issues.add(context.createConfigIssue(Groups.MONGODB.name(), MONGO_CONFIG_PREFIX + "connectionString",
                Errors.MONGODB_00, e.toString()));
        return null;
    }

    validateServerList(context, mongoURI.getHosts(), servers, issues);
    if (!issues.isEmpty()) {
        return null;
    }

    MongoClient mongoClient = null;
    List<MongoCredential> credentials;
    try {
        credentials = createCredentials();
    } catch (StageException ex) {
        issues.add(context.createConfigIssue(Groups.MONGODB.name(), MONGO_CONFIG_PREFIX + "connectionString",
                Errors.MONGODB_34, ex.toString()));
        return null;
    }

    if (credentials.isEmpty()) {
        Optional.ofNullable(mongoURI.getCredentials()).ifPresent(credentials::add);
    }

    try {
        if (isSingleMode) {
            mongoClient = new MongoClient(servers.get(0), credentials, mongoURI.getOptions());
        } else {
            mongoClient = new MongoClient(servers, credentials, mongoURI.getOptions());
        }
    } catch (MongoException e) {
        issues.add(context.createConfigIssue(Groups.MONGODB.name(), MONGO_CONFIG_PREFIX + "connectionString",
                Errors.MONGODB_01, e.toString()));
    }

    return mongoClient;
}

From source file:com.vidico.jsp.listener.MongoDBContextListener.java

@Override
public void contextInitialized(ServletContextEvent sce) {
    try {/*from   w  w w .j a v a 2s.  co m*/
        ServletContext ctx = sce.getServletContext();

        MongoClientURI uri = null;
        uri = new MongoClientURI("mongodb://vishal:vishal@ds057066.mlab.com:57066/vidico",
                MongoClientOptions.builder().cursorFinalizerEnabled(false));
        MongoClient mongo = new MongoClient(uri);

        //            MongoClient mongo = new MongoClient(
        //                    ctx.getInitParameter("MONGODB_HOST"),
        //                    Integer.parseInt(ctx.getInitParameter("MONGODB_PORT")));
        System.out.println("MongoClient initialized successfully");
        sce.getServletContext().setAttribute("MONGO_CLIENT", mongo);
    } catch (Exception e) {
        throw new RuntimeException("MongoClient init failed " + e.getMessage());
    }
}

From source file:hulop.hokoukukan.utils.MongoAdapter.java

License:Open Source License

public MongoAdapter(String url, String dbName, String cert) throws Exception {
    mongoURI = cert != null ? new MongoClientURI(url, optionsBuilder(cert)) : new MongoClientURI(url);
    client = new MongoClient(mongoURI);
    db = client.getDB(dbName != null ? dbName : mongoURI.getDatabase());
    mFS = new GridFS(db);
    System.out.println(db.getCollectionNames());
    mapCol = db.getCollection("maps");
    userCol = db.getCollection("users");
    logCol = db.getCollection("logs");
    fileCol = db.getCollection("files");
    entryCol = db.getCollection("entries");

    mapCol.createIndex(new BasicDBObject("geometry", "2dsphere"));
}