Example usage for javax.servlet.http HttpServletResponse getStatus

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

Introduction

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

Prototype

public int getStatus();

Source Link

Document

Gets the current status code of this response.

Usage

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

/**
 * Serve the specified content, optionally including the data content.
 * This method handles both GET and HEAD requests.
 *//*w ww  . j ava  2 s  .c om*/
public static void serveContent(final MCRContent content, final HttpServletRequest request,
        final HttpServletResponse response, final ServletContext context, final Config config,
        final boolean withContent) throws IOException {

    boolean serveContent = withContent;

    final String path = getRequestPath(request);
    if (LOGGER.isDebugEnabled()) {
        if (serveContent) {
            LOGGER.debug("Serving '" + path + "' headers and data");
        } else {
            LOGGER.debug("Serving '" + path + "' headers only");
        }
    }

    if (response.isCommitted()) {
        //getContent has access to response
        return;
    }

    final boolean isError = response.getStatus() >= HttpServletResponse.SC_BAD_REQUEST;

    if (content == null && !isError) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND, request.getRequestURI());
        return;
    }

    //Check if all conditional header validate
    if (!isError && !checkIfHeaders(request, response, content)) {
        return;
    }

    // Find content type.
    String contentType = content.getMimeType();
    final String filename = getFileName(request, content);
    if (contentType == null) {
        contentType = context.getMimeType(filename);
        content.setMimeType(contentType);
    }
    String enc = content.getEncoding();
    if (enc != null) {
        contentType = String.format(Locale.ROOT, "%s; charset=%s", contentType, enc);
    }

    String eTag = null;
    ArrayList<Range> ranges = null;
    if (!isError) {
        eTag = content.getETag();
        if (config.useAcceptRanges) {
            response.setHeader("Accept-Ranges", "bytes");
        }

        ranges = parseRange(request, response, content);

        response.setHeader("ETag", eTag);

        long lastModified = content.lastModified();
        if (lastModified >= 0) {
            response.setDateHeader("Last-Modified", lastModified);
        }
        if (serveContent) {
            String dispositionType = request.getParameter("dl") == null ? "inline" : "attachment";
            response.setHeader("Content-Disposition", dispositionType + ";filename=\"" + filename + "\"");
        }
    }

    final long contentLength = content.length();
    //No Content to serve?
    if (contentLength == 0) {
        serveContent = false;
    }

    if (content.isUsingSession()) {
        response.addHeader("Cache-Control", "private, max-age=0, must-revalidate");
        response.addHeader("Vary", "*");
    }

    try (ServletOutputStream out = serveContent ? response.getOutputStream() : null) {
        if (serveContent) {
            try {
                response.setBufferSize(config.outputBufferSize);
            } catch (final IllegalStateException e) {
                //does not matter if we fail
            }
        }
        if (response instanceof ServletResponseWrapper) {
            if (request.getHeader("Range") != null) {
                LOGGER.warn("Response is wrapped by ServletResponseWrapper, no 'Range' requests supported.");
            }
            ranges = FULL;
        }

        if (isError || (ranges == null || ranges.isEmpty()) && request.getHeader("Range") == null
                || ranges == FULL) {
            //No ranges
            if (contentType != null) {
                if (LOGGER.isDebugEnabled()) {
                    LOGGER.debug("contentType='" + contentType + "'");
                }
                response.setContentType(contentType);
            }
            if (contentLength >= 0) {
                if (LOGGER.isDebugEnabled()) {
                    LOGGER.debug("contentLength=" + contentLength);
                }
                setContentLengthLong(response, contentLength);
            }

            if (serveContent) {
                copy(content, out, config.inputBufferSize, config.outputBufferSize);
            }

        } else {

            if (ranges == null || ranges.isEmpty()) {
                return;
            }

            // Partial content response.

            response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);

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

                final Range range = ranges.get(0);
                response.addHeader("Content-Range",
                        "bytes " + range.start + "-" + range.end + "/" + range.length);
                final long length = range.end - range.start + 1;
                setContentLengthLong(response, length);

                if (contentType != null) {
                    if (LOGGER.isDebugEnabled()) {
                        LOGGER.debug("contentType='" + contentType + "'");
                    }
                    response.setContentType(contentType);
                }

                if (serveContent) {
                    copy(content, out, range, config.inputBufferSize, config.outputBufferSize);
                }

            } else {

                response.setContentType("multipart/byteranges; boundary=" + MIME_BOUNDARY);

                if (serveContent) {
                    copy(content, out, ranges.iterator(), contentType, config.inputBufferSize,
                            config.outputBufferSize);
                }
            }
        }
    }
}

