Example usage for com.mongodb BasicDBObjectBuilder start

List of usage examples for com.mongodb BasicDBObjectBuilder start

Introduction

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

Prototype

public static BasicDBObjectBuilder start() 

Source Link

Document

Creates a builder intialized with an empty document.

Usage

From source file:org.obiba.magma.datasource.mongodb.MongoDBValueTable.java

License:Open Source License

/**
 * Drop the files from the {@link com.mongodb.gridfs.GridFS} for this table.
 *//* w  w w.ja va2s  .  com*/
private void dropFiles() {
    GridFS gridFS = getMongoDBDatasource().getMongoDBFactory().getGridFS();
    BasicDBObjectBuilder metaDataQuery = BasicDBObjectBuilder.start() //
            .add("metadata.datasource", getDatasource().getName()) //
            .add("metadata.table", getName());
    gridFS.remove(metaDataQuery.get());
}

From source file:org.obiba.magma.datasource.mongodb.MongoDBVariableValueSourceFactory.java

License:Open Source License

@Override
public Set<VariableValueSource> createSources() {
    ImmutableSet.Builder<VariableValueSource> builder = ImmutableSet.builder();
    try (DBCursor variableCursor = table.getVariablesCollection().find(new BasicDBObject())
            .sort(BasicDBObjectBuilder.start().add("_id", 1).get())) {
        while (variableCursor.hasNext()) {
            builder.add(new MongoDBVariableValueSource(table, variableCursor.next().get("name").toString()));
        }/*from w  w  w. j a  v a2s .  c  o  m*/
    }
    return builder.build();
}

From source file:org.opencb.opencga.storage.mongodb.alignment.CoverageMongoDBWriter.java

License:Apache License

private void secureInsert(DBObject query, DBObject object, String chromosome, int start, int size) {
    boolean documentExists = true;
    boolean fileExists = true;

    //Check if the document exists
    {/*from w  ww  .ja  v a2  s  .  co m*/
        QueryResult countId = collection.count(query);
        if (countId.getNumResults() == 1 && countId.getResultType().equals(Long.class.getCanonicalName())) {
            if ((Long) countId.getResult().get(0) < 1) {
                DBObject document = BasicDBObjectBuilder.start().append(FILES_FIELD, new BasicDBList())
                        .append(CHR_FIELD, chromosome).append(START_FIELD, start).append(SIZE_FIELD, size)
                        .get();
                document.putAll(query); //{_id:<chunkId>, files:[]}
                collection.insert(document, null); //Insert a document with empty files array.
                fileExists = false;
            }
        } else {
            logger.error(countId.getErrorMsg(), countId);
        }
    }

    if (documentExists) {
        //Check if the file exists
        BasicDBObject fileQuery = new BasicDBObject(FILES_FIELD + "." + FILE_ID_FIELD, fileId);
        fileQuery.putAll(query);
        QueryResult countFile = collection.count(fileQuery);
        if (countFile.getNumResults() == 1 && countFile.getResultType().equals(Long.class.getCanonicalName())) {
            if ((Long) countFile.getResult().get(0) < 1) {
                fileExists = false;
            }
        } else {
            logger.error(countFile.getErrorMsg(), countFile);
        }
    }

    if (fileExists) {
        BasicDBObject fileQuery = new BasicDBObject(FILES_FIELD + "." + FILE_ID_FIELD, fileId);
        fileQuery.putAll(query);

        BasicDBObject fileObject = new BasicDBObject();
        for (String key : object.keySet()) {
            fileObject.put(FILES_FIELD + ".$." + key, object.get(key));
        }
        //            DBObject update = new BasicDBObject("$set", new BasicDBObject(FILES_FIELD, fileObject));
        DBObject update = new BasicDBObject("$set", fileObject);

        //db.<collectionName>.update({_id:<chunkId>  , "files.id":<fileId>}, {$set:{"files.$.<objKey>":<objValue>}})
        collection.update(fileQuery, update, updateOptions);
    } else {
        BasicDBObject fileObject = new BasicDBObject(FILE_ID_FIELD, fileId);
        fileObject.putAll(object);
        DBObject update = new BasicDBObject("$addToSet", new BasicDBObject(FILES_FIELD, fileObject));

        //db.<collectionName>.update({_id:<chunkId>} , {$addToSet:{files:{id:<fileId>, <object>}}})
        collection.update(query, update, updateOptions);
    }
}

