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:org.aw20.mongoworkbench.command.GridFSPutFileCommand.java

License:Open Source License

@Override
public void execute() throws Exception {
    MongoClient mdb = MongoFactory.getInst().getMongo(sName);

    if (mdb == null)
        throw new Exception("no server selected");

    if (sDb == null)
        throw new Exception("no database selected");

    MongoFactory.getInst().setActiveDB(sDb);
    DB db = mdb.getDB(sDb);//from   w  w w .ja va  2 s. c  o m

    GridFS gfs = new GridFS(db, sColl.substring(0, sColl.lastIndexOf(".")));

    GridFSInputFile gridFSInputFile = gfs.createFile(getFile);
    gridFSInputFile.setContentType(MimetypesFileTypeMap.getDefaultFileTypeMap().getContentType(getFile));
    gridFSInputFile.save();

    setMessage("fileLoaded=" + getFile + "; size=" + getFile.length());
}

From source file:org.chimi.s4s.storage.mongofs.MongoFSFileStorage.java

License:Apache License

@Override
public FileId save(File file) throws SaveFailureStorageException {
    try {//w ww . j  a v  a2  s  .c  om
        DB storageDb = mongo.getDB(db);
        GridFS gridFS = new GridFS(storageDb);
        GridFSInputFile gridFile = gridFS.createFile(file);
        gridFile.save();
        return new FileId(gridFile.getId().toString());
    } catch (IOException e) {
        throw new SaveFailureStorageException(e);
    }
}

From source file:org.cleaner.main.GridFSFileLoader.java

License:Open Source License

@SuppressWarnings("deprecation")
public static void main(String[] args) throws IOException {
    try (MongoClient mc = new MongoClient()) {
        DB db = mc.getDB("gridfs");
        GridFS gfs = new GridFS(db);
        try (DirectoryStream<Path> stream = Files.newDirectoryStream(Paths.get(DIRECTORY_TO_LOAD))) {
            for (Path entry : stream) {
                File file = entry.toFile();
                if (file.isDirectory())
                    continue;
                else
                    gfs.createFile(file).save();
            }/* ww  w . jav a2s  .  c  o m*/
        }

    }

}

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

License:Open Source License

@Override
public ObjectId saveFile(MultipartFile file) throws IOException {
    GridFS gFS = new GridFS(mongoTemplate.getDb());
    GridFSInputFile gFSInputFile = gFS.createFile(file.getInputStream());
    gFSInputFile.setFilename(file.getOriginalFilename());
    gFSInputFile.setContentType(file.getContentType());
    gFSInputFile.save();//from w  w w .j a v  a2 s. c o m
    return (ObjectId) gFSInputFile.getId();
}

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

License:Apache License

/**
 * Save the file into MongoDB using GridFS
 * @param fileName/*from w  w w  .  j a  va  2 s .c o m*/
 * @return
 * @throws IOException
 */
public Object saveLargeFile(String fileName) throws IOException {
    System.out.println("\n== ==  WRITE IN GRIFS / MONGODB  == == == ");
    GridFS fs = new GridFS(db);
    // large file
    byte[] fileAsBytes = extractBytes(fileName);
    GridFSInputFile in = fs.createFile(fileAsBytes);
    in.save();
    System.out.println("File ID : " + in.getId());
    System.out.println("\n== ==  == == == ");
    return in.getId();
}

From source file:org.mule.transport.mongodb.MongoDBMessageDispatcher.java

License:Open Source License

