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.datacleaner.connection.MongoDbDatastore.java

License:Open Source License

@Override
protected UsageAwareDatastoreConnection<UpdateableDataContext> createDatastoreConnection() {
    try {/*from  www  .ja  va2s . c om*/
        final Mongo mongo = new Mongo(_hostname, _port);
        final DB mongoDb = mongo.getDB(_databaseName);
        if (_username != null && _password != null) {
            final boolean authenticated = mongoDb.authenticate(_username, _password);
            if (!authenticated) {
                logger.warn("Autheticate returned false!");
            }
        }

        final UpdateableDataContext dataContext;
        if (_tableDefs == null || _tableDefs.length == 0) {
            dataContext = new MongoDbDataContext(mongoDb);
        } else {
            dataContext = new MongoDbDataContext(mongoDb, _tableDefs);
        }
        return new UpdateableDatastoreConnectionImpl<UpdateableDataContext>(dataContext, this);
    } catch (Exception e) {
        if (e instanceof RuntimeException) {
            throw (RuntimeException) e;
        }
        throw new IllegalStateException("Failed to connect to MongoDB instance: " + e.getMessage(), e);
    }
}

From source file:org.datavyu.models.db.MongoDatastore.java

License:Open Source License

/**
 * Spin up the mongo instance so that we can query and do stuff with it.
 *//*from w  ww. j av a2 s .  co  m*/
public static void startMongo() {
    // Unpack the mongo executable.
    try {
        String mongoDir;
        switch (Datavyu.getPlatform()) {
        case MAC:
            mongoDir = NativeLoader.unpackNativeApp(mongoOSXLocation);
            break;
        case WINDOWS:
            mongoDir = NativeLoader.unpackNativeApp(mongoWindowsLocation);
            break;
        default:
            mongoDir = NativeLoader.unpackNativeApp(mongoOSXLocation);
        }

        // When files are unjared - they loose their executable status.
        // So find the mongod executable and set it to exe
        Collection<File> files = FileUtils.listFiles(new File(mongoDir), new RegexFileFilter(".*mongod.*"),
                TrueFileFilter.INSTANCE);

        File f;
        if (files.iterator().hasNext()) {
            f = files.iterator().next();
            f.setExecutable(true);
        } else {
            f = new File("");
            System.out.println("ERROR: Could not find mongod");
        }

        //            File f = new File(mongoDir + "/mongodb-osx-x86_64-2.0.2/bin/mongod");
        //            f.setExecutable(true);

        // Spin up a new mongo instance.
        File mongoD = new File(mongoDir);
        //            int port = findFreePort(27019);
        int port = 27019;

        // Try to shut down the server if it is already running
        try {
            mongoDriver = new Mongo("127.0.0.1", port);
            DB db = mongoDriver.getDB("admin");
            db.command(new BasicDBObject("shutdownServer", 1));
        } catch (Exception e) {
            e.printStackTrace();
        }

        mongoProcess = new ProcessBuilder(f.getAbsolutePath(), "--dbpath", mongoD.getAbsolutePath(),
                "--bind_ip", "127.0.0.1", "--port", String.valueOf(port), "--directoryperdb").start();
        //            InputStream in = mongoProcess.getInputStream();
        //            InputStreamReader isr = new InputStreamReader(in);

        System.out.println("Starting mongo driver.");
        mongoDriver = new Mongo("127.0.0.1", port);

        System.out.println("Getting DB");

        // Start with a clean DB
        mongoDB = mongoDriver.getDB("datavyu");

        DBCollection varCollection = mongoDB.getCollection("variables");
        varCollection.setObjectClass(MongoVariable.class);

        DBCollection cellCollection = mongoDB.getCollection("cells");
        cellCollection.setObjectClass(MongoCell.class);

        DBCollection matrixCollection = mongoDB.getCollection("matrix_values");
        matrixCollection.setObjectClass(MongoMatrixValue.class);

        DBCollection nominalCollection = mongoDB.getCollection("nominal_values");
        nominalCollection.setObjectClass(MongoNominalValue.class);

        DBCollection textCollection = mongoDB.getCollection("text_values");
        textCollection.setObjectClass(MongoTextValue.class);

        System.out.println("Got DB");
        running = true;

    } catch (Exception e) {
        System.err.println("Unable to fire up the mongo datastore.");
        e.printStackTrace();
    }
}

From source file:org.eclipse.birt.data.oda.mongodb.impl.MongoDBDriver.java

License:Open Source License

private static Mongo createMongoNode(ServerNodeKey serverNodeKey) throws OdaException {
    /* NOTE: Not able to use the new 2.10 MongoClient classes directly,
     *  as their public methods, as of 2.10.1, do not allow merging options of
     *  MongoClientURL and MongoClientOptions
     *///from  w  w w .  j ava  2  s  . co  m
    List<String> hosts = serverNodeKey.getServerHosts();
    String standaloneHost = hosts.size() == 1 ? hosts.get(0) : null;
    Integer port = serverNodeKey.getServerPort();
    MongoOptions options = serverNodeKey.getOptions();
    if (options == null)
        options = sm_defaultClientOptions;

    try {
        if (standaloneHost != null) {
            ServerAddress serverAddr = port != null ? new ServerAddress(standaloneHost, port)
                    : new ServerAddress(standaloneHost);
            return new Mongo(serverAddr, options);
        } else {
            List<ServerAddress> serverSeeds = new ArrayList<ServerAddress>(hosts.size());
            for (String host : hosts)
                serverSeeds.add(new ServerAddress(host));
            return new Mongo(serverSeeds, options);
        }
    } catch (Exception ex) {
        throw new OdaException(ex);
    }
}