From source file:org.opencb.opencga.storage.mongodb.alignment.IndexedAlignmentDBAdaptor.java

License:Apache License

private QueryResult _getAllIntervalFrequencies(Region region, QueryOptions options) {
    long startTime = System.currentTimeMillis();
    MongoDBCollection collection = mongoDataStore.getCollection(CoverageMongoDBWriter.COVERAGE_COLLECTION_NAME);

    int size = region.getEnd() - region.getStart();
    String fileId = options.getString(QO_FILE_ID);
    //        boolean histogram = options.getBoolean(QO_HISTOGRAM, size < 2000);
    boolean histogram = true;
    int batchSize = histogram ? options.getInt(QO_INTERVAL_SIZE, 1000) : 1000;
    String batchName = MeanCoverage.sizeToNameConvert(batchSize);

    String coverageType;//from w  w  w  . ja v  a  2 s .  c o m
    ComplexTypeConverter complexTypeConverter;
    if (histogram) {
        complexTypeConverter = new DBObjectToMeanCoverageConverter();
        coverageType = CoverageMongoDBWriter.AVERAGE_FIELD;
    } else {
        complexTypeConverter = new DBObjectToRegionCoverageConverter();
        coverageType = CoverageMongoDBWriter.COVERAGE_FIELD;
    }
    List<String> regions = new LinkedList<>();

    for (int i = region.getStart() / batchSize; i <= (region.getEnd() - 1) / batchSize; i++) {
        regions.add(region.getChromosome() + "_" + i + "_" + batchName);
    }

    //db.alignment.find( { _id:{$in:regions}}, { files: {$elemMatch : {id:fileId} }, "files.cov":0 , "files.id":0 } )}
    DBObject query = new BasicDBObject(CoverageMongoDBWriter.ID_FIELD, new BasicDBObject("$in", regions));
    DBObject projection = BasicDBObjectBuilder.start()
            //                .append(CoverageMongoWriter.FILES_FIELD+"."+CoverageMongoWriter.FILE_ID_FIELD,fileId)
            .append(CoverageMongoDBWriter.FILES_FIELD,
                    new BasicDBObject("$elemMatch",
                            new BasicDBObject(CoverageMongoDBWriter.FILE_ID_FIELD, fileId)))
            .append(CoverageMongoDBWriter.FILES_FIELD + "." + coverageType, true)

            //.append(CoverageMongoWriter.FILES_FIELD+"."+DBObjectToRegionCoverageConverter.COVERAGE_FIELD, true)
            //.append(CoverageMongoWriter.FILES_FIELD+"."+DBObjectToMeanCoverageConverter.AVERAGE_FIELD, true)
            //.append(CoverageMongoWriter.FILES_FIELD+"."+CoverageMongoWriter.FILE_ID_FIELD, true)
            .get();

    System.out.println("db." + CoverageMongoDBWriter.COVERAGE_COLLECTION_NAME + ".find(" + query.toString()
            + ", " + projection.toString() + ")");

    QueryResult queryResult = collection.find(query, projection, complexTypeConverter, null);
    queryResult.setId(region.toString());
    queryResult.setTime((int) (System.currentTimeMillis() - startTime));
    return queryResult;
}

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

License:Open Source License

private static BasicDBObject noteToDbObject(Note note) {
    if (note == null) {
        return null;
    }/* www  .ja  v  a2s.co  m*/
    BasicDBObject noteDoc = (BasicDBObject) BasicDBObjectBuilder.start()
            .add(Note.Fields.noteId.getName(), note.getNoteId())
            .add(Note.Fields.noteText.getName(), note.getNoteText())
            .add(Note.Fields.clientDomain.getName(), note.getClientDomain()).get();

    User user = note.getCreatedByUser();
    if (user != null) {
        BasicDBObject userDoc = (BasicDBObject) BasicDBObjectBuilder.start().get();
        @SuppressWarnings("unchecked")
        Dictionary<String, Object> props = user.getProperties();
        if (props != null && !props.isEmpty()) {
            Enumeration<String> keys = props.keys();
            while (keys.hasMoreElements()) {
                String key = keys.nextElement();
                userDoc.append(key, props.get(key));
            }
        }
        noteDoc.append(Note.Fields.createdByUser.getName(), userDoc);
    }

    // look for custom fields
    for (String field : note.getAttributeNames()) {
        noteDoc.put(field, note.getAttribute(field));
    }

    return noteDoc;
}

From source file:org.seadpdt.impl.ROServicesImpl.java

