Example usage for javax.servlet.http HttpServletResponse addDateHeader

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

Introduction

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

Prototype

public void addDateHeader(String name, long date);

Source Link

Document

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

Usage

From source file:annis.gui.servlets.ResourceServlet.java

@Override
@SuppressWarnings("unchecked")
public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    OutputStream outStream = response.getOutputStream();

    String completePath = request.getPathInfo();

    if (completePath == null) {
        response.sendError(404, "must provide a valid and existing path with a vistype");
        return;//from www.j a  v a  2  s . co m
    }

    // remove trailing /
    completePath = completePath.substring(1);

    String[] pathComponents = completePath.split("/");

    String vistype = pathComponents[0];

    if (pathComponents.length < 2) {
        response.sendError(404, "must provide a valid and existing path");
        return;
    }

    String path = StringUtils.join(Arrays.copyOfRange(pathComponents, 1, pathComponents.length), "/");

    // get the visualizer for this vistype
    ResourcePlugin vis = resourceRegistry.get(vistype);
    if (vis == null) {
        response.sendError(500, "There is no resource with the short name " + vistype);
    } else if (path.endsWith(".class")) {
        response.sendError(403, "illegal class path access");
    } else {
        URL resource = vis.getClass().getResource(path);
        if (resource == null) {
            response.sendError(404, path + " not found");
        } else {
            // check if it is new
            URLConnection resourceConnection = resource.openConnection();
            long resourceLastModified = resourceConnection.getLastModified();
            long requestLastModified = request.getDateHeader("If-Modified-Since");
            if (requestLastModified != -1 && resourceLastModified <= requestLastModified) {
                response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
            } else {
                response.addDateHeader("Last-Modified", resourceLastModified);
                if ("localhost".equals(request.getServerName())) {
                    // does always expire right now
                    response.addDateHeader("Expires", new Date().getTime());
                } else {
                    // expires in one minute per default
                    response.addDateHeader("Expires", new Date().getTime() + 60000);
                }
                // not in cache, stream out
                String mimeType = getServletContext().getMimeType(path);
                response.setContentType(mimeType);
                if (mimeType.startsWith("text/")) {
                    response.setCharacterEncoding("UTF-8");
                }
                OutputStream bufferedOut = new BufferedOutputStream(outStream);
                InputStream resourceInStream = new BufferedInputStream(resource.openStream());

                try {
                    int v = -1;
                    while ((v = resourceInStream.read()) != -1) {
                        bufferedOut.write(v);
                    }
                } finally {
                    resourceInStream.close();
                    bufferedOut.flush();
                    outStream.flush();
                }
            }
        }
    }

}

From source file:com.orange.api.atmosdav.AtmosDavServlet.java

/**
 * Process a GET request for the specified resource.
 *
 * Note: GET method currently does not support Content-Range parameter.
 * It will send the complete content./*from  ww  w.j a v a2 s  . c o  m*/
 *
 * @param request The servlet request we are processing
 * @param response The servlet response we are creating
 *
 * @exception IOException if an input/output error occurs
 * @exception ServletException if a servlet-specified error occurs
 */
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
    String href = getPathFromReq(req);
    AtmosApi api = getAPIFromAuthent(req, resp);

    try {
        ObjectPath obj_path = getAtmosPath(href, api);
        MetadataList metadata = getObjectMetadata(api.api, getAtmosPath(href, api));
        AtmosType obj_type = getObjectType(metadata);

        if (obj_type == AtmosType.NON_EXISTENT) {
            // check if we need to initialize the directory container for webdav
            if ("/".equals(href)) {
                api.api.createObjectOnPath(getAtmosPath(href, api), null, null, null, null);
                obj_type = AtmosType.DIRECTORY;
            } else {
                resp.sendError(HttpServletResponse.SC_NOT_FOUND, href);
                return;
            }
        }

        if (obj_type == AtmosType.REGULAR) {
            resp.setStatus(resp.SC_OK);
            //response.setContentType("application/octet-stream");
            resp.setContentType("text/plain");

            String last_modified_str = metadata.getMetadata("mtime").getValue();
            resp.addDateHeader("Last-Modified", ATMOS_DATE_FORMAT.parse(last_modified_str).getTime());

            DownloadHelper down_helper = new DownloadHelper(api.api, null);
            down_helper.readObject(obj_path, resp.getOutputStream(), false);
        } else if (obj_type == AtmosType.DIRECTORY) {
            resp.sendError(resp.SC_FORBIDDEN, "Directory listing not allowed.");
        } else if (obj_type == AtmosType.NON_EXISTENT) {
            resp.sendError(resp.SC_NOT_FOUND);
        } else {
            resp.sendError(resp.SC_INTERNAL_SERVER_ERROR,
                    "Internal error: Invalid object type '" + obj_type + "', should be directory or regular");
        }

    } catch (EsuException e) {
        if ((e.getAtmosCode() == 1003) || (e.getHttpCode() == 404)) {
            resp.sendError(resp.SC_NOT_FOUND);
        } else {
            throw e;
        }
    } catch (Exception e) {
        resp.sendError(resp.SC_INTERNAL_SERVER_ERROR, "Exception: " + e.getMessage());
    }

}

