Example usage for com.mongodb DBCollection save

List of usage examples for com.mongodb DBCollection save

Introduction

In this page you can find the example usage for com.mongodb DBCollection save.

Prototype

public WriteResult save(final DBObject document) 

Source Link

Document

Update an existing document or insert a document depending on the parameter.

Usage

From source file:xbdd.webapp.resource.feature.Feature.java

License:Apache License

/**
 * Goes through each environment detail on this feature and pushes each unique one to a per-product document in the 'environments'
 * collection./*w ww .  j  a v a2 s .c om*/
 *
 * @param db
 * @param coordinates
 * @param feature
 */
@SuppressWarnings("unchecked")
public void updateEnvironmentDetails(final DB db, final Coordinates coordinates, final DBObject feature) {
    final DBCollection env = db.getCollection("environments");
    final List<DBObject> elements = (List<DBObject>) feature.get("elements");
    final BasicDBObject envQuery = coordinates.getQueryObject(Field.PRODUCT);
    // pull back the "product" document containing all the environments.
    DBObject productEnvironments = env.findOne(envQuery);
    // if one doesn't exist then create it.
    if (productEnvironments == null) {
        productEnvironments = new BasicDBObject();
        productEnvironments.put("coordinates", coordinates.getObject(Field.PRODUCT));
    }
    // pull back the list of environments
    List<Object> envs = (List<Object>) productEnvironments.get("environments");
    // if the list doesn't exist then create it.
    if (envs == null) {
        envs = new BasicDBList();
        productEnvironments.put("environments", envs);
    }
    final List<String> titleCache = new ArrayList<String>();
    // go through each scenario, pull out the environment details and add them to the back of the list.
    for (final DBObject scenario : elements) {
        String notes = (String) scenario.get("environment-notes");
        if (notes != null) {
            notes = notes.trim();
            if (notes.length() > 0) {
                if (!titleCache.contains(notes)) {
                    titleCache.add(notes);
                }
            }
        }
    }
    // go through each unique environment detail, remove it if it is already in the list and append to the end.
    for (final String environmentDetail : titleCache) {
        envs.remove(environmentDetail);
        envs.add(environmentDetail);
    }
    // if the list gets too long, truncate it on a LRU basis.
    if (envs.size() > MAX_ENVIRONMENTS_FOR_A_PRODUCT) {
        envs = envs.subList(envs.size() - MAX_ENVIRONMENTS_FOR_A_PRODUCT, envs.size());
        productEnvironments.put("environments", envs);
    }
    // save the list back.
    env.save(productEnvironments);
}

From source file:xbdd.webapp.resource.feature.Report.java

License:Apache License

protected void updateStatsDocument(final DB bdd, final Coordinates coordinates, final BasicDBList features) {
    // product and version are redundant for search, but ensure they're populated if the upsert results in an insert.
    final DBCollection statsCollection = bdd.getCollection("reportStats");
    final String id = coordinates.getProduct() + "/" + coordinates.getVersionString() + "/"
            + coordinates.getBuild();//from  w w w .j  a  va2  s .  co m
    statsCollection.remove(new BasicDBObject("_id", id));
    final BasicDBObject stats = new BasicDBObject("coordinates", coordinates.getReportCoordinates());
    stats.put("_id", id);
    final BasicDBObject summary = new BasicDBObject();
    stats.put("summary", summary);
    final BasicDBObject feature = new BasicDBObject();
    stats.put("feature", feature);
    for (final Object ob : features) {
        final BasicDBList scenarios = (BasicDBList) ((DBObject) ob).get("elements");
        if (scenarios != null) {
            for (final Object o : scenarios) {
                final String status = StatusHelper.getFinalScenarioStatus((DBObject) o, false).getTextName();
                final Integer statusCounter = (Integer) summary.get(status);
                if (statusCounter == null) {
                    summary.put(status, 1);
                } else {
                    summary.put(status, statusCounter + 1);
                }
            }
        }
    }
    statsCollection.save(stats);
}

From source file:xbdd.webapp.resource.feature.Report.java

License:Apache License

