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.opencb.opencga.storage.mongodb.variant.VariantSourceMongoDBAdaptor.java

License:Apache License

/**
 * Populates the dictionary relating sources and samples.
 *
 * @return The QueryResult with information of how long the query took
 *//*from w  w  w.  j a v  a  2s .c om*/
private QueryResult populateSamplesInSources() {
    MongoDBCollection coll = db.getCollection(collectionName);
    DBObject projection = new BasicDBObject(DBObjectToVariantSourceConverter.FILEID_FIELD, true)
            .append(DBObjectToVariantSourceConverter.SAMPLES_FIELD, true);
    QueryResult queryResult = coll.find((DBObject) null, projection, null);

    List<DBObject> result = queryResult.getResult();
    for (DBObject dbo : result) {
        if (!dbo.containsField(DBObjectToVariantSourceConverter.FILEID_FIELD)) {
            continue;
        }
        String key = dbo.get(DBObjectToVariantSourceConverter.FILEID_FIELD).toString();
        DBObject value = (DBObject) dbo.get(DBObjectToVariantSourceConverter.SAMPLES_FIELD);
        samplesInSources.put(key, new ArrayList(value.toMap().keySet()));
    }

    return queryResult;
}

From source file:org.opentaps.notes.repository.impl.NoteRepositoryImpl.java

License:Open Source License

private Note dbObjectToNote(DBObject noteDoc) {
    if (noteDoc == null) {
        return null;
    }// w ww  .ja v a 2  s.  c  o  m

    Note note = factory.newInstance();
    note.setNoteId(noteDoc.get(NoteMongo.MONGO_ID_FIELD).toString());
    note.setNoteText((String) noteDoc.get(Note.Fields.noteText.getName()));
    if (noteDoc.containsField("createdByUserId")) {
        String userId = (String) noteDoc.get("createdByUserId");
        if (!GenericValidator.isBlankOrNull(userId)) {
            note.setCreatedByUser(new NoteUser(userId, (String) noteDoc.get("userIdType")));
        }
    } else if (noteDoc.containsField(Note.Fields.createdByUser.getName())) {
        BasicDBObject userDoc = (BasicDBObject) noteDoc.get(Note.Fields.createdByUser.getName());
        if (userDoc != null) {
            User user = new NoteUser();
            Set<Entry<String, Object>> entries = userDoc.entrySet();
            for (Entry<String, Object> entry : entries) {
                user.getProperties().put(entry.getKey(), entry.getValue());
            }
            note.setCreatedByUser(user);
        }
    }
    note.setClientDomain((String) noteDoc.get(Note.Fields.clientDomain.getName()));
    note.setSequenceNum((Long) noteDoc.get(Note.Fields.sequenceNum.getName()));
    Date dateTimeCreated = (Date) noteDoc.get(Note.Fields.dateTimeCreated.getName());
    if (dateTimeCreated != null) {
        note.setDateTimeCreated(new Timestamp(dateTimeCreated.getTime()));
    }
    // look for custom fields
    for (String field : noteDoc.keySet()) {
        if (!note.isBaseField(field)) {
            note.setAttribute(field, (String) noteDoc.get(field));
        }
    }

    return note;
}

From source file:org.restheart.handlers.collection.PatchCollectionHandler.java

License:Open Source License

/**
 *
 * @param exchange/*from  ww  w  .  ja v  a 2  s . c  om*/
 * @param context
 * @throws Exception
 */
