Example usage for com.mongodb.gridfs GridFS createFile

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

Introduction

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

Prototype

public GridFSInputFile createFile(final String filename) 

Source Link

Document

Creates a file entry.

Usage

From source file:com.pubkit.platform.persistence.impl.ApplicationDaoImpl.java

License:Open Source License

public String saveFile(byte[] fileData, String fileName, String contentType) {
    GridFS gridFs = new GridFS(mongoTemplate.getDb(), PK_FILES_BUCKET);
    GridFSInputFile gfsFile = gridFs.createFile(fileData);

    gfsFile.setFilename(fileName);//from  w w w .j ava  2s. c  o  m
    gfsFile.setContentType(contentType);
    gfsFile.save();

    LOG.info("Saved new file :" + fileName);

    return gfsFile.getId().toString();
}

From source file:com.spring.tutorial.entitites.FileUploader.java

public String upload() throws IOException, ServletException, FacebookException {
    OutputStream output = null;/*  w ww  .j a va  2s . com*/
    InputStream fileContent = null;
    final Part filePart;

    final File file;
    try {
        filePart = request.getPart("file");

        fileContent = filePart.getInputStream();

        MongoClient mongoClient = new MongoClient();
        mongoClient = new MongoClient();
        DB db = mongoClient.getDB("fou");

        char[] pass = "mongo".toCharArray();
        boolean auth = db.authenticate("admin", pass);

        file = File.createTempFile("fileToStore", "tmp");

        file.deleteOnExit();
        FileOutputStream fout = new FileOutputStream(file);

        int read = 0;
        byte[] bytes = new byte[1024];

        while ((read = fileContent.read(bytes)) != -1) {
            fout.write(bytes, 0, read);
        }

        GridFS gridFS = new GridFS(db, request.getSession().getAttribute("id") + "_files");
        GridFSInputFile gfsInputFile = gridFS.createFile(file);
        gfsInputFile.setFilename(filePart.getSubmittedFileName());
        gfsInputFile.save();

        DBCollection collection = db.getCollection(request.getSession().getAttribute("id") + "_files_meta");
        BasicDBObject metaDocument = new BasicDBObject();
        metaDocument.append("name", filePart.getSubmittedFileName());
        metaDocument.append("size", filePart.getSize());
        metaDocument.append("content-type", filePart.getContentType());
        metaDocument.append("file-id", gfsInputFile.getId());
        metaDocument.append("tags", request.getParameter("tags"));
        metaDocument.append("description", request.getParameter("description"));

        DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");

        metaDocument.append("last_modified", dateFormat.format(new Date()));

        collection.insert(metaDocument);

    } catch (Exception e) {
        return "message:" + e.getMessage();
    } finally {
        if (output != null) {
            output.close();
        }
        if (fileContent != null) {
            fileContent.close();
        }
    }

    return "success";
}

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 ww.j av  a  2  s  . com*/
    //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:DataBase.JavaMongoDB.java

/**
 *
 * @param path/*from  w  w w  .j  av  a 2  s . c om*/
 * @param Basededatos
 * @param cubo
 * @param nombre
 */
public void InsertarAudio(String path, DB Basededatos, String cubo, String nombre) {
    GridFS gfsAudio;
    GridFSInputFile gfsFile;
    File imageFile;
    imageFile = new File(path);
    gfsAudio = new GridFS(Basededatos, cubo);
    try {
        gfsFile = gfsAudio.createFile(imageFile);
        String newFileName = nombre;
        gfsFile.setFilename(newFileName);
        gfsFile.save();

    } catch (IOException ex) {
        Logger.getLogger(JavaMongoDB.class.getName()).log(Level.SEVERE, null, ex);
    }

    //DBCollection collection = db.getCollection("Audio_meta");
    // collection.insert(info, WriteConcern.SAFE);
    //GridFS gfsAudioConsulta = new GridFS(db, "audio");
    //GridFSDBFile imageForOutput = gfsAudioConsulta.findOne("1073");
    //System.out.println(imageForOutput);
}

From source file:eu.eubrazilcc.lvl.storage.mongodb.MongoDBConnector.java

License:EUPL

/**
 * Saves a file into the current database using the specified <tt>namespace</tt> and <tt>filename</tt>. All files sharing the same 
 * <tt>namespace</tt> and <tt>filename</tt> are considered versions of the same file. So, inserting a new file with an existing 
 * <tt>namespace</tt> and <tt>filename</tt> will create a new entry in the database. The method {@link #readFile(String, String)} will 
 * retrieve the latest version of the file and the method {@link #readFile(String, String)} will remove all the versions of the file. 
 * Other possible options could be to define a unique index in the <tt>files</tt> collection to avoid duplicates (versions) to be 
 * created: <code>createIndex("filename", namespace + ".files");</code>
 * @param namespace - (optional) name space under the file is saved. When nothing specified, the default bucket is used
 * @param filename - filename to be assigned to the file in the database
 * @param file - file to be saved to the database
 * @param metadata - optional file metadata
 * @return the id associated to the file in the collection
 *///from  w w w.  jav a 2 s  . co m
