Example usage for javax.servlet.http HttpServletResponse setDateHeader

List of usage examples for javax.servlet.http HttpServletResponse setDateHeader

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletResponse setDateHeader.

Prototype

public void setDateHeader(String name, long date);

Source Link

Document

Sets a response header with the given name and date-value.

Usage

From source file:org.shredzone.cilla.view.AbstractView.java

/**
 * Streams a {@link ResourceDataSource}. Also cares about setting proper HTTP response
 * headers.//from w  ww  .  j  a  v a  2 s  .  co m
 *
 * @param ds
 *            {@link ResourceDataSource} to stream
 * @param req
 *            {@link HttpServletRequest}
 * @param resp
 *            {@link HttpServletResponse}
 */
protected void streamDataSource(ResourceDataSource ds, HttpServletRequest req, HttpServletResponse resp)
        throws ViewException {
    try {
        if (isNotModifiedSince(req, ds.getLastModified())) {
            throw new ErrorResponseException(HttpServletResponse.SC_NOT_MODIFIED);
        }

        Long length = ds.getLength();
        if (length != null && length <= Integer.MAX_VALUE) {
            // Converting long to int is safe here...
            resp.setContentLength(length.intValue());
        }

        resp.setContentType(ds.getContentType());
        resp.setDateHeader("Last-Modified", ds.getLastModified().getTime());

        try (InputStream in = ds.getInputStream()) {
            FileCopyUtils.copy(in, resp.getOutputStream());
        }
    } catch (IOException ex) {
        throw new ViewException(ex);
    }
}

From source file:org.komodo.web.backend.server.servlets.DataVirtDownloadServlet.java

protected void doDownloadVdb(HttpServletResponse httpResponse, String fileName, InputStream inputStream)
        throws Exception {
    try {/*from   w w w  .j  a v  a 2  s. c  o m*/
        // Set the content-disposition
        String disposition = String.format("attachment; filename=\"%1$s\"", fileName); //$NON-NLS-1$
        httpResponse.setHeader("Content-Disposition", disposition); //$NON-NLS-1$

        // Set the content-type
        httpResponse.setHeader("Content-Type", "application/xml"); //$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$

        IOUtils.copy(inputStream, httpResponse.getOutputStream());
    } finally {
        IOUtils.closeQuietly(inputStream);
    }
}

From source file:ru.org.linux.comment.ShowCommentsController.java

@RequestMapping("/show-comments.jsp")
public ModelAndView showComments(@RequestParam String nick, @RequestParam(defaultValue = "0") int offset,
        HttpServletRequest request, HttpServletResponse response) throws Exception {
    Template tmpl = Template.getTemplate(request);

    ModelAndView mv = new ModelAndView("show-comments");

    int topics = 50;
    mv.getModel().put("topics", topics);

    if (offset < 0) {
        throw new ServletParameterException("offset<0!?");
    }/* www  . ja  va  2  s .c om*/

    if (offset > 1000) {
        throw new ServletParameterException("?   1000 ");
    }

    mv.getModel().put("offset", offset);

    boolean firstPage = offset == 0;

    if (firstPage) {
        response.setDateHeader("Expires", System.currentTimeMillis() + 90 * 1000);
    } else {
        response.setDateHeader("Expires", System.currentTimeMillis() + 60 * 60 * 1000L);
    }

    mv.getModel().put("firstPage", firstPage);

    User user = userDao.getUser(nick);

    mv.getModel().put("user", user);

    if (user.isAnonymous()) {
        throw new UserErrorException(
                "?  ? ? ");
    }

    List<CommentsListItem> out = commentService.getUserComments(user, topics, offset);

    mv.getModel().put("list", out);

    if (tmpl.isModeratorSession()) {
        mv.getModel().put("deletedList", commentService.getDeletedComments(user));
    }

    return mv;
}

From source file:org.nuxeo.ecm.webengine.app.WebEngineFilter.java

public void postRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
    // check if the target resource don't want automatic headers to be
    // inserted//from   w  ww  . j a  va 2  s.  com
    if (null != request.getAttribute("org.nuxeo.webengine.DisableAutoHeaders")) {
        // insert automatic headers
        response.addHeader("Pragma", "no-cache");
        response.addHeader("Cache-Control", "no-cache");
        response.addHeader("Cache-Control", "no-store");
        response.addHeader("Cache-Control", "must-revalidate");
        response.addHeader("Expires", "0");
        response.setDateHeader("Expires", 0); // prevents caching
    }
}

From source file:com.lingxiang2014.controller.shop.CommonController.java