@Override
public void handleRequest(HttpServerExchange exchange, RequestContext context) throws Exception {
    if (context.getDBName().isEmpty()) {
        ResponseHelper.endExchangeWithMessage(exchange, HttpStatus.SC_NOT_ACCEPTABLE,
                "wrong request, db name cannot be empty");
        return;
    }

    if (context.getCollectionName().isEmpty() || context.getCollectionName().startsWith("_")) {
        ResponseHelper.endExchangeWithMessage(exchange, HttpStatus.SC_NOT_ACCEPTABLE,
                "wrong request, collection name cannot be empty or start with _");
        return;
    }

    DBObject content = context.getContent();

    if (content == null) {
        ResponseHelper.endExchangeWithMessage(exchange, HttpStatus.SC_NOT_ACCEPTABLE, "no data provided");
        return;
    }

    // cannot PATCH with an array
    if (content instanceof BasicDBList) {
        ResponseHelper.endExchangeWithMessage(exchange, HttpStatus.SC_NOT_ACCEPTABLE,
                "data cannot be an array");
        return;
    }

    // check RELS metadata
    if (content.containsField(Relationship.RELATIONSHIPS_ELEMENT_NAME)) {
        try {
            Relationship.getFromJson(content);
        } catch (InvalidMetadataException ex) {
            ResponseHelper.endExchangeWithMessage(exchange, HttpStatus.SC_NOT_ACCEPTABLE,
                    "wrong relationships definition. " + ex.getMessage(), ex);
            return;
        }
    }

    // check RT metadata
    if (content.containsField(RepresentationTransformer.RTS_ELEMENT_NAME)) {
        try {
            RepresentationTransformer.getFromJson(content);
        } catch (InvalidMetadataException ex) {
            ResponseHelper.endExchangeWithMessage(exchange, HttpStatus.SC_NOT_ACCEPTABLE,
                    "wrong representation transformer definition. " + ex.getMessage(), ex);
            return;
        }
    }

    // check SC metadata
    if (content.containsField(RequestChecker.SCS_ELEMENT_NAME)) {
        try {
            RequestChecker.getFromJson(content);
        } catch (InvalidMetadataException ex) {
            ResponseHelper.endExchangeWithMessage(exchange, HttpStatus.SC_NOT_ACCEPTABLE,
                    "wrong schema checker definition. " + ex.getMessage(), ex);
            return;
        }
    }

    ObjectId etag = RequestHelper.getWriteEtag(exchange);

    if (etag == null) {
        ResponseHelper.endExchange(exchange, HttpStatus.SC_CONFLICT);
        return;
    }

    int httpCode = getDatabase().upsertCollection(context.getDBName(), context.getCollectionName(), content,
            etag, true, true);

    // send the warnings if any (and in case no_content change the return code to ok
    if (context.getWarnings() != null && !context.getWarnings().isEmpty()) {
        sendWarnings(httpCode, exchange, context);
    } else {
        exchange.setResponseCode(httpCode);
    }

    if (httpCode == HttpStatus.SC_CREATED || httpCode == HttpStatus.SC_OK) {
        content.put("_etag", etag);
        ResponseHelper.injectEtagHeader(exchange, content);
    }

    exchange.endExchange();

    LocalCachesSingleton.getInstance().invalidateCollection(context.getDBName(), context.getCollectionName());
}

From source file:org.restheart.handlers.collection.PutCollectionHandler.java

License:Open Source License

/**
 *
 * @param exchange/*  w w  w .  j a v a 2 s .  c o  m*/
 * @param context
 * @throws Exception
 */
@Override
public void handleRequest(HttpServerExchange exchange, RequestContext context) throws Exception {
    if (context.getCollectionName().isEmpty() || context.getCollectionName().startsWith(UNDERSCORE)) {
        ResponseHelper.endExchangeWithMessage(exchange, HttpStatus.SC_NOT_ACCEPTABLE,
                "wrong request, collection name cannot be empty or start with '_'");
        return;
    }

    DBObject content = context.getContent();

    if (content == null) {
        content = new BasicDBObject();
    }

    // cannot PUT an array
    if (content instanceof BasicDBList) {
        ResponseHelper.endExchangeWithMessage(exchange, HttpStatus.SC_NOT_ACCEPTABLE,
                "data cannot be an array");
        return;
    }

    // check RELS metadata
    if (content.containsField(Relationship.RELATIONSHIPS_ELEMENT_NAME)) {
        try {
            Relationship.getFromJson(content);
        } catch (InvalidMetadataException ex) {
            ResponseHelper.endExchangeWithMessage(exchange, HttpStatus.SC_NOT_ACCEPTABLE,
                    "wrong relationships definition. " + ex.getMessage(), ex);
            return;
        }
    }

    // check RT metadata
    if (content.containsField(RepresentationTransformer.RTS_ELEMENT_NAME)) {
        try {
            RepresentationTransformer.getFromJson(content);
        } catch (InvalidMetadataException ex) {
            ResponseHelper.endExchangeWithMessage(exchange, HttpStatus.SC_NOT_ACCEPTABLE,
                    "wrong representation transformer definition. " + ex.getMessage(), ex);
            return;
        }
    }

    // check SC metadata
    if (content.containsField(RequestChecker.SCS_ELEMENT_NAME)) {
        try {
            RequestChecker.getFromJson(content);
        } catch (InvalidMetadataException ex) {
            ResponseHelper.endExchangeWithMessage(exchange, HttpStatus.SC_NOT_ACCEPTABLE,
                    "wrong schema checker definition. " + ex.getMessage(), ex);
            return;
        }
    }

    ObjectId etag = RequestHelper.getWriteEtag(exchange);
    boolean updating = context.getCollectionProps() != null;

    int httpCode = getDatabase().upsertCollection(context.getDBName(), context.getCollectionName(), content,
            etag, updating, false);

    // send the warnings if any (and in case no_content change the return code to ok
    if (context.getWarnings() != null && !context.getWarnings().isEmpty()) {
        sendWarnings(httpCode, exchange, context);
    } else {
        exchange.setResponseCode(httpCode);
    }

    if (httpCode == HttpStatus.SC_CREATED || httpCode == HttpStatus.SC_OK) {
        content.put("_etag", etag);
        ResponseHelper.injectEtagHeader(exchange, content);
    }

    exchange.endExchange();
    LocalCachesSingleton.getInstance().invalidateCollection(context.getDBName(), context.getCollectionName());
}

