Example usage for com.mongodb.gridfs GridFSInputFile getFilename

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

Introduction

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

Prototype

public String getFilename() 

Source Link

Document

Gets the filename.

Usage

From source file:com.ibm.ws.lars.rest.PersistenceBean.java

License:Apache License

/**
 * @param attachmentContentStream// w  ww  .j a v a2  s . co  m
 * @return
 */
@Override
public AttachmentContentMetadata createAttachmentContent(String name, String contentType,
        InputStream attachmentContentStream) {
    // Do not specify a bucket (so the data will be stored in fs.files and fs.chunks)
    GridFSInputFile gfsFile = gridFS.createFile(attachmentContentStream);
    ObjectId id = new ObjectId();
    gfsFile.setContentType(contentType);
    gfsFile.setId(id);
    String filename = id.toString();
    gfsFile.setFilename(filename);
    gfsFile.save();

    return new AttachmentContentMetadata(gfsFile.getFilename(), gfsFile.getLength());
}

From source file:com.imaginea.mongodb.services.GridFSServiceImpl.java

License:Apache License

/**
 * Service implementation for uploading a file to GridFS.
 *
 * @param dbName      Name of Database/*  ww  w .  ja v  a 2  s.c  o m*/
 * @param bucketName  Name of GridFS Bucket
 * @param formData    formDataBodyPart of the uploaded file
 * @param inputStream inputStream of the uploaded file
 * @param dbInfo      Mongo Db Configuration provided by user to connect to.
 * @returns Success message with additional file details such as name, size,
 * download url & deletion url as JSON Array string.
 */
public JSONArray insertFile(String dbName, String bucketName, String dbInfo, InputStream inputStream,
        FormDataBodyPart formData)
        throws DatabaseException, CollectionException, DocumentException, ValidationException {
    mongoInstance = mongoInstanceProvider.getMongoInstance();
    if (dbName == null) {
        throw new EmptyDatabaseNameException("Database name is null");

    }
    if (dbName.equals("")) {
        throw new EmptyDatabaseNameException("Database Name Empty");
    }

    if (bucketName == null) {
        throw new EmptyCollectionNameException("Bucket name is null");
    }
    if (bucketName.equals("")) {
        throw new EmptyCollectionNameException("Bucket Name Empty");
    }

    JSONArray result = new JSONArray();
    FormDataContentDisposition fileData = formData.getFormDataContentDisposition();
    try {
        if (!mongoInstance.getDatabaseNames().contains(dbName)) {
            throw new UndefinedDatabaseException("DB [" + dbName + "] DOES NOT EXIST");
        }

        GridFS gridFS = new GridFS(mongoInstance.getDB(dbName), bucketName);
        GridFSInputFile fsInputFile = gridFS.createFile(inputStream, fileData.getFileName());
        fsInputFile.setContentType(formData.getMediaType().toString());
        fsInputFile.save();
        JSONObject obj = new JSONObject();
        obj.put("name", fsInputFile.getFilename());
        obj.put("size", fsInputFile.getLength());
        obj.put("url", String.format("services/%s/%s/gridfs/getfile?id=%s&download=%s&dbInfo=%s&ts=%s", dbName,
                bucketName, fsInputFile.getId().toString(), false, dbInfo, new Date()));
        obj.put("delete_url", String.format("services/%s/%s/gridfs/dropfile?id=%s&dbInfo=%s&ts=%s", dbName,
                bucketName, fsInputFile.getId().toString(), dbInfo, new Date().getTime()));
        obj.put("delete_type", "GET");
        result.put(obj);

    } catch (Exception e) {
        CollectionException ce = new CollectionException(ErrorCodes.UPLOAD_FILE_EXCEPTION,
                "UPLOAD_FILE_EXCEPTION", e.getCause());
        throw ce;
    }
    return result;
}

From source file:com.impetus.client.mongodb.MongoDBClient.java

License:Apache License

/**
 * Save GRID FS file.//  w ww  .j ava  2s  .c  o m
 * 
 * @param gfsInputFile
 *            the gfs input file
 * @param m
 *            the m
 */
