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

License:Open Source License

/**
 * Converts the contents of a GridFS file to a float array
 * @param file the file//  w  ww . j a v a 2 s.c  o  m
 * @return the float array
 * @throws IOException if the file could not be read
 */
private float[] toFloatArray(GridFSDBFile file) throws IOException {
    DataInputStream is = new DataInputStream(new BufferedInputStream(file.getInputStream()));
    int len = (int) file.getLength() / (Float.SIZE / Byte.SIZE);
    float[] b = new float[len];
    for (int i = 0; i < len; ++i) {
        b[i] = is.readFloat();
    }
    return b;
}

From source file:de.iew.imageread.Main.java

License:Apache License

public boolean encodeImage(File outFile, GridFSDBFile gridFSDBFile) throws Exception {
    try {//  w w w .  java 2 s.  com
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(outFile);

            BufferedImage bufferedImage = ImageIO.read(gridFSDBFile.getInputStream());
            JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(fos);

            JPEGEncodeParam jpegEncodeParam = encoder.getDefaultJPEGEncodeParam(bufferedImage);
            jpegEncodeParam.setQuality(1f, false);
            encoder.setJPEGEncodeParam(jpegEncodeParam);
            encoder.encode(bufferedImage);
            return true;
        } finally {
            if (fos != null) {
                fos.flush();
                fos.close();
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }
}

From source file:de.iew.raspimotion.persistence.mongodb.MongoDbFileDaoImpl.java

License:Apache License

public InputStream openFileInputStream(FileDescriptor fd) {
    MongoDbFile mongoDbFile = (MongoDbFile) fd;

    GridFSDBFile gridFSDBFile = this.gridFsTemplate
            .findOne(new Query(Criteria.where("id").is(new ObjectId(mongoDbFile.getId()))));
    return gridFSDBFile.getInputStream();
}

From source file:de.steilerdev.myVerein.server.controller.ContentController.java

License:Open Source License

/**
 * This function gathers the club logo either from the database or the classpath, depending if the user uploaded a custom logo. The function is invoked by GETting the URI /content/clubLogo.
 * @param defaultLogo If this parameter is present the method will return the default logo, without searching through the database.
 * @return The current club logo as byte array.
 *//*from  ww w .j a v a  2s  .  c  om*/
@RequestMapping(value = "clubLogo", produces = "image/png", method = RequestMethod.GET)
@ResponseBody
ResponseEntity<byte[]> getClubLogo(@RequestParam(required = false) String defaultLogo) {
    logger.trace("Loading club logo");
    GridFSDBFile clubLogo = null;
    if (defaultLogo == null) {
        //Loading file only from database if the request did not state the fact to use the default logo.
        clubLogo = gridFSRepository.findClubLogo();
    } else {
        logger.info("Directly loading default club logo");
    }

    if (clubLogo == null) {
        if (defaultLogo == null) {
            logger.info("No club logo found, using default logo");
        }

        try {
            return new ResponseEntity<>(
                    IOUtils.toByteArray(new ClassPathResource("content/Logo.png").getInputStream()),
                    HttpStatus.OK);
        } catch (IOException e) {
            logger.warn("Unable to load default logo: " + e.getMessage());
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
        }
    } else {
        logger.debug("Loading club logo from database");
        try {
            return new ResponseEntity<>(IOUtils.toByteArray(clubLogo.getInputStream()), HttpStatus.OK);
        } catch (IOException e) {
            logger.warn("Unable to load club logo from database: " + e.getMessage());
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
}

From source file:fr.wseduc.resizer.GridFsFileAccess.java

License:Apache License

@Override
public void read(String src, Handler<ImageFile> handler) {
    String[] path = parsePath(src);
    if (path == null || path.length != 2) {
        handler.handle(null);//from www. j  a  v a  2  s  . com
        return;
    }
    GridFS fs = new GridFS(db, path[0]);
    GridFSDBFile f = fs.findOne(pathToDbObject(path[1]));
    if (f != null) {
        handler.handle(new ImageFile(f.getInputStream(), f.getFilename(), f.getContentType()));
    } else {
        handler.handle(null);
    }
}

From source file:httpUtils.HttpUtils.java

License:LGPL

/**
 * Get the GridFSDBFile wrapped in a HttpServletResponse
 * @param request// ww w.  j  a  va2 s  .c o m
 * @param response
 * @param file
 * @return
 */
public static HttpServletResponse getGridFSDBFileAsStream(HttpServletRequest request,
        HttpServletResponse response, GridFSDBFile file) {
    //TODO GridFSDBFile or GridFSFile
    InputStream dataStream = file.getInputStream();
    long fileLength = file.getLength();
    String fileName = file.getFilename();
    Date dateLastModified = file.getUploadDate();
    String contentType = file.getContentType();
    long fileLastModified = 0L;

    if (dateLastModified != null) {
        fileLastModified = dateLastModified.getTime();
    }

    return getFileAsStream(request, response, dataStream, fileLength, fileName, fileLastModified, contentType);
}

From source file:hulop.hokoukukan.utils.MongoAdapter.java

License:Open Source License

@Override
public InputStream getAttachment(String path) {
    GridFSDBFile file = getFile(path);
    return file != null ? file.getInputStream() : null;
}

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

License:Apache License

/**
 * Processes requests for both HTTP//from w  w  w. j a va2s . com
 * <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   ww  w .  j a va  2  s .c  om*/
 * <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();
    }

}

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

License:Apache License

/**
 *
 * @param request/*from w  w  w  . ja  v a 2 s .  c  om*/
 * @param response
 * @throws ServletException
 * @throws IOException
 */
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");
    final String type = Default.toString(params.get("type"), "min");

    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 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 String formatIn = getFormatIn(period);
    final String formatOut = getFormatOut(period);

    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 DefaultCategoryDataset dataset = new DefaultCategoryDataset();
    ChartEnumMinMaxHelper chartEnum = ChartEnumMinMaxHelper.getByFieldAndType(field, type);

    for (MapReduceMinMax m : mapReduceResult) {
        try {
            final Date tmpDate = DateTimeUtil.getDate(formatIn, m.getId().toString());

            if (tmpDate == null) {
                continue;
            }

            final Method method = m.getClass().getMethod(chartEnum.getMethod());
            final Number n = (Number) method.invoke(m);
            dataset.addValue(n, chartEnum.getType(), DateTimeUtil.dateFormat(formatOut, tmpDate));

        } 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 JFreeChart chart = ChartFactory.createBarChart(chartEnum.getTitle(), // chart title
            "", // domain axis label
            chartEnum.getUm(), // range axis label
            dataset, // data
            PlotOrientation.VERTICAL, // orientation
            false, // include legend
            true, // tooltips?
            false // URLs?
    );

    final CategoryPlot xyPlot = (CategoryPlot) chart.getPlot();
    final CategoryAxis domain = xyPlot.getDomainAxis();

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

    domain.setCategoryLabelPositions(CategoryLabelPositions.DOWN_90);

    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 {
        boolean delete = f.delete();
    }

}