From source file:com.github.wnameless.spring.papertrail.PaperTrailService.java

@Transactional
@SuppressWarnings({ "unchecked", "deprecation" })
public void audit(HttpServletRequest request, HttpServletResponse response) {
    if (!targetMethods.contains(HttpMethod.valueOf(request.getMethod())))
        return;/*from w ww.ja  va2s .c  om*/

    final PaperTrail paperTrail = newPaperTrail();
    paperTrail.setUserId(userIdStrategy == null ? getUserTypedId(request) : userIdStrategy.getUserId(request));
    paperTrail.setRemoteAddr(request.getRemoteAddr());
    paperTrail.setHttpMethod(HttpMethod.valueOf(request.getMethod()));
    paperTrail.setRequestUri(request.getRequestURI());
    paperTrail.setHttpStatus(response.getStatus());

    // Before callbacks
    if (beforeCallback != null) {
        beforeCallback.beforePaperTrail(paperTrail, request, response);
    }

    // Around callback
    if (aroundCallback != null) {
        aroundCallback.aroundPaperTrail(paperTrailRepo, paperTrail, request, response);
    } else {
        paperTrailRepo.save(paperTrail);
    }

    // After callbacks
    if (afterCallback != null) {
        afterCallback.afterPaperTrail(paperTrail, request, response);
    }

    // Legacy after callbacks
    if (!callbacks.isEmpty()) {
        for (@SuppressWarnings("rawtypes")
        PaperTrailCallback callback : callbacks.values()) {
            callback.doWithPaperTrail(paperTrail, request, response);
        }
    }
}

From source file:org.opentestsystem.shared.docs.RequestLoggingInterceptor.java

@Override
public void afterCompletion(final HttpServletRequest request, final HttpServletResponse response,
        final Object handler, final Exception ex) throws Exception { // NOPMD
    FileOutputStream fileOut = null;
    try {/*  w w  w.java  2s.c  o m*/
        LOGGER.debug(" ");
        LOGGER.debug(" ");

        LOGGER.debug("Request ");

        int rank = getRankOfApiDoc();
        // if rank is -1 skip it: that's the way to hide a api doc. Also exclude negative security testing
        if (rank >= ZERO && response.getStatus() != HttpStatus.SC_UNAUTHORIZED) {
            // block pmd concurrent hashmap warning
            ApiExample example = new ApiExample();
            example.setApiDocRank(rank);
            example.setRequestMethod(HttpMethod.valueOf(request.getMethod()));
            example.setRequestContentType(request.getContentType());
            example.setRequestUri(request.getRequestURI());
            String reqQueryString = request.getQueryString();
            //grab the parameters off the request instead
            if (StringUtils.isBlank(reqQueryString)) {
                if (request.getParameterMap() != null) {
                    List<String> params = new ArrayList<String>();
                    for (Entry<String, String[]> entry : request.getParameterMap().entrySet()) {
                        String temp = entry.getKey() + "=";
                        if (entry.getValue() != null) {
                            temp += Joiner.on(",").join(entry.getValue());
                        }
                        params.add(temp);
                    }
                    reqQueryString = Joiner.on("&").join(params.toArray());
                }
            }
            example.setRequestQueryString(reqQueryString);

            LOGGER.debug(example.toString());

            InputStream instream = request.getInputStream();
            String requestData = "";
            if (instream != null) {
                StringWriter writer = new StringWriter();
                IOUtils.copy(instream, writer, "UTF-8");
                requestData = writer.toString();
            }
            example.setRequestData(requestData);
            LOGGER.debug("request data :" + example.getRequestData());
            LOGGER.debug(" ");

            LOGGER.debug("Response  ");
            MockHttpServletResponse res = (MockHttpServletResponse) response;
            example.setResponseContent(res.getContentAsString());
            example.setResponseCode(res.getStatus());

            LOGGER.debug("Server Response:" + example.getResponseContent());
            LOGGER.debug(" ");
            LOGGER.debug(" ");

            if (API_EXAMPLE_FILE != null) {
                fileOut = new FileOutputStream(API_EXAMPLE_FILE, true);
                ObjectMapper mapper = new ObjectMapper();
                byte[] bytes = mapper.writeValueAsBytes(example);
                fileOut.write(bytes);
                String str = ",";
                fileOut.write(str.getBytes());
                fileOut.close();
            }
        }
    } finally {
        if (fileOut != null) {
            fileOut.close();
        }
    }
}

