Example usage for com.mongodb.gridfs GridFS remove

List of usage examples for com.mongodb.gridfs GridFS remove

Introduction

In this page you can find the example usage for com.mongodb.gridfs GridFS remove.

Prototype

public void remove(final DBObject query) 

Source Link

Document

Removes all files matching the given query.

Usage

From source file:mx.org.cedn.avisosconagua.engine.processors.Init.java

License:Open Source License

/**
 * Processes an uploaded file and stores it in MongoDB.
 * @param item file item from the parsed servlet request
 * @param currentId ID for the current MongoDB object for the advice
 * @return file name/*from  w ww  . jav a  2s.  c  o m*/
 * @throws IOException 
 */
private String processUploadedFile(FileItem item, String currentId) throws IOException {
    System.out.println("file: size=" + item.getSize() + " name:" + item.getName());
    GridFS gridfs = mi.getImagesFS();
    String filename = currentId + ":" + item.getFieldName() + "_" + item.getName();
    gridfs.remove(filename);
    GridFSInputFile gfsFile = gridfs.createFile(item.getInputStream());
    gfsFile.setFilename(filename);
    gfsFile.setContentType(item.getContentType());
    gfsFile.save();
    return filename;
}

From source file:mx.org.cedn.avisosconagua.mongo.CAPFileGenerator.java

License:Open Source License

/**
 * Generates and stores the CAP file.//  www  .  j  ava2  s .  co  m
 */
public void generate() {
    try {
        GridFS fs = MongoInterface.getInstance().getGeneratedFS();
        fs.remove(name);
        GridFSInputFile infile = fs.createFile(generator.generate().getBytes("UTF-8"));
        infile.setContentType("text/xml");
        infile.setFilename(name);
        infile.save();
        isOK = true;
    } catch (UnsupportedEncodingException uex) {
        uex.printStackTrace();
    }
}

From source file:mx.org.cedn.avisosconagua.mongo.HtmlZipGenerator.java

License:Open Source License

/**
 * Generates the ZIP file of the HTMl advice.
 *//* w  w w. j  a va2s .co m*/
public void generate() {
    try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
        String localFolder = "./" + adviceID + "/";
        ZipOutputStream zout = new ZipOutputStream(baos);
        zout.setLevel(9);
        zout.putNextEntry(new ZipEntry(name));
        zout.write(html.generate(true).getBytes("ISO8859-1"));
        //zout.putNextEntry(new ZipEntry(localFolder));
        if (html.getPrincipalFile() != null) {
            GridFS gridfs = MongoInterface.getInstance().getImagesFS();
            GridFSDBFile imageForOutput = gridfs.findOne(html.getPrincipalFile());
            zout.putNextEntry(new ZipEntry(prefix + "_1"
                    + html.getPrincipalFile().substring(html.getPrincipalFile().lastIndexOf(".")))); //localFolder + 
            imageForOutput.writeTo(zout);
        }
        if (html.getPronosticoFile() != null) {
            GridFS gridfs = MongoInterface.getInstance().getImagesFS();
            GridFSDBFile imageForOutput = gridfs.findOne(html.getPronosticoFile());
            zout.putNextEntry(new ZipEntry(prefix + "_2"
                    + html.getPrincipalFile().substring(html.getPrincipalFile().lastIndexOf(".")))); //localFolder +
            imageForOutput.writeTo(zout);
        }
        zout.putNextEntry(new ZipEntry(prefix + "_f.gif"));
        InputStream fin = HtmlZipGenerator.class.getResourceAsStream("/fondo.gif");
        byte[] buff = new byte[8192];
        int lenght;
        while ((lenght = fin.read(buff)) > -1) {
            zout.write(buff, 0, lenght);
        }
        //            ArrayList<String> lista = MongoInterface.getInstance().listFilesFromAdvice(adviceID);
        //            for (String filename : lista) {
        //                GridFS gridfs = MongoInterface.getInstance().getImagesFS();
        //                GridFSDBFile imageForOutput = gridfs.findOne(filename);
        //                String fnpart[] = filename.split(":");
        //                zout.putNextEntry(new ZipEntry(localFolder + fnpart[1]));
        //                imageForOutput.writeTo(zout);
        //            }
        zout.close();
        GridFS fs = MongoInterface.getInstance().getGeneratedFS();
        fs.remove(nameZip);
        GridFSInputFile infile = fs.createFile(baos.toByteArray());
        infile.setContentType("application/zip");
        infile.setFilename(nameZip);
        infile.save();
        isOK = true;
    } catch (IOException ioe) {
        ioe.printStackTrace();
    }
}

