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:org.mycore.common.content.util.MCRServletContentHelper.java

/**
 * Check if the If-Modified-Since condition is satisfied.
 *
 *///from   www. j ava2s.c o  m
private static boolean checkIfModifiedSince(final HttpServletRequest request,
        final HttpServletResponse response, final MCRContent content) throws IOException {
    try {
        final long headerValue = request.getDateHeader("If-Modified-Since");
        final long lastModified = content.lastModified();
        if (headerValue != -1) {

            // If an If-None-Match header has been specified, if modified since
            // is ignored.
            if (request.getHeader("If-None-Match") == null && lastModified < headerValue + 1000) {
                response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
                response.setHeader("ETag", content.getETag());

                return false;
            }
        }
    } catch (final IllegalArgumentException illegalArgument) {
        return true;
    }
    return true;
}

From source file:net.duckling.ddl.web.controller.file.BaseAttachController.java

private void sendNotModifiedHeader(int age, MetaInfo meta, HttpServletResponse res) {
    res.addDateHeader("Last-Modified", meta.lastUpdate.getTime());
    LOGGER.debug("?" + meta.docid);
    res.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
}

From source file:com.reachcall.pretty.http.ProxyServlet.java

private void execute(Match match, HttpRequestBase method, HttpServletRequest req, HttpServletResponse resp)
        throws IOException, ServletException {
    LOG.log(Level.FINE, "Requesting {0}", method.getURI());

    HttpClient client = this.getClient();
    HttpResponse response = client.execute(method);

    for (Header h : response.getHeaders("Set-Cookie")) {
        String line = parseCookie(h.getValue());
        LOG.log(Level.FINER, method.getURI() + "{0}", new Object[] { line });

        if (line != null) {
            LOG.log(Level.INFO, "Bonding session {0} to host {1}",
                    new Object[] { line, match.destination.hostAndPort() });

            try {
                resolver.bond(line, match);
            } catch (ExecutionException ex) {
                Logger.getLogger(ProxyServlet.class.getName()).log(Level.SEVERE, null, ex);
                this.releaseClient(client);

                throw new ServletException(ex);
            }/*from   ww w.j av a  2 s .  co  m*/
        }
    }

    int rc = response.getStatusLine().getStatusCode();

    if ((rc >= HttpServletResponse.SC_MULTIPLE_CHOICES) && (rc < HttpServletResponse.SC_NOT_MODIFIED)) {
        String location = response.getFirstHeader(HEADER_LOCATION).getValue();

        if (location == null) {
            throw new ServletException("Recieved status code: " + rc + " but no " + HEADER_LOCATION
                    + " header was found in the response");
        }

        String hostname = req.getServerName();

        if ((req.getServerPort() != 80) && (req.getServerPort() != 443)) {
            hostname += (":" + req.getServerPort());
        }

        hostname += req.getContextPath();

        String replaced = location.replace(match.destination.hostAndPort() + match.path.getDestination(),
                hostname);

        if (replaced.startsWith("http://")) {
            replaced = replaced.replace("http:", req.getScheme() + ":");
        }

        resp.sendRedirect(replaced);
        this.releaseClient(client);

        return;
    } else if (rc == HttpServletResponse.SC_NOT_MODIFIED) {
        resp.setIntHeader(HEADER_CONTENT_LENTH, 0);
        resp.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
        this.releaseClient(client);

        return;
    }

    resp.setStatus(rc);

    Header[] headerArrayResponse = response.getAllHeaders();

    for (Header header : headerArrayResponse) {
        resp.setHeader(header.getName(), header.getValue());
    }

    if (response.getEntity() != null) {
        resp.setContentLength((int) response.getEntity().getContentLength());

        response.getEntity().writeTo(resp.getOutputStream());
    }

    this.releaseClient(client);

    LOG.finer("Done.");
}

From source file:axiom.servlet.AbstractServletClient.java

