Example usage for com.mongodb BasicDBObject toMap

List of usage examples for com.mongodb BasicDBObject toMap

Introduction

In this page you can find the example usage for com.mongodb BasicDBObject toMap.

Prototype

public Map toMap() 

Source Link

Document

Converts a DBObject to a map.

Usage

From source file:com.petpet.c3po.dao.mongo.MongoPersistenceLayer.java

License:Apache License

public DBObject mapReduceStats(int key, String property, Filter filter) {
    LOG.debug("Starting mapReduceStats for the following property: {}", property);
    long start = System.currentTimeMillis();
    Property prop = getCache().getProperty(property);
    String propType = prop.getType();
    String map = "";
    String reduce = "";
    String finalize = "";
    if (propType.equals(PropertyType.INTEGER.toString()) || propType.equals(PropertyType.FLOAT.toString())) {
        map = "function() {\n" + "    property = '" + property + "';\n" + "    for (mr in this.metadata){\n"
                + "        metadataRecord=this.metadata[mr];\n"
                + "        if(metadataRecord.property == property){\n" + "            {\n"
                + "                emit({\n" + "                    property: property,\n"
                + "                    value: property\n" + "                }, \n" + "                {\n"
                + "                    sum: metadataRecord.sourcedValues[0].value,\n"
                + "                    min: metadataRecord.sourcedValues[0].value,\n"
                + "                    max: metadataRecord.sourcedValues[0].value,\n"
                + "                    count: 1,\n" + "                    diff: 0\n" + "                }\n"
                + "                )\n" + "            }\n" + "            return;\n" + "        }\n"
                + "    }\n" + "    emit({\n" + "        property: property,\n" + "        value: 'Unknown'\n"
                + "        }, 1);\n" + "}\n";
        reduce = "function reduce(key, values) {\n" + "var a = values[0];\n"
                + "        for (var i = 1; i < values.length; i++) {\n" + "            var b = values[i];\n"
                + "            var delta = a.sum / a.count - b.sum / b.count;\n"
                + "            var weight = (a.count * b.count) / (a.count + b.count);\n"
                + "            a.diff += b.diff + delta * delta * weight;\n"
                + "            a.sum = b.sum*1+ a.sum*1;\n" + "            a.count += b.count;\n"
                + "            a.min = Math.min(a.min, b.min);\n"
                + "            a.max = Math.max(a.max, b.max);\n" + "        }\n" + "return a;" + "}"

        ;//from  w  ww.  j  a v a  2  s. c o  m
        finalize = "function finalize(key, value) {\n" + "    value.avg = value.sum / value.count;\n"
                + "    value.variance = value.diff / value.count;\n"
                + "    value.stddev = Math.sqrt(value.variance);\n" + "    return value;\n" + "}";

    }
    DBObject query = this.getCachedFilter(filter);
    LOG.debug("filter query is:\n{}", query);
    DBCollection elmnts = getCollection(Element.class);
    MapReduceCommand cmd = new MapReduceCommand(elmnts, map, reduce, null, INLINE, query);
    cmd.setFinalize(finalize);
    MapReduceOutput output = elmnts.mapReduce(cmd);

    //List<BasicDBObject> results = (List<BasicDBObject>) output.getCommandResult().get( "results" );
    Iterator<DBObject> iterator = output.results().iterator();
    List<BasicDBObject> results = new ArrayList<BasicDBObject>();
    while (iterator.hasNext()) {
        results.add((BasicDBObject) iterator.next());

    }

    LOG.debug("MapReduce produced {} results", results.size());
    DBCollection histCollection = this.db.getCollection(TBL_HISTOGRAMS);
    BasicDBObject old = new BasicDBObject("_id", key);
    BasicDBObject res = new BasicDBObject(old.toMap());
    res.put("results", results);
    histCollection.update(old, res, true, false);

    DBCursor cursor = histCollection.find(new BasicDBObject("_id", key));

    if (cursor.count() == 0) {
        return null;
    }
    long end = System.currentTimeMillis();
    LOG.debug("The map-reduce job took {} seconds", (end - start) / 1000);
    return (DBObject) cursor.next().get("results");
}

From source file:com.streamreduce.storm.spouts.EventSpout.java

License:Apache License

/**
 * {@inheritDoc}//from   w w w . j a  va 2s.  c  o  m
 */
@Override
public void handleDBEntry(SpoutOutputCollector collector, BasicDBObject entry) {
    BasicDBObject metadata = entry.containsField("metadata") ? (BasicDBObject) entry.get("metadata")
            : new BasicDBObject();
    String eventType = metadata.getString("targetType");

    // Just in case
    if (eventType == null) {
        // TODO: Figure out the best way to handle this

        // Log the inability to process further
        logger.error("Event with id of " + entry.get("_id") + " has no target type.  Unable to process.");

        // Early return to avoid emitting the event
        return;
    }

    String v = (String) metadata.get("targetVisibility");
    if (v != null) {
        Visibility visibility = Visibility.valueOf(v);
        if (visibility == Visibility.SELF) {
            // do not process private information
            return;
        }
    }

    MongoClient.mapMongoToPlainJavaTypes(entry);
    // Emit the entry to the type-specific stream
    collector.emit(eventType, new Values(entry.toMap()));
    ack(entry);
}

