Example usage for com.mongodb.gridfs GridFSInputFile setMetaData

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

Introduction

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

Prototype

public void setMetaData(final DBObject metadata) 

Source Link

Document

Gets the file metadata.

Usage

From source file:com.bluedragon.mongo.gridfs.Add.java

License:Open Source License

public cfData execute(cfSession _session, cfArgStructData argStruct) throws cfmRunTimeException {

    // Get the necessary Mongo references
    DB db = getDB(_session, argStruct);/*from w  w w.  j  a v a 2 s.  c  o  m*/

    GridFS gridfs = getGridFS(_session, argStruct, db);
    GridFSInputFile fsInputFile = null;

    // Get the file information
    String filename = getNamedStringParam(argStruct, "filename", null);
    if (filename == null)
        throwException(_session, "please specify a filename");

    try {

        cfData ftmp = getNamedParam(argStruct, "file", null);
        if (ftmp.getDataType() == cfData.CFBINARYDATA) {
            fsInputFile = gridfs.createFile(((cfBinaryData) ftmp).getByteArray());
        } else {
            // The 'file' parameter is a string, which means it is a path to a file

            File inputFile = new File(ftmp.getString());
            if (!inputFile.exists())
                throwException(_session, "File:" + inputFile + " does not exist");

            if (!inputFile.isFile())
                throwException(_session, "File:" + inputFile + " is not a valid file");

            fsInputFile = gridfs.createFile(inputFile);
        }

    } catch (IOException e) {
        throwException(_session, e.getMessage());
    }

    fsInputFile.setFilename(filename);

    String contenttype = getNamedStringParam(argStruct, "contenttype", null);
    if (contenttype != null)
        fsInputFile.setContentType(contenttype);

    String _id = getNamedStringParam(argStruct, "_id", null);
    if (_id != null)
        fsInputFile.setId(_id);

    // Get and set the metadata
    cfData mTmp = getNamedParam(argStruct, "metadata", null);
    if (mTmp != null)
        fsInputFile.setMetaData(getDBObject(mTmp));

    // Save the Object
    try {
        fsInputFile.save();
        return new cfStringData(fsInputFile.getId().toString());
    } catch (MongoException me) {
        throwException(_session, me.getMessage());
        return null;
    }
}

From source file:com.edgytech.umongo.DbPanel.java

License:Apache License

public void uploadFile(final ButtonBase button) {
    final DbNode dbNode = getDbNode();
    final DB db = dbNode.getDb();

    final String path = getStringFieldValue(Item.uploadFilePath);
    if (path.isEmpty()) {
        return;//  ww  w.j  a  v  a 2 s. c o m
    }
    final File src = new File(path);
    final String fileName = getStringFieldValue(Item.uploadFileName);
    final String contentType = getStringFieldValue(Item.uploadContentType);
    final DBObject metadata = ((DocBuilderField) getBoundUnit(Item.uploadMetadata)).getDBObject();

    new DbJob() {

        @Override
        public Object doRun() throws IOException {
            final GridFSInputFile file = getGridFS().createFile(src);
            if (!fileName.isEmpty()) {
                file.setFilename(fileName);
            }
            if (!contentType.isEmpty()) {
                file.setContentType(contentType);
            }
            if (metadata != null) {
                file.setMetaData(metadata);
            }
            file.save();
            return file;
        }

        @Override
        public String getNS() {
            return db.getName();
        }

        @Override
        public String getShortName() {
            return "Upload File";
        }

        @Override
        public DBObject getRoot(Object result) {
            return new BasicDBObject("path", path);
        }

        @Override
        public void wrapUp(Object res) {
            super.wrapUp(res);
            // may have new collections
            dbNode.structureComponent();
        }

        @Override
        public ButtonBase getButton() {
            return button;
        }
    }.addJob();
}

From source file:com.englishtown.integration.java.IntegrationTestHelper.java

License:Open Source License

public static String createFile(JsonObject config, String bucket) {

    GridFS gridFS = IntegrationTestHelper.getGridFS(config, bucket);
    GridFSInputFile inputFile = gridFS
            .createFile(IntegrationTestHelper.class.getResourceAsStream("/EF_Labs_ENG_logo.JPG"));

    inputFile.setContentType(DEFAULT_CONTENT_TYPE);
    inputFile.setFilename(DEFAULT_FILENAME);
    inputFile.setChunkSize(DEFAULT_CHUNK_SIZE);
    inputFile.setMetaData(DEFAULT_METADATA);
    inputFile.save();/*from w w  w  .ja va  2 s. c  o  m*/

    return inputFile.getId().toString();
}

From source file:com.glaf.core.test.MongoDBGridFSThread.java

License:Apache License

