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.fao.unredd.portal.ApplicationController.java

@RequestMapping("/static/**")
public void getCustomStaticFile(HttpServletRequest request, HttpServletResponse response) throws IOException {

    // Get path to file
    String fileName = (String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);

    // Verify file exists
    File file = new File(config.getDir() + "/static/" + fileName);
    if (!file.isFile()) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;/*  w  w  w  . j  a  v a2s .c  o  m*/
    }

    // Manage cache headers: Last-Modified and If-Modified-Since
    long ifModifiedSince = request.getDateHeader("If-Modified-Since");
    long lastModified = file.lastModified();
    if (ifModifiedSince >= (lastModified / 1000 * 1000)) {
        response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
        return;
    }
    response.setDateHeader("Last-Modified", lastModified);

    // Set content type
    FileNameMap fileNameMap = URLConnection.getFileNameMap();
    String type = fileNameMap.getContentTypeFor(fileName);
    response.setContentType(type);

    // Send contents
    try {
        InputStream is = new FileInputStream(file);
        IOUtils.copy(is, response.getOutputStream());
        response.flushBuffer();
    } catch (IOException e) {
        logger.error("Error reading file", e);
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
}

From source file:org.olat.commons.servlets.StaticsLegacyDispatcher.java

/**
 * Serve the requested resource./*from  w  ww .j  av a2 s.c  om*/
 * 
 * @param request
 * @param response
 * @param copyContent
 * @return False if serving the resource failed/was aborted.
 * @throws IOException
 */
private boolean serveResource(HttpServletRequest request, HttpServletResponse response, boolean copyContent)
        throws IOException {
    // just another internal forward or even a direct call
    String path = getRelativePath(request);
    if (path.indexOf("/secstatic/") == 0) {
        path = path.substring(10, path.length());
    }
    PathHandler handler = null;
    String relPath = null;
    String handlerName = null;
    long start = 0;

    boolean logDebug = log.isDebug();
    if (logDebug)
        start = System.currentTimeMillis();
    try {
        relPath = path.substring(1);
        int index = relPath.indexOf('/');
        if (index != -1) {
            handlerName = relPath.substring(0, index);
            relPath = relPath.substring(index);
        }

        if (handlerName != null) {
            handler = StaticsModule.getInstance(handlerName);
        }
    } catch (IndexOutOfBoundsException e) {
        // if some problem with the url, we assign no handler
    }

    if (handler == null || relPath == null) {
        // no handler found or relPath incomplete
        response.sendError(HttpServletResponse.SC_NOT_FOUND, request.getRequestURI());
        return false;
    }

    ResourceDescriptor rd = handler.getResourceDescriptor(request, relPath);
    if (rd == null) {
        // no handler found or relPath incomplete
        response.sendError(HttpServletResponse.SC_NOT_FOUND, request.getRequestURI());
        return false;
    }

    // check if modified since
    long ifModifiedSince = request.getDateHeader("If-Modified-Since");
    long lastMod = rd.getLastModified();
    if (lastMod != -1L && ifModifiedSince >= lastMod) {
        response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
        return false;
    }

    // server the resource
    if (copyContent) {
        InputStream is = handler.getInputStream(request, rd);
        if (is == null) {
            // resource not found or access denied
            response.sendError(HttpServletResponse.SC_NOT_FOUND, request.getRequestURI());
            return false;
        }
        StaticMediaResource smr = new StaticMediaResource(is, rd);
        ServletUtil.serveResource(request, response, smr);
        if (logDebug) {
            long stop = System.currentTimeMillis();
            log.debug("Serving resource '" + relPath + "' (" + rd.getSize() + " bytes) in " + (stop - start)
                    + "ms with handler '" + handlerName + "'.");
        }
    }
    return true;
}

From source file:org.nuxeo.ecm.core.io.download.TestDownloadService.java

