Example usage for com.mongodb Mongo getDB

List of usage examples for com.mongodb Mongo getDB

Introduction

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

Prototype

@Deprecated 
public DB getDB(final String dbName) 

Source Link

Document

Gets a database object.

Usage

From source file:pl.nask.hsn2.os.MongoConnector.java

License:Open Source License

private MongoConnector(String host, int port) throws IOException {
    Mongo mongo = null;
    try {/*  w ww.j a  v  a  2s  .  com*/
        mongo = new Mongo(host, port);
        mongo.dropDatabase("object-store");
        db = mongo.getDB("object-store");
        collection = db.createCollection("allJobsInOne", null);
        collection.ensureIndex(new BasicDBObject("parent", 1));
    } catch (UnknownHostException e) {
        LOGGER.error("MongoDB host is unreachable: {}", e.getMessage());
        throw new IOException("MongoDB is unreachable", e);
    } catch (MongoException.Network e) {
        LOGGER.error("Couldn't connect to MongoDB: {}", e.getMessage());
        throw new IOException("MongoDB is unreachable", e);
    }
}

From source file:pl.solr.ag.mongodb.sink.ComplexDataSink.java

License:Apache License

@Override
public void init(PlayerConfig config) throws InitializationFailedException {
    super.init(config);

    host = config.get(BASE_HOST_KEY);/*from w w  w  .j a  v a  2 s  . c o  m*/
    port = Integer.valueOf(config.get(BASE_PORT_KEY));
    dbName = config.get(DB_NAME_KEY);
    collectionName = config.get(COLLECTION_NAME_KEY);

    if (host == null || "".equals(host.trim())) {
        throw new IllegalArgumentException(
                this.getClass().getName() + " expects configuration property " + BASE_HOST_KEY);
    }

    if (port == null) {
        throw new IllegalArgumentException(
                this.getClass().getName() + " expects configuration property " + BASE_PORT_KEY);
    }

    if (dbName == null || "".equals(dbName.trim())) {
        throw new IllegalArgumentException(
                this.getClass().getName() + " expects configuration property " + DB_NAME_KEY);
    }

    if (collectionName == null || "".equals(collectionName.trim())) {
        throw new IllegalArgumentException(
                this.getClass().getName() + " expects configuration property " + COLLECTION_NAME_KEY);
    }

    Mongo mongo = null;
    try {
        mongo = new Mongo(host, port);
    } catch (Exception e) {
        throw new InitializationFailedException(e.getMessage());
    }
    db = mongo.getDB(dbName);
    collection = db.getCollection(collectionName);
}

From source file:servertcp.DataBase.java

public static void initMongoDB(String ip, int port, String DBname, String CollectionName)
        throws UnknownHostException {

    Mongo mongo = new Mongo(ip, port);
    db = mongo.getDB(DBname);
    collection = db.getCollection(CollectionName);

}

From source file:session.BookSessionBean.java

@PostConstruct
private void initDB() {
    Mongo mongo = null;
    try {//from ww w  .j av a2 s .c om
        mongo = new Mongo("ds033133.mongolab.com", 33133);
    } catch (UnknownHostException ex) {
        Logger.getLogger(BookSessionBean.class.getName()).log(Level.SEVERE, null, ex);
    }

    DB db = mongo.getDB("librosdb");
    boolean auth = db.authenticate("cposdaa", "--".toCharArray());
    if (auth) {
        bookCollection = db.getCollection("books");
        //valido si la colleccion existe si no la crea
        if (bookCollection == null) {
            bookCollection = db.createCollection("books", null);
        }

    } else {
        System.out.println("Login failed");
    }

}

From source file:streamflow.datastore.mongodb.impl.MongoGridFsFileContentDao.java

License:Apache License

@Inject
public MongoGridFsFileContentDao(Mongo mongo, DatastoreConfig datastoreConfig) {
    String dbName = (String) datastoreConfig.properties().get("dbName");
    if (dbName == null || dbName.isEmpty()) {
        dbName = "streamflow";
    }//from   w  ww  . j  av a2s.  c o  m

    DB db = mongo.getDB(dbName);

    gridFs = new GridFS(db);
}

