Example usage for com.mongodb DBObject putAll

List of usage examples for com.mongodb DBObject putAll

Introduction

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

Prototype

void putAll(BSONObject o);

Source Link

Document

Sets all key/value pairs from an object into this object

Usage

From source file:mongoDB.MongoDbClientAllImagesAsByteArrays.java

License:Open Source License

@Override
public int viewTopKResources(int requesterID, int profileOwnerID, int k,
        Vector<HashMap<String, ByteIterator>> result) {
    int retVal = 0;
    if (profileOwnerID < 0 || requesterID < 0 || k < 0)
        return -1;

    com.mongodb.DB db = null;/*from w  w  w .jav  a 2  s.  c  o m*/

    try {
        db = mongo.getDB(database);
        db.requestStart();
        if (scanResources) {
            DBCollection collection = db.getCollection("resources");
            // find all resources that belong to profileOwnerID
            // sort them by _id desc coz we want latest ones and get the top
            // k
            DBObject q = new BasicDBObject().append("walluserid", Integer.toString(profileOwnerID));
            DBCursor queryResult = null;
            queryResult = collection.find(q);
            // DBObject s = new BasicDBObject().append("_id", -1); //desc
            DBObject s = new BasicDBObject(); // desc
            s.put("_id", -1);
            queryResult = queryResult.sort(s);
            queryResult = queryResult.limit(k);
            Iterator it = queryResult.iterator();
            while (it.hasNext()) {
                HashMap<String, ByteIterator> vals = new HashMap<String, ByteIterator>();
                DBObject oneRes = new BasicDBObject();
                oneRes.putAll((DBObject) it.next());
                vals.putAll(oneRes.toMap());
                // needed to do this so the coreworkload will not need to
                // know the datastore type
                if (vals.get("_id") != null) {
                    String tmp = vals.get("_id") + "";
                    vals.remove("_id");
                    vals.put("rid", new ObjectByteIterator(tmp.getBytes()));
                }
                if (vals.get("walluserid") != null) {
                    String tmp = vals.get("walluserid") + "";
                    vals.remove("walluserid");
                    vals.put("walluserid", new ObjectByteIterator(tmp.getBytes()));
                }
                if (vals.get("creatorid") != null) {
                    String tmp = vals.get("creatorid") + "";
                    vals.remove("creatorid");
                    vals.put("creatorid", new ObjectByteIterator(tmp.getBytes()));
                }
                result.add(vals);
            }
            queryResult.close();

        } else {
            DBCollection collection = db.getCollection("users");
            DBObject q = new BasicDBObject().append("_id", profileOwnerID);
            DBObject queryResult = null;
            queryResult = collection.findOne(q);
            String x = queryResult.get("wallResources").toString();
            if (!x.equals("[ ]")) {
                x = x.substring(1, x.length() - 1);
                String resourceIds[] = x.split(",");
                BasicDBObject query = new BasicDBObject();
                List<Integer> list = new ArrayList<Integer>();
                for (int i = resourceIds.length - 1; i >= resourceIds.length
                        - Math.min(k, resourceIds.length); i--) { // to
                    // limit
                    // it
                    list.add(Integer.parseInt(resourceIds[i].trim()));
                }
                collection = db.getCollection("resources");
                query.put("_id", new BasicDBObject("$in", list));
                DBCursor cursor = collection.find(query);
                while (cursor.hasNext()) {
                    HashMap<String, ByteIterator> vals = new HashMap<String, ByteIterator>();
                    vals.putAll(cursor.next().toMap());
                    if (vals.get("_id") != null) {
                        String tmp = vals.get("_id") + "";
                        vals.remove("_id");
                        vals.put("rid", new ObjectByteIterator(tmp.getBytes()));
                    }
                    if (vals.get("walluserid") != null) {
                        String tmp = vals.get("walluserid") + "";
                        vals.remove("walluserid");
                        vals.put("walluserid", new ObjectByteIterator(tmp.getBytes()));
                    }
                    if (vals.get("creatorid") != null) {
                        String tmp = vals.get("creatorid") + "";
                        vals.remove("creatorid");
                        vals.put("creatorid", new ObjectByteIterator(tmp.getBytes()));
                    }
                    result.add(vals);
                }
                cursor.close();
            }
        }
    } catch (Exception e) {
        System.out.println(e.toString());
        retVal = -1;
    } finally {
        if (db != null) {
            db.requestDone();
        }
    }
    return retVal;

}