@Test
public void testETagHeaderNoDigest() throws Exception {
    String blobValue = "Hello World";
    Blob blob = Blobs.createBlob(blobValue);
    blob.setFilename("myFile.txt");

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    HttpServletRequest req = mock(HttpServletRequest.class);
    when(req.getHeader("If-None-Match")).thenReturn("\"b10a8db164e0754105b7a99be72e3fe5\"");
    when(req.getMethod()).thenReturn("GET");

    HttpServletResponse resp = mock(HttpServletResponse.class);
    ServletOutputStream sos = new ServletOutputStream() {
        @Override//from ww  w. j  a va  2 s  .  co m
        public void write(int b) throws IOException {
            out.write(b);
        }
    };
    @SuppressWarnings("resource")
    PrintWriter printWriter = new PrintWriter(sos);
    when(resp.getOutputStream()).thenReturn(sos);
    when(resp.getWriter()).thenReturn(printWriter);

    downloadService.downloadBlob(req, resp, null, null, blob, null, "test");

    verify(req, atLeastOnce()).getHeader("If-None-Match");
    assertEquals(0, out.toByteArray().length);
    verify(resp).sendError(HttpServletResponse.SC_NOT_MODIFIED);
}

From source file:com.codeabovelab.dm.gateway.proxy.common.HttpProxy.java

private boolean doResponseRedirectOrNotModifiedLogic(HttpProxyContext proxyContext, HttpResponse proxyResponse,
        int statusCode) throws ServletException, IOException {
    HttpServletResponse servletResponse = proxyContext.getResponse();
    // Check if the proxy response is a redirect
    // The following code is adapted from org.tigris.noodle.filters.CheckForRedirect
    if (statusCode >= HttpServletResponse.SC_MULTIPLE_CHOICES /* 300 */
            && statusCode < HttpServletResponse.SC_NOT_MODIFIED /* 304 */) {
        Header locationHeader = proxyResponse.getLastHeader(HttpHeaders.LOCATION);
        if (locationHeader == null) {
            throw new ServletException("Received status code: " + statusCode + " but no " + HttpHeaders.LOCATION
                    + " header was found in the response");
        }//from w w w .j  a  v a2  s  .co  m
        // Modify the redirect to go to this proxy servlet rather that the proxied host
        String locStr = rewriteUrlFromResponse(proxyContext, locationHeader.getValue());

        servletResponse.sendRedirect(locStr);
        return true;
    }
    // 304 needs special handling.  See:
    // http://www.ics.uci.edu/pub/ietf/http/rfc1945.html#Code304
    // We get a 304 whenever passed an 'If-Modified-Since'
    // header and the data on disk has not changed; server
    // responds w/ a 304 saying I'm not going to send the
    // body because the file has not changed.
    if (statusCode == HttpServletResponse.SC_NOT_MODIFIED) {
        servletResponse.setIntHeader(HttpHeaders.CONTENT_LENGTH, 0);
        servletResponse.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
        return true;
    }
    return false;
}

From source file:org.geowebcache.util.ResponseUtils.java

/**
 * Writes a transparent, 8 bit PNG to avoid having clients like OpenLayers showing lots of pink
 * tiles/*from   ww w  .j a  va2s  . c o  m*/
 */
private static void writeEmpty(DefaultStorageFinder defaultStorageFinder, ConveyorTile tile, String message,
        RuntimeStats runtimeStats) {
    tile.servletResp.setHeader("geowebcache-message", message);
    TileLayer layer = tile.getLayer();
    if (layer != null) {
        layer.setExpirationHeader(tile.servletResp, (int) tile.getTileIndex()[2]);

        if (layer.useETags()) {
            String ifNoneMatch = tile.servletReq.getHeader("If-None-Match");
            if (ifNoneMatch != null && ifNoneMatch.equals("gwc-blank-tile")) {
                tile.servletResp.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
                return;
            } else {
                tile.servletResp.setHeader("ETag", "gwc-blank-tile");
            }
        }
    }

    writeFixedResponse(tile.servletResp, 200, ImageMime.png.getMimeType(), loadBlankTile(defaultStorageFinder),
            CacheResult.OTHER, runtimeStats);
}

