Example usage for com.mongodb.gridfs GridFSDBFile writeTo

List of usage examples for com.mongodb.gridfs GridFSDBFile writeTo

Introduction

In this page you can find the example usage for com.mongodb.gridfs GridFSDBFile writeTo.

Prototype

public long writeTo(final OutputStream out) throws IOException 

Source Link

Document

Writes the file's data to an OutputStream.

Usage

From source file:org.craftercms.social.services.impl.SupportDataAccessImpl.java

License:Open Source License

@Override
public void streamAttachment(ObjectId attachmentId, HttpServletResponse response) {
    try {//from  www .j  a va  2 s .c  om
        GridFS gFS = new GridFS(mongoTemplate.getDb());
        GridFSDBFile file = gFS.find(attachmentId);
        if (file != null) {
            response.setContentType(file.getContentType());
            response.setContentLength((int) file.getLength());
            response.setHeader("Content-Disposition", "attachment; filename=" + file.getFilename());
            file.writeTo(response.getOutputStream());

        } else {
            log.error("Attachment with id {} does not exist", attachmentId);
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }

    } catch (Exception e) {
        log.error("Can not stream file.", e);
    }
}

From source file:org.exist.mongodb.xquery.gridfs.Stream.java

License:Open Source License

/**
 * Stream document to HTTP agent/*from w  w  w  . ja v  a 2s  . c o  m*/
 */
void stream(GridFSDBFile gfsFile, String documentId, Boolean setDisposition)
        throws IOException, XPathException {
    if (gfsFile == null) {
        throw new XPathException(this, GridfsModule.GRFS0004,
                String.format("Document '%s' could not be found.", documentId));
    }

    DBObject metadata = gfsFile.getMetaData();

    // Determine actual size
    String compression = (metadata == null) ? null : (String) metadata.get(EXIST_COMPRESSION);
    Long originalSize = (metadata == null) ? null : (Long) metadata.get(EXIST_ORIGINAL_SIZE);

    long length = gfsFile.getLength();
    if (originalSize != null) {
        length = originalSize;
    }

    // Stream response stream
    ResponseWrapper rw = getResponseWrapper(context);

    // Set HTTP Headers
    rw.addHeader(Constants.CONTENT_LENGTH, String.format("%s", length));

    // Set filename when required
    String filename = determineFilename(documentId, gfsFile);
    if (setDisposition && StringUtils.isNotBlank(filename)) {
        rw.addHeader(Constants.CONTENT_DISPOSITION, String.format("attachment;filename=%s", filename));
    }

    String contentType = getMimeType(gfsFile.getContentType(), filename);
    if (contentType != null) {
        rw.setContentType(contentType);
    }

    boolean isGzipSupported = isGzipEncodingSupported(context);

    // Stream data
    if ((StringUtils.isBlank(compression))) {
        // Write data as-is, no marker available that data is stored compressed
        try (OutputStream os = rw.getOutputStream()) {
            gfsFile.writeTo(os);
            os.flush();
        }

    } else {

        if (isGzipSupported && StringUtils.contains(compression, GZIP)) {
            // Write compressend data as-is, since data is stored as gzipped data and
            // the agent suports it.
            rw.addHeader(Constants.CONTENT_ENCODING, GZIP);
            try (OutputStream os = rw.getOutputStream()) {
                gfsFile.writeTo(os);
                os.flush();
            }

        } else {
            // Write data uncompressed
            try (OutputStream os = rw.getOutputStream()) {
                InputStream is = gfsFile.getInputStream();
                try (GZIPInputStream gzis = new GZIPInputStream(is)) {
                    IOUtils.copyLarge(gzis, os);
                    os.flush();
                }
            }
        }
    }
}

From source file:org.mongodb.demos.binary.GridFSDemo.java

License:Apache License

/**
 * Read the file stored in GridFS and  save it into the fileToSave location
 * @param id//from  www . ja v  a  2  s . c  o  m
 * @param fileToSave
 * @throws Exception
 */
public void readLargeFile(Object id, String fileToSave) throws Exception {
    GridFS fs = new GridFS(db);
    GridFSDBFile out = fs.findOne(new BasicDBObject("_id", id));
    out.writeTo(fileToSave);

    System.out.println("File saved into " + fileToSave);
}

From source file:org.opentestsystem.authoring.testauth.rest.FileGroupController.java

License:Open Source License

