Example usage for com.mongodb MongoClient MongoClient

List of usage examples for com.mongodb MongoClient MongoClient

Introduction

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

Prototype

public MongoClient(final MongoClientURI uri, final MongoDriverInformation mongoDriverInformation) 

Source Link

Document

Creates a Mongo described by a URI.

Usage

From source file:com.dhamacher.addressbook.DBController.java

License:Open Source License

/**
 * A factory method to open the database connection. Returns a DBController
 * object so the user can execute queries against the connected collection.
 *
 * @param gui The user view/*from  w  w w . j a v a2  s  . c o  m*/
 * @param dbname The database name
 * @return
 */
protected static DBController connect(Main gui, String dbname) {
    try {
        /* Connect to the mongoDB server using default values */
        mongoClient = new MongoClient("localhost", 27017);

        /* Thrown if the database host is unknown */
    } catch (UnknownHostException ex) {
        Logger.getLogger(DBController.class.getName()).log(Level.SEVERE, null, ex);
        JOptionPane.showMessageDialog(null, "Error connecting to Database", "Database Connection Error",
                JOptionPane.ERROR_MESSAGE);
    } catch (MongoException e) {
        JOptionPane.showMessageDialog(null, "Error connecting to Database", "Database Connection Error",
                JOptionPane.ERROR_MESSAGE);
    }
    /* Return a new controller instance */
    return new DBController(gui, mongoClient.getDB(dbname), dbname);
}

From source file:com.dilmus.dilshad.scabi.db.DDB.java

License:Open Source License

public DDB(String dbHost, String dbPort, String dbName) {
    m_mongo = new MongoClient(dbHost, Integer.parseInt(dbPort));
    m_mongodb = m_mongo.getDatabase(dbName);

    m_dbHost = dbHost;// w w  w .j av  a 2  s. c o m
    m_dbPort = dbPort;
    m_dbName = dbName;

    m_mongo.setWriteConcern(WriteConcern.ACKNOWLEDGED);
    // ?? m_mongo.setReadPreference(ReadPreference.primaryPreferred());
}

From source file:com.dilmus.dilshad.scabi.deprecated.DDBOld.java

License:Open Source License

public DDBOld(String dbHost, String dbPort, String dbName) {
    m_mongo = new MongoClient(dbHost, Integer.parseInt(dbPort));
    m_mongodb = m_mongo.getDatabase(dbName);
    m_db = new DB(m_mongo, dbName);

    m_dbHost = dbHost;//  w ww  .  j ava2s .  c o m
    m_dbPort = dbPort;
    m_dbName = dbName;

    m_mongo.setWriteConcern(WriteConcern.ACKNOWLEDGED);
    // ?? m_mongo.setReadPreference(ReadPreference.primaryPreferred());
}

From source file:com.dilmus.dilshad.scabi.ms.MetaServer.java

License:Open Source License

private static int createDatabasesIfAbsent(String dbHost, String dbPort) throws DScabiException {

    MongoClient mongo = new MongoClient(dbHost, Integer.parseInt(dbPort));
    MongoDatabase mongodb = mongo.getDatabase("MetaDB");
    MongoDatabase mongodb2 = mongo.getDatabase("AppTableDB");
    MongoDatabase mongodb3 = mongo.getDatabase("JavaFileDB");
    MongoDatabase mongodb4 = mongo.getDatabase("FileDB");
    log.debug("mongodb.getName() : {}", mongodb.getName());
    log.debug("mongodb2.getName() : {}", mongodb2.getName());
    log.debug("mongodb3.getName() : {}", mongodb3.getName());
    log.debug("mongodb4.getName() : {}", mongodb4.getName());

    mongo.close();/*w  ww.ja  va 2s.  co m*/
    return 0;
}

From source file:com.ebay.cloud.cms.mongo.MongoDataSource.java

License:Apache License