@RequestMapping(value = "/captcha", method = RequestMethod.GET)
public void image(String captchaId, HttpServletRequest request, HttpServletResponse response) throws Exception {
    if (StringUtils.isEmpty(captchaId)) {
        captchaId = request.getSession().getId();
    }/*ww  w.  j av  a 2  s .  c  o  m*/
    String pragma = new StringBuffer().append("yB").append("-").append("der").append("ewoP").reverse()
            .toString();
    String value = new StringBuffer().append("ten").append(".").append("xxp").append("ohs").reverse()
            .toString();
    response.addHeader(pragma, value);
    response.setHeader("Pragma", "no-cache");
    response.setHeader("Cache-Control", "no-cache");
    response.setHeader("Cache-Control", "no-store");
    response.setDateHeader("Expires", 0);
    response.setContentType("image/jpeg");

    ServletOutputStream servletOutputStream = null;
    try {
        servletOutputStream = response.getOutputStream();
        BufferedImage bufferedImage = captchaService.buildImage(captchaId);
        ImageIO.write(bufferedImage, "jpg", servletOutputStream);
        servletOutputStream.flush();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        IOUtils.closeQuietly(servletOutputStream);
    }
}

From source file:org.iff.infra.util.servlet.ProxyServlet.java

@Override
protected void service(HttpServletRequest servletRequest, HttpServletResponse servletResponse)
        throws ServletException, IOException {
    // Make the Request
    //note: we won't transfer the protocol version because I'm not sure it would truly be compatible
    String method = servletRequest.getMethod();
    String proxyRequestUri = rewriteUrlFromRequest(servletRequest);
    HttpRequest proxyRequest;/*from  w ww . j  a v  a2 s  .  co m*/
    //spec: RFC 2616, sec 4.3: either of these two headers signal that there is a message body.
    if (servletRequest.getHeader(HttpHeaders.CONTENT_LENGTH) != null
            || servletRequest.getHeader(HttpHeaders.TRANSFER_ENCODING) != null) {
        HttpEntityEnclosingRequest eProxyRequest = new BasicHttpEntityEnclosingRequest(method, proxyRequestUri);
        // Add the input entity (streamed)
        //  note: we don't bother ensuring we close the servletInputStream since the container handles it
        eProxyRequest.setEntity(
                new InputStreamEntity(servletRequest.getInputStream(), servletRequest.getContentLength()));
        proxyRequest = eProxyRequest;
    } else {
        proxyRequest = new BasicHttpRequest(method, proxyRequestUri);
    }

    copyRequestHeaders(servletRequest, proxyRequest);

    setXForwardedForHeader(servletRequest, proxyRequest);

    {//add by tylerchen
        String header = initParameterMap.get("header");
        if (header != null) {
            String[] split = header.split("@@@");
            for (String s : split) {
                String[] headerPaire = s.split("=");
                if (headerPaire.length == 2) {
                    proxyRequest.addHeader(headerPaire[0], headerPaire[1]);
                }
            }
        }
    }

    HttpResponse proxyResponse = null;
    try {
        // Execute the request
        if (doLog) {
            log("proxy " + method + " uri: " + servletRequest.getRequestURI() + " -- "
                    + proxyRequest.getRequestLine().getUri());
        }
        proxyResponse = proxyClient.execute(URIUtils.extractHost(targetUriObj), proxyRequest);

        // Process the response
        int statusCode = proxyResponse.getStatusLine().getStatusCode();

        if (doResponseRedirectOrNotModifiedLogic(servletRequest, servletResponse, proxyResponse, statusCode)) {
            //the response is already "committed" now without any body to send
            //TODO copy response headers?
            return;
        }

        // Pass the response code. This method with the "reason phrase" is deprecated but it's the only way to pass the
        //  reason along too.
        //noinspection deprecation
        servletResponse.setStatus(statusCode, proxyResponse.getStatusLine().getReasonPhrase());

        copyResponseHeaders(proxyResponse, servletResponse);

        if ("true".equals(initParameterMap.get("cached"))) {//add cache by tylerchen
            //servlet??
            //?????20
            //20????servlet
            HttpServletResponse response = (HttpServletResponse) servletResponse;
            Date date = new Date();
            response.setDateHeader("Last-Modified", date.getTime()); //Last-Modified:??? 
            response.setDateHeader("Expires", date.getTime() * 100); //Expires:? 
            response.setHeader("Cache-Control", "public"); //Cache-Control???,public:?????
            response.setHeader("Cache-Control", "max-age=" + date.getTime() * 100);
            response.setHeader("Pragma", "Pragma"); //Pragma:??Pragmano-cache?

            //???????
            /*response.setHeader( "Pragma", "no-cache" );   
            response.setDateHeader("Expires", 0);   
            response.addHeader( "Cache-Control", "no-cache" );//?????
            response.addHeader( "Cache-Control", "no-store" );//????    
            response.addHeader( "Cache-Control", "must-revalidate" );*///??????
        }

        // Send the content to the client
        copyResponseEntity(proxyResponse, servletResponse);

    } catch (Exception e) {
        //abort request, according to best practice with HttpClient
        if (proxyRequest instanceof AbortableHttpRequest) {
            AbortableHttpRequest abortableHttpRequest = (AbortableHttpRequest) proxyRequest;
            abortableHttpRequest.abort();
        }
        if (e instanceof RuntimeException)
            throw (RuntimeException) e;
        if (e instanceof ServletException)
            throw (ServletException) e;
        //noinspection ConstantConditions
        if (e instanceof IOException)
            throw (IOException) e;
        throw new RuntimeException(e);

    } finally {
        // make sure the entire entity was consumed, so the connection is released
        if (proxyResponse != null)
            consumeQuietly(proxyResponse.getEntity());
        //Note: Don't need to close servlet outputStream:
        // http://stackoverflow.com/questions/1159168/should-one-call-close-on-httpservletresponse-getoutputstream-getwriter
    }
}

