Example usage for com.mongodb DBObject put

List of usage examples for com.mongodb DBObject put

Introduction

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

Prototype

Object put(String key, Object v);

Source Link

Document

Sets a name/value pair in this object.

Usage

From source file:com.impetus.client.mongodb.schemamanager.MongoDBSchemaManager.java

License:Apache License

private void indexColumn(IndexInfo indexInfo, DBCollection collection) {
    DBObject keys = new BasicDBObject();
    getIndexType(indexInfo.getIndexType(), keys, indexInfo.getColumnName());
    DBObject options = new BasicDBObject();
    if (indexInfo.getMinValue() != null) {
        options.put(MongoDBConstants.MIN, indexInfo.getMinValue());
    }/*from w  w  w  . jav a 2  s .co  m*/
    if (indexInfo.getMaxValue() != null) {
        options.put(MongoDBConstants.MAX, indexInfo.getMaxValue());
    }

    if (indexInfo.getIndexType() != null && (indexInfo.getIndexType().toLowerCase()).equals("unique")) {
        options.put("unique", true);
    }
    collection.createIndex(keys, options);
    KunderaCoreUtils.printQuery("Create indexes on:" + keys, showQuery);
}

From source file:com.impetus.client.mongodb.schemamanager.MongoDBSchemaManager.java

License:Apache License

private void indexEmbeddedColumn(IndexInfo indexInfo, String embeddedColumnName, DBCollection collection) {
    DBObject keys = new BasicDBObject();
    getIndexType(indexInfo.getIndexType(), keys, embeddedColumnName + "." + indexInfo.getColumnName());
    DBObject options = new BasicDBObject();
    if (indexInfo.getMinValue() != null) {
        options.put(MongoDBConstants.MIN, indexInfo.getMinValue());
    }/*w ww .  j av a 2s.  co  m*/
    if (indexInfo.getMaxValue() != null) {
        options.put(MongoDBConstants.MAX, indexInfo.getMaxValue());
    }
    collection.createIndex(keys, options);
    KunderaCoreUtils.printQuery("Create indexes on:" + keys, showQuery);
}

From source file:com.impetus.client.mongodb.schemamanager.MongoDBSchemaManager.java

License:Apache License

/**
 * @param indexType/*  w w w .  j  a  va  2s  .  co m*/
 * @param clazz
 * @return
 */
private void getIndexType(String indexType, DBObject keys, String columnName) {
    // TODO validation for indexType and attribute type

    if (indexType != null) {
        if (indexType.equals(IndexType.ASC.name())) {
            keys.put(columnName, 1);
            return;
        } else if (indexType.equals(IndexType.DSC.name())) {
            keys.put(columnName, -1);
            return;
        } else if (indexType.equals(IndexType.GEO2D.name())) {
            keys.put(columnName, "2d");
            return;
        }
    }
    keys.put(columnName, 1);
    return;
}

From source file:com.intellijob.MongoConfiguration.java

License:Apache License

@Autowired
@Bean/*  ww w.java2  s  . c  o m*/
public Boolean doImportData(MongoClient mongoClient) throws IOException {

    DBCollection sys_import_collection = mongoClient.getDB(this.properties.getDatabase())
            .getCollection(ApplicationSettings.COLLECTION_NAME);
    if (isProduction && sys_import_collection.count() == 0) {
        LOG.info("IMPORT DATA =============================================>");

        //Import collection skill_caegories.
        loadCollectionSkillCategories(mongoClient);

        //Import languages
        loadSkillsData(mongoClient, "skill_languages.json", "skill_languages");

        //Import knowledges
        loadSkillsData(mongoClient, "skill_knowledge.json", "skill_knowledges");

        //Import personal strength
        loadSkillsData(mongoClient, "skill_personalstrengths.json", "skill_personalstrengths");

        DBObject row = new BasicDBObject();
        row.put(ApplicationSettings.FIELD_MONGO_DATA_IMPORTED, true);
        row.put(ApplicationSettings.FIELD_MONGO_DATA_IMPORTED_DATE, new Date());
        row.put(ApplicationSettings.FIELD_ELASTIC_DATA_IMPORTED, false);
        row.put(ApplicationSettings.FIELD_ELASTIC_DATA_IMPORTED_DATE, null);

        sys_import_collection.insert(row);
        LOG.info("IMPORT DATA FINISHED!");
        return true;
    }

    return false;
}

From source file:com.intellijob.MongoConfiguration.java

License:Apache License

/**
 * Import collection skill_categories.//from  www . j a  v  a2s  . co m
 */
