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.nesscomputing.httpserver.jetty.ClasspathResourceHandler.java

@Override
public void handle(final String target, final Request baseRequest, final HttpServletRequest request,
        final HttpServletResponse response) throws IOException, ServletException {
    if (baseRequest.isHandled()) {
        return;/*  w  w w . j av  a 2 s.c om*/
    }

    String pathInfo = request.getPathInfo();

    // Only serve the content if the request matches the base path.
    if (pathInfo == null || !pathInfo.startsWith(basePath)) {
        return;
    }

    pathInfo = pathInfo.substring(basePath.length());

    if (!pathInfo.startsWith("/") && !pathInfo.isEmpty()) {
        // basepath is /foo and request went to /foobar --> pathInfo starts with bar
        // basepath is /foo and request went to /foo --> pathInfo should be /index.html
        return;
    }

    // Allow index.html as welcome file
    if ("/".equals(pathInfo) || "".equals(pathInfo)) {
        pathInfo = "/index.html";
    }

    boolean skipContent = false;

    // When a request hits this handler, it will serve something. Either data or an error.
    baseRequest.setHandled(true);

    final String method = request.getMethod();
    if (!StringUtils.equals(HttpMethods.GET, method)) {
        if (StringUtils.equals(HttpMethods.HEAD, method)) {
            skipContent = true;
        } else {
            response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
            return;
        }
    }

    // Does the request contain an IF_MODIFIED_SINCE header?
    final long ifModifiedSince = request.getDateHeader(HttpHeaders.IF_MODIFIED_SINCE);
    if (ifModifiedSince > 0 && startupTime <= ifModifiedSince / 1000 && !is304Disabled) {
        response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
        return;
    }

    InputStream resourceStream = null;

    try {
        if (pathInfo.startsWith("/")) {
            final String resourcePath = resourceLocation + pathInfo;
            resourceStream = getClass().getResourceAsStream(resourcePath);
        }

        if (resourceStream == null) {
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }

        final Buffer mime = MIME_TYPES.getMimeByExtension(request.getPathInfo());
        if (mime != null) {
            response.setContentType(mime.toString("ISO8859-1"));
        }

        response.setDateHeader(HttpHeaders.LAST_MODIFIED, startupTime * 1000L);

        if (skipContent) {
            return;
        }

        // Send the content out. Lifted straight out of ResourceHandler.java

        OutputStream out = null;
        try {
            out = response.getOutputStream();
        } catch (IllegalStateException e) {
            out = new WriterOutputStream(response.getWriter());
        }

        if (out instanceof AbstractHttpConnection.Output) {
            ((AbstractHttpConnection.Output) out).sendContent(resourceStream);
        } else {
            ByteStreams.copy(resourceStream, out);
        }
    } finally {
        IOUtils.closeQuietly(resourceStream);
    }
}

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