From source file:org.gaul.s3proxy.S3ProxyHandler.java

private static void addMetadataToResponse(HttpServletRequest request, HttpServletResponse response,
        BlobMetadata metadata) {/*from w  w  w .  j  a  v a 2 s .c om*/
    ContentMetadata contentMetadata = metadata.getContentMetadata();
    addResponseHeaderWithOverride(request, response, HttpHeaders.CACHE_CONTROL, "response-cache-control",
            contentMetadata.getCacheControl());
    addResponseHeaderWithOverride(request, response, HttpHeaders.CONTENT_ENCODING, "response-content-encoding",
            contentMetadata.getContentEncoding());
    addResponseHeaderWithOverride(request, response, HttpHeaders.CONTENT_LANGUAGE, "response-content-language",
            contentMetadata.getContentLanguage());
    addResponseHeaderWithOverride(request, response, HttpHeaders.CONTENT_DISPOSITION,
            "response-content-disposition", contentMetadata.getContentDisposition());
    response.addHeader(HttpHeaders.CONTENT_LENGTH, contentMetadata.getContentLength().toString());
    String overrideContentType = request.getParameter("response-content-type");
    response.setContentType(
            overrideContentType != null ? overrideContentType : contentMetadata.getContentType());
    String eTag = metadata.getETag();
    if (eTag != null) {
        response.addHeader(HttpHeaders.ETAG, maybeQuoteETag(eTag));
    }
    String overrideExpires = request.getParameter("response-expires");
    if (overrideExpires != null) {
        response.addHeader(HttpHeaders.EXPIRES, overrideExpires);
    } else {
        Date expires = contentMetadata.getExpires();
        if (expires != null) {
            response.addDateHeader(HttpHeaders.EXPIRES, expires.getTime());
        }
    }
    response.addDateHeader(HttpHeaders.LAST_MODIFIED, metadata.getLastModified().getTime());
    for (Map.Entry<String, String> entry : metadata.getUserMetadata().entrySet()) {
        response.addHeader(USER_METADATA_PREFIX + entry.getKey(), entry.getValue());
    }
}

From source file:com.ecyrd.jspwiki.attachment.AttachmentServlet.java

/**
 *  Serves a GET with two parameters: 'wikiname' specifying the wikiname
 *  of the attachment, 'version' specifying the version indicator.
 *  //from  w w w.j a  va 2 s . c o m
 *  {@inheritDoc}
 */