From source file:com.iflytek.edu.cloud.frame.support.ServiceRequestLogging.java

/**
 * @param request// ww  w. ja va2s.com
 * @param response
 */
public void recoredLog(HttpServletRequest request, HttpServletResponse response) {
    String clientIp = ServiceUtil.getRemoteAddr(request);
    String locale = ((Locale) request.getAttribute(Constants.SYS_PARAM_KEY_LOCALE)).getDisplayName();
    String format = (String) request.getAttribute(Constants.SYS_PARAM_KEY_FORMAT);
    String appkey = (String) request.getParameter(Constants.SYS_PARAM_KEY_APPKEY);
    String httpMethod = request.getMethod();
    String serviceMethod = request.getParameter(Constants.SYS_PARAM_KEY_METHOD);
    String serviceVersion = request.getParameter(Constants.SYS_PARAM_KEY_VERSION);
    int responseStatus = response.getStatus();
    Long requestTimeMillis = (Long) request.getAttribute(ServiceMetricsFilter.SERVICE_EXEC_TIME);

    String mainErrorCode = (String) request.getAttribute(Constants.MAIN_ERROR_CODE);

    RestContext context = RestContextHolder.getContext();
    if (StringUtils.hasText(mainErrorCode)) {
        LOGGER.warn("service request information : mainErrorCode={}, clientIp={}, httpMethod={}, locale={},"
                + " appkey={}, serviceMethod={}, serviceVersion={}, format={}, responseStatus={}, requestTimeMillis={},"
                + " callCycoreCount={}, callCycoreTime={}", mainErrorCode, clientIp, httpMethod, locale, appkey,
                serviceMethod, serviceVersion, format, responseStatus, requestTimeMillis,
                context.getCallCycoreCount(), context.getCallCycoreTime());
    } else {
        LOGGER.info("service request information : clientIp={}, httpMethod={}, locale={},"
                + " appkey={}, serviceMethod={}, serviceVersion={}, format={}, responseStatus={}, requestTimeMillis={}"
                + " callCycoreCount={}, callCycoreTime={}", clientIp, httpMethod, locale, appkey, serviceMethod,
                serviceVersion, format, responseStatus, requestTimeMillis, context.getCallCycoreCount(),
                context.getCallCycoreTime());
    }
}

From source file:com.ibm.jaggr.core.impl.AbstractAggregatorImplTest.java

@Test
public void testProcessResourceRequest_invalidAccess() throws Exception {
    final MutableObject<URI> newResource = new MutableObject<URI>();
    AbstractAggregatorImpl testAggregator = new TestAggregatorImpl() {
        @Override//w  w w. j a va 2s  .c  om
        public IResource newResource(URI uri) {
            newResource.setValue(uri);
            return new NotFoundResource(uri);
        }
    };
    Map<String, String> responseParams = new HashMap<String, String>();
    HttpServletRequest req = TestUtils.createMockRequest(testAggregator);
    HttpServletResponse resp = TestUtils.createMockResponse(responseParams);
    EasyMock.replay(req, resp);

    URI uri = new URI("/folder/");
    testAggregator.processResourceRequest(req, resp, uri, "sub/../../file.res");
    Assert.assertEquals(HttpServletResponse.SC_BAD_REQUEST, resp.getStatus());

    testAggregator.processResourceRequest(req, resp, uri, "/file.res");
    Assert.assertEquals(HttpServletResponse.SC_BAD_REQUEST, resp.getStatus());

    uri = new URI("/folder");
    testAggregator.processResourceRequest(req, resp, uri, "/folder.js");
    Assert.assertEquals(HttpServletResponse.SC_BAD_REQUEST, resp.getStatus());

    newResource.setValue(null);
    testAggregator.processResourceRequest(req, resp, uri, "./file.js");
    Assert.assertEquals(HttpServletResponse.SC_NOT_FOUND, resp.getStatus());
    Assert.assertEquals(new URI("/folder/file.js"), newResource.getValue());

    newResource.setValue(null);
    testAggregator.processResourceRequest(req, resp, uri, "file.js");
    Assert.assertEquals(HttpServletResponse.SC_NOT_FOUND, resp.getStatus());
    Assert.assertEquals(new URI("/folder/file.js"), newResource.getValue());

    uri = new URI("/");
    newResource.setValue(null);
    testAggregator.processResourceRequest(req, resp, uri, "/file.js");
    Assert.assertEquals(HttpServletResponse.SC_NOT_FOUND, resp.getStatus());
    Assert.assertEquals(new URI("/file.js"), newResource.getValue());

    newResource.setValue(null);
    testAggregator.processResourceRequest(req, resp, uri, "./file.js");
    Assert.assertEquals(HttpServletResponse.SC_NOT_FOUND, resp.getStatus());
    Assert.assertEquals(new URI("/file.js"), newResource.getValue());

    testAggregator.processResourceRequest(req, resp, uri, "../file.js");
    Assert.assertEquals(HttpServletResponse.SC_BAD_REQUEST, resp.getStatus());
}