From source file:org.activiti.rest.api.cycle.ContentGet.java

private void getContent(ActivitiRequest req, WebScriptResponse res) throws IOException {
    CycleContentService contentService = CycleServiceFactory.getContentService();

    // Retrieve the artifactId from the request
    String cnonectorId = req.getMandatoryString("connectorId");
    String artifactId = req.getMandatoryString("artifactId");
    String contentRepresentationId = req.getMandatoryString("contentRepresentationId");

    // Retrieve the artifact from the repository
    RepositoryArtifact artifact = repositoryService.getRepositoryArtifact(cnonectorId, artifactId);

    ContentRepresentation contentRepresentation = contentService.getContentRepresentation(artifact,
            contentRepresentationId);//from  w w  w.j  a va 2 s. c  om

    MimeType contentType = contentRepresentation.getRepresentationMimeType();
    // assuming we want to create an attachment for binary data...
    boolean attach = contentType.getName().startsWith("application/") ? true : false;

    // TODO: This code should become obsolete when the connectors store the file
    // names properly with suffix.
    String attachmentFileName = null;
    if (attach) {
        attachmentFileName = artifact.getMetadata().getName();

        if (contentType.equals(CycleApplicationContext.get(XmlMimeType.class))
                && !attachmentFileName.endsWith(".xml")) {
            attachmentFileName += ".xml";
        } else if (contentType.equals(CycleApplicationContext.get(JsonMimeType.class))
                && !attachmentFileName.endsWith(".json")) {
            attachmentFileName += ".json";
        } else if (contentType.equals(CycleApplicationContext.get(TextMimeType.class))
                && !attachmentFileName.endsWith(".txt")) {
            attachmentFileName += ".txt";
        } else if (contentType.equals(CycleApplicationContext.get(PdfMimeType.class))
                && !attachmentFileName.endsWith(".pdf")) {
            attachmentFileName += ".pdf";
        } else if (contentType.equals(CycleApplicationContext.get(MsExcelMimeType.class))
                && !attachmentFileName.endsWith(".xls")) {
            attachmentFileName += ".xls";
        } else if (contentType.equals(CycleApplicationContext.get(MsPowerpointMimeType.class))
                && !attachmentFileName.endsWith(".ppt")) {
            attachmentFileName += ".ppt";
        } else if (contentType.equals(CycleApplicationContext.get(MsWordMimeType.class))
                && !attachmentFileName.endsWith(".doc")) {
            attachmentFileName += ".doc";
        }
    }

    InputStream contentInputStream = null;
    try {
        contentInputStream = contentRepresentation.getContent(artifact).asInputStream();

        // TODO: this is broken for SignavioPNG

        // Calculate an etag for the content using the MD5 algorithm
        MessageDigest md = MessageDigest.getInstance("MD5");
        byte[] messageDigest = md.digest(contentRepresentation.getContent(artifact).asByteArray());

        BigInteger number = new BigInteger(1, messageDigest);
        String etag = number.toString(16);
        while (etag.length() < 32) {
            etag = "0" + etag;
        }
        // String etag ="";
        String requestEtag = req.getHttpServletRequest().getHeader("If-None-Match");
        if (requestEtag != null) {
            // For some reason the etag (If-None-Match) parameter is always returned
            // as a quoted string, remove the quotes before comparing it with the
            // newly calculated etag
            requestEtag = requestEtag.replace("\"", "");
        }

        // Check whether the file has been modified since it was last fetched by
        // the client
        if (etag.equals(requestEtag)) {
            throw new WebScriptException(HttpServletResponse.SC_NOT_MODIFIED, "");
        } else {
            streamResponse(res, contentInputStream, new Date(0), etag, attach, attachmentFileName,
                    contentType.getContentType());
        }

    } catch (TransformationException e) {
        // Stream the contents of the exception as HTML, this is a workaround to
        // display exceptions that occur during content transformations
        streamResponse(res, new ByteArrayInputStream(e.getRenderContent().getBytes()), new Date(0), "", false,
                null, CycleApplicationContext.get(HtmlMimeType.class).getContentType());
    } catch (NoSuchAlgorithmException e) {
        // This should never be reached... MessageDigest throws an exception if it
        // is being instantiated with a wrong algorithm, but we know that MD5
        // exists.
    } finally {
        IoUtil.closeSilently(contentInputStream);
    }
}