@SuppressWarnings("boxing")
@Override/* w  w  w  .  j a va2s .com*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
    if (request.getHeader("If-Modified-Since") != null) {
        response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
        return;
    }

    Uri uri = new UriBuilder(request).toUri();
    ConcatUriManager.ConcatUri concatUri = concatUriManager.process(uri);

    ConcatUriManager.Type concatType = concatUri.getType();
    try {
        if (concatType == null) {
            throw new GadgetException(GadgetException.Code.MISSING_PARAMETER, "Missing type",
                    HttpResponse.SC_BAD_REQUEST);
        }
        HttpUtil.setCachingHeaders(response,
                concatUri.translateStatusRefresh(LONG_LIVED_REFRESH, DEFAULT_REFRESH), false);
    } catch (GadgetException gex) {
        response.sendError(HttpResponse.SC_BAD_REQUEST, formatError(gex, uri));
        return;
    }

    // Throughout this class, wherever output is generated it's done as a UTF8 String.
    // As such, we affirmatively state that UTF8 is being returned here.
    response.setHeader("Content-Type", concatType.getMimeType() + "; charset=UTF8");
    response.setHeader("Content-Disposition", "attachment;filename=p.txt");

    if (doFetchConcatResources(response, concatUri)) {
        response.setStatus(HttpResponse.SC_OK);
    } else {
        response.setStatus(HttpResponse.SC_BAD_REQUEST);
    }
}

From source file:net.ymate.platform.webmvc.util.WebCacheHelper.java

public void writeResponse() throws Exception {
    if (ICaches.Scope.DEFAULT.equals(__scope)) {
        for (final Map.Entry<String, PairObject<Type.HeaderType, Object>> _header : __element.getHeaders()
                .entrySet()) {//from   ww w. java  2  s.  c om
            if ("ETag".equals(_header.getKey())) {
                String _ifNoneMatch = __request.getHeader("If-None-Match");
                if (_header.getValue() != null && _header.getValue().getValue().equals(_ifNoneMatch)) {
                    __response.sendError(HttpServletResponse.SC_NOT_MODIFIED);
                    return;
                }
                break;
            }
            if (_header.getValue().getValue() != null && "Last-Modified".equals(_header.getKey())) {
                long _ifModifiedSince = __request.getDateHeader("If-Modified-Since");
                if (_ifModifiedSince != -1) {
                    final Date _requestDate = new Date(_ifModifiedSince);
                    final Date _pageDate;
                    switch (_header.getValue().getKey()) {
                    case STRING:
                        _pageDate = DateTimeUtils.parseDateTime((String) _header.getValue().getValue(),
                                "EEE, dd MMM yyyy HH:mm:ss z", "0");
                        break;
                    case DATE:
                        _pageDate = new Date((Long) _header.getValue().getValue());
                        break;
                    default:
                        throw new IllegalArgumentException("Header " + _header + " is not supported as type: "
                                + _header.getValue().getKey());
                    }
                    if (!_requestDate.before(_pageDate)) {
                        __response.sendError(HttpServletResponse.SC_NOT_MODIFIED);
                        __response.setHeader("Last-Modified", __request.getHeader("If-Modified-Since"));
                        return;
                    }
                }
            }
        }
    }
    //
    __response.setContentType(__element.getContentType());
    __doSetHeaders();
    //
    byte[] _body;
    if (__element.isStoreGzipped() && StringUtils.contains(__request.getHeader("Accept-Encoding"), "gzip")) {
        _body = __element.getGzippedBody();
        if (_body.length == EMPTY_GZIPPED_CONTENT_SIZE) {
            _body = new byte[0];
        } else {
            __response.setHeader("Content-Encoding", "gzip");
        }
    } else {
        _body = __element.getUngzippedBody();
    }
    __response.setContentLength(_body.length);
    OutputStream out = new BufferedOutputStream(__response.getOutputStream());
    out.write(_body);
    out.flush();
}

From source file:io.wcm.wcm.commons.caching.CacheHeaderTest.java

@Test
public void testIsNotModified_WithIfModifiedSinceHeader_Author() throws Exception {
    when(request.getAttribute(WCMMode.REQUEST_ATTRIBUTE_NAME)).thenReturn(WCMMode.EDIT);
    when(request.getHeader(HEADER_IF_MODIFIED_SINCE)).thenReturn(formatDate(SAMPLE_CALENDAR_2.getTime()));
    assertTrue(CacheHeader.isNotModified(resource, request, response));
    verify(response).setStatus(HttpServletResponse.SC_NOT_MODIFIED);
    verifyNoMoreInteractions(response);//from w w  w .  ja v a 2  s  . co  m
}

From source file:v7db.files.buckets.BucketsServletTest.java

public void testEchoPutGET() throws IOException, SAXException {

    ServletUnitClient sc = sr.newClient();
    {/*w ww  .  j  a  v  a2  s  . c o m*/
        WebRequest request = new GetMethodWebRequest("http://test/myServlet/1");
        request.setParameter("sha", "1234");
        try {
            sc.getResponse(request);
            fail("bucket not found => 404");
        } catch (HttpNotFoundException e) {
            assertEquals("Bucket '1' not found", e.getResponseMessage());
        }

    }

    prepareBucket("1", "EchoPut", null, null);
    {
        WebRequest request = new GetMethodWebRequest("http://test/myServlet/1");
        request.setParameter("sha", "1234");
        try {
            sc.getResponse(request);
            fail("bucket not found => 404");
        } catch (HttpNotFoundException e) {
            assertEquals("Bucket '1' does not have a file matching digest '1234'", e.getResponseMessage());
        }
    }

    MongoContentStorage storage = new MongoContentStorage(getMongo().getDB("test"));
    ContentSHA sha = storage.storeContent(new ByteArrayInputStream("test".getBytes()));
    {
        WebRequest request = new GetMethodWebRequest("http://test/myServlet/1");
        request.setParameter("sha", sha.getDigest());
        request.setParameter("filename", "a.txt");
        WebResponse response = sc.getResponse(request);
        assertEquals("test", response.getText());
        assertEquals(sha.getDigest(), response.getHeaderField("ETag"));
        assertEquals(4, response.getContentLength());
        assertEquals("attachment; filename=\"a.txt\"", response.getHeaderField("Content-Disposition"));
    }

    {
        WebRequest request = new GetMethodWebRequest("http://test/myServlet/1");
        request.setParameter("sha", sha.getDigest());
        request.setHeaderField("If-None-Match", sha.getDigest());
        WebResponse response = sc.getResponse(request);
        assertEquals(HttpServletResponse.SC_NOT_MODIFIED, response.getResponseCode());
    }

}

