Example usage for javax.servlet.http HttpServletResponse SC_PRECONDITION_FAILED

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

Introduction

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

Prototype

int SC_PRECONDITION_FAILED

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

Click Source Link

Document

Status code (412) indicating that the precondition given in one or more of the request-header fields evaluated to false when it was tested on the server.

Usage

From source file:org.eclipse.orion.internal.server.servlets.file.DirectoryHandlerV1.java

/**
 * Asserts that request options are valid. If options are not valid then this method handles the request response and return false. If the options
 * are valid this method return true.//  w  ww.j a v  a  2  s .c o m
 */
private boolean validateOptions(HttpServletRequest request, HttpServletResponse response, IFileStore toCreate,
        boolean destinationExists, int options) throws ServletException {
    //operation cannot be both copy and move
    int copyMove = CREATE_COPY | CREATE_MOVE;
    if ((options & copyMove) == copyMove) {
        statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR,
                HttpServletResponse.SC_BAD_REQUEST, "Syntax error in request", null));
        return false;
    }
    //if overwrite is disallowed make sure destination does not exist yet
    boolean noOverwrite = (options & CREATE_NO_OVERWRITE) != 0;
    //for copy/move case, let the implementation check for overwrite because pre-validating is complicated
    if ((options & copyMove) == 0 && noOverwrite && destinationExists) {
        statusHandler.handleRequest(request, response,
                new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_PRECONDITION_FAILED,
                        "A file or folder with the same name already exists at this location", null));
        return false;
    }
    return true;
}

From source file:org.apache.sling.launchpad.webapp.integrationtest.servlets.post.PostServletMoveTest.java

public void testMoveNodeMultipleSourceInValid() throws IOException {
    final String testPath = TEST_BASE_PATH + "/mvmult/" + System.currentTimeMillis();
    final String testRoot = testClient.createNode(HTTP_BASE_URL + testPath, null);

    // create multiple source nodes
    Map<String, String> props = new HashMap<String, String>();
    props.put("text", "Hello");
    testClient.createNode(HTTP_BASE_URL + testPath + "/src1", props);
    testClient.createNode(HTTP_BASE_URL + testPath + "/src2", props);
    testClient.createNode(HTTP_BASE_URL + testPath + "/src3", props);
    testClient.createNode(HTTP_BASE_URL + testPath + "/src4", props);

    // move the src? nodes
    List<NameValuePair> nvPairs = new ArrayList<NameValuePair>();
    nvPairs.add(new NameValuePair(SlingPostConstants.RP_OPERATION, SlingPostConstants.OPERATION_MOVE));
    nvPairs.add(new NameValuePair(SlingPostConstants.RP_DEST, testPath + "/dest"));
    nvPairs.add(new NameValuePair(SlingPostConstants.RP_APPLY_TO, testPath + "/src1"));
    nvPairs.add(new NameValuePair(SlingPostConstants.RP_APPLY_TO, testPath + "/src2"));
    nvPairs.add(new NameValuePair(SlingPostConstants.RP_APPLY_TO, testPath + "/src3"));
    nvPairs.add(new NameValuePair(SlingPostConstants.RP_APPLY_TO, testPath + "/src4"));
    assertPostStatus(testRoot, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, nvPairs,
            "Expecting Move Failure (dest must have trailing slash)");

    // create destination parent
    testClient.createNode(HTTP_BASE_URL + testPath + "/dest", props);

    // retest after creating test
    assertPostStatus(testRoot, HttpServletResponse.SC_PRECONDITION_FAILED, nvPairs,
            "Expecting Move Failure (dest already exists)");

    // assert non-existence of the src?/text properties
    assertHttpStatus(HTTP_BASE_URL + testPath + "/dest/src1/text", HttpServletResponse.SC_NOT_FOUND);
    assertHttpStatus(HTTP_BASE_URL + testPath + "/dest/src2/text", HttpServletResponse.SC_NOT_FOUND);
    assertHttpStatus(HTTP_BASE_URL + testPath + "/dest/src3/text", HttpServletResponse.SC_NOT_FOUND);
    assertHttpStatus(HTTP_BASE_URL + testPath + "/dest/src4/text", HttpServletResponse.SC_NOT_FOUND);

    // assert non-existence of src?
    assertHttpStatus(HTTP_BASE_URL + testPath + "/src1.html", HttpServletResponse.SC_OK);
    assertHttpStatus(HTTP_BASE_URL + testPath + "/src2.html", HttpServletResponse.SC_OK);
    assertHttpStatus(HTTP_BASE_URL + testPath + "/src3.html", HttpServletResponse.SC_OK);
    assertHttpStatus(HTTP_BASE_URL + testPath + "/src4.html", HttpServletResponse.SC_OK);

    testClient.delete(testRoot);/*  w  w w .  j  a  v  a 2  s.c  o  m*/
}