public String saveFile(final @Nullable String namespace, final String filename, final File file,
        final @Nullable DBObject metadata) {
    checkArgument(isNotBlank(filename), "Uninitialized or invalid filename");
    checkArgument(file != null && file.canRead() && file.isFile(), "Uninitialized or invalid file");
    String objectId = null;
    final String namespace2 = trimToEmpty(namespace);
    final String filename2 = filename.trim();
    if (metadata != null) {
        metadata.removeField(IS_LATEST_VERSION_ATTR);
    }
    final DB db = client().getDB(CONFIG_MANAGER.getDbName());
    final GridFS gfsNs = isNotBlank(namespace2) ? new GridFS(db, namespace2) : new GridFS(db);
    // enforce isolation property: each namespace has its own bucket (encompassing 2 collections: files and chunks) and indexes in the database
    createSparseIndexWithUniqueConstraint(FILE_VERSION_PROP,
            gfsNs.getBucketName() + "." + GRIDFS_FILES_COLLECTION, false);
    // index open access links
    createNonUniqueIndex(FILE_OPEN_ACCESS_LINK_PROP, gfsNs.getBucketName() + "." + GRIDFS_FILES_COLLECTION,
            false);
    try {
        // insert new file/version in the database
        final GridFSInputFile gfsFile = gfsNs.createFile(file);
        gfsFile.setFilename(filename2);
        gfsFile.setContentType(mimeType(file));
        gfsFile.setMetaData(metadata);
        gfsFile.save();
        objectId = ObjectId.class.cast(gfsFile.getId()).toString();
        // unset the latest version in the database
        final GridFSDBFile latestVersion = getLatestVersion(gfsNs, filename2);
        if (latestVersion != null && latestVersion.getMetaData() != null) {
            latestVersion.getMetaData().removeField(IS_LATEST_VERSION_ATTR);
            latestVersion.save();
        }
    } catch (DuplicateKeyException dke) {
        throw new MongoDBDuplicateKeyException(dke.getMessage());
    } catch (IOException ioe) {
        throw new IllegalStateException("Failed to save file", ioe);
    } finally {
        // enforce versioning property by always restoring the latest version in the database
        restoreLatestVersion(gfsNs, filename2);
    }
    return objectId;
}

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

License:Apache License

private void persistFile(Message<Buffer> message, byte[] data, JsonObject header) {
    GridFS fs = new GridFS(db, bucket);
    GridFSInputFile f = fs.createFile(data);
    String id = header.getString("_id");
    if (id == null || id.trim().isEmpty()) {
        id = UUID.randomUUID().toString();
    }//  w  w  w  . j a v  a 2s  .c o  m
    f.setId(id);
    f.setContentType(header.getString("content-type"));
    f.setFilename(header.getString("filename"));
    f.save();
    JsonObject reply = new JsonObject();
    reply.putString("_id", id);
    replyOK(message, reply);
}

From source file:fr.wseduc.resizer.GridFsFileAccess.java

License:Apache License

private GridFSInputFile saveFile(ImageFile img, String id, GridFS fs) {
    GridFSInputFile f = fs.createFile(img.getData());
    f.setId(id);/*from w  w  w . j  a v a2 s  . com*/
    f.setContentType(img.getContentType());
    f.setFilename(img.getFilename());
    f.save();
    return f;
}

From source file:in.mtap.iincube.mongoapi.GridFsUpdater.java

License:Apache License

@Override
public Boolean execute() {
    GridFS gridFS = getGridFs();
    gridFS.remove(filename);/*from  w ww.j av  a2s  . co  m*/
    GridFSInputFile file = gridFS.createFile(stream);
    file.setContentType(contentType);
    file.setFilename(filename);
    file.save();
    return true;
}

From source file:in.mtap.iincube.mongoapi.GridFsWriter.java

License:Apache License

@Override
public Boolean execute() {
    GridFS gridFS = getGridFs();
    GridFSInputFile file = gridFS.createFile(stream);
    file.setFilename(filename);//from w ww. j  av  a2s  .com
    file.setContentType(contentType);
    file.save();
    return false;
}

From source file:io.liveoak.mongo.gridfs.GridFSBlobResource.java

License:Open Source License

private GridFSFilesPathItemResource pushToDB(RequestContext ctx, MediaType contentType, GridFSDBObject fileInfo,
        Supplier contentProvider) throws IOException {
    ObjectId currentId = fileInfo.getId();
    boolean fileExists = currentId != null;

    // update the targeted userspace - hopefully current user has rights to do that
    GridFS gridfs = getUserspace().getGridFS();

    Object content = contentProvider.get();
    GridFSInputFile blob;//ww w  .  ja  v a  2  s  . c  o m
    if (fileExists) {
        // here is a time gap when file doesn't exist for a while when being updated.
        // making the switch instantaneous would require another layer of indirection
        // - not using file_id as canonical id, but some other id, mapped to a file.
        // there would still remain a moment between mapping from old file to new file
        // involving two separate file items and a moment in time when during a switch
        // no file would match a filename, nor file id.
        gridfs.remove(currentId);
    }
    if (content instanceof File) {
        blob = gridfs.createFile((File) content);
    } else if (content instanceof InputStream) {
        blob = gridfs.createFile((InputStream) content);
    } else if (content instanceof ByteBuf) {
        blob = gridfs.createFile(((ByteBuf) content).array());
    } else {
        throw new IllegalArgumentException("Unsupported value supplied: " + content.getClass());
    }

    // meta data
    if (fileExists) {
        blob.setId(currentId);
    }
    blob.setFilename(fileInfo().getString("filename"));
    blob.setContentType(contentType != null ? contentType.toString() : "application/octet-stream");
    blob.put("parent", fileInfo().getParentId());
    blob.save();

    String oid = blob.getId().toString();

    return new GridFSFilesPathItemResource(ctx, getFilesRoot(), oid, new GridFSDBObject(blob),
            GridFSResourcePath.fromContext(ctx));
}