Example usage for com.mongodb Mongo Mongo

List of usage examples for com.mongodb Mongo Mongo

Introduction

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

Prototype

Mongo(final MongoClientURI mongoURI, @Nullable final MongoDriverInformation mongoDriverInformation) 

Source Link

Usage

From source file:org.apache.sling.mongodb.impl.MongoDBResourceProviderFactory.java

License:Apache License

@Activate
protected void activate(final Map<String, Object> props) throws Exception {
    final String[] roots = PropertiesUtil.toStringArray(props.get(ResourceProvider.ROOTS));
    if (roots == null || roots.length == 0) {
        throw new Exception("Roots configuration is missing.");
    }/*from   ww  w  . j  a v  a 2s. c om*/
    if (roots.length > 1) {
        throw new Exception("Only a single root should be configured.");
    }
    if (roots[0] == null || roots[0].trim().length() == 0) {
        throw new Exception("Roots configuration is missing.");
    }
    final String host = PropertiesUtil.toString(props.get(PROP_HOST), DEFAULT_HOST);
    final int port = PropertiesUtil.toInteger(props.get(PROP_PORT), DEFAULT_PORT);
    final String db = PropertiesUtil.toString(props.get(PROP_DB), DEFAULT_DB);
    logger.info("Starting MongoDB resource provider with host={}, port={}, db={}",
            new Object[] { host, port, db });
    final DBAddress address = new DBAddress(host, port, db);
    final MongoOptions options = new MongoOptions();

    options.connectionsPerHost = PropertiesUtil.toInteger(props.get(PROP_NUM_CONNECTIONS),
            DEFAULT_NUMCONNECTIONS);
    options.threadsAllowedToBlockForConnectionMultiplier = PropertiesUtil
            .toInteger(props.get(PROP_THREAD_MULTIPLIER), DEFAULT_THREAD_MULTIPLIER);
    final Mongo m = new Mongo(address, options);

    final DB database = m.getDB(db);
    logger.info("Connected to database {}", database);

    this.context = new MongoDBContext(database, roots[0],
            PropertiesUtil.toStringArray(props.get(PROP_FILTER_COLLECTIONS)), this.eventAdmin);
}

From source file:org.apache.whirr.service.mongodb.MongoDBReplSetMemberClusterActionHandler.java

License:Apache License

@Override
protected void afterConfigure(ClusterActionEvent event) {
    ClusterSpec clusterSpec = event.getClusterSpec();
    Cluster cluster = event.getCluster();

    LOG.info("Configuring replica set members.");

    //Get all the instances that are marked as replica set members
    Set<String> replSetRoles = Sets.newHashSet(ROLE, MongoDBArbiterClusterActionHandler.ROLE);
    Set<Cluster.Instance> replSetInstances = cluster.getInstancesMatching(anyRoleIn(replSetRoles));
    //Just grab the first of these instances, use it to send the rs.initiate()
    Cluster.Instance setLeader = replSetInstances.iterator().next();

    try {/*from   w  ww.j  a v a 2  s . co  m*/
        Configuration config = getConfiguration(clusterSpec);
        this.arbiterPort = config.getInt(MongoDBArbiterClusterActionHandler.CFG_KEY_PORT,
                MongoDBArbiterClusterActionHandler.PORT);
    } catch (IOException e) {
        this.arbiterPort = MongoDBArbiterClusterActionHandler.PORT;
    }

    Mongo mongo;
    DB db;

    try {
        // throws IOExc, UnknownHostExc:
        LOG.info(
                "Connecting to " + setLeader.getPublicAddress().getHostAddress() + " to initiate replica set.");
        mongo = new Mongo(setLeader.getPublicAddress().getHostAddress(), PORT);
        db = mongo.getDB("admin");
        if (this.authPassword != null && this.authUsername != null) {
            db.authenticate(this.authUsername, this.authPassword.toCharArray());
        }
    } catch (Exception e) {
        LOG.error("Unable to get public host address of replica set leader, " + e.getMessage());
        return;
    }

    try {
        BasicDBObject configObject = this.generateReplicaSetConfig(replSetInstances); // throws IOexc
        LOG.info("config object:" + configObject.toString());
        BasicDBObject commandInfo = new BasicDBObject("replSetInitiate", configObject);
        LOG.info("Sending rs.initiate() command");
        CommandResult initiateResult = db.command(commandInfo);
        LOG.info("Command Result: " + initiateResult.toString());
    } catch (IOException e) {
        LOG.error("Unable to get private host addresses of replica set members, " + e.getMessage());
    } finally {
        //TODO any cleanup?
    }

}

From source file:org.axonframework.eventsourcing.eventstore.mongo.MongoFactory.java

License:Apache License

/**
 * Creates a mongo instance based on the provided configuration. Read javadoc of the class to learn about the
 * configuration options. A new Mongo instance is created each time this method is called.
 *
 * @return a new Mongo instance each time this method is called.
 *///from  w  w  w  .  ja  v  a2s .  c o m
