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.gigaspaces.persistency.MongoSpaceDataSource.java

License:Open Source License

public DBObject getInitialQuery(SpaceTypeDescriptor typeDescriptor) {
    DBObject query = new BasicDBObject();
    String routingPropertyName = typeDescriptor.getRoutingPropertyName();
    if (clusterInfo != null && clusterInfo.getNumberOfInstances() > 1 && routingPropertyName != null) {
        SpacePropertyDescriptor routingPropDesc = typeDescriptor.getFixedProperty(routingPropertyName);
        if (Integer.class.isAssignableFrom(routingPropDesc.getType())) {
            ArrayList l = new ArrayList();
            l.add(clusterInfo.getNumberOfInstances());
            l.add(clusterInfo.getInstanceId() - 1);

            query.put(routingPropertyName, new BasicDBObject("$mod", l));
        }/*from   ww w .  jav  a 2 s.c  om*/
    }

    return query;
}

From source file:com.github.camellabs.iot.cloudlet.document.driver.mongodb.BsonMapper.java

License:Apache License

public static DBObject bsonToJson(DBObject bson) {
    checkNotNull(bson, "BSON passed to the conversion can't be null.");
    LOG.debug("Converting BSON object to JSON: {}", bson);
    DBObject json = new BasicDBObject(bson.toMap());
    Object id = json.get("_id");
    if (id != null) {
        json.removeField("_id");
        json.put("id", id.toString());
    }// w  ww . j a  va2  s  . com
    return json;
}

From source file:com.github.camellabs.iot.cloudlet.document.driver.mongodb.BsonMapper.java

License:Apache License

public static DBObject jsonToBson(DBObject json) {
    checkNotNull(json, "JSON passed to the conversion can't be null.");
    LOG.debug("Converting JSON object to BSON: {}", json);
    DBObject bson = new BasicDBObject(json.toMap());
    Object id = bson.get("id");
    if (id != null) {
        bson.removeField("id");
        bson.put("_id", new ObjectId(id.toString()));
    }//from w  w w  .  j  a v  a  2s  .c  o m
    return bson;
}

From source file:com.github.carlomicieli.nerdmovies.models.MovieBeforeSaveListener.java

License:Apache License

@Override
public void onBeforeSave(Movie movie, DBObject dbo) {
    dbo.put("slug", movie.buildSlug());
    dbo.put("savedAt", new Date());
}

From source file:com.github.jmkgreen.morphia.mapping.DefaultMapper.java

License:Open Source License

DBObject toDBObject(Object entity, Map<Object, DBObject> involvedObjects, boolean lifecycle) {

    DBObject dbObject = new BasicDBObject();
    MappedClass mc = getMappedClass(entity);

    if (mc.getEntityAnnotation() == null || !mc.getEntityAnnotation().noClassnameStored())
        dbObject.put(CLASS_NAME_FIELDNAME, entity.getClass().getName());

    if (lifecycle)
        dbObject = (DBObject) mc.callLifecycleMethods(PrePersist.class, entity, dbObject, this);

    for (MappedField mf : mc.getPersistenceFields()) {
        try {/*  ww w .j  av a2  s. com*/
            writeMappedField(dbObject, mf, entity, involvedObjects);
        } catch (Exception e) {
            throw new MappingException("Error mapping field:" + mf.getFullName(), e);
        }
    }
    if (involvedObjects != null)
        involvedObjects.put(entity, dbObject);

    if (lifecycle)
        mc.callLifecycleMethods(PreSave.class, entity, dbObject, this);

    return dbObject;
}

From source file:com.github.maasdi.di.trans.steps.mongodbdelete.MongoDbDeleteData.java

License:Apache License

