Example usage for javax.servlet.http HttpServletResponse setStatus

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

Introduction

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

Prototype

public void setStatus(int sc);

Source Link

Document

Sets the status code for this response.

Usage

From source file:io.druid.server.AsyncQueryForwardingServlet.java

private static void handleException(HttpServletResponse response, ObjectMapper objectMapper,
        Exception exception) throws IOException {
    if (!response.isCommitted()) {
        final String errorMessage = exception.getMessage() == null ? "null exception" : exception.getMessage();

        response.resetBuffer();//from  w ww  . j  a  v  a2s. c  o  m
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        objectMapper.writeValue(response.getOutputStream(), ImmutableMap.of("error", errorMessage));
    }
    response.flushBuffer();
}

From source file:com.iorga.iraj.security.AbstractSecurityFilter.java

protected static void sendError(final int sc, final String message, final HttpServletResponse resp,
        final String debugMessage, final Throwable debugThrowableCause) throws IOException {
    if (log.isDebugEnabled()) {
        final String logMessage = "[" + sc + ":" + message + "]"
                + (debugMessage != null ? " " + debugMessage : "");
        if (debugThrowableCause != null) {
            log.debug(logMessage, debugThrowableCause);
        } else {/*  ww w. j a  va 2  s.  c  om*/
            log.debug(logMessage);
        }
    }

    resp.setStatus(sc);
    new MessagesBuilder().appendError(message).build().writeToOutputStream(resp.getOutputStream());
}

From source file:com.github.thorqin.webapi.oauth2.OAuthServer.java

public static void responseGetResourceFailed(HttpServletResponse response, OAuthError error,
        String errorDescription, String errorUri) {
    String headContent = "Bearer ";
    headContent += "error=\"" + error.toString().toLowerCase() + "\"";
    if (errorDescription != null)
        headContent += "error_description=\"" + errorDescription + "\"";
    if (errorUri != null)
        headContent += "error_uri=\"" + errorUri + "\"";
    response.setHeader("WWW-Authenticate", headContent);

    switch (error) {
    case INVALID_REQUEST:
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        break;//from  w ww . j a  v  a2s. c  o  m
    case UNAUTHORIZED_CLIENT:
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        break;
    case ACCESS_DENIED:
    case UNSUPPORTED_RESPONSE_TYPE:
    case INVALID_SCOPE:
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        break;
    case SERVER_ERROR:
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        break;
    case TEMPORARILY_UNAVAILABLE:
        response.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
        break;
    }
}

From source file:httpUtils.HttpUtils.java

/**
 * Parse the request headers, build the response, stream back file
 * @param request//from  w w w .jav  a 2  s  .  c  o m
 * @param response
 * @param dataStream
 * @param fileLength
 * @param fileName
 * @param fileLastModified
 * @param contentType
 * @return
 */
