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.localmatters.lesscss4j.servlet.LessCssServlet.java

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

    String clearCache = request.getParameter(CLEAR_CACHE);
    if (clearCache != null && clearCache.equals("true")) {
        clearCache();//from   ww  w.  ja va 2 s.  c  o m
    }

    final String resource = getRequestedResource(request);
    if (resource == null || resource.trim().length() == 0) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }

    final long now = getTime();

    CacheEntry cacheEntry = getCacheEntry(resource, now);

    if (cacheEntry.getValue() != null) {
        boolean isHeadRequest = METHOD_HEAD.equalsIgnoreCase(request.getMethod());
        if (isHeadRequest || isModified(request, cacheEntry)) {
            response.addDateHeader(LAST_MODIFIED, cacheEntry.getLastUpdate());
            response.addDateHeader(EXPIRES, now + getHttpCacheMillis());
            response.addHeader(CACHE_CONTROL, String.format("%s=%s", MAX_AGE, getHttpCacheMillis() / 1000));
            response.setContentType("text/css; charset=UTF-8");
            response.setContentLength(cacheEntry.getValue().length);

            if (!isHeadRequest) {
                IOUtils.write(cacheEntry.getValue(), response.getOutputStream());
            }
        } else {
            response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
        }
    } else {
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
    }
}

From source file:org.geoserver.gwc.wms.CachingWebMapService.java

private void setConditionalGetHeaders(RawMap map, ConveyorTile cachedTile, GetMapRequest request, String etag) {
    map.setResponseHeader("ETag", etag);

    final long tileTimeStamp = cachedTile.getTSCreated();
    final String ifModSinceHeader = request.getHttpRequestHeader("If-Modified-Since");
    // commons-httpclient's DateUtil can encode and decode timestamps formatted as per RFC-1123,
    // which is one of the three formats allowed for Last-Modified and If-Modified-Since headers
    // (e.g. 'Sun, 06 Nov 1994 08:49:37 GMT'). See
    // http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3.1

    final String lastModified = org.apache.commons.httpclient.util.DateUtil.formatDate(new Date(tileTimeStamp));
    map.setResponseHeader("Last-Modified", lastModified);

    final Date ifModifiedSince;
    if (ifModSinceHeader != null && ifModSinceHeader.length() > 0) {
        try {/*ww w.  ja v  a2 s  . c o  m*/
            ifModifiedSince = DateUtil.parseDate(ifModSinceHeader);
            // the HTTP header has second precision
            long ifModSinceSeconds = 1000 * (ifModifiedSince.getTime() / 1000);
            long tileTimeStampSeconds = 1000 * (tileTimeStamp / 1000);
            if (ifModSinceSeconds >= tileTimeStampSeconds) {
                throw new HttpErrorCodeException(HttpServletResponse.SC_NOT_MODIFIED);
            }
        } catch (DateParseException e) {
            if (LOGGER.isLoggable(Level.FINER)) {
                LOGGER.finer("Can't parse client's If-Modified-Since header: '" + ifModSinceHeader + "'");
            }
        }
    }
}

From source file:org.ambraproject.wombat.controller.StaticResourceController.java

/**
 * Serves a file provided by a theme./*from ww w .ja v a2  s.  com*/
 *
 * @param filePath the path to the file (relative to the theme)
 * @param response response object
 * @param theme    specifies the theme from which we are loading the file
 * @throws IOException
 */