From source file:ch.entwine.weblounge.common.impl.request.Http11ProtocolHandler.java

/**
 * Method generateResponse./*from  www.  j  av  a 2 s .  c  o m*/
 * 
 * @param resp
 * @param type
 * @param is
 * @return boolean
 * @throws IOException
 *           if generating the response fails
 */
public static boolean generateResponse(HttpServletResponse resp, Http11ResponseType type, InputStream is)
        throws IOException {

    /* first generate the response headers */
    generateHeaders(resp, type);

    /* adjust the statistics */
    ++stats[STATS_BODY_GENERATED];
    incResponseStats(type.type, bodyStats);

    /* generate the response body */
    try {
        if (resp.isCommitted())
            log.warn("Response is already committed!");
        switch (type.type) {
        case RESPONSE_OK:
            if (!type.isHeaderOnly() && is != null) {
                resp.setBufferSize(BUFFER_SIZE);
                OutputStream os = null;
                try {
                    os = resp.getOutputStream();
                    IOUtils.copy(is, os);
                } catch (IOException e) {
                    if (RequestUtils.isCausedByClient(e))
                        return true;
                } finally {
                    IOUtils.closeQuietly(os);
                }
            }
            break;

        case RESPONSE_PARTIAL_CONTENT:
            if (type.from < 0 || type.to < 0 || type.from > type.to || type.to > type.size) {
                resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                        "Invalid partial content parameters");
                log.warn("Invalid partial content parameters");
            } else if (!type.isHeaderOnly() && is != null) {
                resp.setBufferSize(BUFFER_SIZE);
                OutputStream os = resp.getOutputStream();
                if (is.skip(type.from) != type.from) {
                    resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                            "Premature end of input stream");
                    log.warn("Premature end of input stream");
                    break;
                }
                try {

                    /* get the temporary buffer for this thread */
                    byte[] tmp = buffer.get();
                    if (tmp == null) {
                        tmp = new byte[BUFFER_SIZE];
                        buffer.set(tmp);
                    }

                    int read = type.to - type.from;
                    int copy = read;
                    int write = 0;

                    read = is.read(tmp);
                    while (copy > 0 && read >= 0) {
                        copy -= read;
                        write = copy > 0 ? read : read + copy;
                        os.write(tmp, 0, write);
                        stats[STATS_BYTES_WRITTEN] += write;
                        read = is.read(tmp);
                    }
                    if (copy > 0) {
                        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                                "Premature end of input stream");
                        log.warn("Premature end of input stream");
                        break;
                    }
                    os.flush();
                    os.close();
                } catch (SocketException e) {
                    log.debug("Request cancelled by client");
                }
            }
            break;

        case RESPONSE_NOT_MODIFIED:
            /* NOTE: we MUST NOT return any content (RFC 2616)!!! */
            break;

        case RESPONSE_PRECONDITION_FAILED:
            if (type.err == null)
                resp.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
            else
                resp.sendError(HttpServletResponse.SC_PRECONDITION_FAILED, type.err);
            break;

        case RESPONSE_REQUESTED_RANGE_NOT_SATISFIABLE:
            if (type.err == null)
                resp.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE);
            else
                resp.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE, type.err);
            break;

        case RESPONSE_METHOD_NOT_ALLOWED:
            if (type.err == null)
                resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
            else
                resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, type.err);
            break;

        case RESPONSE_INTERNAL_SERVER_ERROR:
        default:
            if (type.err == null)
                resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            else
                resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, type.err);
        }
    } catch (IOException e) {
        if (e instanceof EOFException) {
            log.debug("Request canceled by client");
            return true;
        }
        ++stats[STATS_ERRORS];
        String message = e.getCause() != null ? e.getCause().getMessage() : e.getMessage();
        Throwable cause = e.getCause() != null ? e.getCause() : e;
        log.warn("I/O exception while sending response: {}", message, cause);
        throw e;
    }

    return true;
}