private static HttpServletResponse getFileAsStream(HttpServletRequest request, HttpServletResponse response,
        InputStream dataStream, long fileLength, String fileName, long fileLastModified, String contentType) {
    if (dataStream == null) {
        response.setStatus(HttpServletResponse.SC_NOT_FOUND);
        return response;
    }

    if (StringUtils.isEmpty(fileName) || fileLastModified == 0L) {
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return response;
    }

    String ifNoneMatch = request.getHeader("If-None-Match");
    if (ifNoneMatch != null && matches(ifNoneMatch, fileName)) {
        response.setHeader("ETag", fileName);
        response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
        return response;
    }

    long ifModifiedSince = request.getDateHeader("If-Modified-Since");
    if (ifNoneMatch == null && ifModifiedSince != -1 && ifModifiedSince + 1000 > fileLastModified) {
        response.setHeader("ETag", fileName);
        response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
        return response;
    }

    String ifMatch = request.getHeader("If-Match");
    if (ifMatch != null && !matches(ifMatch, fileName)) {
        response.setStatus(HttpServletResponse.SC_PRECONDITION_FAILED);
        return response;
    }

    long ifUnmodifiedSince = request.getDateHeader("If-Unmodified-Since");
    if (ifUnmodifiedSince != -1 && ifUnmodifiedSince + 1000 <= fileLastModified) {
        response.setStatus(HttpServletResponse.SC_PRECONDITION_FAILED);
        return response;
    }

    Range full = new Range(0, fileLength - 1, fileLength);
    List<Range> ranges = new ArrayList<Range>();
    String range = request.getHeader("Range");
    if (range != null) {
        if (!range.matches("^bytes=\\d*-\\d*(,\\d*-\\d*)*$")) {
            response.setHeader("Content-Range", "bytes */" + fileLength);
            response.setStatus(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE);
            return response;
        }

        String ifRange = request.getHeader("If-Range");
        if (ifRange != null && !ifRange.equals(fileName)) {
            try {
                long ifRangeTime = request.getDateHeader("If-Range");
                if (ifRangeTime != -1) {
                    ranges.add(full);
                }
            } catch (IllegalArgumentException ignore) {
                ranges.add(full);
            }
        }

        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 = fileLength - end;
                    end = fileLength - 1;
                } else if (end == -1 || end > fileLength - 1) {
                    end = fileLength - 1;
                }

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

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

    // Get content type by file name and set content disposition.
    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";
    } else if (!contentType.startsWith("image")) {
        // 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.
        String accept = request.getHeader("Accept");
        disposition = accept != null && accepts(accept, contentType) ? "inline" : "attachment";
    }

    // Initialize response.
    response.reset();
    response.setBufferSize(HttpUtils.DEFAULT_BUFFER_SIZE);
    response.setHeader("Content-Disposition", disposition + ";filename=\"" + fileName + "\"");
    response.setHeader("Accept-Ranges", "bytes");
    response.setHeader("ETag", fileName);
    response.setDateHeader("Last-Modified", fileLastModified);
    response.setDateHeader("Expires", System.currentTimeMillis() + HttpUtils.DEFAULT_EXPIRE_TIME);

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

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

    try {
        // Open streams.
        input = new BufferedInputStream(dataStream);
        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);
            response.setHeader("Content-Length", String.valueOf(r.length));
            copy(input, output, fileLength, 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.

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

        } else {

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

            // 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("--" + HttpUtils.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, fileLength, r.start, r.length);
            }

            // End with multipart boundary.
            sos.println();
            sos.println("--" + HttpUtils.MULTIPART_BOUNDARY + "--");
        }
    } catch (Exception e) {
        log.error("get file as stream failed", e);
    } finally {
        // Gently close streams.
        close(output);
        close(input);
        close(dataStream);
    }
    return response;
}

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

/**
 * If any validation errors from a form are present, set them up to be rendered.
 * <p>/* w  w w  . ja v a2s. c  om*/
 * If this method returns {@code true}, it generally means that the calling controller should halt and render a page
 * displaying the validation messages.
 *
 * @param response             the response
 * @param model                the model
 * @param validationErrorNames attribute names for present validation errors
 * @return {@code true} if a validation error is present
 */
protected static boolean applyValidation(HttpServletResponse response, Model model,
        Collection<String> validationErrorNames) {
    if (validationErrorNames.isEmpty())
        return false;

    /*
     * Presently, it is assumed that all validation error messages in FreeMarker use a simple presence/absence check
     * with the '??' operator. The value 'true' is just a placeholder. If any validation error messages require more
     * specific values, they must be added to the model separately. Refactor this method if that happens too often.
     */
    validationErrorNames.forEach(error -> model.addAttribute(error, true));

    response.setStatus(HttpStatus.BAD_REQUEST.value());
    return true;
}

From source file:org.openmrs.module.webservices.rest.web.RestUtil.java

/**
 * Sets the HTTP status on the response to no content, and returns an empty value, suitable for
 * returning from a @ResponseBody annotated Spring controller method.
 * //from   w w  w  . j a  v  a 2s  . co  m
 * @param response
 * @return
 */
public static Object noContent(HttpServletResponse response) {
    response.setStatus(HttpServletResponse.SC_NO_CONTENT);
    return "";
}

From source file:org.openmrs.module.webservices.rest.web.RestUtil.java

/**
 * Sets the HTTP status for CREATED and (if 'created' has a uri) the Location header attribute
 * //from  w w  w  .  j a  v  a2s .c  o m
 * @param response
 * @param created
 * @return the object passed in
 */
public static Object created(HttpServletResponse response, Object created) {
    response.setStatus(HttpServletResponse.SC_CREATED);
    try {
        String uri = (String) PropertyUtils.getProperty(created, "uri");
        response.addHeader("Location", uri);
    } catch (Exception ex) {
    }
    return created;
}

From source file:org.openmrs.module.webservices.rest.web.RestUtil.java

