Example usage for com.mongodb.gridfs GridFSInputFile getId

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

Introduction

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

Prototype

public Object getId() 

Source Link

Document

Gets the id.

Usage

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

License:Open Source License

/**
 * Spring GridFsTemplate./*from ww w  .  ja v a 2 s  .  co 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.exist.mongodb.xquery.gridfs.Store.java

License:Open Source License

@Override
public Sequence eval(Sequence[] args, Sequence contextSequence) throws XPathException {

    try {/* w  ww.  j  a v  a2s .  c om*/
        // Verify clientid and get client
        String mongodbClientId = args[0].itemAt(0).getStringValue();
        MongodbClientStore.getInstance().validate(mongodbClientId);
        MongoClient client = MongodbClientStore.getInstance().get(mongodbClientId);

        // Get parameters
        String dbname = args[1].itemAt(0).getStringValue();
        String bucket = args[2].itemAt(0).getStringValue();
        String documentName = args[3].itemAt(0).getStringValue();
        String contentType = getMimeType(args[4], documentName);

        LOG.info(String.format("Storing document %s (%s)", documentName, contentType));

        // Actual content: File object, doc() element, base64...
        Item content = args[5].itemAt(0);

        // Get database
        DB db = client.getDB(dbname);

        // Creates a GridFS instance for the specified bucket
        GridFS gfs = new GridFS(db, bucket);

        // Create file
        GridFSInputFile gfsFile = gfs.createFile();

        // Set meta data
        gfsFile.setFilename(documentName);
        gfsFile.setContentType(contentType);

        StopWatch stopWatch = new StopWatch();

        // Write data
        if (StringUtils.endsWithAny(documentName, nonCompressables)) {
            writeRaw(gfsFile, stopWatch, content);
        } else {
            int dataType = content.getType();
            writeCompressed(gfsFile, stopWatch, content, dataType);
        }

        LOG.info(String.format("serialization time: %s", stopWatch.getTime()));

        // Report identifier
        return new StringValue(gfsFile.getId().toString());

    } catch (XPathException ex) {
        LOG.error(ex.getMessage(), ex);
        throw new XPathException(this, ex.getMessage(), ex);

    } catch (MongoException ex) {
        LOG.error(ex.getMessage(), ex);
        throw new XPathException(this, GridfsModule.GRFS0002, ex.getMessage());

    } catch (Throwable ex) {
        LOG.error(ex.getMessage(), ex);
        throw new XPathException(this, GridfsModule.GRFS0003, ex.getMessage());
    }

}

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 ww  w  .ja  v a 2 s.c  om*/
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/*ww  w . java 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 w  w.j a v a  2s .  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;
}