From source file:hu.api.SivaPlayerVideoServlet.java

private void doAction(HttpServletRequest request, HttpServletResponse response, String requestType)
        throws ServletException, IOException {

    // Check if it's an AJAX request
    this.isAJAXRequest = (request.getParameter("ajax") != null && request.getParameter("ajax").equals("true"));

    // Allow Cross-Origin-Requests
    response.setHeader("Access-Control-Allow-Origin", "*");
    response.setHeader("Access-Control-Allow-Methods", "GET, PUT, POST, DELETE, OPTIONS");
    response.setHeader("Access-Control-Max-Age", "1000");
    response.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization, X-Requested-With");

    // URL pattern: /videoId
    // Get request parameter from URL and check if it has been set.
    // Show 400 if less or more parameters than allowed.
    String requestedVideo = request.getPathInfo();
    if (requestedVideo == null || requestedVideo.split("/").length < 2
            || requestedVideo.split("/")[1].equals("")) {
        this.sendError(response, HttpServletResponse.SC_BAD_REQUEST,
                "The video folder has to be specified for using this web service.");
        return;//from  w  ww .j  ava2s.  co m
    }

    this.persistenceProvider = (IPersistenceProvider) getServletContext().getAttribute("PersistenceProvider");
    this.mailService = (MailService) getServletContext().getAttribute("mailService");
    this.brandingConfiguration = (BrandingConfiguration) getServletContext()
            .getAttribute("brandingConfiguration");

    // Check if it's a watching request
    if (request.getPathInfo().endsWith("/watch.html")) {
        this.providePlayer(request, response);
        return;
    }

    // Check if it's a log request and perform logging if so
    if (request.getPathInfo().endsWith("/log") && requestType.equals("POST")) {
        this.doLogging(request, response);
        return;
    }

    // Check if it's a checkSession request and provide session status if so
    if (requestedVideo.endsWith("/getStats.js")) {
        this.getStats(request, response);
        return;
    }

    // Check if user requests user secret and perform login
    if (request.getPathInfo().endsWith("/getSecret.js") && requestType.equals("POST")) {
        this.provideUserSecret(request, response, requestType);
        return;
    }

    // Check if current session exists and if it is allowed to access this
    // video, stop further execution, if so.
    boolean result = handleAccess(request, response, requestType);
    if (!result) {
        return;
    }

    // Check if it's collaboration request and provide data
    if (request.getPathInfo().endsWith("/getCollaboration.js")) {
        this.provideCollaboration(request, response);
        return;
    }

    // Check if it's a thread creation request
    if (request.getPathInfo().endsWith("/createCollaborationThread.js")) {
        this.createCollaborationThread(request, response);
        return;
    }

    // Check if it's a post creation request
    if (request.getPathInfo().endsWith("/createCollaborationPost.js")) {
        this.createCollaborationPost(request, response);
        return;
    }

    // Check if it's a post activation request
    if (request.getPathInfo().endsWith("/activateCollaborationPost.js")) {
        this.activateCollaborationPost(request, response);
        return;
    }

    // Check if it's a post creation request
    if (request.getPathInfo().endsWith("/deleteCollaborationThread.js")) {
        this.deleteCollaborationThread(request, response);
        return;
    }

    // Check if it's a post creation request
    if (request.getPathInfo().endsWith("/deleteCollaborationPost.js")) {
        this.deleteCollaborationPost(request, response);
        return;
    }

    // Check if it's a checkSession request and provide session status if so
    if (requestedVideo.endsWith("/checkSession.js")) {
        this.provideSessionStatus(request, response);
        return;
    }

    // Decode the file name from the URL and check if file actually exists
    // in
    // file system, send 404 if not
    File file = new File(videoPath, URLDecoder.decode(requestedVideo, "UTF-8"));
    if (!file.exists()) {
        this.sendError(response, HttpServletResponse.SC_NOT_FOUND, "File not found");
        return;
    }

    // Create log entry for file request
    this.logFileRequest(requestedVideo);

    // Check if configuration is requested and do needed preparing and
    // stop standard file preparation
    if (file.getName().equals("export.js")) {
        this.provideConfigFile(request, response, file);
        return;
    }

    // Prepare some variables. The ETag is an unique identifier of the file.
    String fileName = file.getName();
    long length = file.length();
    long lastModified = file.lastModified();
    String eTag = fileName + "_" + length + "_" + lastModified;
    long expires = System.currentTimeMillis() + DEFAULT_EXPIRE_TIME;

    // Validate request headers for caching
    // ---------------------------------------------------

    // If-None-Match header should contain "*" or ETag. If so, then return
    // 304.
    String ifNoneMatch = request.getHeader("If-None-Match");
    if (ifNoneMatch != null && matches(ifNoneMatch, eTag)) {
        response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
        response.setHeader("ETag", eTag); // Required in 304.
        response.setDateHeader("Expires", expires); // Postpone cache with 1
        // week.
        return;
    }

    // If-Modified-Since header should be greater than LastModified. If so,
    // then return 304.
    // This header is ignored if any If-None-Match header is specified.
    long ifModifiedSince = request.getDateHeader("If-Modified-Since");
    if (ifNoneMatch == null && ifModifiedSince != -1 && ifModifiedSince + 1000 > lastModified) {
        response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
        response.setHeader("ETag", eTag); // Required in 304.
        response.setDateHeader("Expires", expires); // Postpone cache with 1
        // week.
        return;
    }

    // Validate request headers for resume
    // ----------------------------------------------------

    // If-Match header should contain "*" or ETag. If not, then return 412.
    String ifMatch = request.getHeader("If-Match");
    if (ifMatch != null && !matches(ifMatch, eTag)) {
        response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
        return;
    }

    // If-Unmodified-Since header should be greater than LastModified. If
    // not, then return 412.
    long ifUnmodifiedSince = request.getDateHeader("If-Unmodified-Since");
    if (ifUnmodifiedSince != -1 && ifUnmodifiedSince + 1000 <= lastModified) {
        response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
        return;
    }

    // Validate and process range
    // -------------------------------------------------------------

    // Prepare some variables. The full Range represents the complete file.
    Range full = new Range(0, length - 1, length);
    List<Range> ranges = new ArrayList<Range>();

    // Validate and process Range and If-Range headers.
    String range = request.getHeader("Range");
    if (range != null) {

        // Range header should match format "bytes=n-n,n-n,n-n...". If not,
        // then return 416.
        if (!range.matches("^bytes=\\d*-\\d*(,\\d*-\\d*)*$")) {
            response.setHeader("Content-Range", "bytes */" + length); // Required
            // in
            // 416.
            response.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE);
            return;
        }

        // If-Range header should either match ETag or be greater then
        // LastModified. If not,
        // then return full file.
        String ifRange = request.getHeader("If-Range");
        if (ifRange != null && !ifRange.equals(eTag)) {
            try {
                long ifRangeTime = request.getDateHeader("If-Range"); // Throws
                // IAE
                // if
                // invalid.
                if (ifRangeTime != -1 && ifRangeTime + 1000 < lastModified) {
                    ranges.add(full);
                }
            } catch (IllegalArgumentException ignore) {
                ranges.add(full);
            }
        }

        // If any valid If-Range header, then process each part of byte
        // range.
        if (ranges.isEmpty()) {
            for (String part : range.substring(6).split(",")) {
                // Assuming a file with length of 100, the following
                // examples returns bytes at:
                // 50-80 (50 to 80), 40- (40 to length=100), -20
                // (length-20=80 to length=100).
                long start = sublong(part, 0, part.indexOf("-"));
                long end = sublong(part, part.indexOf("-") + 1, part.length());

                if (start == -1) {
                    start = length - end;
                    end = length - 1;
                } else if (end == -1 || end > length - 1) {
                    end = length - 1;
                }

                // Check if Range is syntactically valid. If not, then
                // return 416.
                if (start > end) {
                    response.setHeader("Content-Range", "bytes */" + length); // Required
                    // in
                    // 416.
                    response.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE);
                    return;
                }

                // Add range.
                ranges.add(new Range(start, end, length));
            }
        }
    }

    // Prepare and initialize response
    // --------------------------------------------------------

    // Get content type by file name and set default GZIP support and
    // content disposition.
    String contentType = getServletContext().getMimeType(fileName);
    boolean acceptsGzip = false;
    String disposition = "inline";

    // If content type is unknown, then set the default value.
    // For all content types, see:
    // http://www.w3schools.com/media/media_mimeref.asp
    // To add new content types, add new mime-mapping entry in web.xml.
    if (contentType == null) {
        contentType = "application/octet-stream";
    }

    // If content type is text, then determine whether GZIP content encoding
    // is supported by
    // the browser and expand content type with the one and right character
    // encoding.
    if (contentType.startsWith("text")) {
        String acceptEncoding = request.getHeader("Accept-Encoding");
        acceptsGzip = acceptEncoding != null && accepts(acceptEncoding, "gzip");
        contentType += ";charset=UTF-8";
    }

    // Else, expect for images, determine content disposition. If content
    // type is supported by
    // the browser, then set to inline, else attachment which will pop a
    // 'save as' dialogue.
    else if (!contentType.startsWith("image")) {
        String accept = request.getHeader("Accept");
        disposition = accept != null && accepts(accept, contentType) ? "inline" : "attachment";
    }

    // Initialize response.
    response.reset();
    response.setBufferSize(DEFAULT_BUFFER_SIZE);
    response.setHeader("Content-Disposition", disposition + ";filename=\"" + fileName + "\"");
    response.setHeader("Accept-Ranges", "bytes");
    response.setHeader("ETag", eTag);
    response.setDateHeader("Last-Modified", lastModified);
    response.setDateHeader("Expires", expires);

    // Send requested file (part(s)) to client
    // ------------------------------------------------

    // Prepare streams.
    RandomAccessFile input = null;
    OutputStream output = null;

    try {
        // Open streams.
        input = new RandomAccessFile(file, "r");
        output = response.getOutputStream();

        if (ranges.isEmpty() || ranges.get(0) == full) {

            // Return full file.
            Range r = full;
            response.setContentType(contentType);
            response.setHeader("Content-Range", "bytes " + r.start + "-" + r.end + "/" + r.total);

            if (requestType.equals("GET")) {
                if (acceptsGzip) {
                    // The browser accepts GZIP, so GZIP the content.
                    response.setHeader("Content-Encoding", "gzip");
                    output = new GZIPOutputStream(output, DEFAULT_BUFFER_SIZE);
                } else {
                    // Content length is not directly predictable in case of
                    // GZIP.
                    // So only add it if there is no means of GZIP, else
                    // browser will hang.
                    response.setHeader("Content-Length", String.valueOf(r.length));
                }

                // Copy full range.
                copy(input, output, r.start, r.length);
            }

        } else if (ranges.size() == 1) {

            // Return single part of file.
            Range r = ranges.get(0);
            response.setContentType(contentType);
            response.setHeader("Content-Range", "bytes " + r.start + "-" + r.end + "/" + r.total);
            response.setHeader("Content-Length", String.valueOf(r.length));
            response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); // 206.

            if (requestType.equals("GET")) {
                // Copy single part range.
                copy(input, output, r.start, r.length);
            }

        } else {

            // Return multiple parts of file.
            response.setContentType("multipart/byteranges; boundary=" + MULTIPART_BOUNDARY);
            response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); // 206.

            if (requestType.equals("GET")) {
                // Cast back to ServletOutputStream to get the easy println
                // methods.
                ServletOutputStream sos = (ServletOutputStream) output;

                // Copy multi part range.
                for (Range r : ranges) {
                    // Add multipart boundary and header fields for every
                    // range.
                    sos.println();
                    sos.println("--" + MULTIPART_BOUNDARY);
                    sos.println("Content-Type: " + contentType);
                    sos.println("Content-Range: bytes " + r.start + "-" + r.end + "/" + r.total);

                    // Copy single part range of multi part range.
                    copy(input, output, r.start, r.length);
                }

                // End with multipart boundary.
                sos.println();
                sos.println("--" + MULTIPART_BOUNDARY + "--");
            }
        }
    } finally {
        // Gently close streams.
        close(output);
        close(input);
    }
}