/**
 * Sets the HTTP status for UPDATED and (if 'updated' has a uri) the Location header attribute
 * //from   www  .  j av a  2 s  . c  om
 * @param response
 * @param updated
 * @return the object passed in
 */
public static Object updated(HttpServletResponse response, Object updated) {
    response.setStatus(HttpServletResponse.SC_OK);
    try {
        String uri = (String) PropertyUtils.getProperty(updated, "uri");
        response.addHeader("Location", uri);
    } catch (Exception ex) {
    }
    return updated;
}

From source file:org.ngrinder.script.controller.DavSvnController.java

/**
 * Handler for error./*from   www.  j  av  a  2s  .  c om*/
 * 
 * @param error
 *            error occurred
 * @param servletResponse
 *            response
 * @throws IOException
 *             occurs when IO has problem
 */
public static void handleError(DAVException error, HttpServletResponse servletResponse) throws IOException {
    SVNDebugLog.getDefaultLog().logFine(SVNLogType.NETWORK, error);
    DAVResponse response = error.getResponse();
    if (response == null) {
        DAVException stackErr = error;
        while (stackErr != null && stackErr.getTagName() == null) {
            stackErr = stackErr.getPreviousException();
        }

        if (stackErr != null && stackErr.getTagName() != null) {
            servletResponse.setContentType(XML_CONTENT_TYPE);
            servletResponse.setStatus(stackErr.getResponseCode());

            StringBuffer errorMessageBuffer = new StringBuffer();
            SVNXMLUtil.addXMLHeader(errorMessageBuffer);
            errorMessageBuffer.append('\n');
            errorMessageBuffer.append("<D:error xmlns:D=\"DAV:\"");

            if (stackErr.getMessage() != null) {
                errorMessageBuffer.append(" xmlns:m=\"http://apache.org/dav/xmlns\"");
            }

            if (stackErr.getNameSpace() != null) {
                errorMessageBuffer.append(" xmlns:C=\"");
                errorMessageBuffer.append(stackErr.getNameSpace());
                errorMessageBuffer.append("\">\n<C:");
                errorMessageBuffer.append(stackErr.getTagName());
                errorMessageBuffer.append("/>");
            } else {
                errorMessageBuffer.append(">\n<D:");
                errorMessageBuffer.append(stackErr.getTagName());
                errorMessageBuffer.append("/>");
            }

            if (stackErr.getMessage() != null) {
                errorMessageBuffer.append("<m:human-readable errcode=\"");
                errorMessageBuffer.append(stackErr.getErrorID());
                errorMessageBuffer.append("\">\n");
                errorMessageBuffer.append(SVNEncodingUtil.xmlEncodeCDATA(stackErr.getMessage()));
                errorMessageBuffer.append('\n');
                errorMessageBuffer.append("</m:human-readable>\n");
            }
            errorMessageBuffer.append("</D:error>\n");
            servletResponse.getWriter().print(errorMessageBuffer.toString());
            SVNDebugLog.getDefaultLog().logFine(SVNLogType.NETWORK, errorMessageBuffer.toString());
            return;
        }
        servletResponse.setStatus(error.getResponseCode());
        return;
    }

    DAVXMLUtil.sendMultiStatus(response, servletResponse, error.getResponseCode(), null);
}

From source file:com.xpn.xwiki.user.impl.xwiki.MyBasicAuthenticator.java

public static void showLogin(HttpServletRequest request, HttpServletResponse response, String realmName)
        throws IOException {
    // save this request
    SecurityFilter.saveRequestInformation(request);

    // determine the number of login attempts
    int loginAttempts;
    if (request.getSession().getAttribute(LOGIN_ATTEMPTS) != null) {
        loginAttempts = ((Integer) request.getSession().getAttribute(LOGIN_ATTEMPTS)).intValue();
        loginAttempts += 1;/*from   w w w .java  2  s. c o m*/
    } else {
        loginAttempts = 1;
    }
    request.getSession().setAttribute(LOGIN_ATTEMPTS, new Integer(loginAttempts));

    if (loginAttempts <= MAX_ATTEMPTS) {
        response.setHeader("WWW-Authenticate", "BASIC realm=\"" + realmName + "\"");
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
    } else {
        request.getSession().removeAttribute(LOGIN_ATTEMPTS);
        response.sendError(HttpServletResponse.SC_UNAUTHORIZED, LOGIN_FAILED_MESSAGE);
    }
}