Example usage for com.mongodb BasicDBObjectBuilder get

List of usage examples for com.mongodb BasicDBObjectBuilder get

Introduction

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

Prototype

public DBObject get() 

Source Link

Document

Gets the top level document.

Usage

From source file:com.gigaspaces.persistency.MongoClientConnector.java

License:Open Source License

public void introduceType(SpaceTypeDescriptor typeDescriptor) {

    DBCollection m = getConnection().getCollection(METADATA_COLLECTION_NAME);

    BasicDBObjectBuilder builder = BasicDBObjectBuilder.start().add(Constants.ID_PROPERTY,
            typeDescriptor.getTypeName());
    try {/*  w  ww .  j a v  a2s.  co m*/
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ObjectOutputStream out = new ObjectOutputStream(bos);
        IOUtils.writeObject(out,
                SpaceTypeDescriptorVersionedSerializationUtils.toSerializableForm(typeDescriptor));

        builder.add(TYPE_DESCRIPTOR_FIELD_NAME, bos.toByteArray());

        WriteResult wr = m.save(builder.get());

        if (logger.isTraceEnabled())
            logger.trace(wr);

        indexBuilder.ensureIndexes(typeDescriptor);

    } catch (IOException e) {
        logger.error(e);

        throw new SpaceMongoException(
                "error occurs while serialize and save type descriptor: " + typeDescriptor, e);
    }
}

From source file:com.gigaspaces.persistency.MongoClientConnector.java

License:Open Source License

private static DBObject normalize(DBObject obj) {
    BasicDBObjectBuilder builder = BasicDBObjectBuilder.start();

    Iterator<String> iterator = obj.keySet().iterator();
    builder.push("$set");
    while (iterator.hasNext()) {

        String key = iterator.next();

        if (Constants.ID_PROPERTY.equals(key))
            continue;

        Object value = obj.get(key);

        if (value == null)
            continue;

        builder.add(key, value);//from  w  ww  . jav  a 2s  .  c  om
    }

    return builder.get();
}

From source file:com.gigaspaces.persistency.MongoSpaceDataSource.java

License:Open Source License

@Override
public Object getById(DataSourceIdQuery idQuery) {

    if (logger.isDebugEnabled())
        logger.debug("MongoSpaceDataSource.getById(" + idQuery + ")");

    SpaceDocumentMapper<DBObject> mapper = new DefaultSpaceDocumentMapper(idQuery.getTypeDescriptor());

    BasicDBObjectBuilder documentBuilder = BasicDBObjectBuilder.start().add(Constants.ID_PROPERTY,
            mapper.toObject(idQuery.getId()));

    DBCollection mongoCollection = mongoClient.getCollection(idQuery.getTypeDescriptor().getTypeName());

    DBObject result = mongoCollection.findOne(documentBuilder.get());

    return mapper.toDocument(result);

}

From source file:com.github.nlloyd.hornofmongo.MongoScope.java

License:Open Source License

public static Object listFiles(Context cx, Scriptable thisObj, Object[] args, Function funObj) {
    File path = null;//w w  w  .  j  a  v a 2  s. co  m
    if (args.length == 0)
        path = ((MongoScope) thisObj).getCwd();
    else if (args.length > 1)
        Context.throwAsScriptRuntimeEx(new MongoScriptException("need to specify 1 argument to listFiles"));
    else {
        try {
            path = resolveFilePath((MongoScope) thisObj, Context.toString(args[0]));
        } catch (IOException e) {
            Context.throwAsScriptRuntimeEx(new MongoScriptException("listFiles: " + e.getMessage()));
        }
    }

    // mongo only checks if the path exists, so we will do the same here
    if (!path.exists())
        Context.throwAsScriptRuntimeEx(
                new MongoScriptException("listFiles: no such directory: " + path.getAbsolutePath()));
    if (!path.isDirectory())
        Context.throwAsScriptRuntimeEx(
                new MongoScriptException("listFiles: not a directory: " + path.getAbsolutePath()));

    List<DBObject> files = new ArrayList<DBObject>();
    for (File file : path.listFiles()) {
        BasicDBObjectBuilder fileObj = new BasicDBObjectBuilder();
        fileObj.append("name", file.getPath()).append("isDirectory", file.isDirectory());
        if (!file.isDirectory())
            fileObj.append("size", file.length());
        files.add(fileObj.get());
    }

    Object jsResult = BSONizer.convertBSONtoJS((MongoScope) thisObj, files);

    return jsResult;
}