protected Object doDispatchToBucket(MuleEvent event, String bucket) throws Exception {
    DB db;//from  w  ww  . j  av  a2 s.  c om

    if (StringUtils.isNotBlank(connector.getMongoURI().getDatabase())) {
        db = connector.getMongo().getDB(connector.getMongoURI().getDatabase());

    } else {
        db = connector.getMongo().getDB(connector.getMongoURI().getDatabase());
    }

    GridFS gridFS = new GridFS(db, bucket);

    db.requestStart();

    Object payload = event.getMessage().getPayload();

    GridFSInputFile file = null;

    if (payload instanceof File) {
        file = gridFS.createFile((File) payload);
    }

    if (payload instanceof InputStream) {
        file = gridFS.createFile((InputStream) payload);
    }

    if (payload instanceof byte[]) {
        file = gridFS.createFile((byte[]) payload);
    }

    if (payload instanceof String) {
        file = gridFS.createFile(((String) payload).getBytes());
    }

    if (file == null) {
        throw new MongoDBException(
                String.format("Cannot persist objects of type %s to GridFS", payload.getClass()));
    }

    String filename = event.getMessage().getOutboundProperty(MongoDBConnector.PROPERTY_FILENAME, "");

    if (StringUtils.isNotBlank(filename)) {
        logger.debug("Setting filename on GridFS file to: " + filename);
        file.setFilename(filename);
    }

    String contentType = event.getMessage().getOutboundProperty(MongoDBConnector.PROPERTY_CONTENT_TYPE, "");

    if (StringUtils.isBlank(contentType) && event.getEndpoint().getProperties().containsKey("contentType")) {
        contentType = (String) event.getEndpoint().getProperty("contentType");
    }

    if (StringUtils.isNotBlank(contentType)) {
        logger.debug("Setting contentType on GridFS file to: " + contentType);
        file.setContentType(contentType);
    }

    logger.debug("Attempting to save file: " + file.getFilename());

    Date startTime = new Date();
    file.save();
    Date endTime = new Date();

    long elapsed = endTime.getTime() - startTime.getTime();

    logger.debug(String.format("GridFS file %s saved in %s seconds", file.getId(), elapsed / 1000.0));

    try {
        file.validate();
    } catch (MongoException ex) {
        if (ex.getMessage().startsWith("md5 differ")) {
            logger.error("MD5 checksum mismatch while saving the file. "
                    + "This may be the real deal or is possibly an issue that keeps recurring with"
                    + " some releases of the Java driver ");
        }
    }

    ObjectId id = (ObjectId) file.getId();
    event.getMessage().setOutboundProperty(MongoDBConnector.PROPERTY_OBJECT_ID, id.toStringMongod());

    db.requestDone();

    return file;
}

From source file:org.s1.mongodb.cluster.GridFSFileStorage.java

License:Apache License

@Override
public FileStorage.FileWriteBean createFileWriteBean(Id id, FileStorage.FileMetaBean meta) {
    meta.setLastModified(new Date());
    meta.setCreated(new Date());
    GridFS fs = new GridFS(MongoDBConnectionHelper.getConnection(id.getDatabase()), id.getCollection());
    fs.remove(id.getEntity());//www . j  a  v a2s.c o m

    GridFSInputFile gfsFile = fs.createFile(id.getEntity());
    gfsFile.setContentType(meta.getContentType());
    gfsFile.setMetaData(MongoDBFormat.fromMap(meta.toMap()));

    GridFSFileWriteBean gridFSFileWriteBean = new GridFSFileWriteBean(id, gfsFile.getOutputStream(), meta);
    gridFSFileWriteBean.gfsFile = gfsFile;
    return gridFSFileWriteBean;
}

From source file:org.sipfoundry.commons.userdb.profile.UserProfileServiceImpl.java

License:Open Source License

@Override
public void saveAvatar(String userName, InputStream originalIs) throws AvatarUploadException {
    ByteArrayOutputStream os = null;
    InputStream is = null;//from w w  w.ja  v  a  2s . c o  m
    try {
        BufferedImage originalImage = ImageIO.read(originalIs);
        BufferedImage thumbnail = Thumbnails.of(originalImage).crop(Positions.CENTER).size(128, 128)
                .asBufferedImage();
        os = new ByteArrayOutputStream();
        ImageIO.write(thumbnail, "png", os);
        is = new ByteArrayInputStream(os.toByteArray());
        String fileName = String.format(AVATAR_NAME, userName);
        GridFS avatarFS = new GridFS(m_template.getDb());
        avatarFS.remove(fileName);
        GridFSInputFile gfsFile = avatarFS.createFile(is);
        gfsFile.setFilename(fileName);
        gfsFile.save();
    } catch (Exception ex) {
        throw new AvatarUploadException(ex);
    } finally {
        IOUtils.closeQuietly(originalIs);
        IOUtils.closeQuietly(is);
        IOUtils.closeQuietly(os);
    }
}

From source file:org.teiid.translator.mongodb.MongoDBExecutionFactory.java