From source file:org.eobjects.analyzer.connection.MongoDbDatastore.java

License:Open Source License

@Override
protected UsageAwareDatastoreConnection<UpdateableDataContext> createDatastoreConnection() {
    try {/*from ww  w.j  a  v  a2  s. co  m*/
        Mongo mongo = new Mongo(_hostname, _port);
        DB mongoDb = mongo.getDB(_databaseName);
        if (_username != null && _password != null) {
            boolean authenticated = mongoDb.authenticate(_username, _password);
            if (!authenticated) {
                logger.warn("Autheticate returned false!");
            }
        }

        final UpdateableDataContext dataContext;
        if (_tableDefs == null || _tableDefs.length == 0) {
            dataContext = new MongoDbDataContext(mongoDb);
        } else {
            dataContext = new MongoDbDataContext(mongoDb, _tableDefs);
        }
        return new UpdateableDatastoreConnectionImpl<UpdateableDataContext>(dataContext, this);
    } catch (Exception e) {
        if (e instanceof RuntimeException) {
            throw (RuntimeException) e;
        }
        throw new IllegalStateException("Failed to connect to MongoDB instance: " + e.getMessage(), e);
    }
}

From source file:org.exoplatform.addons.persistence.services.mongodb.MongoBootstrap.java

License:Open Source License

private Mongo mongo() {
    if (m == null) {
        try {/*from   w  w  w .  ja  va2s  .  co  m*/
            if (PropertyManager.PROPERTY_DB_SERVER_TYPE_EMBED
                    .equals(PropertyManager.getProperty(PropertyManager.PROPERTY_DB_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_DB_SERVER_HOST);
            int port = Integer.parseInt(PropertyManager.getProperty(PropertyManager.PROPERTY_DB_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.exoplatform.addons.storage.services.mongodb.MongoBootstrap.java

License:Open Source License

private Mongo mongo() {
    if (m == null) {
        try {/* www  .  jav a  2  s .co m*/
            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.exoplatform.chat.services.mongodb.MongoBootstrap.java

License:Open Source License

private Mongo mongo() {
    if (m == null) {
        try {/*from  w  ww. ja v  a2 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) {
            LOG.warning(e.getMessage());
        } catch (IOException e) {
            LOG.warning(e.getMessage());
        }
    }
    return m;
}

From source file:org.exoplatform.mongo.factory.MongoFactoryBean.java

License:Open Source License

protected Mongo createInstance() throws Exception {
    Mongo mongo = null;/*from   w ww .j a  v a2s.c  o m*/
    if (mongoOptions == null) {
        mongoOptions = new MongoOptions();
        mongoOptions.safe = true;
        // mongoOptions.fsync = true;
        // mongoOptions.slaveOk = true;
    }
    setMultiAddress(configuration.getDataStoreReplicas().split(","));
    logger.debug("Created Mongo with MongoOptions: [" + mongoOptions.toString() + "], ReplicaSets: "
            + replicaSetSeeds);

    try {
        if (replicaSetSeeds.size() > 0) {
            if (mongoOptions != null) {
                mongo = new Mongo(replicaSetSeeds, mongoOptions);
            } else {
                mongo = new Mongo(replicaSetSeeds);
            }
        } else {
            mongo = new Mongo();
        }
    } catch (MongoException mongoException) {
        logger.error("Problem creating Mongo instance", mongoException);
        throw mongoException;
    }
    return mongo;
}

From source file:org.fiware.apps.repository.dao.MongoDAOFactory.java

License:BSD License

public synchronized static DB createConnection() {
    Mongo m;/*from   w  ww .  j a  v  a 2s  .c om*/
    DB db;

    try {
        m = new Mongo(RepositorySettings.getProperty("mongodb.host"),
                Integer.parseInt(RepositorySettings.getProperty("mongodb.port")));
        db = m.getDB(RepositorySettings.getProperty("mongodb.db"));
    } catch (UnknownHostException | MongoException ex) {
        throw new MongoException(ex.getLocalizedMessage());
    }
    return db;
}

From source file:org.fornax.cartridges.sculptor.framework.accessimpl.mongodb.DbManager.java

License:Apache License

private synchronized void init() {
    if (initialized) {
        return;/*from  w  w w. j  a v a2  s  .c o  m*/
    }
    if (dbname == null) {
        throw new IllegalStateException("MongoDB dbname not defined");
    }
    try {
        if (dbUrl1 == null || dbUrl1.equals("")) {
            // default host/port, but with options
            mongo = new Mongo(new ServerAddress(), options);
        } else if (dbUrl2 != null && !dbUrl2.equals("")) {
            DBAddress left = new DBAddress(urlWithDbname(dbUrl1));
            DBAddress right = new DBAddress(urlWithDbname(dbUrl2));
            mongo = new Mongo(left, right, options);
        } else {
            DBAddress left = new DBAddress(urlWithDbname(dbUrl1));
            mongo = new Mongo(left, options);
        }
        db = mongo.getDB(dbname);
        initialized = true;
    } catch (Exception e) {
        throw new RuntimeException(e.getMessage(), e);
    }
}