From source file:org.alfresco.services.TextRepoContentGetter.java

public GetTextContentResponse getTextContent(Long nodeId, QName propertyQName, Long modifiedSince)
        throws AuthenticationException, IOException, org.alfresco.httpclient.AuthenticationException {
    StringBuilder url = new StringBuilder(128);
    url.append(GET_CONTENT);//from w  w  w.j a  va  2  s  . c  o  m

    StringBuilder args = new StringBuilder(128);
    if (nodeId != null) {
        args.append("?");
        args.append("nodeId");
        args.append("=");
        args.append(nodeId);
    } else {
        throw new NullPointerException("getTextContent(): nodeId cannot be null.");
    }
    if (propertyQName != null) {
        if (args.length() == 0) {
            args.append("?");
        } else {
            args.append("&");
        }
        args.append("propertyQName");
        args.append("=");
        args.append(URLEncoder.encode(propertyQName.toString()));
    }

    url.append(args);

    GetRequest req = new GetRequest(url.toString());

    if (modifiedSince != null) {
        Map<String, String> headers = new HashMap<String, String>(1, 1.0f);
        headers.put("If-Modified-Since", String.valueOf(DateUtil.formatDate(new Date(modifiedSince))));
        req.setHeaders(headers);
    }

    Response response = repoClient.sendRequest(req);

    if (response.getStatus() != HttpServletResponse.SC_NOT_MODIFIED
            && response.getStatus() != HttpServletResponse.SC_NO_CONTENT
            && response.getStatus() != HttpServletResponse.SC_OK) {
        throw new AlfrescoRuntimeException("GetTextContentResponse return status is " + response.getStatus());
    }

    return new GetTextContentResponse(response);
}

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

/**
 * Wraps {@link WebMapService#getMap(GetMapRequest)}, called by the {@link Dispatcher}
 * /*from  w ww  .j  a  v a 2s . c om*/
 * @see WebMapService#getMap(GetMapRequest)
 * @see org.aopalliance.intercept.MethodInterceptor#invoke(org.aopalliance.intercept.MethodInvocation)
 */
