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:net.siegmar.japtproxy.misc.IOHandler.java

/**
 * Sends a locally stored pool object to the client. This method will
 * send HTTP status code 304 (not modified) if the client sent a
 * 'If-Modified-Since' header and the pool object wasn't modified since
 * that date.//from w  w w  . j a v  a  2  s  .c  o m
 *
 * @param poolObject           the pool object to sent
 * @param requestModifiedSince the "If-Modified-Since" header
 * @param res                  the HttpServletResponse object
 * @throws IOException is thrown if a problem occured while sending data
 */
protected void sendLocalFile(final PoolObject poolObject, final long requestModifiedSince,
        final HttpServletResponse res) throws IOException {
    final long poolModification = poolObject.getLastModified();

    if (requestModifiedSince != -1 && poolModification <= requestModifiedSince) {
        LOG.debug("Requested resource wasn't modified since last request. "
                + "Returning status code 304 - not modified");
        res.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
        return;
    }

    res.setContentType(poolObject.getContentType());
    res.setContentLength((int) poolObject.getSize());
    res.setDateHeader(HttpHeaderConstants.LAST_MODIFIED, poolObject.getLastModified());

    InputStream is = null;
    final OutputStream sendOs = res.getOutputStream();

    try {
        LOG.info("Sending locally cached object '{}'", poolObject.getName());

        is = poolObject.getInputStream();
        IOUtils.copy(is, sendOs);
    } finally {
        IOUtils.closeQuietly(is);
    }
}

From source file:it.jugpadova.controllers.EventController.java

@RequestMapping
public ModelAndView json(HttpServletRequest req, HttpServletResponse res) throws Exception {
    try {//from   w w  w  .j a  v a  2s.c  o m
        EventSearch eventSearch = buildEventSearch(req);
        List<Event> events = eventBo.search(eventSearch);
        String json = feedsBo.buildJson(events, Utilities.getBaseUrl(req), true);
        // flush it in the res
        res.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0, no-store");
        res.setHeader("Pragma", "public, no-cache");
        res.setDateHeader("Expires", 0);
        res.setContentType("application/json");
        res.setContentLength(json.getBytes().length);
        res.setCharacterEncoding("UTF-8");
        ServletOutputStream resOutputStream = res.getOutputStream();
        Writer writer = new OutputStreamWriter(resOutputStream, "UTF-8");
        writer.write(json);
        writer.flush();
        writer.close();
    } catch (Exception exception) {
        logger.error("Error producing JSON", exception);
        throw exception;
    }
    return null;
}

From source file:freeciv.servlet.ProxyServlet.java

/**
 * Performs an HTTP GET request/*from   w  w  w  .  j ava  2  s. co  m*/
 * @param httpServletRequest The {@link HttpServletRequest} object passed
 *                            in by the servlet engine representing the
 *                            client request to be proxied
 * @param httpServletResponse The {@link HttpServletResponse} object by which
 *                             we can send a proxied response to the client 
 */
public void doGet(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)
        throws IOException, ServletException {

    // Create a GET request
    GetMethod getMethodProxyRequest = new GetMethod(this.getProxyURL(httpServletRequest));
    // Forward the request headers
    setProxyRequestHeaders(httpServletRequest, getMethodProxyRequest);

    // Ensures that Web browsers / Ajax clients don't cache the XML.
    httpServletResponse.setHeader("Cache-Control", "no-cache"); //HTTP 1.1
    httpServletResponse.setHeader("Pragma", "no-cache"); //HTTP 1.0
    httpServletResponse.setDateHeader("Expires", 0); //prevents caching at the proxy server

    // Execute the proxy request
    this.executeProxyRequest(getMethodProxyRequest, httpServletRequest, httpServletResponse);
}

From source file:com.manydesigns.portofino.actions.user.LoginAction.java