private void saveGridFSFile(GridFSInputFile gfsInputFile, EntityMetadata m) {
    try {
        DBCollection coll = mongoDb.getCollection(m.getTableName() + MongoDBUtils.FILES);
        createUniqueIndexGFS(coll, ((AbstractAttribute) m.getIdAttribute()).getJPAColumnName());
        gfsInputFile.save();
        log.info("Input GridFS file: " + gfsInputFile.getFilename() + " is saved successfully in "
                + m.getTableName() + MongoDBUtils.CHUNKS + " and metadata in " + m.getTableName()
                + MongoDBUtils.FILES);
    } catch (MongoException e) {
        log.error("Error in saving GridFS file in " + m.getTableName() + MongoDBUtils.FILES + " or "
                + m.getTableName() + MongoDBUtils.CHUNKS + " collections.");
        throw new KunderaException("Error in saving GridFS file in " + m.getTableName() + MongoDBUtils.FILES
                + " or " + m.getTableName() + MongoDBUtils.CHUNKS + " collections. Caused By: ", e);
    }
    try {
        gfsInputFile.validate();
        log.info("Input GridFS file: " + gfsInputFile.getFilename() + " is validated.");
    } catch (MongoException e) {
        log.error(
                "Error in validating GridFS file in " + m.getTableName() + MongoDBUtils.FILES + " collection.");
        throw new KunderaException("Error in validating GridFS file in " + m.getTableName() + MongoDBUtils.FILES
                + " collection. Caused By: ", e);
    }
}

From source file:oecp.framework.fs.gridfs.GridxFS.java

License:Apache License

public static void main(String[] args) {
    ApplicationContext context = new ClassPathXmlApplicationContext("classpath*:**/applicationcontext*.xml");

    GridxFS fs = (GridxFS) context.getBean("GridxFS");
    File file = new File("c:\\6302790910_c4eb865892_o.jpg");
    GridFSInputFile fsf = fs.save(file);
    String filename = fsf.getFilename();
    //       GridFSDBFile a = fs.findOne("6302790910_c4eb865892_o.jpg");
    System.out.println(filename);
    //       System.out.println(a.get("originalName"));
    //       fs.remove("abceee.jpg");
}

From source file:org.apache.camel.component.gridfs.GridFsProducer.java

License:Apache License

public void process(Exchange exchange) throws Exception {
    String operation = endpoint.getOperation();
    if (operation == null) {
        operation = exchange.getIn().getHeader(GridFsEndpoint.GRIDFS_OPERATION, String.class);
    }/*  ww  w  .j ava  2  s  . c o  m*/
    if (operation == null || "create".equals(operation)) {
        final String filename = exchange.getIn().getHeader(Exchange.FILE_NAME, String.class);
        Long chunkSize = exchange.getIn().getHeader(GridFsEndpoint.GRIDFS_CHUNKSIZE, Long.class);

        InputStream ins = exchange.getIn().getMandatoryBody(InputStream.class);
        GridFSInputFile gfsFile = endpoint.getGridFs().createFile(ins, filename, true);
        if (chunkSize != null && chunkSize > 0) {
            gfsFile.setChunkSize(chunkSize);
        }
        final String ct = exchange.getIn().getHeader(Exchange.CONTENT_TYPE, String.class);
        if (ct != null) {
            gfsFile.setContentType(ct);
        }
        String metaData = exchange.getIn().getHeader(GridFsEndpoint.GRIDFS_METADATA, String.class);
        DBObject dbObject = (DBObject) JSON.parse(metaData);
        gfsFile.setMetaData(dbObject);
        gfsFile.save();
        exchange.getIn().setHeader(Exchange.FILE_NAME_PRODUCED, gfsFile.getFilename());
    } else if ("remove".equals(operation)) {
        final String filename = exchange.getIn().getHeader(Exchange.FILE_NAME, String.class);
        endpoint.getGridFs().remove(filename);
    } else if ("findOne".equals(operation)) {
        final String filename = exchange.getIn().getHeader(Exchange.FILE_NAME, String.class);
        GridFSDBFile file = endpoint.getGridFs().findOne(filename);
        if (file != null) {
            exchange.getIn().setHeader(GridFsEndpoint.GRIDFS_METADATA, JSON.serialize(file.getMetaData()));
            exchange.getIn().setHeader(Exchange.FILE_CONTENT_TYPE, file.getContentType());
            exchange.getIn().setHeader(Exchange.FILE_LENGTH, file.getLength());
            exchange.getIn().setHeader(Exchange.FILE_LAST_MODIFIED, file.getUploadDate());
            exchange.getIn().setBody(file.getInputStream(), InputStream.class);
        } else {
            throw new FileNotFoundException("No GridFS file for " + filename);
        }
    } else if ("listAll".equals(operation)) {
        final String filename = exchange.getIn().getHeader(Exchange.FILE_NAME, String.class);
        DBCursor cursor;
        if (filename == null) {
            cursor = endpoint.getGridFs().getFileList();
        } else {
            cursor = endpoint.getGridFs().getFileList(new BasicDBObject("filename", filename));
        }
        exchange.getIn().setBody(new DBCursorFilenameReader(cursor), Reader.class);
    } else if ("count".equals(operation)) {
        final String filename = exchange.getIn().getHeader(Exchange.FILE_NAME, String.class);
        DBCursor cursor;
        if (filename == null) {
            cursor = endpoint.getGridFs().getFileList();
        } else {
            cursor = endpoint.getGridFs().getFileList(new BasicDBObject("filename", filename));
        }
        exchange.getIn().setBody(cursor.count(), Integer.class);
    }

}

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