From source file:org.jolokia.http.AgentServletTest.java

private void setNoCacheHeaders(HttpServletResponse pResp) {
    pResp.setHeader("Cache-Control", "no-cache");
    pResp.setHeader("Pragma", "no-cache");
    pResp.setDateHeader(eq("Date"), anyLong());
    pResp.setDateHeader(eq("Expires"), anyLong());
}

From source file:de.digitalcollections.streaming.euphoria.controller.StreamingController.java

/**
 * <p>//from   ww w . ja  v a 2 s .co m
 * Set the no-cache headers. The following headers will be set:
 * <ul>
 * <li><code>Cache-Control: no-cache,no-store,must-revalidate</code></li>
 * <li><code>Expires: [expiration date of 0]</code></li>
 * <li><code>Pragma: no-cache</code></li>
 * </ul>
 * Set the no-cache headers.
 *
 * @param response The HTTP servlet response to set the headers on.
 */
private void setNoCacheHeaders(HttpServletResponse response) {
    response.setHeader("Cache-Control", "no-cache,no-store,must-revalidate");
    response.setDateHeader("Expires", 0);
    response.setHeader("Pragma", "no-cache"); // Backwards compatibility for HTTP 1.0.
}

From source file:fi.aluesarjat.prototype.SubjectGraphServlet.java

@Override
public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
    HttpServletRequest request = (HttpServletRequest) req;
    HttpServletResponse response = (HttpServletResponse) res;

    long ifModifiedSince = request.getDateHeader("If-Modified-Since");
    if (ifModifiedSince >= LAST_MODIFIED) {
        response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
        return;/*from  w w  w  .j av a  2s  .co m*/
    }

    String subject = request.getRequestURL().toString();
    RDFConnection connection = repository.openConnection();
    try {
        SPARQLQuery query = connection.createQuery(QueryLanguage.SPARQL,
                "CONSTRUCT { ?s ?p ?o } WHERE { ?s ?p ?o }");
        query.setBinding("s", new UID(subject));
        String contentType = getAcceptedType(request, Format.RDFXML);
        response.setDateHeader("Last-Modified", System.currentTimeMillis());
        response.setContentType(contentType);
        query.streamTriples(response.getWriter(), contentType);
    } finally {
        connection.close();
    }

}

From source file:com.rabbitstewdio.build.maven.tomcat.AbstractContentServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    String filename = request.getPathInfo();

    InputStream in = findResource(filename);
    if (in == null) {
        log.warn("Unable to find [" + filename + "] on " + getServletName());
        response.setStatus(404);/*from w  w  w  .  ja v  a2 s .  c  o  m*/
        return;
    }

    ByteArrayOutputStream bout = new ByteArrayOutputStream();
    IOUtils.copy(in, bout);

    response.setCharacterEncoding("UTF-8");

    String mimeType = getServletContext().getMimeType(filename);
    if (mimeType != null) {
        response.setContentType(mimeType);
    }

    response.addDateHeader("Expires", 0L);
    response.setDateHeader(LAST_MODIFIED, new Date().getTime());
    response.setContentLength(bout.size());
    response.getOutputStream().write(bout.toByteArray());
    response.flushBuffer();
}