Example usage for com.mongodb.gridfs GridFSInputFile save

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

Introduction

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

Prototype

@Override
public void save() 

Source Link

Document

Calls GridFSInputFile#save(long) with the existing chunk size.

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  . ja v a 2 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.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);//from   w w  w.  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.photon.phresco.service.impl.DbService.java

License:Apache License

protected void saveFileToDB(String id, InputStream is) throws PhrescoException {
    if (isDebugEnabled) {
        LOGGER.debug("DbService.saveFileToDB:Entry");
        if (StringUtils.isEmpty(id)) {
            LOGGER.warn("DbService.saveFileToDB", STATUS_BAD_REQUEST, "message=\"id is empty\"");
            throw new PhrescoException("id is empty");
        }//www.  j  av  a2 s.co m
        LOGGER.info("DbService.saveFileToDB", "id=\"" + id + "\"");
    }
    getGridFs().remove(id);
    GridFSInputFile file = getGridFs().createFile(is);
    file.setFilename(id);
    file.save();
    if (isDebugEnabled) {
        LOGGER.debug("DbService.saveFileToDB:Exit");
    }
}

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);/*  w w  w.  jav a 2s  .c o  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//w ww.j  a  v a 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;//from  ww w .  j  a v  a2s .  c  o  m
    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   ww  w. j a va 2  s.com
    //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: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 ww w  .java2 s  .com*/
    f.setMetaData(metadata);
    f.setContentType(file.getContentType());
    f.save();
}

From source file:controllers.user.UserController.java

/**
 * ??/*from   w w w .  ja v a  2  s  . c o m*/
 * 
 * @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:DataBase.JavaMongoDB.java

/**
 *
 * @param path/*from ww  w  .j  av  a  2 s  .c o  m*/
 * @param Basededatos
 * @param cubo
 * @param nombre
 */
public void InsertarAudio(String path, DB Basededatos, String cubo, String nombre) {
    GridFS gfsAudio;
    GridFSInputFile gfsFile;
    File imageFile;
    imageFile = new File(path);
    gfsAudio = new GridFS(Basededatos, cubo);
    try {
        gfsFile = gfsAudio.createFile(imageFile);
        String newFileName = nombre;
        gfsFile.setFilename(newFileName);
        gfsFile.save();

    } catch (IOException ex) {
        Logger.getLogger(JavaMongoDB.class.getName()).log(Level.SEVERE, null, ex);
    }

    //DBCollection collection = db.getCollection("Audio_meta");
    // collection.insert(info, WriteConcern.SAFE);
    //GridFS gfsAudioConsulta = new GridFS(db, "audio");
    //GridFSDBFile imageForOutput = gfsAudioConsulta.findOne("1073");
    //System.out.println(imageForOutput);
}