private void serveFile(String filePath, HttpServletRequest request, HttpServletResponse response, Theme theme)
        throws IOException {
    try (InputStream inputStream = theme.getStaticResource(filePath)) {
        if (inputStream == null) {
            throw new NotFoundException();
        } else {
            Theme.ResourceAttributes attributes = theme.getResourceAttributes(filePath);

            // We use a "weak" etag, that is, one prepended by "W/".  This means that the resource should be
            // considered semantically-equivalent, but not byte-identical, if the etags match.  It's probably
            // splitting hairs, but this is most appropriate since we don't use a fingerprint of the contents
            // here (instead concatenating length and mtime).  This is what the legacy ambra does for all
            // resources.
            String etag = String.format("W/\"%d-%d\"", attributes.getContentLength(),
                    attributes.getLastModified());
            if (HttpMessageUtil.checkIfModifiedSince(request, attributes.getLastModified(), etag)) {
                response.setHeader("Etag", etag);
                response.setDateHeader(HttpHeaders.LAST_MODIFIED, attributes.getLastModified());
                try (OutputStream outputStream = response.getOutputStream()) {
                    IOUtils.copy(inputStream, outputStream);
                }
            } else {
                response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
                response.setHeader("Etag", etag);
            }
        }
    } catch (FileNotFoundException e) {
        // In case filePath refers to a directory
        throw new NotFoundException(e);
    }
}

From source file:nl.strohalm.cyclos.servlets.ImageByNameServlet.java

/**
 * Write the image file to the response/*from w w w .  ja v a  2  s. c o  m*/
 */
private void write(final HttpServletRequest request, final HttpServletResponse response, final File file,
        final ImageType type) throws IOException {
    final long ifModifiedSince = request.getDateHeader("If-Modified-Since");
    if (ifModifiedSince > 0 && file.lastModified() <= ifModifiedSince) {
        // The contents have not changed
        response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
        return;
    }
    // The contents are modified, or not in browser's cache. Render it
    if (type != null) {
        response.setContentType(type.getContentType());
    }
    responseHelper.writeFile(response, file);
    response.flushBuffer();
}

From source file:org.dspace.app.webui.servlet.HandleServlet.java