From source file:org.realityforge.proxy_servlet.AbstractProxyServlet.java

private boolean doResponseRedirectOrNotModifiedLogic(final HttpServletRequest servletRequest,
        final HttpServletResponse servletResponse, final HttpResponse proxyResponse, final int statusCode)
        throws ServletException, IOException {
    // Check if the proxy response is a redirect
    // The following code is adapted from org.tigris.noodle.filters.CheckForRedirect
    if (statusCode >= HttpServletResponse.SC_MULTIPLE_CHOICES && /* 300 */
            statusCode < HttpServletResponse.SC_NOT_MODIFIED /* 304 */ ) {
        final Header locationHeader = proxyResponse.getLastHeader(HttpHeaders.LOCATION);
        if (null == locationHeader) {
            final String message = "Received status code: " + statusCode + " but no " + HttpHeaders.LOCATION
                    + " header was found in the response";
            throw new ServletException(message);
        }/*from  www  . ja  v  a  2 s . co  m*/
        // Modify the redirect to go to this proxy servlet rather that the proxied host
        final String locStr = rewriteUrlFromResponse(servletRequest, locationHeader.getValue());

        servletResponse.sendRedirect(locStr);
        return true;
    }

    // 304 needs special handling.  See:
    // http://www.ics.uci.edu/pub/ietf/http/rfc1945.html#Code304
    // We get a 304 whenever passed an 'If-Modified-Since'
    // header and the data on disk has not changed; server
    // responds w/ a 304 saying I'm not going to send the
    // body because the file has not changed.
    if (statusCode == HttpServletResponse.SC_NOT_MODIFIED) {
        servletResponse.setIntHeader(HttpHeaders.CONTENT_LENGTH, 0);
        servletResponse.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
        return true;
    }
    return false;
}

From source file:com.asual.lesscss.ResourceServlet.java

public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException {

    try {/*w  w w.j ava 2s.  com*/

        String pkg = request.getParameter("pack");
        String[] uri = (pkg != null) ? pkg.split(separator)
                : new String[] { request.getRequestURI().replaceAll("/+", "/") };
        String mimeType = getResourceMimeType(uri[0]);

        long lastModified = 0;
        byte[] content = new byte[0];

        for (String resource : uri) {
            resource = resource.replaceAll("^" + request.getContextPath(), "");
            try {
                content = mergeContent(content, getResourceContent(resource));
            } catch (FileNotFoundException e) {
                response.setStatus(HttpServletResponse.SC_NOT_FOUND);
                return;
            } catch (ResourceNotFoundException e) {
                response.setStatus(HttpServletResponse.SC_NOT_FOUND);
                return;
            }
            lastModified = Math.max(lastModified, getResourceLastModified(resource));
        }

        long ifModifiedSince = request.getDateHeader("If-Modified-Since");
        if (ifModifiedSince != 0 && ifModifiedSince / milliseconds == lastModified / milliseconds) {
            logger.debug("Return with SC_NOT_MODIFIED, since " + ifModifiedSince + " == " + lastModified);
            response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
            return;
        }

        response.setContentType(mimeType + (mimeType.startsWith("text/") ? ";charset=" + charset : ""));
        if (cache) {
            response.setDateHeader("Expires", System.currentTimeMillis() + maxAge * milliseconds);
            response.setDateHeader("Last-Modified", lastModified);
            response.setHeader("Cache-control", "max-age=" + maxAge);
        } else {
            response.setDateHeader("Expires", System.currentTimeMillis());
            response.setDateHeader("Last-Modified", System.currentTimeMillis());
            response.setHeader("Cache-control", "max-age=0");
        }
        response.setContentLength(content.length);
        response.getOutputStream().write(content);
        response.getOutputStream().flush();
        response.getOutputStream().close();

    } catch (Exception e) {
        throw new ServletException(e.getMessage(), e);
    }
}

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

