Example usage for com.mongodb.gridfs GridFS DEFAULT_BUCKET

List of usage examples for com.mongodb.gridfs GridFS DEFAULT_BUCKET

Introduction

In this page you can find the example usage for com.mongodb.gridfs GridFS DEFAULT_BUCKET.

Prototype

String DEFAULT_BUCKET

To view the source code for com.mongodb.gridfs GridFS DEFAULT_BUCKET.

Click Source Link

Document

Bucket to use for the collection namespaces

Usage

From source file:com.bugull.mongo.fs.BuguFSFactory.java

License:Apache License

public BuguFS create() {
    return create(GridFS.DEFAULT_BUCKET, GridFS.DEFAULT_CHUNKSIZE);
}

From source file:com.bugull.mongo.fs.BuguFSFactory.java

License:Apache License

public BuguFS create(long chunkSize) {
    return create(GridFS.DEFAULT_BUCKET, chunkSize);
}

From source file:com.bugull.mongo.fs.UploadedFileServlet.java

License:Apache License

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    if (!StringUtil.isEmpty(password)) {
        String p = request.getParameter("password");
        if (StringUtil.isEmpty(p) || !p.equals(password)) {
            return;
        }/* w ww.  j  a v a  2s  .c  o  m*/
    }
    String uri = request.getRequestURI();
    int second = uri.indexOf(SLASH, 1);
    uri = uri.substring(second);
    int last = uri.lastIndexOf(SLASH);
    String filename = uri.substring(last + 1);
    DBObject query = new BasicDBObject(BuguFS.FILENAME, filename);
    query.put(ImageUploader.DIMENSION, null); //note: this is necessary!
    String bucketName = GridFS.DEFAULT_BUCKET;
    int first = uri.indexOf(SLASH);
    if (first != last) {
        String sub = uri.substring(first + 1, last);
        String[] arr = sub.split(SLASH);
        for (int i = 0; i < arr.length; i += 2) {
            if (arr[i].equals(BuguFS.BUCKET)) {
                bucketName = arr[i + 1];
            } else {
                query.put(arr[i], arr[i + 1]);
            }
        }
    }
    //check if the bucket is allowed to access by this servlet
    if (!StringUtil.isEmpty(allowBucket) && !allowBucket.equalsIgnoreCase(bucketName)) {
        return;
    }
    if (!StringUtil.isEmpty(forbidBucket) && forbidBucket.equalsIgnoreCase(bucketName)) {
        return;
    }
    BuguFS fs = BuguFSFactory.getInstance().create(bucketName);
    GridFSDBFile f = fs.findOne(query);
    if (f == null) {
        return;
    }
    OutputStream os = response.getOutputStream();
    int fileLength = (int) f.getLength();
    String ext = StringUtil.getExtention(filename);
    response.setContentType(getContentType(ext));
    String range = request.getHeader("Range");
    //normal http request, no "range" in header.
    if (StringUtil.isEmpty(range)) {
        response.setStatus(HttpServletResponse.SC_OK);
        response.setContentLength(fileLength);
        if (needCache(ext)) {
            String modifiedSince = request.getHeader("If-Modified-Since");
            DateFormat df = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.ENGLISH);
            df.setTimeZone(TimeZone.getTimeZone("GMT"));
            Date uploadDate = f.getUploadDate();
            String lastModified = df.format(uploadDate);
            if (modifiedSince != null) {
                Date modifiedDate = null;
                Date sinceDate = null;
                try {
                    modifiedDate = df.parse(lastModified);
                    sinceDate = df.parse(modifiedSince);
                } catch (ParseException ex) {
                    logger.error("Can not parse the Date", ex);
                }
                if (modifiedDate.compareTo(sinceDate) <= 0) {
                    response.setStatus(304); //Not Modified
                    return;
                }
            }
            long maxAge = 365L * 24L * 60L * 60L; //one year, in seconds
            response.setHeader("Cache-Control", "max-age=" + maxAge);
            response.setHeader("Last-Modified", lastModified);
            response.setDateHeader("Expires", uploadDate.getTime() + maxAge * 1000L);
        } else {
            response.setHeader("Pragma", "no-cache");
            response.setHeader("Cache-Control", "no-cache");
            response.setDateHeader("Expires", 0);
        }
        f.writeTo(os);
    }
    //has "range" in header
    else {
        range = range.substring("bytes=".length());
        if (StringUtil.isEmpty(range)) {
            return;
        }
        int begin = 0;
        int end = fileLength - 1;
        boolean onlyLast = range.startsWith("-");
        String[] rangeArray = range.split("-");
        if (rangeArray.length == 1) {
            if (onlyLast) {
                begin = fileLength - Integer.parseInt(rangeArray[0]);
            } else {
                begin = Integer.parseInt(rangeArray[0]);
            }
        } else if (rangeArray.length == 2) {
            begin = Integer.parseInt(rangeArray[0]);
            end = Integer.parseInt(rangeArray[1]);
        }
        response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);
        int contentLength = end - begin + 1;
        response.setContentLength(contentLength);
        response.setHeader("Content-Range", "bytes " + begin + "-" + end + "/" + contentLength);
        InputStream is = f.getInputStream();
        is.skip(begin);
        int read = -1;
        int bufferSize = (int) f.getChunkSize();
        byte[] buffer = new byte[bufferSize];
        int remain = contentLength;
        int readSize = Math.min(bufferSize, remain);
        while ((read = is.read(buffer, 0, readSize)) != -1) {
            os.write(buffer, 0, read);
            remain -= read;
            if (remain <= 0) {
                break;
            }
            readSize = Math.min(bufferSize, remain);
        }
        StreamUtil.safeClose(is);
    }
    StreamUtil.safeClose(os);
}