@PUT
@Path("/{product}/{major}.{minor}.{servicePack}/{build}")
public DBObject putReport(@BeanParam final Coordinates coordinates, final DBObject root) throws IOException {
    final BasicDBList doc = (BasicDBList) root;
    final DB grid = this.client.getDB("grid");
    final GridFS gridFS = new GridFS(grid);
    final DB bdd = this.client.getDB("bdd");
    final DBCollection features = bdd.getCollection("features");
    updateSummaryDocument(bdd, coordinates);

    for (int i = 0; i < doc.size(); i++) {
        // take each feature and give it a unique id.
        final DBObject feature = (DBObject) doc.get(i);
        final String _id = coordinates.getFeature_Id((String) feature.get("id"));
        feature.put("_id", _id);
        embedSteps(feature, gridFS, coordinates); // extract embedded content and hyperlink to it.
        packBackgroundsInToScenarios(feature); // nest background elements within their scenarios
        final BasicDBObject featureCo = coordinates.getReportCoordinates();
        feature.put("coordinates", featureCo);

        final BasicDBList newElements = mergeExistingScenarios(features, feature, _id);
        feature.put("elements", newElements);

        final String originalStatus = StatusHelper.getFeatureStatus(feature);
        feature.put("calculatedStatus", originalStatus);
        feature.put("originalAutomatedStatus", originalStatus);
        this.log.info("Saving: " + feature.get("name") + " - " + feature.get("calculatedStatus"));
        this.log.trace("Adding feature:" + JSON.serialize(feature));
        features.save(feature);
    }//from  w w  w .  j  av  a  2  s.c  o m
    final DBCursor cursor = features.find(coordinates.getReportCoordinatesQueryObject()); // get new co-ordinates to exclude the "version"
    // field
    final List<DBObject> returns = new ArrayList<DBObject>();
    try {
        while (cursor.hasNext()) {
            returns.add(cursor.next());
        }
    } finally {
        cursor.close();
    }
    final BasicDBList list = new BasicDBList();
    list.addAll(returns);
    updateStatsDocument(bdd, coordinates, list);
    return list;
}

From source file:xbdd.webapp.resource.feature.UploadAttachment.java

License:Apache License

@SuppressWarnings("unchecked")
@POST/*from  www  .j  a va  2  s .c  o m*/
@Path("/{elementId}/{report}/{version}/{build}/{id}")
@Consumes(MediaType.MULTIPART_FORM_DATA)
public String setAttachment(@PathParam("report") final String report,
        @PathParam("version") final String version, @PathParam("build") final String build,
        @PathParam("id") final String id, @PathParam("elementId") final String elementId,
        @FormDataParam("attachmentfile") final File file,
        @FormDataParam("attachmentfile") final FormDataBodyPart body, @Context final HttpServletRequest req)
        throws IOException {
    try (final InputStream is = new FileInputStream(file.getAbsolutePath())) {
        final String elementIdMod = elementId.replace("&2F", "/");
        final DB gridDB = this.client.getDB("grid");
        final GridFS gridFS = new GridFS(gridDB);
        final GridFSInputFile gridFile = gridFS.createFile(is);
        gridFile.setFilename(
                body.getMediaType().toString().split("/")[0] + ".x1.mu." + UUID.randomUUID().toString());
        gridFile.setContentType(body.getMediaType().toString());
        gridFile.save();
        final DB bddDB = this.client.getDB("bdd");
        final DBCollection collection = bddDB.getCollection("features");
        // // get object
        final String featureId = report + "/" + version + "/" + build + "/" + id;
        final DBObject feature = collection.findOne(new BasicDBObject("_id", featureId));
        final BasicDBList elements = (BasicDBList) feature.get("elements");
        String scenarioName = "";
        if (elements != null) {
            for (int i = 0; i < elements.size(); i++) {
                final DBObject scenario = (DBObject) elements.get(i);
                if (scenario.get("id").equals(id + ";" + elementIdMod)) {
                    scenarioName = (String) scenario.get("name");
                    // get steps
                    final BasicDBList steps = (BasicDBList) scenario.get("steps");
                    final DBObject laststep = (DBObject) steps.get(steps.size() - 1);
                    List<String> embeddings = new ArrayList<String>();
                    if (laststep.containsField("embeddings")) {
                        embeddings = (ArrayList<String>) laststep.get("embeddings");
                    }
                    embeddings.add(gridFile.getFilename()); // get existng then add to them
                    laststep.put("embeddings", embeddings);
                    steps.set(steps.size() - 1, laststep);
                    scenario.put("steps", steps);
                    elements.set(i, scenario);
                }
            }
        }
        feature.put("elements", elements);
        feature.put("statusLastEditedBy", req.getRemoteUser());
        feature.put("lastEditOn", new Date());

        // add edit update
        BasicDBList edits = (BasicDBList) feature.get("edits");
        if (edits == null) {
            edits = new BasicDBList();
        }
        final BasicDBList temp = new BasicDBList();
        temp.add(new BasicDBObject().append("id", "embeddings").append("added", gridFile.getFilename())
                .append("removed", null));

        final BasicDBList masks = new BasicDBList();
        masks.add(new BasicDBObject().append("scenario", scenarioName).append("changes", temp));

        final BasicDBObject edit = new BasicDBObject().append("name", feature.get("statusLastEditedBy"))
                .append("date", feature.get("lastEditOn")).append("prev", feature.get("calculatedStatus"))
                .append("curr", feature.get("calculatedStatus")).append("stepChanges", masks);

        final BasicDBList newEdits = new BasicDBList();
        newEdits.add(edit);
        newEdits.addAll(edits);
        feature.put("edits", newEdits);

        collection.save(feature);
        return gridFile.getFilename();
    }
}