Example usage for com.mongodb DBObject containsField

List of usage examples for com.mongodb DBObject containsField

Introduction

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

Prototype

boolean containsField(String s);

Source Link

Document

Checks if this object contains a field with the given name.

Usage

From source file:org.fornax.cartridges.sculptor.framework.accessimpl.mongodb.MongoDbSaveAccessImpl.java

License:Apache License

protected T performSave(T obj) {
    updateAuditInformation(obj);/*from  ww w.ja  va 2 s  .com*/
    DBObject dbObj = getDataMapper().toData(obj);

    if (dbObj.containsField("_id")) {
        if (dbObj.containsField("version")) {
            updateWithOptimisticLocking(obj, dbObj);
        } else {
            update(dbObj);
        }
    } else {
        insert(obj, dbObj);
    }

    return obj;
}

From source file:org.fornax.cartridges.sculptor.framework.accessimpl.mongodb.MongoDbSaveAccessImpl.java

License:Apache License

protected void insert(T obj, DBObject dbObj) {
    ObjectId objectId = ObjectId.get();/*w  ww  .ja v a2  s. c o  m*/
    dbObj.put("_id", objectId);
    Long newVersion = null;
    if (dbObj.containsField("version") && dbObj.get("version") == null) {
        newVersion = 1L;
        dbObj.put("version", newVersion);
    }
    getDBCollection().insert(dbObj);
    checkLastError();
    IdReflectionUtil.internalSetId(obj, objectId.toStringMongod());
    if (newVersion != null) {
        IdReflectionUtil.internalSetVersion(obj, newVersion);
    }
}

From source file:org.fornax.cartridges.sculptor.framework.accessimpl.mongodb.MongoDbSaveAccessImpl.java

License:Apache License

protected void updateWithOptimisticLocking(T obj, DBObject dbObj) {
    Long version = (Long) dbObj.get("version");
    DBObject q = new BasicDBObject();
    q.put("_id", dbObj.get("_id"));
    // version in db must be same as old version
    q.put("version", version);
    Long newVersion;//from  w  w w  .  j  a v  a2s .  co m
    if (version == null) {
        newVersion = 1L;
    } else {
        newVersion = version + 1;
    }
    dbObj.put("version", newVersion);
    DBCollection dbCollection = getDBCollection();
    dbCollection.update(q, dbObj);
    DBObject lastError = dbCollection.getDB().getLastError();

    if (lastError.containsField("updatedExisting") && Boolean.FALSE.equals(lastError.get("updatedExisting"))) {
        throw new OptimisticLockingException(
                "Optimistic locking violation. Object was updated by someone else.");
    }

    checkLastError();
    IdReflectionUtil.internalSetVersion(obj, newVersion);
}

From source file:org.fracturedatlas.athena.apa.impl.MongoApaAdapter.java

License:Open Source License

@Override
public TicketProp getTicketProp(String fieldName, String type, Object ticketId) {
    TicketProp ticketProp = null;/*from  w  ww  .j  av  a  2 s  .  c om*/
    DBObject recordDoc = getRecordDocument(new BasicDBObject(), type, ObjectId.massageToObjectId(ticketId));

    if (recordDoc != null) {
        DBObject propsObj = (DBObject) recordDoc.get("props");
        if (propsObj.containsField(fieldName)) {
            PropField field = getPropField(fieldName);

            ticketProp = field.getValueType().newTicketProp();
            ticketProp.setId(null);
            ticketProp.setPropField(field);

            try {
                ticketProp.setValue(propsObj.get(fieldName));
            } catch (Exception e) {
                //TODO: This should throw something besides Exception
                logger.error(e.getMessage(), e);
            }

            JpaRecord hugeWorkaround = new JpaRecord(type);
            hugeWorkaround.setId(ticketId);
            ticketProp.setTicket(hugeWorkaround);
        }
    }

    return ticketProp;
}

From source file:org.fracturedatlas.athena.apa.impl.MongoApaAdapter.java

License:Open Source License

@Override
public void deleteTicketProp(TicketProp prop) {

    if (prop.getTicket() != null) {
        DBObject recordDoc = getRecordDocument(new BasicDBObject(), prop.getTicket().getType(),
                ObjectId.massageToObjectId(prop.getTicket().getId()));
        String fieldName = prop.getPropField().getName();
        if (recordDoc != null) {
            DBObject propsObj = (DBObject) recordDoc.get("props");
            if (propsObj.containsField(fieldName)) {
                propsObj.removeField(fieldName);
            }/* ww w  .j a v  a2 s .co  m*/
            recordDoc.put("props", propsObj);
            db.getCollection(prop.getTicket().getType()).save(recordDoc);
        }
    }
}

From source file:org.geotools.data.mongodb.MongoResultSet.java

License:LGPL

/**
 * Create a Geometry object; GeometryCollection, Point, MultiPoint, Polygon etc.
 * //from   w w w.  j a v  a2 s  .  c  om
 * @param type Geometry type to create
 * @param geoElement coordinates
 * @return Geometry, may be null if coordinates null/invalid, or type invalid
 */
