Example usage for com.mongodb.gridfs GridFSInputFile getId

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

Introduction

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

Prototype

public Object getId() 

Source Link

Document

Gets the id.

Usage

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

License:Open Source License

/**
 * Since we don't know the name, we'll have to save the data before we can
 * determine the name. So save it under a random UUID, calculate the name,
 * and if the name is not already in the file system then rename it.
 * Otherwise delete it./*  w w  w . j a v  a2 s . c o m*/
 * 
 * @throws DocSearchException
 */
@Override
protected StoreRequestResult storeAndDetermineHash(Document document, HashingInputStream inputStream)
        throws DocStoreException {
    final String temporaryName = java.util.UUID.randomUUID().toString();
    GridFSInputFile newFile = gridFS.createFile(inputStream);
    newFile.setFilename(temporaryName);
    setFileMetaData(newFile, document, -1);
    newFile.save();
    try {
        newFile.validate();
    } catch (MongoException e) {
        throw new DocStoreException("file saved to GridFS did not validate", e);
    }

    final byte[] actualHash = inputStream.getDigest();
    final String actualName = getIdentifierFromHash(actualHash);
    final int shardKey = getShardIndexFromHash(actualHash);

    try {
        try {
            documentLockingService.lockWithRetries(actualName, DocStoreConstants.LOCK_TO_STORE, LOCK_RETRIES,
                    LOCK_RETRY_DELAY_MILLISECONDS);
        } catch (LockAcquisitionException e) {
            gridFS.remove((ObjectId) newFile.getId());
            throw new DocStoreException("could not acquire lock to store document \"" + actualName + "\"");
        }

        // so now we're in "control" of that file

        try {
            if (fileExists(actualName)) {
                gridFS.remove(temporaryName);
                return new StoreRequestResultImpl(actualName, true, shardKey);
            } else {
                final boolean wasRenamed = setFileNameAndShardKey(newFile.getId(), actualName, shardKey);
                if (!wasRenamed) {
                    throw new DocStoreException("expected to find and rename a GridFS file with id \""
                            + newFile.getId() + "\" but could not find it");
                }
                return new StoreRequestResultImpl(actualName, false, shardKey);
            }
        } finally {
            documentLockingService.releaseLock(actualName);
        }
    } catch (LockServiceException e) {
        throw new DocStoreException(e);
    }
}

From source file:com.pubkit.platform.persistence.impl.ApplicationDaoImpl.java

License:Open Source License