// FIXME: Messages would need to be localized somehow.
public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException {
    WikiContext context = m_engine.createContext(req, WikiContext.ATTACH);

    String version = req.getParameter(HDR_VERSION);
    String nextPage = req.getParameter("nextpage");

    String msg = "An error occurred. Ouch.";
    int ver = WikiProvider.LATEST_VERSION;

    AttachmentManager mgr = m_engine.getAttachmentManager();
    AuthorizationManager authmgr = m_engine.getAuthorizationManager();

    String page = context.getPage().getName();

    if (page == null) {
        log.info("Invalid attachment name.");
        res.sendError(HttpServletResponse.SC_BAD_REQUEST);
        return;
    }

    OutputStream out = null;
    InputStream in = null;

    try {
        log.debug("Attempting to download att " + page + ", version " + version);
        if (version != null) {
            ver = Integer.parseInt(version);
        }

        Attachment att = mgr.getAttachmentInfo(page, ver);

        if (att != null) {
            //
            //  Check if the user has permission for this attachment
            //

            Permission permission = PermissionFactory.getPagePermission(att, "view");
            if (!authmgr.checkPermission(context.getWikiSession(), permission)) {
                log.debug("User does not have permission for this");
                res.sendError(HttpServletResponse.SC_FORBIDDEN);
                return;
            }

            //
            //  Check if the client already has a version of this attachment.
            //
            if (HttpUtil.checkFor304(req, att)) {
                log.debug("Client has latest version already, sending 304...");
                res.sendError(HttpServletResponse.SC_NOT_MODIFIED);
                return;
            }

            String mimetype = getMimeType(context, att.getFileName());

            res.setContentType(mimetype);

            //
            //  We use 'inline' instead of 'attachment' so that user agents
            //  can try to automatically open the file.
            //

            res.addHeader("Content-Disposition", "inline; filename=\"" + att.getFileName() + "\";");

            res.addDateHeader("Last-Modified", att.getLastModified().getTime());

            if (!att.isCacheable()) {
                res.addHeader("Pragma", "no-cache");
                res.addHeader("Cache-control", "no-cache");
            }

            // If a size is provided by the provider, report it.
            if (att.getSize() >= 0) {
                // log.info("size:"+att.getSize());
                res.setContentLength((int) att.getSize());
            }

            out = res.getOutputStream();
            in = mgr.getAttachmentStream(context, att);

            int read = 0;
            byte[] buffer = new byte[BUFFER_SIZE];

            while ((read = in.read(buffer)) > -1) {
                out.write(buffer, 0, read);
            }

            if (log.isDebugEnabled()) {
                msg = "Attachment " + att.getFileName() + " sent to " + req.getRemoteUser() + " on "
                        + req.getRemoteAddr();
                log.debug(msg);
            }
            if (nextPage != null)
                res.sendRedirect(nextPage);

            return;
        }

        msg = "Attachment '" + page + "', version " + ver + " does not exist.";

        log.info(msg);
        res.sendError(HttpServletResponse.SC_NOT_FOUND, msg);
        return;
    } catch (ProviderException pe) {
        msg = "Provider error: " + pe.getMessage();

        log.debug("Provider failed while reading", pe);
        //
        //  This might fail, if the response is already committed.  So in that
        //  case we just log it.
        //
        try {
            res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg);
        } catch (IllegalStateException e) {
        }
        return;
    } catch (NumberFormatException nfe) {
        msg = "Invalid version number (" + version + ")";
        res.sendError(HttpServletResponse.SC_BAD_REQUEST, msg);
        return;
    } catch (SocketException se) {
        //
        //  These are very common in download situations due to aggressive
        //  clients.  No need to try and send an error.
        //
        log.debug("I/O exception during download", se);
        return;
    } catch (IOException ioe) {
        //
        //  Client dropped the connection or something else happened.
        //  We don't know where the error came from, so we'll at least
        //  try to send an error and catch it quietly if it doesn't quite work.
        //
        msg = "Error: " + ioe.getMessage();
        log.debug("I/O exception during download", ioe);

        try {
            res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg);
        } catch (IllegalStateException e) {
        }
        return;
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
            }
        }

        //
        //  Quite often, aggressive clients close the connection when they have
        //  received the last bits.  Therefore, we close the output, but ignore
        //  any exception that might come out of it.
        //

        if (out != null) {
            try {
                out.close();
            } catch (IOException e) {
            }
        }
    }
}

From source file:com.ecyrd.jspwiki.attachment.SilverpeasAttachmentServlet.java

/**
 * Serves a GET with two parameters: 'wikiname' specifying the wikiname of the attachment,
 * 'version' specifying the version indicator. {@inheritDoc}
 *//*w  ww.  j  av a  2  s .  co m*/