From source file:com.vmware.photon.controller.api.common.filters.LoggingFilter.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {

    if (request instanceof HttpServletRequest) {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        String requestId = requestIdProvider.get().toString();

        LoggingUtils.setRequestId(requestId);
        logger.debug("Request: {} {}", httpRequest.getMethod(), httpRequest.getPathInfo());

        StopWatch stopwatch = new StopWatch();
        stopwatch.start();/*from   w w  w. ja  v a  2 s  .  c om*/
        try {
            chain.doFilter(request, response);
        } finally {
            stopwatch.stop();
            String msg = String.format("Response: %s [%s] in %sms", httpRequest.getPathInfo(),
                    httpResponse.getStatus(), stopwatch.getTime());
            if (httpResponse.getStatus() == HttpServletResponse.SC_OK) {
                logger.debug(msg);
            } else {
                logger.info(msg);
            }

            LoggingUtils.clearRequestId();
        }
    } else {
        chain.doFilter(request, response);
    }
}

From source file:com.ibm.ws.lars.rest.ErrorHandler.java

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

    response.setStatus(500);/*  w  w  w  .j  av a  2 s.c om*/
    response.setContentType(MediaType.APPLICATION_JSON);
    PrintWriter printWriter = response.getWriter();
    JsonGenerator frontPageJsonGenerator = new JsonFactory().createGenerator(printWriter);
    frontPageJsonGenerator.setPrettyPrinter(new DefaultPrettyPrinter());

    frontPageJsonGenerator.writeStartObject();
    frontPageJsonGenerator.writeStringField("message",
            "Internal server error, please contact the server administrator");
    frontPageJsonGenerator.writeNumberField("statusCode", response.getStatus());
    frontPageJsonGenerator.writeEndObject();

    frontPageJsonGenerator.flush();
    frontPageJsonGenerator.close();
}

From source file:net.community.chest.gitcloud.facade.backend.git.GitBackendServlet.java

@Override
protected void service(HttpServletRequest req, HttpServletResponse rsp) throws ServletException, IOException {
    if (logger.isDebugEnabled()) {
        logger.debug(/* ww  w  . ja  v a2s  . c  o m*/
                "service(" + req.getMethod() + ")[" + req.getRequestURI() + "][" + req.getQueryString() + "]");
    }

    if (logger.isTraceEnabled()) {
        logHeaders(req, ServletUtils.getRequestHeaders(req), "REQ");
    }

    super.service(req, rsp);

    if (logger.isDebugEnabled()) {
        logger.debug("service(" + req.getMethod() + ")[" + req.getRequestURI() + "][" + req.getQueryString()
                + "]" + " Content-Type: " + rsp.getContentType() + ", status=" + rsp.getStatus());
    }

    if (logger.isTraceEnabled()) {
        logHeaders(req, ServletUtils.getResponseHeaders(rsp), "RSP");
    }
}

From source file:net.eusashead.hateoas.conditional.interceptor.ConditionalResponseInterceptorTest.java

@Test
public void testPreHandlePutPreconditionRequired() throws Exception {

    // Request value
    String path = "/path/to/resource/";

    // Set the request/response
    HttpServletRequest request = put(path).build();
    HttpServletResponse response = response().build();

    // Execute// ww  w. j  av a 2s . co  m
    boolean handle = interceptor.preHandle(request, response, new Object());

    // Validate
    Assert.assertFalse(handle);
    Assert.assertEquals(428, response.getStatus());

}

From source file:net.eusashead.hateoas.conditional.interceptor.ConditionalResponseInterceptorTest.java

@Test
public void testPreHandleDeletePreconditionRequired() throws Exception {

    // Request value
    String path = "/path/to/resource/";

    // Set the request/response
    HttpServletRequest request = delete(path).build();
    HttpServletResponse response = response().build();

    // Execute/*  w  w w  .jav a  2s . c  o  m*/
    boolean handle = interceptor.preHandle(request, response, new Object());

    // Validate
    Assert.assertFalse(handle);
    Assert.assertEquals(428, response.getStatus());

}