public static DBObject getQueryObject(List<MongoDbDeleteMeta.MongoField> fieldDefs, RowMetaInterface inputMeta,
        Object[] row, VariableSpace vars) throws KettleException {

    DBObject query = new BasicDBObject();

    boolean haveMatchFields = false;
    boolean hasNonNullMatchValues = false;

    for (MongoDbDeleteMeta.MongoField field : fieldDefs) {
        haveMatchFields = true;//from  ww w . j  a  v a  2  s.c  o  m

        hasNonNullMatchValues = true;

        String mongoPath = field.m_mongoDocPath;
        String path = vars.environmentSubstitute(mongoPath);
        boolean hasPath = !Const.isEmpty(path);

        if (!hasPath) {
            throw new KettleException(
                    BaseMessages.getString(PKG, "MongoDbDelete.ErrorMessage.NoMongoPathsDefined"));
        }

        // post process arrays to fit the dot notation (if not already done
        // by the user)
        if (path.indexOf('[') > 0) {
            path = path.replace("[", ".").replace("]", "");
        }

        if (Comparator.EQUAL.getValue().equals(field.m_comparator)) {
            String field1 = vars.environmentSubstitute(field.m_incomingField1);
            int index = inputMeta.indexOfValue(field1);
            ValueMetaInterface vm = inputMeta.getValueMeta(index);

            // ignore null fields
            if (vm.isNull(row[index])) {
                continue;
            }

            setMongoValueFromKettleValue(query, path, vm, row[index]);
        } else if (Comparator.NOT_EQUAL.getValue().equals(field.m_comparator)) {
            String field1 = vars.environmentSubstitute(field.m_incomingField1);
            int index = inputMeta.indexOfValue(field1);
            ValueMetaInterface vm = inputMeta.getValueMeta(index);

            // ignore null fields
            if (vm.isNull(row[index])) {
                continue;
            }
            DBObject notEqual = new BasicDBObject();
            setMongoValueFromKettleValue(notEqual, "$ne", vm, row[index]);
            query.put(path.toString(), notEqual);
        } else if (Comparator.GREATER_THAN.getValue().equals(field.m_comparator)) {
            String field1 = vars.environmentSubstitute(field.m_incomingField1);
            int index = inputMeta.indexOfValue(field1);
            ValueMetaInterface vm = inputMeta.getValueMeta(index);

            // ignore null fields
            if (vm.isNull(row[index])) {
                continue;
            }
            DBObject greaterThan = new BasicDBObject();
            setMongoValueFromKettleValue(greaterThan, "$gt", vm, row[index]);
            query.put(path.toString(), greaterThan);

        } else if (Comparator.GREATER_THAN_EQUAL.getValue().equals(field.m_comparator)) {
            String field1 = vars.environmentSubstitute(field.m_incomingField1);
            int index = inputMeta.indexOfValue(field1);
            ValueMetaInterface vm = inputMeta.getValueMeta(index);

            // ignore null fields
            if (vm.isNull(row[index])) {
                continue;
            }
            DBObject greaterThanEqual = new BasicDBObject();
            setMongoValueFromKettleValue(greaterThanEqual, "$gte", vm, row[index]);
            query.put(path.toString(), greaterThanEqual);
        } else if (Comparator.LESS_THAN.getValue().equals(field.m_comparator)) {
            String field1 = vars.environmentSubstitute(field.m_incomingField1);
            int index = inputMeta.indexOfValue(field1);
            ValueMetaInterface vm = inputMeta.getValueMeta(index);

            // ignore null fields
            if (vm.isNull(row[index])) {
                continue;
            }
            DBObject lessThan = new BasicDBObject();
            setMongoValueFromKettleValue(lessThan, "$lt", vm, row[index]);
            query.put(path.toString(), lessThan);
        } else if (Comparator.LESS_THAN_EQUAL.getValue().equals(field.m_comparator)) {
            String field1 = vars.environmentSubstitute(field.m_incomingField1);
            int index = inputMeta.indexOfValue(field1);
            ValueMetaInterface vm = inputMeta.getValueMeta(index);

            // ignore null fields
            if (vm.isNull(row[index])) {
                continue;
            }
            DBObject lessThanEqual = new BasicDBObject();
            setMongoValueFromKettleValue(lessThanEqual, "$lte", vm, row[index]);
            query.put(path.toString(), lessThanEqual);
        } else if (Comparator.BETWEEN.getValue().equals(field.m_comparator)) {

            if (Const.isEmpty(field.m_incomingField1) || Const.isEmpty(field.m_incomingField2)) {
                throw new KettleException(
                        BaseMessages.getString(PKG, "MongoDbDelete.ErrorMessage.BetweenTwoFieldsRequired"));
            }

            String field1 = vars.environmentSubstitute(field.m_incomingField1);
            int index1 = inputMeta.indexOfValue(field1);
            ValueMetaInterface vm1 = inputMeta.getValueMeta(index1);

            String field2 = vars.environmentSubstitute(field.m_incomingField2);
            int index2 = inputMeta.indexOfValue(field2);
            ValueMetaInterface vm2 = inputMeta.getValueMeta(index2);

            // ignore null fields
            if (vm1.isNull(row[index1]) && vm2.isNull(row[index2])) {
                continue;
            }

            BasicDBObject between = new BasicDBObject();
            setMongoValueFromKettleValue(between, "$gt", vm1, row[index1]);
            setMongoValueFromKettleValue(between, "$lt", vm2, row[index2]);
            query.put(path.toString(), between);

        } else if (Comparator.IS_NULL.getValue().equals(field.m_comparator)) {
            BasicDBObject exist = new BasicDBObject();
            exist.put("$exists", false);
            query.put(path.toString(), exist);
        } else if (Comparator.IS_NOT_NULL.getValue().equals(field.m_comparator)) {
            BasicDBObject exist = new BasicDBObject();
            exist.put("$exists", true);
            query.put(path.toString(), exist);
        } else {
            throw new KettleException(BaseMessages.getString(PKG,
                    "MongoDbDelete.ErrorMessage.ComparatorNotSupported", new String[] { field.m_comparator }));
        }

    }

    if (!haveMatchFields) {
        throw new KettleException(
                BaseMessages.getString(PKG, "MongoDbDelete.ErrorMessage.NoFieldsToDeleteSpecifiedForMatch"));
    }

    if (!hasNonNullMatchValues) {
        return null;
    }

    return query;
}

