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:com.sangupta.urn.service.impl.MongoGridFSUrnStorageServiceImpl.java

License:Apache License

@Override
protected UrnObject get(String objectKey) {
    Query query = new Query(Criteria.where("filename").is(objectKey));
    GridFSDBFile file = this.template.findOne(query);
    if (file == null) {
        return null;
    }/*from  w  ww .java 2 s  .c  o  m*/

    // check for expiry
    Long expiry = (Long) file.get(FIELD_EXPIRY);
    if (expiry != null) {
        if (expiry.longValue() < System.currentTimeMillis()) {
            this.remove(objectKey);
            return null;
        }
    }

    byte[] bytes = null;
    try {
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        file.writeTo(stream);
        stream.close();
        bytes = stream.toByteArray();
    } catch (IOException e) {
        LOGGER.error("Error reading file from mongo database for key: " + objectKey, e);
        return null;
    }

    UrnObject urnObject = new UrnObject(objectKey, bytes);

    // now the metadata
    if (expiry != null) {
        urnObject.expiry = expiry.longValue();
    }

    urnObject.name = (String) file.get(FIELD_NAME);
    urnObject.mime = file.getContentType();
    urnObject.stored = file.getUploadDate().getTime();

    // return the object
    return urnObject;
}

From source file:com.spring.tutorial.controllers.DefaultController.java

@RequestMapping(value = "/files/{id}", method = RequestMethod.GET)
public String getFile(@PathVariable("id") String id, ModelMap map, HttpServletRequest request,
        HttpServletResponse response) throws IOException, Exception {

    String _id = request.getSession().getAttribute("id").toString();
    MongoData data = new MongoData();
    GridFS collection = new GridFS(data.getDB(), _id + "_files");

    BasicDBObject query = new BasicDBObject();
    query.put("_id", new ObjectId(id));
    GridFSDBFile file = collection.findOne(query);

    DBCollection metaFileCollection = data.getDB().getCollection(_id + "_files_meta");
    BasicDBObject metaQuery = new BasicDBObject();
    metaQuery.put("file-id", new ObjectId(id));
    DBObject metaFileDoc = metaFileCollection.findOne(metaQuery);
    MongoFile metaFile = new MongoFile(metaFileDoc);

    ServletOutputStream out = response.getOutputStream();
    String mimeType = metaFile.getType();
    response.setContentType(mimeType);/* w w  w  . jav a2 s  .  c om*/
    response.setContentLength((int) file.getLength());
    String headerKey = "Content-Disposition";

    File f = File.createTempFile(file.getFilename(),
            metaFile.getType().substring(metaFile.getType().indexOf("/") + 1));
    String headerValue = String.format("attachment; filename=\"%s\"", file.getFilename());
    response.setHeader(headerKey, headerValue);
    file.writeTo(f);

    FileInputStream inputStream = new FileInputStream(f);
    byte[] buffer = new byte[4096];
    int bytesRead = -1;

    while (inputStream.read(buffer, 0, 4096) != -1) {
        out.write(buffer, 0, 4096);
    }
    inputStream.close();
    out.flush();
    out.close();

    return "mydrive/temp";
}

From source file:com.test.mavenproject1.Main.java

public static void main(String[] args) throws Exception {
    //Load our image
    byte[] imageBytes = LoadImage("/home/fabrice/Pictures/priv/DSCN3338.JPG");
    //Connect to database
    Mongo mongo = new Mongo("127.0.0.1");
    String dbName = "GridFSTestJava";
    DB db = mongo.getDB(dbName);/*from   w  w w  .jav  a2  s .  c o m*/
    //Create GridFS object
    GridFS fs = new GridFS(db);
    //Save image into database
    GridFSInputFile in = fs.createFile(imageBytes);
    in.save();

    //Find saved image
    GridFSDBFile out = fs.findOne(new BasicDBObject("_id", in.getId()));

    //Save loaded image from database into new image file
    FileOutputStream outputImage = new FileOutputStream("/home/fabrice/Pictures/DSCN3338Copy.JPG");
    out.writeTo(outputImage);
    outputImage.close();
}

From source file:data.repository.pragma.DataObjectController.java

License:Apache License