// FIXME: Messages would need to be localized somehow.
public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException {
    WikiContext context = m_engine.createContext(req, WikiContext.ATTACH);

    String version = req.getParameter(HDR_VERSION);
    String nextPage = req.getParameter("nextpage");

    String msg = "An error occurred. Ouch.";
    int ver = WikiProvider.LATEST_VERSION;

    AttachmentManager mgr = m_engine.getAttachmentManager();
    AuthorizationManager authmgr = m_engine.getAuthorizationManager();

    String page = context.getPage().getName();

    if (page == null) {
        log.info("Invalid attachment name.");
        res.sendError(HttpServletResponse.SC_BAD_REQUEST);
        return;
    }

    OutputStream out = null;
    InputStream in = null;

    try {
        log.debug("Attempting to download att " + page + ", version " + version);
        if (version != null) {
            ver = Integer.parseInt(version);
        }

        Attachment att = mgr.getAttachmentInfo(page, ver);

        if (att != null) {
            //
            // Check if the user has permission for this attachment
            //

            Permission permission = PermissionFactory.getPagePermission(att, "view");
            if (!authmgr.checkPermission(context.getWikiSession(), permission)) {
                log.debug("User does not have permission for this");
                res.sendError(HttpServletResponse.SC_FORBIDDEN);
                return;
            }

            //
            // Check if the client already has a version of this attachment.
            //
            if (HttpUtil.checkFor304(req, att)) {
                log.debug("Client has latest version already, sending 304...");
                res.sendError(HttpServletResponse.SC_NOT_MODIFIED);
                return;
            }

            String mimetype = getMimeType(context, att.getFileName());

            res.setContentType(mimetype);

            //
            // We use 'inline' instead of 'attachment' so that user agents
            // can try to automatically open the file.
            //

            res.addHeader("Content-Disposition", "inline; filename=\"" + att.getFileName() + "\";");

            res.addDateHeader("Last-Modified", att.getLastModified().getTime());

            if (!att.isCacheable()) {
                res.addHeader("Pragma", "no-cache");
                res.addHeader("Cache-control", "no-cache");
            }

            // If a size is provided by the provider, report it.
            if (att.getSize() >= 0) {
                res.setContentLength((int) att.getSize());
            }

            out = res.getOutputStream();
            in = mgr.getAttachmentStream(context, att);
            int read = 0;
            byte[] buffer = new byte[BUFFER_SIZE];

            while ((read = in.read(buffer)) > -1) {
                out.write(buffer, 0, read);
            }
            System.out.println("Attachment file is c:/tmp/result/" + att.getFileName());
            System.out.println("Attachment " + att.getFileName() + " sent to " + req.getRemoteUser() + " on "
                    + req.getRemoteAddr());
            if (log.isDebugEnabled()) {
                msg = "Attachment " + att.getFileName() + " sent to " + req.getRemoteUser() + " on "
                        + req.getRemoteAddr();
                log.debug(msg);
            }
            if (nextPage != null) {
                res.sendRedirect(nextPage);
            }

            return;
        }

        msg = "Attachment '" + page + "', version " + ver + " does not exist.";

        log.info(msg);
        res.sendError(HttpServletResponse.SC_NOT_FOUND, msg);
        return;
    } catch (ProviderException pe) {
        msg = "Provider error: " + pe.getMessage();

        log.debug("Provider failed while reading", pe);
        //
        // This might fail, if the response is already committed. So in that
        // case we just log it.
        //
        try {
            res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg);
        } catch (IllegalStateException e) {
        }
        return;
    } catch (NumberFormatException nfe) {
        msg = "Invalid version number (" + version + ")";
        res.sendError(HttpServletResponse.SC_BAD_REQUEST, msg);
        return;
    } catch (SocketException se) {
        //
        // These are very common in download situations due to aggressive
        // clients. No need to try and send an error.
        //
        log.debug("I/O exception during download", se);
        return;
    } catch (IOException ioe) {
        //
        // Client dropped the connection or something else happened.
        // We don't know where the error came from, so we'll at least
        // try to send an error and catch it quietly if it doesn't quite work.
        //
        msg = "Error: " + ioe.getMessage();
        log.debug("I/O exception during download", ioe);

        try {
            res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg);
        } catch (IllegalStateException e) {
        }
        return;
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
            }
        }

        //
        // Quite often, aggressive clients close the connection when they have
        // received the last bits. Therefore, we close the output, but ignore
        // any exception that might come out of it.
        //

        if (out != null) {
            try {
                out.close();
            } catch (IOException e) {
            }
        }
    }
}

