List of usage examples for javax.servlet ServletOutputStream write
public abstract void write(int b) throws IOException;
From source file:com.alfaariss.oa.helper.stylesheet.handler.StreamHandler.java
/** * @see com.alfaariss.oa.helper.stylesheet.handler.AbstractStyleSheetHandler#process(com.alfaariss.oa.api.session.ISession, javax.servlet.http.HttpServletResponse, boolean) *//*from w w w . j a v a2s. co m*/ public void process(ISession session, HttpServletResponse response, boolean isWireless) throws StyleSheetException { BufferedReader streamInput = null; ServletOutputStream responseOutputStream = null; try { String sStyleSheet = super.resolveStyleSheetLocation(session, isWireless); if (sStyleSheet != null) { URL oURL = new URL(sStyleSheet); streamInput = new BufferedReader(new InputStreamReader(oURL.openStream())); responseOutputStream = response.getOutputStream(); String sInput = null; while ((sInput = streamInput.readLine()) != null) { sInput += "\r\n"; responseOutputStream.write(sInput.getBytes(CHARSET)); } } } catch (Exception e) { _logger.error("Could not stream stylesheet", e); throw new StyleSheetException(SystemErrors.ERROR_INTERNAL); } finally { try { if (responseOutputStream != null) { responseOutputStream.flush(); responseOutputStream.close(); } } catch (Exception e) { _logger.error("Could not close output stream", e); } try { if (streamInput != null) streamInput.close(); } catch (Exception e) { _logger.error("Could not close input stream", e); } } }
From source file:SendWord.java
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //get the 'file' parameter String fileName = (String) request.getParameter("file"); if (fileName == null || fileName.equals("")) throw new ServletException("Invalid or non-existent file parameter in SendWord servlet."); // add the .doc suffix if it doesn't already exist if (fileName.indexOf(".doc") == -1) fileName = fileName + ".doc"; String wordDir = getServletContext().getInitParameter("word-dir"); if (wordDir == null || wordDir.equals("")) throw new ServletException("Invalid or non-existent wordDir context-param."); ServletOutputStream stream = null; BufferedInputStream buf = null; try {//from w ww . j a va 2 s.c o m stream = response.getOutputStream(); File doc = new File(wordDir + "/" + fileName); response.setContentType("application/msword"); response.addHeader("Content-Disposition", "attachment; filename=" + fileName); response.setContentLength((int) doc.length()); FileInputStream input = new FileInputStream(doc); buf = new BufferedInputStream(input); int readBytes = 0; while ((readBytes = buf.read()) != -1) stream.write(readBytes); } catch (IOException ioe) { throw new ServletException(ioe.getMessage()); } finally { if (stream != null) stream.close(); if (buf != null) buf.close(); } }
From source file:SendXml.java
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //get the 'file' parameter String fileName = (String) request.getParameter("file"); if (fileName == null || fileName.equals("")) throw new ServletException("Invalid or non-existent file parameter in SendXml servlet."); // add the .doc suffix if it doesn't already exist if (fileName.indexOf(".xml") == -1) fileName = fileName + ".xml"; String xmlDir = getServletContext().getInitParameter("xml-dir"); if (xmlDir == null || xmlDir.equals("")) throw new ServletException("Invalid or non-existent xmlDir context-param."); ServletOutputStream stream = null; BufferedInputStream buf = null; try {/*ww w. j a v a2s .c om*/ stream = response.getOutputStream(); File xml = new File(xmlDir + "/" + fileName); response.setContentType("text/xml"); response.addHeader("Content-Disposition", "attachment; filename=" + fileName); response.setContentLength((int) xml.length()); FileInputStream input = new FileInputStream(xml); buf = new BufferedInputStream(input); int readBytes = 0; while ((readBytes = buf.read()) != -1) stream.write(readBytes); } catch (IOException ioe) { throw new ServletException(ioe.getMessage()); } finally { if (stream != null) stream.close(); if (buf != null) buf.close(); } }
From source file:werecloud.api.view.JSONView.java
@Override public void render(Map<String, ?> model, HttpServletRequest request, HttpServletResponse response) throws Exception { ServletOutputStream out = response.getOutputStream(); if (model.containsKey("model")) { ObjectMapper mapper = new ObjectMapper(); //use ISO-8601 dates instead of timestamp mapper.configure(SerializationConfig.Feature.WRITE_DATES_AS_TIMESTAMPS, false); mapper.configure(SerializationConfig.Feature.WRITE_NULL_PROPERTIES, outputNulls); ByteArrayOutputStream bos = new ByteArrayOutputStream(); mapper.writeValue(bos, model.get("model")); response.setContentLength(bos.size()); response.setContentType("application/json"); out.write(bos.toByteArray()); return;//from w w w. jav a2 s .c o m } throw new Exception("Could not find model."); }
From source file:argendata.web.controller.DatasetController.java
@RequestMapping(method = RequestMethod.GET) public void exportDatasets(HttpServletRequest request, HttpServletResponse response) { response.setContentType("application/octet-stream"); Iterable<Dataset> listDataset = this.datasetService.getAllApprovedDatasets(); String text = ""; for (Dataset d : listDataset) { String line = ""; line = d.getTitle() + ";"; line += d.getLicense() + ";"; Set<String> myTags = d.getKeyword(); for (String s : myTags) { line += s + ","; }//from www . ja v a 2 s .co m line = line.substring(0, line.length() - 1); line += ";"; line += d.getDataQuality() + ";"; line += d.getModified().substring(0, 10) + ";"; line += d.getSpatial() + ";"; line += d.getTemporal() + ";"; line += d.getPublisherName() + ";"; line += d.getAccessURL() + ";"; line += d.getSize() + ";"; line += d.getFormat() + ";"; if (d.getDistribution() instanceof Feed) { line += "Feed,"; } else if (d.getDistribution() instanceof WebService) { line += "Web Service;"; } else { line += "Download;"; } line += d.getLocation() + ";"; line += d.getDescription(); line += "\n"; text += line; } response.setHeader("Content-Disposition", "attachment; filename=\"Datasets.csv"); response.setContentLength(text.length()); ServletOutputStream out = null; try { out = response.getOutputStream(); out.write(text.getBytes()); } catch (IOException e) { logger.error(e.getMessage()); logger.error(e.getStackTrace()); } }
From source file:au.org.ala.biocache.web.MapController.java
private void displayBlankImage(int width, int height, boolean useBase, HttpServletResponse response) { try {//from www. j av a 2 s .com response.setContentType("image/png"); BufferedImage baseImage = null; if (useBase) { baseImage = createBaseMapImage(); } else { baseImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); } ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ImageIO.write(baseImage, "png", outputStream); ServletOutputStream outStream = response.getOutputStream(); outStream.write(outputStream.toByteArray()); outStream.flush(); outStream.close(); } catch (Exception e) { logger.error("Unable to write image", e); } }
From source file:org.sigmah.server.auth.SigmahAuthDictionaryServlet.java
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { /*/*from w ww . j ava 2 s . c om*/ * Initialize quartz scheduler here, because it needs link{EntityManager} * which can only accessed in request scope. */ injector.getInstance(GlobalExportJobActivator.class); if (req.getParameter("remove") != null) { final Cookie cookie = new Cookie("authToken", ""); cookie.setPath("/"); cookie.setMaxAge(0); resp.addCookie(cookie); } else { final HashMap<String, String> parameters = new HashMap<String, String>(); parameters.put(SigmahAuthProvider.SHOW_MENUS, String.valueOf(false)); final String authToken = getAuthToken(req.getCookies()); if (authToken != null) { final AuthenticationDAO authDAO = injector.getInstance(AuthenticationDAO.class); final Authentication auth = authDAO.findById(authToken); final User user = auth.getUser(); if (user.getOrganization() == null) { log.error(String.format( "User with id=%d, email=%s has no organization set, cannot log into the Sigmah interface.", user.getId(), user.getEmail())); resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Your account is not configured for use with Sigmah"); return; } parameters.put(SigmahAuthProvider.USER_ID, Integer.toString(user.getId())); parameters.put(SigmahAuthProvider.USER_TOKEN, '"' + authToken + '"'); parameters.put(SigmahAuthProvider.USER_EMAIL, '"' + user.getEmail() + '"'); parameters.put(SigmahAuthProvider.USER_NAME, '"' + user.getName() + '"'); parameters.put(SigmahAuthProvider.USER_FIRST_NAME, '"' + user.getFirstName() + '"'); parameters.put(SigmahAuthProvider.USER_ORG_ID, Integer.toString(user.getOrganization().getId())); parameters.put(SigmahAuthProvider.USER_ORG_UNIT_ID, Integer.toString(user.getOrgUnitWithProfiles().getOrgUnit().getId())); // Custom serialization of the profile. final ProfileDTO aggregatedProfile = aggregateProfiles(user, null, injector); final String aggregatedProfileAsString = ProfileUtils.writeProfile(aggregatedProfile); parameters.put(SigmahAuthProvider.USER_AG_PROFILE, '"' + aggregatedProfileAsString + '"'); if (log.isDebugEnabled()) { log.debug("[doGet] Writes aggregated profile: " + aggregatedProfile); log.debug("[doGet] String representation of the profile: " + aggregatedProfileAsString); } } final Properties properties = injector.getInstance(Properties.class); parameters.put(SigmahAuthProvider.VERSION_NUMBER, '"' + properties.getProperty("version.number") + '"'); final Charset utf8 = Charset.forName("UTF-8"); resp.setCharacterEncoding("UTF-8"); final ServletOutputStream output = resp.getOutputStream(); output.println("var " + SigmahAuthProvider.DICTIONARY_NAME + " = {"); boolean first = true; for (Map.Entry<String, String> entry : parameters.entrySet()) { if (first) first = false; else output.println(","); output.print(entry.getKey() + ": "); output.write(entry.getValue().getBytes(utf8)); } output.println("};"); } }
From source file:au.org.ala.biocache.web.MapController.java
@RequestMapping(value = "/occurrences/legend", method = RequestMethod.GET) public void pointLegendImage( @RequestParam(value = "colourby", required = false, defaultValue = "0") Integer colourby, @RequestParam(value = "width", required = false, defaultValue = "50") Integer widthObj, @RequestParam(value = "height", required = false, defaultValue = "50") Integer heightObj, HttpServletResponse response) {/* w w w . ja v a 2 s. c o m*/ try { int width = widthObj.intValue(); int height = heightObj.intValue(); BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); Graphics2D g = (Graphics2D) img.getGraphics(); if (colourby != null) { int colour = 0xFF000000 | colourby.intValue(); Color c = new Color(colour); g.setPaint(c); } else { g.setPaint(Color.blue); } g.fillOval(0, 0, width, width); g.dispose(); response.setContentType("image/png"); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ImageIO.write(img, "png", outputStream); ServletOutputStream outStream = response.getOutputStream(); outStream.write(outputStream.toByteArray()); outStream.flush(); outStream.close(); } catch (Exception e) { logger.error("Unable to write image", e); } }
From source file:au.org.ala.biocache.web.MapController.java
/** * This method creates and renders a density map legend for a species. * /* w ww. j av a2 s.c om*/ * @throws Exception */ @RequestMapping(value = "/density/legend", method = RequestMethod.GET) public @ResponseBody void speciesDensityLegend(SpatialSearchRequestParams requestParams, @RequestParam(value = "forceRefresh", required = false, defaultValue = "false") boolean forceRefresh, HttpServletRequest request, HttpServletResponse response) throws Exception { response.setContentType("image/png"); File baseDir = new File(heatmapOutputDir); String outputHMFile = getOutputFile(request); //Does file exist on disk? File f = new File(baseDir + "/" + "legend_" + outputHMFile); if (!f.isFile() || !f.exists() || forceRefresh) { //If not, generate logger.debug("regenerating heatmap legend"); generateStaticHeatmapImages(requestParams, true, false, 0, "0000ff", null, null, 1.0f, request); } else { logger.debug("legend file already exists on disk, sending file back to user"); } //read file off disk and send back to user try { File file = new File(baseDir + "/" + "legend_" + outputHMFile); //only send the image back if it actually exists - a legend won't exist if we create the map based on points if (file.exists()) { BufferedImage img = ImageIO.read(file); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ImageIO.write(img, "png", outputStream); ServletOutputStream outStream = response.getOutputStream(); outStream.write(outputStream.toByteArray()); outStream.flush(); outStream.close(); } } catch (Exception e) { logger.error("Unable to write image.", e); } }