Example usage for com.mongodb BasicDBObject get

List of usage examples for com.mongodb BasicDBObject get

Introduction

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

Prototype

public Object get(final String key) 

Source Link

Document

Gets a value from this object

Usage

From source file:com.ikanow.infinit.e.utility.MongoIndexerUtils.java

License:Apache License

private static BasicDBObject addChunkModifier(BasicDBObject minOrMax) {
    BasicDBObject modifier = new BasicDBObject();
    Iterator<String> indexFieldIt = minOrMax.keySet().iterator();
    while (indexFieldIt.hasNext()) {
        String indexField = indexFieldIt.next();

        Object fieldObj = minOrMax.get(indexField);
        if ((null != fieldObj) && // else it's a min/max so can just ignore
                (fieldObj instanceof String) || (fieldObj instanceof ObjectId)
                || (fieldObj instanceof Number)) {
            modifier.put(indexField, fieldObj);
        }//ww  w.  ja  va  2s.  c o m
    }
    if (modifier.isEmpty())
        return null;

    return modifier;
}

From source file:com.ikanow.utility.GridFSRandomAccessFile.java

License:Open Source License

/** Move around in the file via relative offset
 * @see java.io.DataInput#skipBytes(int)
 *//*from  ww  w.j a v a  2  s . c o  m*/
@Override
public int skipBytes(int n) throws IOException {
    //TEST:System.out.println("skipBytes1: "+n);

    long oldPosInFile = _currPosInFile;
    _currPosInFile = _currPosInFile + n;
    if (_currPosInFile < 0) {
        _currPosInFile = 0;
    } else if (_currPosInFile > _fileSize) {
        _currPosInFile = _fileSize;
    }
    int newChunkNum = (int) (_currPosInFile / _chunkSize);

    if ((newChunkNum != _currChunkNum) || (null == _currChunkObj)) {
        _chunkQuery.put(_CHUNK_n_, newChunkNum);
        BasicDBObject newChunk = (BasicDBObject) _chunkCollection.findOne(_chunkQuery);
        if (null == newChunk) {
            throw new IOException("Unknown I/O exception");
        }
        //TEST:System.out.println("skipBytes2: "+n+" currChunkNum="+_currChunkNum+"->"+newChunkNum+" posInFile="+_currPosInFile);

        _currChunkObj = newChunk;
        _currChunkNum = newChunkNum;
        _currData = (byte[]) newChunk.get(_CHUNK_data_);
        _currChunkSize = (_lastChunkNum == 0) ? _finalChunkSize : _chunkSize;
    }
    _currPosInChunk = (int) (_currPosInFile % _chunkSize);
    return (int) (_currPosInFile - oldPosInFile);

}

From source file:com.images3.data.impl.MongoDBObjectMapper.java

License:Apache License

public ImagePlantOS mapToImagePlantOS(BasicDBObject source) {
    int maximumImageSize = MaximumImageSize.UNLIMITED;
    if (source.containsValue("maximumImageSize")) {
        maximumImageSize = source.getInt("maximumImageSize");
    }/*from  www .j  a  v a2s. c o m*/
    return new ImagePlantOS(source.getString("id"), source.getString("name"),
            new Date(source.getLong("creationTime")), mapToAmazonS3Bucket((BasicDBObject) source.get("bucket")),
            source.getString("masterTemplateName"), source.getLong("numberOfTemplates"), maximumImageSize);
}

From source file:com.images3.data.impl.MongoDBObjectMapper.java

License:Apache License

public TemplateOS mapToTemplateOS(BasicDBObject source) {
    return new TemplateOS(new TemplateIdentity(source.getString("imagePlantId"), source.getString("name")),
            source.getBoolean("isArchived"), source.getBoolean("isRemovable"),
            mapToResizingConfig((BasicDBObject) source.get("resizingConfig")));
}

From source file:com.images3.data.impl.MongoDBObjectMapper.java

License:Apache License

public ImageOS mapToImageOS(BasicDBObject source) {
    return new ImageOS(new ImageIdentity(source.getString("imagePlantId"), source.getString("id")),
            new Date(source.getLong("dateTime")), mapToImageMetadata((BasicDBObject) source.get("metadata")),
            mapToImageVersion((BasicDBObject) source.get("version")));
}