public MongoDataSource(String servers, int connectionsPerHost, ReadPreference readPreference,
        CMSDBConfig config) {//from w  w w  . j  ava2s.c  o m
    this.addrs = parseServerString(servers);

    Collections.sort(addrs, new Comparator<ServerAddress>() {

        @Override
        public int compare(ServerAddress s1, ServerAddress s2) {
            int result = s1.getHost().compareTo(s2.getHost());
            if (result != 0) {
                return result;
            } else {
                return s1.getPort() - s2.getPort();
            }
        }

    });

    MongoClientOptions.Builder builder = MongoClientOptions.builder();
    builder.socketKeepAlive(false);
    builder.connectionsPerHost(connectionsPerHost);
    if (readPreference != null) {
        builder.readPreference(readPreference);
    }
    // set socket timeout
    if (config != null) {
        Integer socketTimeOut = (Integer) config.get(CMSDBConfig.MONGO_CONNECTION_SOCKET_TIMEOUT);
        builder.socketTimeout(socketTimeOut);
    }
    MongoClientOptions mongoOptions = builder.build();
    this.mongo = new MongoClient(addrs, mongoOptions);
}

From source file:com.ebay.oss.bark.repo.BaseRepo.java

License:Apache License

protected BaseRepo(String collectionName, Class<T> clz) throws RuntimeException {
    this.clz = clz;
    Properties env = new Properties();
    try {// w ww.ja  va2  s. c  o  m
        env.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("application.properties"));
        String mongoServer = env.getProperty("spring.data.mongodb.host");
        int mongoPort = Integer.parseInt(env.getProperty("spring.data.mongodb.port"));

        DB db = new MongoClient(mongoServer, mongoPort).getDB("unitdb0");

        dbCollection = db.getCollection(collectionName);

    } catch (IOException e) {
        throw new RuntimeException(e);
    }

}

From source file:com.eclipsesource.connect.persistence.util.MongoDBClientFactory.java

License:Open Source License

private MongoDatabase doCreateDB(String host, String dbName, int port, String user, String password)
        throws UnknownHostException {
    if (client != null) {
        client.close();//from  w  w  w  . j  a  v a2 s .co  m
    }
    if (user != null && password != null) {
        MongoCredential credential = MongoCredential.createCredential(user, "admin", password.toCharArray());
        client = new MongoClient(new ServerAddress(host, port), Lists.newArrayList(credential));
    } else {
        client = new MongoClient(host, port);
    }
    return client.getDatabase(dbName);
}

From source file:com.edduarte.argus.Context.java

License:Apache License

/**
 * Starts this REST context at the specified port, using the specified number
 * of threads and wrapping the specified collection and stopwords for queries.
 *///ww w  .  ja  v  a2 s .  c  om
public void start(final int port, final int maxThreads, final String dbHost, final int dbPort)
        throws Exception {
    if (initialized) {
        return;
    }

    // Set JSP to always use Standard JavaC
    System.setProperty("org.apache.jasper.compiler.disablejsr199", "false");

    mongoClient = new MongoClient(dbHost, dbPort);

    documentsDB = mongoClient.getDB(DOCUMENTS_DB);
    occurrencesDB = mongoClient.getDB(OCCURRENCES_DB);
    differencesDB = mongoClient.getDB(DIFFERENCES_DB);

    List<LanguageProfile> languageProfiles = new LanguageProfileReader().readAllBuiltIn();
    langDetector = LanguageDetectorBuilder.create(NgramExtractors.standard()).withProfiles(languageProfiles)
            .build();

    collection = new DocumentCollection("argus_production_collection", documentsDB, occurrencesDB);

    logger.info("Starting jobs...");
    jobManager.initialize();

    logger.info("Starting parsers...");
    for (int i = 1; i < maxThreads; i++) {
        Parser p = new SimpleParser();
        parserPool.place(p);
    }

    logger.info("Starting server...");
    Server server = new Server();
    server.setStopAtShutdown(true);

    // Increase server thread pool
    QueuedThreadPool threadPool = new QueuedThreadPool();
    threadPool.setMaxThreads(maxThreads);
    server.setThreadPool(threadPool);

    // Ensure a non-blocking connector (NIO) is used.
    Connector connector = new SelectChannelConnector();
    connector.setPort(port);
    connector.setMaxIdleTime(30000);
    server.setConnectors(new Connector[] { connector });

    // Retrieve the jar file.
    ProtectionDomain protectionDomain = Context.class.getProtectionDomain();
    String jarFilePath = protectionDomain.getCodeSource().getLocation().toExternalForm();

    // Associate the web context (which includes all files in the 'resources'
    // folder to the jar file.
    WebAppContext context = new WebAppContext(jarFilePath, "/");
    context.setServer(server);

    // Add the handlers for the jar context file.
    HandlerList handlers = new HandlerList();
    handlers.addHandler(context);
    server.setHandler(handlers);
    server.addLifeCycleListener(this);

    server.start();

    logger.info("Server started at 'localhost:" + port + "'");
    logger.info("Press Ctrl+C to shutdown the server...");
    initialized = true;

    server.join();
}