From source file:mongoDB.MongoDbClientAllImagesAsByteArrays.java

License:Open Source License

public int getCreatedResources(int creatorID, Vector<HashMap<String, ByteIterator>> result) {
    int retVal = 0;
    if (creatorID < 0)
        return -1;

    com.mongodb.DB db = null;/*from  ww  w.java2 s  .  c om*/

    try {
        db = mongo.getDB(database);
        db.requestStart();
        DBCollection collection = db.getCollection("resources");
        // find all resources that belong to profileOwnerID
        // sort them by _id desc coz we want latest ones and get the top k
        DBObject q = new BasicDBObject().append("creatorid", Integer.toString(creatorID));
        DBCursor queryResult = null;
        queryResult = collection.find(q);
        // DBObject s = new BasicDBObject().append("_id", -1); //desc
        DBObject s = new BasicDBObject(); // desc
        s.put("_id", -1);
        queryResult = queryResult.sort(s);
        Iterator it = queryResult.iterator();
        while (it.hasNext()) {
            HashMap<String, ByteIterator> vals = new HashMap<String, ByteIterator>();
            DBObject oneRes = new BasicDBObject();
            oneRes.putAll((DBObject) it.next());
            vals.putAll(oneRes.toMap());
            // needed to do this so the coreworkload will not need to know
            // the datastore typr
            if (vals.get("_id") != null) {
                String tmp = vals.get("_id") + "";
                vals.remove("_id");
                vals.put("rid", new ObjectByteIterator(tmp.getBytes()));
            }
            if (vals.get("creatorid") != null) {
                String tmp = vals.get("creatorid") + "";
                vals.remove("creatorid");
                vals.put("creatorid", new ObjectByteIterator(tmp.getBytes()));
            }
            result.add(vals);
        }
        queryResult.close();

    } catch (Exception e) {
        System.out.println(e.toString());
        retVal = -1;
    } finally {
        if (db != null) {
            db.requestDone();
        }
    }
    return retVal;

}

From source file:mongoDB.MongoDbClientAllImagesAsByteArrays.java

License:Open Source License

@Override
public int viewCommentOnResource(int requesterID, int profileOwnerID, int resourceID,
        Vector<HashMap<String, ByteIterator>> result) {
    int retVal = 0;
    if (profileOwnerID < 0 || requesterID < 0 || resourceID < 0)
        return -1;

    com.mongodb.DB db = null;//from   w w w . j av  a 2  s  . c o m

    try {
        db = mongo.getDB(database);
        db.requestStart();
        if (!manipulationArray) {
            DBCollection collection = db.getCollection("manipulation");
            // find all resources that belong to profileOwnerID
            // sort them by _id desc coz we want latest ones and get the top
            // k
            DBObject q = new BasicDBObject().append("rid", Integer.toString(resourceID));
            DBCursor queryResult = null;
            queryResult = collection.find(q);
            Iterator<DBObject> it = queryResult.iterator();
            while (it.hasNext()) {
                HashMap<String, ByteIterator> vals = new HashMap<String, ByteIterator>();
                DBObject oneRes = new BasicDBObject();
                oneRes.putAll((DBObject) it.next());
                vals.putAll(oneRes.toMap());
                result.add(vals);
            }
            queryResult.close();
        } else {
            DBCollection collection = db.getCollection("resources");
            DBObject q = new BasicDBObject().append("_id", resourceID);
            DBObject queryResult = null;
            queryResult = collection.findOne(q);
            if (queryResult.get("Manipulations") != "" && queryResult.get("Manipulations") != null) {
                ArrayList<DBObject> mans = (ArrayList<DBObject>) queryResult.get("Manipulations");
                for (int i = 0; i < mans.size(); i++) {
                    result.add((HashMap<String, ByteIterator>) mans.get(i).toMap());
                }
            }
        }

    } catch (Exception e) {
        System.out.println(e.toString());
        retVal = -1;
    } finally {
        if (db != null) {
            db.requestDone();
        }
    }
    return retVal;
}

From source file:nl.knaw.huygens.timbuctoo.storage.mongo.MongoQueries.java

License:Open Source License

public DBObject getRevisionFromVersionCollection(String id, int revision) {
    DBObject query = selectById(id);
    query.putAll(getRevisionProjection(revision));

    return query;
}

From source file:nl.kpmg.lcm.server.data.dao.mongo.MongoMetaDataWriteConverter.java

License:Apache License