From source file:info.magnolia.cms.filters.RangeSupportFilter.java

private HttpServletResponse wrapResponse(final HttpServletRequest request, final HttpServletResponse response) {
    return new HttpServletResponseWrapper(response) {

        /** default length is max. We hope that the underlying code will set proper content length as a header before we proceed serving some bytes. */
        private int length = Integer.MAX_VALUE;

        private final Map<String, Object> headers = new HashMap<String, Object>();

        private String eTag;

        private List<RangeInfo> ranges;

        private RangeInfo full;

        private ServletOutputStream stream;

        private PrintWriter writer;

        @Override//from w w w. j  av  a  2  s. c o m
        public void addDateHeader(String name, long date) {
            super.addDateHeader(name, date);
            this.headers.put(name, date);
            if ("Last-Modified".equalsIgnoreCase(name)) {
                lastModTime = date;
            }
        }

        @Override
        public void setDateHeader(String name, long date) {
            super.setDateHeader(name, date);
            this.headers.put(name, date);
            if ("Last-Modified".equalsIgnoreCase(name)) {
                lastModTime = date;
            }
        }

        @Override
        public void addHeader(String name, String value) {
            if ("Content-Disposition".equalsIgnoreCase(name) && log.isDebugEnabled()) {
                log.warn("content disposition enforced by underlying filter/servlet");
            }
            super.addHeader(name, value);
            this.headers.put(name, value);
        }

        @Override
        public void setHeader(String name, String value) {
            if ("Content-Disposition".equalsIgnoreCase(name) && log.isDebugEnabled()) {
                log.warn("content disposition enforced by underlying filter/servlet");
            }
            super.setHeader(name, value);
            this.headers.put(name, value);
        }

        @Override
        public void addIntHeader(String name, int value) {
            super.addIntHeader(name, value);
            this.headers.put(name, value);
        }

        @Override
        public void setIntHeader(String name, int value) {
            super.setIntHeader(name, value);
            this.headers.put(name, value);
        }

        @Override
        public void setContentLength(int len) {
            this.length = len;
            // do not propagate length up. We might not be able to change it once it is set. We will set it ourselves once we are ready to serve bytes.
        }

        @Override
        public ServletOutputStream getOutputStream() throws IOException {
            // make sure we set stream only once. Multiple calls to this method are allowed.
            if (this.stream == null) {
                ServletOutputStream stream = super.getOutputStream();
                // wrap the response to filter out everything except desired range
                this.stream = addRangeSupportWrapper(request, response, stream);

                if (!isServeContent || this.stream == null) {
                    // swallow output on head requests
                    this.stream = new ServletOutputStream() {

                        @Override
                        public void write(int b) throws IOException {
                            // do nothing, we do not write any output now
                        }
                    };
                }
            }
            return stream;
        }

        private ServletOutputStream addRangeSupportWrapper(final HttpServletRequest request,
                final HttpServletResponse response, ServletOutputStream stream) throws IOException {
            if (!processContent(request, response)) {
                // we might have to return null stream instead as the previous method already called res.sendError();
                return null;
            }

            if (headers.containsKey("Content-Range")) {
                // doesn't work for tomcat as it accesses underlying stream under our hands!!!
                log.debug("Range request was handled by underlying filter/servlet.");
                return stream;
            }
            if (ranges == null || ranges.isEmpty()) {
                // no op, serve all as usual
                log.debug("Didn't find any range to speak of. Serving all content as usual.");
                if (length != Integer.MAX_VALUE) {
                    // set real length when we know it
                    response.setContentLength(length);
                }
            } else if (ranges.size() == 1) {
                RangeInfo range = ranges.get(0);
                log.debug("Serving range [{}].", range);
                // setting 206 header is essential for some clients. The would abort if response is set to 200
                response.setStatus(SC_PARTIAL_CONTENT);
                stream = new RangedOutputStream(stream, range);
            } else {
                log.error("Requested multiple ranges [{}].", ranges.size());
                // TODO: add support for multiple ranges (sent as multipart request), for now just send error back
                response.setHeader("Content-Range", "bytes */" + length);
                response.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE);
                // again we might have to return null stream after calling sendError() as the original stream might no longer be valid
            }
            return stream;
        }

        @Override
        public PrintWriter getWriter() throws IOException {
            if (!wrapWriter) {
                return super.getWriter();
            }
            if (this.writer == null) {
                this.writer = new PrintWriter(new OutputStreamWriter(getOutputStream()));
            }
            return writer;
        }

        private boolean processContent(HttpServletRequest request, HttpServletResponse response)
                throws IOException {
            log.debug("Serving binary on uri {} was last modified at {}",
                    new Object[] { request.getRequestURI(), lastModTime });
            if (!isRequestValid(request, response)) {
                log.debug("Skipping request {} since it doesn't require body",
                        new Object[] { request.getRequestURI() });
                return false;
            }
            if (!processRange(request)) {
                log.debug("Could not process range of request {}", new Object[] { request.getRequestURI() });
                return false;
            }
            return true;
        }

        private boolean processRange(HttpServletRequest request) throws IOException {
            full = new RangeInfo(0, length - 1, length);
            ranges = new ArrayList<RangeInfo>();

            String range = request.getHeader("Range");

            // Valid range header format is "bytes=n-n,n-n,n-n...". If not, then return 416.
            if (!range.matches("^bytes=\\d*-\\d*(,\\d*-\\d*)*$")) {
                response.setHeader("Content-Range", "bytes */" + length);
                response.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE);
                return false;
            }

            // If-Range header must match ETag or be greater then LastModified. If not, then return full file.
            String ifRange = request.getHeader("If-Range");
            if (ifRange != null && !ifRange.equals(eTag)) {
                try {
                    long ifRangeTime = request.getDateHeader("If-Range");
                    if (ifRangeTime != -1 && ifRangeTime + 1000 < lastModTime) {
                        ranges.add(full);
                    }
                } catch (IllegalArgumentException ignore) {
                    // happens when if-range contains something else then date
                    ranges.add(full);
                }
            }

            // in case there were no invalid If-Range headers, then look at requested byte ranges.
            if (ranges.isEmpty()) {
                for (String part : range.substring(6).split(",")) {
                    int start = intSubstring(StringUtils.substringBefore(part, "-"));
                    int end = intSubstring(StringUtils.substringAfter(part, "-"));

                    if (start == -1) {
                        start = length - end;
                        end = length - 1;
                    } else if (end == -1 || end > length - 1) {
                        end = length - 1;
                    }

                    // Is range valid?
                    if (start > end) {
                        response.setHeader("Content-Range", "bytes */" + length); // Required in 416.
                        response.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE);
                        return false;
                    }

                    // Add range.
                    ranges.add(new RangeInfo(start, end, length));
                }
            }

            response.setHeader("ETag", eTag);
            if (ranges.size() == 1) {
                RangeInfo r = ranges.get(0);
                response.setHeader("Accept-Ranges", "bytes");
                response.setHeader("Content-Range",
                        "bytes " + r.start + "-" + r.end + "/" + r.totalLengthOfServedBinary);
                length = r.lengthOfRange;
            }
            return true;
        }

        private int intSubstring(String value) {
            return value.length() > 0 ? Integer.parseInt(value) : -1;
        }

        @Override
        public void flushBuffer() throws IOException {
            if (writer != null) {
                writer.flush();
            }
            if (stream != null) {
                stream.flush();
            }

            super.flushBuffer();
        }

        private boolean isRequestValid(HttpServletRequest request, HttpServletResponse response)
                throws IOException {
            String fileName = StringUtils.substringAfterLast(request.getRequestURI(), "/");
            eTag = fileName + "_" + length + "_" + lastModTime;

            // If-None-Match header should contain "*" or ETag.
            String ifNoneMatch = request.getHeader("If-None-Match");
            if (ifNoneMatch != null && matches(ifNoneMatch, eTag)) {
                response.setHeader("ETag", eTag); // Required in 304.
                log.debug("Returning {} on header If-None-Match", HttpServletResponse.SC_NOT_MODIFIED);
                response.sendError(HttpServletResponse.SC_NOT_MODIFIED);
                return false;
            }

            // If-Modified-Since header must be greater than LastModified. ignore if If-None-Match header exists
            long ifModifiedSince = request.getDateHeader("If-Modified-Since");
            if (ifNoneMatch == null && ifModifiedSince != -1 && ifModifiedSince + 1000 > lastModTime) {
                response.setHeader("ETag", eTag); // Required in 304.
                // 304 response should contain Date header unless running on timeless server (see 304 response docu)
                response.addDateHeader("Date", lastModTime);
                log.debug("Returning {} on header If-Modified-Since", HttpServletResponse.SC_NOT_MODIFIED);
                response.sendError(HttpServletResponse.SC_NOT_MODIFIED);
                return false;
            }

            // If-Match header should contain "*" or ETag.
            String ifMatch = request.getHeader("If-Match");
            if (ifMatch != null && !matches(ifMatch, eTag)) {
                log.debug("Returning {} on header If-Match", HttpServletResponse.SC_PRECONDITION_FAILED);
                response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
                return false;
            }

            // If-Unmodified-Since header must be greater than LastModified.
            long ifUnmodifiedSince = request.getDateHeader("If-Unmodified-Since");
            if (ifUnmodifiedSince != -1 && ifUnmodifiedSince + 1000 <= lastModTime) {
                log.debug("Returning {} on header If-Unmodified-Since",
                        HttpServletResponse.SC_PRECONDITION_FAILED);
                response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
                return false;
            }

            log.debug("Passed all precondition checkes for request {}", request.getRequestURI());
            return true;
        }
    };
}