From source file:com.images3.data.impl.MongoDBObjectMapper.java

License:Apache License

public ImageMetadata mapToImageMetadata(BasicDBObject source) {
    return new ImageMetadata(mapToImageDimension((BasicDBObject) source.get("dimension")),
            ImageFormat.valueOf(source.getString("format")), source.getLong("size"));
}

From source file:com.imaginea.mongodb.requestdispatchers.Graphs.java

License:Apache License

/**
 * Process <opcounters> query request made after each second by Front end
 * /*from   w  w  w  . j  a va  2 s  .c o m*/
 * @param db
 *            : Db Name to egt Server Stats <admin>
 * @return Server stats of <opcounters> key
 * @throws IOException
 * @throws JSONException
 */
private JSONArray processQuery(DB db) throws IOException, JSONException {

    CommandResult cr = db.command("serverStatus");
    BasicDBObject obj = (BasicDBObject) cr.get("opcounters");
    int currentValue;
    JSONObject temp = new JSONObject();

    num = num + jump;
    temp.put("TimeStamp", num);
    currentValue = (Integer) obj.get("query");
    temp.put("QueryValue", currentValue - lastNoOfQueries);
    lastNoOfQueries = currentValue;
    currentValue = (Integer) obj.get("insert");
    temp.put("InsertValue", currentValue - lastNoOfInserts);
    lastNoOfInserts = currentValue;
    currentValue = (Integer) obj.get("update");
    temp.put("UpdateValue", currentValue - lastNoOfUpdates);
    lastNoOfUpdates = currentValue;
    currentValue = (Integer) obj.get("delete");
    temp.put("DeleteValue", currentValue - lastNoOfDeletes);
    lastNoOfDeletes = currentValue;

    if (array.length() == maxLen) {
        JSONArray tempArray = new JSONArray();
        for (int i = 1; i < maxLen; i++) {
            tempArray.put(array.get(i));
        }
        array = tempArray;
    }
    array.put(temp);
    return array;
}

From source file:com.imaginea.mongodb.requestdispatchers.Graphs.java

License:Apache License

/**
 * /* w w w. j  a  v a  2 s  .co m*/
 * Initialize by previous <opcounter> value.
 * 
 * @param db
 *            : Name of Database
 * @return : Status of Initialization
 * @throws RuntimeException
 */

private JSONObject processInitiate(DB db) throws RuntimeException, JSONException {

    JSONObject respObj = new JSONObject();
    array = new JSONArray();
    num = 0;
    try {

        CommandResult cr = db.command("serverStatus");
        BasicDBObject obj = (BasicDBObject) cr.get("opcounters");
        lastNoOfQueries = (Integer) obj.get("query");
        lastNoOfInserts = (Integer) obj.get("insert");
        lastNoOfUpdates = (Integer) obj.get("update");
        lastNoOfDeletes = (Integer) obj.get("delete");

        respObj.put("result", "Initiated");
    } catch (Exception e) {
        // Invalid User
        JSONObject error = new JSONObject();
        error.put("message", e.getMessage());
        error.put("code", ErrorCodes.ERROR_INITIATING_GRAPH);

        respObj.put("error", error);
        logger.info(respObj);
    }
    return respObj;
}

From source file:com.impetus.client.mongodb.query.gis.NearQueryImpl.java

License:Apache License

@Override
public Object createGeospatialQuery(String geolocationColumnName, Object shape, Object query) {
    BasicDBObject q = (BasicDBObject) query;

    if (q == null)
        q = new BasicDBObject();

    // Set point in query which is involved in near search
    if (shape != null && shape.getClass().isAssignableFrom(Point.class)) {
        Point point = (Point) shape;
        BasicDBObject filter = (BasicDBObject) q.get(geolocationColumnName);

        if (filter == null)
            filter = new BasicDBObject();

        if (point.getSurfaceType().equals(SurfaceType.SPHERICAL)) {
            filter.put("$nearSphere", new double[] { point.getX(), point.getY() });
        } else {//ww  w.  j av a2  s . c om
            filter.put("$near", new double[] { point.getX(), point.getY() });
        }

        q.put(geolocationColumnName, filter);
    }

    // Set maximum distance from the given point
    if (shape != null && (shape.getClass().isAssignableFrom(Double.class)
            || shape.getClass().isAssignableFrom(double.class))) {
        Double maxDistance = (Double) shape;

        BasicDBObject filter = (BasicDBObject) q.get(geolocationColumnName);

        if (filter == null)
            filter = new BasicDBObject();

        filter.put("$maxDistance", maxDistance);

        q.put(geolocationColumnName, filter);
    }

    return q;
}

