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:de.fhg.igd.mongomvcc.impl.MongoDBVLargeCollection.java

License:Open Source License

@Override
public void insert(Map<String, Object> obj) {
    DefaultConvertStrategy cs = new DefaultConvertStrategy(_gridFS, getCounter());
    _accessStrategy.setConvertStrategy(cs);
    _accessStrategy.onInsert(obj);/*from  w  w w . j a  v a  2  s.  c  o m*/

    //save original object
    super.insert(obj);

    //save GridFS files
    for (GridFSInputFile file : cs.getConvertedFiles()) {
        file.put(PARENT, obj.get(OID));
        file.save();
    }
}

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
 *///w  w w .j  a v a  2  s  .c om
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: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();
    }//from www .jav a 2s.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);//from www .ja  va2 s.co  m
    f.setContentType(img.getContentType());
    f.setFilename(img.getFilename());
    f.save();
    return f;
}

From source file:in.mtap.iincube.mongoapi.GridFsUpdater.java

License:Apache License

@Override
public Boolean execute() {
    GridFS gridFS = getGridFs();/*from   w ww.ja  v  a2  s. c  om*/
    gridFS.remove(filename);
    GridFSInputFile file = gridFS.createFile(stream);
    file.setContentType(contentType);
    file.setFilename(filename);
    file.save();
    return true;
}

From source file:in.mtap.iincube.mongoapi.GridFsWriter.java

License:Apache License

@Override
public Boolean execute() {
    GridFS gridFS = getGridFs();/*from  w w w .ja va 2  s . c om*/
    GridFSInputFile file = gridFS.createFile(stream);
    file.setFilename(filename);
    file.setContentType(contentType);
    file.save();
    return false;
}

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);/*w ww .  j  a va2s.c  om*/
    }
    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 w  w w.ja va  2 s  .  co 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();

}

From source file:it.marcoberri.mbmeteo.action.chart.Get.java

License:Apache License