private void loadCollectionSkillCategories(MongoClient mongoClient) {

    InputStream inputStream = Thread.currentThread().getContextClassLoader()
            .getResourceAsStream("imports/skills_categories.json");

    String collectionName = "skill_categories";
    try {
        LOG.info("LOAD {} DATA ....................................", collectionName);
        DBCollection col = mongoClient.getDB(this.properties.getDatabase()).getCollection(collectionName);

        List<Map<String, Object>> categories = new ObjectMapper().readValue(inputStream,
                TypeFactory.defaultInstance().constructCollectionType(List.class, HashMap.class));

        for (Map<String, Object> category : categories) {
            DBObject dbObject = new BasicDBObject(category);
            dbObject.put("_id", new ObjectId(category.get("_id").toString()));
            col.insert(dbObject);
        }
        LOG.info("DONE!");
    } catch (Exception e) {
        LOG.error("Collection (" + collectionName + ") could not be imported successfully!", e);
    }
}

From source file:com.janeluo.jfinalplus.plugin.monogodb.MongoKit.java

License:Apache License

private static void sort(Map<String, Object> sort, DBCursor dbCursor) {
    if (sort != null) {
        DBObject dbo = new BasicDBObject();
        Set<Entry<String, Object>> entrySet = sort.entrySet();
        for (Entry<String, Object> entry : entrySet) {
            String key = entry.getKey();
            Object val = entry.getValue();
            dbo.put(key, "asc".equalsIgnoreCase(val + "") ? 1 : -1);
        }/* ww w  . j  a v  a 2s  .  co  m*/
        dbCursor = dbCursor.sort(dbo);
    }
}

From source file:com.jaspersoft.mongodb.importer.MongoDbImporter.java

License:Open Source License

public void importTable(String tableName) throws Exception {
    createConnection();//from  w w w  .  j  av a2 s .c  om
    logger.info("Initialize import");
    ResultSet resultSet = null;
    List<DBObject> objectsList = new ArrayList<DBObject>();
    try {
        resultSet = statement.executeQuery("SELECT * FROM " + tableName);
        ResultSetMetaData metaData = resultSet.getMetaData();
        int index, columnCount = metaData.getColumnCount(), count = 0;
        logger.info("Importing rows");
        DBCollection collection = null;
        if (!mongodbConnection.getMongoDatabase().collectionExists(tableName)) {
            logger.info("Collection \"" + tableName + "\" doesn't exist");
            DBObject options = new BasicDBObject("capped", false);
            collection = mongodbConnection.getMongoDatabase().createCollection(tableName, options);
        } else {
            logger.info("Collection \"" + tableName + "\" exists");
            collection = mongodbConnection.getMongoDatabase().getCollectionFromString(tableName);
            collection.drop();
            logger.info("Collection \"" + tableName + "\" was cleaned up");
        }
        Object value;
        DBObject newObject;
        while (resultSet.next()) {
            newObject = new BasicDBObject();
            for (index = 1; index <= columnCount; index++) {
                value = resultSet.getObject(index);
                if (value != null) {
                    newObject.put(metaData.getColumnName(index), value);
                }
            }
            objectsList.add(newObject);
            count++;
            if (count % 100 == 0) {
                logger.info("Processed: " + count);
                logger.info("Result: " + collection.insert(objectsList).getField("ok"));
                objectsList.clear();
            }
        }
        if (objectsList.size() > 0) {
            collection.insert(objectsList);
            logger.info("Result: " + collection.insert(objectsList).getField("ok"));
            objectsList.clear();
        }
        logger.info("Rows added: " + count);
        logger.info("Import done");
    } finally {
        if (resultSet != null) {
            resultSet.close();
        }
    }
}

From source file:com.jaspersoft.mongodb.query.MongoDbQueryWrapper.java

License:Open Source License

private Object fixQueryObject(DBObject queryObjectToFix, Map<String, Object> reportParameters) {
    Set<String> keySet = queryObjectToFix.keySet();
    if (keySet.size() == 1) {
        String key = keySet.iterator().next();
        if (reportParameters.containsKey(key) && queryObjectToFix.get(key) == null) {
            return reportParameters.get(key);
        }/*from  w  ww.  j a  v a 2  s . c  o  m*/
    }
    for (String key : queryObjectToFix.keySet()) {
        Object value = queryObjectToFix.get(key);
        if (value instanceof DBObject) {
            queryObjectToFix.put(key, fixQueryObject((DBObject) value, reportParameters));
        }
    }
    return queryObjectToFix;
}

From source file:com.jaspersoft.mongodb.query.MongoDbQueryWrapper.java

License:Open Source License