From source file:com.englishtown.vertx.GridFSModule.java

License:Open Source License

public void saveFile(Message<JsonObject> message, JsonObject jsonObject) {

    ObjectId id = getObjectId(message, jsonObject, "id");
    if (id == null) {
        return;//  w  w  w  . ja v a  2  s  . c  om
    }

    Integer length = getRequiredInt("length", message, jsonObject, 1);
    if (length == null) {
        return;
    }

    Integer chunkSize = getRequiredInt("chunkSize", message, jsonObject, 1);
    if (chunkSize == null) {
        return;
    }

    long uploadDate = jsonObject.getLong("uploadDate", 0);
    if (uploadDate <= 0) {
        uploadDate = System.currentTimeMillis();
    }

    String filename = jsonObject.getString("filename");
    String contentType = jsonObject.getString("contentType");
    JsonObject metadata = jsonObject.getObject("metadata");

    try {
        BasicDBObjectBuilder builder = BasicDBObjectBuilder.start().add("_id", id).add("length", length)
                .add("chunkSize", chunkSize).add("uploadDate", new Date(uploadDate));

        if (filename != null)
            builder.add("filename", filename);
        if (contentType != null)
            builder.add("contentType", contentType);
        if (metadata != null)
            builder.add("metadata", JSON.parse(metadata.encode()));

        DBObject dbObject = builder.get();

        String bucket = jsonObject.getString("bucket", GridFS.DEFAULT_BUCKET);
        DBCollection collection = db.getCollection(bucket + ".files");

        // Ensure standard indexes as long as collection is small
        if (collection.count() < 1000) {
            collection.ensureIndex(BasicDBObjectBuilder.start().add("filename", 1).add("uploadDate", 1).get());
        }

        collection.save(dbObject);
        sendOK(message);

    } catch (Exception e) {
        sendError(message, "Error saving file", e);
    }
}

From source file:com.englishtown.vertx.GridFSModule.java

License:Open Source License

public void saveChunk(Message<Buffer> message, JsonObject jsonObject, byte[] data) {

    if (data == null || data.length == 0) {
        sendError(message, "chunk data is missing");
        return;/*from   ww  w . java 2  s.c o m*/
    }

    ObjectId id = getObjectId(message, jsonObject, "files_id");
    if (id == null) {
        return;
    }

    Integer n = getRequiredInt("n", message, jsonObject, 0);
    if (n == null) {
        return;
    }

    try {
        DBObject dbObject = BasicDBObjectBuilder.start().add("files_id", id).add("n", n).add("data", data)
                .get();

        String bucket = jsonObject.getString("bucket", GridFS.DEFAULT_BUCKET);
        DBCollection collection = db.getCollection(bucket + ".chunks");

        // Ensure standard indexes as long as collection is small
        if (collection.count() < 1000) {
            collection.ensureIndex(BasicDBObjectBuilder.start().add("files_id", 1).add("n", 1).get(),
                    BasicDBObjectBuilder.start().add("unique", 1).get());
        }

        collection.save(dbObject);
        sendOK(message);

    } catch (RuntimeException e) {
        sendError(message, "Error saving chunk", e);
    }

}