/**
 * Processes requests for both HTTP//from  ww w.  j av a  2s. c  o m
 * <code>GET</code> and
 * <code>POST</code> methods.
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    log.debug("start : " + this.getClass().getName());

    final HashMap<String, String> params = getParams(request.getParameterMap());
    final Integer dimy = Default.toInteger(params.get("dimy"), 600);
    final Integer dimx = Default.toInteger(params.get("dimx"), 800);
    final String from = Default.toString(params.get("from") + " 00:00:00", "1970-01-01 00:00:00");
    final String to = Default.toString(params.get("to") + " 23:59:00", "2030-01-01 23:59:00");
    final String field = Default.toString(params.get("field"), "outdoorTemperature");

    request.getSession().setAttribute("from", params.get("from"));
    request.getSession().setAttribute("to", params.get("to"));

    final String cacheKey = getCacheKey(params);

    if (cacheReadEnable) {
        final Query q = ds.find(Cache.class);
        q.filter("cacheKey", cacheKey).filter("servletName", this.getClass().getName());

        final Cache c = (Cache) q.get();

        if (c == null) {
            log.info("cacheKey:" + cacheKey + " on servletName: " + this.getClass().getName() + " not found");
        }

        if (c != null) {
            log.debug("get file from cache id: " + c.getGridId());
            final GridFSDBFile imageForOutput = MongoConnectionHelper.getGridFS()
                    .findOne(new ObjectId(c.getGridId()));
            if (imageForOutput != null) {

                ds.save(c);

                try {
                    response.setHeader("Content-Length", "" + imageForOutput.getLength());
                    response.setHeader("Content-Disposition",
                            "inline; filename=\"" + imageForOutput.getFilename() + "\"");
                    final OutputStream out = response.getOutputStream();
                    final InputStream in = imageForOutput.getInputStream();
                    final byte[] content = new byte[(int) imageForOutput.getLength()];
                    in.read(content);
                    out.write(content);
                    in.close();
                    out.close();
                    return;
                } catch (final IOException e) {
                    log.error(e);
                }

            } else {
                log.error("file not in db");
            }
        }
    }

    final String titleChart = ChartEnumHelper.getByName(field).getTitle();
    final String umChart = ChartEnumHelper.getByName(field).getUm();
    final Query q = ds.createQuery(Meteolog.class);
    final Date dFrom = DateTimeUtil.getDate("yyyy-MM-dd hh:mm:ss", from);
    final Date dTo = DateTimeUtil.getDate("yyyy-MM-dd hh:mm:ss", to);

    q.disableValidation().filter("time >=", dFrom).filter("time <=", dTo);

    final List<Meteolog> meteoLogList = q.asList();
    final TimeSeries series = new TimeSeries(umChart);

    for (Meteolog m : meteoLogList) {
        final Millisecond t = new Millisecond(m.getTime());
        try {
            //violenza di una reflection
            final Method method = m.getClass().getMethod(ChartEnumHelper.getByName(field).getMethod());
            final Number n = (Number) method.invoke(m);
            series.add(t, n);
        } catch (final NoSuchMethodException ex) {
            log.error(ex);
        } catch (final InvocationTargetException ex) {
            log.error(ex);
        } catch (final IllegalAccessException ex) {
            log.error(ex);
        } catch (final SecurityException ex) {
            log.error(ex);
        }

    }

    final TimeSeriesCollection dataset = new TimeSeriesCollection();
    dataset.addSeries(series);

    final JFreeChart chart = ChartFactory.createTimeSeriesChart(titleChart, "", umChart, dataset, false, false,
            false);
    final XYPlot plot = (XYPlot) chart.getPlot();
    final DateAxis axis = (DateAxis) plot.getDomainAxis();
    axis.setDateFormatOverride(new SimpleDateFormat("dd-MM-yyyy HH:mm"));
    axis.setVerticalTickLabels(true);

    if (field.toUpperCase().indexOf("PRESSURE") != -1) {
        plot.getRangeAxis().setRange(chartPressureMin, chartPressureMax);
    }

    final File f = File.createTempFile("mbmeteo", ".jpg");
    ChartUtilities.saveChartAsJPEG(f, chart, dimx, dimy);

    try {

        if (cacheWriteEnable) {

            final GridFSInputFile gfsFile = MongoConnectionHelper.getGridFS().createFile(f);
            gfsFile.setFilename(f.getName());
            gfsFile.save();

            final Cache c = new Cache();
            c.setServletName(this.getClass().getName());
            c.setCacheKey(cacheKey);
            c.setGridId(gfsFile.getId().toString());

            ds.save(c);

        }

        response.setContentType("image/jpeg");
        response.setHeader("Content-Length", "" + f.length());
        response.setHeader("Content-Disposition", "inline; filename=\"" + f.getName() + "\"");
        final OutputStream out = response.getOutputStream();
        final FileInputStream in = new FileInputStream(f.toString());
        final int size = in.available();
        final byte[] content = new byte[size];
        in.read(content);
        out.write(content);
        in.close();
        out.close();
    } catch (final IOException e) {
        log.error(e);
    } finally {
        f.delete();
    }

}

From source file:it.marcoberri.mbmeteo.action.chart.GetMinAndMax.java

License:Apache License

/**
 * Processes requests for both HTTP//from w ww . j  a v  a 2s  .co m
 * <code>GET</code> and
 * <code>POST</code> methods.
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    log.debug("start : " + this.getClass().getName());

    final HashMap<String, String> params = getParams(request.getParameterMap());
    final Integer dimy = Default.toInteger(params.get("dimy"), 600);
    final Integer dimx = Default.toInteger(params.get("dimx"), 800);
    final String from = Default.toString(params.get("from") + " 00:00:00", "1970-01-01 00:00:00");
    final String to = Default.toString(params.get("to") + " 23:59:00", "2030-01-01 23:59:00");
    final String field = Default.toString(params.get("field"), "outdoorTemperature");
    final String period = Default.toString(params.get("period"), "day");

    request.getSession().setAttribute("from", params.get("from"));
    request.getSession().setAttribute("to", params.get("to"));

    final String cacheKey = getCacheKey(params);

    if (cacheReadEnable) {

        final Query q = ds.find(Cache.class);
        q.filter("cacheKey", cacheKey).filter("servletName", this.getClass().getName());

        final Cache c = (Cache) q.get();

        if (c == null) {
            log.info("cacheKey:" + cacheKey + " on servletName: " + this.getClass().getName() + " not found");
        }

        if (c != null) {
            final GridFSDBFile imageForOutput = MongoConnectionHelper.getGridFS()
                    .findOne(new ObjectId(c.getGridId()));
            if (imageForOutput != null) {
                ds.save(c);

                try {
                    response.setHeader("Content-Length", "" + imageForOutput.getLength());
                    response.setHeader("Content-Disposition",
                            "inline; filename=\"" + imageForOutput.getFilename() + "\"");
                    final OutputStream out = response.getOutputStream();
                    final InputStream in = imageForOutput.getInputStream();
                    final byte[] content = new byte[(int) imageForOutput.getLength()];
                    in.read(content);
                    out.write(content);
                    in.close();
                    out.close();
                    return;
                } catch (Exception e) {
                    log.error(e);
                }

            } else {
                log.error("file not in db");
            }
        }
    }

    final String formatIn = getFormatIn(period);
    final String formatOut = getFormatOut(period);

    final Query q = ds.createQuery(MapReduceMinMax.class).disableValidation();

    final Date dFrom = DateTimeUtil.getDate("yyyy-MM-dd hh:mm:ss", from);
    final Date dTo = DateTimeUtil.getDate("yyyy-MM-dd hh:mm:ss", to);

    final List<Date> datesIn = getRangeDate(dFrom, dTo);
    final HashSet<String> datesInString = new HashSet<String>();

    for (Date d : datesIn) {
        datesInString.add(DateTimeUtil.dateFormat(formatIn, d));
    }

    if (datesIn != null && !datesIn.isEmpty()) {
        q.filter("_id in", datesInString);
    }
    q.order("_id");

    final List<MapReduceMinMax> mapReduceResult = q.asList();
    final TimeSeries serieMin = new TimeSeries("Min");
    final TimeSeries serieMax = new TimeSeries("Max");

    for (MapReduceMinMax m : mapReduceResult) {
        try {

            final Date tmpDate = DateTimeUtil.getDate(formatIn, m.getId().toString());
            if (tmpDate == null) {
                continue;
            }

            final Millisecond t = new Millisecond(tmpDate);

            ChartEnumMinMaxHelper chartEnum = ChartEnumMinMaxHelper.getByFieldAndType(field, "min");
            Method method = m.getClass().getMethod(chartEnum.getMethod());
            Number n = (Number) method.invoke(m);
            serieMin.add(t, n);

            chartEnum = ChartEnumMinMaxHelper.getByFieldAndType(field, "max");
            method = m.getClass().getMethod(chartEnum.getMethod());
            n = (Number) method.invoke(m);
            serieMax.add(t, n);

        } catch (IllegalAccessException ex) {
            log.error(ex);
        } catch (IllegalArgumentException ex) {
            log.error(ex);
        } catch (InvocationTargetException ex) {
            log.error(ex);
        } catch (NoSuchMethodException ex) {
            log.error(ex);
        } catch (SecurityException ex) {
            log.error(ex);
        }
    }

    final ChartEnumMinMaxHelper chartData = ChartEnumMinMaxHelper.getByFieldAndType(field, "min");

    final TimeSeriesCollection dataset = new TimeSeriesCollection();
    dataset.addSeries(serieMin);
    dataset.addSeries(serieMax);

    final JFreeChart chart = ChartFactory.createTimeSeriesChart("Max/Min", "", chartData.getUm(), dataset, true,
            false, false);
    final XYPlot plot = (XYPlot) chart.getPlot();
    final DateAxis axis = (DateAxis) plot.getDomainAxis();
    axis.setDateFormatOverride(new SimpleDateFormat(formatOut));

    axis.setVerticalTickLabels(true);

    if (field.toUpperCase().indexOf("PRESSURE") != -1) {
        plot.getRangeAxis().setRange(chartPressureMin, chartPressureMax);
    }

    final File f = File.createTempFile("mbmeteo", ".jpg");
    ChartUtilities.saveChartAsJPEG(f, chart, dimx, dimy);

    try {

        if (cacheWriteEnable) {
            final GridFSInputFile gfsFile = MongoConnectionHelper.getGridFS().createFile(f);
            gfsFile.setFilename(f.getName());
            gfsFile.save();

            final Cache c = new Cache();
            c.setServletName(this.getClass().getName());
            c.setCacheKey(cacheKey);
            c.setGridId(gfsFile.getId().toString());

            ds.save(c);

        }

        response.setContentType("image/jpeg");
        response.setHeader("Content-Length", "" + f.length());
        response.setHeader("Content-Disposition", "inline; filename=\"" + f.getName() + "\"");
        final OutputStream out = response.getOutputStream();
        final FileInputStream in = new FileInputStream(f.toString());
        final int size = in.available();
        final byte[] content = new byte[size];
        in.read(content);
        out.write(content);
        in.close();
        out.close();
    } catch (Exception e) {
        log.error(e);
    } finally {
        f.delete();
    }

}