License:Open Source License

public MuleMessage doSend(MuleEvent event) throws Exception {

    logger.debug("Attempting to evaluate endpoint: " + event.getEndpoint().getEndpointURI().toString());
    String evaluatedEndpoint = event.getMuleContext().getExpressionManager()
            .parse(event.getEndpoint().getEndpointURI().toString(), event.getMessage());

    logger.debug("Evaluated endpoint: " + evaluatedEndpoint);

    String destination = evaluatedEndpoint.split("://")[1];

    Object result;// ww w. j  ava  2s .  c  o m

    MuleMessage responseMessage;

    if (!destination.startsWith("bucket:")) {
        logger.debug("Dispatching to collection: " + destination);

        if (!endpoint.getProperties().containsKey("query")) {
            result = doDispatchToCollection(event, destination);
        } else {
            result = doQueryCollection(event, destination);
        }
        responseMessage = createMuleMessage(result);
    } else {
        result = doDispatchToBucket(event, destination.split("bucket:")[1]);
        responseMessage = createMuleMessage(result);
        GridFSInputFile file = (GridFSInputFile) result;
        if (StringUtils.isNotBlank(file.getFilename())) {
            responseMessage.setOutboundProperty("filename", file.getFilename());
        }
    }

    if (event.getMessage().getOutboundPropertyNames().contains(MongoDBConnector.PROPERTY_OBJECT_ID)) {
        responseMessage.setOutboundProperty(MongoDBConnector.PROPERTY_OBJECT_ID,
                event.getMessage().<Object>getOutboundProperty(MongoDBConnector.PROPERTY_OBJECT_ID));
    }
    return responseMessage;
}

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

License:Open Source License