From source file:mx.org.cedn.avisosconagua.mongo.MongoInterface.java

License:Open Source License

/**
 * Makes a deep clone of an existing advice object.
 * @param originAdviceID source object//www .j  a v a  2 s  . com
 * @param currentAdviceId ID for the cloned advice object
 */
public void copyFromAdvice(String originAdviceID, String currentAdviceId) {
    BasicDBObject origen = getAdvice(originAdviceID);
    BasicDBObject destino = getAdvice(currentAdviceId);
    destino.putAll(origen.toMap());
    destino.put(INTERNAL_FORM_ID, currentAdviceId);
    origen = getAdvice(currentAdviceId);
    mongoDB.getCollection(CAPTURA_COL).update(origen, destino);
}

From source file:org.canedata.provider.mongodb.entity.MongoEntity.java

License:Apache License

public int update(Serializable... keys) {
    if (logger.isDebug())
        logger.debug("Updating entitiy, Database is {0}, Collection is {1}, keys is {2}.", getSchema(),
                getName(), Arrays.toString(keys));

    try {/*from   ww w.j ava2s . c om*/
        if (keys == null || keys.length == 0)
            return 0;

        validateState();

        final BasicDBObject fields = new BasicDBObject();
        final BasicDBObject othersFields = new BasicDBObject();
        final BasicDBObject options = new BasicDBObject();

        getIntent().playback(new Tracer() {

            public Tracer trace(Step step) throws AnalyzeBehaviourException {
                switch (step.step()) {
                case MongoStep.PUT:
                    if (logger.isDebug())
                        logger.debug("Analyzing behivor PUT, step is {0}, purpose is {1}, scalar is {2}.",
                                step.step(), step.getPurpose(), Arrays.toString(step.getScalar()));

                    if (StringUtils.isBlank(step.getPurpose()))
                        break;

                    Object val = (step.getScalar() == null || step.getScalar().length == 0) ? null
                            : step.getScalar()[0];

                    if (step.getPurpose().matches(internalCmds))
                        othersFields.append(step.getPurpose(), val);
                    else
                        fields.append(step.getPurpose(), val);

                    break;
                case MongoStep.OPTION:
                    options.append(step.getPurpose(), step.getScalar()[0]);

                    break;
                default:
                    logger.warn("Step {0} does not apply to activities create, this step will be ignored.",
                            step.step());
                }

                return this;
            }

        });

        BasicDBObject fs = new BasicDBObject();
        if (!fields.isEmpty())
            fs.put("$set", fields);

        if (!othersFields.isEmpty())
            fs.putAll(othersFields.toMap());

        if (fs.isEmpty())
            return 0;

        WriteResult wr = getCollection().update(new BasicDBObject().append("_id", keys[0]), fs,
                options.getBoolean(Options.UPSERT, false), false, getCollection().getWriteConcern());
        if (!StringUtils.isBlank(wr.getError()))
            throw new DataAccessException(wr.getError());

        // invalidate cache
        if (null != getCache()) {
            String cacheKey = getKey().concat("#").concat(keys[0].toString());
            getCache().remove(cacheKey);

            if (logger.isDebug())
                logger.debug("Invalidated cache key is {0}.", keys[0].toString());
        }

        return wr.getN();
    } catch (AnalyzeBehaviourException abe) {
        if (logger.isDebug())
            logger.debug(abe, "Analyzing behaviour failure, cause by: {0}.", abe.getMessage());

        throw new RuntimeException(abe);
    } finally {
        getIntent().reset();
    }
}

From source file:org.canedata.provider.mongodb.entity.MongoEntity.java

License:Apache License