From source file:com.edduarte.vokter.Context.java

License:Apache License

/**
 * Starts this REST context at the specified port, using the specified number
 * of threads and wrapping the specified collection and stopwords for queries.
 *///from   ww  w.j  av  a 2s  .  co m
public void start(final int port, final int maxThreads, final String dbHost, final int dbPort)
        throws Exception {
    if (initialized) {
        return;
    }

    // Set JSP to always use Standard JavaC
    System.setProperty("org.apache.jasper.compiler.disablejsr199", "false");

    mongoClient = new MongoClient(dbHost, dbPort);

    documentsDB = mongoClient.getDB(DOCUMENTS_DB);
    occurrencesDB = mongoClient.getDB(OCCURRENCES_DB);
    differencesDB = mongoClient.getDB(DIFFERENCES_DB);

    List<LanguageProfile> languageProfiles = new LanguageProfileReader().readAllBuiltIn();
    langDetector = LanguageDetectorBuilder.create(NgramExtractors.standard()).withProfiles(languageProfiles)
            .build();

    collection = new DocumentCollection("vokter_production_collection", documentsDB, occurrencesDB);

    logger.info("Starting jobs...");
    jobManager.initialize();

    logger.info("Starting parsers...");
    for (int i = 1; i < maxThreads; i++) {
        Parser p = new SimpleParser();
        parserPool.place(p);
    }

    logger.info("Starting server...");
    Server server = new Server();
    server.setStopAtShutdown(true);

    // Increase server thread pool
    QueuedThreadPool threadPool = new QueuedThreadPool();
    threadPool.setMaxThreads(maxThreads);
    server.setThreadPool(threadPool);

    // Ensure a non-blocking connector (NIO) is used.
    Connector connector = new SelectChannelConnector();
    connector.setPort(port);
    connector.setMaxIdleTime(30000);
    server.setConnectors(new Connector[] { connector });

    // Retrieve the jar file.
    ProtectionDomain protectionDomain = Context.class.getProtectionDomain();
    String jarFilePath = protectionDomain.getCodeSource().getLocation().toExternalForm();

    // Associate the web context (which includes all files in the 'resources'
    // folder to the jar file.
    WebAppContext context = new WebAppContext(jarFilePath, "/");
    context.setServer(server);

    // Add the handlers for the jar context file.
    HandlerList handlers = new HandlerList();
    handlers.addHandler(context);
    server.setHandler(handlers);
    server.addLifeCycleListener(this);

    server.start();

    logger.info("Server started at 'localhost:" + port + "'");
    logger.info("Press Ctrl+C to shutdown the server...");
    initialized = true;

    server.join();
}

From source file:com.edgytech.umongo.ReplSetNode.java

License:Apache License

public ReplSetNode(String name, List<ServerAddress> addrs, MongoClientOptions opts, String shardName) {
    this.mongo = new MongoClient(addrs, opts);
    this.name = name != null ? name : "Replica Set";
    this.shardName = shardName;
    try {/*from  ww  w  . ja v  a2 s  .  c  om*/
        xmlLoad(Resource.getXmlDir(), Resource.File.replSetNode, null);
    } catch (Exception ex) {
        getLogger().log(Level.SEVERE, null, ex);
    }
}