public void run() {
    if (file.exists() && file.isFile()) {
        String path = file.getAbsolutePath();
        path = path.replace('\\', '/');
        if (StringUtils.contains(path, "/temp/") || StringUtils.contains(path, "/tmp/")
                || StringUtils.contains(path, "/logs/") || StringUtils.contains(path, "/work/")
                || StringUtils.endsWith(path, ".log") || StringUtils.endsWith(path, ".class")) {
            return;
        }//  w ww .j av a 2  s. com
        int retry = 0;
        boolean success = false;
        byte[] bytes = null;
        GridFSInputFile inputFile = null;
        while (retry < 1 && !success) {
            try {
                retry++;
                bytes = FileUtils.getBytes(file);
                if (bytes != null) {
                    inputFile = gridFS.createFile(bytes);
                    DBObject metadata = new BasicDBObject();
                    metadata.put("path", path);
                    metadata.put("filename", file.getName());
                    metadata.put("size", bytes.length);
                    inputFile.setMetaData(metadata);
                    inputFile.setId(path);
                    inputFile.setFilename(file.getName());// ??
                    inputFile.save();// ?
                    bytes = null;
                    success = true;
                    logger.debug(file.getAbsolutePath() + " save ok.");
                }
            } catch (Exception ex) {
                logger.error(ex);
                ex.printStackTrace();
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            } finally {
                bytes = null;
                inputFile = null;
            }
        }
    }
}

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

License:Apache License

/**
 * Gets the GFSInputFile from entity./*from www  .j  ava  2 s .com*/
 * 
 * @param gfs
 *            the gfs
 * @param m
 *            the m
 * @param entity
 *            the entity
 * @param kunderaMetadata
 *            the kundera metadata
 * @return the GFS iuput file from entity
 */
public GridFSInputFile getGFSInputFileFromEntity(GridFS gfs, EntityMetadata m, Object entity,
        KunderaMetadata kunderaMetadata, boolean isUpdate) {
    MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata()
            .getMetamodel(m.getPersistenceUnit());
    EntityType entityType = metaModel.entity(m.getEntityClazz());
    GridFSInputFile gridFSInputFile = null;

    DBObject gfsMetadata = new BasicDBObject();

    Set<Attribute> columns = entityType.getAttributes();
    for (Attribute column : columns) {
        boolean isLob = ((Field) column.getJavaMember()).getAnnotation(Lob.class) != null;
        if (isLob) {
            gridFSInputFile = createGFSInputFile(gfs, entity, (Field) column.getJavaMember());
            gridFSInputFile.setFilename(column.getName());
        } else {
            if (isUpdate && column.getName().equals(m.getIdAttribute().getName())) {
                gfsMetadata.put(((AbstractAttribute) column).getJPAColumnName(), new ObjectId());
            } else
                DocumentObjectMapper.extractFieldValue(entity, gfsMetadata, column);
        }
    }
    gridFSInputFile.setMetaData(gfsMetadata);
    return gridFSInputFile;
}

From source file:com.linuxbox.enkive.docstore.mongogrid.MongoGridDocStoreService.java

License:Open Source License

void setFileMetaData(GridFSInputFile newFile, Document document, int shardKey) {
    newFile.setContentType(document.getMimeType());

    // store the encoding as meta-data for EncodedDocuments
    DBObject metaData = newFile.getMetaData();
    if (metaData == null) {
        metaData = new BasicDBObject();
    }/*from   www. java 2s  .  c o  m*/

    metaData.put(INDEX_STATUS_KEY, STATUS_UNINDEXED);
    metaData.put(FILE_EXTENSION_KEY, document.getFileExtension());
    metaData.put(BINARY_ENCODING_KEY, document.getBinaryEncoding());
    metaData.put(INDEX_SHARD_KEY, shardKey);

    newFile.setMetaData(metaData);
}

From source file:com.mongo.gridfs.GridFSFileLoader.java

License:Open Source License

public void loadFile(String fileToLoad, String contentType, Map<String, String> metaData) {
    InputStream is = new GridFSFileValidator().loadFile(fileToLoad);
    GridFSInputFile file = gridfs.createFile(is);
    file.setContentType(contentType);/*  www.  j  a  v a2 s.  c  o  m*/
    file.setFilename(fileToLoad);
    BasicDBObject metadata = new BasicDBObject();
    if (metaData != null) {
        for (Entry<String, String> entry : metaData.entrySet()) {
            metadata.put(entry.getKey(), entry.getValue());
        }
    }
    file.setMetaData(metadata);
    file.save();
}

From source file:com.trenako.images.ImagesRepositoryImpl.java

License:Apache License

@Override
public void store(UploadFile file) {
    DBObject metadata = fillMetadata(file.getMetadata());

    GridFSInputFile f = getGridFs().createFile(file.getContent());
    f.setFilename(file.getFilename());/*from  w  ww . j  ava2s .c o m*/
    f.setMetaData(metadata);
    f.setContentType(file.getContentType());
    f.save();
}