@RequestMapping(value = "/DO/find/data", method = RequestMethod.GET)
@ResponseBody//from w  ww.  j  a v  a  2s  . c o  m
public void DOfindData(@RequestParam(value = "ID", required = true) String ID, HttpServletResponse response) {
    // Connect to MongoDB and return DO data files as response
    // return
    try {
        GridFSDBFile doc = Staging_repository.findDOByID(ID);
        response.setContentType(doc.getContentType());
        response.setContentLengthLong(doc.getLength());
        response.setHeader("Content-Disposition", "attachment; filename=\"" + doc.getFilename() + "\"");
        OutputStream out = response.getOutputStream();
        doc.writeTo(out);

    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:data.repository.pragma.PermanentRepoController.java

License:Apache License

@RequestMapping(value = "/repo/find/data", method = RequestMethod.GET)
@ResponseBody/*from w w  w. ja v a2  s.  c o  m*/
public void DOfindData(@RequestParam(value = "ID", required = true) String ID, HttpServletResponse response) {
    // Connect to MongoDB and return DO data files as response
    // return
    try {
        GridFSDBFile doc = permanent_repository.findDOByID(ID);
        response.setContentType(doc.getContentType());
        response.setContentLengthLong(doc.getLength());
        response.setHeader("Content-Disposition", "attachment; filename=\"" + doc.getFilename() + "\"");
        OutputStream out = response.getOutputStream();
        doc.writeTo(out);

    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:eu.eubrazilcc.lvl.storage.mongodb.cache.FilePersistingCache.java

License:EUPL

public CachedFile put(final @Nullable String namespace, final GridFSDBFile gfsFile) throws IOException {
    checkArgument(gfsFile != null && isNotBlank(gfsFile.getFilename()) && isNotBlank(gfsFile.getMD5()),
            "Uninitialized or invalid file");
    File outfile = null;/* w  w w  . jav a  2  s .  c om*/
    try {
        final String uuid = randomUUID().toString();
        outfile = new File(new File(cacheDir, uuid.substring(0, 2)), uuid);
        final File parentDir = outfile.getParentFile();
        if (parentDir.exists() || parentDir.mkdirs())
            ;
        if ((outfile.isFile() && outfile.canWrite()) || outfile.createNewFile())
            ;
        final CachedFile cachedFile = CachedFile.builder().cachedFilename(outfile.getCanonicalPath())
                .md5(gfsFile.getMD5()).build();
        gfsFile.writeTo(outfile);
        CACHE.put(toKey(namespace, gfsFile.getFilename()), cachedFile);
        return cachedFile;
    } catch (Exception e) {
        deleteQuietly(outfile);
        throw e;
    }
}

From source file:eu.euregjug.site.assets.AssetApiController.java

License:Apache License

@RequestMapping({ "/{filename:.+}" })
public void get(final @PathVariable String filename, final HttpServletRequest request,
        final HttpServletResponse response) throws IOException {
    final GridFSDBFile file = this.gridFs.findOne(Query.query(Criteria.where("filename").is(filename)));
    if (file == null) {
        response.setStatus(HttpServletResponse.SC_NOT_FOUND);
    } else {//ww w .j  av a  2  s.c  o m
        final int cacheForDays = 365;
        response.setHeader("Content-Type", file.getContentType());
        response.setHeader("Content-Disposition", String.format("inline; filename=\"%s\"", file.getFilename()));
        response.setHeader("Expires", now(of("UTC")).plusDays(cacheForDays).format(RFC_1123_DATE_TIME));
        response.setHeader("Cache-Control",
                String.format("max-age=%d, %s", TimeUnit.DAYS.toSeconds(cacheForDays), "public"));
        file.writeTo(response.getOutputStream());
        response.flushBuffer();
    }
}

From source file:fr.wseduc.gridfs.GridFSPersistor.java

License:Apache License

private void writeTo(Message<JsonObject> message) {
    String path = message.body().getString("path");
    if (path == null) {
        sendError(message, "Invalid output path.");
        return;/*  ww  w. ja  v  a2  s. c  o m*/
    }
    JsonObject query = message.body().getObject("query");
    if (query == null) {
        sendError(message, "Invalid query.");
        return;
    }
    JsonObject alias = message.body().getObject("alias", new JsonObject());
    boolean renameIfExists = message.body().getBoolean("rename-if-exists", true);
    GridFS fs = new GridFS(db, bucket);
    try {
        List<GridFSDBFile> files = fs.find(jsonToDBObject(query));
        FileSystem fileSystem = vertx.fileSystem();
        for (GridFSDBFile f : files) {
            String a = alias.getString(f.getId().toString());
            String p = path + File.separator + ((a != null) ? a : f.getFilename());
            if (renameIfExists && fileSystem.existsSync(p)) {
                p = path + File.separator + f.getId().toString() + "_" + ((a != null) ? a : f.getFilename());
            }
            f.writeTo(p);
        }
        sendOK(message, new JsonObject().putNumber("number", files.size()));
    } catch (IOException | MongoException e) {
        logger.error(e.getMessage(), e);
        sendError(message, e.getMessage());
    }
}

From source file:fr.wseduc.gridfs.GridFSPersistor.java

License:Apache License

private void getFile(Message<Buffer> message, JsonObject json) {
    JsonObject query = json.getObject("query");
    if (query == null) {
        return;//  w ww .ja  v  a 2s.c  o m
    }
    GridFS fs = new GridFS(db, bucket);
    try {
        GridFSDBFile f = fs.findOne(jsonToDBObject(query));
        if (f == null) {
            replyError(message, "File not found with query : " + query.encode());
            return;
        }
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        f.writeTo(os);
        message.reply(new Buffer(os.toByteArray()));
    } catch (IOException | MongoException e) {
        container.logger().error(e.getMessage(), e);
        JsonObject j = new JsonObject().putString("status", "error").putString("message", e.getMessage());
        try {
            message.reply(new Buffer(j.encode().getBytes("UTF-8")));
        } catch (UnsupportedEncodingException e1) {
            container.logger().error(e1.getMessage(), e1);
        }
    }
}

From source file:fr.wseduc.gridfs.GridFSPersistor.java

License:Apache License

private void copyFile(Message<Buffer> message, JsonObject json) {
    JsonObject query = json.getObject("query");
    if (query == null) {
        return;//from   w w  w . j  a v a  2  s .c  o  m
    }
    GridFS fs = new GridFS(db, bucket);
    try {
        GridFSDBFile f = fs.findOne(jsonToDBObject(query));
        if (f == null) {
            replyError(message, "File not found with query : " + query.encode());
            return;
        }
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        f.writeTo(os);
        JsonObject j = new JsonObject();
        j.putString("content-type", f.getContentType());
        j.putString("filename", f.getFilename());
        persistFile(message, os.toByteArray(), j);
    } catch (IOException | MongoException e) {
        replyError(message, e.getMessage());
    }
}