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:org.jwebsocket.storage.mongodb.MongoDBUtils.java

License:Apache License

/**
 *
 * @param aConnection//from   ww  w . j  a  v  a  2  s  . c om
 * @param aDatabaseName
 * @param aUsername
 * @param aPassword
 * @return
 */
public static DB getDB(Mongo aConnection, String aDatabaseName, String aUsername, String aPassword) {
    DB lDB = aConnection.getDB(aDatabaseName);
    if (null != aUsername) {
        Assert.isTrue(lDB.authenticate(aUsername, aPassword.toCharArray()), "Invalid credentials!");
    }

    return lDB;
}

From source file:org.lisapark.octopus.util.json.JsonUtils.java

License:Open Source License

/**
 * Returns mongo collection using supplied properties. 
 * @param properties//from  w  w w  .  j a  va  2s.  c  o m
 * @return
 * @throws UnknownHostException 
 */
public DBCollection mongoCollection(Properties properties) throws UnknownHostException {
    DBCollection collection = null;

    Mongo mongoDb;

    String host = properties.getProperty(HOST);
    Integer port = getInteger(properties, PORT);
    String dbName = properties.getProperty(MONGO_DB_NAME);
    String collectionName = properties.getProperty(MONGO_COLLECTION);

    mongoDb = new Mongo(host, port);
    DB db = mongoDb.getDB(dbName);
    collection = db.getCollection(collectionName);

    return collection;
}

From source file:org.mediawiki.importer.XmlDumpReader.java

License:Open Source License

/**
 * Initialize a processor for a MediaWiki XML dump stream.
 * Events are sent to a single DumpWriter output sink, but you
 * can chain multiple output processors with a MultiWriter.
 * @param inputStream Stream to read XML from.
 * @param writer Output sink to send processed events to.
 *///from  w  w w  .  j av a  2 s  . c  om
public XmlDumpReader(InputStream inputStream, DumpWriter writer) {
    input = inputStream;
    this.writer = writer;
    buffer = new char[4096];
    len = 0;
    hasContent = false;

    //by philipp.staender
    try {
        //open connection to monogdb an get collections
        Mongo m = new Mongo();
        System.out.println("Initialisiere mongodb Datenbank '" + this.mongodbDatabasename + "'");
        m.dropDatabase(this.mongodbDatabasename);
        DB db = m.getDB(this.mongodbDatabasename);
        System.out.println("Setze Indizes in mongodb collections...");
        this.mongodbArticles = db.getCollection("articles");
        this.mongodbArticles.ensureIndex("title");
        if (XmlDumpReader.generateTextIndizes) {
            this.mongodbTextindexes = db.getCollection("textindex");
            this.mongodbTextindexes.ensureIndex("title");
            this.mongodbTextindexes.ensureIndex("article");
            this.mongodbTextindexes.ensureIndex("links");
            this.mongodbTextindexes.ensureIndex("sections.subtitle");
        }
    } catch (Exception e) {
        System.err.println("Fehler beim Initialisieren  der mongodb: " + e.getMessage());
        System.err.println("Applikation wird beendet");
        System.exit(0);
    }
    //open connection to mysql
    String dbURL = "jdbc:mysql://" + this.mysqlHost + ":" + this.mysqlPort + "/" + this.mysqlDatabase;
    try {
        this.mysqlConnection = (Connection) DriverManager.getConnection(dbURL, this.mysqlUsername,
                this.mysqlPassword);
        //Prepare tables for database
        System.out.println("Initialisiere notwendige Tabellen in mysql Datenbank '" + this.mysqlDatabase + "'");
        Statement stmt = (Statement) this.mysqlConnection.createStatement();
        String sql = "DROP TABLE IF EXISTS `articles`;";
        stmt.executeUpdate(sql);
        sql = "CREATE TABLE IF NOT EXISTS `articles` (  `ID` int(11) NOT NULL AUTO_INCREMENT,  `MongoID` varchar(255) NOT NULL,  `Title` varchar(255) NOT NULL,  `Redirect` varchar(255) NOT NULL,  `Comment` text NOT NULL,  `Content` longtext NOT NULL, `Links` text NOT NULL, PRIMARY KEY (`ID`),  KEY `ArticleTitle` (`Title`)) ENGINE=MyISAM  DEFAULT CHARSET=utf8;";
        stmt.executeUpdate(sql);
        if (XmlDumpReader.generateTextIndizes) {
            sql = "DROP TABLE IF EXISTS `textindex`;";
            stmt.executeUpdate(sql);
            sql = "CREATE TABLE IF NOT EXISTS `textindex` (  `ID` int(11) NOT NULL AUTO_INCREMENT,  `ArticleID` int(11) NOT NULL,  `MongoID` varchar(255) DEFAULT NULL,  `Sort` int(11) NOT NULL, `Title` varchar(255) DEFAULT NULL,  `Text` longtext,  `Links` text NOT NULL,  PRIMARY KEY (`ID`),  KEY `ArticleID` (`ArticleID`)) ENGINE=MyISAM  DEFAULT CHARSET=utf8;";
            stmt.executeUpdate(sql);
        }
    } catch (SQLException ex) {
        // handle any errors
        System.err.println("Fehler beim Initialisieren der mysql Datenbank...");
        System.err.println("SQLException: " + ex.getMessage());
        System.err.println("SQLState: " + ex.getSQLState());
        System.err.println("VendorError: " + ex.getErrorCode());
        System.err.println("Applikation wird beendet");
        System.exit(0);
    }
}