From source file:eu.eubrazilcc.lvl.storage.mongodb.MongoDBConnector.java

License:EUPL

/**
 * Saves a file into the current database using the specified <tt>namespace</tt> and <tt>filename</tt>. All files sharing the same 
 * <tt>namespace</tt> and <tt>filename</tt> are considered versions of the same file. So, inserting a new file with an existing 
 * <tt>namespace</tt> and <tt>filename</tt> will create a new entry in the database. The method {@link #readFile(String, String)} will 
 * retrieve the latest version of the file and the method {@link #readFile(String, String)} will remove all the versions of the file. 
 * Other possible options could be to define a unique index in the <tt>files</tt> collection to avoid duplicates (versions) to be 
 * created: <code>createIndex("filename", namespace + ".files");</code>
 * @param namespace - (optional) name space under the file is saved. When nothing specified, the default bucket is used
 * @param filename - filename to be assigned to the file in the database
 * @param file - file to be saved to the database
 * @param metadata - optional file metadata
 * @return the id associated to the file in the collection
 *//*from   w  w  w. j a  va  2s  .c  o  m*/
public String saveFile(final @Nullable String namespace, final String filename, final File file,
        final @Nullable DBObject metadata) {
    checkArgument(isNotBlank(filename), "Uninitialized or invalid filename");
    checkArgument(file != null && file.canRead() && file.isFile(), "Uninitialized or invalid file");
    String objectId = null;
    final String namespace2 = trimToEmpty(namespace);
    final String filename2 = filename.trim();
    if (metadata != null) {
        metadata.removeField(IS_LATEST_VERSION_ATTR);
    }
    final DB db = client().getDB(CONFIG_MANAGER.getDbName());
    final GridFS gfsNs = isNotBlank(namespace2) ? new GridFS(db, namespace2) : new GridFS(db);
    // enforce isolation property: each namespace has its own bucket (encompassing 2 collections: files and chunks) and indexes in the database
    createSparseIndexWithUniqueConstraint(FILE_VERSION_PROP,
            gfsNs.getBucketName() + "." + GRIDFS_FILES_COLLECTION, false);
    // index open access links
    createNonUniqueIndex(FILE_OPEN_ACCESS_LINK_PROP, gfsNs.getBucketName() + "." + GRIDFS_FILES_COLLECTION,
            false);
    try {
        // insert new file/version in the database
        final GridFSInputFile gfsFile = gfsNs.createFile(file);
        gfsFile.setFilename(filename2);
        gfsFile.setContentType(mimeType(file));
        gfsFile.setMetaData(metadata);
        gfsFile.save();
        objectId = ObjectId.class.cast(gfsFile.getId()).toString();
        // unset the latest version in the database
        final GridFSDBFile latestVersion = getLatestVersion(gfsNs, filename2);
        if (latestVersion != null && latestVersion.getMetaData() != null) {
            latestVersion.getMetaData().removeField(IS_LATEST_VERSION_ATTR);
            latestVersion.save();
        }
    } catch (DuplicateKeyException dke) {
        throw new MongoDBDuplicateKeyException(dke.getMessage());
    } catch (IOException ioe) {
        throw new IllegalStateException("Failed to save file", ioe);
    } finally {
        // enforce versioning property by always restoring the latest version in the database
        restoreLatestVersion(gfsNs, filename2);
    }
    return objectId;
}

From source file:it.marcoberri.mbfasturl.action.Commons.java

License:Apache License

/**
 * //  w  w w.  j  ava 2s. co m
 * @param u
 * @param dimx
 * @param dimy
 * @return
 * @throws WriterException
 * @throws IOException
 */
public static String generateQrcode(Url u, int dimx, int dimy) throws WriterException, IOException {

    final String proxy = ConfigurationHelper.getProp().getProperty("url.proxy.domain", "http://mbfu.it/");
    final GridFS fs = MongoConnectionHelper.getGridFS();

    final QRCodeWriter writer = new QRCodeWriter();
    final BitMatrix bitMatrix = writer.encode(proxy + "/" + u.getFast(), BarcodeFormat.QR_CODE, dimx, dimy);
    final File temp = File.createTempFile("tempfile" + System.currentTimeMillis(), ".tmp");
    MatrixToImageWriter.writeToFile(bitMatrix, "gif", temp);

    final GridFSInputFile gfi = fs.createFile(temp);
    gfi.setFilename(u.getFast() + ".gif");

    final BasicDBObject meta = new BasicDBObject();
    meta.put("ref_url", u.getId());
    meta.put("created", new Date());
    gfi.setMetaData(meta);

    gfi.setContentType("image/gif");
    gfi.save();

    temp.deleteOnExit();

    return gfi.getId().toString();

}