protected void doDSGet(Context context, HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, SQLException, AuthorizeException {
    String handle = null;/* w  ww.  java2s. c  o  m*/
    String extraPathInfo = null;
    DSpaceObject dso = null;

    // Original path info, of the form "1721.x/1234"
    // or "1721.x/1234/extra/stuff"
    String path = request.getPathInfo();

    if (path != null) {
        // substring(1) is to remove initial '/'
        path = path.substring(1);

        try {
            // Extract the Handle
            int firstSlash = path.indexOf('/');
            int secondSlash = path.indexOf('/', firstSlash + 1);

            if (secondSlash != -1) {
                // We have extra path info
                handle = path.substring(0, secondSlash);
                extraPathInfo = path.substring(secondSlash);
            } else {
                // The path is just the Handle
                handle = path;
            }
        } catch (NumberFormatException nfe) {
            // Leave handle as null
        }
    }

    // Find out what the handle relates to
    if (handle != null) {
        dso = HandleManager.resolveToObject(context, handle);
    }

    if (dso == null) {
        log.info(LogManager.getHeader(context, "invalid_id", "path=" + path));
        JSPManager.showInvalidIDError(request, response, StringEscapeUtils.escapeHtml(path), -1);

        return;
    }

    if ("/statistics".equals(extraPathInfo)) {
        // Check configuration properties, auth, etc.
        // Inject handle attribute
        log.info(LogManager.getHeader(context, "display_statistics",
                "handle=" + handle + ", path=" + extraPathInfo));
        request.setAttribute("handle", handle);

        // Forward to DisplayStatisticsServlet without changing path.
        RequestDispatcher dispatch = getServletContext().getNamedDispatcher("displaystats");
        dispatch.forward(request, response);

        // If we don't return here, we keep processing and end up
        // throwing a NPE when checking community authorization
        // and firing a usage event for the DSO we're reporting for
        return;

    }

    // OK, we have a valid Handle. What is it?
    if (dso.getType() == Constants.ITEM) {
        // do we actually want to display the item, or forward to another page?
        if ((extraPathInfo == null) || (extraPathInfo.equals("/"))) {
            Item item = (Item) dso;

            // Only use last-modified if this is an anonymous access
            // - caching content that may be generated under authorisation
            //   is a security problem

            if (context.getCurrentUser() == null) {
                response.setDateHeader("Last-Modified", item.getLastModified().getTime());

                // Check for if-modified-since header

                long modSince = request.getDateHeader("If-Modified-Since");

                if (modSince != -1 && item.getLastModified().getTime() < modSince) {
                    // Item has not been modified since requested date,
                    // hence bitstream has not been, either; return 304
                    response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
                } else {
                    // Display the item page
                    displayItem(context, request, response, item, handle);
                }
            } else {
                // Display the item page
                displayItem(context, request, response, item, handle);
            }
        } else {
            // Forward to another servlet
            request.getRequestDispatcher(extraPathInfo).forward(request, response);
        }

    } else if (dso.getType() == Constants.COLLECTION) {
        Collection c = (Collection) dso;

        // Store collection location in request
        request.setAttribute("dspace.collection", c);

        /*
         * Find the "parent" community the collection, mainly for
         * "breadcrumbs" FIXME: At the moment, just grab the first community
         * the collection is in. This should probably be more context
         * sensitive when we have multiple inclusion.
         */
        Community[] parents = c.getCommunities();
        request.setAttribute("dspace.community", parents[0]);

        /*
         * Find all the "parent" communities for the collection for
         * "breadcrumbs"
         */
        request.setAttribute("dspace.communities", getParents(parents[0], true));

        // home page, or forward to another page?
        if ((extraPathInfo == null) || (extraPathInfo.equals("/"))) {
            collectionHome(context, request, response, parents[0], c);
        } else {
            // Forward to another servlet
            request.getRequestDispatcher(extraPathInfo).forward(request, response);
        }
    } else if (dso.getType() == Constants.COMMUNITY) {
        Community c = (Community) dso;

        // Store collection location in request
        request.setAttribute("dspace.community", c);

        /*
         * Find all the "parent" communities for the community
         */
        request.setAttribute("dspace.communities", getParents(c, false));

        // home page, or forward to another page?
        if ((extraPathInfo == null) || (extraPathInfo.equals("/"))) {
            communityHome(context, request, response, c);
        } else {
            // Forward to another servlet
            request.getRequestDispatcher(extraPathInfo).forward(request, response);
        }
    } else {
        // Shouldn't happen. Log and treat as invalid ID
        log.info(LogManager.getHeader(context, "Handle not an item, collection or community",
                "handle=" + handle));
        JSPManager.showInvalidIDError(request, response, StringEscapeUtils.escapeHtml(path), -1);

        return;
    }
}

From source file:org.craftercms.core.controller.rest.ContentStoreRestControllerTest.java

private void testNotModified(CachingAwareObject cachingAwareObject, RestMethodCallback callback)
        throws Exception {
    cachingAwareObject.setCachingTime(System.currentTimeMillis());
    request.addHeader(IF_MODIFIED_SINCE_HEADER_NAME, cachingAwareObject.getCachingTime());

    Map<String, Object> model = callback.executeMethod();
    assertTrue(MapUtils.isEmpty(model));
    assertEquals(HttpServletResponse.SC_NOT_MODIFIED, response.getStatus());
    assertEquals(MUST_REVALIDATE_HEADER_VALUE, response.getHeader(CACHE_CONTROL_HEADER_NAME));
}

From source file:cn.knet.showcase.demos.servletproxy.ProxyServlet.java

protected void service(HttpServletRequest servletRequest, HttpServletResponse servletResponse)
        throws ServletException, IOException {
    //initialize request attributes from caches if unset by a subclass by this point
    if (servletRequest.getAttribute(ATTR_TARGET_URI) == null) {
        servletRequest.setAttribute(ATTR_TARGET_URI, targetUri);
    }//  ww w. jav  a2 s .  c  o  m
    if (servletRequest.getAttribute(ATTR_TARGET_HOST) == null) {
        servletRequest.setAttribute(ATTR_TARGET_HOST, targetHost);
    }

    // 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;
    //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) {
        proxyRequest = newProxyRequestWithEntity(method, proxyRequestUri, servletRequest);
    } else {
        proxyRequest = new BasicHttpRequest(method, proxyRequestUri);
    }

    copyRequestHeaders(servletRequest, proxyRequest);

    setXForwardedForHeader(servletRequest, proxyRequest);

    HttpResponse proxyResponse = null;
    try {
        // Execute the request

        //Fallback on using older client:

        proxyResponse = proxyClient.execute(getTargetHost(servletRequest), proxyRequest);

        // Process the response:

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

        // Copying response headers to make sure SESSIONID or other Cookie which comes from the remote
        // server will be saved in client when the proxied url was redirected to another one.
        // See issue [#51](https://github.com/mitre/HTTP-Proxy-Servlet/issues/51)
        copyResponseHeaders(proxyResponse, servletRequest, servletResponse);

        if (statusCode == HttpServletResponse.SC_NOT_MODIFIED) {
            // 304 needs special handling.  See:
            // http://www.ics.uci.edu/pub/ietf/http/rfc1945.html#Code304
            // Don't send body entity/content!
            servletResponse.setIntHeader(HttpHeaders.CONTENT_LENGTH, 0);
        } else {
            // 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.apache.struts2.rest.RestActionInvocation.java

protected void processResult() throws Exception {
    String timerKey = "processResult: " + getResultCode();
    try {//from   w  w w.  ja v a 2  s .  com
        UtilTimerStack.push(timerKey);

        HttpServletRequest request = ServletActionContext.getRequest();
        HttpServletResponse response = ServletActionContext.getResponse();

        // Select the target
        selectTarget();

        // Get the httpHeaders
        if (httpHeaders == null) {
            httpHeaders = new DefaultHttpHeaders(resultCode);
        }

        // Apply headers
        if (!hasErrors) {
            httpHeaders.apply(request, response, target);
        } else {
            disableCatching(response);
        }

        // Don't return content on a not modified
        if (httpHeaders.getStatus() != HttpServletResponse.SC_NOT_MODIFIED) {
            executeResult();
        } else {
            LOG.debug("Result not processed because the status code is not modified.");
        }

    } finally {
        UtilTimerStack.pop(timerKey);
    }
}

From source file:au.edu.anu.portal.portlets.tweetal.servlet.TweetalServlet.java

public void deleteTweets(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String userToken = request.getParameter("u");
    String userSecret = request.getParameter("s");
    long statusID = Long.parseLong(request.getParameter("d"));

    log.debug("Deleting tweet " + statusID);

    Twitter twitter = twitterLogic.getTwitterAuthForUser(userToken, userSecret);
    if (twitter == null) {
        // no connection
        response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
        return;//from www .  j  a v a  2 s.c o  m
    }

    try {
        Status s = twitter.destroyStatus(statusID);
        if (s != null) {
            // success
            response.setStatus(HttpServletResponse.SC_OK);

            // remove tweets from cache
            String cacheKey = userToken;
            tweetsCache.remove(cacheKey);

        } else {
            response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
        }

    } catch (TwitterException e) {
        // problem in deleting the tweet
        log.error("Delete Tweet: " + e.getStatusCode() + ": " + e.getClass() + e.getMessage());
        response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
    }
}

From source file:org.sprintapi.api.http.HttpServlet.java

protected void doService(HttpServletRequest httpRequest, HttpServletResponse httpResponse)
        throws ErrorException, IOException {

    final RequestHolder<Object> request = new RequestHolder<Object>(getUri(httpRequest));
    request.setContext(httpRequest.getContextPath());

    // Resolve incoming URL and get resource descriptor
    final ResourceDescriptor resourceDsc = resolve(request.getUri());

    // Does the requested resource exist?
    if (resourceDsc == null) {
        throw new ErrorException(request.getUri(), HttpServletResponse.SC_NOT_FOUND);
    }/* w  ww .j  av  a2 s  . c o m*/

    // Is requested method supported?
    if (httpRequest.getMethod() == null) {
        throw new ErrorException(request.getUri(), HttpServletResponse.SC_BAD_REQUEST);
    }

    try {
        request.setMethod(Method.valueOf(httpRequest.getMethod().toUpperCase(Locale.US)));

    } catch (IllegalArgumentException ex) {
        throw new ErrorException(request.getUri(), HttpServletResponse.SC_NOT_IMPLEMENTED);
    }

    if (request.getMethod() == null) {
        throw new ErrorException(request.getUri(), HttpServletResponse.SC_NOT_IMPLEMENTED);
    }

    // Get supported methods for requested resource
    Map<Method, MethodDescriptor<?, ?>> methods = resourceDsc.methods();

    // Get requested method descriptors for the resource
    MethodDescriptor<?, ?> methodDsc = (methods != null) ? methods.get(request.getMethod()) : null;

    // Is requested method supported?
    if ((methodDsc == null)) {
        throw new ErrorException(request.getUri(), HttpServletResponse.SC_METHOD_NOT_ALLOWED);
    }

    ContentAdapter<InputStream, ?> inputContentAdapter = null;

    // Is request body expected?
    if (request.getMethod().isRequestBody()) {
        String requestContentType = httpRequest.getContentType();

        inputContentAdapter = (methodDsc.consumes() != null) ? methodDsc.consumes().get(requestContentType)
                : null;
        if (inputContentAdapter == null) {
            throw new ErrorException(request.getUri(), HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE);
        }

    } else if (httpRequest.getContentLength() > 0) {
        // Unexpected request body
        throw new ErrorException(request.getUri(), HttpServletResponse.SC_BAD_REQUEST);
    }

    ContentAdapter<?, InputStream> outputContentAdapter = null;

    String responseContentType = null;

    // Is response body expected?
    if (request.getMethod().isResponseBody()) {
        // Check Accept header
        HttpAcceptHeader acceptHeader = HttpAcceptHeader
                .read(httpRequest.getHeader(ContentDescriptor.META_ACCEPT));
        if (acceptHeader != null) {

            Map<String, ?> produces = methodDsc.produces();

            // Response content negotiation 
            if (produces != null) {
                int weight = 0;

                for (String ct : produces.keySet()) {
                    int tw = acceptHeader.accept(ct);
                    if (tw > weight) {
                        weight = tw;
                        responseContentType = ct;
                        outputContentAdapter = (ContentAdapter<?, InputStream>) produces.get(ct);
                    }
                }
            }
            if (outputContentAdapter == null) {
                throw new ErrorException(request.getUri(), HttpServletResponse.SC_NOT_ACCEPTABLE);
            }
        }
    }

    if (inputContentAdapter != null) {
        ContentHolder<Object> lc = new ContentHolder<Object>();
        lc.setBody(inputContentAdapter.transform(request.getUri(), httpRequest.getInputStream()));
        request.setContent(lc);
    }

    // Invoke resource method
    Response response = methodDsc.invoke((Request) request);

    if (response == null) {
        throw new ErrorException(request.getUri(), HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }

    // Write response status
    int responseStatus = (response.getStatus() > 0) ? response.getStatus() : HttpServletResponse.SC_OK;
    httpResponse.setStatus(responseStatus);

    if (response.getContent() == null) {
        return;
    }

    // Write response headers
    if (response.getContent().getMetaNames() != null) {
        for (String metaName : response.getContent().getMetaNames()) {
            Object metaValue = response.getContent().getMeta(metaName);
            if (metaValue != null) {
                if (metaValue instanceof Date) {
                    httpResponse.setHeader(metaName, HttpDate.RFC1123_FORMAT.format(((Date) metaValue)));
                } else {
                    httpResponse.setHeader(metaName, metaValue.toString());
                }
            }
        }
    }

    if ((HttpServletResponse.SC_CREATED == responseStatus)) {
        httpResponse.setHeader(ContentDescriptor.META_LOCATION, response.getContext() + response.getUri());
    }

    if ((response.getContent().getBody() == null) || (HttpServletResponse.SC_NOT_MODIFIED == responseStatus)) {
        return;
    }

    // Write response body
    if (outputContentAdapter != null) {
        httpResponse.setHeader(ContentDescriptor.META_CONTENT_TYPE, responseContentType);
        InputStream is = ((ContentAdapter<Object, InputStream>) outputContentAdapter)
                .transform(request.getUri(), response.getContent().getBody());
        if (is != null) {
            CopyUtils.copy(is, httpResponse.getOutputStream());
        }
    }
}