License:Apache License

@POST
@Path("/")
@Consumes(MediaType.APPLICATION_JSON)/*from   w ww . j a  va 2s. c o  m*/
@Produces(MediaType.APPLICATION_JSON)
public Response startROPublicationProcess(String publicationRequestString,
        @QueryParam("requestUrl") String requestURL, @QueryParam("oreId") String oreId)
        throws URISyntaxException {
    String messageString = "";
    Document request = Document.parse(publicationRequestString);
    Document content = (Document) request.get("Aggregation");
    if (content == null) {
        messageString += "Missing Aggregation ";
    }
    Document preferences = (Document) request.get("Preferences");
    if (preferences == null) {
        messageString += "Missing Preferences ";
    }
    Object repository = request.get("Repository");
    if (repository == null) {
        messageString += "Missing Respository ";
    } else {
        FindIterable<Document> iter = repositoriesCollection.find(new Document("orgidentifier", repository));
        if (iter.first() == null) {
            messageString += "Unknown Repository: " + repository + " ";
        }

    }

    if (messageString.equals("")) {
        // Get organization from profile(s)
        // Add to base document
        Object creatorObject = content.get("Creator");
        String ID = (String) content.get("Identifier");
        BasicBSONList affiliations = new BasicBSONList();
        if (creatorObject != null) {
            if (creatorObject instanceof ArrayList) {
                Iterator<String> iter = ((ArrayList<String>) creatorObject).iterator();

                while (iter.hasNext()) {
                    String creator = iter.next();
                    List<String> orgs = getOrganizationforPerson(creator);
                    if (!orgs.isEmpty()) {
                        affiliations.addAll(orgs);
                    }
                }

            } else {
                // BasicDBObject - single value
                List<String> orgs = getOrganizationforPerson((String) creatorObject);
                if (!orgs.isEmpty()) {
                    affiliations.addAll(orgs);
                }
            }
        }

        request.append("Affiliations", affiliations);

        // Add first status message

        List<DBObject> statusreports = new ArrayList<DBObject>();
        DBObject status = BasicDBObjectBuilder.start()
                .add("date", DateFormat.getDateTimeInstance().format(new Date(System.currentTimeMillis())))
                .add("reporter", Constants.serviceName).add("stage", "Receipt Acknowledged")
                .add("message", "request recorded and processing will begin").get();
        statusreports.add(status);
        request.append("Status", statusreports);
        // Create initial status message - add
        // Add timestamp
        // Generate ID - by calling Workflow?
        // Add doc, return 201

        String newMapURL = requestURL + "/" + ID + "/oremap";
        URI uri = new URI(newMapURL);
        uri = uri.normalize();
        content.put("@id", uri.toString() + "#aggregation");
        content.put("authoratativeMap", oreId);

        publicationsCollection.insertOne(request);
        URI resource = null;
        try {
            resource = new URI("./" + ID);
        } catch (URISyntaxException e) {
            // Should not happen given simple ids
            e.printStackTrace();
        }
        return Response.created(resource).entity(new Document("identifier", ID)).build();
    } else {
        return Response.status(ClientResponse.Status.BAD_REQUEST).entity(messageString).build();
    }
}

From source file:org.sglover.checksum.dao.mongo.MongoChecksumDAO.java

License:Open Source License

private DBObject toDBObject(NodeChecksums documentChecksums) {
    BasicDBObjectBuilder checksumsObjectBuilder = BasicDBObjectBuilder.start();
    for (Map.Entry<Integer, List<Checksum>> checksums : documentChecksums.getChecksums().entrySet()) {
        List<DBObject> checksumDBObjects = new LinkedList<>();
        for (Checksum checksum : checksums.getValue()) {
            DBObject checksumDBObject = toDBObject(checksum);
            checksumDBObjects.add(checksumDBObject);
        }//from  w w w  . j av  a 2 s. c  om
        checksumsObjectBuilder.add(String.valueOf(checksums.getKey()), checksumDBObjects);
    }
    DBObject dbObject = BasicDBObjectBuilder.start("n", documentChecksums.getNodeId())
            .add("ni", documentChecksums.getNodeInternalId()).add("v", documentChecksums.getNodeVersion())
            .add("l", documentChecksums.getVersionLabel()).add("b", documentChecksums.getBlockSize())
            .add("nb", documentChecksums.getNumBlocks()).add("c", checksumsObjectBuilder.get()).get();
    return dbObject;
}