public String saveFile(byte[] fileData, String fileName, String contentType) {
    GridFS gridFs = new GridFS(mongoTemplate.getDb(), PK_FILES_BUCKET);
    GridFSInputFile gfsFile = gridFs.createFile(fileData);

    gfsFile.setFilename(fileName);/*from   w ww .  j  av  a 2s  .  co m*/
    gfsFile.setContentType(contentType);
    gfsFile.save();

    LOG.info("Saved new file :" + fileName);

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

From source file:com.seajas.search.contender.service.storage.StorageService.java

License:Open Source License

/**
 * Store the given content in GridFS and return the relevant ObjectId.
 *
 * @param content//  ww  w .j  a va 2  s  .  c  om
 * @return ObjectId
 */
private ObjectId storeContent(final InputStream content) {
    if (content == null)
        throw new IllegalArgumentException("Content storage was requested but no content was given");

    if (!content.markSupported())
        logger.warn(
                "Marking of the (original) content stream is not supported - will not reset the stream after storage");

    GridFSInputFile inputFile = gridFs.createFile(content, false);

    try {
        inputFile.save();
    } finally {
        if (content.markSupported())
            try {
                content.reset();
            } catch (IOException e) {
                logger.error("Unable to reset the given stream, despite mark() being supported", e);
            }

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

From source file:com.spring.tutorial.entitites.FileUploader.java

public String upload() throws IOException, ServletException, FacebookException {
    OutputStream output = null;//  w  ww . ja  v  a2  s .  com
    InputStream fileContent = null;
    final Part filePart;

    final File file;
    try {
        filePart = request.getPart("file");

        fileContent = filePart.getInputStream();

        MongoClient mongoClient = new MongoClient();
        mongoClient = new MongoClient();
        DB db = mongoClient.getDB("fou");

        char[] pass = "mongo".toCharArray();
        boolean auth = db.authenticate("admin", pass);

        file = File.createTempFile("fileToStore", "tmp");

        file.deleteOnExit();
        FileOutputStream fout = new FileOutputStream(file);

        int read = 0;
        byte[] bytes = new byte[1024];

        while ((read = fileContent.read(bytes)) != -1) {
            fout.write(bytes, 0, read);
        }

        GridFS gridFS = new GridFS(db, request.getSession().getAttribute("id") + "_files");
        GridFSInputFile gfsInputFile = gridFS.createFile(file);
        gfsInputFile.setFilename(filePart.getSubmittedFileName());
        gfsInputFile.save();

        DBCollection collection = db.getCollection(request.getSession().getAttribute("id") + "_files_meta");
        BasicDBObject metaDocument = new BasicDBObject();
        metaDocument.append("name", filePart.getSubmittedFileName());
        metaDocument.append("size", filePart.getSize());
        metaDocument.append("content-type", filePart.getContentType());
        metaDocument.append("file-id", gfsInputFile.getId());
        metaDocument.append("tags", request.getParameter("tags"));
        metaDocument.append("description", request.getParameter("description"));

        DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");

        metaDocument.append("last_modified", dateFormat.format(new Date()));

        collection.insert(metaDocument);

    } catch (Exception e) {
        return "message:" + e.getMessage();
    } finally {
        if (output != null) {
            output.close();
        }
        if (fileContent != null) {
            fileContent.close();
        }
    }

    return "success";
}

From source file:com.test.mavenproject1.Main.java

public static void main(String[] args) throws Exception {
    //Load our image
    byte[] imageBytes = LoadImage("/home/fabrice/Pictures/priv/DSCN3338.JPG");
    //Connect to database
    Mongo mongo = new Mongo("127.0.0.1");
    String dbName = "GridFSTestJava";
    DB db = mongo.getDB(dbName);/*from  w  ww  .ja  v a2  s . co m*/
    //Create GridFS object
    GridFS fs = new GridFS(db);
    //Save image into database
    GridFSInputFile in = fs.createFile(imageBytes);
    in.save();

    //Find saved image
    GridFSDBFile out = fs.findOne(new BasicDBObject("_id", in.getId()));

    //Save loaded image from database into new image file
    FileOutputStream outputImage = new FileOutputStream("/home/fabrice/Pictures/DSCN3338Copy.JPG");
    out.writeTo(outputImage);
    outputImage.close();
}

From source file:controllers.user.UserController.java

/**
 * ??/*from ww w  . j  a va 2 s  .  c om*/
 * 
 * @author Poppy
 * @date 2014-9-29
 * @return
 * @since 1.0
 */
public static Result add() {
    String msg = "";
    UserForm form = new UserForm();
    User user = new User();
    try {
        // ??
        Form<UserForm> userForm = Form.form(UserForm.class);
        form = userForm.bindFromRequest().get();
        // ?cookie??
        Cookie cookie = request().cookie(IContent.VERIFYCODE_COOKIE);
        String cookieValue = (cookie == null) ? "" : cookie.value();
        String verifyCode = form.verifyCode;
        if (!verifyCode.toUpperCase().equals(cookieValue.toUpperCase())) {
            msg = "verifyWrong";
            return ok(register.render(form, msg));
        }
        // 
        FilePart pro = request().body().asMultipartFormData().getFile("productionCertificateUrl");
        FilePart food = request().body().asMultipartFormData().getFile("foodCirculationUrl");
        FilePart bus = request().body().asMultipartFormData().getFile("businessLicenseUrl");
        // ????
        if (EmptyUtil.isNotEmpty(pro)) {
            File proFile = pro.getFile();
            // ?
            String ext = "jpg";
            String proFileExt = pro.getFilename().substring(pro.getFilename().lastIndexOf(".") + 1)
                    .toLowerCase();
            if (!Arrays.<String>asList(ext.split(",")).contains(proFileExt)) {
                msg = "extWrong";
                return ok(register.render(form, msg));
            } else {
                // 
                GridFSInputFile gProFile = PlayJongo.gridfs().createFile(proFile);
                gProFile.setFilename(pro.getFilename());
                gProFile.setContentType(proFileExt);
                gProFile.save();
                user.productionCertificateUrl = "/common/download/" + gProFile.getId();
            }
        } else {
            user.productionCertificateUrl = "";
        }
        // ?????
        if (EmptyUtil.isNotEmpty(food)) {
            File foodFile = food.getFile();
            // ?
            String ext = "jpg";
            String foodFileExt = food.getFilename().substring(food.getFilename().lastIndexOf(".") + 1)
                    .toLowerCase();
            if (!Arrays.<String>asList(ext.split(",")).contains(foodFileExt)) {
                msg = "extWrong";
                return ok(register.render(form, msg));
            } else {
                // 
                GridFSInputFile gFoodFile = PlayJongo.gridfs().createFile(foodFile);
                gFoodFile.setFilename(food.getFilename());
                gFoodFile.setContentType(foodFileExt);
                gFoodFile.save();
                user.foodCirculationUrl = "/common/download/" + gFoodFile.getId();
            }
        } else {
            user.foodCirculationUrl = "";
        }
        // ??
        if (EmptyUtil.isNotEmpty(bus)) {
            File busFile = bus.getFile();
            // ?
            String ext = "jpg";
            String busFileExt = bus.getFilename().substring(bus.getFilename().lastIndexOf(".") + 1)
                    .toLowerCase();
            if (!Arrays.<String>asList(ext.split(",")).contains(busFileExt)) {
                msg = "extWrong";
                return ok(register.render(form, msg));
            } else {
                // 
                GridFSInputFile gBusFile = PlayJongo.gridfs().createFile(busFile);
                gBusFile.setFilename(bus.getFilename());
                gBusFile.setContentType(busFileExt);
                gBusFile.save();
                user.businessLicenseUrl = "/common/download/" + gBusFile.getId();
            }
        } else {
            user.businessLicenseUrl = "";
        }
        // form??
        user.addr = form.addr;
        user.businessLicenseCode = form.businessLicenseCode;
        user.city = form.city;
        user.enterpriseName = form.enterpriseName;
        user.enterprisePrincipal = form.enterprisePrincipal;
        user.enterpriseType = form.enterpriseType;
        user.executiveStandard = form.executiveStandard;
        user.legalPerson = form.legalPerson;
        user.organizationCode = form.organizationCode;
        user.postCode = form.postCode;
        user.productionAddr = form.productionAddr;
        user.province = form.province;
        user.pwd = form.pwd;
        user.qualityPrincipal = form.qualityPrincipal;
        user.qualityAuthorizer = form.qualityAuthorizer;
        user.tel = form.tel;
        user.email = form.email;
        user.productionCertificate = form.productionCertificate;
        user.variety = form.variety;
        user.enterpriseAddr = form.enterpriseAddr;
        user.busiScope = form.busiScope;
        user.busiMod = form.busiMod;
        user.foodCirculation = form.foodCirculation;
        user.approvalFlag = 0;
        user.updateFlag = 0;
        if (form.enterpriseType == 1) {
            user.userName = form.organizationCode;
            // ??
            Long checkResult = User.registerCheck(user.organizationCode);
            if (checkResult == 0) {
                // ?form??
                user.add();
                msg = "success";
            } else {
                msg = "checkWrong";
            }
        } else {
            user.userName = form.foodCirculation;
            // ?????
            Long checkResult = User.registerCheckBis(user.foodCirculation);
            if (checkResult == 0) {
                // ?form??
                user.add();
                msg = "success";
            } else {
                msg = "checkWrong";
            }
        }
    } catch (Exception e) {
        // 
        Logger.error("UserController-add:?", e);
        msg = "error";
    }
    // 
    return ok(register.render(form, msg));
}

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 ww .ja v a 2 s  . co 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:ezbake.data.mongo.MongoDriverHandler.java

License:Apache License

public EzWriteResult insert_driver(String collection, EzInsertRequest req, EzSecurityToken token)
        throws TException, EzMongoDriverException {
    //        if (!collection.equals("fs.chunks") && !collection.equals("fs.files")) {
    collection = appName + "_" + collection;
    //        }//ww w. j  av  a  2  s.co m

    appLog.debug("insert_driver() to collection: {}", collection);

    TokenUtils.validateSecurityToken(token, handler.getConfigurationProperties());
    EzWriteResult ewr = new EzWriteResult();
    try {
        DBCollection c = handler.db.getCollection(normalizeCollection(collection));

        ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(req.getDbObjectList()));
        List<DBObject> list = (List<DBObject>) ois.readObject();

        ois = new ObjectInputStream(new ByteArrayInputStream(req.getWriteConcern()));
        WriteConcern writeConcern = (WriteConcern) ois.readObject();

        ois = new ObjectInputStream(new ByteArrayInputStream(req.getDbEncoder()));
        DBEncoder dbEncoder = (DBEncoder) ois.readObject();

        HashMap<String, String> auditParamsMap = new HashMap<>();
        auditParamsMap.put("action", "insert_driver");
        auditParamsMap.put("collectionName", collection);
        auditParamsMap.put("list", handler.printMongoObject(list));
        auditParamsMap.put("writeConcern", handler.printMongoObject(writeConcern));
        auditParamsMap.put("dbEncoder", handler.printMongoObject(dbEncoder));
        handler.auditLog(token, AuditEventType.FileObjectCreate, auditParamsMap);

        WriteResult res = null;

        Boolean isDriverUnitTestMode = req.isIsUnitTestMode();

        if (!isDriverUnitTestMode) {
            // check if the user has the auths to insert these records
            List<DBObject> insertableList = new ArrayList<>();
            for (DBObject dbObject : list) {
                try {
                    handler.getMongoInsertHelper().checkAbilityToInsert(token, null, dbObject, null, false,
                            true);
                    insertableList.add(dbObject);
                } catch (ClassCastException | VisibilityParseException | EzMongoBaseException e) {
                    appLog.error(e.toString());
                    appLog.debug("User does not have the auths to insert record: {}", dbObject);
                }
            }
            res = c.insert(insertableList, writeConcern, dbEncoder);
        } else {
            res = c.insert(list, writeConcern, dbEncoder);
        }

        if (list != null && list.size() == 1 && list.get(0) instanceof GridFSInputFile) {
            GridFSInputFile g = (GridFSInputFile) list.get(0);
            Object o = g.getId();
            if (o instanceof ObjectId) {
                ObjectId id = (ObjectId) o;
                cm.getCache(GRID_FS_INPUT_FILE_MAP_CACHE).put(new Element(id.toString(), id));
            }
        }

        appLog.debug("WriteResult: {}", res);

        ByteArrayOutputStream bOut = new ByteArrayOutputStream();
        new ObjectOutputStream(bOut).writeObject(res);

        ewr.setWriteResult(bOut.toByteArray());
    } catch (Exception e) {
        appLog.error(e.toString());
        EzMongoDriverException eme = new EzMongoDriverException();
        eme.setEx(ser(e));
        throw eme;
    }
    return ewr;
}

From source file:io.liveoak.mongo.gridfs.GridFSBlobResource.java

License:Open Source License

private GridFSFilesPathItemResource pushToDB(RequestContext ctx, MediaType contentType, GridFSDBObject fileInfo,
        Supplier contentProvider) throws IOException {
    ObjectId currentId = fileInfo.getId();
    boolean fileExists = currentId != null;

    // update the targeted userspace - hopefully current user has rights to do that
    GridFS gridfs = getUserspace().getGridFS();

    Object content = contentProvider.get();
    GridFSInputFile blob;
    if (fileExists) {
        // here is a time gap when file doesn't exist for a while when being updated.
        // making the switch instantaneous would require another layer of indirection
        // - not using file_id as canonical id, but some other id, mapped to a file.
        // there would still remain a moment between mapping from old file to new file
        // involving two separate file items and a moment in time when during a switch
        // no file would match a filename, nor file id.
        gridfs.remove(currentId);/*from w ww. j  a  va2 s .co m*/
    }
    if (content instanceof File) {
        blob = gridfs.createFile((File) content);
    } else if (content instanceof InputStream) {
        blob = gridfs.createFile((InputStream) content);
    } else if (content instanceof ByteBuf) {
        blob = gridfs.createFile(((ByteBuf) content).array());
    } else {
        throw new IllegalArgumentException("Unsupported value supplied: " + content.getClass());
    }

    // meta data
    if (fileExists) {
        blob.setId(currentId);
    }
    blob.setFilename(fileInfo().getString("filename"));
    blob.setContentType(contentType != null ? contentType.toString() : "application/octet-stream");
    blob.put("parent", fileInfo().getParentId());
    blob.save();

    String oid = blob.getId().toString();

    return new GridFSFilesPathItemResource(ctx, getFilesRoot(), oid, new GridFSDBObject(blob),
            GridFSResourcePath.fromContext(ctx));
}

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

License:Apache License

/**
 * //from ww  w .j a v  a2s  .c  o 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();

}