From source file:org.restheart.handlers.database.PatchDBHandler.java

License:Open Source License

/**
 * partial update db properties//from  www.j ava 2  s.c  om
 *
 * @param exchange
 * @param context
 * @throws Exception
 */
@Override
public void handleRequest(HttpServerExchange exchange, RequestContext context) throws Exception {
    if (context.getDBName().isEmpty() || context.getDBName().startsWith("_")) {
        ResponseHelper.endExchangeWithMessage(exchange, HttpStatus.SC_NOT_ACCEPTABLE,
                "wrong request, db name cannot be empty or start with _");
        return;
    }

    DBObject content = context.getContent();

    if (content == null) {
        ResponseHelper.endExchangeWithMessage(exchange, HttpStatus.SC_NOT_ACCEPTABLE, "data is empty");
        return;
    }

    // cannot PATCH an array
    if (content instanceof BasicDBList) {
        ResponseHelper.endExchangeWithMessage(exchange, HttpStatus.SC_NOT_ACCEPTABLE,
                "data cannot be an array");
        return;
    }

    // check RTL metadata
    if (content.containsField(RepresentationTransformer.RTS_ELEMENT_NAME)) {
        try {
            RepresentationTransformer.getFromJson(content);
        } catch (InvalidMetadataException ex) {
            ResponseHelper.endExchangeWithMessage(exchange, HttpStatus.SC_NOT_ACCEPTABLE,
                    "wrong representation transform logic definition. " + ex.getMessage(), ex);
            return;
        }
    }

    ObjectId etag = RequestHelper.getWriteEtag(exchange);

    if (etag == null) {
        ResponseHelper.endExchange(exchange, HttpStatus.SC_CONFLICT);
        return;
    }

    int httpCode = getDatabase().upsertDB(context.getDBName(), content, etag, true);

    // send the warnings if any (and in case no_content change the return code to ok
    if (context.getWarnings() != null && !context.getWarnings().isEmpty()) {
        sendWarnings(httpCode, exchange, context);
    } else {
        exchange.setResponseCode(httpCode);
    }

    if (httpCode == HttpStatus.SC_CREATED || httpCode == HttpStatus.SC_OK) {
        ResponseHelper.injectEtagHeader(exchange, content);
    }

    exchange.endExchange();

    LocalCachesSingleton.getInstance().invalidateDb(context.getDBName());
}

From source file:org.restheart.handlers.database.PutDBHandler.java

License:Open Source License

/**
 *
 * @param exchange//from  www.j a va 2 s .  c o m
 * @param context
 * @throws Exception
 */
@Override
public void handleRequest(HttpServerExchange exchange, RequestContext context) throws Exception {
    if (context.getDBName().isEmpty() || context.getDBName().startsWith("_")) {
        ResponseHelper.endExchangeWithMessage(exchange, HttpStatus.SC_NOT_ACCEPTABLE,
                "db name cannot be empty or start with _");
        return;
    }

    DBObject content = context.getContent();

    if (content == null) {
        content = new BasicDBObject();
    }

    // cannot PUT an array
    if (content instanceof BasicDBList) {
        ResponseHelper.endExchangeWithMessage(exchange, HttpStatus.SC_NOT_ACCEPTABLE,
                "data cannot be an array");
        return;
    }

    // check RTL metadata
    if (content.containsField(RepresentationTransformer.RTS_ELEMENT_NAME)) {
        try {
            RepresentationTransformer.getFromJson(content);
        } catch (InvalidMetadataException ex) {
            ResponseHelper.endExchangeWithMessage(exchange, HttpStatus.SC_NOT_ACCEPTABLE,
                    "wrong representation transform logic definition. " + ex.getMessage(), ex);
            return;
        }
    }

    ObjectId etag = RequestHelper.getWriteEtag(exchange);

    int httpCode = getDatabase().upsertDB(context.getDBName(), content, etag, false);

    // send the warnings if any (and in case no_content change the return code to ok
    if (context.getWarnings() != null && !context.getWarnings().isEmpty()) {
        sendWarnings(httpCode, exchange, context);
    } else {
        exchange.setResponseCode(httpCode);
    }

    if (httpCode == HttpStatus.SC_CREATED || httpCode == HttpStatus.SC_OK) {
        content.put("_etag", etag);
        ResponseHelper.injectEtagHeader(exchange, content);
    }

    exchange.endExchange();

    LocalCachesSingleton.getInstance().invalidateDb(context.getDBName());
}