protected void writeResponse(HttpServletRequest req, HttpServletResponse res, RequestTrans axiomreq,
        ResponseTrans axiomres) throws IOException {
    if (axiomres.getForward() != null) {
        sendForward(res, req, axiomres);
        return;//ww w .j a  v a 2s. co m
    }

    if (axiomres.getETag() != null) {
        res.setHeader("ETag", axiomres.getETag());
    }

    if (axiomres.getRedirect() != null) {
        sendRedirect(req, res, axiomres.getRedirect());
    } else if (axiomres.getNotModified()) {
        res.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
    } else {
        if (!axiomres.isCacheable() || !caching) {
            // Disable caching of response.
            // for HTTP 1.0
            res.setDateHeader("Expires", System.currentTimeMillis() - 10000);
            res.setHeader("Pragma", "no-cache");

            // for HTTP 1.1
            res.setHeader("Cache-Control", "no-cache, no-store, must-revalidate, max-age=0");
        }

        if (axiomres.getStatus() > 0) {
            res.setStatus(axiomres.getStatus());
        }

        // set last-modified header to now
        long modified = axiomres.getLastModified();
        if (modified > -1) {
            res.setDateHeader("Last-Modified", modified);
        }
        res.setDateHeader("Date", System.currentTimeMillis());

        res.setContentLength(axiomres.getContentLength());
        res.setContentType(axiomres.getContentType());

        if ("HEAD".equalsIgnoreCase(req.getMethod())) {
            return;
        }

        try {
            OutputStream out = res.getOutputStream();

            InputStream istream = axiomres.getInputStream();
            if (istream != null) {
                try {
                    byte[] buf = new byte[8192];
                    int len;
                    while ((len = istream.read(buf)) != -1) {
                        out.write(buf, 0, len);
                    }
                    out.flush();
                } finally {
                    axiomres.closeInputStream();
                }
            } else {
                out.write(axiomres.getContent());
                out.flush();
            }
        } catch (Exception io_e) {
            log("Exception in writeResponse: " + io_e);
        }
    }
}

From source file:edu.cornell.mannlib.vitro.webapp.filters.CachingResponseFilter.java

/**
 * Technically, if the request is not GET or HEAD, we should return 412
 * PreconditionFailed. However, we usually treat GET and POST as equivalent.
 *///from  w  w w.j av a2s  .co m
private void produceCacheHitResponse(HttpServletResponse resp, String etag) throws IOException {
    log.debug("Produce cache hit response: etag='" + etag + "'");
    resp.addHeader("ETag", etag);
    resp.addHeader("Vary", "Accept-Language");
    resp.sendError(HttpServletResponse.SC_NOT_MODIFIED, "Not Modified");
}

From source file:jenkins.metrics.api.MetricsRootAction.java

/**
 * Condense the health check into one bit of information
 * for frontend reverse proxies like haproxy.
 *
 * Other health check calls requires authentication, which
 * is not suitable for the haproxy use. But this endpoint
 * only exposes one bit information, it's deemed OK to be exposed
 * unsecurely./*from w  w  w .j  a  v a  2  s .c o  m*/
 *
 * return status 200 if everything is OK, 503 (service unavailable) otherwise
 */
@SuppressWarnings("unused") // stapler binding
@Restricted(NoExternalUse.class) // stapler binding
public HttpResponse doHealthcheckOk(StaplerRequest req) {
    long ifModifiedSince = req.getDateHeader("If-Modified-Since");
    long maxAge = getCacheControlMaxAge(req);
    Metrics.HealthCheckData data = Metrics.getHealthCheckData();
    if (data == null || (maxAge != -1 && data.getLastModified() + maxAge < System.currentTimeMillis())) {
        data = new Metrics.HealthCheckData(Metrics.healthCheckRegistry().runHealthChecks());
    } else if (ifModifiedSince != -1 && data.getLastModified() < ifModifiedSince) {
        return HttpResponses.status(HttpServletResponse.SC_NOT_MODIFIED);
    }
    for (HealthCheck.Result result : data.getResults().values()) {
        if (!result.isHealthy()) {
            return new StatusResponse(HttpServletResponse.SC_SERVICE_UNAVAILABLE, data.getLastModified(),
                    data.getExpires());
        }
    }
    return new StatusResponse(HttpServletResponse.SC_OK, data.getLastModified(), data.getExpires());
}

From source file:org.geoserver.gwc.GWCIntegrationTest.java

