List of usage examples for javax.servlet.http HttpServletResponse reset
public void reset();
From source file:servlets.Analysis_servlets.java
private void getAnalysisImageHandler(HttpServletRequest request, HttpServletResponse response) throws IOException { String analysis_id = request.getParameter("analysis_id"); String experiment_id = request.getParameter("experimentID"); try {// ww w . ja va 2 s . co m File file = new File(DATA_LOCATION + IMAGE_FILES_LOCATION.replaceAll("<experiment_id>", experiment_id) + analysis_id + ".png"); if (file.exists()) { response.reset(); response.addHeader("Access-Control-Allow-Origin", "*"); response.setContentType("image/png"); response.addHeader("Content-Disposition", "attachment; filename=" + analysis_id + ".png"); response.setContentLength((int) file.length()); FileInputStream fileInputStream = new FileInputStream(file); OutputStream responseOutputStream = response.getOutputStream(); int bytes; while ((bytes = fileInputStream.read()) != -1) { responseOutputStream.write(bytes); } responseOutputStream.close(); } } catch (NullPointerException e) { ServerErrorManager.addErrorMessage(4, Analysis_servlets.class.getName(), "get_analysis_img_handler", e.getMessage()); response.setStatus(400); response.getWriter().print(ServerErrorManager.getErrorResponse()); } catch (Exception e) { ServerErrorManager.addErrorMessage(4, Analysis_servlets.class.getName(), "get_analysis_img_handler", e.getMessage()); response.setStatus(400); response.getWriter().print(ServerErrorManager.getErrorResponse()); } }
From source file:de.itsvs.cwtrpc.security.AbstractRpcFailureHandler.java
protected void writeExpectedException(HttpServletRequest request, HttpServletResponse response, Exception remoteException) throws IOException { final RPCRequest rpcRequest; final String responsePayload; rpcRequest = AbstractRpcAuthenticationProcessingFilter.getRpcRequest(request); try {/*from w ww .ja va2 s . c o m*/ if (rpcRequest != null) { /* checked exceptions must be declared by service method */ responsePayload = RPC.encodeResponseForFailure(rpcRequest.getMethod(), remoteException, rpcRequest.getSerializationPolicy()); } else { log.warn("Could not determine RPC request. Using default serialization."); responsePayload = RPC.encodeResponseForFailure(null, remoteException); } } catch (UnexpectedException e) { if (rpcRequest != null) { log.error("Exception " + remoteException.getClass().getName() + " is unexpected for method " + rpcRequest.getMethod() + " of declaring class " + rpcRequest.getMethod().getDeclaringClass().getName(), e); } else { log.error("Exception " + remoteException.getClass().getName() + " is unexpected for unknown method", e); } writeUnexpectedException(request, response, remoteException); return; } catch (SerializationException e) { log.error("Error while serializing " + remoteException.getClass().getName(), e); writeUnexpectedException(request, response, remoteException); return; } if (CwtRpcUtils.getRpcSessionInvalidationPolicy(request).isInvalidateOnExpectedException()) { invalidateSession(request); } response.reset(); addNoCacheResponseHeaders(request, response); RPCServletUtils.writeResponse(getServletContext(), response, responsePayload, false); response.flushBuffer(); }
From source file:servlets.Analysis_servlets.java
private void getAnalysisPreviewImageHandler(HttpServletRequest request, HttpServletResponse response) throws IOException { String analysisID = request.getParameter("analysis_id"); String experiment_id = request.getParameter("experimentID"); try {// w w w . ja v a 2s .co m File file = new File(DATA_LOCATION + IMAGE_FILES_LOCATION.replaceAll("<experiment_id>", experiment_id) + analysisID + "_prev.jpg"); if (file.exists()) { response.reset(); response.addHeader("Access-Control-Allow-Origin", "*"); response.setContentType("image/jpeg"); response.addHeader("Content-Disposition", "attachment; filename=" + analysisID + "_prev.jpg"); response.setContentLength((int) file.length()); FileInputStream fileInputStream = new FileInputStream(file); OutputStream responseOutputStream = response.getOutputStream(); int bytes; while ((bytes = fileInputStream.read()) != -1) { responseOutputStream.write(bytes); } responseOutputStream.close(); } } catch (NullPointerException e) { ServerErrorManager.addErrorMessage(4, Analysis_servlets.class.getName(), "get_analysis_img_prev_handler", e.getMessage()); response.setStatus(400); response.getWriter().print(ServerErrorManager.getErrorResponse()); } catch (Exception e) { ServerErrorManager.addErrorMessage(4, Analysis_servlets.class.getName(), "get_analysis_img_prev_handler", e.getMessage()); response.setStatus(400); response.getWriter().print(ServerErrorManager.getErrorResponse()); } }
From source file:cn.edu.pku.lib.dataverse.UsageLogStatisPage.java
public void downloadRequestJoinGroupLog(String type) { FacesContext context = FacesContext.getCurrentInstance(); HttpServletResponse response = (HttpServletResponse) context.getExternalContext().getResponse(); File file = null;//w ww .j a v a 2 s . co m switch (type) { case "csv": file = generateCSVRequestJoinGroupLogFile(); break; case "xlsx": file = generateExcelRequestJoinGroupLogFile(); break; default: file = generateCSVRequestJoinGroupLogFile(); } if (file == null) { try { response.sendError(HttpServletResponse.SC_NOT_FOUND); } catch (IOException ex) { logger.log(Level.SEVERE, null, ex); } return; } response.reset(); response.setContentType("application/octet-stream"); switch (type) { case "csv": response.setHeader("Content-Disposition", "attachment;filename=\"join_user_group_information.csv\""); break; case "xlsx": response.setHeader("Content-Disposition", "attachment;filename=\"join_user_group_information.xlsx\""); break; default: response.setHeader("Content-Disposition", "attachment;filename=\"join_user_group_information.csv\""); } response.setContentLength((int) file.length()); try (BufferedInputStream in = new BufferedInputStream(new FileInputStream(file)); BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());) { byte[] buffer = new byte[1024 * 4]; int length; while ((length = in.read(buffer)) > 0) { out.write(buffer, 0, length); } } catch (IOException ioe) { logger.log(Level.SEVERE, null, ioe); } context.responseComplete(); if (file.exists()) file.delete(); }
From source file:org.apache.roller.planet.ui.rendering.servlets.OpmlServlet.java
/** * Handle GET requests for weblog feeds. *//*from w w w . jav a 2 s . c o m*/ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { log.debug("Entering"); Planet planet = null; PlanetGroup group = null; PlanetGroupOpmlRequest opmlRequest = null; try { // parse the incoming request and extract the relevant data opmlRequest = new PlanetGroupOpmlRequest(request); planet = opmlRequest.getPlanet(); if (planet == null) { throw new PlanetException("unable to lookup planet: " + opmlRequest.getPlanetHandle()); } group = opmlRequest.getGroup(); if (group == null) { throw new PlanetException("unable to lookup group: " + opmlRequest.getGroupHandle()); } } catch (Exception e) { // invalid feed request format or weblog doesn't exist log.debug("error creating planet page request", e); response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } // set content type response.setContentType("application/xml; charset=utf-8"); // looks like we need to render content HashMap model = new HashMap(); try { // populate the rendering model Map initData = new HashMap(); initData.put("planetRequest", opmlRequest); // Load models for feeds String opmlModels = PlanetConfig.getProperty("rendering.opmlModels"); ModelLoader.loadModels(opmlModels, model, initData, true); } catch (PlanetException ex) { log.error("ERROR loading model for page", ex); if (!response.isCommitted()) response.reset(); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return; } // lookup Renderer we are going to use Renderer renderer = null; try { log.debug("Looking up renderer"); Template template = new StaticTemplate("opml.vm", null, "velocity"); renderer = RendererManager.getRenderer(template); } catch (Exception e) { // nobody wants to render my content :( if (!response.isCommitted()) response.reset(); response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } // render content. use default size of about 24K for a standard page try { log.debug("Doing rendering"); renderer.render(model, response.getWriter()); } catch (Exception e) { // bummer, error during rendering log.error("Error during rendering for opml.vm", e); if (!response.isCommitted()) response.reset(); response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } // post rendering process // flush rendered content to response log.debug("Flushing response output"); //response.setContentLength(rendererOutput.getContent().length); //response.getOutputStream().write(rendererOutput.getContent()); log.debug("Exiting"); }
From source file:org.sakaiproject.kernel.webapp.RestServlet.java
/** * {@inheritDoc}// w ww . ja v a 2s . c o m * * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, * javax.servlet.http.HttpServletResponse) */ @Override protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String requestPath = request.getPathInfo(); if (requestPath == null) { requestPath = ""; } String[] elements = StringUtils.split(requestPath, '/'); String locator = "default"; if (elements != null && elements.length > 0) { locator = elements[0]; } Map<String, RestProvider> restProviders = registry.getMap(); if (locator == null) { locator = "default"; } if ("__describe__".equals(locator)) { locator = "default"; } RestProvider restProvider = restProviders.get(locator); if (restProvider == null) { response.sendError(HttpServletResponse.SC_NOT_FOUND); } else { try { if (requestPath.endsWith("__describe__")) { RestDescription description = restProvider.getDescription(); String format = request.getParameter("fmt"); if ("xml".equals(format)) { response.setContentType("text/xml"); response.getWriter().print(description.toXml()); } else if ("json".equals(format)) { response.setContentType(RestProvider.CONTENT_TYPE); response.getWriter().print(description.toJson()); } else { response.setContentType("text/html"); response.getWriter().print(description.toHtml()); } } else { restProvider.dispatch(elements, request, response); } } catch (SecurityException ex) { response.reset(); response.sendError(HttpServletResponse.SC_FORBIDDEN, ex.getMessage()); } catch (RestServiceFaultException ex) { ex.printStackTrace(); response.reset(); response.sendError(ex.getStatusCode(), ex.getMessage()); } } }
From source file:net.yacy.http.servlets.YaCyDefaultServlet.java
protected boolean passConditionalHeaders(HttpServletRequest request, HttpServletResponse response, Resource resource) throws IOException { try {//from w w w.j av a2 s . c o m if (!request.getMethod().equals(HttpMethod.HEAD.asString())) { String ifms = request.getHeader(HttpHeader.IF_MODIFIED_SINCE.asString()); if (ifms != null) { long ifmsl = request.getDateHeader(HttpHeader.IF_MODIFIED_SINCE.asString()); if (ifmsl != -1) { if (resource.lastModified() / 1000 <= ifmsl / 1000) { response.reset(); response.setStatus(HttpServletResponse.SC_NOT_MODIFIED); response.flushBuffer(); return false; } } } // Parse the if[un]modified dates and compare to resource long date = request.getDateHeader(HttpHeader.IF_UNMODIFIED_SINCE.asString()); if (date != -1) { if (resource.lastModified() / 1000 > date / 1000) { response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED); return false; } } } } catch (IllegalArgumentException iae) { if (!response.isCommitted()) { response.sendError(HttpServletResponse.SC_BAD_REQUEST, iae.getMessage()); return false; } throw iae; } return true; }
From source file:info.magnolia.cms.servlets.EntryServlet.java
/** * All HTTP/s requests are handled here. * @param req HttpServletRequest//from ww w.j ava 2 s.c o m * @param res HttpServletResponse * @throws IOException can be thrown when the servlet is unable to write to the response stream * @throws ServletException */ public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException { // Initialize magnolia context super.doGet(req, res); if (ConfigLoader.isBootstrapping()) { // @todo a nice page, with the log content... res.getWriter().write("Magnolia bootstrapping has failed, check bootstrap.log in magnolia/logs"); //$NON-NLS-1$ return; } if (ModuleRegistration.getInstance().isRestartNeeded()) { res.sendRedirect(req.getContextPath() + "/.magnolia/pages/restart.html"); } try { if (isAuthorized(req, res)) { if (redirect(req, res)) { return; } intercept(req, res); // aggregate content boolean success = Aggregator.collect(req); if (success) { Template template = (Template) req.getAttribute(Aggregator.TEMPLATE); if (template != null) { try { String type = template.getType(); TemplateRenderer renderer = TemplateRendererManager.getInstance().getRenderer(type); if (renderer == null) { throw new RuntimeException("No renderer found for type " + type); } renderer.renderTemplate(template, req, res); } catch (Exception e) { // @todo better handling of rendering exception log.error(e.getMessage(), e); if (!res.isCommitted()) { res.reset(); res.setContentType("text/html"); } throw new NestableRuntimeException(e); } } else { // direct request req.getRequestDispatcher(DIRECT_REQUEST_RECEIVER).forward(req, res); } } else { if (log.isDebugEnabled()) { log.debug("Resource not found, redirecting request for [{}] to 404 URI", //$NON-NLS-1$ req.getRequestURI()); } if (!res.isCommitted()) { res.sendError(HttpServletResponse.SC_NOT_FOUND); } else { log.info("Unable to redirect to 404 page, response is already committed. URI was {}", //$NON-NLS-1$ req.getRequestURI()); } } } } catch (AccessDeniedException e) { // don't log AccessDenied as errors, it can happen... log.warn(e.getMessage()); } catch (RepositoryException e) { log.error(e.getMessage(), e); throw new ServletException(e.getMessage(), e); } catch (RuntimeException e) { log.error(e.getMessage(), e); throw new ServletException(e.getMessage(), e); } }
From source file:edu.jhu.cvrg.ceptools.main.PubMedSearch.java
public void downloadFile(String filename, String filetype) { //The filetypes used are as follows- //doc|docx|xls|xlsx|pdf|abf|xml|pgf|pul|amp|dat|txt|zip|tar String contentType = ""; if (filetype.equals("zip")) { contentType = "application/zip"; } else if (filetype.equals("tar")) { contentType = "application/tar"; } else if (filetype.equals("xls") || filetype.equals("xlsx")) { contentType = "application/xls"; }//from w w w. j a va 2 s . com else if (filetype.equals("doc") || filetype.equals("docx")) { contentType = "application/doc"; } else if (filetype.equals("pdf")) { contentType = "application/pdf"; } else if (filetype.equals("xml")) { contentType = "text/xml"; } else { contentType = "text/plain"; } FacesContext facesContext = (FacesContext) FacesContext.getCurrentInstance(); ExternalContext externalContext = facesContext.getExternalContext(); PortletResponse portletResponse = (PortletResponse) externalContext.getResponse(); HttpServletResponse response = PortalUtil.getHttpServletResponse(portletResponse); File file = new File(selecteddownloadfile.getLocalfilestore(), filename); BufferedInputStream input = null; BufferedOutputStream output = null; try { input = new BufferedInputStream(new FileInputStream(file), 10240); response.reset(); response.setHeader("Content-Type", contentType); response.setHeader("Content-Length", String.valueOf(file.length())); response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\""); response.flushBuffer(); output = new BufferedOutputStream(response.getOutputStream(), 10240); byte[] buffer = new byte[10240]; int length; while ((length = input.read(buffer)) > 0) { output.write(buffer, 0, length); } output.flush(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { output.close(); input.close(); } catch (IOException e) { e.printStackTrace(); } } facesContext.responseComplete(); }
From source file:com.eliteams.pay.web.controller.RegisterController.java
/** * ?/*from w ww . j av a2s . c om*/ * * @param remoteFilePath * @param localFilePath */ @RequestMapping(value = "/downloadLocal") public void downloadLocal(HttpServletResponse response, HttpServletRequest request) throws Exception { logger.info(""); // String filePath = request.getSession().getServletContext().getRealPath("//") + "//pay//word/???.docx"; // String filePath = request.getScheme() + "://" + request.getLocalAddr() + ":" + request.getLocalPort() // + uploadpath + "???.docx"; String filePath = null; try { String os = System.getProperties().getProperty("os.name"); logger.info("os.startsWith=" + os); if (os.startsWith("win") || os.startsWith("Win")) { filePath = request.getSession().getServletContext().getRealPath("") + "\\pay\\word\\???.docx"; } else { filePath = request.getSession().getServletContext().getRealPath("") + "/pay/word/???.docx"; } logger.info("" + filePath); // String fileName = "???.docx".toString(); // ??? // ? InputStream inStream = new FileInputStream(filePath);// // ? response.reset(); response.setContentType("bin"); response.setHeader("Content-Disposition", "attachment; filename=" + java.net.URLEncoder.encode(fileName, "UTF-8")); // ??? byte[] b = new byte[100]; int len; while ((len = inStream.read(b)) > 0) response.getOutputStream().write(b, 0, len); inStream.close(); } catch (IOException e) { e.printStackTrace(); } }