List of usage examples for javax.servlet.http HttpServletResponse setDateHeader
public void setDateHeader(String name, long date);
From source file:gsn.http.OutputStructureHandler.java
public void handle(HttpServletRequest request, HttpServletResponse response) throws IOException { response.setStatus(HttpServletResponse.SC_OK); String vsName = request.getParameter("name"); VSensorConfig sensorConfig = Mappings.getVSensorConfig(vsName); logger.info(new StringBuilder().append("Structure request for *").append(vsName).append("* received.") .toString());// w ww .j a va 2s .c om StringBuilder sb = new StringBuilder("<virtual-sensor name=\"").append(vsName).append("\">\n"); sb.append( "<field name=\"time\" type=\"string\" description=\"The timestamp associated with the stream element\" unit=\"\"/>\n"); for (DataField df : sensorConfig.getOutputStructure()) { sb.append("<field name=\"").append(df.getName()).append("\" ").append("type=\"").append(df.getType()) .append("\" ").append("description=\"") .append(StringEscapeUtils.escapeXml(df.getDescription())); if (df.getUnit() != null && df.getUnit().trim().length() != 0) sb.append("\" ").append("unit=\"").append(df.getUnit()); else sb.append("\" ").append("unit=\"").append(""); sb.append("\" />\n"); } sb.append("</virtual-sensor>"); response.setHeader("Cache-Control", "no-store"); response.setDateHeader("Expires", 0); response.setHeader("Pragma", "no-cache"); response.getWriter().write(sb.toString()); }
From source file:org.exist.webstart.JnlpWriter.java
/** * Send JAR or JAR.PACK.GZ file to end user. * * @param filename Name of JAR file/*from w w w . ja va 2 s. c o m*/ * @param response Object for writing to end user. * @throws java.io.IOException */ void sendJar(JnlpJarFiles jnlpFiles, String filename, HttpServletRequest request, HttpServletResponse response) throws IOException { logger.debug("Send jar file " + filename); final File localFile = jnlpFiles.getJarFile(filename); if (localFile == null || !localFile.exists()) { response.sendError(HttpServletResponse.SC_NOT_FOUND, "Jar file '" + filename + "' not found."); return; } logger.debug("Actual file " + localFile.getAbsolutePath()); if (localFile.getName().endsWith(".jar")) { //response.setHeader(CONTENT_ENCODING, JAR_MIME_TYPE); response.setContentType(JAR_MIME_TYPE); } else if (localFile.getName().endsWith(".jar.pack.gz")) { response.setHeader(CONTENT_ENCODING, PACK200_GZIP_ENCODING); response.setContentType(PACK_MIME_TYPE); } // It is very improbable that a 64 bit jar is needed, but // it is better to be ready // response.setContentLength(Integer.parseInt(Long.toString(localFile.length()))); response.setHeader("Content-Length", Long.toString(localFile.length())); response.setDateHeader("Last-Modified", localFile.lastModified()); final FileInputStream fis = new FileInputStream(localFile); final ServletOutputStream os = response.getOutputStream(); try { // Transfer bytes from in to out final byte[] buf = new byte[4096]; int len; while ((len = fis.read(buf)) > 0) { os.write(buf, 0, len); } } catch (final IllegalStateException ex) { logger.debug(ex.getMessage()); } catch (final IOException ex) { logger.debug("Ignore IOException for '" + filename + "'"); } os.flush(); os.close(); fis.close(); }
From source file:org.overlord.dtgov.ui.server.servlets.DeploymentDownloadServlet.java
/** * Downloads the content of the artifact. * @param httpResponse/*from w ww. j a v a 2 s. com*/ * @param client * @param artyType * @param artifact * @throws Exception */ protected void doDownloadContent(HttpServletResponse httpResponse, SrampAtomApiClient client, ArtifactType artyType, BaseArtifactType artifact) throws Exception { InputStream artifactContent = null; try { // Set the content-disposition String artifactName = artifact.getName(); String disposition = String.format("attachment; filename=\"%1$s\"", artifactName); //$NON-NLS-1$ httpResponse.setHeader("Content-Disposition", disposition); //$NON-NLS-1$ // Set the content-type ArtifactContentTypeVisitor ctVizzy = new ArtifactContentTypeVisitor(); ArtifactVisitorHelper.visitArtifact(ctVizzy, artifact); String contentType = ctVizzy.getContentType().toString(); httpResponse.setHeader("Content-Type", contentType); //$NON-NLS-1$ // Set the content-size (if possible) if (artifact instanceof DocumentArtifactType) { DocumentArtifactType d = (DocumentArtifactType) artifact; long size = d.getContentSize(); if (size != -1) { httpResponse.setHeader("Content-Size", String.valueOf(size)); //$NON-NLS-1$ } } // Make sure the browser doesn't cache it Date now = new Date(); httpResponse.setDateHeader("Date", now.getTime()); //$NON-NLS-1$ httpResponse.setDateHeader("Expires", now.getTime() - 86400000L); //$NON-NLS-1$ httpResponse.setHeader("Pragma", "no-cache"); //$NON-NLS-1$ //$NON-NLS-2$ httpResponse.setHeader("Cache-control", "no-cache, no-store, must-revalidate"); //$NON-NLS-1$ //$NON-NLS-2$ artifactContent = client.getArtifactContent(artyType, artifact.getUuid()); IOUtils.copy(artifactContent, httpResponse.getOutputStream()); } finally { IOUtils.closeQuietly(artifactContent); } }
From source file:de.micromata.genome.gwiki.web.GWikiServlet.java
protected void serveStatic(String page, GWikiContext wikiContext) throws ServletException, IOException { String res = "/" + page; HttpServletResponse resp = wikiContext.getResponse(); InputStream is = getStaticResource(res, wikiContext); if (is == null) { resp.sendError(HttpServletResponse.SC_NOT_FOUND); return;/*from ww w . ja v a 2 s . co m*/ } if (etagTimeOut > 1) { String etag = wikiContext.getWikiWeb().geteTagWiki(); String ifnm = wikiContext.getRequest().getHeader("If-None-Match"); if (StringUtils.equals(etag, ifnm) == true) { wikiContext.getResponse().sendError(304, "Not modified"); return; } wikiContext.getResponse().addHeader("ETag", etag); long nt = new Date().getTime() + etagTimeOut; } long nt = new Date().getTime() + etagTimeOut; String mime = wikiContext.getWikiWeb().getDaoContext().getMimeTypeProvider().getMimeType(wikiContext, page); if (StringUtils.equals(mime, "application/x-shockwave-flash")) { resp.setHeader("Cache-Control", "cache, must-revalidate"); resp.setHeader("Pragma", "public"); } if (mime != null) { resp.setContentType(mime); } resp.setDateHeader("Expires", nt); resp.setHeader("Cache-Control", "max-age=86400, public"); if (mime != null) { resp.setContentType(mime); } byte[] data = IOUtils.toByteArray(is); IOUtils.closeQuietly(is); resp.setContentLength(data.length); IOUtils.write(data, resp.getOutputStream()); }
From source file:org.apache.catalina.core.StandardWrapperValve.java
/** * Invoke the servlet we are managing, respecting the rules regarding * servlet lifecycle and SingleThreadModel support. * * @param request Request to be processed * @param response Response to be produced * @param valveContext Valve context used to forward to the next Valve * * @exception IOException if an input/output error occurred * @exception ServletException if a servlet error occurred *///from w w w . j av a2 s . c o m public final void invoke(Request request, Response response, ValveContext valveContext) throws IOException, ServletException { // Initialize local variables we may need boolean unavailable = false; Throwable throwable = null; // This should be a Request attribute... long t1 = System.currentTimeMillis(); requestCount++; StandardWrapper wrapper = (StandardWrapper) getContainer(); HttpRequest hrequest = (HttpRequest) request; Servlet servlet = null; HttpServletRequest hreq = (HttpServletRequest) request.getRequest(); HttpServletResponse hres = (HttpServletResponse) response.getResponse(); // Check for the application being marked unavailable if (!((Context) wrapper.getParent()).getAvailable()) { hres.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, sm.getString("standardContext.isUnavailable")); unavailable = true; } // Check for the servlet being marked unavailable if (!unavailable && wrapper.isUnavailable()) { log(sm.getString("standardWrapper.isUnavailable", wrapper.getName())); if (hres == null) { ; // NOTE - Not much we can do generically } else { long available = wrapper.getAvailable(); if ((available > 0L) && (available < Long.MAX_VALUE)) { hres.setDateHeader("Retry-After", available); hres.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, sm.getString("standardWrapper.isUnavailable", wrapper.getName())); } else if (available == Long.MAX_VALUE) { hres.sendError(HttpServletResponse.SC_NOT_FOUND, sm.getString("standardWrapper.notFound", wrapper.getName())); } } unavailable = true; } // Allocate a servlet instance to process this request try { if (!unavailable) { servlet = wrapper.allocate(); } } catch (UnavailableException e) { long available = wrapper.getAvailable(); if ((available > 0L) && (available < Long.MAX_VALUE)) { hres.setDateHeader("Retry-After", available); hres.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, sm.getString("standardWrapper.isUnavailable", wrapper.getName())); } else if (available == Long.MAX_VALUE) { hres.sendError(HttpServletResponse.SC_NOT_FOUND, sm.getString("standardWrapper.notFound", wrapper.getName())); } } catch (ServletException e) { log(sm.getString("standardWrapper.allocateException", wrapper.getName()), e); throwable = e; exception(request, response, e); servlet = null; } catch (Throwable e) { log(sm.getString("standardWrapper.allocateException", wrapper.getName()), e); throwable = e; exception(request, response, e); servlet = null; } // Acknowlege the request try { response.sendAcknowledgement(); } catch (IOException e) { hreq.removeAttribute(Globals.JSP_FILE_ATTR); log(sm.getString("standardWrapper.acknowledgeException", wrapper.getName()), e); throwable = e; exception(request, response, e); } catch (Throwable e) { log(sm.getString("standardWrapper.acknowledgeException", wrapper.getName()), e); throwable = e; exception(request, response, e); servlet = null; } MessageBytes requestPathMB = null; if (hreq != null) { requestPathMB = hrequest.getRequestPathMB(); } hreq.setAttribute(ApplicationFilterFactory.DISPATCHER_TYPE_ATTR, ApplicationFilterFactory.REQUEST_INTEGER); hreq.setAttribute(ApplicationFilterFactory.DISPATCHER_REQUEST_PATH_ATTR, requestPathMB); // Create the filter chain for this request ApplicationFilterFactory factory = ApplicationFilterFactory.getInstance(); ApplicationFilterChain filterChain = factory.createFilterChain((ServletRequest) request, wrapper, servlet); // Call the filter chain for this request // NOTE: This also calls the servlet's service() method try { String jspFile = wrapper.getJspFile(); if (jspFile != null) hreq.setAttribute(Globals.JSP_FILE_ATTR, jspFile); else hreq.removeAttribute(Globals.JSP_FILE_ATTR); if ((servlet != null) && (filterChain != null)) { filterChain.doFilter(hreq, hres); } hreq.removeAttribute(Globals.JSP_FILE_ATTR); } catch (ClientAbortException e) { hreq.removeAttribute(Globals.JSP_FILE_ATTR); throwable = e; exception(request, response, e); } catch (IOException e) { hreq.removeAttribute(Globals.JSP_FILE_ATTR); log(sm.getString("standardWrapper.serviceException", wrapper.getName()), e); throwable = e; exception(request, response, e); } catch (UnavailableException e) { hreq.removeAttribute(Globals.JSP_FILE_ATTR); log(sm.getString("standardWrapper.serviceException", wrapper.getName()), e); // throwable = e; // exception(request, response, e); wrapper.unavailable(e); long available = wrapper.getAvailable(); if ((available > 0L) && (available < Long.MAX_VALUE)) { hres.setDateHeader("Retry-After", available); hres.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, sm.getString("standardWrapper.isUnavailable", wrapper.getName())); } else if (available == Long.MAX_VALUE) { hres.sendError(HttpServletResponse.SC_NOT_FOUND, sm.getString("standardWrapper.notFound", wrapper.getName())); } // Do not save exception in 'throwable', because we // do not want to do exception(request, response, e) processing } catch (ServletException e) { hreq.removeAttribute(Globals.JSP_FILE_ATTR); Throwable rootCause = e; Throwable rootCauseCheck = null; // Extra aggressive rootCause finding do { try { rootCauseCheck = (Throwable) PropertyUtils.getProperty(rootCause, "rootCause"); if (rootCauseCheck != null) rootCause = rootCauseCheck; } catch (ClassCastException ex) { rootCauseCheck = null; } catch (IllegalAccessException ex) { rootCauseCheck = null; } catch (NoSuchMethodException ex) { rootCauseCheck = null; } catch (java.lang.reflect.InvocationTargetException ex) { rootCauseCheck = null; } } while (rootCauseCheck != null); if (!(rootCause instanceof ClientAbortException)) { log(sm.getString("standardWrapper.serviceException", wrapper.getName()), rootCause); } throwable = e; exception(request, response, e); } catch (Throwable e) { hreq.removeAttribute(Globals.JSP_FILE_ATTR); log(sm.getString("standardWrapper.serviceException", wrapper.getName()), e); throwable = e; exception(request, response, e); } // Release the filter chain (if any) for this request try { if (filterChain != null) filterChain.release(); } catch (Throwable e) { log(sm.getString("standardWrapper.releaseFilters", wrapper.getName()), e); if (throwable == null) { throwable = e; exception(request, response, e); } } // Deallocate the allocated servlet instance try { if (servlet != null) { wrapper.deallocate(servlet); } } catch (Throwable e) { log(sm.getString("standardWrapper.deallocateException", wrapper.getName()), e); if (throwable == null) { throwable = e; exception(request, response, e); } } // If this servlet has been marked permanently unavailable, // unload it and release this instance try { if ((servlet != null) && (wrapper.getAvailable() == Long.MAX_VALUE)) { wrapper.unload(); } } catch (Throwable e) { log(sm.getString("standardWrapper.unloadException", wrapper.getName()), e); if (throwable == null) { throwable = e; exception(request, response, e); } } long t2 = System.currentTimeMillis(); long time = t2 - t1; processingTime += time; if (time > maxTime) maxTime = time; if (time < minTime) minTime = time; }
From source file:org.ejbca.ui.web.protocol.OCSPServlet.java
/** * RFC 2560 does not specify how cache headers should be used, but RFC 5019 does. Therefore we will only * add the headers if the requirements of RFC 5019 is fulfilled: A GET-request, a single embedded reponse, * the response contains a nextUpdate and no nonce is present. * @param maxAge is the margin to Expire when using max-age in milliseconds * @throws org.bouncycastle.cert.ocsp.OCSPException *//*from w ww. ja va 2 s. co m*/ private void addRfc5019CacheHeaders(HttpServletRequest request, HttpServletResponse response, OcspResponseInformation ocspResponseInformation) throws IOException, org.bouncycastle.cert.ocsp.OCSPException { if (!ocspResponseInformation.shouldAddCacheHeaders()) { return; } if (ocspResponseInformation.getMaxAge() <= 0) { if (log.isDebugEnabled()) { log.debug( "Will not add RFC 5019 cache headers: RFC 5019 6.2: max-age should be 'later than thisUpdate but earlier than nextUpdate'."); } return; } final long now = System.currentTimeMillis(); final long thisUpdate = ocspResponseInformation.getThisUpdate(); final long nextUpdate = ocspResponseInformation.getNextUpdate(); // RFC 5019 6.2: Date: The date and time at which the OCSP server generated the HTTP response. // On JBoss AS the "Date"-header is cached for 1 second, so this value will be overwritten and off by up to a second response.setDateHeader("Date", now); // RFC 5019 6.2: Last-Modified: date and time at which the OCSP responder last modified the response. == thisUpdate response.setDateHeader("Last-Modified", thisUpdate); // RFC 5019 6.2: Expires: This date and time will be the same as the nextUpdate timestamp in the OCSP response itself. response.setDateHeader("Expires", nextUpdate); // This is overridden by max-age on HTTP/1.1 compatible components // RFC 5019 6.2: This profile RECOMMENDS that the ETag value be the ASCII HEX representation of the SHA1 hash of the OCSPResponse structure. response.setHeader("ETag", "\"" + ocspResponseInformation.getResponseHeader() + "\""); if (ocspResponseInformation.isExplicitNoCache()) { // Note that using no-cache here is not conforming to RFC5019, but with more recent CABForum discussions it seems RFC5019 will not // be followed, or will be changed. (See ECA-3289) response.setHeader("Cache-Control", "no-cache, must-revalidate"); //HTTP 1.1 response.setHeader("Pragma", "no-cache"); //HTTP 1.0 } else { // Max age is retrieved in milliseconds, but it must be in seconds in the cache-control header long maxAge = ocspResponseInformation.getMaxAge(); if (maxAge >= (nextUpdate - thisUpdate)) { maxAge = nextUpdate - thisUpdate - 1; log.warn(intres.getLocalizedMessage("ocsp.shrinkmaxage", maxAge)); } response.setHeader("Cache-Control", "max-age=" + (maxAge / 1000L) + ",public,no-transform,must-revalidate"); } }
From source file:org.apache.sling.reqanalyzer.impl.RequestAnalyzerWebConsole.java
@Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { if (req.getRequestURI().endsWith(RAW_FILE_MARKER) || req.getRequestURI().endsWith(ZIP_FILE_MARKER)) { InputStream input = null; OutputStream output = null; try {//w ww .j a v a2 s . c o m input = new FileInputStream(this.logFile); output = resp.getOutputStream(); if (req.getRequestURI().endsWith(ZIP_FILE_MARKER)) { ZipOutputStream zip = new ZipOutputStream(output); zip.setLevel(Deflater.BEST_SPEED); ZipEntry entry = new ZipEntry(this.logFile.getName()); entry.setTime(this.logFile.lastModified()); entry.setMethod(ZipEntry.DEFLATED); zip.putNextEntry(entry); output = zip; resp.setContentType("application/zip"); } else { resp.setContentType("text/plain"); resp.setCharacterEncoding("UTF-8"); resp.setHeader("Content-Length", String.valueOf(this.logFile.length())); // might be bigger than } resp.setDateHeader("Last-Modified", this.logFile.lastModified()); IOUtils.copy(input, output); } catch (IOException ioe) { throw new ServletException("Cannot create copy of log file", ioe); } finally { IOUtils.closeQuietly(input); if (output instanceof ZipOutputStream) { ((ZipOutputStream) output).closeEntry(); ((ZipOutputStream) output).finish(); } } resp.flushBuffer(); } else if (req.getRequestURI().endsWith(WINDOW_MARKER)) { if (canOpenSwingGui(req)) { showWindow(); } String target = req.getRequestURI(); target = target.substring(0, target.length() - WINDOW_MARKER.length()); resp.sendRedirect(target); resp.flushBuffer(); } else { super.service(req, resp); } }
From source file:org.commonfarm.web.ECSideFilter.java
public void setResponseHeaders(HttpServletRequest request, HttpServletResponse response, String exportFileName) {/*from w w w . jav a2 s. c o m*/ String mimeType = MimeUtils.getFileMimeType(exportFileName); // response.reset(); if (StringUtils.isNotBlank(mimeType)) { response.setContentType(mimeType); } // response.setHeader("Content-Type",mimeType); try { exportFileName = encodeFileName(request, exportFileName); } catch (UnsupportedEncodingException e) { String errorMessage = "Unsupported response.getCharacterEncoding() [" + "UTF-8" + "]."; logger.error("TDExportFilter.setResponseHeaders() - " + errorMessage); } response.setHeader("Content-Disposition", "attachment;filename=\"" + exportFileName + "\""); response.setHeader("Content-Transfer-Encoding", "binary"); // response.setHeader("Cache-Control","private"); // response.setHeader("Pragma", "private"); response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0"); response.setHeader("Pragma", "public"); response.setDateHeader("Expires", (System.currentTimeMillis() + 1000)); }
From source file:com.ningpai.common.util.CaptchaController.java
@RequestMapping("/captcha") public void writeCaptcha(HttpServletRequest request, HttpServletResponse response) { byte[] captchaChallengeAsJpeg = null; // the output stream to render the captcha image as jpeg into ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream(); try {// www . j a v a2 s . c om // get the session id that will identify the generated captcha. // the same id must be used to validate the response, the session id is a good candidate! String captchaId = request.getSession().getId(); BufferedImage challenge = captchaService.getImageChallengeForID(captchaId, request.getLocale()); try { ImageIO.write(challenge, CAPTCHA_IMAGE_FORMAT, jpegOutputStream); } catch (IOException e) { } } catch (IllegalArgumentException e) { try { response.sendError(HttpServletResponse.SC_NOT_FOUND); } catch (IOException e1) { } return; } catch (CaptchaServiceException e) { try { response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } catch (IOException e1) { } return; } captchaChallengeAsJpeg = jpegOutputStream.toByteArray(); // flush it in the response response.setHeader("Cache-Control", "no-store"); response.setHeader("Pragma", "no-cache"); response.setDateHeader("Expires", 0); response.setContentType("image/" + CAPTCHA_IMAGE_FORMAT); ServletOutputStream responseOutputStream; try { responseOutputStream = response.getOutputStream(); responseOutputStream.write(captchaChallengeAsJpeg); responseOutputStream.flush(); responseOutputStream.close(); } catch (IOException e) { } }
From source file:org.opencms.workplace.CmsLogin.java
/** * Public constructor for login page.<p> * /*from w ww . j a va 2s.c o m*/ * @param context the JSP page context object * @param req the JSP request * @param res the JSP response */ public CmsLogin(PageContext context, HttpServletRequest req, HttpServletResponse res) { super(context, req, res); // this page must never be cached res.setDateHeader(CmsRequestUtil.HEADER_LAST_MODIFIED, System.currentTimeMillis()); CmsRequestUtil.setNoCacheHeaders(res); // divine the best locale from the users browser settings CmsAcceptLanguageHeaderParser parser = new CmsAcceptLanguageHeaderParser(req, OpenCms.getWorkplaceManager().getDefaultLocale()); List<Locale> acceptedLocales = parser.getAcceptedLocales(); List<Locale> workplaceLocales = OpenCms.getWorkplaceManager().getLocales(); m_locale = OpenCms.getLocaleManager().getFirstMatchingLocale(acceptedLocales, workplaceLocales); if (m_locale == null) { // no match found - use OpenCms default locale m_locale = OpenCms.getWorkplaceManager().getDefaultLocale(); } }