@Override
public DBObject convert(MetaData source) {
    DBObject dbo = new BasicDBObject();
    if (source.getId() != null) {
        dbo.put("_id", new ObjectId(source.getId()));
    }//from   w  w w  . j  a  v a  2 s  .c  o m
    putIfNotNull(dbo, "name", source.getName());
    putIfNotNull(dbo, "inactive", source.getInactive());
    dbo.putAll(source.anyGetter());
    return dbo;
}

From source file:org.apache.gora.mongodb.filters.MongoFilterUtil.java

License:Apache License

/**
 * Set a filter on the <tt>query</tt>. It translates a Gora filter to a
 * MongoDB filter./*w  ww  .  jav  a2  s. c  o  m*/
 * 
 * @param query
 *          The Mongo Query
 * @param filter
 *          The Gora filter.
 * @param store
 *          The MongoStore.
 * @return if remote filter is successfully applied.
 */
public boolean setFilter(final DBObject query, final Filter<K, T> filter, final MongoStore<K, T> store) {

    FilterFactory<K, T> factory = getFactory(filter);
    if (factory == null) {
        LOG.warn("MongoDB remote filter factory not yet implemented for "
                + filter.getClass().getCanonicalName());
        return false;
    } else {
        DBObject mongoFilter = factory.createFilter(filter, store);
        if (mongoFilter == null) {
            LOG.warn("MongoDB remote filter not yet implemented for " + filter.getClass().getCanonicalName());
            return false;
        } else {
            query.putAll(mongoFilter);
            return true;
        }
    }
}

From source file:org.atlasapi.persistence.content.mongo.MongoDBQueryBuilder.java

License:Apache License

DBObject buildQuery(ContentQuery query) {

    // handle attributes that are not part of a list structure
    Multimap<List<String>, ConstrainedAttribute> attributeConstraints = HashMultimap.create();
    for (ConstrainedAttribute constraint : buildQueries(query)) {
        if (constraint == null) {
            continue;
        }// www  . ja v  a  2 s.  c om
        attributeConstraints.put(entityPath(constraint.attribute), constraint);
    }

    // sort the keys by length so that versions are dealt with before broadcasts etc.
    TreeMap<List<String>, Collection<ConstrainedAttribute>> map = Maps.newTreeMap(LENGTH_ORDER);
    map.putAll(attributeConstraints.asMap());

    DBObject finalQuery = new BasicDBObject();

    Map<List<String>, DBObject> queries = Maps.newHashMap();
    for (Entry<List<String>, Collection<ConstrainedAttribute>> entry : map.entrySet()) {

        List<String> entityPath = entry.getKey();

        Collection<ConstrainedAttribute> constraints = entry.getValue();

        if (entityPath.isEmpty()) {
            finalQuery.putAll(buildQueryForSingleLevelEntity(constraints));
            continue;
        }

        DBObject parentDbObject = null;

        List<String> parentPath = entityPath;
        while (!parentPath.isEmpty()) {
            parentPath = parentPath.subList(0, parentPath.size() - 1);
            if (queries.get(parentPath) != null) {
                parentDbObject = queries.get(parentPath);
                break;
            }
        }
        if (parentDbObject == null) {
            parentDbObject = finalQuery;
            parentPath = ImmutableList.of();
        }

        DBObject rhs = buildQueryForSingleLevelEntity(constraints);
        String key = DOTTED_MONGO_ATTRIBUTE_PATH.join(entityPath.subList(parentPath.size(), entityPath.size()));
        DBObject attrObj = new BasicDBObject(key, new BasicDBObject(MongoConstants.ELEM_MATCH, rhs));
        parentDbObject.putAll(attrObj);
        queries.put(entityPath, rhs);
    }
    return finalQuery;
}

From source file:org.devgateway.ocds.web.rest.controller.CostEffectivenessVisualsController.java

License:Open Source License

@ApiOperation(value = "Cost effectiveness of Tenders:"
        + " Displays the total amount of the active tenders that have active awards, "
        + "grouped by year. Only tenders.status=active"
        + "are taken into account. The year is calculated from tenderPeriod.startDate")
@RequestMapping(value = "/api/costEffectivenessTenderAmount", method = { RequestMethod.POST,
        RequestMethod.GET }, produces = "application/json")