private Geometry createGeometry(GeometryType type, DBObject coordinates) {
    Geometry geometryObj = null;

    // GeometryCollection different; has geometries field rather than coordinates
    if (type.equals(GeometryType.GeometryCollection)) {
        if (!coordinates.containsField("geometries")) {
            log.warning("No geometries detected for GeometryCollection, skipping.");
            return geometryObj;
        }
        BasicDBList geometryList = (BasicDBList) coordinates.get("geometries");
        int i = 0;
        Geometry[] geometries = new Geometry[geometryList.size()];
        for (Object geoElement : geometryList) {
            String subType = (String) ((BasicDBList) geoElement).get("type");
            GeometryType geoType = GeometryType.valueOf(subType);
            geometries[i++] = createGeometry(geoType, (DBObject) geoElement);
        }
        geometryObj = geoFactory.createGeometryCollection(geometries);
    }

    // all other geometry types; Point, Polygon etc.
    else {
        if (!coordinates.containsField("coordinates")) {
            return geoFactory.createPoint((Coordinate) null);
        }

        BasicDBList coords = (BasicDBList) coordinates.get("coordinates");
        int i = 0;

        switch (type) {
        case LineString:
            geometryObj = createLineString(coords);
            break;

        case Point:
            geometryObj = createPoint(coords);
            break;

        case Polygon:
            geometryObj = createPolygon(coords);
            break;

        case MultiLineString:
            LineString[] lines = new LineString[coords.size()];
            for (Object lineCoords : coords) {
                lines[i++] = createLineString((BasicDBList) lineCoords);
            }
            geometryObj = geoFactory.createMultiLineString(lines);
            break;

        case MultiPoint:
            Point[] points = new Point[coords.size()];
            for (Object obj : coords) {
                BasicDBList aPoint = (BasicDBList) obj;
                points[i++] = createPoint(aPoint);
            }
            geometryObj = geoFactory.createMultiPoint(points);
            break;

        case MultiPolygon:
            Polygon[] polys = new Polygon[coords.size()];
            for (Object polyCoords : coords) {
                polys[i++] = createPolygon((BasicDBList) polyCoords);
            }
            geometryObj = geoFactory.createMultiPolygon(polys);
            break;
        }
    }

    return geometryObj;
}

From source file:org.graylog2.cluster.NodeServiceImpl.java

License:Open Source License

@Override
public Node byNodeId(String nodeId) throws NodeNotFoundException {
    DBObject query = new BasicDBObject("node_id", nodeId);
    DBObject o = findOne(NodeImpl.class, query);

    if (o == null || !o.containsField("node_id")) {
        throw new NodeNotFoundException("Unable to find node " + nodeId);
    }// ww w . ja v a 2 s . c o m

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

From source file:org.graylog2.inputs.InputServiceImpl.java

License:Open Source License

@Override
@SuppressWarnings("unchecked")
public List<Extractor> getExtractors(Input input) {
    if (input.getFields().get(InputImpl.EMBEDDED_EXTRACTORS) == null) {
        return Collections.emptyList();
    }//  w  w w.  java2  s.  c  om

    final ImmutableList.Builder<Extractor> listBuilder = ImmutableList.builder();
    final BasicDBList mEx = (BasicDBList) input.getFields().get(InputImpl.EMBEDDED_EXTRACTORS);
    for (final Object element : mEx) {
        final DBObject ex = (BasicDBObject) element;

        // SOFT MIGRATION: does this extractor have an order set? Implemented for issue: #726
        Long order = 0l;
        if (ex.containsField(Extractor.FIELD_ORDER)) {
            order = (Long) ex.get(Extractor.FIELD_ORDER); // mongodb driver gives us a java.lang.Long
        }

        try {
            final Extractor extractor = extractorFactory.factory((String) ex.get(Extractor.FIELD_ID),
                    (String) ex.get(Extractor.FIELD_TITLE), order.intValue(),
                    Extractor.CursorStrategy
                            .valueOf(((String) ex.get(Extractor.FIELD_CURSOR_STRATEGY)).toUpperCase()),
                    Extractor.Type.valueOf(((String) ex.get(Extractor.FIELD_TYPE)).toUpperCase()),
                    (String) ex.get(Extractor.FIELD_SOURCE_FIELD),
                    (String) ex.get(Extractor.FIELD_TARGET_FIELD),
                    (Map<String, Object>) ex.get(Extractor.FIELD_EXTRACTOR_CONFIG),
                    (String) ex.get(Extractor.FIELD_CREATOR_USER_ID), getConvertersOfExtractor(ex),
                    Extractor.ConditionType
                            .valueOf(((String) ex.get(Extractor.FIELD_CONDITION_TYPE)).toUpperCase()),
                    (String) ex.get(Extractor.FIELD_CONDITION_VALUE));

            listBuilder.add(extractor);
        } catch (Exception e) {
            LOG.error("Cannot build extractor from persisted data. Skipping.", e);
        }
    }

    return listBuilder.build();
}

From source file:org.graylog2.ServerValue.java

License:Open Source License

private DBObject findOrCreateMongoInstance(String instanceId) {
    DBCollection sv = MongoConnection.getInstance().getDatabase().getCollection("server_values");

    // Doing it this way because java driver sucks in querying for subdoc keys. :(
    DBCursor cur = sv.find(); // find all
    while (cur.hasNext()) {
        DBObject obj = cur.next();
        if (obj.containsField(instanceId)) {
            // Found the instance.
            return obj;
        }//from   ww w  . j a  v a 2s.  c o  m
    }

    // There is no such instance in the collection yet if we arrive here.
    DBObject instance = new BasicDBObject();
    instance.put(instanceId, null);
    sv.insert(instance);

    return instance;
}

From source file:org.hibernate.ogm.datastore.mongodb.impl.MongoDBSchemaDefiner.java

License:LGPL

private String getPreexistingTextIndex(Map<String, DBObject> preexistingIndexes) {
    for (Entry<String, DBObject> indexEntry : preexistingIndexes.entrySet()) {
        DBObject keys = (DBObject) indexEntry.getValue().get("key");
        if (keys != null && keys.containsField("_fts")) {
            return indexEntry.getKey();
        }//from  w  w w.  j a  va  2s .c om
    }
    return null;
}