From source file:org.restheart.handlers.document.DocumentRepresentationFactory.java

License:Open Source License

private static boolean isBinaryFile(DBObject data) {
    return data.containsField("filename") && data.containsField("chunkSize");
}

From source file:org.sipfoundry.sipxconfig.commserver.imdb.AbstractDataSetGenerator.java

License:Open Source License

protected void removeField(DBObject top, String field) {
    if (top.containsField(field)) {
        top.removeField(field);
    }
}

From source file:org.slc.sli.dal.repository.MongoEntityRepository.java

License:Apache License

private Query addEmbededFields(Query query, Set<String> embededFields) {
    if (query == null) {
        return null;
    }//from   w w w .  j  a v  a  2 s.c  om
    DBObject fieldObjects = query.getFieldsObject();
    if (fieldObjects != null) {
        for (String embededField : embededFields) {
            if (!fieldObjects.containsField(embededField)) {
                fieldObjects.put(embededField, 1);
            }
        }
    }
    return query;
}

From source file:org.springframework.data.document.mongodb.convert.MappingMongoConverter.java

License:Apache License

private <S extends Object> S read(final MongoPersistentEntity<S> entity, final DBObject dbo) {

    final StandardEvaluationContext spelCtx = new StandardEvaluationContext();
    if (null != applicationContext) {
        spelCtx.setBeanResolver(new BeanFactoryResolver(applicationContext));
    }//from w w  w.jav a  2  s. c  om
    if (!(dbo instanceof BasicDBList)) {
        String[] keySet = dbo.keySet().toArray(new String[] {});
        for (String key : keySet) {
            spelCtx.setVariable(key, dbo.get(key));
        }
    }

    final List<String> ctorParamNames = new ArrayList<String>();
    final MongoPersistentProperty idProperty = entity.getIdProperty();
    final S instance = constructInstance(entity, new PreferredConstructor.ParameterValueProvider() {
        @SuppressWarnings("unchecked")
        public <T> T getParameterValue(PreferredConstructor.Parameter<T> parameter) {
            String name = parameter.getName();
            TypeInformation<T> type = parameter.getType();
            Class<T> rawType = parameter.getRawType();
            String key = idProperty == null ? name
                    : idProperty.getName().equals(name) ? idProperty.getKey() : name;
            Object obj = dbo.get(key);

            ctorParamNames.add(name);
            if (obj instanceof DBRef) {
                return read(type, ((DBRef) obj).fetch());
            } else if (obj instanceof BasicDBList) {
                BasicDBList objAsDbList = (BasicDBList) obj;
                List<?> l = unwrapList(objAsDbList, type);
                return conversionService.convert(l, rawType);
            } else if (obj instanceof DBObject) {
                return read(type, ((DBObject) obj));
            } else if (null != obj && obj.getClass().isAssignableFrom(rawType)) {
                return (T) obj;
            } else if (null != obj) {
                return conversionService.convert(obj, rawType);
            }

            return null;
        }
    }, spelCtx);

    // Set properties not already set in the constructor
    entity.doWithProperties(new PropertyHandler<MongoPersistentProperty>() {
        public void doWithPersistentProperty(MongoPersistentProperty prop) {

            boolean isConstructorProperty = ctorParamNames.contains(prop.getName());
            boolean hasValueForProperty = dbo.containsField(prop.getKey());

            if (!hasValueForProperty || isConstructorProperty) {
                return;
            }

            Object obj = getValueInternal(prop, dbo, spelCtx, prop.getSpelExpression());
            try {
                setProperty(instance, prop, obj, useFieldAccessOnly);
            } catch (IllegalAccessException e) {
                throw new MappingException(e.getMessage(), e);
            } catch (InvocationTargetException e) {
                throw new MappingException(e.getMessage(), e);
            }
        }
    });

    // Handle associations
    entity.doWithAssociations(new AssociationHandler<MongoPersistentProperty>() {
        public void doWithAssociation(Association<MongoPersistentProperty> association) {
            MongoPersistentProperty inverseProp = association.getInverse();
            Object obj = getValueInternal(inverseProp, dbo, spelCtx, inverseProp.getSpelExpression());
            try {
                setProperty(instance, inverseProp, obj);
            } catch (IllegalAccessException e) {
                throw new MappingException(e.getMessage(), e);
            } catch (InvocationTargetException e) {
                throw new MappingException(e.getMessage(), e);
            }
        }
    });

    return instance;
}