public List<DBObject> costEffectivenessTenderAmount(
        @ModelAttribute @Valid final GroupingFilterPagingRequest filter) {

    DBObject project = new BasicDBObject();
    project.put("year", new BasicDBObject("$year", MongoConstants.FieldNames.TENDER_PERIOD_START_DATE_REF));
    addYearlyMonthlyProjection(filter, project, MongoConstants.FieldNames.TENDER_PERIOD_START_DATE_REF);
    project.put("tender.value.amount", 1);
    project.put(Fields.UNDERSCORE_ID, "$tender._id");
    project.put("tenderWithAwards",
            new BasicDBObject("$cond", Arrays.asList(
                    new BasicDBObject("$eq", Arrays.asList("$awards.status", Award.Status.active.toString())),
                    1, 0)));/*  w  w w . j  ava  2  s.c  o  m*/
    project.put("tenderWithAwardsValue", new BasicDBObject("$cond",
            Arrays.asList(
                    new BasicDBObject("$eq", Arrays.asList("$awards.status", Award.Status.active.toString())),
                    "$tender.value.amount", 0)));
    project.putAll(filterProjectMap);

    DBObject group1 = new BasicDBObject();
    group1.put(Fields.UNDERSCORE_ID, Fields.UNDERSCORE_ID_REF);
    addYearlyMonthlyGroupingOperationFirst(filter, group1);
    group1.put("tenderWithAwards", new BasicDBObject("$max", "$tenderWithAwards"));
    group1.put("tenderWithAwardsValue", new BasicDBObject("$max", "$tenderWithAwardsValue"));
    group1.put("tenderAmount", new BasicDBObject("$first", "$tender.value.amount"));
    filterProjectMap
            .forEach(
                    (k, v) -> group1
                            .put(k.replace(".", ""),
                                    k.equals("tender.items.classification._id")
                                            ? new BasicDBObject("$first",
                                                    new BasicDBObject("$arrayElemAt",
                                                            Arrays.asList("$" + k, 0)))
                                            : new BasicDBObject("$first", "$" + k)));

    Aggregation agg = Aggregation
            .newAggregation(
                    match(where("tender.status").is(Tender.Status.active.toString())
                            .and(MongoConstants.FieldNames.TENDER_PERIOD_START_DATE).exists(true)
                            .andOperator(
                                    getYearDefaultFilterCriteria(filter,
                                            MongoConstants.FieldNames.TENDER_PERIOD_START_DATE))),
                    getMatchDefaultFilterOperation(filter), new CustomUnwindOperation("$awards", true),
                    new CustomProjectionOperation(project), new CustomGroupingOperation(group1),
                    getTopXFilterOperation(filter, getYearlyMonthlyGroupingFields(filter))
                            .sum("tenderWithAwardsValue").as(Keys.TOTAL_TENDER_AMOUNT).count()
                            .as(Keys.TOTAL_TENDERS).sum("tenderWithAwards").as(Keys.TOTAL_TENDER_WITH_AWARDS),
                    project(Keys.TOTAL_TENDER_AMOUNT, Keys.TOTAL_TENDERS, Keys.TOTAL_TENDER_WITH_AWARDS)
                            .andInclude(
                                    Fields.from(Fields.field(Fields.UNDERSCORE_ID, Fields.UNDERSCORE_ID_REF)))
                            .and(Keys.TOTAL_TENDER_WITH_AWARDS).divide(Keys.TOTAL_TENDERS)
                            .as(Keys.FRACTION_TENDERS_WITH_AWARDS),
                    project(Keys.TOTAL_TENDER_AMOUNT, Keys.TOTAL_TENDERS, Keys.TOTAL_TENDER_WITH_AWARDS,
                            Fields.UNDERSCORE_ID).and(Keys.FRACTION_TENDERS_WITH_AWARDS).multiply(100)
                                    .as(Keys.PERCENTAGE_TENDERS_WITH_AWARDS),
                    (filter.getGroupByCategory() == null ? transformYearlyGrouping(filter) : project())
                            .andInclude(Keys.TOTAL_TENDER_AMOUNT, Keys.TOTAL_TENDERS,
                                    Keys.TOTAL_TENDER_WITH_AWARDS, Keys.PERCENTAGE_TENDERS_WITH_AWARDS),
                    filter.getGroupByCategory() == null ? getSortByYearMonth(filter)
                            : sort(Sort.Direction.DESC, Keys.TOTAL_TENDER_AMOUNT),
                    skip(filter.getSkip()), limit(filter.getPageSize()))
            .withOptions(Aggregation.newAggregationOptions().allowDiskUse(true).build());

    AggregationResults<DBObject> results = mongoTemplate.aggregate(agg, "release", DBObject.class);
    List<DBObject> tagCount = results.getMappedResults();

    return tagCount;

}