public Resolution captcha() {
    final String token = cage.getTokenGenerator().next();
    context.getRequest().getSession().setAttribute(CAPTCHA_SESSION_ATTRIBUTE, token);
    if (token != null) {
        return new StreamingResolution("image/" + cage.getFormat()) {

            @Override//from w w w  .j  ava2 s .  com
            protected void applyHeaders(HttpServletResponse response) {
                super.applyHeaders(response);
                response.setHeader("Cache-Control", "no-cache, no-store");
                response.setHeader("Pragma", "no-cache");
                long time = System.currentTimeMillis();
                response.setDateHeader("Last-Modified", time);
                response.setDateHeader("Date", time);
                response.setDateHeader("Expires", time);
            }

            @Override
            protected void stream(HttpServletResponse response) throws Exception {
                cage.draw(token, response.getOutputStream());
            }
        };
    } else {
        return new ErrorResolution(404);
    }
}

From source file:de.micromata.genome.gwiki.web.StaticFileServlet.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String uri = req.getPathInfo();
    String servletp = req.getServletPath();
    String respath = servletp + uri;
    if (uri == null) {
        resp.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;//from w ww.  ja  v a  2s .  c o m
    }

    InputStream is = getServletContext().getResourceAsStream(respath);
    if (is == null) {
        resp.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }
    long nt = new Date().getTime() + TimeInMillis.DAY;
    String mime = MimeUtils.getMimeTypeFromFile(respath);
    if (StringUtils.equals(mime, "application/x-shockwave-flash")) {
        resp.setHeader("Cache-Control", "cache, must-revalidate");
        resp.setHeader("Pragma", "public");
    }
    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.sakaiproject.nakamura.http.cache.CacheControlFilter.java

/**
 * {@inheritDoc}//  ww w .j a  v  a 2s  . c o  m
 * 
 * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest,
 *      javax.servlet.ServletResponse, javax.servlet.FilterChain)
 */
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    HttpServletRequest srequest = (HttpServletRequest) request;
    HttpServletResponse sresponse = (HttpServletResponse) response;
    String path = srequest.getPathInfo();
    TelemetryCounter.incrementValue("http", "CacheControl", path);
    int respCode = 0;
    Map<String, String> headers = null;
    boolean withLastModfied = true;
    boolean withCookies = true;
    int cacheAge = 0;
    CachedResponseManager cachedResponseManager = null;
    FilterResponseWrapper fresponse = null;
    if ("GET".equals(srequest.getMethod())) {
        headers = getHeaders(path);
        if (headers != null) {
            sresponse.setDateHeader("Date", System.currentTimeMillis());
            withLastModfied = !"unset".equals(headers.get(".lastmodified"));
            withCookies = !"unset".equals(headers.get(".cookies"));
            String cacheAgeValue = headers.get(".requestCache");
            if (cacheAgeValue != null) {
                cacheAge = Integer.parseInt(cacheAgeValue);
            }

            String expiresOffsetValue = headers.get(".expires");
            if (expiresOffsetValue != null) {
                long expiresOffset = Long.parseLong(expiresOffsetValue);
                sresponse.setDateHeader("Expires", System.currentTimeMillis() + (expiresOffset * 1000L));
            }
            for (Entry<String, String> header : headers.entrySet()) {
                if (header.getKey().charAt(0) != '.') {
                    sresponse.setHeader(header.getKey(), header.getValue());
                }
            }
        }
    }
    if (respCode > 0) {
        sresponse.setHeader("X-CacheControlFilterCode", String.valueOf(respCode));
        sresponse.setStatus(respCode);
        sresponse.flushBuffer();
    } else {
        if (cacheAge > 0) {
            cachedResponseManager = new CachedResponseManager(srequest, cacheAge, getCache());
            if (cachedResponseManager.isValid()) {
                cachedResponseManager.send(sresponse);
                return;
            }
        }
        if (!withLastModfied || !withCookies || cachedResponseManager != null) {
            fresponse = new FilterResponseWrapper(sresponse, withLastModfied, withCookies,
                    cachedResponseManager != null);
        }
        if (fresponse != null) {
            chain.doFilter(request, fresponse);
            if (cachedResponseManager != null) {
                cachedResponseManager.save(fresponse.getResponseOperation());
            }
        } else {
            chain.doFilter(request, response);
        }
    }
}

From source file:it.jugpadova.controllers.EventController.java