public int updateRange(Expression expr) {
    if (logger.isDebug())
        logger.debug("Updating entities, Database is {0}, Collection is {1} ...", getSchema(), getName());

    try {/*from w  w  w.ja  va  2 s. c o  m*/
        validateState();

        final BasicDBObject fields = new BasicDBObject();
        final BasicDBObject othersFields = new BasicDBObject();
        final BasicDBObject options = new BasicDBObject();

        getIntent().playback(new Tracer() {

            public Tracer trace(Step step) throws AnalyzeBehaviourException {
                switch (step.step()) {
                case MongoStep.PUT:
                    if (StringUtils.isBlank(step.getPurpose()))
                        break;

                    Object val = (step.getScalar() == null || step.getScalar().length == 0) ? null
                            : step.getScalar()[0];

                    if (step.getPurpose().matches(internalCmds))
                        othersFields.append(step.getPurpose(), val);
                    else
                        fields.append(step.getPurpose(), val);

                    break;
                case MongoStep.OPTION:
                    options.append(step.getPurpose(), step.getScalar()[0]);

                    break;
                default:
                    logger.warn("Step {0} does not apply to activities create, this step will be ignored.",
                            step.step());
                }

                return this;
            }

        });

        final MongoExpressionFactory expFactory = new MongoExpressionFactory.Impl();
        BasicDBObject query = expFactory.parse((MongoExpression) expr);

        if (logger.isDebug())
            logger.debug("Updating entities, Database is {0}, Collection is {1}, expression is {2} ...",
                    getSchema(), getName(), query.toString());

        BasicDBObject fs = new BasicDBObject();
        if (!fields.isEmpty())
            fs.append("$set", fields);

        if (!othersFields.isEmpty())
            fs.putAll(othersFields.toMap());

        if (fs.isEmpty())
            return 0;

        WriteResult wr = getCollection().update(query, fs, options.getBoolean(Options.UPSERT, false), true,
                getCollection().getWriteConcern());
        if (!StringUtils.isBlank(wr.getError()))
            throw new DataAccessException(wr.getError());

        // invalidate cache
        if (null != getCache()) {
            invalidateCache(query);
        }

        return wr.getN();
    } catch (AnalyzeBehaviourException abe) {
        if (logger.isDebug())
            logger.debug(abe, "Analyzing behaviour failure, cause by: {0}.", abe.getMessage());

        throw new RuntimeException(abe);
    } finally {
        getIntent().reset();
    }
}

From source file:org.graylog2.dashboards.DashboardServiceImpl.java

License:Open Source License

@Override
public Dashboard load(String id) throws NotFoundException {
    BasicDBObject o = (BasicDBObject) get(DashboardImpl.class, id);

    if (o == null) {
        throw new NotFoundException();
    }//from   w ww. j a  v  a 2 s .  co m

    return new DashboardImpl((ObjectId) o.get("_id"), o.toMap());
}

From source file:org.graylog2.savedsearches.SavedSearchServiceImpl.java

License:Open Source License

@Override
@SuppressWarnings("unchecked")
public SavedSearchImpl load(String id) throws NotFoundException {
    BasicDBObject o = (BasicDBObject) get(SavedSearchImpl.class, id);

    if (o == null) {
        throw new NotFoundException();
    }/*from  w w w.  j a  v  a2  s  .co m*/

    return new SavedSearchImpl((ObjectId) o.get("_id"), o.toMap());
}

From source file:org.graylog2.streams.StreamRuleServiceImpl.java

License:Open Source License

@Override
public StreamRule load(String id) throws NotFoundException {
    BasicDBObject o = (BasicDBObject) get(StreamRuleImpl.class, new ObjectId(id));

    if (o == null) {
        throw new NotFoundException();
    }//from   w  w  w .j  a  v  a 2 s .  c  om

    return new StreamRuleImpl((ObjectId) o.get("_id"), o.toMap());
}

From source file:org.mule.transport.mongodb.MongoDBMessageDispatcher.java

License:Open Source License

protected Object doDispatchToCollection(MuleEvent event, String collection) throws Exception {
    Object payload = event.getMessage().getPayload();

    DB db;/*from  w w  w .  ja v  a2  s . co  m*/
    db = connector.getMongo().getDB(connector.getMongoURI().getDatabase());
    db.requestStart();

    if (payload instanceof List) {
        List list = (List) payload;

        for (Object o : list) {
            performOperation(event, o, db, collection);
        }

        db.requestDone();
        return payload;
    } else {
        MuleMessage message = event.getMessage();

        BasicDBObject result = performOperation(event, message.getPayload(), db, collection);

        Object id = getObjectIdAsString(result.get("_id"));

        if (id == null) {
            logger.warn("_id is null, cannot set " + MongoDBConnector.PROPERTY_OBJECT_ID);
        } else {
            event.getMessage().setOutboundProperty(MongoDBConnector.PROPERTY_OBJECT_ID, id);
        }
        db.requestDone();

        return result.toMap();
    }
}

From source file:org.opencb.opencga.storage.mongodb.variant.DBObjectToSamplesConverter.java

License:Apache License

private VariantSourceEntry getLegacyNoncompressedSamples(BasicDBObject object) {
    VariantSourceEntry variantSourceEntry = new VariantSourceEntry(object.get(FILEID_FIELD).toString(),
            object.get(STUDYID_FIELD).toString());

    BasicDBObject mongoGenotypes = (BasicDBObject) object.get(GENOTYPES_FIELD);
    for (Object entry : mongoGenotypes.toMap().entrySet()) {
        Map.Entry sample = (Map.Entry) entry;
        variantSourceEntry.addSampleData(sample.getKey().toString(), ((DBObject) sample.getValue()).toMap());
    }/*from  w  ww .j a  va 2  s.  c  om*/
    //            for (String sample : samples) {
    //                Map<String, String> sampleData = ((DBObject) mongoGenotypes.get(sample)).toMap();
    //                fileWithSamples.addSampleData(sample, sampleData);
    //                System.out.println("Sample processed: " + sample);
    //            }
    return variantSourceEntry;
}