Java Examples for com.mongodb.DB

The following java examples will help you to understand the usage of com.mongodb.DB. These source code samples are taken from different open source projects.

Example 1
Project: qrone-master  File: MongoTest.java View source code
public static void main(String[] args) {
    Mongo m;
    try {
        m = new Mongo();
        DB db = m.getDB("test");
        DBCollection coll = db.getCollection("things");
        DBCursor cur = coll.find();
        while (cur.hasNext()) {
            System.out.println(cur.next());
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
Example 2
Project: hvdf-master  File: IndexingTaskTest.java View source code
@Test
public void shouldIndexAllCollections() throws Exception {
    String feedName = "feed1";
    String channelName = "channel1";
    String configPath = "plugin_config/indexing_task_all_channels.json";
    Channel channel = getConfiguredChannel(configPath, feedName, channelName);
    pushDataToChannel(channel, "v", 5000, 1, TimeUnit.SECONDS);
    // Wait for the task to complete
    Thread.sleep(2000);
    // Get the collections for the feed
    DB feedDB = this.testClient.getDB(feedName);
    Set<String> collNames = feedDB.getCollectionNames();
    assertEquals("Should have 5 data collections + system.indexes", 6, collNames.size());
    for (String collName : collNames) {
        if (collName.equals("system.indexes") == false) {
            DBCollection coll = feedDB.getCollection(collName);
            List<DBObject> indexes = coll.getIndexInfo();
            assertEquals("Should have _id index plus one additional", 2, indexes.size());
            assertEquals("Should have data.v_1 index", indexes.get(1).get("name"), "data.v_1");
        }
    }
}
Example 3
Project: mongodb-ide-master  File: Database.java View source code
private DB getInternalDB() throws UnknownHostException, MongoException {
    MongoServer server = (MongoServer) getParent();
    // 1) use databseName
    DB db = MongoShellCommandManager.getInstance().use(server, server.getMongo(), getName());
    String username = server.getUsername();
    // 2) authenticate if needed
    if (StringUtils.isNotEmpty(username) && !alreadyAuthenticated) {
        MongoShellCommandManager.getInstance().authenticate(server, db, username, server.getPasswordAsCharArray());
        alreadyAuthenticated = true;
    }
    return db;
}
Example 4
Project: emf-fragments-master  File: EmfFragMongoDBActivator.java View source code
public DB getDataBase(String host, int port) {
    DB dataBase = dataBases.get(host + port);
    if (dataBase == null) {
        MongoClient dbClient;
        try {
            ReadPreference.nearest();
            if (port != -1) {
                dbClient = new MongoClient(host, port);
            } else {
                dbClient = new MongoClient(host);
            }
        } catch (UnknownHostException e) {
            throw new IllegalArgumentException("Given host does not exists or DB is not running: " + host);
        }
        dataBase = dbClient.getDB("emffrag");
        dataBases.put(host + port, dataBase);
    }
    return dataBase;
}
Example 5
Project: everBeen-master  File: MongoMapStoreFactory.java View source code
/**
	 * Initializes the client connection to MongoDB
	 * 
	 * @throws UnknownHostException
	 * @param properties
	 *          connection properties
	 */
private static synchronized void initialize(final String dbname, final Properties properties) throws UnknownHostException {
    if (mongoClient == null) {
        final String username = properties.getProperty(MAP_STORE_DB_USERNAME);
        final String password = properties.getProperty(MAP_STORE_DB_PASSWORD);
        final String hostname = properties.getProperty(MAP_STORE_DB_HOSTNAME);
        mongoClient = new MongoClient(hostname, new MongoClientOptions.Builder().build());
        final DB db = mongoClient.getDB(dbname);
        if (username != null && !username.isEmpty() && password != null) {
            if (!db.authenticate(username, password.toCharArray())) {
                throw new RuntimeException("Failed to authenticate against MapStore database");
            }
        }
    }
}
Example 6
Project: NoSQLBenchmark-master  File: MongodbBenchmark.java View source code
public static void main(String[] args) {
    Configuration configuration = new PropertiesBasedConfiguration("configuration/configuration.properties");
    DataStore<DB> dataStore = new MongodbDataStore(configuration);
    BenchmarkHelper.run(configuration, dataStore, new InsertDoc(), new FindDoc(), new CompositeAction<DB>("Mongodb-InsertAndFind", new InsertDoc(), new FindDoc()));
// Mongodb-java-client use asynchronous writing to make high throughput
// and therefore could not read result by the same key immediately
// BenchmarkHelper.run(configuration, dataStore, new
// CompositeAction<DB>("Mongodb-InsertAndFind", new InsertDoc(), new
// FindDoc()));
}
Example 7
Project: cyberattack-event-collector-master  File: EventPersisterImpl.java View source code
/* (non-Javadoc)
 * @see events.EventPersister#persist(java.lang.String)
 */
public void persist(String jsonEventString, String dbName, String dbCollectionName) {
    try {
        DB db = mongo.getDB(dbName);
        DBCollection collection = db.getCollection(dbCollectionName);
        DBObject dbObject = (DBObject) JSON.parse(jsonEventString);
        collection.insert(dbObject);
    } catch (Exception e) {
        logger.log(Level.SEVERE, "Error persisting event: ", e);
    }
}
Example 8
Project: effektif-master  File: MongoGridFSSupplier.java View source code
@Override
public Object supply(Brewery brewery) {
    MongoConfiguration mongoConfiguration = brewery.get(MongoConfiguration.class);
    MongoClient mongoClient = brewery.get(MongoClient.class);
    String filedatabaseName = mongoConfiguration.getFileDatabaseName();
    DB db = mongoClient.getDB(filedatabaseName);
    return new GridFS(db);
}
Example 9
Project: elasticsearch-repository-gridfs-master  File: GridFsService.java View source code
public synchronized DB mongoDB(String host, int port, String databaseName, String username, String password) {
    if (mongoDB != null) {
        return mongoDB;
    }
    try {
        MongoClient client = new MongoClient(host, port);
        mongoDB = client.getDB(databaseName);
        if (username != null && password != null) {
            mongoDB.authenticate(username, password.toCharArray());
        }
        return mongoDB;
    } catch (UnknownHostException e) {
        throw new ElasticsearchIllegalArgumentException("Unknown host", e);
    }
}
Example 10
Project: M101J-master  File: Week1Homework4.java View source code
public static void main(String[] args) throws UnknownHostException {
    final Configuration configuration = new Configuration();
    configuration.setClassForTemplateLoading(Week1Homework4.class, "/");
    MongoClient client = new MongoClient(new ServerAddress("localhost", 27017));
    DB database = client.getDB("m101");
    final DBCollection collection = database.getCollection("funnynumbers");
    Spark.get(new Route("/") {

        @Override
        public Object handle(final Request request, final Response response) {
            StringWriter writer = new StringWriter();
            try {
                Template helloTemplate = configuration.getTemplate("answer.ftl");
                // Not necessary yet to understand this.  It's just to prove that you
                // are able to run a command on a mongod server
                AggregationOutput output = collection.aggregate(new BasicDBObject("$group", new BasicDBObject("_id", "$value").append("count", new BasicDBObject("$sum", 1))), new BasicDBObject("$match", new BasicDBObject("count", new BasicDBObject("$lte", 2))), new BasicDBObject("$sort", new BasicDBObject("_id", 1)));
                int answer = 0;
                for (DBObject doc : output.results()) {
                    answer += (Double) doc.get("_id");
                }
                Map<String, String> answerMap = new HashMap<String, String>();
                answerMap.put("answer", Integer.toString(answer));
                helloTemplate.process(answerMap, writer);
            } catch (Exception e) {
                logger.error("Failed", e);
                halt(500);
            }
            return writer;
        }
    });
}
Example 11
Project: mongo-rest-master  File: MongoFactoryBean.java View source code
protected DB createDB() throws Exception {
    DB db = createInstance().getDB(configuration.getDataStoreName());
    if (!StringUtils.isNullOrEmpty(configuration.getDataStoreUsername()) && !StringUtils.isNullOrEmpty(configuration.getDataStorePassword())) {
        db.authenticate(configuration.getDataStoreUsername(), configuration.getDataStorePassword().toCharArray());
    }
    return db;
}
Example 12
Project: play-jongo-master  File: PlayJongo.java View source code
private void configure(Configuration config, ClassLoader classLoader, boolean isTestMode) throws Exception {
    String clientFactoryName = config.getString("playjongo.mongoClientFactory");
    MongoClientFactory factory = getMongoClientFactory(clientFactoryName, config, isTestMode);
    mongo = factory.createClient();
    if (mongo == null) {
        throw new IllegalStateException("No MongoClient was created by instance of " + factory.getClass().getName());
    }
    DB db = mongo.getDB(factory.getDBName());
    jongo = new Jongo(db, createMapper(config, classLoader));
    if (config.getBoolean("playjongo.gridfs.enabled", false)) {
        gridfs = new GridFS(jongo.getDatabase());
    }
}
Example 13
Project: TadpoleForDBTools-master  File: MongoTestServerSideJavascript.java View source code
/**
	 * @param args
	 */
public static void main(String[] args) throws Exception {
    ConAndAuthentication testMongoCls = new ConAndAuthentication();
    Mongo mongo = testMongoCls.connection(ConAndAuthentication.serverurl, ConAndAuthentication.port);
    DB db = mongo.getDB("test");
    createServerSideJavaScript(db);
    updateServerSideJavaScript(db, "addNumbers", "update java script");
    findAllServerSideJavaScript(db);
    Object[] arryArgs = { 25, 34 };
    evalServerSideJavaScript(db, "addNumbers2", arryArgs);
    mongo.close();
    try {
        Thread.sleep(1);
    } catch (Exception e) {
    }
}
Example 14
Project: mongobee-master  File: ChangeEntryDao.java View source code
public MongoDatabase connectMongoDb(MongoClient mongo, String dbName) throws MongobeeConfigurationException {
    if (!hasText(dbName)) {
        throw new MongobeeConfigurationException("DB name is not set. Should be defined in MongoDB URI or via setter");
    } else {
        this.mongoClient = mongo;
        // for Jongo driver and backward compatibility (constructor has required parameter Jongo(DB) )
        db = mongo.getDB(dbName);
        mongoDatabase = mongo.getDatabase(dbName);
        ensureChangeLogCollectionIndex(mongoDatabase.getCollection(CHANGELOG_COLLECTION));
        initializeLock();
        return mongoDatabase;
    }
}
Example 15
Project: 10gen-m101j-master  File: Week1Homework4.java View source code
public static void main(String[] args) throws UnknownHostException {
    final Configuration configuration = new Configuration();
    configuration.setClassForTemplateLoading(Week1Homework4.class, "/");
    MongoClient client = new MongoClient(new ServerAddress("localhost", 27017));
    DB database = client.getDB("m101");
    final DBCollection collection = database.getCollection("funnynumbers");
    Spark.get(new Route("/") {

        @Override
        public Object handle(final Request request, final Response response) {
            StringWriter writer = new StringWriter();
            try {
                Template helloTemplate = configuration.getTemplate("answer.ftl");
                // Not necessary yet to understand this.  It's just to prove that you
                // are able to run a command on a mongod server
                AggregationOutput output = collection.aggregate(new BasicDBObject("$group", new BasicDBObject("_id", "$value").append("count", new BasicDBObject("$sum", 1))), new BasicDBObject("$match", new BasicDBObject("count", new BasicDBObject("$lte", 2))), new BasicDBObject("$sort", new BasicDBObject("_id", 1)));
                int answer = 0;
                for (DBObject doc : output.results()) {
                    answer += (Double) doc.get("_id");
                }
                Map<String, String> answerMap = new HashMap<String, String>();
                answerMap.put("answer", Integer.toString(answer));
                helloTemplate.process(answerMap, writer);
            } catch (Exception e) {
                logger.error("Failed", e);
                halt(500);
            }
            return writer;
        }
    });
}
Example 16
Project: cdo-master  File: MongoDBConfig.java View source code
protected void dropDatabase(MongoURI mongoURI, String repoName) {
    Mongo mongo = null;
    try {
        mongo = new Mongo(mongoURI);
        DB db = mongo.getDB(repoName);
        if (!db.getCollectionNames().isEmpty()) {
            db.dropDatabase();
        }
    } catch (Exception ex) {
        throw WrappedException.wrap(ex);
    } finally {
        if (mongo != null) {
            mongo.close();
        }
    }
}
Example 17
Project: course-mongodb-M101J-master  File: DotNotationTest.java View source code
public static void main(String[] args) throws UnknownHostException {
    MongoClient client = new MongoClient();
    DB db = client.getDB("course");
    DBCollection lines = db.getCollection("DotNotationTest");
    lines.drop();
    Random rand = new Random();
    // insert 10 lines with random start and end points
    for (int i = 0; i < 10; i++) {
        lines.insert(new BasicDBObject("_id", i).append("start", new BasicDBObject("x", rand.nextInt(90) + 10).append("y", rand.nextInt(90) + 10)).append("end", new BasicDBObject("x", rand.nextInt(90) + 10).append("y", rand.nextInt(90) + 10)));
    }
    QueryBuilder builder = QueryBuilder.start("start.x").greaterThan(50);
    DBCursor cursor = lines.find(builder.get(), new BasicDBObject("start.y", true).append("_id", false));
    try {
        while (cursor.hasNext()) {
            DBObject cur = cursor.next();
            System.out.println(cur);
        }
    } finally {
        cursor.close();
    }
}
Example 18
Project: debop4j-master  File: LoadSelectedColumnsInEntityTest.java View source code
@Override
protected void addExtraColumn() {
    MongoDBDatastoreProvider provider = (MongoDBDatastoreProvider) super.getService(DatastoreProvider.class);
    DB database = provider.getDatabase();
    DBCollection collection = database.getCollection("Project");
    BasicDBObject query = new BasicDBObject(1);
    query.put("_id", "projectID");
    BasicDBObject updater = new BasicDBObject(1);
    updater.put("$push", new BasicDBObject("extraColumn", 1));
    collection.update(query, updater);
}
Example 19
Project: embedmongo.flapdoodle.de-master  File: MongoExecutableTest.java View source code
@Test
public void testStartStopTenTimesWithNewMongoExecutable() throws IOException {
    boolean useMongodb = false;
    int loops = 10;
    MongodConfig mongodConfig = new MongodConfig(Version.V2_0, 12345, Network.localhostIsIPv6());
    for (int i = 0; i < loops; i++) {
        _logger.info("Loop: " + i);
        MongodExecutable mongodExe = MongoDBRuntime.getDefaultInstance().prepare(mongodConfig);
        MongodProcess mongod = mongodExe.start();
        if (useMongodb) {
            Mongo mongo = new Mongo("localhost", mongodConfig.getPort());
            DB db = mongo.getDB("test");
            DBCollection col = db.createCollection("testCol", new BasicDBObject());
            col.save(new BasicDBObject("testDoc", new Date()));
        }
        mongod.stop();
        mongodExe.cleanup();
    }
}
Example 20
Project: fudanweixin-master  File: TestPushMsg.java View source code
@Test
public void balance() throws Exception {
    String uid = "04538";
    String clientid = "ecard";
    String pass = "4c9cc8d2a1b6cfa7f6019b0c38c9ee537d100861";
    String enckey = "cb2c197c4ca21cad80fd4a85cdb0efb33d620d43d9548f7a";
    DB db = MongoUtil.getInstance().getDB();
    DBObject user = db.getCollection("Bindings").findOne(new BasicDBObject("binds", new BasicDBObject("$elemMatch", new BasicDBObject("uisid", uid))));
    BindingHelper.removeOthers(user, uid);
    BasicDBList l = new TACOAuth2Model().yktxx(user);
    Object balance = ((DBObject) l.get(0)).get("card_balance") + "Ôª";
    Object username = ((DBObject) l.get(0)).get("username") + " (" + uid + ")";
    DBObject data = new BasicDBObject("url", Config.getInstance().get("weixin.context")).append("first", "目�账�余�").append("name", username).append("money", balance).append("remark", "本消�仅供测试");
    long now = System.currentTimeMillis();
    String userenc = EncodeHelper.bytes2hex(EncodeHelper.encrypt("DESede", (pass + now).getBytes(), EncodeHelper.hex2bytes(enckey), null));
    DBObject head = new BasicDBObject("template", "ecard_balance").append("touser", uid).append("timestamp", now).append("clientid", clientid).append("userenc", userenc).append("checksum", EncodeHelper.digest(JSON.serialize(data).replaceAll("[ \\r\\n\\t]", "") + uid + userenc, "SHA"));
    System.out.println(JSON.serialize(head).replaceAll("[ \\r\\n]", ""));
    System.out.println(CommonUtil.postWebRequest(Config.getInstance().get("weixin.context") + "msgpush.act", JSON.serialize(new BasicDBObject("head", head).append("data", data)).getBytes("utf-8"), "application/json"));
}
Example 21
Project: GeoGig-master  File: MongoGraphDatabaseTest.java View source code
@Override
protected MongoGraphDatabase createDatabase(Platform platform) throws Exception {
    final IniMongoProperties properties = new IniMongoProperties();
    final String uri = properties.get("mongodb.uri", String.class).or("mongodb://localhost:27017/");
    final String database = properties.get("mongodb.database", String.class).or("geogig");
    MongoClient client = new MongoClient(new MongoClientURI(uri));
    DB db = client.getDB(database);
    db.dropDatabase();
    MongoConnectionManager manager = new MongoConnectionManager();
    ConfigDatabase config = new TestConfigDatabase(platform);
    MongoGraphDatabase mongoGraphDatabase = new MongoGraphDatabase(manager, config);
    return mongoGraphDatabase;
}
Example 22
Project: gig-master  File: MongoGraphDatabaseTest.java View source code
@Override
protected MongoGraphDatabase createDatabase(Platform platform) throws Exception {
    final IniMongoProperties properties = new IniMongoProperties();
    final String uri = properties.get("mongodb.uri", String.class).or("mongodb://localhost:27017/");
    final String database = properties.get("mongodb.database", String.class).or("geogig");
    MongoClient client = new MongoClient(new MongoClientURI(uri));
    DB db = client.getDB(database);
    db.dropDatabase();
    MongoConnectionManager manager = new MongoConnectionManager();
    ConfigDatabase config = new TestConfigDatabase(platform);
    MongoGraphDatabase mongoGraphDatabase = new MongoGraphDatabase(manager, config);
    return mongoGraphDatabase;
}
Example 23
Project: giulius-master  File: CollectionProvider.java View source code
private DBCollection _get() {
    DB d = db.get();
    if (!d.collectionExists(name)) {
        synchronized (this) {
            if (!d.collectionExists(name)) {
                BasicDBObject arg = new BasicDBObject();
                MongoInitializer.Registry registry = reg.get();
                try {
                    registry.onBeforeCreateCollection(name, arg);
                    DBCollection coll = d.createCollection(name, arg);
                    registry.onCreateCollection(coll);
                    return collection = coll;
                } catch (MongoCommandException ex) {
                    if ("collection already exists".equals(ex.getErrorMessage())) {
                        return d.getCollection(name);
                    }
                    return Exceptions.chuck(ex);
                }
            } else {
                return collection = d.getCollection(name);
            }
        }
    } else {
        return collection = d.getCollection(name);
    }
}
Example 24
Project: Grapes-master  File: MigrationTask.java View source code
private Jongo initDBConnection() throws Exception {
    final ServerAddress address = new ServerAddress(config.getHost(), config.getPort());
    mongo = new MongoClient(address);
    final DB db = mongo.getDB(config.getDatastore());
    if (config.getUser() != null && config.getPwd() != null) {
        db.authenticate(config.getUser(), config.getPwd());
    }
    return new Jongo(db);
}
Example 25
Project: java-test-applications-master  File: MongoDbUtils.java View source code
public String getUrl(MongoDbFactory mongoDbFactory) {
    DB mongoDb = mongoDbFactory.getDb();
    if (mongoDb != null) {
        StringBuilder builder = new StringBuilder();
        List<ServerAddress> serverAddresses = mongoDb.getMongo().getAllAddress();
        builder.append(getServerString(mongoDb, serverAddresses.get(0)));
        for (int i = 1; i < serverAddresses.size(); i++) {
            builder.append(", ").append(getServerString(mongoDb, serverAddresses.get(i)));
        }
        return builder.toString();
    }
    return "mongodb://fake.connection";
}
Example 26
Project: jetty-plugin-support-master  File: MongoTest.java View source code
public static void main(String... args) throws Exception {
    Mongo m = new Mongo("127.0.0.1", 27017);
    DB db = m.getDB("mydb");
    Set<String> colls = db.getCollectionNames();
    System.err.println("Colls=" + colls);
    DBCollection coll = db.getCollection("testCollection");
    BasicDBObject key = new BasicDBObject("id", "1234");
    BasicDBObject sets = new BasicDBObject("name", "value");
    BasicDBObject upsert = new BasicDBObject("$set", sets);
    WriteResult result = coll.update(key, upsert, true, false);
    System.err.println(result.getLastError());
    while (coll.count() > 0) {
        DBObject docZ = coll.findOne();
        System.err.println("removing    " + docZ);
        if (docZ != null)
            coll.remove(docZ);
    }
}
Example 27
Project: jetty-spdy-master  File: MongoTest.java View source code
public static void main(String... args) throws Exception {
    Mongo m = new Mongo("127.0.0.1", 27017);
    DB db = m.getDB("mydb");
    Set<String> colls = db.getCollectionNames();
    System.err.println("Colls=" + colls);
    DBCollection coll = db.getCollection("testCollection");
    BasicDBObject key = new BasicDBObject("id", "1234");
    BasicDBObject sets = new BasicDBObject("name", "value");
    BasicDBObject upsert = new BasicDBObject("$set", sets);
    WriteResult result = coll.update(key, upsert, true, false);
    System.err.println(result.getLastError());
    while (coll.count() > 0) {
        DBObject docZ = coll.findOne();
        System.err.println("removing    " + docZ);
        if (docZ != null)
            coll.remove(docZ);
    }
}
Example 28
Project: jetty.project-master  File: MongoTest.java View source code
public static void main(String... args) throws Exception {
    Mongo m = new Mongo("127.0.0.1", 27017);
    DB db = m.getDB("mydb");
    Set<String> colls = db.getCollectionNames();
    System.err.println("Colls=" + colls);
    DBCollection coll = db.getCollection("testCollection");
    BasicDBObject key = new BasicDBObject("id", "1234");
    BasicDBObject sets = new BasicDBObject("name", "value");
    BasicDBObject upsert = new BasicDBObject("$set", sets);
    WriteResult result = coll.update(key, upsert, true, false);
    System.err.println(result.getLastError());
    while (coll.count() > 0) {
        DBObject docZ = coll.findOne();
        System.err.println("removing    " + docZ);
        if (docZ != null)
            coll.remove(docZ);
    }
}
Example 29
Project: jmeter-master  File: MongoDB.java View source code
public DB getDB(String database, String username, String password) {
    if (log.isDebugEnabled()) {
        log.debug("username: " + username + ", password: " + password + ", database: " + database);
    }
    DB db = mongo.getDB(database);
    boolean authenticated = db.isAuthenticated();
    if (!authenticated) {
        if (username != null && password != null && username.length() > 0 && password.length() > 0) {
            authenticated = db.authenticate(username, password.toCharArray());
        }
    }
    if (log.isDebugEnabled()) {
        log.debug("authenticated: " + authenticated);
    }
    return db;
}
Example 30
Project: Liferay-plugins-master  File: MongoExpandoTableLocalServiceImpl.java View source code
@Override
public ExpandoTable updateTable(long tableId, String name) throws PortalException {
    ExpandoTable expandoTable = super.getTable(tableId);
    DB db = MongoDBUtil.getDB(expandoTable.getCompanyId());
    String collectionName = MongoDBUtil.getCollectionName(expandoTable.getClassName(), expandoTable.getName());
    String newCollectionName = MongoDBUtil.getCollectionName(expandoTable.getClassName(), name);
    if (db.collectionExists(newCollectionName)) {
        throw new DuplicateTableNameException(name);
    }
    expandoTable = super.updateTable(tableId, name);
    if (db.collectionExists(collectionName)) {
        DBCollection dbCollection = db.getCollection(collectionName);
        dbCollection.rename(newCollectionName);
    } else {
        db.createCollection(newCollectionName, null);
    }
    return expandoTable;
}
Example 31
Project: MongOCOM-master  File: IntegerGenerator.java View source code
@Override
public Integer generateValue(Class parent, DB db) {
    DBCollection collection = db.getCollection("values_" + parent.getSimpleName());
    DBObject o = collection.findOne();
    int value = 0;
    if (o != null) {
        value = (int) o.get("generatedValue");
    } else {
        o = new BasicDBObject("generatedValue", value);
    }
    o.put("generatedValue", ++value);
    collection.save(o);
    return value;
}
Example 32
Project: mongoDB-course-M101J-master  File: Week1Homework4.java View source code
public static void main(String[] args) throws UnknownHostException {
    final Configuration configuration = new Configuration();
    configuration.setClassForTemplateLoading(Week1Homework4.class, "/");
    MongoClient client = new MongoClient(new ServerAddress("localhost", 27017));
    DB database = client.getDB("m101");
    final DBCollection collection = database.getCollection("funnynumbers");
    Spark.get(new Route("/") {

        @Override
        public Object handle(final Request request, final Response response) {
            StringWriter writer = new StringWriter();
            try {
                Template helloTemplate = configuration.getTemplate("answer.ftl");
                // Not necessary yet to understand this.  It's just to prove that you
                // are able to run a command on a mongod server
                AggregationOutput output = collection.aggregate(new BasicDBObject("$group", new BasicDBObject("_id", "$value").append("count", new BasicDBObject("$sum", 1))), new BasicDBObject("$match", new BasicDBObject("count", new BasicDBObject("$lte", 2))), new BasicDBObject("$sort", new BasicDBObject("_id", 1)));
                int answer = 0;
                for (DBObject doc : output.results()) {
                    answer += (Double) doc.get("_id");
                }
                Map<String, String> answerMap = new HashMap<String, String>();
                answerMap.put("answer", Integer.toString(answer));
                helloTemplate.process(answerMap, writer);
            } catch (Exception e) {
                logger.error("Failed", e);
                halt(500);
            }
            return writer;
        }
    });
}
Example 33
Project: mongodb-m101j-training-master  File: Week1Homework4.java View source code
public static void main(String[] args) throws UnknownHostException {
    final Configuration configuration = new Configuration();
    configuration.setClassForTemplateLoading(Week1Homework4.class, "/");
    MongoClient client = new MongoClient(new ServerAddress("localhost", 27017));
    DB database = client.getDB("m101");
    final DBCollection collection = database.getCollection("funnynumbers");
    Spark.get(new Route("/") {

        @Override
        public Object handle(final Request request, final Response response) {
            StringWriter writer = new StringWriter();
            try {
                Template helloTemplate = configuration.getTemplate("answer.ftl");
                // Not necessary yet to understand this.  It's just to prove that you
                // are able to run a command on a mongod server
                AggregationOutput output = collection.aggregate(new BasicDBObject("$group", new BasicDBObject("_id", "$value").append("count", new BasicDBObject("$sum", 1))), new BasicDBObject("$match", new BasicDBObject("count", new BasicDBObject("$lte", 2))), new BasicDBObject("$sort", new BasicDBObject("_id", 1)));
                int answer = 0;
                for (DBObject doc : output.results()) {
                    answer += (Double) doc.get("_id");
                }
                Map<String, String> answerMap = new HashMap<String, String>();
                answerMap.put("answer", Integer.toString(answer));
                helloTemplate.process(answerMap, writer);
            } catch (Exception e) {
                logger.error("Failed", e);
                halt(500);
            }
            return writer;
        }
    });
}
Example 34
Project: mongolyn-master  File: RepositorySettingsPage.java View source code
@Override
public void run(IProgressMonitor progressMonitor) throws CoreException {
    progressMonitor.beginTask(Messages.RepositorySettingsPage_ValidateRepositorySettings, 1);
    DB db = null;
    try {
        db = MongolynUtils.openNewDB(repository);
        db.getCollectionNames();
        progressMonitor.worked(1);
    } finally {
        if (db != null)
            db.getMongo().close();
        progressMonitor.done();
    }
}
Example 35
Project: mongoom.flapdoodle.de-master  File: Indexes.java View source code
public static void ensureIndex(DB db, IndexDef index, String collectionName) {
    // public <T> void ensureIndex(Class<T> clazz, String name,
    // Set<IndexFieldDef> defs, boolean unique,
    // boolean dropDupsOnCreate) {
    BasicDBObjectBuilder keys = BasicDBObjectBuilder.start();
    BasicDBObjectBuilder keyOpts = null;
    List<FieldIndex> indexSorted = Lists.newArrayList(index.fields());
    Collections.sort(indexSorted, new Comparator<FieldIndex>() {

        @Override
        public int compare(FieldIndex o1, FieldIndex o2) {
            if (o1.priority() == o2.priority())
                return 0;
            if (o1.priority() < o2.priority())
                return 1;
            return -1;
        }
    });
    for (FieldIndex def : indexSorted) {
        String fieldName = def.name();
        Direction dir = def.direction();
        if (dir == Direction.BOTH)
            keys.add(fieldName, 1).add(fieldName, -1);
        else
            keys.add(fieldName, (dir == Direction.ASC) ? 1 : -1);
    }
    String name = index.name();
    if (name != null && !name.isEmpty()) {
        if (keyOpts == null)
            keyOpts = new BasicDBObjectBuilder();
        keyOpts.add("name", name);
    }
    if (index.unique()) {
        if (keyOpts == null)
            keyOpts = new BasicDBObjectBuilder();
        keyOpts.add("unique", true);
        if (index.dropDups())
            keyOpts.add("dropDups", true);
    }
    if (index.sparse()) {
        if (keyOpts == null)
            keyOpts = new BasicDBObjectBuilder();
        keyOpts.add("sparse", true);
    }
    try {
        db.requestStart();
        DBCollection dbColl = db.getCollection(collectionName);
        DBObject indexKeys = keys.get();
        //			DatastoreImpl._logger.info("Ensuring index for " + dbColl.getName() + "." + index + " with keys " + indexKeys);
        if (keyOpts == null) {
            _logger.info("Ensuring index for " + dbColl.getName() + "." + index + " with keys " + indexKeys);
            dbColl.ensureIndex(indexKeys);
        } else {
            DBObject options = keyOpts.get();
            _logger.info("Ensuring index for " + dbColl.getName() + "." + index + " with keys " + indexKeys + " and opts " + options);
            dbColl.ensureIndex(indexKeys, options);
        }
    } finally {
        Errors.checkError(db, Operation.Insert);
        db.requestDone();
    }
}
Example 36
Project: morphia-master  File: TestIndexCollections.java View source code
@Test
public void testEmbedded() {
    AdvancedDatastore ads = getAds();
    DB db = getDb();
    getMorphia().map(HasEmbeddedIndex.class);
    ads.ensureIndexes();
    ads.ensureIndexes("b_2", HasEmbeddedIndex.class);
    BasicDBObject[] indexes = new BasicDBObject[] { new BasicDBObject("name", 1), new BasicDBObject("embeddedIndex.color", -1), new BasicDBObject("embeddedIndex.name", 1) };
    testIndex(db.getCollection("b_2").getIndexInfo(), indexes);
    testIndex(ads.getCollection(HasEmbeddedIndex.class).getIndexInfo(), indexes);
}
Example 37
Project: MyCassandra-master  File: MongoConfigure.java View source code
public DB connect(String dbName, String host, int port, String user, String pass) {
    try {
        Mongo mongo = new Mongo(host, port);
        DB db = mongo.getDB(dbName);
        if (user != null && pass != null)
            if (!db.authenticate(user, pass.toCharArray()))
                throw new Exception("authentication error!!");
        return db;
    } catch (Exception e) {
        System.err.println("can't connect MongoDB [host: " + host + " port:" + port + " user:" + user + "]");
        System.exit(1);
    }
    return null;
}
Example 38
Project: nutch-mongodb-indexer-master  File: MongodbWriter.java View source code
@Override
public void write(NutchDocument doc) throws IOException {
    // Connect to a mongodb database
    DB db = mongo.getDB("nutch");
    DBCollection col = db.getCollection("index");
    // Setup the mongodb db object
    BasicDBObject mongoDoc = new BasicDBObject();
    for (final Entry<String, NutchField> e : doc) {
        for (final Object val : e.getValue().getValues()) {
            String key;
            // normalise the string representation for a Date
            Object val2 = val;
            if (val instanceof Date) {
                key = e.getKey();
                val2 = DateUtil.getThreadLocalDateFormat().format(val);
                mongoDoc.put(key, val2);
            } else {
                key = e.getKey();
                mongoDoc.put(key, val);
            }
        }
    }
    // insert the document into mongodb
    col.insert(mongoDoc);
}
Example 39
Project: OldLilliput-master  File: PlaceEvents.java View source code
@SuppressWarnings("rawtypes")
@Get("json")
public JsonRepresentation toJson() throws JSONException {
    try {
        String epc = (String) getRequest().getAttributes().get("uid");
        //Save Space to Ontology if it is not saved
        RemoteProjectManager rpm = RemoteProjectManager.getInstance();
        Project p = rpm.getProject("localhost:5100", "Lilliput", "1234", "IoTSocialGraph", true);
        OWLModel owlModel = (OWLModel) p.getKnowledgeBase();
        RDFIndividual spaceInd = owlModel.getOWLIndividual(epc);
        OWLObjectProperty objectEventProp = owlModel.getOWLObjectProperty("hasObjectEventIn");
        OWLObjectProperty spaceEventProp = owlModel.getOWLObjectProperty("hasSpaceEvent");
        JSONObject returnJSON = new JSONObject();
        List<String> objectEventIDs = new ArrayList<String>();
        List<String> spaceEventIDs = new ArrayList<String>();
        Collection oeCol = spaceInd.getPropertyValues(objectEventProp);
        Iterator oeIter = oeCol.iterator();
        Collection seCol = spaceInd.getPropertyValues(spaceEventProp);
        Iterator seIter = seCol.iterator();
        while (oeIter.hasNext()) {
            RDFIndividual tempInd = (RDFIndividual) oeIter.next();
            objectEventIDs.add(Util.individualToBrowserText(tempInd.getBrowserText()));
            System.out.println(tempInd.getBrowserText() + "is added to list");
        }
        while (seIter.hasNext()) {
            RDFIndividual tempInd = (RDFIndividual) seIter.next();
            spaceEventIDs.add(Util.individualToBrowserText(tempInd.getBrowserText()));
            System.out.println(tempInd.getBrowserText() + "is added to list");
        }
        Mongo m = new Mongo("143.248.106.26", 27017);
        DB db = m.getDB("Lilliput");
        //¾îÂ÷ÇÇ size ´Â 1ÀÓ.
        for (int i = 0; i < objectEventIDs.size(); i++) {
            DBCollection collection = db.getCollection("ObjectEvent");
            DBObject query = new BasicDBObject();
            query.put("_id", new ObjectId(objectEventIDs.get(i)));
            DBObject queriedObject = collection.findOne(query);
            Map queriedMap = queriedObject.toMap();
            JSONObject queriedJson = new JSONObject(queriedMap);
            returnJSON.put("ObjectEvent", queriedJson);
        }
        for (int i = 0; i < spaceEventIDs.size(); i++) {
            DBCollection collection = db.getCollection("SpaceEvent");
            DBObject query = new BasicDBObject();
            query.put("_id", new ObjectId(spaceEventIDs.get(i)));
            DBObject queriedObject = collection.findOne(query);
            Map queriedMap = queriedObject.toMap();
            JSONObject queriedJson = new JSONObject(queriedMap);
            returnJSON.put("SpaceEvent", queriedJson);
        }
        JsonRepresentation representation = new JsonRepresentation(returnJSON);
        return representation;
    } catch (UnknownHostException e) {
        e.printStackTrace();
    } catch (MongoException e) {
        e.printStackTrace();
    } catch (JSONException e) {
        e.printStackTrace();
    }
    JSONObject err = new JSONObject();
    err.put("message", "error occured");
    JsonRepresentation representation = new JsonRepresentation(err);
    return representation;
}
Example 40
Project: projects-master  File: edx_to_moodle_section.java View source code
public static void main(String[] args) throws ClassNotFoundException, UnknownHostException, SQLException {
    Class.forName("com.mysql.jdbc.Driver");
    Connection conn = null;
    conn = DriverManager.getConnection(DB_URL, USER, PASS);
    //mysql statement
    Statement stmt = conn.createStatement();
    //To connect to mongodb server
    MongoClient mongoClient = new MongoClient("localhost", 27017);
    //Now connect to your databases
    DB db = mongoClient.getDB("xmodule");
    //System.out.println("Connection to Database Successfull");
    DBCollection coll = db.getCollection("modulestore");
    //System.out.println("Collection Selected Successfull");
    BasicDBObject query = new BasicDBObject("_id.category", "chapter");
    //BasicDBObject query = new BasicDBObject("_id.category", "course").append("_id.course", "CS201");
    DBCursor cursor = coll.find(query);
    String resulta = "", resultb = "";
    while (cursor.hasNext()) {
        DBObject tobj = cursor.next();
        resulta = tobj.get("_id").toString();
        resultb = tobj.get("metadata").toString();
    }
    //System.out.println(resulta);
    String[] temp1 = resulta.split(":");
    String resa = temp1[3];
    String[] resb = resa.split(",");
    String resc = resb[0];
    String resd = resc.substring(2, resc.length() - 2);
    System.out.println(resd);
    //System.out.println(resultb);
    String[] temp2 = resultb.split(":");
    String rese = temp2[1];
    String newsectionname = rese.substring(2, rese.length() - 2);
    System.out.println(newsectionname);
    cursor.close();
    String sql = "select * from mdl_course where idnumber = '" + resd + "'";
    //System.out.println(sql);
    ResultSet rs = stmt.executeQuery(sql);
    int id = 0;
    while (rs.next()) {
        id = rs.getInt("id");
    }
    //System.out.println(id);
    sql = "select * from mdl_course_sections where course = " + id + " and name!='null'";
    //sql = "select * from mdl_course_sections where course = 65 and name!='null'";
    rs = stmt.executeQuery(sql);
    String name = "";
    int flag = 1;
    while (rs.next()) {
        name = rs.getString("name");
        if (name.compareTo(newsectionname) == 0)
            flag = 0;
    }
    if (flag == 1) {
        //System.out.println(sql);
        rs = stmt.executeQuery(sql);
        sql = "select id from mdl_course_sections where section=0 and course = " + id;
        //sql ="select id from mdl_course_sections where section=0 and course = 65";
        rs = stmt.executeQuery(sql);
        int id1 = 0;
        while (rs.next()) {
            id1 = rs.getInt("id");
        }
        sql = "select * from mdl_course_sections where course = " + id + " and name!='null'";
        //sql = "select * from mdl_course_sections where course = 65 and name!='null'";
        rs = stmt.executeQuery(sql);
        while (rs.next()) {
            id1 = rs.getInt("id");
        }
        id1++;
        System.out.println(id1);
        sql = "update mdl_course_sections set name='" + newsectionname + "' where id=" + id1;
        stmt.execute(sql);
    }
}
Example 41
Project: smartly-master  File: SmartlyMongoTest.java View source code
// ------------------------------------------------------------------------
//                      p r i v a t e
// ------------------------------------------------------------------------
@Test
public void testMain() throws Exception {
    DB db = MongoDBConnectionFactory.getDB("MONGO_sample");
    MongoSchema schema = new MongoSchema(db);
    schema.initialize();
    // try insert and remove user
    MongoUserService srvc = new MongoUserService(db, MongoDBConnectionFactory.getLanguages());
    final MongoUser user = new MongoUser();
    MongoUser.setId(user, "TEST___USER");
    MongoUser.setUserName(user, "test-user");
    srvc.upsert(user);
    DBObject dbuser = srvc.getById(MongoUser.getId(user), false);
    Assert.assertTrue(null != dbuser);
    srvc.remove(user);
    dbuser = srvc.getById(MongoUser.getId(user), false);
    Assert.assertNull(dbuser);
}
Example 42
Project: Trivial4b-master  File: RemoteMongoDB.java View source code
/**
	 * Este metodo se conecta con la base de datos remota y obtiene las
	 * preguntas almacenadas, recogiendolas en una List de objetos Pregunta
	 * 
	 * @return List<Pregunta> lista de preguntas cargadas desde la base de datos
	 *         remota
	 */
public List<Pregunta> cargarPreguntas() {
    List<Pregunta> listaPreguntas = new ArrayList<Pregunta>();
    MongoClient mongoClient = null;
    BufferedReader br = null;
    try {
        br = new BufferedReader(new InputStreamReader(getClass().getClassLoader().getResourceAsStream("db/userReader.mongouser")));
        String user = "";
        String pass = "";
        while (br.ready()) {
            String linea = br.readLine();
            if (linea.contains("user="))
                user = linea.split("=")[1];
            else if (linea.contains("pass="))
                pass = linea.split("=")[1];
        }
        br.close();
        MongoCredential mongoCredential = MongoCredential.createMongoCRCredential(user, "trivial", pass.toCharArray());
        mongoClient = new MongoClient(new ServerAddress("ds062797.mongolab.com", 62797), Arrays.asList(mongoCredential));
        // Conectar con nuestra base de datos
        DB db = mongoClient.getDB("trivial");
        System.out.println("Conexion creada con la base de datos");
        DBCollection preguntas = db.getCollection("preguntas");
        DBCursor cursor = preguntas.find();
        while (cursor.hasNext()) {
            DBObject preguntaJSON = cursor.next();
            String enunciado = (String) preguntaJSON.get("enunciado");
            String categoria = (String) preguntaJSON.get("categoria");
            BasicDBList respuestas = (BasicDBList) preguntaJSON.get("respuestas");
            Pregunta pregunta = new Pregunta(enunciado, categoria);
            for (int i = 0; i < respuestas.size(); i++) {
                DBObject respuestaJSON = (DBObject) respuestas.get(i);
                Respuesta respuesta = new Respuesta((String) respuestaJSON.get("respuesta"), (Boolean) respuestaJSON.get("isCorrecta"));
                //					pregunta.getRespuestas().add(respuesta);
                pregunta.addRespuesta(respuesta);
            }
            listaPreguntas.add(pregunta);
        }
        cursor.close();
    } catch (UnknownHostException e) {
        e.printStackTrace();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (mongoClient != null)
            mongoClient.close();
    }
    return listaPreguntas;
}
Example 43
Project: v7cr-master  File: svntest.java View source code
/**
	 * @param args
	 * @throws SVNException
	 * @throws MongoException
	 * @throws UnknownHostException
	 */
public static void main(String[] args) throws SVNException, UnknownHostException, MongoException {
    DAVRepositoryFactory.setup();
    DB db = new Mongo().getDB("v7cr");
    final Project project = new Project(BSONBackedObjectLoader.wrap(db.getCollection("projects").findOne("sanction-route"), null));
    final DBCollection reviews = db.getCollection("reviews");
    Long latestRev;
    try {
        BSONObject latest = (BSONObject) reviews.find(new BasicDBObject("p", project.getId())).sort(new BasicDBObject("svn.rev", -1)).limit(1).next().get("svn");
        latestRev = (Long) latest.get("rev");
    } catch (NoSuchElementException e) {
        latestRev = 0l;
    }
    System.out.println(latestRev);
    SVNURL url = SVNURL.parseURIDecoded(project.getRepositoryUrl());
    SVNClientManager svn = SVNClientManager.newInstance();
    // svn.setAuthenticationManager(new BasicAuthenticationManager("name",
    // "password"));
    SVNLogClient log = svn.getLogClient();
    log.doLog(url, null, SVNRevision.HEAD, SVNRevision.create(latestRev + 1), SVNRevision.HEAD, true, true, 100, new ISVNLogEntryHandler() {

        public void handleLogEntry(SVNLogEntry logEntry) throws SVNException {
            String message = logEntry.getMessage();
            String title = message;
            if (title.contains("\n")) {
                title = title.substring(0, title.indexOf('\n'));
            }
            if (title.length() > 80) {
                title = StringUtils.abbreviate(title, 80);
            }
            Review r = new Review(project.getId(), title);
            BasicDBObject b = new BasicDBObject(r.getBSONObject());
            BSONObject svn = Review.toBSON(logEntry);
            b.put("reviewee", new AccountInfo(logEntry.getAuthor(), logEntry.getAuthor()).getBSONObject());
            b.put("svn", svn);
            b.put("c", logEntry.getDate());
            System.out.println(b);
            Versioning.insert(reviews, b);
        }
    });
    svn.dispose();
}
Example 44
Project: v7files-master  File: MkdirCommand.java View source code
public static void main(String[] args) throws IOException {
    if (args.length != 3) {
        System.err.println("Create a directory/folder");
        System.err.println("  mkdir <root> <path>");
        System.exit(1);
    }
    DB db = Configuration.getMongo().getDB(Configuration.getProperty("mongo.db"));
    V7GridFS fs = new V7GridFS(db);
    String[] path = CopyCommand.getPath(args[1], args[2]);
    V7File existing = fs.getFile(path);
    if (existing != null) {
        if (existing.hasContent()) {
            throw new IOException(args[2] + " already exists (and is a file)");
        }
        throw new IOException("directory " + args[2] + " already exists");
    }
    V7File parent = CopyCommand.getParent(fs, path);
    fs.addFolder(parent.getId(), path[path.length - 1]);
}
Example 45
Project: Web-Karma-master  File: TestMongoDB.java View source code
public static void main(String[] args) {
    try {
        MongoClient mongoClient = new MongoClient("localhost", 27017);
        DB db = mongoClient.getDB("test");
        //			boolean auth = db.authenticate(myUserName, myPassword);
        Set<String> colls = db.getCollectionNames();
        for (String s : colls) {
            System.out.println(s);
        }
        DBCollection coll = db.getCollection("testData");
        DBObject myDoc = coll.findOne();
        System.out.println(myDoc);
        DBCursor cursor = coll.find();
        try {
            while (cursor.hasNext()) {
                System.out.println(cursor.next());
            }
        } finally {
            cursor.close();
        }
    } catch (UnknownHostException e) {
        e.printStackTrace();
    }
}
Example 46
Project: XBDD-master  File: QueryBuilderTagQueryTest.java View source code
@SuppressWarnings("unchecked")
@Test
public void testTagQuery() {
    final DB db = this.mongo.getDB(this.dbName);
    final DBCollection col = db.getCollection(this.collection);
    final BasicDBObject query = new BasicDBObject();
    final List<DBObject> tagQuery = QueryBuilder.getInstance().buildHasTagsQuery();
    query.append("$and", tagQuery);
    final DBCursor cursor = col.find(query);
    Assert.assertThat(cursor.count(), equalTo(3));
    while (cursor.hasNext()) {
        final DBObject next = cursor.next();
        List<DBObject> elements;
        boolean tags = next.containsField("tags");
        if (next.containsField("elements")) {
            elements = (List<DBObject>) next.get("elements");
            for (final DBObject element : elements) {
                if (element.containsField("tags")) {
                    tags = true;
                }
            }
        }
        Assert.assertTrue(tags);
    }
}
Example 47
Project: bolton-sigmod2013-code-master  File: MongoDbClient.java View source code
@Override
public /**
     * Initialize any state for this DB.
     * Called once per DB instance; there is one DB instance per client thread.
     */
void init() throws DBException {
    // initialize MongoDb driver
    Properties props = getProperties();
    String url = props.getProperty("mongodb.url", "mongodb://localhost:27017");
    database = props.getProperty("mongodb.database", "ycsb");
    String writeConcernType = props.getProperty("mongodb.writeConcern", "safe").toLowerCase();
    if ("none".equals(writeConcernType)) {
        writeConcern = WriteConcern.NONE;
    } else if ("safe".equals(writeConcernType)) {
        writeConcern = WriteConcern.SAFE;
    } else if ("normal".equals(writeConcernType)) {
        writeConcern = WriteConcern.NORMAL;
    } else if ("fsync_safe".equals(writeConcernType)) {
        writeConcern = WriteConcern.FSYNC_SAFE;
    } else if ("replicas_safe".equals(writeConcernType)) {
        writeConcern = WriteConcern.REPLICAS_SAFE;
    } else {
        System.err.println("ERROR: Invalid writeConcern: '" + writeConcernType + "'. " + "Must be [ none | safe | normal | fsync_safe | replicas_safe ]");
        System.exit(1);
    }
    try {
        // http://www.mongodb.org/display/DOCS/Connections
        if (url.startsWith("mongodb://")) {
            url = url.substring(10);
        }
        // need to append db to url.
        url += "/" + database;
        System.out.println("new database url = " + url);
        mongo = new Mongo(new DBAddress(url));
        System.out.println("mongo connection created with " + url);
    } catch (Exception e1) {
        System.err.println("Could not initialize MongoDB connection pool for Loader: " + e1.toString());
        e1.printStackTrace();
        return;
    }
}
Example 48
Project: hat-vldb2014-code-master  File: MongoDbClient.java View source code
@Override
public /**
     * Delete a record from the database.
     *
     * @param table The name of the table
     * @param key The record key of the record to delete.
     * @return Zero on success, a non-zero error code on error. See this class's description for a discussion of error codes.
     */
int delete(String table, String key) {
    com.mongodb.DB db = null;
    try {
        db = mongo.getDB(database);
        db.requestStart();
        DBCollection collection = db.getCollection(table);
        DBObject q = new BasicDBObject().append("_id", key);
        WriteResult res = collection.remove(q, writeConcern);
        return res.getN() == 1 ? 0 : 1;
    } catch (Exception e) {
        System.err.println(e.toString());
        return 1;
    } finally {
        if (db != null) {
            db.requestDone();
        }
    }
}
Example 49
Project: ycsb-memcached-master  File: MongoDbClient.java View source code
@Override
public /**
     * Delete a record from the database.
     *
     * @param table The name of the table
     * @param key The record key of the record to delete.
     * @return Zero on success, a non-zero error code on error. See this class's description for a discussion of error codes.
     */
int delete(String table, String key) {
    com.mongodb.DB db = null;
    try {
        db = mongo.getDB(database);
        db.requestStart();
        DBCollection collection = db.getCollection(table);
        DBObject q = new BasicDBObject().append("_id", key);
        if (writeConcern.equals(WriteConcern.SAFE)) {
            q.put("$atomic", true);
        }
        collection.remove(q);
        // see if record was deleted
        DBObject errors = db.getLastError();
        return ((Integer) errors.get("n")) == 1 ? 0 : 1;
    } catch (Exception e) {
        System.err.println(e.toString());
        return 1;
    } finally {
        if (db != null) {
            db.requestDone();
        }
    }
}
Example 50
Project: androidCgmMonitor-master  File: GetData.java View source code
public TimeMatechedRecord[] getDataFromMLW() {
    try {
        Log.d(TAG, "Connected");
        TimeMatechedRecordDao dataDao = new TimeMatechedRecordDao(context);
        Column[] columns = dataDao.getTableHelper().getColumns();
        SQLiteDatabase db = dataDao.getDbHelper(context).getReadableDatabase();
        Cursor curs = db.rawQuery("SELECT MAX(_id) from TimeMatechedRecord", null);
        long maxTimeIndex = 0;
        if (curs.moveToFirst()) {
            maxTimeIndex = curs.getLong(0);
        }
        curs.close();
        TimeMatechedRecord[] matched = null;
        String uri = "mongodb://user:password@server.mongolab.com:53109/datbase_name";
        MongoClientURI mongoURI = new MongoClientURI(uri);
        MongoClient client = new MongoClient(mongoURI);
        // get db
        DB mongoDb = client.getDB(mongoURI.getDatabase());
        String collectionName = "data_col";
        // get collection
        DBCollection coll = mongoDb.getCollection(collectionName.trim());
        BasicDBObject fields = new BasicDBObject().append("date", 1).append("_id", 0).append("sgv", 1);
        BasicDBObject query = new BasicDBObject();
        long lastDate = 0;
        DBCursor cursor = coll.find(query, fields);
        int count = 0;
        try {
            while (cursor.hasNext()) {
                DBObject row = cursor.next();
                Long date = (Long) row.get("date") / 1000 / 300;
                TimeMatechedRecord cor = new TimeMatechedRecord();
                cor.timeIndex = date;
                cor.LocalSecondsSinceDexcomEpoch = (Long) row.get("date") / 1000;
                cor.GlucoseValue = Short.parseShort((String) row.get("sgv"));
                //                    Log.d(TAG,"got point "+date + " "+cor.GlucoseValue);
                try {
                    dataDao.insert(cor);
                } catch (Exception e) {
                    dataDao.update(cor);
                }
                count++;
            }
        } finally {
            cursor.close();
        }
        Log.e(TAG, "got data " + count);
        this.err = null;
        return matched;
    } catch (Throwable e) {
        Log.e(TAG, "getData " + e.getMessage(), e);
        this.err = e;
        return null;
    } finally {
    }
}
Example 51
Project: build-failure-analyzer-plugin-master  File: MongoDBAuthenticationHudsonTest.java View source code
/**
     * Tests that we can authenticate towards Mongo DB.
     * @throws Exception if so.
     */
public void testAuthenticate() throws Exception {
    KnowledgeBase kb = new MongoDBKnowledgeBase("", 27017, "mydb", "user", Secret.fromString("password"), false, false);
    DB db = mock(DB.class);
    when(db.authenticate("user", "password".toCharArray())).thenReturn(false);
    Whitebox.setInternalState(kb, db);
    try {
        kb.getShallowCauses();
        fail("No AuthenticationException thrown!");
    //CS IGNORE EmptyBlock FOR NEXT 2 LINES. REASON: this should be thrown.
    } catch (AuthenticationException e) {
    }
}
Example 52
Project: cloudtm-data-platform-master  File: LoadSelectedColumnsInEntityTest.java View source code
@Override
protected void addExtraColumn() {
    MongoDBDatastoreProvider provider = (MongoDBDatastoreProvider) super.getService(DatastoreProvider.class);
    DB database = provider.getDatabase();
    DBCollection collection = database.getCollection("Project");
    BasicDBObject query = new BasicDBObject(1);
    query.put("_id", "projectID");
    BasicDBObject updater = new BasicDBObject(1);
    updater.put("$push", new BasicDBObject("extraColumn", 1));
    collection.update(query, updater);
}
Example 53
Project: clusters-master  File: MongodbLocalServerIntegrationTest.java View source code
@Test
public void testMongodbLocalServer() throws Exception {
    MongoClient mongo = new MongoClient(mongodbLocalServer.getIp(), mongodbLocalServer.getPort());
    DB db = mongo.getDB(propertyParser.getProperty(ConfigVars.MONGO_DATABASE_NAME_KEY));
    DBCollection col = db.createCollection(propertyParser.getProperty(ConfigVars.MONGO_COLLECTION_NAME_KEY), new BasicDBObject());
    col.save(new BasicDBObject("testDoc", new Date()));
    LOG.info("MONGODB: Number of items in collection: {}", col.count());
    assertEquals(1, col.count());
    DBCursor cursor = col.find();
    while (cursor.hasNext()) {
        LOG.info("MONGODB: Document output: {}", cursor.next());
    }
    cursor.close();
}
Example 54
Project: geotools-master  File: GeoJSONMongoTestSetup.java View source code
@Override
public void setUp(DB db) {
    DBCollection ft1 = db.getCollection("ft1");
    ft1.drop();
    ft1.save(BasicDBObjectBuilder.start().add("id", "ft1.0").push("geometry").add("type", "Point").add("coordinates", list(0, 0)).pop().push("properties").add("intProperty", 0).add("doubleProperty", 0.0).add("stringProperty", "zero").add("listProperty", list(new BasicDBObject("value", 0.1), new BasicDBObject("value", 0.2))).add("dateProperty", getDateProperty(0)).pop().get());
    ft1.save(BasicDBObjectBuilder.start().add("id", "ft1.1").push("geometry").add("type", "Point").add("coordinates", list(1, 1)).pop().push("properties").add("intProperty", 1).add("doubleProperty", 1.1).add("stringProperty", "one").add("listProperty", list(new BasicDBObject("value", 1.1), new BasicDBObject("value", 1.2))).add("dateProperty", getDateProperty(1)).pop().get());
    ft1.save(BasicDBObjectBuilder.start().add("id", "ft1.2").push("geometry").add("type", "Point").add("coordinates", list(2, 2)).pop().push("properties").add("intProperty", 2).add("doubleProperty", 2.2).add("stringProperty", "two").add("listProperty", list(new BasicDBObject("value", 2.1), new BasicDBObject("value", 2.2))).add("dateProperty", getDateProperty(2)).pop().get());
    ft1.createIndex(new BasicDBObject("geometry", "2dsphere"));
    ft1.createIndex(new BasicDBObject("properties.listProperty.value", 1));
    DBCollection ft2 = db.getCollection("ft2");
    ft2.drop();
}
Example 55
Project: hadoop-mini-clusters-master  File: MongodbLocalServerIntegrationTest.java View source code
@Test
public void testMongodbLocalServer() throws Exception {
    MongoClient mongo = new MongoClient(mongodbLocalServer.getIp(), mongodbLocalServer.getPort());
    DB db = mongo.getDB(propertyParser.getProperty(ConfigVars.MONGO_DATABASE_NAME_KEY));
    DBCollection col = db.createCollection(propertyParser.getProperty(ConfigVars.MONGO_COLLECTION_NAME_KEY), new BasicDBObject());
    col.save(new BasicDBObject("testDoc", new Date()));
    LOG.info("MONGODB: Number of items in collection: {}", col.count());
    assertEquals(1, col.count());
    DBCursor cursor = col.find();
    while (cursor.hasNext()) {
        LOG.info("MONGODB: Document output: {}", cursor.next());
    }
    cursor.close();
}
Example 56
Project: JMongoCounter-master  File: Counter.java View source code
@Override
public void run() {
    try {
        System.out.println(this.configuration.toString());
        MongoClient client = new MongoClient(this.configuration.getHost(), this.configuration.getPort());
        DB db = client.getDB(this.configuration.getDbname());
        DBCollection coll = db.getCollection(this.configuration.getCollname());
        while (this.thread != null && Thread.currentThread().getId() == this.thread.getId()) {
            String query = configuration.getQuery();
            long count = query.isEmpty() ? coll.count() : coll.count((DBObject) JSON.parse(query));
            System.out.println("[" + HumanDate.now() + "] " + count);
            this.notifyListenersOfCount(count);
            Thread.sleep(this.configuration.getInterval() * 1000);
        }
        client.close();
    } catch (Exception e) {
        this.stop();
        this.notifyListenersOfCountError();
        System.out.println("Processing error...");
        e.printStackTrace();
    }
}
Example 57
Project: jooby-master  File: JongoFactoryImplTest.java View source code
@Test
public void get() throws Exception {
    new MockUnit(MongoClientURI.class, MongoClient.class, Mapper.class, DB.class).expect(database).expect(defdb).expect(jongo).run( unit -> {
        Jongo jongo = new JongoFactoryImpl(unit.get(MongoClientURI.class), unit.get(MongoClient.class), unit.get(Mapper.class)).get();
        assertEquals(unit.get(Jongo.class), jongo);
    });
}
Example 58
Project: kurve-server-master  File: MongoAccountServiceTests.java View source code
@BeforeClass
public static void init() throws UnknownHostException {
    ServerAddress mongoServer = new ServerAddress(dbConfig.host, Integer.valueOf(dbConfig.port));
    MongoCredential credential = MongoCredential.createCredential(dbConfig.username, dbConfig.name, dbConfig.password.toCharArray());
    MongoClient mongoClient = new MongoClient(mongoServer, new ArrayList<MongoCredential>() {

        {
            add(credential);
        }
    });
    DB db = mongoClient.getDB(dbConfig.name);
    accountService = new MongoAccountService(db);
}
Example 59
Project: mongo-hadoop-master  File: BaseShardedTest.java View source code
@Before
public void shuffleChunks() throws IOException, InterruptedException, TimeoutException {
    assumeTrue(isSharded(getInputUri()));
    LOG.info("shuffling chunks across shards");
    final DB adminDB = getClient(getInputUri()).getDB("admin");
    adminDB.command(new BasicDBObject("enablesharding", "mongo_hadoop"));
    getClient(getInputUri()).getDB("config").getCollection("settings").update(new BasicDBObject("_id", "balancer"), new BasicDBObject("$set", new BasicDBObject("stopped", true)), false, true);
    adminDB.command(new BasicDBObject("shardCollection", "mongo_hadoop.yield_historical.in").append("key", new BasicDBObject("_id", 1)));
    final DBCollection historicalIn = getClient(getInputUri()).getDB("mongo_hadoop").getCollection("yield_historical.in");
    for (final int chunkpos : new int[] { 2000, 3000, 1000, 500, 4000, 750, 250, 100, 3500, 2500, 2250, 1750 }) {
        final Object middle = historicalIn.find().sort(new BasicDBObject("_id", 1)).skip(chunkpos).iterator().next().get("_id");
        adminDB.command(new BasicDBObject("split", "mongo_hadoop.yield_historical.in").append("middle", new BasicDBObject("_id", middle)));
    }
    final DB configDB = getMongos().getDB("config");
    final DBCollection shards = configDB.getCollection("shards");
    final DBCollection chunks = configDB.getCollection("chunks");
    final long numChunks = chunks.count();
    final Object chunkSource = chunks.findOne().get("shard");
    final Object chunkDest = shards.findOne(new BasicDBObject("_id", new BasicDBObject("$ne", chunkSource)));
    LOG.info("chunk source: " + chunkSource);
    LOG.info("chunk dest: " + chunkDest);
    // shuffle chunks around
    for (int i = 0; i < numChunks / 2; i++) {
        final DBObject chunk = chunks.findOne(new BasicDBObject("shard", chunkSource));
        LOG.info(String.format("moving %s from %s to %s", chunk, chunkSource, chunkDest));
        try {
            adminDB.command(new BasicDBObject("moveChunk", "mongo_hadoop.yield_historical.in").append("find", chunk.get("min")).append("to", chunkDest));
        } catch (final Exception e) {
            LOG.error(e.getMessage(), e);
        }
    }
}
Example 60
Project: mongo-java-driver-master  File: Decimal128LegacyAPIQuickTour.java View source code
/**
     * Run this main method to see the output of this quick example.
     *
     * @param args takes an optional single argument for the connection string
     */
public static void main(final String[] args) {
    MongoClient mongoClient;
    if (args.length == 0) {
        // connect to the local database server
        mongoClient = new MongoClient();
    } else {
        mongoClient = new MongoClient(new MongoClientURI(args[0]));
    }
    // get handle to "mydb" database
    DB database = mongoClient.getDB("mydb");
    // get a handle to the "test" collection
    DBCollection collection = database.getCollection("test");
    // drop all the data in it
    collection.drop();
    // make a document and insert it
    BasicDBObject doc = new BasicDBObject("name", "MongoDB").append("amount1", Decimal128.parse(".10")).append("amount2", new Decimal128(42L)).append("amount3", new Decimal128(new BigDecimal(".200")));
    collection.insert(doc);
    DBObject first = collection.findOne(QueryBuilder.start("amount1").is(new Decimal128(new BigDecimal(".10"))).get());
    Decimal128 amount3 = (Decimal128) first.get("amount3");
    BigDecimal amount2AsBigDecimal = amount3.bigDecimalValue();
    System.out.println(amount3.toString());
    System.out.println(amount2AsBigDecimal.toString());
}
Example 61
Project: mongobrowser-master  File: NewCollectionAction.java View source code
@Override
public void actionPerformed(ActionEvent e) {
    JTree tree = context.getTree();
    String collectionName = JOptionPane.showInputDialog(tree, MongoBundle.getString(MongoBundle.Key.NewCollection));
    if (collectionName != null) {
        DB db = context.getDatabase();
        DBCollection dbCollection = db.getCollection(collectionName);
        DefaultTreeModel model = (DefaultTreeModel) tree.getModel();
        MongoTreeNode root = (MongoTreeNode) model.getRoot();
        MongoTreeNode collectionNode = new MongoTreeNode(dbCollection, false);
        root.add(collectionNode);
        MongoTreeNode slug = new MongoTreeNode();
        collectionNode.add(slug);
        model.nodeStructureChanged(root);
        TreePath selection = new TreePath(collectionNode.getPath());
        tree.scrollPathToVisible(selection);
        tree.setSelectionPath(selection);
    }
}
Example 62
Project: monitrix-master  File: MongoDBConnector.java View source code
@Override
@SuppressWarnings("unchecked")
public <T extends ExtensionTable> T getExtensionTable(String name, Class<T> type) {
    ExtensionTable ext = extensionTables.get(name);
    if (ext == null) {
        try {
            ext = type.getConstructor(DB.class).newInstance(db);
            extensionTables.put(name, ext);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    return (T) ext;
}
Example 63
Project: netbeans-mongodb-master  File: OneDBChildren.java View source code
@Override
public Void call() throws Exception {
    MongoClient client = lookup.lookup(MongoClient.class);
    DbInfo info = lookup.lookup(DbInfo.class);
    DB db = client.getDB(info.dbName);
    List<String> names = new LinkedList<>(db.getCollectionNames());
    for (String name : names) {
        list.add(new CollectionInfo(name, lookup));
    }
    return null;
}
Example 64
Project: nosql-unit-master  File: MongoDbCommands.java View source code
public static void shutdown(String host, int port) {
    MongoClient mongo = null;
    try {
        mongo = new MongoClient(host, port);
        DB db = mongo.getDB("admin");
        CommandResult shutdownResult = db.command(new BasicDBObject("shutdown", 1));
        shutdownResult.throwOnError();
    } catch (MongoException e) {
    } catch (Throwable e) {
        throw new IllegalStateException("Mongodb could not be shutdown.", e);
    } finally {
        mongo.close();
    }
}
Example 65
Project: provider-mongodb-master  File: MongoResourceProvider.java View source code
public synchronized Resource<DB> getResource() {
    if (null == resource) {
        resource = new MongoResource() {

            @Override
            MongoClient getMongo() {
                return MongoResourceProvider.this.getMongo();
            }

            @Override
            MongoResourceProvider getProvider() {
                return MongoResourceProvider.this;
            }
        };
    }
    return resource;
}
Example 66
Project: seyren-master  File: MongoDbIT.java View source code
@Test
public void testPopulateMongoDb() throws Exception {
    Mongo mongo = new MongoClient("localhost", 27017);
    DB db = mongo.getDB("seyren");
    File[] collections = readCollectionDirectory();
    for (File collection : collections) {
        Collection<File> jsonFiles = readJsonFiles(collection);
        loadJsonFiles(collection, jsonFiles, db);
    }
}
Example 67
Project: Statik-Report-master  File: ProcessRunnable.java View source code
public void process() {
    final BeanstalkJob bsj;
    try {
        // wait indefinitely for a job
        bsj = this.bsc.reserve(null);
        if (bsj == null)
            return;
    } catch (final BeanstalkException ex) {
        this.rs.getLogger().warning("Could not reserve a BeanstalkJob:");
        this.rs.getLogger().log(Level.WARNING, ex.getMessage(), ex);
        ex.printStackTrace();
        return;
    }
    final DB db = this.rs.getMongoDB().getDB();
    db.requestStart();
    try {
        db.requestEnsureConnection();
        // we should be passed a JSONObject in String form
        final Request r = new Request(new JSONObject(new String(bsj.getData())));
        final DBCollection dbc = db.getCollection(this.collection);
        dbc.insert(r.createMongoVersion());
    } catch (final JSONException ex) {
        this.rs.getLogger().warning("A JSONException occurred while processing data:");
        this.rs.getLogger().log(Level.WARNING, ex.getMessage(), ex);
    } finally {
        db.requestDone();
    }
    try {
        this.bsc.deleteJob(bsj);
    } catch (final BeanstalkException ex) {
        this.rs.getLogger().warning("Could not delete beanstalk job:");
        this.rs.getLogger().log(Level.WARNING, ex.getMessage(), ex);
    }
}
Example 68
Project: umongo-master  File: TagRangeDialog.java View source code
void resetForEdit(DB config, BasicDBObject range) {
    xmlLoadCheckpoint();
    ((DocBuilderField) getBoundUnit(Item.min)).setDBObject((DBObject) range.get("min"));
    ((DocBuilderField) getBoundUnit(Item.min)).enabled = false;
    ((DocBuilderField) getBoundUnit(Item.max)).setDBObject((DBObject) range.get("max"));
    ((DynamicComboBox) getBoundUnit(Item.tag)).items = getExistingTags(config);
    setStringFieldValue(Item.tag, range.getString("tag"));
    updateComponent();
}
Example 69
Project: acteur-master  File: MongoModuleTest.java View source code
@Test
public void testIt(MongoHarness mongo, MongoClient client, DB db, Fixture f, Dependencies deps) throws IOException, InterruptedException {
    assertNotNull(db);
    assertEquals("testit", db.getName());
    assertNotNull(f.users);
    assertNotNull(f.capped);
    assertEquals("ttusers", f.users.getName());
    assertEquals("cappedStuff", f.capped.getName());
    assertTrue(f.capped.isCapped());
    //
    //        mongo.stop();
    //
    //        Ge ge = new Ge(deps);
    //        Thread t = new Thread(ge);
    //        t.setDaemon(true);
    //        t.start();
    //        ge.await();
    //        Thread.yield();
    //
    //        mongo.start();
    DB db3 = deps.getInstance(DB.class);
    assertNotNull(db3);
    Fixture f1 = deps.getInstance(Fixture.class);
    assertNotSame(f, f1);
    assertEquals("testit", db3.getName());
    //        assertNotNull(ge.db);
    //        assertEquals(db3.getName(), ge.db.getName());
    System.out.println("Test done");
}
Example 70
Project: burpdeveltraining-master  File: BurpExtenderWIP2.java View source code
@Override
public void registerExtenderCallbacks(IBurpExtenderCallbacks callbacks) {
    this.callbacks = callbacks;
    helpers = callbacks.getHelpers();
    callbacks.setExtensionName("ReplayAndDiff");
    System.out.println("\n\n:: ReplayAndDiff Headless Extension ::\n\n");
    // 1 - Parse command line arguments and store values in local variables
    // -h|--host=<IP>, -p|--port=<port>, -o|--ouput=<dir>, -e|--report=<filename>, -t|--timeout=<seconds>
    String[] args = callbacks.getCommandLineArguments();
    for (String arg : args) {
        if (arg.contains("-h=") || arg.contains("--host=")) {
            MONGO_HOST = arg.substring(arg.indexOf('=') + 1);
        } else if (arg.contains("-p=") || arg.contains("--port=")) {
            MONGO_PORT = Integer.valueOf(arg.substring(arg.indexOf('=') + 1));
        } else if (arg.contains("-o=") || arg.contains("--ouput=")) {
            OUTPUT_DIR = arg.substring(arg.indexOf('=') + 1);
        } else if (arg.contains("-r=") || arg.contains("--report=")) {
            REPORT_NAME = arg.substring(arg.indexOf('=') + 1);
        } else if (arg.contains("-t=") || arg.contains("--timeout=")) {
            TIMEOUT = Integer.valueOf(arg.substring(arg.indexOf('=') + 1));
        }
    }
    System.out.println("[*] Configuration {MONGO_HOST=" + MONGO_HOST + ",MONGO_PORT=" + MONGO_PORT + ",OUTPUT_DIR=" + OUTPUT_DIR + ",REPORT_NAME=" + REPORT_NAME + ",TIMEOUT=" + TIMEOUT + "}");
    // 2 - Connect to MongoDB
    MongoClient mongo = null;
    try {
        mongo = new MongoClient(MONGO_HOST, MONGO_PORT);
    } catch (UnknownHostException ex) {
        System.err.println("[!] MongoDB Connection Error: " + ex.toString());
    }
    // 3 - Retrieve login requests from the 'login' collection in db 'sitelogger'
    DB db = mongo.getDB("sitelogger");
    DBCollection table = db.getCollection("login");
    DBCursor cursor = table.find();
    String host = null;
    while (cursor.hasNext()) {
    // 4 - For each entry, issue a new HTTP request (using Burp's makeHttpRequest) and collect the cookies (using Burp's analyzeResponse)
    // 5 - If there are cookies, update Burp's Cookies jar (using Burp's updateCookieJar)
    // TODO
    }
    // 6 - Retrieve from the database all previously saved HTTP requests
    if (host != null) {
        table = db.getCollection(host.replaceAll("\\.", "_") + "_site");
    } else {
        throw new NullPointerException();
    }
    cursor = table.find();
    URL website = null;
    while (cursor.hasNext()) {
    // 7 - Trigger a new active scan on the same URL (using Burp's doActiveScan)
    // 8 - Reissue a new HTTP request and trigger a new passive scan on the same URL (using Burp's doPassiveScan)
    // TODO
    }
    // 9 - Wait until all scans are completed
    try {
        System.out.println("[*] Pausing extension...");
        // HOMEWORK - Build a queuing system to check scans status and confirm once all scans are done
        Thread.sleep(1000 * TIMEOUT);
        System.out.println("[*] Resuming extension...");
    } catch (InterruptedException ex) {
        System.err.println("[!] InterruptedException: " + ex.toString());
    }
    table = db.getCollection(host.replaceAll("\\.", "_") + "_vuln");
    BasicDBObject searchQuery = null;
    IScanIssue[] allVulns = null;
    boolean newFinding = false;
    // 10 - Obtain the list of new findings (using Burp's getScanIssues)
    if (website != null) {
        allVulns = callbacks.getScanIssues(website.toString());
        for (IScanIssue allVuln : allVulns) {
            // 11 - Diff old and new findings
            // For now, let's use a simple heuristic: if there's at least a new finding (not previously reported), success!
            searchQuery = new BasicDBObject();
            searchQuery.put("type", allVuln.getIssueType());
            searchQuery.put("name", allVuln.getIssueName());
            searchQuery.put("URL", allVuln.getUrl().toString());
            System.out.println("[*] Looking for: " + searchQuery.toString());
            cursor = table.find(searchQuery);
            if (cursor.size() == 0) {
                //There's at least one new finding
                System.out.println("[*] Got a new finding!");
                newFinding = true;
            }
        }
        // 12 - In case of new findings, generate the report (using Burp's generateScanReport)
        if (newFinding) {
        // TODO
        }
    } else {
        throw new NullPointerException();
    }
    System.out.println("[*] Ready to shutdown...Bye!");
    callbacks.exitSuite(false);
}
Example 71
Project: chililog-server-master  File: MongoConnection.java View source code
/**
     * Returns a connection to the Mongo database as specified in the app.properties file
     * 
     * @param dbName
     *            database name
     * @param username
     *            username for database
     * @param password
     *            password for database
     * @return Mongo Database connection
     * @throws ChiliLogException
     *             if connection or authentication fails
     */
public DB getConnection(String dbName, String username, String password) throws ChiliLogException {
    try {
        DB db = _mongo.getDB(dbName);
        // "can't call authenticate twice on the same DBObject" exception
        if (!db.isAuthenticated()) {
            if (!db.authenticate(username, password.toCharArray())) {
                throw new ChiliLogException(Strings.MONGODB_AUTHENTICATION_ERROR, dbName);
            }
        }
        return db;
    } catch (MongoException ex) {
        throw new ChiliLogException(ex, Strings.MONGODB_CONNECTION_ERROR, ex.getMessage());
    }
}
Example 72
Project: com.lowereast.guiceymongo-master  File: DBProviderModule.java View source code
public DB get() {
    try {
        if (_cachedDB == null)
            cacheDB();
        return _cachedDB;
    } catch (MongoException e) {
        throw new GuiceyMongoException("Could not connect to an instance of MongoDB", e);
    } catch (UnknownHostException e) {
        throw new GuiceyMongoException("Could not connect to an instance of MongoDB", e);
    }
}
Example 73
Project: gaiandb-master  File: MongoConnectionFactory.java View source code
/**
	 * Returns a handle to a Mongo DB object - which may be used to manage collections.
	 * 
	 * @param connectionParams - object containing all the parameters needed to connect to MongoDB
	 * @exception UnknownHostException - if we cannot connect to the mongoDB host specified
	 * @exception AuthenticationException - if authentication with the mongoDB process fails.
	 * 
	 */
public static DB getMongoDB(MongoConnectionParams connectionParams) throws Exception {
    // connect to the mongo process
    MongoClient mongoClient = new MongoClient(connectionParams.getHostAddress(), connectionParams.getHostPort());
    if (mongoClient == null)
        throw new ConnectException(MongoMessages.DSWRAPPER_MONGODB_CONNECTION_ERROR);
    // Connect to the specific database
    // TBD possibly try to reuse these.
    DB mongoDb = mongoClient.getDB(connectionParams.getDatabaseName());
    if (mongoDb == null)
        throw new ConnectException(MongoMessages.DSWRAPPER_MONGODB_DATABASE_CONN_ERROR);
    // Authenticate if the configuration parameters have been set
    String userName = connectionParams.getUserName();
    String password = connectionParams.getPassword();
    if (userName != null && password != null) {
        boolean authenticated = mongoDb.authenticate(userName, password.toCharArray());
        if (!authenticated) {
            throw new AuthenticationException(MongoMessages.DSWRAPPER_MONGODB_AUTHENTICATION_ERROR);
        }
    }
    return mongoDb;
}
Example 74
Project: guiceymongo-master  File: DBProviderModule.java View source code
public DB get() {
    try {
        if (_cachedDB == null)
            cacheDB();
        return _cachedDB;
    } catch (MongoException e) {
        throw new GuiceyMongoException("Could not connect to an instance of MongoDB", e);
    } catch (UnknownHostException e) {
        throw new GuiceyMongoException("Could not connect to an instance of MongoDB", e);
    }
}
Example 75
Project: javaee-nosql-master  File: MongoExtensionTest.java View source code
@Test
public void shouldCdiAndClassicCallContainTheSameValue() throws UnknownHostException {
    MongoClient mgc = new MongoClient(new MongoClientURI(MONGODB_TEST_URI));
    DB db = mgc.getDB(TEST_DB);
    DBCollection dbc = db.getCollection(TEST_COLLECTION);
    dbc.insert(getBasicDBObject());
    DBObject inserted = dbc.findOne();
    DBObject myDoc = myCollection.findOne();
    Assert.assertEquals(inserted, myDoc);
}
Example 76
Project: logdb-master  File: MongoFindCommand.java View source code
@Override
public void run() {
    MongoProfile profile = options.getProfile();
    MongoClient mongo = null;
    DBCursor cursor = null;
    try {
        mongo = new MongoClient(profile.getAddress(), profile.getCredentials());
        DB db = mongo.getDB(options.getDatabase());
        DBCollection col = db.getCollection(options.getCollection());
        cursor = col.find();
        while (cursor.hasNext()) {
            DBObject doc = cursor.next();
            Map<String, Object> m = convert(doc);
            pushPipe(new Row(m));
        }
    } catch (Throwable t) {
        slog.error("araqne logdb mongo: cannot run mongo.find", t);
    } finally {
        if (cursor != null)
            cursor.close();
        if (mongo != null)
            mongo.close();
    }
}
Example 77
Project: MongoDB-master  File: MongoDBClient.java View source code
public int addEntry(String jsonString) throws Exception, ParseException {
    JSONParser parser = new JSONParser();
    int result = 0;
    try {
        //get service connection and initialize mongoclient
        String connURL = getServiceURI();
        MongoClient mongo = new MongoClient(new MongoClientURI(connURL));
        //initialize database and collection
        DB db = mongo.getDB("db");
        DBCollection table = db.getCollection("books");
        Object obj = parser.parse(jsonString);
        //check if json is an array or not
        if (obj.getClass().getName().matches(".*[JSONArray]")) {
            JSONArray objArr = (JSONArray) obj;
            BulkWriteOperation builder = table.initializeOrderedBulkOperation();
            for (int i = 0; i < objArr.size(); i++) {
                BasicDBObject entry = (BasicDBObject) JSON.parse(objArr.get(i).toString());
                builder.insert(entry);
            }
            // bulk insert operation
            BulkWriteResult wr = builder.execute();
            //Returns true if the write was acknowledged.
            if (wr.isAcknowledged())
                result = objArr.size();
        } else {
            BasicDBObject entry = (BasicDBObject) JSON.parse(obj.toString());
            WriteResult wr = table.insert(entry);
            //Returns true if the write was acknowledged.
            if (wr.wasAcknowledged())
                result = 1;
        }
    } catch (ParseException pe) {
        pe.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return result;
}
Example 78
Project: Mongrel-master  File: ListCollections.java View source code
@Override
public Sequence eval(Sequence[] args, Sequence contextSequence) throws XPathException {
    try {
        // Verify clientid and get client
        String mongodbClientId = args[0].itemAt(0).getStringValue();
        MongodbClientStore.getInstance().validate(mongodbClientId);
        MongoClient client = MongodbClientStore.getInstance().get(mongodbClientId);
        // Additional parameter
        String dbname = args[1].itemAt(0).getStringValue();
        // Retrieve database          
        DB db = client.getDB(dbname);
        // Retrieve collection names
        Set<String> collectionNames = db.getCollectionNames();
        // Storage for results
        ValueSequence valueSequence = new ValueSequence();
        // Iterate over collection names 
        for (String collName : collectionNames) {
            valueSequence.add(new StringValue(collName));
        }
        return valueSequence;
    } catch (XPathException ex) {
        LOG.error(ex.getMessage(), ex);
        throw new XPathException(this, ex.getMessage(), ex);
    } catch (MongoException ex) {
        LOG.error(ex.getMessage(), ex);
        throw new XPathException(this, MongodbModule.MONG0002, ex.getMessage());
    } catch (Throwable ex) {
        LOG.error(ex.getMessage(), ex);
        throw new XPathException(this, MongodbModule.MONG0003, ex.getMessage());
    }
}
Example 79
Project: Morphlines-master  File: MongoCheckpointFilterHandler.java View source code
@Override
public String getLastCheckpoint(Map<String, String> context) {
    String checkpoint;
    DBCursor cursor;
    Object fieldValue = null;
    final long count = countCheckpoints();
    if (count > 0) {
        try {
            cursor = mongoCollection.find().skip((int) (count - 1));
            while (cursor.hasNext()) {
                DBObject object = cursor.next();
                fieldValue = object.get(checkpointField);
            }
            checkpoint = (String) checkpointType.buildCheckpoint(fieldValue, context);
        } catch (Exception e) {
            throw new MongoCheckpointFilterException("Error accesing DB. Verify db/collection name.");
        }
    } else {
        checkpoint = (String) checkpointType.buildDefaultCheckpoint(context);
    }
    return checkpoint;
}
Example 80
Project: OG-Platform-master  File: MongoConnectorFactoryBean.java View source code
//-------------------------------------------------------------------------
@Override
public MongoConnector createObject() {
    // store in variable to protect against change by subclass
    final String name = getName();
    ArgumentChecker.notNull(name, "name");
    final MongoClient mongo = createMongo();
    final DB db = createDatabase(mongo);
    return new MongoConnector(name, mongo, db, getCollectionSuffix());
}
Example 81
Project: openbd-core-master  File: Find.java View source code
public cfData execute(cfSession _session, cfArgStructData argStruct) throws cfmRunTimeException {
    // Get the necessary Mongo references
    DB db = getDB(_session, argStruct);
    GridFS gridfs = getGridFS(_session, argStruct, db);
    // Get the file information
    String filename = getNamedStringParam(argStruct, "filename", null);
    if (filename != null) {
        return toArray(gridfs.find(filename));
    } else {
        cfData mTmp = getNamedParam(argStruct, "query", null);
        if (mTmp != null)
            return toArray(gridfs.find(getDBObject(mTmp)));
    }
    throwException(_session, "Please specify file or a query");
    return null;
}
Example 82
Project: OpenSpotLight-master  File: RawStorageTest.java View source code
@Test
public void shouldStoreAndRetrieveSomething() throws Exception {
    final Mongo m = new Mongo();
    final DB db = m.getDB("db");
    final BasicDBObject someObj = new BasicDBObject("_id", "sameID");
    someObj.put("la", "la");
    db.getCollection("col").save(someObj);
    final BasicDBObject sameObj = new BasicDBObject("_id", "sameID");
    someObj.put("le", "le");
    db.getCollection("col").save(sameObj);
}
Example 83
Project: Pdf-Reviewer-master  File: MongoDB.java View source code
private List<Review> findRequests(User userToLookFor, String roleOfUser) {
    List<Review> retVal = new ArrayList<>();
    DB db = mongoClient.getDB(DB_NAME);
    DBCollection coll = db.getCollection(DB_NAME);
    coll.setObjectClass(Review.class);
    BasicDBObject query = new BasicDBObject(roleOfUser + ".Login", userToLookFor.getLogin());
    DBCursor cursor = coll.find(query);
    try {
        while (cursor.hasNext()) {
            DBObject element = cursor.next();
            retVal.add((Review) element);
        }
    } finally {
        cursor.close();
    }
    return retVal;
}
Example 84
Project: quhao-master  File: TestMerchantController.java View source code
// extends FunctionalTest{
public static void main(String[] args) {
    DBAddress addr = null;
    try {
        addr = new DBAddress("localhost", "quhao-dev-db");
    } catch (UnknownHostException e) {
        e.printStackTrace();
        Logger.debug("QuhaoException: %s", ExceptionUtil.getTrace(e));
    }
    DB db = Mongo.connect(addr);
    DBCollection col = db.getCollection("Account");
    DBCursor cursor = col.find();
    List<String> accounts = new ArrayList<String>();
    String testPhone = "";
    while (cursor.hasNext()) {
        DBObject account = cursor.next();
        String phone = account.get("phone").toString();
        if (phone.equals("18817261072")) {
            String aid = account.get("_id").toString();
            testPhone = aid;
            if (accounts.size() == 5) {
                break;
            } else {
                continue;
            }
        }
        int jifen = Integer.parseInt(account.get("jifen").toString());
        if (jifen > 0) {
            if (accounts.size() == 5) {
                continue;
            }
            String aid = account.get("_id").toString();
            accounts.add(aid);
        }
    }
    accounts.add(testPhone);
    String merchantId = "52e3c726036431505d9a9e20";
    // hard code for test
    int seatNo = 13;
    for (int i = 0; i < accounts.size(); i++) {
        String accountId = accounts.get(i);
        String buf = get("/nahao?accountId=" + accountId + "&mid=" + merchantId + "&seatNumber=" + seatNo);
        if (StringUtils.isEmpty(buf)) {
        } else {
        }
    }
}
Example 85
Project: SampleTap-master  File: NextHopSwitch.java View source code
public static boolean adjustReference(final ReferenceCountEnum adjType, String nhsId, SwitchEntry tapPolicy) throws NotFoundException {
    DB database = TappingApp.getDatabase();
    DBCollection table = database.getCollection(DatabaseNames.getNextHopSwitchTableName());
    // Look for the SwitchEntry object by object ID in the database
    BasicDBObject searchQuery = new BasicDBObject();
    ObjectId id = new ObjectId(nhsId);
    searchQuery.put("_id", id);
    DBObject dbObj = table.findOne(searchQuery);
    if (dbObj == null)
        throw new NotFoundException();
    // create an increment query
    DBObject modifier = new BasicDBObject("refCount", (adjType == ReferenceCountEnum.DECREMENT) ? -1 : 1);
    DBObject incQuery = new BasicDBObject("$inc", modifier);
    // increment a counter value atomically
    WriteResult result = table.update(searchQuery, incQuery);
    return (result != null) ? true : false;
}
Example 86
Project: spring-data-book-master  File: AbstractIntegrationTest.java View source code
@Before
public void setUp() {
    DB database = mongo.getDB("e-store");
    // Customers
    DBCollection customers = database.getCollection("customer");
    customers.remove(new BasicDBObject());
    BasicDBObject address = new BasicDBObject();
    address.put("city", "New York");
    address.put("street", "Broadway");
    address.put("country", "United States");
    BasicDBList addresses = new BasicDBList();
    addresses.add(address);
    DBObject dave = new BasicDBObject("firstname", "Dave");
    dave.put("lastname", "Matthews");
    dave.put("email", "dave@dmband.com");
    dave.put("addresses", addresses);
    customers.insert(dave);
    // Products
    DBCollection products = database.getCollection("product");
    products.drop();
    DBObject iPad = new BasicDBObject("name", "iPad");
    iPad.put("description", "Apple tablet device");
    iPad.put("price", 499.0);
    iPad.put("attributes", new BasicDBObject("connector", "plug"));
    DBObject macBook = new BasicDBObject("name", "MacBook Pro");
    macBook.put("description", "Apple notebook");
    macBook.put("price", 1299.0);
    BasicDBObject dock = new BasicDBObject("name", "Dock");
    dock.put("description", "Dock for iPhone/iPad");
    dock.put("price", 49.0);
    dock.put("attributes", new BasicDBObject("connector", "plug"));
    products.insert(iPad, macBook, dock);
    // Orders
    DBCollection orders = database.getCollection("order");
    orders.drop();
    // Line items
    DBObject iPadLineItem = new BasicDBObject("product", iPad);
    iPadLineItem.put("amount", 2);
    DBObject macBookLineItem = new BasicDBObject("product", macBook);
    macBookLineItem.put("amount", 1);
    BasicDBList lineItems = new BasicDBList();
    lineItems.add(iPadLineItem);
    lineItems.add(macBookLineItem);
    DBObject order = new BasicDBObject("customer", new DBRef(database, "customer", dave.get("_id")));
    order.put("lineItems", lineItems);
    order.put("shippingAddress", address);
    orders.insert(order);
}
Example 87
Project: spring-data-mongodb-master  File: MongoVersionRule.java View source code
private void initCurrentVersion() {
    if (currentVersion == null) {
        try {
            MongoClient client;
            client = new MongoClient(host, port);
            DB db = client.getDB("test");
            CommandResult result = db.command(new BasicDBObject().append("buildInfo", 1));
            this.currentVersion = Version.parse(result.get("version").toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
Example 88
Project: spring-insight-plugins-master  File: MongoDbOperationCollectionAspectTest.java View source code
private Operation assertCommandOperation(DB db) {
    final String argVal = db.getName() + "-arg";
    db.command(argVal);
    Operation op = getLastEntered();
    assertNotNull("No operation extracted", op);
    assertEquals("Mismatched operation type", MongoDBOperationExternalResourceAnalyzer.TYPE, op.getType());
    assertEquals("Mismatched operation label", "MongoDB: DB.command()", op.getLabel());
    assertEquals("Mismatched DB name", db.getName(), op.get("dbName", String.class));
    if (!StringUtil.isEmpty(argVal)) {
        OperationList argsList = op.get("args", OperationList.class);
        assertNotNull("Missing arguments list");
        String actVal = argsList.get(0, String.class);
        assertEquals("Mismatched operation arguments", argVal, actVal);
    }
    return op;
}
Example 89
Project: streamreduce-core-master  File: MongoNumberIT.java View source code
@Test
@Ignore("Integration Tests depended on sensitive account keys, ignoring until better harness is in place.")
public void testNumberFidelity() {
    String json = "{\"min\":" + Constants.PERIOD_MINUTE + ",\"hour\":" + Constants.PERIOD_HOUR + ",\"day\":" + Constants.PERIOD_DAY + ",\"week\":" + Constants.PERIOD_WEEK + ",\"month\":" + Constants.PERIOD_MONTH + ",\"crap\":" + Constants.PERIOD_WEEK * 30 + ",\"foo\":\"foo\"}";
    BasicDBObject newPayloadObject = (BasicDBObject) JSON.parse(json);
    gcdao.createCollectionEntry(DAODatasourceType.BUSINESS, getClass().toString(), newPayloadObject);
    DB db = businessDatastore.getDB();
    DBCollection collection = db.getCollection(getClass().toString());
    BasicDBObject results = (BasicDBObject) collection.findOne(new BasicDBObject("foo", "foo"));
    assertTrue(((Integer) results.get("min")).longValue() == Constants.PERIOD_MINUTE);
    assertTrue(((Integer) results.get("hour")).longValue() == Constants.PERIOD_HOUR);
    assertTrue(((Integer) results.get("day")).longValue() == Constants.PERIOD_DAY);
    assertTrue(((Integer) results.get("week")).longValue() == Constants.PERIOD_WEEK);
    assertTrue((Long) results.get("crap") == Constants.PERIOD_WEEK * 30);
    assertTrue((Long) results.get("month") == Constants.PERIOD_MONTH);
    String valMin = results.get("min").toString();
    String valHour = results.get("hour").toString();
    String valDay = results.get("day").toString();
    String valWeek = results.get("week").toString();
    String valMonth = results.get("month").toString();
    String valCrap = results.get("crap").toString();
    System.out.println("valMin: " + valMin);
    System.out.println("valHour: " + valHour);
    System.out.println("valDay: " + valDay);
    System.out.println("valWeek: " + valWeek);
    System.out.println("valMonth: " + valMonth);
    System.out.println("valCrap: " + valCrap);
    assertTrue(Long.valueOf(valMin) == Constants.PERIOD_MINUTE);
    assertTrue(Long.valueOf(valHour) == Constants.PERIOD_HOUR);
    assertTrue(Long.valueOf(valDay) == Constants.PERIOD_DAY);
    assertTrue(Long.valueOf(valWeek) == Constants.PERIOD_WEEK);
    assertTrue(Long.valueOf(valMonth) == Constants.PERIOD_MONTH);
    assertTrue(Long.valueOf(valCrap) == Constants.PERIOD_WEEK * 30);
}
Example 90
Project: symmetric-ds-master  File: SimpleMongoClientManager.java View source code
@Override
public DB getDB(String name) {
    if (currentDB == null || !currentDB.getName().equals(name)) {
        currentDB = get().getDB(name);
        /**
             * TODO make this a property
             */
        currentDB.setWriteConcern(WriteConcern.ACKNOWLEDGED);
        String username = null;
        char[] password = null;
        if (parameterService != null) {
            username = parameterService.getString(name + MongoConstants.USERNAME, username);
            String passwordString = parameterService.getString(name + MongoConstants.PASSWORD, null);
            if (passwordString != null) {
                password = passwordString.toCharArray();
            }
        }
        if (username != null && !currentDB.authenticate(username, password)) {
            throw new SymmetricException("Failed to authenticate with the mongo database: " + name);
        }
    }
    return currentDB;
}
Example 91
Project: todo-apps-master  File: ToDoStoreFactory.java View source code
private static DBCollection getCollection(MongoServiceInfo info) throws ToDoStoreException {
    MongoClient client;
    try {
        client = new MongoClient(info.getHost(), info.getPort());
        DB db = client.getDB(info.getDatabase());
        boolean auth = db.authenticate(info.getUserName(), info.getPassword().toCharArray());
        if (!auth) {
            throw new ToDoStoreException("Could not authenticate to Mongo DB.");
        }
        return db.getCollection("todos");
    } catch (Exception e) {
        throw new ToDoStoreException("Error creating Mongo DB client.", e);
    }
}
Example 92
Project: tomcat-mongo-access-log-master  File: CollectionFactory.java View source code
public static DBCollection getOrCreateCollection(String uri, String dbName, String collName, boolean capped, int capSize, Log log, StringManager sm) {
    MongoClient mongoClient = null;
    DB db = null;
    try {
        mongoClient = new MongoClient(new MongoClientURI(uri));
        db = mongoClient.getDB(dbName);
    } catch (UnknownHostException ex) {
        log.error(sm.getString("mongoAccessLogValve.openConnectionError", uri), ex);
        throw new RuntimeException(ex);
    }
    DBCollection coll = null;
    try {
        if (capped) {
            DBObject options = new BasicDBObject();
            options.put("capped", true);
            options.put("size", capSize * 1024 * 1024);
            coll = db.createCollection(collName, options);
            for (DBObject indexOption : getIndexOptions()) {
                coll.createIndex(indexOption);
            }
        } else {
            coll = db.getCollection(collName);
        }
    } catch (com.mongodb.CommandFailureException ex) {
        String errmsg = (String) ex.getCommandResult().get("errmsg");
        if ("collection already exists".equals(errmsg)) {
            log.info(sm.getString("mongoAccessLogValve.collectionExisted", collName));
            coll = db.getCollection(collName);
        }
        ExceptionUtils.handleThrowable(ex);
    } catch (Exception ex) {
        log.error(sm.getString("mongoAccessLogValve.openConnectionError", uri), ex);
    }
    return coll;
}
Example 93
Project: WindMobile-Server-master  File: ITTestChatServiceImpl.java View source code
@Before
public void beforeTest() {
    Mongo mongo = null;
    try {
        mongo = new Mongo();
        DB db = mongo.getDB(MongoDBConstants.DATABASE_NAME);
        InputStream is = getClass().getResourceAsStream("/init-script.js");
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        FileCopyUtils.copy(is, out);
        String code = out.toString();
        Logger.getLogger("WindoMobile").info("Create test database");
        Object result = db.doEval(code);
        Logger.getLogger("WindoMobile").info("Result : " + result.toString());
    } catch (Exception e) {
        Logger.getLogger("WindoMobile").log(Level.SEVERE, "Error : " + e.getMessage());
        e.printStackTrace();
    } finally {
        if (mongo != null) {
            mongo.close();
        }
    }
}
Example 94
Project: 5.2.0.RC-master  File: MongoService.java View source code
public synchronized DB getSingleDb() {
    try {
        Mongo mongo = new Mongo(host, port);
        DB db = mongo.getDB(dbname);
        boolean auth = db.authenticate(username, password.toCharArray());
        logger.debug("Mongo authenticate result : " + auth);
        if (auth)
            return db;
        throw new MongoException(" Can not connect to Mongo ...");
    } catch (UnknownHostException e) {
        throw new MongoException(" unknown host ...", e);
    } catch (MongoException e) {
        throw new MongoException(" Mongo exception ...", e);
    }
}
Example 95
Project: alfresco-nosql-daos-master  File: MongoNodeDAOImpl.java View source code
@Override
public void onApplicationEvent(ApplicationContextEvent event) {
    if (event instanceof ContextRefreshedEvent) {
        if (mongo != null) {
            try {
                if (mongo != null) {
                    mongo.close();
                }
            } catch (Exception e) {
                logger.error("Failed to shut MongoDB connection cleanly.", e);
            }
        }
        try {
            mongo = new MongoClient(mongoHost, mongoPort);
            logger.info("Created MongoDB connection to " + mongo);
        } catch (Exception e) {
            throw new RuntimeException("Failed to create MongoDB client.", e);
        }
        DB db = mongo.getDB(mongoDatabase);
        initCollections(db);
    } else if (event instanceof ContextClosedEvent) {
        logger.info("Shutting down MongoDB connection to " + mongo);
        try {
            if (mongo != null) {
                mongo.close();
            }
        } catch (Exception e) {
            logger.error("Failed to shut MongoDB connection cleanly.", e);
        }
    }
}
Example 96
Project: almende-master  File: FirstUseActivity.java View source code
@Override
protected String doInBackground(String... strings) {
    if (Cookie.getInstance().internet) {
        try {
            MongoClient client = Database.getInstance();
            DB db = client.getDB(Database.uri.getDatabase());
            DBCollection userCollection = db.getCollection("user");
            userCollection.setObjectClass(User.class);
            User match = new User();
            match.put("facebookID", Cookie.getInstance().userEntryId);
            User update = (User) userCollection.findOne(match);
            update.put("nulmeting", baseline);
            userCollection.update(match, update);
        } catch (Exception e) {
            System.out.println(e);
        }
    }
    return null;
}
Example 97
Project: AnalyzerBeans-master  File: MongoDbDatastore.java View source code
@Override
protected UsageAwareDatastoreConnection<UpdateableDataContext> createDatastoreConnection() {
    try {
        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);
    }
}
Example 98
Project: avisos-master  File: UpdateIssueDate.java View source code
public static void main(String[] arg) throws Exception {
    MongoClientURI mongoClientURI = new MongoClientURI(System.getenv("MONGOHQ_URL"));
    MongoClient mongoClient = new MongoClient(mongoClientURI);
    DB mongoDB = mongoClient.getDB(mongoClientURI.getDatabase());
    String GENERATED_COL = "GeneratedFiles";
    SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm");
    SimpleDateFormat isoformater = new SimpleDateFormat("YYYY-MM-dd HH:mm");
    if (null != mongoClientURI.getUsername()) {
        mongoDB.authenticate(mongoClientURI.getUsername(), mongoClientURI.getPassword());
    }
    DBCollection col = mongoDB.getCollection(GENERATED_COL);
    DBCursor cursor = col.find();
    for (DBObject obj : cursor) {
        String date = (String) obj.get("issueDate");
        Date fec = null;
        try {
            fec = sdf.parse(date);
        } catch (ParseException npe) {
        }
        if (null != fec) {
            date = isoformater.format(fec);
            DBObject act = col.findOne(obj);
            obj.put("issueDate", date);
            col.update(act, obj);
        }
    }
}
Example 99
Project: balas-master  File: UserList.java View source code
/**
	 * Creates the default records if no users in database.
	 * 
	 * @param db
	 *            the db
	 */
public static void createDefaultRecords(DB db) {
    if (db != null) {
        DBCollection coll = db.getCollection(collectionname);
        if (coll.getCount() < 1) {
            UserRole defaultroles = new UserRole();
            defaultroles.setAdmin();
            User user = new User();
            user.setPassword("admin");
            user.setLogin("admin");
            user.setDomain("127.0.0.1");
            user.setUsername("Admin The Great");
            user.setUserrole(defaultroles);
            user.addNewUser();
            BasicDBObject i = new BasicDBObject();
            i.put("login", 1);
            i.put("domain", 1);
            coll.createIndex(i);
            i.put("istrash", 1);
            coll.createIndex(i);
        }
    }
}
Example 100
Project: ca-apm-fieldpack-mongodb-master  File: MongoReplicaSetForTestFactory.java View source code
private void initializeReplicaSet(Entry<String, List<IMongodConfig>> entry) throws Exception {
    String replicaName = entry.getKey();
    List<IMongodConfig> mongoConfigList = entry.getValue();
    if (mongoConfigList.size() < 3) {
        throw new Exception("A replica set must contain at least 3 members.");
    }
    // Create 3 mongod processes
    for (IMongodConfig mongoConfig : mongoConfigList) {
        if (!mongoConfig.replication().getReplSetName().equals(replicaName)) {
            throw new Exception("Replica set name must match in mongo configuration");
        }
        MongodStarter starter = MongodStarter.getDefaultInstance();
        MongodExecutable mongodExe = starter.prepare(mongoConfig);
        MongodProcess process = mongodExe.start();
        mongodProcessList.add(process);
    }
    Thread.sleep(1000);
    MongoClientOptions mo = MongoClientOptions.builder().autoConnectRetry(true).build();
    MongoClient mongo = new MongoClient(new ServerAddress(mongoConfigList.get(0).net().getServerAddress().getHostName(), mongoConfigList.get(0).net().getPort()), mo);
    DB mongoAdminDB = mongo.getDB(ADMIN_DATABASE_NAME);
    CommandResult cr = mongoAdminDB.command(new BasicDBObject("isMaster", 1));
    logger.info("isMaster: " + cr);
    // Build BSON object replica set settings
    DBObject replicaSetSetting = new BasicDBObject();
    replicaSetSetting.put("_id", replicaName);
    BasicDBList members = new BasicDBList();
    int i = 0;
    for (IMongodConfig mongoConfig : mongoConfigList) {
        DBObject host = new BasicDBObject();
        host.put("_id", i++);
        host.put("host", mongoConfig.net().getServerAddress().getHostName() + ":" + mongoConfig.net().getPort());
        members.add(host);
    }
    replicaSetSetting.put("members", members);
    logger.info(replicaSetSetting.toString());
    // Initialize replica set
    cr = mongoAdminDB.command(new BasicDBObject("replSetInitiate", replicaSetSetting));
    logger.info("replSetInitiate: " + cr);
    Thread.sleep(5000);
    cr = mongoAdminDB.command(new BasicDBObject("replSetGetStatus", 1));
    logger.info("replSetGetStatus: " + cr);
    // Check replica set status before to proceed
    while (!isReplicaSetStarted(cr)) {
        logger.info("Waiting for 3 seconds...");
        Thread.sleep(1000);
        cr = mongoAdminDB.command(new BasicDBObject("replSetGetStatus", 1));
        logger.info("replSetGetStatus: " + cr);
    }
    mongo.close();
    mongo = null;
}
Example 101
Project: CISEN-master  File: MongoDBServiceImpl.java View source code
@Activate
public void start(Map<String, Object> properties) {
    LOGGER.info("Starting MongoDb service...");
    MongoClient mongoClient;
    try {
        String host = PropertiesUtil.toString(properties.get(MONGO_HOST), "127.0.0.1");
        int port = PropertiesUtil.toInteger(properties.get(MONGO_PORT), 27017);
        String dbName = PropertiesUtil.toString(properties.get(MONGO_DB_NAME), "cisen");
        mongoClient = new MongoClient(host, port);
        DB mDb = mongoClient.getDB(dbName);
        this.m_mongo = mDb.getMongo();
        this.jongo = new Jongo(mDb);
        setUpDB();
        LOGGER.info("MongoDb service was started successfully.");
    } catch (UnknownHostException e) {
        LOGGER.error("Fail to connect: ", e);
    }
}