From source file:mytubermiserver.mongo.GridFileSystem.java

public void RemoveVideo(String fileName) throws UnknownHostException, MongoException, IOException {
    Mongo mongo = new Mongo(hostAddress, portAddress);

    DB db = mongo.getDB("MyTube");
    // create a "video" namespace
    GridFS gfsVideo = new GridFS(db, "video");
    // remove the image file from mongoDB
    gfsVideo.remove(fileName);
}

From source file:net.kamradtfamily.mongorest.GridfsServlet.java

License:GNU General Public License

@Override
protected void doDelete(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {

    log.fine("doDelete()");

    String db_name = req.getParameter("dbname");
    String bucket_name = req.getParameter("bucketname");
    if (db_name == null || bucket_name == null) {
        String names[] = req2mongonames(req);
        if (names != null) {
            db_name = names[0];/*  ww w.j av  a  2 s  .  c  o m*/
            bucket_name = names[1];
        }
        if (db_name == null) {
            error(res, SC_BAD_REQUEST, Status.get("param name missing"));
            return;
        }
    }

    if (bucket_name == null)
        bucket_name = "fs";

    DB db = mongo.getDB(db_name);

    String fs_cache_key = db_name + bucket_name;
    GridFS fs = fs_cache.get(fs_cache_key);
    if (fs == null) {
        fs = new GridFS(db, bucket_name);
        fs_cache.put(fs_cache_key, fs);
    }

    // mongo auth
    String user = req.getParameter("user");
    String passwd = req.getParameter("passwd");
    if (user != null && passwd != null && (!db.isAuthenticated())) {
        boolean auth = db.authenticate(user, passwd.toCharArray());
        if (!auth) {
            res.sendError(SC_UNAUTHORIZED);
            return;
        }
    }

    String file_name = req.getParameter("filename");

    if (file_name == null) {
        error(res, SC_BAD_REQUEST, Status.get("param name missing"));
        return;
    }

    fs.remove(file_name);

    out_json(req, Status.OK);

}

From source file:org.aw20.mongoworkbench.command.GridFSRemoveFileCommand.java

License:Open Source License

@Override
public void execute() throws Exception {
    MongoClient mdb = MongoFactory.getInst().getMongo(sName);

    if (mdb == null)
        throw new Exception("no server selected");

    if (sDb == null)
        throw new Exception("no database selected");

    MongoFactory.getInst().setActiveDB(sDb);
    DB db = mdb.getDB(sDb);/*from   w  w w .ja  va 2  s. c o m*/

    GridFS gfs = new GridFS(db, sColl.substring(0, sColl.lastIndexOf(".")));
    gfs.remove(new ObjectId(id));

    setMessage("fileRemoved=" + id);
}

From source file:org.bananaforscale.cormac.dao.gridfs.GridFsDataServiceImpl.java

License:Apache License

/**
 * Removes all files in a bucket./* w  ww  .  j av  a  2  s.  com*/
 *
 * @param databaseName the database
 * @param bucketName the bucket
 * @return a status message with the outcome of the operation
 * @throws DatasourceException
 * @throws NotFoundException
 */
@Override
public boolean removeAll(String databaseName, String bucketName) throws DatasourceException, NotFoundException {
    try {
        if (!databaseExists(databaseName)) {
            throw new NotFoundException("The database doesn't exist in the datasource");
        }
        DB mongoDatabase = mongoClient.getDB(databaseName);
        GridFS gfsBucket = new GridFS(mongoDatabase, bucketName); // TODO: determine behavior if bucket doesnt exist
        DBCursor cursor = gfsBucket.getFileList();
        Iterator<DBObject> curIter = cursor.iterator();
        while (curIter.hasNext()) {
            DBObject current = curIter.next();
            gfsBucket.remove(current);
        }
        return true;
    } catch (MongoException ex) {
        logger.error("An error occured while removing files", ex);
        throw new DatasourceException("An error occured while removing files");
    }
}

From source file:org.bananaforscale.cormac.dao.gridfs.GridFsDataServiceImpl.java

License:Apache License

/**
 * Saves a file to the database by file name. This is used during a form upload. We use tika to
 * determine the content type./*  w w w .j  av  a 2  s .c o m*/
 *
 * TODO: Refactor this mess
 *
 * @param databaseName the name of the database
 * @param bucketName the name of the bucket
 * @param fileName the name of the file
 * @param overwrite whether to overwrite an existing file with the same name
 * @param stream the file byte stream
 * @return the Mongo ID of the file
 * @throws DatasourceException
 * @throws ExistsException
 * @throws NotFoundException
 */
@Override
public String addByForm(String databaseName, String bucketName, String fileName, boolean overwrite,
        InputStream stream) throws DatasourceException, ExistsException, NotFoundException {
    String fileId = null;
    try {
        if (!databaseExists(databaseName)) {
            throw new NotFoundException("The database doesn't exist in the datasource");
        }
        DB mongoDatabase = mongoClient.getDB(databaseName);
        GridFS gfsBucket = new GridFS(mongoDatabase, bucketName);
        GridFSDBFile gfsFile = gfsBucket.findOne(fileName);
        if (gfsFile == null) {
            // the file does not exist -- create
            GridFSInputFile dbFile = gfsBucket.createFile(stream, fileName);
            dbFile.setContentType(tika.detect(fileName));
            dbFile.save();
            fileId = dbFile.getId().toString();
        } else {
            // the file exists
            if (overwrite) {
                // overwrite the existing file
                gfsBucket.remove(gfsFile);
                GridFSInputFile inputFile = gfsBucket.createFile(stream, fileName);
                inputFile.setContentType(tika.detect(fileName));
                inputFile.save();
                fileId = inputFile.getId().toString();
            } else {
                throw new ExistsException("The file already exists in the bucket");
            }
        }
    } catch (MongoException ex) {
        logger.error("Could not persist entity to bucket", ex);
        throw new DatasourceException("Could not persist file to bucket");
    }
    if (fileId == null || fileId.isEmpty()) {
        throw new DatasourceException("Could not persist file to bucket");
    }
    return fileId;
}

From source file:org.bananaforscale.cormac.dao.gridfs.GridFsDataServiceImpl.java

License:Apache License

/**
 * Updates a file in the database. If the file exists in the database it will be updated. If the
 * file doesn't exist it will be created.
 *
 * @param databaseName the database//from  w ww .ja v a  2 s  .c o  m
 * @param bucketName the bucket
 * @param fileName the file name
 * @param inputStream the binary payload
 * @return the identifier of the file
 * @throws DatasourceException
 * @throws NotFoundException
 */
@Override
public String updateByFileName(String databaseName, String bucketName, String fileName, InputStream inputStream)
        throws DatasourceException, NotFoundException {
    try {
        if (!databaseExists(databaseName)) {
            throw new NotFoundException("The database doesn't exist in the datasource");
        }
        DB mongoDatabase = mongoClient.getDB(databaseName);
        GridFS gfsBucket = new GridFS(mongoDatabase, bucketName);
        GridFSDBFile gfsFile = gfsBucket.findOne(fileName);
        if (gfsFile == null) {
            GridFSInputFile inputFile = gfsBucket.createFile(inputStream, fileName);
            inputFile.setContentType(tika.detect(fileName));
            inputFile.save();
            return inputFile.getId().toString();
        } else {
            gfsBucket.remove(gfsFile);
            GridFSInputFile inputFile = gfsBucket.createFile(inputStream, fileName);
            inputFile.setContentType(tika.detect(fileName));
            inputFile.save();
            return inputFile.getId().toString();
        }
    } catch (MongoException ex) {
        logger.error("An error occured while updating the file", ex);
        throw new DatasourceException("An error occured while updating the file");
    }
}

From source file:org.bananaforscale.cormac.dao.gridfs.GridFsDataServiceImpl.java

License:Apache License

/**
 * Removes a file in the database.//from  w  ww  . j  av a  2 s.  c  o m
 *
 * @param databaseName the database
 * @param bucketName the bucket
 * @param fileName the file to delete
 * @return a status message with the outcome of the operation
 * @throws DatasourceException
 * @throws NotFoundException
 */
@Override
public boolean removeByFileName(String databaseName, String bucketName, String fileName)
        throws DatasourceException, NotFoundException {
    try {
        if (!databaseExists(databaseName)) {
            throw new NotFoundException("The database doesn't exist in the datasource");
        }
        DB mongoDatabase = mongoClient.getDB(databaseName);
        GridFS gfsBucket = new GridFS(mongoDatabase, bucketName);
        GridFSDBFile gfsFile = gfsBucket.findOne(fileName);
        if (gfsFile == null) {
            throw new NotFoundException("The file doesnt exist");
        }
        gfsBucket.remove(gfsFile);
        return true;
    } catch (MongoException ex) {
        logger.error("An error occured while removing the file", ex);
        throw new DatasourceException("An error occured while removing the file");
    }
}