Example usage for com.mongodb.gridfs GridFSDBFile getInputStream

List of usage examples for com.mongodb.gridfs GridFSDBFile getInputStream

Introduction

In this page you can find the example usage for com.mongodb.gridfs GridFSDBFile getInputStream.

Prototype

public InputStream getInputStream() 

Source Link

Document

Returns an InputStream from which data can be read.

Usage

From source file:com.cognifide.aet.vs.artifacts.ArtifactsDAOMongoDBImpl.java

License:Apache License

@Override
public Artifact getArtifact(DBKey dbKey, String objectID) {
    Artifact artifact = null;/* w  w  w. j  a va 2s .c om*/

    GridFS gfs = getGridFS(dbKey);
    if (gfs != null) {
        BasicDBObject query = new BasicDBObject();
        query.put(ID_FIELD_NAME, new ObjectId(objectID));
        GridFSDBFile file = gfs.findOne(query);
        if (file != null) {
            artifact = new Artifact(file.getInputStream(), file.getContentType());
        }
    }
    return artifact;
}

From source file:com.epam.ta.reportportal.database.GridFSDataStorage.java

License:Open Source License

@Override
public BinaryData fetchData(String dataId) {
    GridFSDBFile file = gridFs.findOne(findByIdQuery(new ObjectId(dataId)));
    return null == file ? null : new BinaryData(file.getContentType(), file.getLength(), file.getInputStream());
}

From source file:com.fileoperations.FolderDownload.java

public File makeFolder() throws IOException {
    try {/*from   ww  w .ja  v  a  2 s. c  o m*/
        String mongoFolder = parentPath + pathMerger + folderName;
        BasicDBObject query = new BasicDBObject();
        query.put("_id", mongoFolder);
        DBCursor cursor = collection.find(query);
        if (cursor.hasNext()) {

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

            for (int i = 0; i < AllFiles.size(); i++) {
                GridFSDBFile indivFile = AllFiles.get(i);
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                InputStream in = indivFile.getInputStream();
                int data = in.read();
                while (data >= 0) {
                    out.write((char) data);
                    data = in.read();
                }

                out.flush();
                String zipPath;
                zipPath = indivFile.get("path").toString() + pathMerger + indivFile.getFilename();
                zipPath = zipPath.replaceFirst(parentPath, "");
                zipPath = zipPath.replaceFirst(pathMerger, "");
                ZipEntry add = new ZipEntry(zipPath);
                folderToZip.putNextEntry(add);
                folderToZip.write(out.toByteArray(), 0, out.toByteArray().length);

            }

            BasicDBObject toFindAllEmptyFilesInFolder = new BasicDBObject();
            toFindAllEmptyFilesInFolder.put("$or", pathOfChildrenEmptyFolders);
            DBCursor emptyFolder = collection.find(toFindAllEmptyFilesInFolder);
            List<String> emptyFolderPathToAdd = new ArrayList<String>();
            while (emptyFolder.hasNext()) {
                DBObject temp = emptyFolder.next();
                BasicDBObject isEmpty = new BasicDBObject();
                isEmpty.put("parent", temp.get("_id").toString());

                if (!collection.find(isEmpty).hasNext()) {
                    if (!temp.get("_id").toString().contains(".")) {
                        emptyFolderPathToAdd.add(temp.get("_id").toString());
                    }
                }

            }
            for (int i = 0; i < emptyFolderPathToAdd.size(); i++) {
                String temp = emptyFolderPathToAdd.get(i).replaceFirst(parentPath, "");
                temp = temp.replaceFirst(pathMerger, "");
                ZipEntry add = new ZipEntry(temp + pathMerger);
                folderToZip.putNextEntry(add);

            }

            folderToZip.closeEntry();
            folderToZip.close();
            return zip;
        } else {
            return null;
        }

    } finally {
        mymongo.closeConnection();
    }

}

From source file:com.fileoperations.FolderDownload.java