@Test
public void testDirectWMSIntegrationIfModifiedSinceSupport() throws Exception {
    final GWC gwc = GWC.get();
    gwc.getConfig().setDirectWMSIntegrationEnabled(true);

    final String layerName = BASIC_POLYGONS.getPrefix() + ":" + BASIC_POLYGONS.getLocalPart();

    final String path = buildGetMap(true, layerName, "EPSG:4326", null) + "&tiled=true";

    MockHttpServletResponse response = getAsServletResponse(path);
    assertEquals(200, response.getStatusCode());
    assertEquals("image/png", response.getContentType());

    String lastModifiedHeader = response.getHeader("Last-Modified");
    assertNotNull(lastModifiedHeader);/* w w  w  .  j  a  v  a  2 s.  co m*/
    Date lastModified = DateUtil.parseDate(lastModifiedHeader);

    MockHttpServletRequest httpReq = createRequest(path);
    httpReq.setMethod("GET");
    httpReq.setBodyContent(new byte[] {});
    httpReq.setHeader("If-Modified-Since", lastModifiedHeader);

    response = dispatch(httpReq, "UTF-8");

    assertEquals(HttpServletResponse.SC_NOT_MODIFIED, response.getErrorCode());

    // set the If-Modified-Since header to some point in the past of the last modified value
    Date past = new Date(lastModified.getTime() - 5000);
    String ifModifiedSince = DateUtil.formatDate(past);

    httpReq.setHeader("If-Modified-Since", ifModifiedSince);
    response = dispatch(httpReq, "UTF-8");
    assertEquals(HttpServletResponse.SC_OK, response.getErrorCode());

    Date future = new Date(lastModified.getTime() + 5000);
    ifModifiedSince = DateUtil.formatDate(future);

    httpReq.setHeader("If-Modified-Since", ifModifiedSince);
    response = dispatch(httpReq, "UTF-8");
    assertEquals(HttpServletResponse.SC_NOT_MODIFIED, response.getErrorCode());
}