protected Object doDispatchToBucket(MuleEvent event, String bucket) throws Exception {
    DB db;//  ww  w . ja  va2 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:xbdd.webapp.resource.feature.Report.java

License:Apache License

/**
 * go through all the embedded content, store it to GridFS, replace the doc embeddings with a hyperlink to the saved content.
 *///from  w  w  w  .j av  a2s  .  c  om
protected void embedSteps(final DBObject feature, final GridFS gridFS, final Coordinates coordinates) {
    final BasicDBList elements = (BasicDBList) feature.get("elements");
    final String featureId = (String) feature.get("_id");
    if (elements != null) {
        for (int j = 0; j < elements.size(); j++) {
            final DBObject scenario = (DBObject) elements.get(j);
            final String scenarioId = (String) scenario.get("_id");
            final BasicDBList steps = (BasicDBList) scenario.get("steps");
            if (steps != null) {
                for (int k = 0; k < steps.size(); k++) {
                    final DBObject step = (DBObject) steps.get(k);
                    final BasicDBList embeddings = (BasicDBList) step.get("embeddings");
                    if (embeddings != null) {
                        for (int l = 0; l < embeddings.size(); l++) {
                            final DBObject embedding = (DBObject) embeddings.get(l);
                            final GridFSInputFile image = gridFS.createFile(
                                    Base64.decodeBase64(((String) embedding.get("data")).getBytes()));
                            image.setFilename(guid());
                            final BasicDBObject metadata = new BasicDBObject()
                                    .append("product", coordinates.getProduct())
                                    .append("major", coordinates.getMajor())
                                    .append("minor", coordinates.getMinor())
                                    .append("servicePack", coordinates.getServicePack())
                                    .append("build", coordinates.getBuild()).append("feature", featureId)
                                    .append("scenario", scenarioId);
                            image.setMetaData(metadata);
                            image.setContentType((String) embedding.get("mime_type"));
                            image.save();
                            embeddings.put(l, image.getFilename());
                        }
                    }
                }
            }
        }
    }
}

From source file:xbdd.webapp.resource.feature.UploadAttachment.java

License:Apache License

@SuppressWarnings("unchecked")
@POST//from  w w  w .j a v  a2  s . co m
@Path("/{elementId}/{report}/{version}/{build}/{id}")
@Consumes(MediaType.MULTIPART_FORM_DATA)
public String setAttachment(@PathParam("report") final String report,
        @PathParam("version") final String version, @PathParam("build") final String build,
        @PathParam("id") final String id, @PathParam("elementId") final String elementId,
        @FormDataParam("attachmentfile") final File file,
        @FormDataParam("attachmentfile") final FormDataBodyPart body, @Context final HttpServletRequest req)
        throws IOException {
    try (final InputStream is = new FileInputStream(file.getAbsolutePath())) {
        final String elementIdMod = elementId.replace("&2F", "/");
        final DB gridDB = this.client.getDB("grid");
        final GridFS gridFS = new GridFS(gridDB);
        final GridFSInputFile gridFile = gridFS.createFile(is);
        gridFile.setFilename(
                body.getMediaType().toString().split("/")[0] + ".x1.mu." + UUID.randomUUID().toString());
        gridFile.setContentType(body.getMediaType().toString());
        gridFile.save();
        final DB bddDB = this.client.getDB("bdd");
        final DBCollection collection = bddDB.getCollection("features");
        // // get object
        final String featureId = report + "/" + version + "/" + build + "/" + id;
        final DBObject feature = collection.findOne(new BasicDBObject("_id", featureId));
        final BasicDBList elements = (BasicDBList) feature.get("elements");
        String scenarioName = "";
        if (elements != null) {
            for (int i = 0; i < elements.size(); i++) {
                final DBObject scenario = (DBObject) elements.get(i);
                if (scenario.get("id").equals(id + ";" + elementIdMod)) {
                    scenarioName = (String) scenario.get("name");
                    // get steps
                    final BasicDBList steps = (BasicDBList) scenario.get("steps");
                    final DBObject laststep = (DBObject) steps.get(steps.size() - 1);
                    List<String> embeddings = new ArrayList<String>();
                    if (laststep.containsField("embeddings")) {
                        embeddings = (ArrayList<String>) laststep.get("embeddings");
                    }
                    embeddings.add(gridFile.getFilename()); // get existng then add to them
                    laststep.put("embeddings", embeddings);
                    steps.set(steps.size() - 1, laststep);
                    scenario.put("steps", steps);
                    elements.set(i, scenario);
                }
            }
        }
        feature.put("elements", elements);
        feature.put("statusLastEditedBy", req.getRemoteUser());
        feature.put("lastEditOn", new Date());

        // add edit update
        BasicDBList edits = (BasicDBList) feature.get("edits");
        if (edits == null) {
            edits = new BasicDBList();
        }
        final BasicDBList temp = new BasicDBList();
        temp.add(new BasicDBObject().append("id", "embeddings").append("added", gridFile.getFilename())
                .append("removed", null));

        final BasicDBList masks = new BasicDBList();
        masks.add(new BasicDBObject().append("scenario", scenarioName).append("changes", temp));

        final BasicDBObject edit = new BasicDBObject().append("name", feature.get("statusLastEditedBy"))
                .append("date", feature.get("lastEditOn")).append("prev", feature.get("calculatedStatus"))
                .append("curr", feature.get("calculatedStatus")).append("stepChanges", masks);

        final BasicDBList newEdits = new BasicDBList();
        newEdits.add(edit);
        newEdits.addAll(edits);
        feature.put("edits", newEdits);

        collection.save(feature);
        return gridFile.getFilename();
    }
}