public WebMap invoke(MethodInvocation invocation) throws Throwable {
    GWCConfig config = gwc.getConfig();
    if (!config.isDirectWMSIntegrationEnabled()) {
        return (WebMap) invocation.proceed();
    }

    final GetMapRequest request = getRequest(invocation);
    boolean tiled = request.isTiled();
    if (!tiled) {
        return (WebMap) invocation.proceed();
    }

    final StringBuilder requestMistmatchTarget = new StringBuilder();
    ConveyorTile cachedTile = gwc.dispatch(request, requestMistmatchTarget);

    if (cachedTile == null) {
        WebMap dynamicResult = (WebMap) invocation.proceed();
        dynamicResult.setResponseHeader("geowebcache-cache-result", MISS.toString());
        dynamicResult.setResponseHeader("geowebcache-miss-reason", requestMistmatchTarget.toString());
        return dynamicResult;
    }
    checkState(cachedTile.getTileLayer() != null);
    final TileLayer layer = cachedTile.getTileLayer();

    if (LOGGER.isLoggable(Level.FINEST)) {
        LOGGER.finest("GetMap request intercepted, serving cached content: " + request);
    }

    final byte[] tileBytes;
    {
        final Resource mapContents = cachedTile.getBlob();
        if (mapContents instanceof ByteArrayResource) {
            tileBytes = ((ByteArrayResource) mapContents).getContents();
        } else {
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            mapContents.transferTo(Channels.newChannel(out));
            tileBytes = out.toByteArray();
        }
    }

    // Handle Etags
    final String ifNoneMatch = request.getHttpRequestHeader("If-None-Match");
    final byte[] hash = MessageDigest.getInstance("MD5").digest(tileBytes);
    final String etag = toHexString(hash);
    if (etag.equals(ifNoneMatch)) {
        // Client already has the current version
        LOGGER.finer("ETag matches, returning 304");
        throw new HttpErrorCodeException(HttpServletResponse.SC_NOT_MODIFIED);
    }

    LOGGER.finer("No matching ETag, returning cached tile");
    final String mimeType = cachedTile.getMimeType().getMimeType();

    RawMap map = new RawMap(null, tileBytes, mimeType);

    map.setContentDispositionHeader(null, "." + cachedTile.getMimeType().getFileExtension(), false);

    Integer cacheAgeMax = getCacheAge(layer);
    LOGGER.log(Level.FINE, "Using cacheAgeMax {0}", cacheAgeMax);
    if (cacheAgeMax != null) {
        map.setResponseHeader("Cache-Control", "max-age=" + cacheAgeMax);
    } else {
        map.setResponseHeader("Cache-Control", "no-cache");
    }

    setConditionalGetHeaders(map, cachedTile, request, etag);
    setCacheMetadataHeaders(map, cachedTile, layer);

    return map;

}

From source file:org.openmrs.module.atomfeed.web.AtomFeedDownloadServlet.java

/**
 * This method is called by the servlet container to process a HEAD request made by RSS readers
 * against the /atomfeed URI/*ww w. j  a v a 2 s .c om*/
 * 
 * @see javax.servlet.http.HttpServlet#doHead(javax.servlet.http.HttpServletRequest,
 *      javax.servlet.http.HttpServletResponse)
 * @should send not modified error if atom feed has not changed
 * @should send valid headers if atom feed has changed
 */
