Example usage for com.mongodb.gridfs GridFSInputFile save

List of usage examples for com.mongodb.gridfs GridFSInputFile save

Introduction

In this page you can find the example usage for com.mongodb.gridfs GridFSInputFile save.

Prototype

@Override
public void save() 

Source Link

Document

Calls GridFSInputFile#save(long) with the existing chunk size.

Usage

From source file:org.bananaforscale.cormac.dao.gridfs.GridFsDataServiceImpl.java

License:Apache License

/**
 * Saves a document to the database by file name. If the document already exists this request
 * will be dropped and the existing file will not be overwritten.
 *
 * @param databaseName the database/*  ww  w .  j a v a 2  s .c  o m*/
 * @param bucketName the bucket
 * @param fileName the file name
 * @param inputStream the binary payload
 * @return the identifier of the file
 * @throws DatasourceException
 * @throws ExistsException
 * @throws NotFoundException
 */
@Override
public String addByFileName(String databaseName, String bucketName, String fileName, InputStream inputStream)
        throws DatasourceException, ExistsException, NotFoundException {
    try {
        if (!databaseExists(databaseName)) {
            throw new NotFoundException("The database doesn't exist in the datasource");
        }
        DB mongoDatabase = mongoClient.getDB(databaseName);
        GridFS gfsBucket = new GridFS(mongoDatabase, bucketName);
        if (gfsBucket.findOne(fileName) != null) {
            throw new ExistsException("The file already exists");
        }
        GridFSInputFile inputFile = gfsBucket.createFile(inputStream, fileName);
        inputFile.setContentType(tika.detect(fileName));
        inputFile.save();
        return inputFile.getId().toString();
    } catch (MongoException ex) {
        logger.error("An error occured while adding the file", ex);
        throw new DatasourceException("An error occured while adding the file");
    }
}

From source file:org.bananaforscale.cormac.dao.gridfs.GridFsDataServiceImpl.java

License:Apache License

/**
 * Updates a file in the database. If the file exists in the database it will be updated. If the
 * file doesn't exist it will be created.
 *
 * @param databaseName the database//  w ww.  j a  v a 2 s .  co m
 * @param bucketName the bucket
 * @param fileName the file name
 * @param inputStream the binary payload
 * @return the identifier of the file
 * @throws DatasourceException
 * @throws NotFoundException
 */
@Override
public String updateByFileName(String databaseName, String bucketName, String fileName, InputStream inputStream)
        throws DatasourceException, NotFoundException {
    try {
        if (!databaseExists(databaseName)) {
            throw new NotFoundException("The database doesn't exist in the datasource");
        }
        DB mongoDatabase = mongoClient.getDB(databaseName);
        GridFS gfsBucket = new GridFS(mongoDatabase, bucketName);
        GridFSDBFile gfsFile = gfsBucket.findOne(fileName);
        if (gfsFile == null) {
            GridFSInputFile inputFile = gfsBucket.createFile(inputStream, fileName);
            inputFile.setContentType(tika.detect(fileName));
            inputFile.save();
            return inputFile.getId().toString();
        } else {
            gfsBucket.remove(gfsFile);
            GridFSInputFile inputFile = gfsBucket.createFile(inputStream, fileName);
            inputFile.setContentType(tika.detect(fileName));
            inputFile.save();
            return inputFile.getId().toString();
        }
    } catch (MongoException ex) {
        logger.error("An error occured while updating the file", ex);
        throw new DatasourceException("An error occured while updating the file");
    }
}

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

License:Apache License

