List of usage examples for com.mongodb.gridfs GridFSInputFile save
@Override public void save()
From source file:it.marcoberri.mbmeteo.action.chart.GetMinOrMax.java
License:Apache License
/** * * @param request/*from w ww . j av a2s. co m*/ * @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(); } }
From source file:me.philnate.textmanager.entities.Document.java
License:Open Source License
public static Document loadAndSave(File file) { GridFSInputFile gFile; try {/* w w w .j av a 2s . c om*/ gFile = docs.createFile(file); gFile.save(); LOG.debug(format("Reading file '%s' for new Document", file.getAbsolutePath())); Document doc = new Document(); doc.setDocument((ObjectId) gFile.getId()).setTitle(file.getName()); return doc.setWordCount(WordCount.countFile(file)); } catch (IOException e1) { return null; } }
From source file:me.yyam.mongodbutils.MongoDbOperater.java
/** * mongodb//w w w .j a v a2 s . c o m * @param dbName ??? * @param fsName GridFS???fsnull? * @param input ?? * @param fsFileName GridFS?? * @throws FileNotFoundException * @throws IOException */ public void upload2GridFS(String dbName, String fsName, InputStream input, String fsFileName) throws FileNotFoundException, IOException { DB db = mongoClient.getDB(dbName); if (fsName == null) { fsName = "fs"; } GridFS fs = new GridFS(db, fsName); GridFSInputFile fsFile = fs.createFile(input); if (StringUtils.isBlank(fsFileName)) { throw new FileNotFoundException("gridfs????fsFileName"); } fsFile.setFilename(fsFileName); fsFile.save(); }
From source file:me.yyam.mongodbutils.MongoDbOperater.java
public void upload2GridFS(String dbName, String fsName, byte[] bytes, String fsFileName) throws FileNotFoundException, IOException { DB db = mongoClient.getDB(dbName);/*from w w w.j a va2 s . c om*/ if (fsName == null) { fsName = "fs"; } GridFS fs = new GridFS(db, fsName); GridFSInputFile fsFile = fs.createFile(bytes); if (StringUtils.isBlank(fsFileName)) { throw new FileNotFoundException("gridfs????fsFileName"); } fsFile.setFilename(fsFileName); fsFile.save(); }
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 w w.j a va 2 s. com * @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.engine.processors.Pronostico.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 ww w. j a v a 2 s. com*/ * @throws IOException */ private String processUploadedFile(FileItem item, String currentId) throws IOException { GridFS gridfs = MongoInterface.getInstance().getImagesFS(); GridFSInputFile gfsFile = gridfs.createFile(item.getInputStream()); String filename = currentId + ":" + item.getFieldName() + "_" + item.getName(); 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.//from w w w . j a v a2 s . c o 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. *///from w w w . ja va 2 s .c om 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 sendVideo(String fileName, InputStream videoStream) throws UnknownHostException, MongoException, IOException { Mongo mongo = new Mongo(hostAddress, portAddress); DB db = mongo.getDB("MyTube"); // create a "video" namespace GridFS gfsPhoto = new GridFS(db, "video"); //get the file from stream GridFSInputFile gfsFile = gfsPhoto.createFile(videoStream); // set a new filename for identify purpose gfsFile.setFilename(fileName);//from www .jav a2 s . co m // save the image file into mongoDB gfsFile.save(); videoStream.close(); }
From source file:net.tooan.ynpay.third.mongodb.fs.BuguFS.java
License:Apache License
public void save(File file, String filename, Map<String, Object> params) { GridFSInputFile f = null; try {/*from w ww . j a v a 2s. c om*/ f = fs.createFile(file); } catch (IOException ex) { logger.error("Can not create GridFSInputFile", ex); } f.setChunkSize(chunkSize); f.setFilename(filename); setParams(f, params); f.save(); }