From source file:com.impetus.client.mongodb.query.MongoDBQuery.java

License:Apache License

/**
 * Creates MongoDB Query object from filterClauseQueue.
 * // www.  ja  v  a2 s. c  o m
 * @param m
 *            the m
 * @param filterClauseQueue
 *            the filter clause queue
 * @return the basic db object
 */
public BasicDBObject createSubMongoQuery(EntityMetadata m, Queue filterClauseQueue) {
    BasicDBObject query = new BasicDBObject();
    BasicDBObject compositeColumns = new BasicDBObject();

    MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata()
            .getMetamodel(m.getPersistenceUnit());

    AbstractManagedType managedType = (AbstractManagedType) metaModel.entity(m.getEntityClazz());

    for (Object object : filterClauseQueue) {
        boolean isCompositeColumn = false;

        boolean isSubCondition = false;

        if (object instanceof FilterClause) {
            FilterClause filter = (FilterClause) object;
            String property = filter.getProperty();
            String condition = filter.getCondition();
            Object value = filter.getValue().get(0);

            // value is string but field.getType is different, then get
            // value using

            Field f = null;

            // if alias is still present .. means it is an enclosing
            // document search.

            if (managedType.hasLobAttribute()) {
                EntityType entity = metaModel.entity(m.getEntityClazz());
                String fieldName = m.getFieldName(property);

                f = (Field) entity.getAttribute(fieldName).getJavaMember();

                if (value.getClass().isAssignableFrom(String.class) && f != null
                        && !f.getType().equals(value.getClass())) {
                    value = PropertyAccessorFactory.getPropertyAccessor(f).fromString(f.getType().getClass(),
                            value.toString());
                }
                value = MongoDBUtils.populateValue(value, value.getClass());

                property = "metadata." + property;
            } else {
                if (((AbstractAttribute) m.getIdAttribute()).getJPAColumnName().equalsIgnoreCase(property)) {
                    property = "_id";
                    f = (Field) m.getIdAttribute().getJavaMember();
                    if (metaModel.isEmbeddable(m.getIdAttribute().getBindableJavaType())
                            && value.getClass().isAssignableFrom(f.getType())) {
                        EmbeddableType compoundKey = metaModel
                                .embeddable(m.getIdAttribute().getBindableJavaType());
                        compositeColumns = MongoDBUtils.getCompoundKeyColumns(m, value, compoundKey);
                        isCompositeColumn = true;
                        continue;
                    }
                } else if (metaModel.isEmbeddable(m.getIdAttribute().getBindableJavaType())
                        && StringUtils.contains(property, '.')) {
                    // Means it is a case of composite column.
                    property = property.substring(property.indexOf(".") + 1);
                    isCompositeColumn = true;
                } /*
                   * if a composite key. "." assuming "." is part of
                   * property in case of embeddable only
                   */
                else if (StringUtils.contains(property, '.')) {
                    EntityType entity = metaModel.entity(m.getEntityClazz());
                    StringTokenizer tokenizer = new StringTokenizer(property, ".");
                    String embeddedAttributeAsStr = tokenizer.nextToken();
                    String embeddableAttributeAsStr = tokenizer.nextToken();
                    Attribute embeddedAttribute = entity.getAttribute(embeddedAttributeAsStr);
                    EmbeddableType embeddableEntity = metaModel
                            .embeddable(((AbstractAttribute) embeddedAttribute).getBindableJavaType());
                    f = (Field) embeddableEntity.getAttribute(embeddableAttributeAsStr).getJavaMember();
                    property = ((AbstractAttribute) embeddedAttribute).getJPAColumnName() + "."
                            + ((AbstractAttribute) embeddableEntity.getAttribute(embeddableAttributeAsStr))
                                    .getJPAColumnName();
                } else {
                    EntityType entity = metaModel.entity(m.getEntityClazz());
                    String discriminatorColumn = ((AbstractManagedType) entity).getDiscriminatorColumn();

                    if (!property.equals(discriminatorColumn)) {
                        String fieldName = m.getFieldName(property);
                        f = (Field) entity.getAttribute(fieldName).getJavaMember();
                    }
                }
                if (value.getClass().isAssignableFrom(String.class) && f != null
                        && !f.getType().equals(value.getClass())) {
                    value = PropertyAccessorFactory.getPropertyAccessor(f).fromString(f.getType().getClass(),
                            value.toString());
                }
                value = MongoDBUtils.populateValue(value, value.getClass());

            }

            // Property, if doesn't exist in entity, may be there in a
            // document embedded within it, so we have to check that
            // TODO: Query should actually be in a format
            // documentName.embeddedDocumentName.column, remove below if
            // block once this is decided

            // Query could be geospatial in nature
            if (f != null && f.getType().equals(Point.class)) {
                GeospatialQuery geospatialQueryimpl = GeospatialQueryFactory
                        .getGeospatialQueryImplementor(condition, value);
                query = (BasicDBObject) geospatialQueryimpl.createGeospatialQuery(property, value, query);

            } else {

                if (isCompositeColumn) {
                    EmbeddableType embeddableType = metaModel
                            .embeddable(m.getIdAttribute().getBindableJavaType());
                    AbstractAttribute attribute = (AbstractAttribute) embeddableType.getAttribute(property);

                    property = new StringBuffer("_id.").append(attribute.getJPAColumnName()).toString();
                }
                if (condition.equals("=")) {
                    query.append(property, value);

                } else if (condition.equalsIgnoreCase("like")) {

                    if (query.containsField(property)) {
                        query.get(property);
                        query.put(property, ((BasicDBObject) query.get(property)).append("$regex",
                                createLikeRegex((String) value)));
                    } else {
                        query.append(property, new BasicDBObject("$regex", createLikeRegex((String) value)));
                    }

                } else if (condition.equalsIgnoreCase(">")) {

                    if (query.containsField(property)) {
                        query.get(property);
                        query.put(property, ((BasicDBObject) query.get(property)).append("$gt", value));
                    } else {
                        query.append(property, new BasicDBObject("$gt", value));
                    }
                } else if (condition.equalsIgnoreCase(">=")) {

                    if (query.containsField(property))

                    {
                        query.get(property);
                        query.put(property, ((BasicDBObject) query.get(property)).append("$gte", value));
                    } else {
                        query.append(property, new BasicDBObject("$gte", value));
                    }

                } else if (condition.equalsIgnoreCase("<")) {

                    if (query.containsField(property)) {
                        query.get(property);
                        query.put(property, ((BasicDBObject) query.get(property)).append("$lt", value));
                    } else {
                        query.append(property, new BasicDBObject("$lt", value));
                    }

                } else if (condition.equalsIgnoreCase("<=")) {

                    if (query.containsField(property)) {
                        query.get(property);
                        query.put(property, ((BasicDBObject) query.get(property)).append("$lte", value));
                    } else {
                        query.append(property, new BasicDBObject("$lte", value));
                    }

                } else if (condition.equalsIgnoreCase("in")) {

                    if (query.containsField(property)) {
                        query.get(property);
                        query.put(property,
                                ((BasicDBObject) query.get(property)).append("$in", filter.getValue()));
                    } else {
                        query.append(property, new BasicDBObject("$in", filter.getValue()));
                    }

                } else if (condition.equalsIgnoreCase("not in")) {

                    if (query.containsField(property)) {
                        query.get(property);
                        query.put(property,
                                ((BasicDBObject) query.get(property)).append("$nin", filter.getValue()));
                    } else {
                        query.append(property, new BasicDBObject("$nin", filter.getValue()));
                    }

                } else if (condition.equalsIgnoreCase("<>")) {

                    if (query.containsField(property)) {
                        query.get(property);
                        query.put(property, ((BasicDBObject) query.get(property)).append("$ne", value));
                    } else {
                        query.append(property, new BasicDBObject("$ne", value));
                    }

                }
            }

            // TODO: Add support for other operators like >, <, >=, <=,
            // order by asc/ desc, limit, skip, count etc
        }
    }
    if (!compositeColumns.isEmpty()) {
        query.append("_id", compositeColumns);
    }

    return query;
}