From source file:TweetAnalytics.DBManager.java

public DBManager(String conStr) {

    // create the database
    try {/*from   w  ww.j  ava 2s. com*/
        // make the initial connection to the mongoDB
        @SuppressWarnings("deprecation")
        Mongo tweetsMongoClient = new Mongo(new MongoURI(conStr));
        db = tweetsMongoClient.getDB("twitter_mini");
    } catch (UnknownHostException ex) {
        System.err.println("The database could not be initialized because of an UnknownHostException.");
        Logger.getLogger(DBManager.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:TweetCollector.DBManager.java

@SuppressWarnings("deprecation")
public DBManager(String conStr) {

    // create the database
    try {//from  w ww .  j a  v  a  2s  .co  m
        // make the initial connection to the mongoDB
        Mongo tweetsMongoClient = new Mongo(new MongoURI(conStr));
        DBManager.db = tweetsMongoClient.getDB("twitter_mini");
    } catch (UnknownHostException ex) {
        System.err.println("The database could not be initialized because of an UnknownHostException.");
        Logger.getLogger(DBManager.class.getName()).log(Level.SEVERE, null, ex);
    }

    // create the tweets collection
    DBManager.tweetsCollection = DBManager.db.getCollection("tweets");
    // tweetsCollection.ensureIndex(new BasicDBObject("text", "text"));

    // create the trends collection
    DBManager.trendsCollection = DBManager.db.getCollection("trends");
}

From source file:uk.ac.ncl.aries.entanglement.cli.export.MongoGraphToAscii.java

License:Apache License

public static void main(String[] args)
        throws UnknownHostException, RevisionLogException, IOException, GraphModelException {
    CommandLineParser parser = new PosixParser();
    Options options = new Options();

    //    options.addOption("g", "format-gdf", false,
    //        "Specifies that the output format is GDF (currently the only option)");

    options.addOption("h", "mongo-host", true, "The MongoDB server host to connect to.");

    options.addOption("d", "mongo-database", true, "The name of a MongoDB database to connect to.");

    options.addOption("g", "graph-name", true,
            "The name of a graph to use (there may be multiple graphs per MongoDB database).");

    options.addOption("b", "graph-branch", true,
            "The name of a graph branch to use (there may be multiple branches per graph).");

    options.addOption("o", "output-file", true, "Specifies a path to a file to use ");

    //    options.addOption(OptionBuilder
    //        .withLongOpt("tags")
    //        .withArgName( "property=value" )
    //        .hasArgs(2)
    //        .withValueSeparator()
    //        .withDescription(
    //        "used to tag files when uploading.")
    //        .create( "t" ));

    if (args.length == 0) {
        printHelpExit(options);/*from  www.  ja va 2 s.c  om*/
    }

    String mongoHost = null;
    String mongoDatabaseName = null;
    String graphName = null;
    String graphBranch = null;
    String outputFilename = null;

    try {
        CommandLine line = parser.parse(options, args);

        if (line.hasOption("mongo-host")) {
            mongoHost = line.getOptionValue("mongo-host", null);
        } else {
            throw new IllegalArgumentException("You must specify a hostname");
        }

        if (line.hasOption("mongo-database")) {
            mongoDatabaseName = line.getOptionValue("mongo-database", null);
        } else {
            throw new IllegalArgumentException("You must specify a database name");
        }

        if (line.hasOption("graph-name")) {
            graphName = line.getOptionValue("graph-name", null);
        } else {
            throw new IllegalArgumentException("You must specify a graph name");
        }

        if (line.hasOption("graph-branch")) {
            graphBranch = line.getOptionValue("graph-branch", null);
        } else {
            throw new IllegalArgumentException("You must specify a graph branch name");
        }

        if (line.hasOption("output-file")) {
            outputFilename = line.getOptionValue("output-file", null);
        } else {
            throw new IllegalArgumentException("You must specify an output filename");
        }
    } catch (ParseException e) {
        e.printStackTrace();
        printHelpExit(options);
        System.exit(1);
    }

    Mongo m = new Mongo();
    //    Mongo m = new Mongo( "localhost" );
    // or
    //    Mongo m = new Mongo( "localhost" , 27017 );
    // or, to connect to a replica set, supply a seed list of members
    //    Mongo m = new Mongo(Arrays.asList(new ServerAddress("localhost", 27017),
    //                                          new ServerAddress("localhost", 27018),
    //                                          new ServerAddress("localhost", 27019)));
    m.setWriteConcern(WriteConcern.SAFE);
    DB db = m.getDB(mongoDatabaseName);
    //    boolean auth = db.authenticate(myUserName, myPassword);

    exportAscii(m, db, graphName, graphBranch, new File(outputFilename));
    System.out.println("\n\nDone.");
}

From source file:uk.ac.ncl.aries.entanglement.cli.export.MongoGraphToGDF.java

License:Apache License

public static void main(String[] args)
        throws UnknownHostException, RevisionLogException, IOException, GraphModelException {
    CommandLineParser parser = new PosixParser();
    Options options = new Options();

    //    options.addOption("g", "format-gdf", false,
    //        "Specifies that the output format is GDF (currently the only option)");

    options.addOption("h", "mongo-host", true, "The MongoDB server host to connect to.");

    options.addOption("d", "mongo-database", true, "The name of a MongoDB database to connect to.");

    options.addOption("g", "graph-name", true,
            "The name of a graph to use (there may be multiple graphs per MongoDB database).");

    options.addOption("b", "graph-branch", true,
            "The name of a graph branch to use (there may be multiple branches per graph).");

    options.addOption("c", "color-properties", true,
            "An (optional) '.properties' file that contains node type -> RGB mappings.");

    options.addOption("o", "output-file", true, "Specifies a path to a file to use ");

    //    options.addOption(OptionBuilder
    //        .withLongOpt("tags")
    //        .withArgName( "property=value" )
    //        .hasArgs(2)
    //        .withValueSeparator()
    //        .withDescription(
    //        "used to tag files when uploading.")
    //        .create( "t" ));

    if (args.length == 0) {
        printHelpExit(options);/*w w  w.  j  a v  a 2  s .com*/
    }

    String mongoHost = null;
    String mongoDatabaseName = null;
    String graphName = null;
    String graphBranch = null;
    String colorPropsFilename = null;
    String outputFilename = null;

    try {
        CommandLine line = parser.parse(options, args);

        if (line.hasOption("mongo-host")) {
            mongoHost = line.getOptionValue("mongo-host", null);
        } else {
            throw new IllegalArgumentException("You must specify a hostname");
        }

        if (line.hasOption("mongo-database")) {
            mongoDatabaseName = line.getOptionValue("mongo-database", null);
        } else {
            throw new IllegalArgumentException("You must specify a database name");
        }

        if (line.hasOption("graph-name")) {
            graphName = line.getOptionValue("graph-name", null);
        } else {
            throw new IllegalArgumentException("You must specify a graph name");
        }

        if (line.hasOption("graph-branch")) {
            graphBranch = line.getOptionValue("graph-branch", null);
        } else {
            throw new IllegalArgumentException("You must specify a graph branch name");
        }

        if (line.hasOption("output-file")) {
            outputFilename = line.getOptionValue("output-file", null);
        } else {
            throw new IllegalArgumentException("You must specify an output filename");
        }

        if (line.hasOption("color-properties")) {
            colorPropsFilename = line.getOptionValue("color-properties", null);
        }
    } catch (ParseException e) {
        e.printStackTrace();
        printHelpExit(options);
        System.exit(1);
    }

    Mongo m = new Mongo();
    //    Mongo m = new Mongo( "localhost" );
    // or
    //    Mongo m = new Mongo( "localhost" , 27017 );
    // or, to connect to a replica set, supply a seed list of members
    //    Mongo m = new Mongo(Arrays.asList(new ServerAddress("localhost", 27017),
    //                                          new ServerAddress("localhost", 27018),
    //                                          new ServerAddress("localhost", 27019)));
    m.setWriteConcern(WriteConcern.SAFE);
    DB db = m.getDB(mongoDatabaseName);
    //    boolean auth = db.authenticate(myUserName, myPassword);

    Map<String, Color> nodeColorMappings = new HashMap<>();
    if (colorPropsFilename != null) {
        nodeColorMappings.putAll(loadColorMappings(new File(colorPropsFilename)));
    }

    exportGdf(m, db, nodeColorMappings, graphName, graphBranch, new File(outputFilename));
    System.out.println("\n\nDone.");
}

From source file:uk.ac.ncl.aries.entanglement.cli.export.MongoGraphToGephi.java

License:Apache License

public static void main(String[] args)
        throws UnknownHostException, RevisionLogException, IOException, GraphModelException {
    CommandLineParser parser = new PosixParser();
    Options options = new Options();

    //    options.addOption("g", "format-gdf", false,
    //        "Specifies that the output format is GDF (currently the only option)");

    options.addOption("h", "mongo-host", true, "The MongoDB server host to connect to.");

    options.addOption("d", "mongo-database", true, "The name of a MongoDB database to connect to.");

    options.addOption("g", "graph-name", true,
            "The name of a graph to use (there may be multiple graphs per MongoDB database).");

    options.addOption("b", "graph-branch", true,
            "The name of a graph branch to use (there may be multiple branches per graph).");

    options.addOption("o", "output-file", true, "Specifies a path to a file to use ");

    if (args.length == 0) {
        printHelpExit(options);/*from   w ww.  ja v a 2 s. com*/
    }

    String mongoHost = null;
    String mongoDatabaseName = null;
    String graphName = null;
    String graphBranch = null;
    String outputFilename = null;

    try {
        CommandLine line = parser.parse(options, args);

        if (line.hasOption("mongo-host")) {
            mongoHost = line.getOptionValue("mongo-host", null);
        } else {
            throw new IllegalArgumentException("You must specify a hostname");
        }

        if (line.hasOption("mongo-database")) {
            mongoDatabaseName = line.getOptionValue("mongo-database", null);
        } else {
            throw new IllegalArgumentException("You must specify a database name");
        }

        if (line.hasOption("graph-name")) {
            graphName = line.getOptionValue("graph-name", null);
        } else {
            throw new IllegalArgumentException("You must specify a graph name");
        }

        if (line.hasOption("graph-branch")) {
            graphBranch = line.getOptionValue("graph-branch", null);
        } else {
            throw new IllegalArgumentException("You must specify a graph branch name");
        }

        if (line.hasOption("output-file")) {
            outputFilename = line.getOptionValue("output-file", null);
            if (!outputFilename.contains(".gexf") && outputFilename.contains(".pdf")
                    && outputFilename.contains(".svg") && outputFilename.contains(".gdf")) {
                throw new IllegalArgumentException(
                        "You must specify an output filename with an extension " + "of [.pdf|.svg|.gexf|gdf]");
            }
        } else {
            throw new IllegalArgumentException(
                    "You must specify an output filename with an extension " + "of [.pdf|.svg|.gexf|gdf]");
        }

    } catch (ParseException e) {
        printHelpExit(options);
        System.exit(1);
    }

    Mongo m = new Mongo();
    m.setWriteConcern(WriteConcern.SAFE);
    DB db = m.getDB(mongoDatabaseName);

    GraphCheckoutNamingScheme collectionNamer = new GraphCheckoutNamingScheme(graphName, graphBranch);
    DBCollection nodeCol = db.getCollection(collectionNamer.getNodeCollectionName());
    DBCollection edgeCol = db.getCollection(collectionNamer.getEdgeCollectionName());
    NodeDAO nodeDao = GraphDAOFactory.createDefaultNodeDAO(classLoader, m, db, nodeCol, edgeCol);
    EdgeDAO edgeDao = GraphDAOFactory.createDefaultEdgeDAO(classLoader, m, db, nodeCol, edgeCol);
    RevisionLog log = new RevisionLogDirectToMongoDbImpl(classLoader, m, db);

    MongoGraphToGephi exporter = new MongoGraphToGephi(nodeDao, edgeDao);
    exporter.exportGexf(new File(outputFilename));
    System.out.println("\n\nDone.");
}