From source file:com.meltmedia.cadmium.servlets.BasicFileServlet.java

public boolean handleConditions(FileRequestContext context) throws IOException {
    // check the conditions
    context.eTag = context.path + "_" + lastUpdated;

    context.ifMatch = context.request.getHeader(IF_MATCH_HEADER);
    if (context.ifMatch != null && !validateStrong(context.ifMatch, context.eTag)) {
        context.response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
        return true;
    }/*from ww  w  .ja v  a2  s . c o m*/

    context.range = context.request.getHeader(RANGE_HEADER);

    try {
        context.inRangeDate = context.request.getDateHeader(IF_RANGE_HEADER);
        if (context.inRangeDate != -1 && context.inRangeDate >= lastUpdated) {
            if (!parseRanges(context)) {
                invalidRanges(context);
                return true;
            }
        }
    } catch (IllegalArgumentException iae) {
        logger.error("Invalid range serving request: " + context.path, iae);
        context.inRangeETag = context.request.getHeader(IF_RANGE_HEADER);
        if (context.inRangeETag != null && validateStrong(context.inRangeETag, context.eTag)) {
            if (!parseRanges(context)) {
                invalidRanges(context);
                return true;
            }
        }
    }

    if (context.inRangeDate == -1 && context.inRangeETag == null) {
        if (!parseRanges(context)) {
            invalidRanges(context);
            return true;
        }
    }

    context.ifNoneMatch = context.request.getHeader(IF_NONE_MATCH_HEADER);
    if (context.ifNoneMatch != null && validateStrong(context.ifNoneMatch, context.eTag)) {
        context.response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
        context.response.setHeader(ETAG_HEADER, context.eTag);
        context.response.setDateHeader(LAST_MODIFIED_HEADER, lastUpdated);
        return true;
    }

    context.ifModifiedSince = context.request.getDateHeader(IF_MODIFIED_SINCE_HEADER);
    if (context.ifModifiedSince != -1 && context.ifModifiedSince >= lastUpdated) {
        context.response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
        context.response.setHeader(ETAG_HEADER, context.eTag);
        context.response.setDateHeader(LAST_MODIFIED_HEADER, lastUpdated);
        return true;
    }

    context.ifUnmodifiedSince = context.request.getDateHeader(IF_UNMODIFIED_SINCE_HEADER);
    if (context.ifUnmodifiedSince != -1 && context.ifUnmodifiedSince < lastUpdated) {
        context.response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
        return true;
    }

    return false;

}

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