/**
 * Compares the "If-Modified-Since header" of the incoming request with the last modification date of an aggregated
 * resource. If the resource was not modified since the client retrieved the resource, a 304-redirect is send to the
 * response (and the method returns true). If the resource has changed (or the client didn't) supply the
 * "If-Modified-Since" header a "Last-Modified" header is set so future requests can be cached.
 * @param dateProvider abstraction layer that calculates the last-modification time of an aggregated resource
 * @param request Request// www .  j  ava2s  . com
 * @param response Response
 * @param setExpiresHeader Set expires header to -1 to ensure the browser checks for a new version on every request.
 * @return true if the method send a 304 redirect, so that the caller shouldn't write any output to the response
 *         stream
 * @throws IOException
 */
public static boolean isNotModified(ModificationDateProvider dateProvider, SlingHttpServletRequest request,
        SlingHttpServletResponse response, boolean setExpiresHeader) throws IOException {

    // assume the resource *was* modified until we know better
    boolean isModified = true;

    // get the modification date of the resource(s) in question
    Date lastModificationDate = dateProvider.getModificationDate();

    // get the date of the version from the client's cache
    String ifModifiedSince = request.getHeader(HEADER_IF_MODIFIED_SINCE);

    // only compare if both resource modification date and If-Modified-Since header is available
    if (lastModificationDate != null && StringUtils.isNotBlank(ifModifiedSince)) {
        try {
            Date clientModificationDate = parseDate(ifModifiedSince);

            // resource is considered modified if it's modification date is *after* the client's modification date
            isModified = lastModificationDate.getTime() - DateUtils.MILLIS_PER_SECOND > clientModificationDate
                    .getTime();
        } catch (ParseException ex) {
            log.warn("Failed to parse value '" + ifModifiedSince + "' of If-Modified-Since header.", ex);
        }
    }

    // if resource wasn't modified: send a 304 and return true so the caller knows it shouldn't go on writing the response
    if (!isModified) {
        response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
        return true;
    }

    // set last modified header so future requests can be cached
    if (lastModificationDate != null) {
        response.setHeader(HEADER_LAST_MODIFIED, formatDate(lastModificationDate));
        if (setExpiresHeader) {
            // by setting an expires header we force the browser to always check for updated versions (only on author)
            response.setHeader(HEADER_EXPIRES, "-1");
        }
    }

    // tell the caller it should go on writing the response as no 304-header was send
    return false;
}

From source file:org.kuali.mobility.icons.controllers.WebIconsController.java

/**
 * Get the icon matching all the criteria of the request and write it the the HttpServletResponse.
 *
 * @param iconName Name of the icon to get.
 * @param theme    The theme to get the icon in.
 * @param size     Size to get the icon in.
 * @param request  The HttpServletRequest being handled.
 * @param response The HttpServletResponse that will reply.
 * @throws IOException Thrown if there is an exception creating the icon or writing it to the response.
 *///  w  w w .j a v a 2s  . c  om
private void writeIconToHttpResponse(String iconName, String theme, int size, HttpServletRequest request,
        HttpServletResponse response) throws IOException {
    long dateChanged = request.getDateHeader("If-Modified-Since") / 1000;
    File imageFile = iconService.getImageFile(iconName, theme, size);

    long mediaChanged = imageFile.lastModified() / 1000;
    if (dateChanged == mediaChanged) {
        response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
        return;
    }
    response.setContentType("image/png");
    InputStream imageInput = new FileInputStream(imageFile);
    response.setDateHeader("Last-Modified", imageFile.lastModified());

    int bytesWritten = IOUtils.copy(imageInput, response.getOutputStream());
    response.setContentLength(bytesWritten);
    response.flushBuffer();
}