Example usage for javax.servlet.http HttpServletResponse SC_NOT_MODIFIED

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

Introduction

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

Prototype

int SC_NOT_MODIFIED

To view the source code for javax.servlet.http HttpServletResponse SC_NOT_MODIFIED.

Click Source Link

Document

Status code (304) indicating that a conditional GET operation found that the resource was available and not modified.

Usage

From source file:com.cnksi.core.web.utils.Servlets.java

/**
 * ?? If-None-Match Header, Etag?./*  ww w  .  j  a va  2 s. co  m*/
 * 
 * Etag, checkIfNoneMatchfalse, 304 not modify status.
 * 
 * @param etag ETag.
 */
public static boolean checkIfNoneMatchEtag(HttpServletRequest request, HttpServletResponse response,
        String etag) {

    String headerValue = request.getHeader(HttpHeaders.IF_NONE_MATCH);
    if (headerValue != null) {
        boolean conditionSatisfied = false;
        if (!"*".equals(headerValue)) {
            StringTokenizer commaTokenizer = new StringTokenizer(headerValue, ",");

            while (!conditionSatisfied && commaTokenizer.hasMoreTokens()) {
                String currentToken = commaTokenizer.nextToken();
                if (currentToken.trim().equals(etag)) {
                    conditionSatisfied = true;
                }
            }
        } else {
            conditionSatisfied = true;
        }

        if (conditionSatisfied) {
            response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
            response.setHeader(HttpHeaders.ETAG, etag);
            return false;
        }
    }
    return true;
}

From source file:org.apache.shindig.gadgets.servlet.GadgetRenderingServlet.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    // If an If-Modified-Since header is ever provided, we always say
    // not modified. This is because when there actually is a change,
    // cache busting should occur.
    UriStatus urlStatus = getUrlStatus(req);
    if (req.getHeader("If-Modified-Since") != null && !"1".equals(req.getParameter("nocache"))
            && urlStatus == UriStatus.VALID_VERSIONED) {
        resp.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
        return;/*from w w  w . j a  va2 s .  c  o  m*/
    }
    render(req, resp, urlStatus);
}

From source file:com.jslsolucoes.tagria.lib.servlet.Tagria.java

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

    String uri = request.getRequestURI().replaceAll(";jsessionid=.*", "");
    String etag = DigestUtils.sha256Hex(uri);

    if (uri.endsWith("blank")) {
        response.setStatus(HttpServletResponse.SC_OK);
        return;/*from w w w .  j  a va 2 s.co m*/
    }

    if (uri.endsWith("locale")) {
        Config.set(request.getSession(), Config.FMT_LOCALE,
                Locale.forLanguageTag(request.getParameter("locale")));
        response.setStatus(HttpServletResponse.SC_OK);
        return;
    }

    if (request.getHeader("If-None-Match") != null && etag.equals(request.getHeader("If-None-Match"))) {
        response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
        return;
    }

    String charset = "utf-8";
    if (TagUtil.getInitParam(TagriaConfigParameter.ENCODING) != null) {
        charset = TagUtil.getInitParam(TagriaConfigParameter.ENCODING);
    }
    response.setCharacterEncoding(charset);
    try {

        DateTime today = new DateTime();
        DateTime expires = new DateTime().plusDays(CACHE_EXPIRES_DAY);

        if (uri.endsWith(".css")) {
            response.setContentType("text/css");
        } else if (uri.endsWith(".js")) {
            response.setContentType("text/javascript");
        } else if (uri.endsWith(".png")) {
            response.setContentType("image/png");
        }

        SimpleDateFormat sdf = new SimpleDateFormat("E, dd MMM yyyy HH:mm:ss 'GMT'", Locale.ENGLISH);

        if (Boolean.valueOf(TagUtil.getInitParam(TagriaConfigParameter.CDN_ENABLED))) {
            response.setHeader(HttpHeaderParameter.ACCESS_CONTROL_ALLOW_ORIGIN.getName(), "*");
        }

        response.setHeader(HttpHeaderParameter.ETAG.getName(), etag);
        response.setHeader(HttpHeaderParameter.EXPIRES.getName(), sdf.format(expires.toDate()));
        response.setHeader(HttpHeaderParameter.CACHE_CONTROL.getName(),
                "public,max-age=" + Seconds.secondsBetween(today, expires).getSeconds());

        String url = "/com/jslsolucoes"
                + uri.replaceFirst(request.getContextPath(), "").replaceAll(";jsessionid=.*", "");
        InputStream in = getClass().getResourceAsStream(url);
        IOUtils.copy(in, response.getOutputStream());
        in.close();

    } catch (Exception exception) {
        logger.error("Could not load resource", exception);
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
}