/**
 * Check if the if-none-match condition is satisfied.
 *///from  ww w .  j a v a 2s  .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;
}

From source file:de.zib.gndms.kit.monitor.GroovyMoniServlet.java

private static ServletRuntimeException preCondFailed(String s) {
    return new ServletRuntimeException(HttpServletResponse.SC_PRECONDITION_FAILED, s, false);
}

From source file:org.apache.sling.launchpad.webapp.integrationtest.servlets.post.PostServletCopyTest.java

public void testCopyNodeMultipleSourcePartial() throws IOException {
    final String testPath = TEST_BASE_PATH + "/cpmult/" + System.currentTimeMillis();
    final String testRoot = testClient.createNode(HTTP_BASE_URL + testPath, null);

    // create multiple source nodes
    Map<String, String> props = new HashMap<String, String>();
    props.put("text", "Hello");
    testClient.createNode(HTTP_BASE_URL + testPath + "/src1", props);
    testClient.createNode(HTTP_BASE_URL + testPath + "/src3", props);

    // copy the src? nodes
    List<NameValuePair> nvPairs = new ArrayList<NameValuePair>();
    nvPairs.add(new NameValuePair(SlingPostConstants.RP_OPERATION, SlingPostConstants.OPERATION_COPY));
    nvPairs.add(new NameValuePair(SlingPostConstants.RP_DEST, testPath + "/dest/"));
    nvPairs.add(new NameValuePair(SlingPostConstants.RP_APPLY_TO, testPath + "/src1"));
    nvPairs.add(new NameValuePair(SlingPostConstants.RP_APPLY_TO, testPath + "/src2"));
    nvPairs.add(new NameValuePair(SlingPostConstants.RP_APPLY_TO, testPath + "/src3"));
    nvPairs.add(new NameValuePair(SlingPostConstants.RP_APPLY_TO, testPath + "/src4"));
    assertPostStatus(testRoot, HttpServletResponse.SC_PRECONDITION_FAILED, nvPairs,
            "Expecting Copy Failure: dest parent does not exist");

    // create destination parent
    testClient.createNode(HTTP_BASE_URL + testPath + "/dest", props);

    // now dest exists, so we expect success
    assertPostStatus(testRoot, HttpServletResponse.SC_OK, nvPairs, "Expecting Copy Success");

    // assert partial existence of the src?/text properties
    assertHttpStatus(HTTP_BASE_URL + testPath + "/dest/src1/text", HttpServletResponse.SC_OK);
    assertHttpStatus(HTTP_BASE_URL + testPath + "/dest/src2/text", HttpServletResponse.SC_NOT_FOUND);
    assertHttpStatus(HTTP_BASE_URL + testPath + "/dest/src3/text", HttpServletResponse.SC_OK);
    assertHttpStatus(HTTP_BASE_URL + testPath + "/dest/src4/text", HttpServletResponse.SC_NOT_FOUND);

    testClient.delete(testRoot);/*from w w w. ja  v a2 s  . c  om*/
}

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