public void doHead(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    // read atomfeed header specific information from the header file
    String headerFileContent = AtomFeedUtil.readFeedHeaderFile();
    int contentLength = 0;
    String etagToken = "";
    Date lastModified = null;
    if (StringUtils.isNotBlank(headerFileContent)) {
        contentLength = headerFileContent.length() + Integer
                .valueOf(StringUtils.substringBetween(headerFileContent, "<entriesSize>", "</entriesSize>"));
        etagToken = StringUtils.substringBetween(headerFileContent, "<versionId>", "</versionId>");
        try {
            lastModified = new SimpleDateFormat(AtomFeedUtil.RFC_3339_DATE_FORMAT)
                    .parse(StringUtils.substringBetween(headerFileContent, "<updated>", "</updated>"));
        } catch (ParseException e) {
            // ignore it here
        }
    }

    // set the content length and type
    resp.setContentLength(contentLength);
    resp.setContentType("application/atom+xml");
    resp.setCharacterEncoding("UTF-8");

    // compare previous ETag token with current one
    String previousEtagToken = req.getHeader("If-None-Match");
    Calendar ifModifiedSince = Calendar.getInstance();
    long ifModifiedSinceInMillis = req.getDateHeader("If-Modified-Since");
    ifModifiedSince.setTimeInMillis(ifModifiedSinceInMillis);
    if (((etagToken != null) && (previousEtagToken != null && previousEtagToken.equals('"' + etagToken + '"')))
            || (ifModifiedSinceInMillis > 0 && ifModifiedSince.getTime().compareTo(lastModified) >= 0)) {
        // send 304 status code that indicates that resource has not been modified
        resp.sendError(HttpServletResponse.SC_NOT_MODIFIED);
        // re-use original last modified time-stamp
        resp.setHeader("Last-Modified", req.getHeader("If-Modified-Since"));
        // no further processing required
        return;
    }

    // set header for the next time the client calls
    if (etagToken != null) {
        resp.setHeader("ETag", '"' + etagToken + '"');
        // set the last modified time if it's already specified
        if (lastModified == null) {
            // otherwise set the last modified time to now
            Calendar cal = Calendar.getInstance();
            cal.set(Calendar.MILLISECOND, 0);
            lastModified = cal.getTime();
        }
        resp.setDateHeader("Last-Modified", lastModified.getTime());
    }
}

From source file:com.enonic.cms.web.portal.page.PortalResponseProcessor.java

private void servePageResponse() throws IOException {
    HttpServletUtil.setDateHeader(httpResponse, request.getRequestTime().toDate());

    boolean forceNoCache = false;

    if (inPreview || renderTraceOn) {
        forceNoCache = true;// w ww .  j  av  a 2s .  c  o  m
        final DateTime expirationTime = request.getRequestTime();
        setHttpCacheHeaders(request.getRequestTime(), expirationTime, forceNoCache);
    } else if (cacheHeadersEnabledForSite) {
        final DateTime expirationTime = resolveExpirationTime(request.getRequestTime(),
                response.getExpirationTime());
        setHttpCacheHeaders(request.getRequestTime(), expirationTime, forceNoCache);
    }

    // filter response with any response plugins
    String content = filterResponseWithPlugins(response.getContent(), response.getHttpContentType());
    response.setContent(content);

    boolean isHeadRequest = "HEAD".compareToIgnoreCase(httpRequest.getMethod()) == 0;
    boolean writeContent = !isHeadRequest;
    boolean handleEtagLogic = cacheHeadersEnabledForSite && !forceNoCacheForSite && !instantTraceEnabled;

    if (handleEtagLogic && !StringUtils.isEmpty(content)) // resolveEtag does not like empty strings
    {
        // Handling etag logic if cache headers are enabled
        final String etagFromContent = resolveEtag(content);

        HttpServletUtil.setEtag(httpResponse, etagFromContent);

        if (!isContentModified(etagFromContent)) {
            httpResponse.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
            writeContent = false;
        }
    }

    if (instantTraceEnabled && currentPortalRequestTrace != null) {
        final InstantTraceSessionObject instantTraceSessionObject = InstantTraceSessionInspector
                .getInstantTraceSessionObject(httpSession);
        final InstantTraceId instantTraceId = new InstantTraceId(
                currentPortalRequestTrace.getCompletedNumber());
        instantTraceSessionObject.addTrace(instantTraceId, currentPortalRequestTrace);
        InstantTraceResponseWriter.applyInstantTraceId(httpResponse, instantTraceId);
    }

    httpResponse.setContentType(response.getHttpContentType());

    if (isHeadRequest) {
        httpResponse.setContentLength(response.getContentAsBytes().length);
    }

    if (writeContent) {
        writeContent(response.getContentAsBytes());
    }
}

