List of usage examples for javax.servlet.http HttpServletResponse reset
public void reset();
From source file:net.siegmar.japtproxy.packages.RepoPackageFinder.java
/** * Fetches an object from a specific backend. * * @param requestedData the requested data. * @param targetResource the target resource. * @param poolObject the pool object. * @param res the HttpServletResponse object * @return true if the requested object was send successfully. * @throws IOException is thrown if an I/O error occurs. *///from www . j av a 2 s .c o m protected boolean handleBackend(final RequestedData requestedData, final URL targetResource, final PoolObject poolObject, final HttpServletResponse res) throws IOException { try { // Send and save data final boolean locallyCached = ioHandler.sendAndSave(requestedData, poolObject, targetResource, res); // If a new version was downloaded and if the configuration // specifies a max-version parameter, remove old versions if (!locallyCached && configuration.getMaxVersions() != null) { packagePool.removeOldPackages(poolObject); } return true; } catch (final ResourceUnavailableException e) { LOG.info("Resource '{}' not found", targetResource); } catch (final IOException e) { LOG.warn(String.format("IOException while getting data from '%s'", targetResource), e); if (res.isCommitted()) { LOG.info("IOException occured but headers are already sent. Have to rethrow exception", e); throw e; } res.reset(); } catch (final InitializationException e) { LOG.warn("Resource '{}' could not be fetched", targetResource, e); } return false; }
From source file:org.sakaiproject.kernel.rest.RestUserProvider.java
private void handleUserExists(String eid, HttpServletResponse response) throws ServletException, IOException { Session session = sessionManagerService.getCurrentSession(); User user = session.getUser();// w w w.ja v a 2 s.co m if ((user == null || user.getUuid() == null) && !anonymousAccounting) { throw new RestServiceFaultException(HttpServletResponse.SC_UNAUTHORIZED); } else { UserEnvironment env = userEnvironmentResolverService.resolve(user); if (!anonymousAccounting && (null == env || !env.isSuperUser())) { throw new RestServiceFaultException(HttpServletResponse.SC_FORBIDDEN); } else { if (userResolverService.resolve(eid) != null) { response.reset(); Map<String, String> body = new HashMap<String, String>(); body.put("response", "OK"); body.put("eid", eid); body.put("exists", "true"); String json = beanConverter.convertToString(body); response.setContentType(RestProvider.CONTENT_TYPE); response.getOutputStream().print(json); response.getOutputStream().flush(); response.getOutputStream().close(); } else { throw new RestServiceFaultException(HttpServletResponse.SC_NOT_FOUND); } } } }
From source file:org.sakaiproject.reports.logic.impl.ReportsManagerImpl.java
/** * THIS IS TAKEN FROM GRADEBOOK: org.sakai.tool.gradebook.ui.ExportBean * <p/>//w w w . ja va 2 s .c o m * Try to head off a problem with downloading files from a secure HTTPS * connection to Internet Explorer. * <p/> * When IE sees it's talking to a secure server, it decides to treat all hints * or instructions about caching as strictly as possible. Immediately upon * finishing the download, it throws the data away. * <p/> * Unfortunately, the way IE sends a downloaded file on to a helper * application is to use the cached copy. Having just deleted the file, * it naturally isn't able to find it in the cache. Whereupon it delivers * a very misleading error message like: * "Internet Explorer cannot download roster from sakai.yoursite.edu. * Internet Explorer was not able to open this Internet site. The requested * site is either unavailable or cannot be found. Please try again later." * <p/> * There are several ways to turn caching off, and so to be safe we use * several ways to turn it back on again. * <p/> * This current workaround should let IE users save the files to disk. * Unfortunately, errors may still occur if a user attempts to open the * file directly in a helper application from a secure web server. * <p/> * TODO Keep checking on the status of this. */ private static void protectAgainstInstantDeletion(HttpServletResponse response) { response.reset(); // Eliminate the added-on stuff response.setHeader("Pragma", "public"); // Override old-style cache control response.setHeader("Cache-Control", "public, must-revalidate, post-check=0, pre-check=0, max-age=0"); // New-style }
From source file:axiom.servlet.AbstractServletClient.java
void sendError(HttpServletResponse response, int code, String message) throws IOException { response.reset(); response.setStatus(code);//from w w w. j a v a2s.c o m response.setContentType("text/html"); Writer writer = response.getWriter(); writer.write("<html><body><h3>"); writer.write("Error in application "); try { writer.write(getApplication().getName()); } catch (Exception besafe) { besafe.printStackTrace(); } writer.write("</h3>"); writer.write(message); writer.write("</body></html>"); writer.flush(); }
From source file:org.ngrinder.perftest.controller.PerfTestController.java
/** * Show the given log for the perf test having the given id. * * @param user user//w ww . j av a 2 s .co m * @param id test id * @param path path in the log folder * @param response response */ @RequestMapping(value = "/{id}/show_log/**") public void showLog(User user, @PathVariable("id") long id, @RemainedPath String path, HttpServletResponse response) { getOneWithPermissionCheck(user, id, false); File targetFile = perfTestService.getLogFile(id, path); response.reset(); response.setContentType("text/plain"); response.setCharacterEncoding("UTF-8"); FileInputStream fileInputStream = null; try { fileInputStream = new FileInputStream(targetFile); ServletOutputStream outputStream = response.getOutputStream(); if (FilenameUtils.isExtension(targetFile.getName(), "zip")) { // Limit log view to 1MB outputStream.println(" Only the last 1MB of a log shows.\n"); outputStream .println("==========================================================================\n\n"); LogCompressUtils.decompress(fileInputStream, outputStream, 1 * 1024 * 1204); } else { IOUtils.copy(fileInputStream, outputStream); } } catch (Exception e) { CoreLogger.LOGGER.error("Error while processing log. {}", targetFile, e); } finally { IOUtils.closeQuietly(fileInputStream); } }
From source file:eu.planets_project.tb.gui.backing.DownloadManager.java
/** * // ww w.ja va2s. c o m * @return * @throws IOException */ public String downloadExportedExperiment(String expExportID, String downloadName) { FacesContext ctx = FacesContext.getCurrentInstance(); // Decode the file name (might contain spaces and on) and prepare file object. try { expExportID = URLDecoder.decode(expExportID, "UTF-8"); } catch (UnsupportedEncodingException e1) { // TODO Auto-generated catch block e1.printStackTrace(); return null; } File file = expCache.getExportedFile(expExportID); HttpServletResponse response = (HttpServletResponse) ctx.getExternalContext().getResponse(); // Check if file exists and can be read: if (!file.exists() || !file.isFile() || !file.canRead()) { return "fileNotFound"; } // Get content type by filename. String contentType = new MimetypesFileTypeMap().getContentType(file); // If content type is unknown, then set the default value. // For all content types, see: http://www.w3schools.com/media/media_mimeref.asp if (contentType == null) { contentType = "application/octet-stream"; } // Prepare streams. BufferedInputStream input = null; BufferedOutputStream output = null; try { // Open the file: input = new BufferedInputStream(new FileInputStream(file)); int contentLength = input.available(); // Initialise the servlet response: response.reset(); response.setContentType(contentType); response.setContentLength(contentLength); response.setHeader("Content-disposition", "attachment; filename=\"" + downloadName + ".xml\""); output = new BufferedOutputStream(response.getOutputStream()); // Write file out: for (int data; (data = input.read()) != -1;) { output.write(data); } // Flush the stream: output.flush(); // Tell Faces that we're finished: ctx.responseComplete(); } catch (IOException e) { // Something went wrong? e.printStackTrace(); } finally { // Gently close streams. close(output); close(input); } return "success"; }
From source file:com.nabla.wapp.server.basic.general.ExportService.java
private boolean exportFile(final String id, final UserSession userSession, final HttpServletResponse response) throws IOException, SQLException, InternalErrorException { final Connection conn = db.getConnection(); try {//from w w w. ja v a 2s. c o m final PreparedStatement stmt = StatementFormat.prepare(conn, "SELECT * FROM export WHERE id=?;", id); try { final ResultSet rs = stmt.executeQuery(); try { if (!rs.next()) { if (log.isDebugEnabled()) log.debug("failed to find file ID= " + id); return false; } if (!userSession.getSessionId().equals(rs.getString("userSessionId"))) { if (log.isTraceEnabled()) log.trace("invalid user session ID"); return false; } if (log.isTraceEnabled()) log.trace("exporting file " + id); response.reset(); response.setBufferSize(DEFAULT_BUFFER_SIZE); response.setContentType(rs.getString("content_type")); if (rs.getBoolean("output_as_file")) { // IMPORTANT: // MUST be done before calling getOutputStream() otherwise no SaveAs dialogbox response.setHeader("Content-Disposition", MessageFormat.format("attachment; filename=\"{0}\"", rs.getString("name"))); } IOUtils.copy(rs.getBinaryStream("content"), response.getOutputStream()); /* final BufferedInputStream input = new BufferedInputStream(rs.getBinaryStream("content"), DEFAULT_BUFFER_SIZE); try { final BufferedOutputStream output = new BufferedOutputStream(response.getOutputStream(), DEFAULT_BUFFER_SIZE); try { final byte[] buffer = new byte[DEFAULT_BUFFER_SIZE]; int length; while ((length = input.read(buffer)) > 0) output.write(buffer, 0, length); } finally { output.close(); } } finally { input.close(); }*/ } finally { rs.close(); try { Database.executeUpdate(conn, "DELETE FROM export WHERE id=?;", id); } catch (final SQLException e) { if (log.isErrorEnabled()) log.error("failed to delete export record: " + e.getErrorCode() + "-" + e.getSQLState(), e); } } } finally { stmt.close(); } } finally { // remove any orphan export records i.e. older than 48h (beware of timezone!) final Calendar dt = Util.dateToCalendar(new Date()); dt.add(GregorianCalendar.DATE, -2); try { Database.executeUpdate(conn, "DELETE FROM export WHERE created < ?;", Util.calendarToSqlDate(dt)); } catch (final SQLException __) { } conn.close(); } return true; }
From source file:com.highcharts.export.controller.ExportController.java
@RequestMapping(method = RequestMethod.POST) public void exporter(@RequestParam(value = "svg", required = false) String svg, @RequestParam(value = "type", required = false) String type, @RequestParam(value = "filename", required = false) String filename, @RequestParam(value = "width", required = false) String width, @RequestParam(value = "scale", required = false) String scale, @RequestParam(value = "options", required = false) String options, @RequestParam(value = "constr", required = false) String constructor, @RequestParam(value = "callback", required = false) String callback, HttpServletResponse response, HttpServletRequest request) throws ServletException, IOException, InterruptedException, SVGConverterException, NoSuchElementException, PoolException, TimeoutException { long start1 = System.currentTimeMillis(); MimeType mime = getMime(type); filename = getFilename(filename);/*from ww w.ja v a2 s . co m*/ Float parsedWidth = widthToFloat(width); Float parsedScale = scaleToFloat(scale); options = sanitize(options); String inputs; boolean convertSvg = false; // Create return JSON object JSONObject jobj = new JSONObject(); if (options != null) { // create a svg file out of the options inputs = options; callback = sanitize(callback); } else { jobj.put("status", -1); jobj.put("msg", "The svg POST is not supported."); response.reset(); response.setContentType("application/json"); response.getWriter().print(jobj); response.flushBuffer(); return; } String[] inputList = inputs.split("!#!"); String input; ByteArrayOutputStream stream = null; //stream = SVGCreator.getInstance().convert(input, mime, constructor, callback, parsedWidth, parsedScale); String fileList = ""; String chartFilename = ""; for (int i = 0; i < inputList.length; i++) { input = inputList[i]; stream = converter.convert(input, mime, constructor, callback, parsedWidth, parsedScale); if (stream == null) { //throw new ServletException("Error while converting"); jobj.put("status", -1); jobj.put("msg", "Error while converting."); response.reset(); response.setContentType("application/json"); response.getWriter().print(jobj); response.flushBuffer(); return; } logger.debug(request.getHeader("referer") + " Total time: " + (System.currentTimeMillis() - start1)); // Now Save the it to file. And return the path. String uuid = UUID.randomUUID().toString(); String extension = ".png"; if (mime.compareTo(MimeType.JPEG) == 0) { extension = ".jpg"; } else if (mime.compareTo(MimeType.PDF) == 0) { extension = ".pdf"; } else if (mime.compareTo(MimeType.PNG) == 0) { extension = ".png"; } else if (mime.compareTo(MimeType.SVG) == 0) { extension = ".svg"; } chartFilename = uuid + extension; //OutputStream chartFile = new FileOutputStream ("C:\\inetpub\\wwwroot\\tmp\\"+chartFilename); OutputStream chartFile = new FileOutputStream( "C:\\Users\\mc142\\Source\\Repos\\JourneyCompass\\website\\tmp\\" + chartFilename); stream.writeTo(chartFile); chartFile.close(); if (i == inputList.length - 1) { fileList += chartFilename; } else { fileList += chartFilename + "!#!"; } stream = null; } jobj.put("filenames", fileList); jobj.put("status", 0); jobj.put("msg", "success"); response.reset(); response.setCharacterEncoding("utf-8"); response.setContentType("application/json"); response.setStatus(HttpStatus.OK.value()); response.addHeader("Access-Control-Allow-Origin", "*"); //response.setHeader("Access-Control-Allow-Headers", "X-MYRESPONSEHEADER"); response.getWriter().print(jobj); response.flushBuffer(); /**** This is the original code that let browser saves the file. response.reset(); response.setCharacterEncoding("utf-8"); response.setContentLength(stream.size()); response.setStatus(HttpStatus.OK.value()); response.setHeader("Content-disposition", "attachment; filename=\"" + filename + "." + mime.name().toLowerCase() + "\""); IOUtils.write(stream.toByteArray(), response.getOutputStream()); response.flushBuffer(); ****/ }
From source file:org.ireland.jnetty.webapp.ErrorPageManager.java
public void sendServletErrorImpl(Throwable e, ServletRequest req, ServletResponse res) throws IOException { HttpServletResponse response = (HttpServletResponse) res; HttpServletRequest request = (HttpServletRequest) req; Throwable rootExn = e;//w w w .j a va 2 s . c o m Throwable errorPageExn = null; LineMap lineMap = null; try { response.reset(); } catch (IllegalStateException e1) { } if (req.isAsyncStarted()) { AsyncContext async = req.getAsyncContext(); if (async != null) async.complete(); } if (response instanceof HttpServletResponseImpl) { HttpServletResponseImpl resFacade = (HttpServletResponseImpl) response; resFacade.killCache(); resFacade.setNoCache(true); } if (rootExn instanceof ClientDisconnectException) throw (ClientDisconnectException) rootExn; String location = null; String title = "500 Servlet Exception"; boolean isBadRequest = false; boolean doStackTrace = true; boolean isCompileException = false; boolean isServletException = false; Throwable compileException = null; String lineMessage = null; boolean lookupErrorPage = true; while (true) { if (rootExn instanceof LineMapException) lineMap = ((LineMapException) rootExn).getLineMap(); if (lookupErrorPage) { errorPageExn = rootExn; } if (rootExn instanceof DisplayableException) { doStackTrace = false; isCompileException = true; if (compileException == null) compileException = rootExn; } else if (rootExn instanceof CompileException) { doStackTrace = false; isCompileException = true; if (compileException == null) // ! isLineCompileException) compileException = rootExn; } else if (rootExn instanceof LineException) { if (lineMessage == null) lineMessage = rootExn.getMessage(); } if (rootExn instanceof BadRequestException) { isBadRequest = true; } if (rootExn instanceof OutOfMemoryError) { String msg = "TcpSocketLink OutOfMemory"; ShutdownSystem.shutdownOutOfMemory(msg); } if (location != null || !lookupErrorPage) { } else if (rootExn instanceof LineMapException && rootExn instanceof ServletException && !(rootExn instanceof LineCompileException) && rootExn.getCause() != null) { // hack to deal with JSP wrapping } else if (!isServletException) { // SRV.9.9.2 Servlet 2.4 // location = getErrorPage(rootExn, ServletException.class); location = getErrorPage(rootExn); isServletException = true; } else { location = getErrorPage(rootExn); lookupErrorPage = false; } if (location != null) lookupErrorPage = false; if (isBadRequest) break; Throwable cause = null; if (rootExn instanceof ServletException && !(rootExn instanceof LineCompileException)) cause = ((ServletException) rootExn).getRootCause(); else { lookupErrorPage = false; cause = rootExn.getCause(); } if (cause != null) rootExn = cause; else { break; } } if (location == null && lookupErrorPage) { location = getErrorPage(rootExn); } if (location == null) location = getErrorPage(500); if (isBadRequest) { // server/05a0, server/0532 if (rootExn instanceof CompileException) title = rootExn.getMessage(); else title = String.valueOf(rootExn); doStackTrace = false; isBadRequest = true; if (request instanceof CauchoRequest) ((CauchoRequest) request).killKeepalive("bad request: " + rootExn); response.resetBuffer(); response.setStatus(HttpServletResponse.SC_BAD_REQUEST); /* * if (location == null) log.warn(e.toString()); */ } else if (rootExn instanceof UnavailableException) { UnavailableException unAvail = (UnavailableException) rootExn; if (unAvail.isPermanent()) { response.setStatus(HttpServletResponse.SC_NOT_FOUND); title = "404 Not Found"; if (location == null) location = getErrorPage(HttpServletResponse.SC_NOT_FOUND); } else { response.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE); title = "503 Unavailable"; if (unAvail.getUnavailableSeconds() > 0) response.setIntHeader("Retry-After", unAvail.getUnavailableSeconds()); if (location == null) location = getErrorPage(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } } else { response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } if (location == null) location = _defaultLocation; if (log.isTraceEnabled()) log.trace(e.toString(), e); else if (isCompileException) { if (isBadRequest) log.trace(BadRequestException.class.getSimpleName() + ": " + compileException.getMessage()); else log.trace(compileException.getMessage()); } else if (!doStackTrace) log.trace(rootExn.toString()); else log.trace(e.toString(), e); if (location != null) { if (errorPageExn == null) errorPageExn = rootExn; request.setAttribute(JSP_EXCEPTION, errorPageExn); request.setAttribute(RequestDispatcher.ERROR_EXCEPTION, errorPageExn); request.setAttribute(RequestDispatcher.ERROR_EXCEPTION_TYPE, errorPageExn.getClass()); if (request instanceof HttpServletRequest) request.setAttribute(RequestDispatcher.ERROR_REQUEST_URI, ((HttpServletRequest) request).getRequestURI()); String servletName = getServletName(request); if (servletName != null) request.setAttribute(RequestDispatcher.ERROR_SERVLET_NAME, servletName); request.setAttribute(RequestDispatcher.ERROR_STATUS_CODE, new Integer(500)); request.setAttribute(RequestDispatcher.ERROR_MESSAGE, errorPageExn.getMessage()); try { RequestDispatcher disp = null; // can't use filters because of error pages due to filters // or security. WebApp webApp = getWebApp(); if (webApp != null) disp = webApp.getRequestDispatcher(location); else if (_host != null) disp = _host.getWebAppContainer().getRequestDispatcher(location); if (disp != null) { ((RequestDispatcherImpl) disp).error(request, response); return; } } catch (Throwable e1) { log.info(e1.toString(), e1); rootExn = e1; } } response.setContentType("text/html"); String encoding = CharacterEncoding.getLocalEncoding(); if (encoding != null) response.setCharacterEncoding(encoding); else { Locale locale = Locale.getDefault(); if (!"ISO-8859-1".equals(Encoding.getMimeName(locale))) response.setLocale(Locale.getDefault()); else response.setCharacterEncoding("utf-8"); } PrintWriter out; try { out = response.getWriter(); } catch (IllegalStateException e1) { log.trace(e1.toString(), e1); out = new PrintWriter(new OutputStreamWriter(response.getOutputStream())); } if (isDevelopmentModeErrorPage()) { out.println("<html>"); if (!response.isCommitted()) out.println("<head><title>" + escapeHtml(title) + "</title></head>"); out.println("<body>"); out.println("<h1>" + escapeHtml(title) + "</h1>"); out.println("<code><pre>"); if (debug && !CurrentTime.isTest()) doStackTrace = true; if (doStackTrace) { out.println("<script language='javascript' type='text/javascript'>"); out.println("function show() { document.getElementById('trace').style.display = ''; }"); out.println("</script>"); out.print("<a style=\"text-decoration\" href=\"javascript:show();\">[show]</a> "); } if (compileException instanceof DisplayableException) { // ioc/0000 // XXX: dispExn.print doesn't normalize user.name // dispExn.print(out); out.println(escapeHtml(compileException.getMessage())); } else if (compileException != null) out.println(escapeHtml(compileException.getMessage())); else out.println(escapeHtml(rootExn.toString())); if (doStackTrace) { out.println("<span id=\"trace\" style=\"display:none\">"); printStackTrace(out, lineMessage, e, rootExn, lineMap); out.println("</span>"); } /* * if (doStackTrace || debug) { printStackTrace(out, lineMessage, e, rootExn, lineMap); } */ out.println("</pre></code>"); printVersion(out); out.println("</body></html>"); } else { // non-development mode out.println("<html>"); out.println("<title>Server Error</title>"); out.println("<body>"); out.println("<h1>Server Error</h1>"); out.println("<p>The server is temporarily unavailable due to an"); out.println("internal error. Please notify the system administrator"); out.println("of this problem.</p>"); out.println("<pre><code>"); out.println("Date: " + QDate.formatISO8601(CurrentTime.getCurrentTime())); out.println("</code></pre>"); printVersion(out); out.println("</body></html>"); } String userAgent = request.getHeader("User-Agent"); if (userAgent != null && userAgent.indexOf("MSIE") >= 0) { out.print(MSIE_PADDING); } out.close(); }
From source file:net.lightbody.bmp.proxy.jetty.jetty.servlet.Default.java
protected boolean passConditionalHeaders(HttpServletRequest request, HttpServletResponse response, Resource resource) throws IOException { if (!request.getMethod().equals(HttpRequest.__HEAD) && request.getAttribute(Dispatcher.__INCLUDE_REQUEST_URI) == null) { // If we have meta data for the file // Try a direct match for most common requests. Avoids // parsing the date. ResourceCache.ResourceMetaData metaData = _httpContext.getResourceMetaData(resource); if (metaData != null) { String ifms = request.getHeader(HttpFields.__IfModifiedSince); String mdlm = metaData.getLastModified(); if (ifms != null && mdlm != null && ifms.equals(mdlm)) { response.reset(); response.setStatus(HttpResponse.__304_Not_Modified); response.flushBuffer();//from www .j a v a 2 s . c om return false; } } long date = 0; // Parse the if[un]modified dates and compare to resource if ((date = request.getDateHeader(HttpFields.__IfUnmodifiedSince)) > 0) { if (resource.lastModified() / 1000 > date / 1000) { response.sendError(HttpResponse.__412_Precondition_Failed); return false; } } if ((date = request.getDateHeader(HttpFields.__IfModifiedSince)) > 0) { if (resource.lastModified() / 1000 <= date / 1000) { response.reset(); response.setStatus(HttpResponse.__304_Not_Modified); response.flushBuffer(); return false; } } } return true; }