From source file:org.apache.shindig.gadgets.servlet.JsServlet.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    // If an If-Modified-Since header is ever provided, we always say
    // not modified. This is because when there actually is a change,
    // cache busting should occur.
    UriStatus vstatus = null;//from www  . ja  v  a  2  s.  c o  m
    try {
        vstatus = jsUriManager.processExternJsUri(new UriBuilder(req).toUri()).getStatus();
    } catch (GadgetException e) {
        resp.sendError(e.getHttpStatusCode(), e.getMessage());
        return;
    }
    if (req.getHeader("If-Modified-Since") != null && vstatus == UriStatus.VALID_VERSIONED) {
        resp.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
        return;
    }

    // Get JavaScript content from features aliases request.
    JsHandler.JsHandlerResponse handlerResponse = jsHandler.getJsContent(req);
    StringBuilder jsData = handlerResponse.getJsData();
    boolean isProxyCacheable = handlerResponse.isProxyCacheable();

    // Add onload handler to add callback function.
    String onloadStr = req.getParameter("onload");
    if (onloadStr != null) {
        if (!ONLOAD_FN_PATTERN.matcher(onloadStr).matches()) {
            resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid onload callback specified");
            return;
        }
        jsData.append(String.format(ONLOAD_JS_TPL, StringEscapeUtils.escapeJavaScript(onloadStr)));
    }

    if (jsData.length() == 0) {
        resp.setStatus(HttpServletResponse.SC_NOT_FOUND);
        return;
    }

    // post JavaScript content fetching
    postJsContentProcessing(resp, vstatus, isProxyCacheable);

    resp.setContentType("text/javascript; charset=utf-8");
    byte[] response = jsData.toString().getBytes("UTF-8");
    resp.setContentLength(response.length);
    resp.getOutputStream().write(response);
}

From source file:cn.com.qiqi.order.utils.Servlets.java

/**
 * ?? If-None-Match Header, Etag?.//from   ww w. j a  va 2 s .c  om
 * 
 * Etag, checkIfNoneMatchfalse, 304 not modify status.
 * 
 * @param etag ETag.
 */
public static boolean checkIfNoneMatchEtag(HttpServletRequest request, HttpServletResponse response,
        String etag) {
    String headerValue = request.getHeader(HttpHeaders.IF_NONE_MATCH);
    if (headerValue != null) {
        boolean conditionSatisfied = false;
        if (!"*".equals(headerValue)) {
            StringTokenizer commaTokenizer = new StringTokenizer(headerValue, ",");

            while (!conditionSatisfied && commaTokenizer.hasMoreTokens()) {
                String currentToken = commaTokenizer.nextToken();
                if (currentToken.trim().equals(etag)) {
                    conditionSatisfied = true;
                }
            }
        } else {
            conditionSatisfied = true;
        }

        if (conditionSatisfied) {
            response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
            response.setHeader(HttpHeaders.ETAG, etag);
            return false;
        }
    }
    return true;
}

From source file:org.olat.core.gui.media.ServletUtil.java

/**
 * @param httpReq//from   w  w w . ja  va 2 s.co  m
 * @param httpResp
 * @param mr
 */