From source file:org.yes.cart.web.filter.ImageFilter.java

public void handleRequestInternal(final HttpServletRequest httpServletRequest,
        final HttpServletResponse httpServletResponse) throws ServletException, IOException {

    final String requestPath = httpServletRequest.getRequestURI(); // RequestURI  -> /yes-shop/imagevault/product/image.png
    final String contextPath = httpServletRequest.getContextPath(); // ContextPath -> /yes-shop
    final String servletPath = requestPath.substring(contextPath.length()); // ServletPath ->          /imagevault/product/image.png

    final String previousToken = httpServletRequest.getHeader(IF_NONE_MATCH);
    final String currentToken = getETagValue(httpServletRequest);

    httpServletResponse.setHeader(ETAG, currentToken);

    final Date modifiedDate = new Date(httpServletRequest.getDateHeader(IF_MODIFIED_SINCE));
    final Calendar calendar = Calendar.getInstance();
    final Date now = calendar.getTime();

    calendar.setTime(modifiedDate);// w ww.  j a  v  a2  s. c om
    calendar.add(Calendar.MINUTE, getEtagExpiration());
    if (currentToken.equals(previousToken) && (now.getTime() < calendar.getTime().getTime())) {
        httpServletResponse.sendError(HttpServletResponse.SC_NOT_MODIFIED);
        // use the same date we sent when we created the ETag the first time through
        httpServletResponse.setHeader(LAST_MODIFIED, httpServletRequest.getHeader(IF_MODIFIED_SINCE));
        final Logger log = ShopCodeContext.getLog(this);
        if (log.isDebugEnabled()) {
            log.debug("ETag the same, will return 304");
        }
    } else {

        httpServletResponse.setDateHeader(LAST_MODIFIED, (new Date()).getTime());

        final String width = httpServletRequest.getParameter(Constants.WIDTH);
        final String height = httpServletRequest.getParameter(Constants.HEIGHT);

        final ImageNameStrategy imageNameStrategy = imageService.getImageNameStrategy(servletPath);

        String code = imageNameStrategy.resolveObjectCode(servletPath); //optional product or sku code
        String locale = imageNameStrategy.resolveLocale(servletPath); //optional locale
        String originalFileName = imageNameStrategy.resolveFileName(servletPath); //here file name with prefix

        final String imageRealPathPrefix = getImageRepositoryRoot();

        String absolutePathToOriginal = imageRealPathPrefix
                + imageNameStrategy.resolveRelativeInternalFileNamePath(originalFileName, code, locale); //path to not resized image

        final boolean origFileExists = imageService.isImageInRepository(originalFileName, code,
                imageNameStrategy.getUrlPath(), imageRealPathPrefix);

        if (!origFileExists) {
            code = Constants.NO_IMAGE;
            originalFileName = imageNameStrategy.resolveFileName(code); //here file name with prefix
            absolutePathToOriginal = imageRealPathPrefix
                    + imageNameStrategy.resolveRelativeInternalFileNamePath(originalFileName, code, locale); //path to not resized image
        }

        String absolutePathToResized = null;
        if (width != null && height != null && imageService.isSizeAllowed(width, height)) {
            absolutePathToResized = imageRealPathPrefix + imageNameStrategy
                    .resolveRelativeInternalFileNamePath(originalFileName, code, locale, width, height);
        }

        final byte[] imageFile = getImageFile(absolutePathToOriginal, absolutePathToResized, width, height);
        IOUtils.write(imageFile, httpServletResponse.getOutputStream());

    }
}