Example usage for com.mongodb.gridfs GridFSInputFile setId

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

Introduction

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

Prototype

public void setId(final Object id) 

Source Link

Document

Sets the ID of this GridFS file.

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  ww w. j  a v a  2s  .  com*/

    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.fileoperations.CopyClass.java

public Boolean forSingleFile() {
    try {//from  w w  w .j a v a 2s  .  c o m
        if (name.contains(".")) {

            BasicDBObject query = new BasicDBObject();
            query.put("_id", parentPath + pathMerger + name);
            DBCursor cursor = collection.find(query);

            if (cursor.hasNext()) {
                BasicDBObject checknewquery = new BasicDBObject();
                checknewquery.put("_id", newPath + pathMerger + name);
                DBCursor tempCursor = collection.find(checknewquery);
                if (tempCursor.hasNext()) {
                    return false;
                }
                DBObject copyFile = cursor.next();
                GridFS fileDB = new GridFS(mymongo.getDB(), userCollectionName);
                InputStream data = fileDB.findOne(query).getInputStream();

                BasicDBObject document = new BasicDBObject();
                document.append("_id", newPath + pathMerger + name);
                document.append("folder", "0");
                document.append("parent", newPath);
                document.append("name", name);
                document.append("type", copyFile.get("type").toString());
                collection.insert(document);
                GridFSInputFile inputFile = fileDB.createFile(data);
                inputFile.setId(newPath + pathMerger + name);
                inputFile.put("path", newPath);
                inputFile.setFilename(name);
                inputFile.save();
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }
    } finally {
        mymongo.closeConnection();
    }
}

From source file:com.fileoperations.FolderDownload.java

public Boolean copyFolder(String newPath) throws IOException {
    try {/*from www . j a  v  a2  s .  co  m*/
        String mongoFolder = parentPath + pathMerger + folderName;

        BasicDBObject query = new BasicDBObject();
        query.put("_id", mongoFolder);
        DBCursor cursor = collection.find(query);
        if (cursor.hasNext()) {
            BasicDBObject newquery = new BasicDBObject();
            newquery.put("_id", newPath + pathMerger + folderName);
            if (collection.find(newquery).hasNext()) {
                return false;
            }

            getPathOfAllChildrenFolder(parentPath, folderName);
            BasicDBObject toFindAllFilesInFolder = new BasicDBObject();
            toFindAllFilesInFolder.put("$or", pathOfChildrenFolders);
            GridFS fileStore = new GridFS(mymongo.getDB(), userCollectionName);
            List<GridFSDBFile> AllFiles = fileStore.find(toFindAllFilesInFolder);

            for (int i = 0; i < AllFiles.size(); i++) {
                GridFSDBFile indivFile = AllFiles.get(i);
                InputStream data = indivFile.getInputStream();
                String zipPath;
                zipPath = indivFile.get("path").toString();
                String tempFileName = indivFile.getFilename();

                zipPath = zipPath.replaceFirst(parentPath, newPath);
                BasicDBObject document = new BasicDBObject();
                document.append("_id", zipPath + pathMerger + tempFileName);
                document.append("folder", "0");
                document.append("parent", zipPath);
                document.append("name", tempFileName);
                int index = tempFileName.lastIndexOf(".");
                document.append("type", tempFileName.substring(index));
                collection.insert(document);
                GridFSInputFile inputFile = fileStore.createFile(data);
                inputFile.setId(zipPath + pathMerger + tempFileName);
                inputFile.put("path", zipPath);
                inputFile.setFilename(tempFileName);
                inputFile.save();

            }

            BasicDBObject toFindAllEmptyFilesInFolder = new BasicDBObject();
            toFindAllEmptyFilesInFolder.put("$or", pathOfChildrenEmptyFolders);
            DBCursor allFolders = collection.find(toFindAllEmptyFilesInFolder);
            while (allFolders.hasNext()) {
                DBObject temp = allFolders.next();
                if (temp.get("folder").toString().equals("1")) {
                    String tempPath = temp.get("parent").toString().replaceFirst(parentPath, newPath);
                    BasicDBObject document = new BasicDBObject();
                    document.put("_id", tempPath + pathMerger + temp.get("name"));
                    document.put("folder", "1");
                    document.put("name", temp.get("name"));
                    document.put("parent", tempPath);
                    document.put("type", "1");
                    collection.insert(document);

                }
            }

            return true;
        } else {
            return false;
        }

    } finally {
        mymongo.closeConnection();
    }
}

From source file:com.fileoperations.FolderDownload.java

public Boolean renameFolder(String newName) throws IOException {
    try {/*from w  w w.j a v a2s .  com*/
        String mongoFolder = parentPath + pathMerger + folderName;
        BasicDBObject query = new BasicDBObject();
        query.put("_id", mongoFolder);
        DBCursor cursor = collection.find(query);
        if (cursor.hasNext()) {
            BasicDBObject newquery = new BasicDBObject();
            newquery.put("_id", parentPath + pathMerger + newName);
            if (collection.find(newquery).hasNext()) {
                return false;
            }
            BasicDBObject doc = new BasicDBObject();
            doc.put("_id", parentPath + pathMerger + newName);
            doc.put("folder", "1");
            doc.put("name", newName);
            doc.put("parent", parentPath);
            doc.put("type", "1");

            collection.insert(doc);

            getPathOfAllChildrenFolder(parentPath, folderName);
            BasicDBObject toFindAllFilesInFolder = new BasicDBObject();
            toFindAllFilesInFolder.put("$or", pathOfChildrenFolders);
            GridFS fileStore = new GridFS(mymongo.getDB(), userCollectionName);
            List<GridFSDBFile> AllFiles = fileStore.find(toFindAllFilesInFolder);

            for (int i = 0; i < AllFiles.size(); i++) {
                GridFSDBFile indivFile = AllFiles.get(i);
                InputStream data = indivFile.getInputStream();
                String zipPath;
                zipPath = indivFile.get("path").toString();
                String tempFileName = indivFile.getFilename();
                zipPath = zipPath.replaceFirst(parentPath + pathMerger + folderName,
                        parentPath + pathMerger + newName);
                BasicDBObject document = new BasicDBObject();
                document.append("_id", zipPath + pathMerger + tempFileName);
                document.append("folder", "0");
                document.append("parent", zipPath);
                document.append("name", tempFileName);
                int index = tempFileName.lastIndexOf(".");
                document.append("type", tempFileName.substring(index));
                collection.insert(document);
                GridFSInputFile inputFile = fileStore.createFile(data);
                inputFile.setId(zipPath + pathMerger + tempFileName);
                inputFile.put("path", zipPath);
                inputFile.setFilename(tempFileName);
                inputFile.save();

            }

            BasicDBObject toFindAllEmptyFilesInFolder = new BasicDBObject();
            toFindAllEmptyFilesInFolder.put("$or", pathOfChildrenEmptyFolders);
            DBCursor allFolders = collection.find(toFindAllEmptyFilesInFolder);
            while (allFolders.hasNext()) {
                DBObject temp = allFolders.next();
                if (temp.get("folder").toString().equals("1")) {
                    String tempPath = temp.get("parent").toString();
                    tempPath = tempPath.replaceFirst(parentPath + pathMerger + folderName,
                            parentPath + pathMerger + newName);
                    BasicDBObject updocument = new BasicDBObject();
                    updocument.put("_id", tempPath + pathMerger + temp.get("name"));
                    updocument.put("folder", "1");
                    updocument.put("name", temp.get("name"));
                    updocument.put("parent", tempPath);
                    updocument.put("type", "1");
                    collection.insert(updocument);

                }
            }

            return true;
        } else {
            return false;
        }

    } finally {
        mymongo.closeConnection();
    }
}

From source file:com.fileoperations.RenameFolder.java

public Boolean forSingleFile() {
    try {/*from   w  w w  . j  a va 2  s.co  m*/
        if (oldName.contains(".")) {

            BasicDBObject query = new BasicDBObject();
            query.put("_id", parentPath + pathMerger + oldName);
            DBCursor cursor = collection.find(query);

            if (cursor.hasNext()) {
                DBObject renameFile = cursor.next();
                BasicDBObject checknewquery = new BasicDBObject();
                checknewquery.put("_id", parentPath + pathMerger + newName + renameFile.get("type").toString());
                DBCursor tempCursor = collection.find(checknewquery);
                if (tempCursor.hasNext()) {
                    return false;
                }

                GridFS file = new GridFS(mymongo.getDB(), userCollectionName);
                InputStream data = file.findOne(query).getInputStream();

                BasicDBObject document = new BasicDBObject();
                document.append("_id", parentPath + pathMerger + newName + renameFile.get("type").toString());
                document.append("folder", "0");
                document.append("parent", parentPath);
                document.append("name", newName + renameFile.get("type").toString());
                document.append("type", renameFile.get("type").toString());
                collection.insert(document);
                GridFSInputFile inputFile = file.createFile(data);
                inputFile.setId(parentPath + pathMerger + newName + renameFile.get("type").toString());
                inputFile.put("path", parentPath);
                inputFile.setFilename(newName + renameFile.get("type").toString());
                inputFile.save();
                file.remove(file.findOne(query));
                collection.remove(renameFile);
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }
    } finally {
        mymongo.closeConnection();
    }
}

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;
        }/*from w  w w  . j av a  2  s .c o  m*/
        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.ibm.ws.lars.rest.PersistenceBean.java

License:Apache License

/**
 * @param attachmentContentStream/*from   w  ww  . j av a2 s.  c o 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.kurento.kmf.repository.internal.repoimpl.mongo.MongoRepository.java

License:Open Source License

@Override
public RepositoryItem createRepositoryItem(String id) {

    // TODO The file is not written until outputstream is closed. There is a
    // potentially data race with this unique test
    if (!gridFS.find(idQuery(id)).isEmpty()) {
        throw new DuplicateItemException(id);
    }//  w w w  .ja  va  2s  .  c  o  m

    GridFSInputFile dbFile = gridFS.createFile(id);
    dbFile.setId(id);
    return createRepositoryItem(dbFile);
}

From source file:fr.wseduc.gridfs.GridFSPersistor.java

License:Apache License

private void persistFile(Message<Buffer> message, byte[] data, JsonObject header) {
    GridFS fs = new GridFS(db, bucket);
    GridFSInputFile f = fs.createFile(data);
    String id = header.getString("_id");
    if (id == null || id.trim().isEmpty()) {
        id = UUID.randomUUID().toString();
    }//w  w w  .  ja  v  a2s. c  o m
    f.setId(id);
    f.setContentType(header.getString("content-type"));
    f.setFilename(header.getString("filename"));
    f.save();
    JsonObject reply = new JsonObject();
    reply.putString("_id", id);
    replyOK(message, reply);
}

From source file:fr.wseduc.resizer.GridFsFileAccess.java

License:Apache License

private GridFSInputFile saveFile(ImageFile img, String id, GridFS fs) {
    GridFSInputFile f = fs.createFile(img.getData());
    f.setId(id);
    f.setContentType(img.getContentType());
    f.setFilename(img.getFilename());/*w  ww . j ava 2s.  c  om*/
    f.save();
    return f;
}