From source file:com.github.sakserv.storm.bolt.SimpleMongoBolt.java

License:Apache License

@Override
public DBObject getDBObjectForInput(Tuple input) {
    BasicDBObjectBuilder dbObjectBuilder = new BasicDBObjectBuilder();

    for (String field : input.getFields()) {
        Object value = input.getValueByField(field);
        if (isValidDBObjectField(value)) {
            dbObjectBuilder.append(field, value);
        }/* ww  w  .  j a va 2 s  . c o m*/
    }

    return dbObjectBuilder.get();
}

From source file:com.ibm.ws.lars.rest.PersistenceBean.java

License:Apache License

/** {@inheritDoc} */
@Override//from  w  w w. j a  va  2  s.com
public void initialize() {
    // Make sure the fields we want to query are indexed
    DBCollection assets = db.getCollection(ASSETS_COLLECTION);
    DBCollection attachments = db.getCollection(ATTACHMENTS_COLLECTION);

    // Add text index
    BasicDBObjectBuilder textIndex = BasicDBObjectBuilder.start();
    for (String indexField : searchIndexFields) {
        textIndex.add(indexField, "text");
    }
    assets.ensureIndex(textIndex.get());

    // Add Attachment(assetId) index
    attachments.ensureIndex(new BasicDBObject("assetId", 1));
}

From source file:com.impetus.client.mongodb.DocumentObjectMapper.java

License:Apache License

/**
 * Extract entity field.//from  ww  w. j  a  v  a2 s . c  o m
 * 
 * @param entity
 *            the entity
 * @param dbObj
 *            the db obj
 * @param column
 *            the column
 * @throws PropertyAccessException
 *             the property access exception
 */
static void extractFieldValue(Object entity, DBObject dbObj, Attribute column) throws PropertyAccessException {
    try {
        Object valueObject = PropertyAccessorHelper.getObject(entity, (Field) column.getJavaMember());

        if (valueObject != null) {
            Class javaType = column.getJavaType();
            switch (AttributeType.getType(javaType)) {
            case MAP:
                Map mapObj = (Map) valueObject;
                // BasicDBObjectBuilder builder =
                // BasicDBObjectBuilder.start(mapObj);
                BasicDBObjectBuilder b = new BasicDBObjectBuilder();
                Iterator i = mapObj.entrySet().iterator();
                while (i.hasNext()) {
                    Map.Entry entry = (Map.Entry) i.next();
                    b.add(entry.getKey().toString(),
                            MongoDBUtils.populateValue(entry.getValue(), entry.getValue().getClass()));
                }
                dbObj.put(((AbstractAttribute) column).getJPAColumnName(), b.get());
                break;
            case SET:
            case LIST:
                Collection collection = (Collection) valueObject;
                BasicDBList basicDBList = new BasicDBList();
                for (Object o : collection) {
                    basicDBList.add(o);
                }
                dbObj.put(((AbstractAttribute) column).getJPAColumnName(), basicDBList);
                break;
            case POINT:

                Point p = (Point) valueObject;
                double[] coordinate = new double[] { p.getX(), p.getY() };
                dbObj.put(((AbstractAttribute) column).getJPAColumnName(), coordinate);
                break;
            case ENUM:
            case PRIMITIVE:
                dbObj.put(((AbstractAttribute) column).getJPAColumnName(),
                        MongoDBUtils.populateValue(valueObject, javaType));
                break;
            }
        }
    } catch (PropertyAccessException paex) {
        log.error("Error while getting column {} value, caused by : .",
                ((AbstractAttribute) column).getJPAColumnName(), paex);
        throw new PersistenceException(paex);
    }
}