From source file:com.englishtown.vertx.GridFSModule.java

License:Open Source License

public void getFile(Message<JsonObject> message, JsonObject jsonObject) {

    ObjectId objectId = getObjectId(message, jsonObject, "id");
    if (objectId == null) {
        return;//from w  ww. j a v  a2  s.  c o m
    }

    // Optional bucket, default is "fs"
    String bucket = jsonObject.getString("bucket", GridFS.DEFAULT_BUCKET);
    GridFS files = new GridFS(db, bucket);

    GridFSDBFile file = files.findOne(objectId);
    if (file == null) {
        sendError(message, "File does not exist: " + objectId.toString());
        return;
    }

    JsonObject fileInfo = new JsonObject().putString("filename", file.getFilename())
            .putString("contentType", file.getContentType()).putNumber("length", file.getLength())
            .putNumber("chunkSize", file.getChunkSize())
            .putNumber("uploadDate", file.getUploadDate().getTime());

    DBObject metadata = file.getMetaData();
    if (metadata != null) {
        fileInfo.putObject("metadata", new JsonObject(JSON.serialize(metadata)));
    }

    // Send file info
    sendOK(message, fileInfo);

}

From source file:com.englishtown.vertx.GridFSModule.java

License:Open Source License

public void getChunk(Message<JsonObject> message, final JsonObject jsonObject) {

    ObjectId id = getObjectId(message, jsonObject, "files_id");

    Integer n = getRequiredInt("n", message, jsonObject, 0);
    if (n == null) {
        return;/*www.  ja v a 2 s  .co  m*/
    }

    String bucket = jsonObject.getString("bucket", GridFS.DEFAULT_BUCKET);

    DBCollection collection = db.getCollection(bucket + ".chunks");
    DBObject dbObject = BasicDBObjectBuilder.start("files_id", id).add("n", n).get();

    DBObject result = collection.findOne(dbObject);

    if (result == null) {
        message.reply(new byte[0]);
        return;
    }

    byte[] data = (byte[]) result.get("data");
    boolean reply = jsonObject.getBoolean("reply", false);
    Handler<Message<JsonObject>> replyHandler = null;

    if (reply) {
        replyHandler = new Handler<Message<JsonObject>>() {
            @Override
            public void handle(Message<JsonObject> reply) {
                int n = jsonObject.getInteger("n") + 1;
                jsonObject.putNumber("n", n);
                getChunk(reply, jsonObject);
            }
        };
    }

    // TODO: Change to reply with a Buffer instead of a byte[]?
    message.reply(data, replyHandler);

}

From source file:com.wavemaker.tools.io.mongo.MongoFolder.java

License:Open Source License

/**
 * Create a new {@link MongoFolder} using rhe specified mongo database. The data will be stored in
 * {@link GridFS#DEFAULT_BUCKET defaul bucket}.
 * //from  w  w w .  j a  v a2  s  .co m
 * @param db the mongo database
 */
public MongoFolder(DB db) {
    this(db, GridFS.DEFAULT_BUCKET);
}

From source file:net.ymate.platform.persistence.mongodb.impl.MongoGridFSSession.java

License:Apache License

public MongoGridFSSession(IMongoDataSourceAdapter dataSourceAdapter) throws Exception {
    this(dataSourceAdapter, GridFS.DEFAULT_BUCKET);
}

From source file:net.ymate.platform.persistence.mongodb.impl.MongoGridFSSession.java

License:Apache License

public MongoGridFSSession(IMongoDataSourceAdapter dataSourceAdapter, String bucketName) throws Exception {
    this.__id = UUIDUtils.UUID();
    this.__dataSourceHolder = dataSourceAdapter;
    this.__bucketName = StringUtils.defaultIfBlank(bucketName, GridFS.DEFAULT_BUCKET);
    ////  w  ww  .j a v  a 2  s.c om
    __gridFS = new GridFS(new DB(dataSourceAdapter.getMongoClient(),
            dataSourceAdapter.getDataSourceCfgMeta().getDatabaseName()), __bucketName);
    __dbCollection = __gridFS.getDB().getCollection(__bucketName.concat(".files"));
}