public Boolean copyFolder(String newPath) throws IOException {
    try {/* w  ww  .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  www . j  a v  a2s .  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", 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.fliker.Modal.OSMPreview.java

public byte[] imagefromid(String imageId) {

    CoursePreview courseprev = new CoursePreview();
    GridFSDBFile imagecontent = courseprev.getFiles(imageId);
    System.out.println("imagecontent ++" + imagecontent.getInputStream());
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    try {//from   w w w  .jav  a 2  s  .  c  o  m
        imagecontent.writeTo(baos);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    byte[] imageblob = baos.toByteArray();

    return imageblob;
}

From source file:com.hangum.tadpole.mongodb.core.query.MongoDBQuery.java

License:Open Source License

/**
 * get gridfs data//from w  w  w  .  j  a  va  2 s . c o m
 * 
 * @param userDB
 * @param _id
 * @return 
 * @throws Exception
 */
public static byte[] getGridFS(UserDBDAO userDB, String strBucket, String _id) throws Exception {
    DB mongoDb = findDB(userDB);
    GridFS gridFs = null;

    if ("".equals(strBucket))
        gridFs = new GridFS(mongoDb);
    else
        gridFs = new GridFS(mongoDb, strBucket);

    GridFSDBFile gridFSFile = gridFs.findOne(new ObjectId(_id));
    InputStream is = gridFSFile.getInputStream();
    return IOUtils.toByteArray(is);
}

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

License:Apache License

/**
 * Returns an InputStream of the content of the attachment or null if the attachment does not
 * exist.//ww  w .jav  a 2s  .  com
 *
 * @throws NonExistentArtefactException
 */
@Override
public AttachmentContentResponse retrieveAttachmentContent(String gridFSId)
        throws NonExistentArtefactException {
    GridFSDBFile file = gridFS.findOne(gridFSId);

    if (file != null) {
        InputStream contentStream = file.getInputStream();
        String contentType = file.getContentType();
        return new AttachmentContentResponse(contentStream, contentType);
    } else {
        throw new NonExistentArtefactException();
    }
}

From source file:com.ikanow.infinit.e.harvest.extraction.document.file.InternalInfiniteFile.java

License:Open Source License

@Override
public InputStream getInputStream() throws IOException {
    if (!_isDirectory) {
        if (_isShare && (null == _zipView)) {
            String jsonShare = (String) _resultObj.get(SharePojo.share_);
            if (null != jsonShare) {
                return new ByteArrayInputStream(jsonShare.toString().getBytes());
            } //TESTED (1.4)
            else { // must be binary
                GridFSDBFile file = DbManager.getSocial().getShareBinary()
                        .find(_resultObj.getObjectId(SharePojo.binaryId_));
                return file.getInputStream();
            } //TESTED (2.4)
        } else if (_isShare) { // then must be a zip file
            try {
                return _zipView.getInputStream(_zipEntry);
            } catch (IOException e) {
                throw new FileNotFoundException(e.getMessage());
            }//from  w  ww  .  j a  v a 2  s.  c o m
        } //TESTED (3.2.1)
        else if (_isCustom) {
            return new ByteArrayInputStream(_resultObj.toString().getBytes());
        } //TESTED (4.2.1)
    }
    return null;
}

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

License:Apache License

/**
 * Gets the entity from GFSDBFile./*from w  w  w  . j a v  a 2s .  c o  m*/
 * 
 * @param entityClazz
 *            the entity clazz
 * @param entity
 *            the entity
 * @param m
 *            the m
 * @param outputFile
 *            the output file
 * @param kunderaMetadata
 *            the kundera metadata
 * @return the entity from GFSDBFile
 */
public Object getEntityFromGFSDBFile(Class<?> entityClazz, Object entity, EntityMetadata m,
        GridFSDBFile outputFile, KunderaMetadata kunderaMetadata) {
    MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata()
            .getMetamodel(m.getPersistenceUnit());
    String id = ((AbstractAttribute) m.getIdAttribute()).getJPAColumnName();
    Object rowKey = ((DBObject) outputFile.get(MongoDBUtils.METADATA)).get(id);
    Class<?> rowKeyValueClass = rowKey.getClass();
    Class<?> idClass = m.getIdAttribute().getJavaType();
    rowKey = MongoDBUtils.populateValue(rowKey, idClass);
    rowKey = MongoDBUtils.getTranslatedObject(rowKey, rowKeyValueClass, idClass);
    PropertyAccessorHelper.setId(entity, m, rowKey);
    EntityType entityType = metaModel.entity(entityClazz);

    Set<Attribute> columns = entityType.getAttributes();
    for (Attribute column : columns) {
        boolean isLob = ((Field) column.getJavaMember()).getAnnotation(Lob.class) != null;
        if (isLob) {
            if (column.getJavaType().isAssignableFrom(byte[].class)) {
                InputStream is = outputFile.getInputStream();
                try {
                    PropertyAccessorHelper.set(entity, (Field) column.getJavaMember(),
                            ByteStreams.toByteArray(is));
                } catch (IOException e) {
                    log.error("Error while converting inputstream from GridFSDBFile to byte array, Caused by: ",
                            e);
                    throw new KunderaException(
                            "Error while converting inputstream from GridFSDBFile to byte array, Caused by: ",
                            e);
                }
            }
        } else if (!column.equals(m.getIdAttribute()))
            DocumentObjectMapper.setFieldValue(outputFile, entity, column, true);
    }
    return entity;
}