private void createIterator() throws JRException {
    if (!queryObject.containsField(COLLECTION_NAME_KEY)) {
        throw new JRException("\"" + COLLECTION_NAME_KEY + "\" must be part of the query object");
    }//from  w  ww. ja  v a2  s.  c o m
    DBObject findQueryObject = (DBObject) queryObject.get(FIND_QUERY_KEY);
    if (findQueryObject == null) {
        findQueryObject = new BasicDBObject();
    }
    if (queryObject.containsField(FIND_QUERY_REGEXP_KEY)) {
        DBObject regExpObject = (DBObject) queryObject.get(FIND_QUERY_REGEXP_KEY);
        String value, flags;
        int index;
        for (String key : regExpObject.keySet()) {
            value = (String) regExpObject.get(key);
            if (value.startsWith("/")) {
                value = value.substring(1, value.length());
            } else {
                throw new JRException("Regular expressions must start with: /");
            }
            if (!value.contains("/")) {
                throw new JRException("No ending symbol found: /");
            }
            index = value.lastIndexOf("/");
            flags = null;
            if (index == value.length() - 1) {
                value = value.substring(0, index);
            } else {
                flags = value.substring(index + 1, value.length());
                value = value.substring(0, index);
            }
            findQueryObject.put(key, Pattern.compile((flags != null ? "(?" + flags + ")" : "") + value));
        }
    }

    DBCollection collection = connection.getMongoDatabase()
            .getCollectionFromString((String) queryObject.removeField(COLLECTION_NAME_KEY));
    if (queryObject.containsField(MAP_REDUCE_KEY)) {
        Object value = queryObject.removeField(MAP_REDUCE_KEY);
        if (!(value instanceof DBObject)) {
            logger.error("MapReduce value must be a valid JSON object");
        } else {
            DBObject mapReduceObject = (DBObject) value;
            String map = validateProperty(mapReduceObject, MAP_KEY);
            String reduce = validateProperty(mapReduceObject, REDUCE_KEY);
            Object outObject = mapReduceObject.get(OUT_KEY);
            if (outObject == null) {
                throw new JRException("\"out\" cannot be null");
            }
            String collectionName = null;
            Object outDb = null;
            OutputType outputType = null;
            boolean hasOutputType = false;
            if (logger.isDebugEnabled()) {
                logger.debug("Out object: " + outObject + ". Type: " + outObject.getClass().getName());
            }
            if (outObject instanceof String) {
                collectionName = String.valueOf(outObject);
            } else if (outObject instanceof DBObject) {
                DBObject outDbObject = (DBObject) outObject;
                outDb = outDbObject.removeField(OUT_DB_KEY);
                Iterator<String> keysIterator = outDbObject.keySet().iterator();
                String type = null;
                if (keysIterator.hasNext()) {
                    type = keysIterator.next();
                    collectionName = String.valueOf(outDbObject.get(type));
                } else {
                    throw new JRException("\"out\" object cannot be empty");
                }
                type = type.toUpperCase();
                outputType = OutputType.valueOf(type);
                if (outputType == null) {
                    throw new JRException("Unknow output type: " + type);
                }
                hasOutputType = true;
                if (logger.isDebugEnabled()) {
                    logger.debug("outobject: " + outDbObject);
                    logger.debug("collectionName: " + collectionName);
                    logger.debug("outputType: " + outputType);
                }
            } else {
                throw new JRException("Unsupported type for \"out\": " + outObject.getClass().getName());
            }
            MapReduceCommand mapReduceCommand = new MapReduceCommand(collection, map, reduce, collectionName,
                    hasOutputType ? outputType : OutputType.REPLACE, null);
            if (outDb != null) {
                mapReduceCommand.setOutputDB(String.valueOf(outDb));
            }
            Object finalizeObject = mapReduceObject.removeField(FINALIZE_KEY);
            if (finalizeObject != null) {
                mapReduceCommand.setFinalize(String.valueOf(finalizeObject));
            }
            MapReduceOutput mapReduceOutput = collection.mapReduce(mapReduceCommand);
            DBCollection mapReduceCollection = mapReduceOutput.getOutputCollection();
            if (mapReduceCollection != null) {
                collection = mapReduceCollection;
            }
        }
    }

    iterator = collection.find(findQueryObject, (DBObject) queryObject.get(FIND_FIELDS_KEY));
    if (queryObject.containsField(SORT_KEY)) {
        iterator = iterator.sort((DBObject) queryObject.get(SORT_KEY));
    }
    if (queryObject.containsField(LIMIT_KEY)) {
        Integer value = processInteger(queryObject.get(LIMIT_KEY));
        if (value != null) {
            iterator = iterator.limit(value.intValue());
        }
    }
}

From source file:com.jive.myco.seyren.mongo.MongoStore.java

License:Apache License

@Override
public SeyrenResponse<Check> getChecks(Boolean enabled, Boolean live) {
    List<Check> checks = new ArrayList<Check>();
    DBObject query = new BasicDBObject();
    if (enabled != null) {
        query.put("enabled", enabled);
    }/*from  ww  w .  j a va 2s .c  o m*/
    if (live != null) {
        query.put("live", live);
    }
    DBCursor dbc = getChecksCollection().find(query);
    while (dbc.hasNext()) {
        checks.add(mapper.checkFrom(dbc.next()));
    }
    return new SeyrenResponse<Check>().withValues(checks).withTotal(dbc.count());
}