/******************************** Grid FS Endpoints ********************************/
@RequestMapping(value = "/fileGroup/gridFsFile/{fileGridId}")
@Secured({ "ROLE_Result Upload Read" })
public ResponseEntity<byte[]> getGridFsFile(@PathVariable final String fileGridId) {
    final ByteArrayOutputStream ret = new ByteArrayOutputStream();
    HttpHeaders responseHeaders;/*w w  w.j  ava  2s . c  o m*/

    try {
        final GridFSDBFile grid = this.fileGroupService.getGridFsFile(fileGridId);
        grid.writeTo(ret);
        responseHeaders = buildResponseHeaders(ret.toByteArray().length, grid.getFilename(),
                grid.getContentType());

        ret.flush();
    } catch (final IOException e) {
        throw new LocalizedException("document.file.notfound", new String[] { fileGridId }, e);
    }
    return new ResponseEntity<byte[]>(ret.toByteArray(), responseHeaders, HttpStatus.OK);
}

From source file:org.opentestsystem.authoring.testauth.rest.ScoringRuleController.java

License:Open Source License

@RequestMapping(value = "/scoringRule/conversionTableFile/{fileGridId}", method = RequestMethod.GET)
@Secured({ "ROLE_Scoring Rule Read" })
// NOTE: there is intentionally no @PreAuthorize annotation...ability to read scoring rule is all that is needed since scoring rule conversion table files are non-tenanted
public ResponseEntity<byte[]> getConversionTableFile(@PathVariable final String fileGridId,
        final HttpServletResponse response) {
    final ByteArrayOutputStream ret = new ByteArrayOutputStream();
    String filename = null;//  w ww  . jav  a 2  s  .  c o  m
    try {
        final GridFSDBFile grid = this.scoringRuleService.getConversionTableFile(fileGridId);
        grid.writeTo(ret);
        filename = grid.getFilename();
        ret.flush();
    } catch (final IOException e) {
        throw new LocalizedException("scoringRule.conversionTableFile.notfound", new String[] { fileGridId },
                e);
    }
    final byte[] bytes = ret.toByteArray();
    final HttpHeaders responseHeaders = buildResponseHeaders(bytes.length, filename);
    return new ResponseEntity<byte[]>(bytes, responseHeaders, HttpStatus.OK);
}

From source file:org.opentestsystem.authoring.testauth.service.impl.ScoringRuleHelper.java

License:Open Source License

private void validateConversionTableFileLengthsMatch(final BindingResult bindingResult,
        final ScoringRule scoringRule) {
    if (scoringRule != null && scoringRule.getValueConversionTableGridFsId() != null
            && scoringRule.getStandardErrorConversionTableGridFsId() != null) {
        final GridFSDBFile valueFile = this.gridFsRepository
                .getById(scoringRule.getValueConversionTableGridFsId());
        final ByteArrayOutputStream valueBaos = new ByteArrayOutputStream();
        try {/*w w  w .  j  a va2 s .  c om*/
            valueFile.writeTo(valueBaos);
        } catch (final IOException e) {
            bindingResult.addError(buildFieldError("valueConversionTableGridFsId",
                    "scoringRule.valueConversionTableGridFsId.required"));
        }
        final int valueListSize = validateConversionListFile(valueBaos.toByteArray(), scoringRule.getLabel(),
                "VALUE", false).size();

        final GridFSDBFile errorFile = this.gridFsRepository
                .getById(scoringRule.getStandardErrorConversionTableGridFsId());
        final ByteArrayOutputStream errorBaos = new ByteArrayOutputStream();
        try {
            errorFile.writeTo(errorBaos);
        } catch (final IOException e) {
            bindingResult.addError(buildFieldError("standardErrorConversionTableGridFsId",
                    "scoringRule.standardErrorConversionTableGridFsId.required"));
        }
        final int errorListSize = validateConversionListFile(errorBaos.toByteArray(), scoringRule.getLabel(),
                "STANDARD_ERROR", false).size();

        if (valueListSize != errorListSize) {
            bindingResult.addError(buildFieldError("standardErrorConversionTableGridFsId",
                    "scoringRule.standardErrorConversionTableGridFsId.length",
                    paramArray(String.valueOf(valueListSize), String.valueOf(errorListSize))));
        }
    }
}

From source file:org.opentestsystem.shared.progman.rest.AssetPoolController.java

License:Open Source License