@Override
public FileId save(File file) throws SaveFailureStorageException {
    try {//from www  .j  a  v  a 2  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.craftercms.commons.mongo.AbstractJongoRepository.java

License:Open Source License

@Override
public FileInfo saveFile(final InputStream inputStream, final String storeName, final String contentType,
        final ObjectId fileId) throws MongoDataException, FileExistsException {
    try {/* ww w . ja v  a2 s .  com*/

        if (gridfs.findOne(storeName) != null) {
            log.error("A file named {} already exists", storeName);
            throw new FileExistsException("File with name " + storeName + " already Exists");
        }
        GridFSInputFile savedFile = gridfs.createFile(inputStream, storeName, true);
        savedFile.setContentType(contentType);
        if (fileId != null) {
            log.debug("Saving file with given Id {} probably a update", fileId);
            savedFile.setId(fileId);
        }
        savedFile.save();
        FileInfo fileInfo = new FileInfo(savedFile, false);
        log.debug("File {} was saved " + fileInfo);
        return fileInfo;
    } catch (MongoException ex) {
        log.error("Unable to save file");
        throw new MongoDataException("Unable to save file to GridFs", ex);
    }
}

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();
    return (ObjectId) gFSInputFile.getId();
}

From source file:org.craftercms.studio.impl.repository.mongodb.services.impl.GridFSServiceImpl.java

License:Open Source License

/**
 * Spring GridFsTemplate.//  w w w .j a v a 2s . c o  m
 */

@Override
public String createFile(final String fileName, final InputStream fileInputStream)
        throws MongoRepositoryException {
    if (StringUtils.isBlank(fileName)) {
        log.error("Given fileInputStream name is null, empty or blank");
        throw new IllegalArgumentException("File name is either null,empty or blank");
    }
    if (fileInputStream == null) {
        log.error("Given inputStream is null");
        throw new IllegalArgumentException("Given File inputStream is null");
    }
    try {

        GridFSInputFile file = gridFs.createFile(fileInputStream, fileName, true);
        file.save();
        return file.getId().toString();
    } catch (MongoException ex) {
        log.error("Unable to save \"" + fileName + "\"file in GridFs due a error", ex);
        throw new MongoRepositoryException(ex);
    }
}

From source file:org.exoplatform.mongo.service.impl.MongoRestServiceImpl.java

License:Open Source License

@POST
@Consumes("multipart/form-data")
@Path("/databases/{dbName}/collections/{collName}/binary")
@Override//from  w  w w .  java 2 s.  c o m
public Response createBinaryDocument(@PathParam("dbName") String dbName, @PathParam("collName") String collName,
        FormDataMultiPart document, @Context HttpHeaders headers, @Context UriInfo uriInfo,
        @Context SecurityContext securityContext) {
    if (shutdown) {
        return Response.status(ServerError.SERVICE_UNAVAILABLE.code())
                .entity(ServerError.SERVICE_UNAVAILABLE.message()).build();
    }
    Response response = null;
    String user = null;
    try {
        Credentials credentials = authenticateAndAuthorize(headers, uriInfo, securityContext);
        user = credentials.getUserName();
        FormDataBodyPart file = document.getField("file");
        String fileName = file.getContentDisposition().getFileName();
        InputStream fileStream = file.getEntityAs(InputStream.class);
        GridFSInputFile gridfsFile = gridFs.createFile(fileStream);
        gridfsFile.setFilename(fileName);
        gridfsFile.save();
        ObjectId documentId = (ObjectId) gridfsFile.getId();
        if (documentId != null && !StringUtils.isNullOrEmpty(documentId.toString())) {
            URI statusSubResource = uriInfo.getBaseUriBuilder().path(MongoRestServiceImpl.class)
                    .path("/databases/" + dbName + "/collections/" + collName + "/binary/" + documentId)
                    .build();
            response = Response.created(statusSubResource).build();
        } else {
            response = Response.status(ServerError.RUNTIME_ERROR.code())
                    .entity(ServerError.RUNTIME_ERROR.message()).build();
        }
    } catch (Exception exception) {
        response = lobException(exception, headers, uriInfo);
    } finally {
        updateStats(user, "createBinaryDocument");
    }
    return response;
}

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

License:Apache License

/**
 * Save the file into MongoDB using GridFS
 * @param fileName//  w  w w.  ja va2s  . 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.module.mongo.api.MongoClientImpl.java

License:Open Source License

public DBObject createFile(final InputStream content, final String filename, final String contentType,
        final DBObject metadata) {
    Validate.notNull(filename);//from  w  ww  .ja v  a  2s . c om
    Validate.notNull(content);
    final GridFSInputFile file = getGridFs().createFile(content);
    file.setFilename(filename);
    file.setContentType(contentType);
    if (metadata != null) {
        file.setMetaData(metadata);
    }
    file.save();
    return file;
}

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   www  . ja  v a  2  s  .c  o  m*/

    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;
}