License:Open Source License

/**
 * Mongodb only supports certain data types, Teiid need to serialize them in other compatible
 * formats, and convert them back while reading them.
 * @param value//from   w  w w .j  av a 2 s.c o  m
 * @return
 */
public Object convertToMongoType(Object value, DB mongoDB, String fqn) throws TranslatorException {
    if (value == null) {
        return null;
    }

    try {
        if (value instanceof BigDecimal) {
            return ((BigDecimal) value).doubleValue();
        } else if (value instanceof BigInteger) {
            return ((BigInteger) value).doubleValue();
        } else if (value instanceof Character) {
            return ((Character) value).toString();
        } else if (value instanceof java.sql.Date) {
            return new java.util.Date(((java.sql.Date) value).getTime());
        } else if (value instanceof java.sql.Time) {
            return new java.util.Date(((java.sql.Time) value).getTime());
        } else if (value instanceof java.sql.Timestamp) {
            return new java.util.Date(((java.sql.Timestamp) value).getTime());
        } else if (value instanceof BinaryType) {
            return new Binary(((BinaryType) value).getBytes());
        } else if (value instanceof byte[]) {
            return new Binary((byte[]) value);
        } else if (value instanceof Blob) {
            String uuid = UUID.randomUUID().toString();
            GridFS gfs = new GridFS(mongoDB, fqn);
            GridFSInputFile gfsFile = gfs.createFile(((Blob) value).getBinaryStream());
            gfsFile.setFilename(uuid);
            gfsFile.save();
            return uuid;
        } else if (value instanceof Clob) {
            String uuid = UUID.randomUUID().toString();
            GridFS gfs = new GridFS(mongoDB, fqn);
            GridFSInputFile gfsFile = gfs.createFile(((Clob) value).getAsciiStream());
            gfsFile.setFilename(uuid);
            gfsFile.save();
            return uuid;
        } else if (value instanceof SQLXML) {
            String uuid = UUID.randomUUID().toString();
            GridFS gfs = new GridFS(mongoDB, fqn);
            GridFSInputFile gfsFile = gfs.createFile(((SQLXML) value).getBinaryStream());
            gfsFile.setFilename(uuid);
            gfsFile.save();
            return uuid;
        } else if (value instanceof Object[]) {
            BasicDBList list = new BasicDBList();
            for (Object obj : (Object[]) value) {
                list.add(obj);
            }
            return list;
        }
        return value;
    } catch (SQLException e) {
        throw new TranslatorException(e);
    }
}

From source file:rmi_video.VideoServer.java

@Override
public boolean addVideo(VideoData d) throws RemoteException {
    try {/*from w  w  w.  ja  v a2  s  .  c o m*/
        //Conexao com mongoDB
        MongoClient mongoClient = new MongoClient("localhost", 27017);
        DB db = mongoClient.getDB("VideoDatabase");

        try (FileOutputStream fos = new FileOutputStream("/Users/philcr/Documents/" + d.getFileName())) {
            fos.write(d.getData());
        }

        File videoFile = new File("/Users/philcr/Documents/" + d.getFileName());

        GridFS gfsVideo = new GridFS(db, "video");

        //Cria e salva o arquivo no DB pelo GridFS
        GridFSInputFile gfsFile = gfsVideo.createFile(videoFile);
        gfsFile.setId(new ObjectId()); //Utiliza a criao de ID do mongo
        gfsFile.put("videoId", d.getId()); //Utiliza nosso metodo de ID
        gfsFile.setFilename(d.getFileName());
        gfsFile.save();

        //Exclui o arquivo local
        boolean deletedFlag = videoFile.delete();
        if (!deletedFlag) {
            System.err.println("File could not be deleted!");
        }

        mongoClient.close();

        return true;

    } catch (UnknownHostException ex) {
        Logger.getLogger(VideoServer.class.getName()).log(Level.SEVERE, null, ex);
        return false;
    } catch (FileNotFoundException ex) {
        Logger.getLogger(VideoServer.class.getName()).log(Level.SEVERE, null, ex);
        return false;
    } catch (IOException ex) {
        Logger.getLogger(VideoServer.class.getName()).log(Level.SEVERE, null, ex);
        return false;
    }
}