public static void serveResource(HttpServletRequest httpReq, HttpServletResponse httpResp, MediaResource mr) {
    boolean debug = log.isDebug();

    try {
        Long lastModified = mr.getLastModified();
        if (lastModified != null) {
            // give browser a chance to cache images
            long ifModifiedSince = httpReq.getDateHeader("If-Modified-Since");
            // TODO: if no such header, what is the return value
            long lastMod = lastModified.longValue();
            if (ifModifiedSince >= (lastMod / 1000L) * 1000L) {
                httpResp.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
                return;
            }
            httpResp.setDateHeader("Last-Modified", lastModified.longValue());
        }

        if (isFlashPseudoStreaming(httpReq, mr)) {
            httpResp.setContentType("video/x-flv");
            pseudoStreamFlashResource(httpReq, httpResp, mr);
        } else {
            String mime = mr.getContentType();
            if (mime != null) {
                httpResp.setContentType(mime);
            }
            serveFullResource(httpReq, httpResp, mr);
        }

        // else there is no stream, but probably just headers
        // like e.g. in case of a 302 http-redirect
    } catch (Exception e) {
        if (debug) {
            log.warn("client browser abort when serving media resource", e);
        }
    } finally {
        try {
            mr.release();
        } catch (Exception e) {
            //we did our best here to clean up
        }
    }
}

From source file:com.dosport.system.utils.ServletUtils.java

/**
 * ?? If-None-Match Header, Etag?.//from   w  w  w  .j a  v a  2  s  .com
 * 
 * Etag, checkIfNoneMatchfalse, 304 not modify status.
 * 
 * @param etag
 *            ETag.
 */
public static boolean checkIfNoneMatchEtag(HttpServletRequest request, HttpServletResponse response,
        String etag) {
    String headerValue = request.getHeader("If-None-Match");
    if (headerValue != null) {
        boolean conditionSatisfied = false;
        if (!"*".equals(headerValue)) {
            StringTokenizer commaTokenizer = new StringTokenizer(headerValue, ",");

            while (!conditionSatisfied && commaTokenizer.hasMoreTokens()) {
                String currentToken = commaTokenizer.nextToken();
                if (currentToken.trim().equals(etag)) {
                    conditionSatisfied = true;
                }
            }
        } else {
            conditionSatisfied = true;
        }

        if (conditionSatisfied) {
            response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
            response.setHeader("ETag", etag);
            return false;
        }
    }
    return true;
}

From source file:edu.wisc.web.filter.ShallowEtagHeaderFilter.java

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
        FilterChain filterChain) throws ServletException, IOException {

    ShallowEtagResponseWrapper responseWrapper = new ShallowEtagResponseWrapper(response);
    filterChain.doFilter(request, responseWrapper);

    byte[] body = responseWrapper.toByteArray();
    int statusCode = responseWrapper.getStatusCode();

    if (isEligibleForEtag(request, responseWrapper, statusCode, body)) {
        String responseETag = generateETagHeaderValue(body);
        response.setHeader(HEADER_ETAG, responseETag);

        String requestETag = request.getHeader(HEADER_IF_NONE_MATCH);
        if (responseETag.equals(requestETag)) {
            if (logger.isTraceEnabled()) {
                logger.trace("ETag [" + responseETag + "] equal to If-None-Match, sending 304");
            }//from w w  w.  j a v a  2  s .  co m
            response.setContentLength(0);
            response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
        } else {
            if (logger.isTraceEnabled()) {
                logger.trace("ETag [" + responseETag + "] not equal to If-None-Match [" + requestETag
                        + "], sending normal response");
            }
            copyBodyToResponse(body, response);
        }
    } else {
        if (logger.isTraceEnabled()) {
            logger.trace("Response with status code [" + statusCode + "] not eligible for ETag");
        }
        copyBodyToResponse(body, response);
    }
}

From source file:nl.b3p.viewer.admin.stripes.ComponentConfigSourceActionBean.java

