Example usage for com.mongodb.gridfs GridFSInputFile save

List of usage examples for com.mongodb.gridfs GridFSInputFile save

Introduction

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

Prototype

@Override
public void save() 

Source Link

Document

Calls GridFSInputFile#save(long) with the existing chunk size.

Usage

From source file:tango.mongo.ImageManager.java

License:Open Source License

private void transferFiles(String queryField, ObjectId queryValue, GridFS gfsSource, GridFS gfsDestination) {
    BasicDBObject query = new BasicDBObject(queryField, queryValue);
    List<GridFSDBFile> files = gfsSource.find(query); // FIXME charge tout en mmoire?
    for (GridFSDBFile file : files) {
        GridFSInputFile gfi = gfsDestination.createFile(file.getInputStream(), file.getFilename());
        gfi.put(queryField, queryValue);
        gfi.put("fileIdx", file.get("fileIdx"));
        gfi.put("fileType", file.get("fileType"));
        gfi.put("pixelDepth", file.get("pixelDepth"));
        gfi.put("unit", file.get("unit"));
        gfi.save();
        if (gfi != null)
            try {
                gfi.getOutputStream().close();
            } catch (IOException ex) {
                Logger.getLogger(ImageManager.class.getName()).log(Level.SEVERE, null, ex);
            }//from  w w  w  .  j  a  v a 2s  . co m
    }
    gfsSource.remove(query);
}

From source file:tango.mongo.MongoConnector.java

License:Open Source License

public synchronized boolean saveInputImage(ObjectId field_id, int fileRank, ImageHandler img,
        boolean flushImage) {
    if (img == null) {
        return false;
    }/*w w w  .  ja  va2s .c  om*/

    //IJ.log("file: "+img.getTitle()+" size:"+img.getSizeInMb()+ " available memory:"+Core.getAvailableMemory()+ " please free memory");
    double scaleZ = img.getScaleZ();
    String unit = img.getUnit();
    String title = img.getTitle();
    MemoryMXBean memoryBean = ManagementFactory.getMemoryMXBean();
    try {
        byte[] data = img.getBinaryData();
        if (data == null) {
            IJ.log("couldn't save image:" + title);
            return false;
        }
        if (flushImage) {
            img.flush();
        }
        GridFSInputFile gfi = this.gfsField.createFile(data);
        data = null;
        gfi.setFilename(title);
        gfi.put("field_id", field_id);
        gfi.put("fileRank", fileRank);
        gfi.put("pixelDepth", scaleZ);
        gfi.put("unit", unit);
        removeInputImage(field_id, fileRank);
        gfi.save();
        gfi.getOutputStream().close();
        return true;
    } catch (Exception e) {
        exceptionPrinter.print(e, "Error while saving image: " + title, true);
    } catch (OutOfMemoryError e) {
        int MEGABYTE = (1024 * 1024);
        MemoryUsage heapUsage = memoryBean.getHeapMemoryUsage();
        long maxMemory = heapUsage.getMax() / MEGABYTE;
        long usedMemory = heapUsage.getUsed() / MEGABYTE;
        IJ.log("Error while saving image:" + title + " Out of memory. Memory Use :" + usedMemory + "M/"
                + maxMemory + "M");
    }
    return false;
}

From source file:tango.mongo.MongoConnector.java

License:Open Source License

public synchronized void saveFieldThumbnail(ObjectId field_id, int fileIdx, byte[] thumbnail) {
    GridFSInputFile gfi = this.gfsFieldThumbnail.createFile(thumbnail);
    BasicDBObject query = new BasicDBObject("field_id", field_id).append("fileRank", fileIdx);
    gfsFieldThumbnail.remove(query);//from  w  w  w.  j ava 2 s . c om
    gfi.put("field_id", field_id);
    gfi.put("fileRank", fileIdx);
    gfi.save();
    try {
        gfi.getOutputStream().close();
    } catch (Exception e) {
        exceptionPrinter.print(e, "", Core.GUIMode);
    }
}

From source file:tango.mongo.MongoConnector.java

License:Open Source License

public synchronized void saveNucleusImage(ObjectId nucleus_id, int fileIdx, int fileType, ImageHandler img) {
    removeNucleusImage(nucleus_id, fileIdx, fileType);
    if (img == null) {
        System.out.println("set nucleus image null");
        return;//from  ww  w. j a  va2s. com
    }
    try {
        GridFSInputFile gfi = this.gfsNucleus.createFile(img.getBinaryData());
        gfi.setFilename(img.getImagePlus().getShortTitle());
        gfi.put("nucleus_id", nucleus_id);
        gfi.put("fileIdx", fileIdx);
        gfi.put("fileType", fileType);
        gfi.put("pixelDepth", img.getScaleZ());
        gfi.put("unit", img.getUnit());
        gfi.put("offsetX", img.offsetX);
        gfi.put("offsetY", img.offsetY);
        gfi.put("offsetZ", img.offsetZ);
        gfi.save();
        if (gfi != null) {
            gfi.getOutputStream().close();
        }
    } catch (Exception e) {
        exceptionPrinter.print(e, "Error while saving image:" + img.getTitle(), Core.GUIMode);
    }
}

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

License:Apache License

/**
 * go through all the embedded content, store it to GridFS, replace the doc embeddings with a hyperlink to the saved content.
 *//*from   w w w. j a v a 2 s  . c om*/
protected void embedSteps(final DBObject feature, final GridFS gridFS, final Coordinates coordinates) {
    final BasicDBList elements = (BasicDBList) feature.get("elements");
    final String featureId = (String) feature.get("_id");
    if (elements != null) {
        for (int j = 0; j < elements.size(); j++) {
            final DBObject scenario = (DBObject) elements.get(j);
            final String scenarioId = (String) scenario.get("_id");
            final BasicDBList steps = (BasicDBList) scenario.get("steps");
            if (steps != null) {
                for (int k = 0; k < steps.size(); k++) {
                    final DBObject step = (DBObject) steps.get(k);
                    final BasicDBList embeddings = (BasicDBList) step.get("embeddings");
                    if (embeddings != null) {
                        for (int l = 0; l < embeddings.size(); l++) {
                            final DBObject embedding = (DBObject) embeddings.get(l);
                            final GridFSInputFile image = gridFS.createFile(
                                    Base64.decodeBase64(((String) embedding.get("data")).getBytes()));
                            image.setFilename(guid());
                            final BasicDBObject metadata = new BasicDBObject()
                                    .append("product", coordinates.getProduct())
                                    .append("major", coordinates.getMajor())
                                    .append("minor", coordinates.getMinor())
                                    .append("servicePack", coordinates.getServicePack())
                                    .append("build", coordinates.getBuild()).append("feature", featureId)
                                    .append("scenario", scenarioId);
                            image.setMetaData(metadata);
                            image.setContentType((String) embedding.get("mime_type"));
                            image.save();
                            embeddings.put(l, image.getFilename());
                        }
                    }
                }
            }
        }
    }
}

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

License:Apache License

@SuppressWarnings("unchecked")
@POST/*from  ww  w.  j ava2s . 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();
    }
}