/**
 * Check if the if-unmodified-since condition is satisfied.
 *///from w w  w .  j a  v a 2 s . c o m
private static boolean checkIfUnmodifiedSince(final HttpServletRequest request,
        final HttpServletResponse response, final MCRContent resource) throws IOException {
    try {
        final long lastModified = resource.lastModified();
        final long headerValue = request.getDateHeader("If-Unmodified-Since");
        if (headerValue != -1) {
            if (lastModified >= headerValue + 1000) {
                // The content has been modified.
                response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
                return false;
            }
        }
    } catch (final IllegalArgumentException illegalArgument) {
        return true;
    }
    return true;
}

From source file:com.github.zhanhb.ckfinder.download.PathPartial.java

/**
 * Check if the if-match condition is satisfied.
 *
 * @param request The servlet request we are processing
 * @param etag ETag of the entity/*from   w w w. j a  va2 s. c o  m*/
 */
private void checkIfMatch(HttpServletRequest request, String etag) {
    String headerValue = request.getHeader(HttpHeaders.IF_MATCH);
    if (headerValue != null && headerValue.indexOf('*') == -1 && !anyMatches(headerValue, etag)) {
        // If none of the given ETags match, 412 Precodition failed is
        // sent back
        throw new UncheckException(HttpServletResponse.SC_PRECONDITION_FAILED);
    }
}