public Resolution source() {
    ViewerComponent vc = ComponentRegistry.getInstance().getViewerComponent(className);

    Resolution notFound = new ErrorResolution(HttpServletResponse.SC_NOT_FOUND);
    if (vc == null) {
        return notFound;
    }//from ww  w .  j a v  a  2 s.com

    File[] files = vc.getConfigSources();

    long lastModified = -1;
    for (File f : files) {
        if (!f.exists() || !f.canRead()) {
            return notFound;
        }
        lastModified = Math.max(lastModified, f.lastModified());
    }
    final File[] theFiles = files;
    StreamingResolution res = new StreamingResolution("application/javascript") {
        @Override
        public void stream(HttpServletResponse response) throws Exception {

            OutputStream out = response.getOutputStream();
            for (File f : theFiles) {
                if (theFiles.length != 1) {
                    out.write(("\n\n// Source file: " + f.getName() + "\n\n").getBytes("UTF-8"));
                }
                IOUtils.copy(new FileInputStream(f), out);
            }
        }
    };
    if (lastModified != -1) {
        long ifModifiedSince = context.getRequest().getDateHeader("If-Modified-Since");

        if (ifModifiedSince != -1) {
            if (ifModifiedSince >= lastModified) {
                return new ErrorResolution(HttpServletResponse.SC_NOT_MODIFIED);
            }
        }
    }
    return res;
}

From source file:net.siegmar.japtproxy.fetcher.FetcherHttp.java

/**
 * {@inheritDoc}//from w  w  w  . j ava 2s  .co  m
 */
@Override
public FetchedResourceHttp fetch(final URL targetResource, final long lastModified,
        final String originalUserAgent) throws IOException, ResourceUnavailableException {

    final HttpGet httpGet = new HttpGet(targetResource.toExternalForm());

    httpGet.addHeader(HttpHeaderConstants.USER_AGENT,
            StringUtils.trim(StringUtils.defaultString(originalUserAgent) + " " + Util.USER_AGENT));

    if (lastModified != 0) {
        final String lastModifiedSince = Util.getRfc822DateFromTimestamp(lastModified);
        LOG.debug("Setting If-Modified-Since: {}", lastModifiedSince);
        httpGet.setHeader(HttpHeaderConstants.IF_MODIFIED_SINCE, lastModifiedSince);
    }

    CloseableHttpResponse httpResponse = null;
    try {
        httpResponse = httpClient.execute(httpGet);

        if (LOG.isDebugEnabled()) {
            logResponseHeader(httpResponse.getAllHeaders());
        }

        final int retCode = httpResponse.getStatusLine().getStatusCode();
        if (retCode == HttpServletResponse.SC_NOT_FOUND) {
            httpGet.releaseConnection();
            throw new ResourceUnavailableException("Resource '" + targetResource + " not found");
        }

        if (retCode != HttpServletResponse.SC_OK && retCode != HttpServletResponse.SC_NOT_MODIFIED) {
            throw new IOException("Invalid status code returned: " + httpResponse.getStatusLine());
        }

        final FetchedResourceHttp fetchedResourceHttp = new FetchedResourceHttp(httpResponse);
        fetchedResourceHttp.setModified(lastModified == 0 || retCode != HttpServletResponse.SC_NOT_MODIFIED);

        if (LOG.isDebugEnabled()) {
            final long fetchedTimestamp = fetchedResourceHttp.getLastModified();
            if (fetchedTimestamp != 0) {
                LOG.debug("Response status code: {}, Last modified: {}", retCode,
                        Util.getSimpleDateFromTimestamp(fetchedTimestamp));
            } else {
                LOG.debug("Response status code: {}", retCode);
            }
        }

        return fetchedResourceHttp;
    } catch (final IOException e) {
        // Closing only in case of an exception - otherwise closed by FetchedResourceHttp
        if (httpResponse != null) {
            httpResponse.close();
        }

        throw e;
    }
}