From source file:com.github.maasdi.di.trans.steps.mongodbdelete.MongoDbDeleteData.java

License:Apache License

private static boolean setMongoValueFromKettleValue(DBObject mongoObject, Object lookup,
        ValueMetaInterface kettleType, Object kettleValue) throws KettleValueException {
    if (kettleType.isNull(kettleValue)) {
        return false; // don't insert nulls!
    }//from w ww  .  ja  va  2  s. c om

    if (kettleType.isString()) {
        String val = kettleType.getString(kettleValue);
        mongoObject.put(lookup.toString(), val);
        return true;
    }
    if (kettleType.isBoolean()) {
        Boolean val = kettleType.getBoolean(kettleValue);
        mongoObject.put(lookup.toString(), val);
        return true;
    }
    if (kettleType.isInteger()) {
        Long val = kettleType.getInteger(kettleValue);
        mongoObject.put(lookup.toString(), val.longValue());
        return true;
    }
    if (kettleType.isDate()) {
        Date val = kettleType.getDate(kettleValue);
        mongoObject.put(lookup.toString(), val);
        return true;
    }
    if (kettleType.isNumber()) {
        Double val = kettleType.getNumber(kettleValue);
        mongoObject.put(lookup.toString(), val.doubleValue());
        return true;
    }
    if (kettleType.isBigNumber()) {
        // use string value - user can use Kettle to convert back
        String val = kettleType.getString(kettleValue);
        mongoObject.put(lookup.toString(), val);
        return true;
    }
    if (kettleType.isBinary()) {
        byte[] val = kettleType.getBinary(kettleValue);
        mongoObject.put(lookup.toString(), val);
        return true;
    }
    if (kettleType.isSerializableType()) {
        throw new KettleValueException(
                BaseMessages.getString(PKG, "MongoDbDelete.ErrorMessage.CantStoreKettleSerializableVals"));
    }

    return false;
}

From source file:com.github.mongo.labs.api.GeoService.java

License:Apache License

@GET
@Path("/")
@ApiOperation(value = "Retourne tous les speakers avec leurs donnes de golocalisation, nom et id", notes = "C'est trs proche du service /speakers/ : les donnes sont les mmes, mais la structure est diffrente.")
public String all() {
    DBObject projection = new BasicDBObject();
    projection.put("name", 1);
    projection.put("geo", 1);
    return JSON.serialize(
            speakers.find(new BasicDBObject("geo", new BasicDBObject("$exists", "true")), projection));
}

From source file:com.github.mongo.labs.api.SpeakersService.java

License:Apache License

@GET
@Path("/")
@ApiOperation(value = "Retourne tous les speakers prsent  Devoxx")
public String all() {
    DBObject sort = new BasicDBObject();
    sort.put("name.lastName", 1);
    sort.put("name.firstName", 1);
    return JSON.serialize(dbCollection.find().sort(sort));
}

From source file:com.github.mongo.labs.api.TagsService.java

License:Apache License

@GET
@Path("/native/")
@ApiOperation(value = "Retourne les tags les plus utiliss avec leurs statistiques associes. Ce endpoint utilise le driver en native", notes = "Le framework d'aggrgation doit tre utilis pour remonter les bonnes donnes")
public String countByTag() {

    DBObject unwind = new BasicDBObject("$unwind", "$tags");
    DBObject project1 = new BasicDBObject("$project",
            new BasicDBObject("tags", new BasicDBObject("$toLower", "$tags")));

    DBObject groupFields = new BasicDBObject();
    groupFields.put("_id", "$tags");
    groupFields.put("count", new BasicDBObject("$sum", 1));
    DBObject group = new BasicDBObject("$group", groupFields);

    DBObject projectFields = new BasicDBObject();
    projectFields.put("_id", 0);
    projectFields.put("tags", "$_id");
    projectFields.put("count", 1);

    DBObject project2 = new BasicDBObject("$project", projectFields);

    DBObject sort = new BasicDBObject("$sort", new BasicDBObject("count", -1));

    return JSON.serialize(dbCollection.aggregate(unwind, project1, group, project2, sort).results());
}