From source file:org.devgateway.ocds.web.rest.controller.FundingByLocationController.java

License:Open Source License

@ApiOperation("Calculates percentage of releases with tender with at least one specified delivery location,"
        + " that is the array tender.items.deliveryLocation has to have items."
        + "Filters out stub tenders, therefore tender.tenderPeriod.startDate has to exist.")
@RequestMapping(value = "/api/qualityFundingByTenderDeliveryLocation", method = { RequestMethod.POST,
        RequestMethod.GET }, produces = "application/json")
public List<DBObject> qualityFundingByTenderDeliveryLocation(
        @ModelAttribute @Valid final YearFilterPagingRequest filter) {

    DBObject project = new BasicDBObject();
    project.putAll(filterProjectMap);
    project.put(Fields.UNDERSCORE_ID, "$tender._id");
    project.put("tenderItemsDeliveryLocation", new BasicDBObject("$cond", Arrays
            .asList(new BasicDBObject("$gt", Arrays.asList("$tender.items.deliveryLocation", null)), 1, 0)));

    DBObject project1 = new BasicDBObject();
    project1.put(Fields.UNDERSCORE_ID, 0);
    project1.put(Keys.TOTAL_TENDERS_WITH_START_DATE, 1);
    project1.put(Keys.TOTAL_TENDERS_WITH_START_DATE_AND_LOCATION, 1);
    project1.put(Keys.PERCENT_TENDERS_WITH_START_DATE_AND_LOCATION, new BasicDBObject("$multiply",
            Arrays.asList(new BasicDBObject("$divide",
                    Arrays.asList("$totalTendersWithStartDateAndLocation", "$totalTendersWithStartDate")),
                    100)));/*from w  ww.ja  va 2s.c o  m*/

    Aggregation agg = newAggregation(
            match(where(MongoConstants.FieldNames.TENDER_PERIOD_START_DATE).exists(true).andOperator(
                    getYearDefaultFilterCriteria(filter, MongoConstants.FieldNames.TENDER_PERIOD_START_DATE))),
            unwind("$tender.items"), new CustomProjectionOperation(project),
            group(Fields.UNDERSCORE_ID_REF).max("tenderItemsDeliveryLocation")
                    .as("hasTenderItemsDeliverLocation"),
            group().count().as("totalTendersWithStartDate").sum("hasTenderItemsDeliverLocation").as(
                    Keys.TOTAL_TENDERS_WITH_START_DATE_AND_LOCATION),
            new CustomProjectionOperation(project1)
    // ,skip(filter.getSkip()),limit(filter.getPageSize())
    );

    AggregationResults<DBObject> results = mongoTemplate.aggregate(agg, "release", DBObject.class);
    List<DBObject> tagCount = results.getMappedResults();
    return tagCount;
}

From source file:org.eclipse.birt.data.oda.mongodb.internal.impl.MDbOperation.java

License:Open Source License

static MapReduceOutput callMapReduceCmd(DBCollection dbCollection, QueryProperties queryProps)
        throws OdaException {
    if (!queryProps.hasMapReduceCommand())
        return null;
    DBObject command = queryProps.getOperationExprAsParsedObject(false);
    if (command == null)
        return null;

    // check if mapreduce key is already specified in user-defined expression
    DBObject mapReduceCmd;
    if (command.containsField(QueryModel.MAP_REDUCE_CMD_KEY)
            || command.containsField(QueryModel.MAP_REDUCE_CMD_KEY2))
        mapReduceCmd = command;/*from   ww  w  .ja v  a2  s .c om*/
    else {
        // add MapReduce input collection as first entry in command Map 
        mapReduceCmd = new BasicDBObject(QueryModel.MAP_REDUCE_CMD_KEY, dbCollection.getName());
        mapReduceCmd.putAll(command); // copy existing command entries
    }

    // mapReduce command's optional "limit" parameter applies to the number 
    // of documents in the *input* collection, and thus cannot be used to apply
    // the searchLimit property defined for data set

    // execute the mapreduce command
    MapReduceOutput output;
    try {
        output = dbCollection.mapReduce(mapReduceCmd);
        output.getCommandResult().throwOnError();
        return output;
    } catch (RuntimeException ex) {
        OdaException odaEx = new OdaException(
                Messages.bind(Messages.mDbOp_mapReduceCmdFailed, queryProps.getOperationExpression()));
        odaEx.initCause(ex);
        throw odaEx;
    }
}