@RequestMapping
public ModelAndView rss(HttpServletRequest req, HttpServletResponse res) throws Exception {
    try {/*from   ww w.  ja va  2 s.co  m*/
        EventSearch eventSearch = buildEventSearch(req);
        List<Event> events = eventBo.search(eventSearch);
        Channel channel = feedsBo.buildChannel(events, Utilities.getBaseUrl(req), buildChannelLink(req));
        // flush it in the res
        WireFeedOutput wfo = new WireFeedOutput();
        res.setHeader("Cache-Control", "no-store");
        res.setHeader("Pragma", "no-cache");
        res.setDateHeader("Expires", 0);
        res.setContentType("text/xml");
        res.setCharacterEncoding("UTF-8");
        ServletOutputStream resOutputStream = res.getOutputStream();
        wfo.output(channel, new OutputStreamWriter(resOutputStream, "UTF-8"));
        resOutputStream.flush();
        resOutputStream.close();
    } catch (Exception exception) {
        logger.error("Error producing RSS", exception);
        throw exception;
    }
    return null;
}

From source file:org.archive.wayback.liveweb.ARCRecordingProxy.java

public boolean handleRequest(HttpServletRequest httpRequest, HttpServletResponse httpResponse)
        throws ServletException, IOException {

    StringBuffer sb = httpRequest.getRequestURL();
    String query = httpRequest.getQueryString();
    if (query != null) {
        sb.append("?").append(query);
    }/*  w w w .  j  a va 2s.  c om*/
    FileRegion r = null;
    try {

        String url = sb.toString();
        LOGGER.info("Caching URL(" + url + ")");
        r = cacher.cacheURL(url, arcCacheDir);

        httpResponse.setStatus(HttpServletResponse.SC_OK);
        httpResponse.setContentLength((int) r.getLength());
        httpResponse.setContentType(ARC_RECORD_CONTENT_TYPE);
        long exp = System.currentTimeMillis();
        exp += (r.isFake ? fakeExpiresMS : expiresMS);

        httpResponse.setDateHeader(EXPIRES_HEADER, exp);

        r.copyToOutputStream(httpResponse.getOutputStream());

    } catch (URIException e) {

        e.printStackTrace();
        httpResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
    }
    return true;
}

From source file:be.fedict.eid.applet.service.KmlServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    LOG.debug("doGet");

    HttpSession httpSession = request.getSession();
    EIdData eIdData = (EIdData) httpSession.getAttribute("eid");

    byte[] document;
    try {/*from www.j  a v a 2 s. c o  m*/
        document = this.kmlGenerator.generateKml(eIdData);
    } catch (IOException e) {
        throw new ServletException("KML generator error: " + e.getMessage(), e);
    }

    response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate, max-age=-1"); // http 1.1
    if (false == request.getScheme().equals("https")) {
        // else the download fails in IE
        response.setHeader("Pragma", "no-cache"); // http 1.0
    } else {
        response.setHeader("Pragma", "public");
    }
    response.setDateHeader("Expires", -1);
    response.setHeader("Content-disposition", "attachment");
    response.setContentLength(document.length);

    response.setContentType(KmlLight.MIME_TYPE);
    response.setContentLength(document.length);
    ServletOutputStream out = response.getOutputStream();
    out.write(document);
    out.flush();
}

From source file:org.granite.grails.web.GrailsGAEWebSWFServlet.java

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

    request.setAttribute(GrailsApplicationAttributes.REQUEST_SCOPE_ID, grailsAttributes);

    // Get the name of the Groovy script (intern the name so that we can lock on it)
    String pageName = "/swf" + request.getServletPath();

    Resource requestedFile = getResourceForUri(pageName);

    File swfFile = requestedFile.getFile();
    if (swfFile == null || !swfFile.exists()) {
        response.sendError(404, "\"" + pageName + "\" not found.");
        return;//from ww w  .j  a  v  a2 s .  c om
    }

    response.setContentType("application/x-shockwave-flash");
    response.setContentLength((int) swfFile.length());
    response.setBufferSize((int) swfFile.length());
    response.setDateHeader("Expires", 0);

    byte[] buf = new byte[1000000];
    FileInputStream is = null;
    try {
        is = new FileInputStream(swfFile);
        OutputStream os = response.getOutputStream();
        int read = is.read(buf, 0, 1000000);
        while (read > 0) {
            os.write(buf, 0, read);
            read = is.read(buf, 0, 1000000);
        }
    } finally {
        if (is != null) {
            IOUtils.closeQuietly(is);
        }
    }
}