From source file:org.modeshape.jcr.value.binary.MongodbBinaryStore.java

License:Apache License

private void initMongoDatabase() {
    // connect to database
    try {/* ww  w  .  j av a  2s  . c  o m*/
        Mongo mongo = null;
        if (!replicaSet.isEmpty()) {
            mongo = new Mongo(replicaSet(replicaSet));
        } else if (!StringUtil.isBlank(host)) {
            mongo = new Mongo(host, port);
        } else {
            mongo = new Mongo();
        }
        db = mongo.getDB(database);
    } catch (UnknownHostException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.mule.module.mongo.MongoCloudConnector.java

License:Open Source License

private DB getDatabase(final Mongo mongo, final String username, final String password, final String database)
        throws ConnectionException {
    final DB db = mongo.getDB(database);
    if (StringUtils.isNotBlank(password)) {
        Validate.notNull(username, "Username must not be null if password is set");
        if (!db.isAuthenticated() && !db.authenticate(username, password.toCharArray())) {
            throw new ConnectionException(ConnectionExceptionCode.INCORRECT_CREDENTIALS, null,
                    "Couldn't connect with the given credentials");
        }//w w w  .jav  a  2s .  c  om
    }
    return db;
}

From source file:org.nutz.mongodb.log2mongodb.log4j.MongoDbAppender.java

License:Open Source License

@Override
public void activateOptions() {
    try {/*from   w  w w. j  av a2  s . c om*/
        Mongo mongo = new Mongo(hostname, port);
        DB database = mongo.getDB(databaseName);

        if (userName != null && userName.trim().length() > 0) {
            if (!database.authenticate(userName, password)) {
                throw new RuntimeException("Unable to authenticate with MongoDB server.");
            }

            // Allow password to be GCed
            password = null;
        }

        collection = database.getCollection(collectionName);
    } catch (Exception e) {
        errorHandler.error("Unexpected exception while initialising MongoDbAppender.", e,
                ErrorCode.GENERIC_FAILURE);
    }
}

From source file:org.ossmeter.factoid.cocomo.CocomoFactoid.java

License:Open Source License

public static void main(String[] args) throws Exception {
    Mongo mongo = new Mongo();
    DB db = mongo.getDB("Xtext");

    CocomoFactoid f = new CocomoFactoid();
    f.adapt(db);/*from w ww.  ja v  a 2  s . c o m*/
    f.measure(null, null, new Factoids(db));

    System.out.println(FactoidCategory.valueOf("asdasdasdd"));
}

From source file:org.ossmeter.platform.admin.FullMetricAnalysis.java

License:Open Source License

@Get("json")
public String represent() {
    Series<Header> responseHeaders = (Series<Header>) getResponse().getAttributes()
            .get("org.restlet.http.headers");
    if (responseHeaders == null) {
        responseHeaders = new Series(Header.class);
        getResponse().getAttributes().put("org.restlet.http.headers", responseHeaders);
    }//  w ww. ja v  a  2s  . c  o  m
    responseHeaders.add(new Header("Access-Control-Allow-Origin", "*"));
    responseHeaders.add(new Header("Access-Control-Allow-Methods", "GET"));

    try {
        String metricId = (String) getRequest().getAttributes().get("metricId");

        Mongo mongo = Configuration.getInstance().getMongoConnection();

        DB db = mongo.getDB("ossmeter");
        DBCollection col = db.getCollection("metricAnalysis");

        BasicDBObject query = new BasicDBObject("metricId", metricId);

        BasicDBObject sort = new BasicDBObject("analysisDate", 1);

        DBCursor cursor = col.find(query).sort(sort);

        ObjectMapper mapper = new ObjectMapper();
        ArrayNode results = mapper.createArrayNode();

        while (cursor.hasNext()) {
            DBObject obj = cursor.next();

            if ("true".equals(getQueryValue("incDate"))) {
                ObjectNode on = mapper.createObjectNode();
                on.put("date", obj.get("analysisDate").toString());
                on.put("millis", (Double) obj.get("millisTaken"));
                results.add(on);
            } else {
                results.add((Double) obj.get("millisTaken"));
            }
        }

        mongo.close();

        return results.toString();

    } catch (UnknownHostException e1) {
        e1.printStackTrace();
    }

    return null;
}

From source file:org.ossmeter.platform.admin.LoggingInformation.java

License:Open Source License

@SuppressWarnings({ "rawtypes", "unchecked" })
@Get("json")//ww w.j  a  va2 s .  c  om
public String represent() {
    @SuppressWarnings("unchecked")
    Series<Header> responseHeaders = (Series<Header>) getResponse().getAttributes()
            .get("org.restlet.http.headers");
    if (responseHeaders == null) {
        responseHeaders = new Series(Header.class);
        getResponse().getAttributes().put("org.restlet.http.headers", responseHeaders);
    }
    responseHeaders.add(new Header("Access-Control-Allow-Origin", "*"));
    responseHeaders.add(new Header("Access-Control-Allow-Methods", "GET"));

    try {
        Mongo mongo = new Mongo();

        DB db = mongo.getDB("logging");
        DBCollection col = db.getCollection("log");

        ObjectMapper mapper = new ObjectMapper();
        ArrayNode results = mapper.createArrayNode();

        DBCursor cursor = col.find();
        try {
            while (cursor.hasNext()) {
                DBObject p = cursor.next();
                p.removeField("_id");
                p.removeField("thread");
                p.removeField("host");
                p.removeField("class");
                results.add(mapper.readTree(p.toString()));
            }
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            cursor.close();
        }

        mongo.close();

        return results.toString();

    } catch (UnknownHostException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    return null;
}

From source file:org.ossmeter.platform.admin.MetricListAnalysis.java

License:Open Source License

@Get("json")
public String represent() {
    Series<Header> responseHeaders = (Series<Header>) getResponse().getAttributes()
            .get("org.restlet.http.headers");
    if (responseHeaders == null) {
        responseHeaders = new Series(Header.class);
        getResponse().getAttributes().put("org.restlet.http.headers", responseHeaders);
    }/* ww w .  jav a 2 s  . co  m*/
    responseHeaders.add(new Header("Access-Control-Allow-Origin", "*"));
    responseHeaders.add(new Header("Access-Control-Allow-Methods", "GET"));

    try {
        Mongo mongo = Configuration.getInstance().getMongoConnection();

        DB db = mongo.getDB("ossmeter");
        DBCollection col = db.getCollection("metricAnalysis");

        ObjectMapper mapper = new ObjectMapper();
        ArrayNode results = mapper.createArrayNode();

        for (Object p : col.distinct("metricId")) {
            results.add(p.toString());
        }

        mongo.close();

        return results.toString();

    } catch (UnknownHostException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    return null;
}