public Mongo createMongo() {
    Mongo mongo;
    if (mongoAddresses.isEmpty()) {
        try {
            mongo = new Mongo(new ServerAddress(), mongoOptions);
        } catch (UnknownHostException e) {
            throw new IllegalStateException(
                    String.format("No addresses were provided, but could not find IP for default host: %s",
                            ServerAddress.defaultHost()),
                    e);
        }
    } else {
        mongo = new Mongo(mongoAddresses, mongoOptions);
    }
    mongo.setWriteConcern(defaultWriteConcern());

    return mongo;
}

From source file:org.benjp.services.mongodb.MongoBootstrap.java

License:Open Source License

private Mongo mongo() {
    if (m == null) {
        try {//from   w ww .  j ava2  s.c  om
            if (PropertyManager.PROPERTY_SERVER_TYPE_EMBED
                    .equals(PropertyManager.getProperty(PropertyManager.PROPERTY_SERVER_TYPE))) {
                log.warning("WE WILL NOW USE MONGODB IN EMBED MODE...");
                log.warning("BE AWARE...");
                log.warning("EMBED MODE SHOULD NEVER BE USED IN PRODUCTION!");
                setupEmbedMongo();
            }

            MongoOptions options = new MongoOptions();
            options.connectionsPerHost = 200;
            options.connectTimeout = 60000;
            options.threadsAllowedToBlockForConnectionMultiplier = 10;
            options.autoConnectRetry = true;
            String host = PropertyManager.getProperty(PropertyManager.PROPERTY_SERVER_HOST);
            int port = Integer.parseInt(PropertyManager.getProperty(PropertyManager.PROPERTY_SERVER_PORT));
            m = new Mongo(new ServerAddress(host, port), options);
            m.setWriteConcern(WriteConcern.SAFE);
        } catch (UnknownHostException e) {
        } catch (IOException e) {
        }
    }
    return m;
}

From source file:org.chililog.server.data.MongoConnection.java

License:Apache License

/**
 * <p>//from w w  w . java2 s  .c o m
 * Loads our mongoDB connection pool
 * </p>
 * <p>
 * This is a package scope method so that we can use it within our junit test cases. It should not be called from
 * real code.
 * </p>
 * 
 * @throws MongoException
 * @throws UnknownHostException
 * 
 */
void loadMongo() throws UnknownHostException, MongoException {
    AppProperties appProperties = AppProperties.getInstance();
    ServerAddress addr = new ServerAddress(appProperties.getDbIpAddress(), appProperties.getDbIpPort());
    MongoOptions options = new MongoOptions();
    options.connectionsPerHost = appProperties.getDbConnectionsPerHost();
    _mongo = new Mongo(addr, options);
}

From source file:org.chimi.s4s.storage.mongofs.MongoFSFileStorage.java

License:Apache License

public MongoFSFileStorage(String mongoHost, int mongoPort, int poolSize)
        throws UnknownHostException, MongoException {
    MongoOptions options = new MongoOptions();
    options.connectionsPerHost = poolSize;
    mongo = new Mongo(new ServerAddress(mongoHost, mongoPort), options);
}

From source file:org.cish4380.groupproject.springconfig.WebConfig.java

@Bean(name = "mongo")
public Mongo getMongoInstance() throws Exception {
    return new Mongo("localhost", 27017);
}

From source file:org.cloudifysource.mongodb.AbstractMongoPlugin.java

License:Open Source License

/**
* Opens connection to mongoDB//from ww  w.ja  v  a 2  s  .  co  m
*/
public void init() {
    try {
        host = (String) config.get("host");
        if (host == null)
            host = DEFAULT_HOST;

        log.info("AbstractMongoPlugin.init: using host " + host);
        int instanseID = serviceContext.getInstanceId();
        log.info("AbstractMongoPlugin.init: InstanceId is " + instanseID);

        port = (Integer) serviceContext.getAttributes().getThisInstance().get("port");
        log.info("AbstractMongoPlugin.init:port is " + port.intValue());

        dbName = (String) config.get("dbName");
        if (dbName == null)
            dbName = DEFAULT_DB_NAME;
        log.info("AbstractMongoPlugin.init:Connecting to mongodb " + dbName + "(" + host + "," + port + ")...");
        Mongo mongo = new Mongo(host, port);
        db = mongo.getDB(dbName);
        log.info("AbstractMongoPlugin.init:Connected to mongodb " + dbName);
        initialized = true;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:org.craftercms.commerce.server.ServerConfig.java

License:Open Source License

private Mongo mongo() throws UnknownHostException, MongoException {
    return new Mongo(mongoHost, mongoPort);
}

From source file:org.cvbase.service.mongodb.MongodbServiceFactory.java

License:Open Source License

public MongodbServiceFactory() {
    config = Config.getInstance();// w w  w  .  j  av a  2 s .c o m
    try {
        // Set the hostname and the port.
        db = new Mongo(config.getString("cvbase.host"), config.getInteger("cvbase.port"));
        LOG.log(Level.INFO, "Mongo DB is opened.");
    } catch (UnknownHostException ex) {
        LOG.log(Level.SEVERE, "Connect can't be established.", ex);
    } catch (MongoException ex) {
        LOG.log(Level.SEVERE, "Connect can't be established.", ex);
    }
}