Example usage for com.mongodb.gridfs GridFSInputFile setContentType

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

Introduction

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

Prototype

public void setContentType(final String contentType) 

Source Link

Document

Sets the content type (MIME type) on the GridFS entry.

Usage

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

        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();// w  ww. j av  a 2s  .c om
    return (ObjectId) gFSInputFile.getId();
}

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 {//from   ww w.ja  v  a2 s. com
        // 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.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 va 2 s.co m
    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.  j a  va 2  s .co 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;
}

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());//from   ww w . j  a  v a2  s .  c  om

    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.springframework.data.mongodb.gridfs.GridFsTemplate.java

License:Apache License

public GridFSFile store(InputStream content, String filename, String contentType, DBObject metadata) {

    Assert.notNull(content);//from  ww w . j a v a 2  s  .c  o m

    GridFSInputFile file = getGridFs().createFile(content);

    if (filename != null) {
        file.setFilename(filename);
    }

    if (metadata != null) {
        file.setMetaData(metadata);
    }

    if (contentType != null) {
        file.setContentType(contentType);
    }

    file.save();
    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.
 *///w ww.j  ava2  s  .  com
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/*  ww  w .j  a va 2  s.com*/
@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();
    }
}