/**
 * Retrieve the /assetFile with query parameter or with JSON (assetPoolId).
 *
 * @param request HttpServletRequest/*from   w  w w  .  j a  va 2 s  .c o  m*/
 * @return byte[] asset file
 */
@RequestMapping(value = "/assetPool/assetFile/{assetGridFsId}/{filename}", method = RequestMethod.GET)
@ResponseBody
public ResponseEntity<byte[]> getAssetFile(@PathVariable final String assetGridFsId,
        final HttpServletResponse response) {
    ByteArrayOutputStream ret = new ByteArrayOutputStream();
    try {
        GridFSDBFile grid = assetPoolService.getAssetFile(assetGridFsId);
        grid.writeTo(ret);
        ret.flush();
    } catch (IOException e) {
        throw new LocalizedException("assetFile.notfound", new String[] { assetGridFsId }, e);
    }
    return new ResponseEntity<byte[]>(ret.toByteArray(), HttpStatus.CREATED);
}

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

License:Apache License

@GET
@Path("/{id}/oremap")
@Produces(MediaType.APPLICATION_JSON)/*  w w w. j a v a2 s.  c  o  m*/
public Response getROOREMap(@PathParam("id") String id) throws JSONException, IOException {

    FindIterable<Document> iter = publicationsCollection.find(new Document("Aggregation.Identifier", id));

    if (iter == null || iter.first() == null) {
        return Response.status(Response.Status.NOT_FOUND)
                .entity(new JSONObject().put("Error", "Cannot find RO with id " + id).toString()).build();
    }

    Document document = iter.first();
    ObjectId mapId = new ObjectId(((Document) document.get("Aggregation")).get("authoratativeMap").toString());

    //FindIterable<Document> oreIter = oreMapCollection.find(new Document("_id", mapId));
    //Document map = oreIter.first();
    GridFSDBFile dbFile = oreMapBucket.findOne(mapId);
    if (dbFile == null) {
        return Response.status(Response.Status.NOT_FOUND)
                .entity(new JSONObject().put("Error", "Cannot find ORE with id " + id).toString()).build();
    }

    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    dbFile.writeTo(bos);
    Document map = Document.parse(bos.toString());

    //Internal meaning only
    map.remove("_id");
    //document.remove("_id");

    return Response.ok(map.toJson()).build();
}

From source file:org.seadpdt.ROServices.java

License:Apache License

@GET
@Path("/{id}/oremap")
@Produces(MediaType.APPLICATION_JSON)/*from   w w w  .  ja v  a 2  s.c  om*/
public Response getROOREMap(@PathParam("id") String id) throws JSONException, IOException {

    FindIterable<Document> iter = publicationsCollection.find(new Document("Aggregation.Identifier", id));

    if (iter == null || iter.first() == null) {
        return Response.status(javax.ws.rs.core.Response.Status.NOT_FOUND)
                .entity(new JSONObject().put("Error", "Cannot find RO with id " + id).toString()).build();
    }

    Document document = iter.first();
    ObjectId mapId = new ObjectId(((Document) document.get("Aggregation")).get("authoratativeMap").toString());

    //FindIterable<Document> oreIter = oreMapCollection.find(new Document("_id", mapId));
    //Document map = oreIter.first();
    GridFSDBFile dbFile = oreMapBucket.findOne(mapId);
    if (dbFile == null) {
        return Response.status(javax.ws.rs.core.Response.Status.NOT_FOUND)
                .entity(new JSONObject().put("Error", "Cannot find ORE with id " + id).toString()).build();
    }

    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    dbFile.writeTo(bos);
    Document map = Document.parse(bos.toString());

    //Internal meaning only
    map.remove("_id");
    //document.remove("_id");

    return Response.ok(map.toJson()).build();
}

From source file:org.waveprotocol.wave.examples.fedone.persistence.mongodb.MongoDbStore.java

License:Apache License

@Override
public AttachmentData getAttachment(String id) {
    final GridFSDBFile attachment = getAttachmentGrid().findOne(id);

    if (attachment == null) {
        return null;
    } else {/*from ww  w  .j av a2s .  c o m*/
        return new AttachmentData() {
            @Override
            public void writeDataTo(OutputStream out) throws IOException {
                attachment.writeTo(out);
            }

            @Override
            public Date getLastModifiedDate() {
                return attachment.getUploadDate();
            }

            @Override
            public long getContentSize() {
                return attachment.getLength();
            }

            @Override
            public InputStream getInputStream() {
                return attachment.getInputStream();
            }
        };
    }
}