From source file:com.jjorgemoura.hangmanz.model.ZDHangmanGame.java

private DBObject createDBObject() {

    List lettersList = new ArrayList();

    BasicDBObjectBuilder docBuilder = BasicDBObjectBuilder.start();
    BasicDBObjectBuilder lettersDocBuilder;

    int theOrder = 1;
    for (Iterator<Integer> it = this.playsRecord.keySet().iterator(); it.hasNext();) {

        Integer i = it.next();//from  w ww  .  java2s  .  c o m
        ZDAlphabet x = this.playsRecord.get(i);

        lettersDocBuilder = BasicDBObjectBuilder.start();
        lettersDocBuilder.append("hm_letter", x.getLetter());
        lettersDocBuilder.append("hm_letter_order", theOrder);
        lettersList.add(lettersDocBuilder.get());
        theOrder++;
    }

    docBuilder.append("hm_uuid", this.uniqueUUID);
    docBuilder.append("hm_start_date", this.startDate.toString());
    docBuilder.append("hm_latest_date", this.latestDate.toString());
    docBuilder.append("hm_the_word", this.theWord.getName());
    docBuilder.append("hm_category", this.category.getName());
    docBuilder.append("hm_letters_played", lettersList);

    return docBuilder.get();
}

From source file:com.mingo.mongo.aggregation.AggregationUtils.java

License:Apache License

/**
 * Added condition for created field./*from ww  w. jav a  2 s .  c  o m*/
 *
 * @param builder    {@link BasicDBObjectBuilder}
 * @param field      field
 * @param parameters parameters
 */
public static void addBetweenCriteria(BasicDBObjectBuilder builder, String field,
        Map<String, String> parameters) {
    BasicDBObjectBuilder createdBuilder = start();
    Date startRange = parameters.containsKey(START_DATE) ? convertToDate(parameters.get(START_DATE)) : null;
    Date endRange = parameters.containsKey(END_DATE) ? addDays(convertToDate(parameters.get(END_DATE)), 1)
            : null;

    if (startRange != null) {
        createdBuilder.add(GT.getMongoName(), startRange);
    }
    if (endRange != null) {
        createdBuilder.add(LT.getMongoName(), endRange);
    }
    if (!createdBuilder.isEmpty()) {
        builder.add(field, createdBuilder.get());
    }
}

From source file:com.mobileman.kuravis.core.services.entity.impl.AbstractEntityServiceImpl.java

License:Apache License

@Override
public List<DBObject> findAll(String entityName, String projection, Pageable page) {
    if (page == null) {
        page = new PageRequest(0, Integer.MAX_VALUE);
    }//  ww w  .j  av  a 2 s .c  om

    DBCursor cursor = null;
    if (StringUtils.isEmpty(projection)) {
        cursor = getCollection(entityName).find(new BasicDBObject());
    } else {
        String[] properties = projection.split(",");
        BasicDBObjectBuilder projectionBuilder = BasicDBObjectBuilder.start();
        boolean idWanted = false;
        for (String property : properties) {
            property = property.trim();
            if (!StringUtils.isEmpty(property)) {
                if (property.equals(EntityUtils.ID)) {
                    idWanted = true;
                }

                projectionBuilder.add(property.trim(), true);
            }
        }

        if (idWanted == false) {
            projectionBuilder.append("_id", false);
        }

        cursor = getCollection(entityName).find(new BasicDBObject(), projectionBuilder.get())
                .sort(new BasicDBObject(projection, 1));
    }

    if (page.getSort() != null) {
        cursor = cursor.sort(createSort(page));
    } else if (projection != null) {
        cursor = cursor.sort(new BasicDBObject(projection, 1));
    }

    cursor = cursor.skip(page.getOffset()).limit(page.getPageSize());

    List<DBObject> result = cursor.toArray();
    return result;
}