From source file:net.ymate.platform.webmvc.view.AbstractView.java

public IView addDateHeader(String name, long date) {
    HttpServletResponse _response = WebContext.getResponse();
    if (_response.containsHeader(name)) {
        _response.addDateHeader(name, date);
    } else {//  w  w  w .  j a va  2 s  . c  o  m
        _response.setDateHeader(name, date);
    }
    return this;
}

From source file:org.brutusin.rpc.http.RpcServlet.java

/**
 *
 * @param req//  w ww  .  j a v  a2 s  .c  o  m
 * @param resp
 * @param cachingInfo
 * @param etag
 * @throws IOException
 */
private void addCacheHeaders(HttpServletRequest req, HttpServletResponse resp, CachingInfo cachingInfo,
        String etag) throws IOException {
    // max-age overrides expires. For legacy proxies (intermedy) cache control is ignored and no cache is performed, the desired behaviour for a private cache. See http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.9.3
    resp.addDateHeader("Expires", 0);
    if (cachingInfo == null) {
        resp.addHeader("Cache-Control", "max-age=0, no-cache, no-store");
        resp.addHeader("Pragma", "no-cache");
    } else {
        StringBuilder cacheControl = new StringBuilder("max-age=").append(cachingInfo.getMaxAge());
        if (cachingInfo.isShared()) {
            cacheControl.append(", public");
        } else {
            cacheControl.append(", private");
        }
        if (!cachingInfo.isStore()) {
            cacheControl.append(", no-store");
        }
        cacheControl.append(", must-revalidate");
        resp.addHeader("Cache-Control", cacheControl.toString());
        if (etag != null) {
            resp.setHeader("ETag", "W/\"" + etag + "\"");
        }
        if (req.getMethod().equals("POST")) {
            addContentLocation(req, resp);
        }
    }
}

From source file:org.carrot2.webapp.QueryProcessorServlet.java

private void setExpires(HttpServletResponse response, int minutes) {
    final HttpServletResponse httpResponse = response;

    final Calendar expiresCalendar = Calendar.getInstance();
    expiresCalendar.add(Calendar.MINUTE, minutes);
    httpResponse.addDateHeader("Expires", expiresCalendar.getTimeInMillis());
}

From source file:org.craftercms.commons.http.HttpUtils.java

/**
 * Disable caching in the client./*from  www .  j  av a  2s.  c  o  m*/
 *
 * @param response the response to add the headers for disabling caching.
 */
public static void disableCaching(HttpServletResponse response) {
    response.addHeader(PRAGMA_HEADER_NAME, "no-cache");
    response.addHeader(CACHE_CONTROL_HEADER_NAME, "no-cache, no-store, max-age=0");
    response.addDateHeader(EXPIRES_HEADER_NAME, 1L);
}