From source file:com.ibm.jaggr.service.impl.AggregatorImpl.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException {
    if (log.isLoggable(Level.FINEST))
        log.finest("doGet: URL=" + req.getRequestURI()); //$NON-NLS-1$

    req.setAttribute(AGGREGATOR_REQATTRNAME, this);
    ConcurrentMap<String, Object> concurrentMap = new ConcurrentHashMap<String, Object>();
    req.setAttribute(CONCURRENTMAP_REQATTRNAME, concurrentMap);

    try {// www  .j a  v a 2  s .c om
        // Validate config last-modified if development mode is enabled
        if (getOptions().isDevelopmentMode()) {
            long lastModified = -1;
            URI configUri = getConfig().getConfigUri();
            if (configUri != null) {
                lastModified = configUri.toURL().openConnection().getLastModified();
            }
            if (lastModified > getConfig().lastModified()) {
                if (reloadConfig()) {
                    // If the config has been modified, then dependencies will be revalidated
                    // asynchronously.  Rather than forcing the current request to wait, return
                    // a response that will display an alert informing the user of what is 
                    // happening and asking them to reload the page.
                    String content = "alert('" + //$NON-NLS-1$ 
                            StringUtil.escapeForJavaScript(Messages.ConfigModified) + "');"; //$NON-NLS-1$
                    resp.addHeader("Cache-control", "no-store"); //$NON-NLS-1$ //$NON-NLS-2$
                    CopyUtil.copy(new StringReader(content), resp.getOutputStream());
                    return;
                }
            }
        }

        getTransport().decorateRequest(req);
        notifyRequestListeners(RequestNotifierAction.start, req, resp);

        ILayer layer = getLayer(req);
        long modifiedSince = req.getDateHeader("If-Modified-Since"); //$NON-NLS-1$
        long lastModified = (Math.max(getCacheManager().getCache().getCreated(), layer.getLastModified(req))
                / 1000) * 1000;
        if (modifiedSince >= lastModified) {
            if (log.isLoggable(Level.FINER)) {
                log.finer("Returning Not Modified response for layer in servlet" + //$NON-NLS-1$
                        getName() + ":" //$NON-NLS-1$
                        + req.getAttribute(IHttpTransport.REQUESTEDMODULES_REQATTRNAME).toString());
            }
            resp.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
        } else {
            // Get the InputStream for the response.  This call sets the Content-Type,
            // Content-Length and Content-Encoding headers in the response.
            InputStream in = layer.getInputStream(req, resp);
            // if any of the readers included an error response, then don't cache the layer.
            if (req.getAttribute(ILayer.NOCACHE_RESPONSE_REQATTRNAME) != null) {
                resp.addHeader("Cache-Control", "no-store"); //$NON-NLS-1$ //$NON-NLS-2$
            } else {
                resp.setDateHeader("Last-Modified", lastModified); //$NON-NLS-1$
                int expires = getConfig().getExpires();
                if (expires > 0) {
                    resp.addHeader("Cache-Control", "max-age=" + expires); //$NON-NLS-1$ //$NON-NLS-2$
                }
            }
            CopyUtil.copy(in, resp.getOutputStream());
        }
        notifyRequestListeners(RequestNotifierAction.end, req, resp);
    } catch (DependencyVerificationException e) {
        // clear the cache now even though it will be cleared when validateDeps has 
        // finished (asynchronously) so that any new requests will be forced to wait
        // until dependencies have been validated.
        getCacheManager().clearCache();
        getDependencies().validateDeps(false);

        resp.addHeader("Cache-control", "no-store"); //$NON-NLS-1$ //$NON-NLS-2$
        if (getOptions().isDevelopmentMode()) {
            String msg = StringUtil.escapeForJavaScript(MessageFormat.format(Messages.DepVerificationFailed,
                    new Object[] { e.getMessage(), AggregatorCommandProvider.EYECATCHER + " " + //$NON-NLS-1$
                            AggregatorCommandProvider.CMD_VALIDATEDEPS + " " + //$NON-NLS-1$
                            getName() + " " + //$NON-NLS-1$
                            AggregatorCommandProvider.PARAM_CLEAN,
                            getWorkingDirectory().toString().replace("\\", "\\\\") //$NON-NLS-1$ //$NON-NLS-2$
                    }));
            String content = "alert('" + msg + "');"; //$NON-NLS-1$ //$NON-NLS-2$
            try {
                CopyUtil.copy(new StringReader(content), resp.getOutputStream());
            } catch (IOException e1) {
                if (log.isLoggable(Level.SEVERE)) {
                    log.log(Level.SEVERE, e1.getMessage(), e1);
                }
                resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            }
        } else {
            resp.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
        }
    } catch (ProcessingDependenciesException e) {
        resp.addHeader("Cache-control", "no-store"); //$NON-NLS-1$ //$NON-NLS-2$
        if (getOptions().isDevelopmentMode()) {
            String content = "alert('" + StringUtil.escapeForJavaScript(Messages.Busy) + "');"; //$NON-NLS-1$ //$NON-NLS-2$
            try {
                CopyUtil.copy(new StringReader(content), resp.getOutputStream());
            } catch (IOException e1) {
                if (log.isLoggable(Level.SEVERE)) {
                    log.log(Level.SEVERE, e1.getMessage(), e1);
                }
                resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            }
        } else {
            resp.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
        }
    } catch (BadRequestException e) {
        exceptionResponse(req, resp, e, HttpServletResponse.SC_BAD_REQUEST);
    } catch (NotFoundException e) {
        exceptionResponse(req, resp, e, HttpServletResponse.SC_NOT_FOUND);
    } catch (Exception e) {
        exceptionResponse(req, resp, e, HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    } finally {
        concurrentMap.clear();
    }
}

From source file:org.mycore.common.content.util.MCRServletContentHelper.java

/**
 * Check if the if-none-match condition is satisfied.
 *///from  w ww. j a v a  2  s  .c  o m
private static boolean checkIfNoneMatch(final HttpServletRequest request, final HttpServletResponse response,
        final MCRContent content) throws IOException {

    final String eTag = content.getETag();
    final String headerValue = request.getHeader("If-None-Match");
    if (headerValue != null) {

        boolean conditionSatisfied = false;

        if ("*".equals(headerValue)) {
            conditionSatisfied = true;
        } else {
            final StringTokenizer commaTokenizer = new StringTokenizer(headerValue, ",");
            while (!conditionSatisfied && commaTokenizer.hasMoreTokens()) {
                final String currentToken = commaTokenizer.nextToken();
                if (currentToken.trim().equals(eTag)) {
                    conditionSatisfied = true;
                }
            }

        }

        if (conditionSatisfied) {
            //'GET' 'HEAD' -> not modified
            if ("GET".equals(request.getMethod()) || "HEAD".equals(request.getMethod())) {
                response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
                response.setHeader("ETag", eTag);

                return false;
            }
            response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
            return false;
        }
    }
    return true;
}