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:de.drv.dsrv.spoc.web.webservice.spring.SpocMessageDispatcherServlet.java

@Override
protected void doService(final HttpServletRequest request, final HttpServletResponse response)
        throws Exception {
    try {//  w w  w.  j ava  2  s  .  c  o m
        if (LOG.isDebugEnabled()) {
            LOG.debug("Request eingegangen, Spring-WS-Verarbeitung wird aufgerufen.");
        }
        super.doService(request, response);
    } catch (final SaajSoapEnvelopeException ex) {
        if (LOG.isInfoEnabled()) {
            LOG.info("Behandlung von Exception - exTRa-Error wird generiert: ", ex);
        }
        // Request enthaelt gueltiges XML, ist aber keine SOAP-Nachricht
        createExtraErrorAndWriteResponse(response, getWebApplicationContext()
                .getMessage(Messages.ERROR_REQUEST_NO_SOAP, null, request.getLocale()));
    }

    // Falls das XML im Request ungueltig ist, "verschluckt" der
    // WebServiceMessageReceiverHandlerAdapter
    // die Exception und setzt den HTTP Status auf 400.
    // Ganz sicher koennen wir hier aber nicht sein, ob das tatsaechlich die
    // Ursache ist.
    if (response.getStatus() == HttpServletResponse.SC_BAD_REQUEST) {
        try {
            if (LOG.isInfoEnabled()) {
                LOG.info("HTTP-Status 400 - exTRa-Error wird generiert.");
            }
            createExtraErrorAndWriteResponse(response, getWebApplicationContext()
                    .getMessage(Messages.ERROR_REQUEST_NO_XML, null, request.getLocale()));
        } catch (final Exception ignored) {
            // Evtl. kann nicht mehr in die Response geschrieben werden,
            // weil das vorher schon geschehen ist.
            LOG.warn("Exception beim Versuch, einen eigenen Extra-Error in die HttpResponse zu schreiben.",
                    ignored);
        }
    }
}

From source file:com.usefullc.platform.common.log.LogHandlerInterceptor.java

@Override
public void afterHandler(ActionHandler actionHandler) {
    if (!this.monitor) { // ?
        return;//  w w  w.  j a  va 2 s .  com
    }
    Long userId = OnlineUserManager.getUserId();
    if (userId == null) { // 
        return;
    }
    // logInfo
    LogInfoDto domain = threadLocal.get();
    if (domain == null) {
        return;
    }
    HttpServletResponse response = actionHandler.getResponse();

    domain.setActionState(actionHandler.getState());

    // ?
    if (!actionHandler.getState()) {
        domain.setErrMsg(actionHandler.getErrMsg());
    }

    // request headers
    JSONObject jsonObj = new JSONObject();

    Collection<String> headerNames = response.getHeaderNames(); //
    for (String headerName : headerNames) {
        Collection<String> headerValues = response.getHeaders(headerName);
        StringBuilder sb = new StringBuilder();
        for (String headerValue : headerValues) {
            sb.append(headerValue);
            sb.append(",");
        }
        if (sb.length() > 0) {
            sb.substring(0, sb.length() - 1);
        }
        jsonObj.put(headerName, sb.toString());
    }
    domain.setResponseHeader(jsonObj.toString());

    domain.setStatus(String.valueOf(response.getStatus()));

    // ??
    logInfoRemoteService.insertLogInfo(domain);

    // ?
    threadLocal.set(null);
}

From source file:org.xlcloud.xsa.meter.ApiCallMeteringFilter.java

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

    LOG.debug("Processing request");
    HttpServletRequest request = (HttpServletRequest) req;
    HttpServletResponse response = (HttpServletResponse) res;
    RequestWrapper requestWrapper = new RequestWrapper(request);
    ResponseWrapper responseWrapper = new ResponseWrapper(response);
    // pre//from  ww w .  ja  v a2s  .com
    String resourceUrl = request.getContextPath();
    String requestBody = requestWrapper.getRequestBody();
    Map<String, Object> metadataMap = new HashMap<String, Object>();
    metadataMap.put("AccountId", getAccountId());

    Date timeStart = new Date();
    chain.doFilter(requestWrapper, responseWrapper);
    Date timeEnd = new Date();
    // post
    String responseBody = responseWrapper.getContent();

    metadataMap.put("HTTP Method", request.getMethod());
    metadataMap.put("HTTP Request Params", request.getParameterMap());
    metadataMap.put("HTTP Request Body", requestBody);
    metadataMap.put("HTTP Response Status Code", Integer.toString(response.getStatus()));
    metadataMap.put("HTTP Response Headers", getHeadersMap(response));
    metadataMap.put("HTTP Response Body", responseBody);
    metadataMap.put("Duration", Long.toString(timeEnd.getTime() - timeStart.getTime()));
    String resourceMetadata = map2json(metadataMap);
    Meter meter = MeterFactory.getXlcApiCall(Source.XSA, getStackId(), getUserIdFromAccessToken("accessToken"),
            resourceUrl, resourceMetadata);
    LOG.debug("Registering meter");
    meterCollector.registerMeter(meter);
}

From source file:org.wso2.carbon.device.mgt.iot.services.sensebot.SenseBotControllerService.java

@Path("/pushsensordata")
@POST/*from  w  ww.  j  a v  a  2  s  .com*/
@Consumes(MediaType.APPLICATION_JSON)
public String pushAlarmData(final DeviceJSON dataMsg, @Context HttpServletResponse response) {
    String result = null;

    String sensorValues = dataMsg.value; //TEMP-PIR-SONAR-LDR
    log.info("Recieved Sensor Data Values: " + sensorValues);

    String sensors[] = sensorValues.split(":");

    if (sensors.length == 4) {
        String temperature = sensors[0];
        String motion = sensors[1];
        String sonar = sensors[2];
        String light = sensors[3];

        if (sonar.equals("-1")) {
            sonar = "No Object";
        }

        sensorValues = "Temperature:" + temperature + "C\t\tMotion:" + motion + "\tSonar:" + sonar + "\tLight:"
                + light;
        log.info(sensorValues);

        result = DeviceControllerService.pushData(dataMsg.owner, "SenseBot", dataMsg.deviceId,
                System.currentTimeMillis(), "DeviceData", temperature, "TEMP", response);

        if (response.getStatus() != HttpStatus.SC_ACCEPTED) {
            return result;
        }

        result = DeviceControllerService.pushData(dataMsg.owner, "SenseBot", dataMsg.deviceId,
                System.currentTimeMillis(), "DeviceData", motion, "MOTION", response);

        if (response.getStatus() != HttpStatus.SC_ACCEPTED) {
            return result;
        }

        if (!sonar.equals("No Object")) {
            result = DeviceControllerService.pushData(dataMsg.owner, "SenseBot", dataMsg.deviceId,
                    System.currentTimeMillis(), "DeviceData", sonar, "SONAR", response);

            if (response.getStatus() != HttpStatus.SC_ACCEPTED) {
                return result;
            }
        }

        result = DeviceControllerService.pushData(dataMsg.owner, "SenseBot", dataMsg.deviceId,
                System.currentTimeMillis(), "DeviceData", light, "LIGHT", response);

    } else {
        response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR);
        return "Invalid data stream format. Needs to be \"TEMP:PIR:SONAR:LDR\"";
    }

    return result;
}

From source file:org.cloudfoundry.identity.uaa.security.web.CorsFilter.java

@Override
protected void doFilterInternal(final HttpServletRequest request, final HttpServletResponse response,
        final FilterChain filterChain) throws ServletException, IOException {

    if (!isCrossOriginRequest(request)) {
        //if the Origin header is not present.
        //Process as usual
        filterChain.doFilter(request, response);
        return;//from ww  w .java2 s .  c om
    }

    if (logger.isDebugEnabled()) {
        logger.debug("CORS Processing request: " + getRequestInfo(request));
    }
    if (isXhrRequest(request)) {
        handleRequest(request, response, filterChain, getXhrConfiguration());
    } else {
        handleRequest(request, response, filterChain, getDefaultConfiguration());
    }
    if (logger.isDebugEnabled()) {
        logger.debug("CORS processing completed for: " + getRequestInfo(request) + " Status:"
                + response.getStatus());
    }
}

From source file:org.openecomp.sdnc.filters.LogFilter.java

private void post(HttpServletRequest request, HttpServletResponse response, long startTime) {

    //AUDIT.info("{}|{}|{}{}",request.getRemoteHost(),request.getMethod(),request.getRequestURL().toString(),request.getQueryString());
    //AUDIT.info(request.getRemoteHost() + D + request.getMethod() + D + request.getRequestURL().toString() + D + request.getQueryString());
    //METRIC.info(request.getMethod() + D + response.getStatus() + D + request.getRequestURL().toString() + D + (System.currentTimeMillis() - startTime) + " ms");
    MDC.put(BEGIN_TIMESTAMP, asIso8601(startTime));
    MDC.put(END_TIMESTAMP, asIso8601(System.currentTimeMillis()));
    //MDC.put(REQUEST_ID,"already done above");
    MDC.put(SERVICE_NAME, request.getRequestURL().toString());
    int idx = request.getPathInfo().toString().lastIndexOf(":");
    String instance = "";
    if (idx != -1) {
        instance = request.getPathInfo().substring(idx + 1);
    }/*from w  ww . j a v  a  2s . co  m*/
    MDC.put(SERVICE_INSTANCE, instance);
    MDC.put(THREAD_ID, "");
    MDC.put(PHYSICAL_SERVER_NAME, "");
    //MDC.put(PARTNER_NAME,"already done above");
    if (response.getStatus() >= 400) {
        MDC.put(STATUS_CODE, "ERROR");
    } else {
        MDC.put(STATUS_CODE, "COMPLETE");
    }

    MDC.put(RESP_CODE, "" + response.getStatus());
    MDC.put(RESP_DESC, "");
    MDC.put(INSTANCE_UUID, "");
    MDC.put(CATEGORY, "");
    MDC.put(SEVERITY, "");
    //MDC.put(SERVER_IP,""); //by chef
    MDC.put(ELAPSED_TIME, "" + (System.currentTimeMillis() - startTime));
    //MDC.put(SERVER_HOST,""); //by chef
    MDC.put(CLIENT_IP, request.getRemoteHost());
    MDC.put(CLASS, "");
    MDC.put(UNUSED, "");
    MDC.put(PROCESS_KEY, "");
    MDC.put(CUST_1, "");
    MDC.put(CUST_2, "");
    MDC.put(CUST_3, "");
    MDC.put(CUST_4, "");
    MDC.put(DETAIL_MESSAGE, request.getMethod());

    AUDIT.info("");
}

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

/**
 * Serve the specified resource, optionally including the data content.
 *
 * @param request The servlet request we are processing
 * @param response The servlet response we are creating
 * @param content Should the content be included?
 * @param path the resource to serve//from   w w w.  ja  v a2  s  .  com
 *
 * @exception IOException if an input/output error occurs
 */
private void serveResource(HttpServletRequest request, HttpServletResponse response, boolean content, Path path)
        throws IOException, ServletException {
    ActionContext context = new ActionContext().put(HttpServletRequest.class, request)
            .put(HttpServletResponse.class, response).put(ServletContext.class, request.getServletContext())
            .put(Path.class, path);
    if (path == null) {
        notFound.handle(context);
        return;
    }
    BasicFileAttributes attr;
    try {
        attr = Files.readAttributes(path, BasicFileAttributes.class);
    } catch (IOException ex) {
        notFound.handle(context);
        return;
    }
    context.put(BasicFileAttributes.class, attr);

    boolean isError = response.getStatus() >= HttpServletResponse.SC_BAD_REQUEST;
    // Check if the conditions specified in the optional If headers are
    // satisfied.
    // Checking If headers
    boolean included = (request.getAttribute(RequestDispatcher.INCLUDE_CONTEXT_PATH) != null);
    String etag = this.eTag.getValue(context);
    if (!included && !isError && !checkIfHeaders(request, response, attr, etag)) {
        return;
    }
    // Find content type.
    String contentType = contentTypeResolver.getValue(context);
    // Get content length
    long contentLength = attr.size();
    // Special case for zero length files, which would cause a
    // (silent) ISE
    boolean serveContent = content && contentLength != 0;
    Range[] ranges = null;
    if (!isError) {
        if (useAcceptRanges) {
            // Accept ranges header
            response.setHeader(HttpHeaders.ACCEPT_RANGES, "bytes");
        }
        // Parse range specifier
        ranges = serveContent ? parseRange(request, response, attr, etag) : FULL;
        // ETag header
        response.setHeader(HttpHeaders.ETAG, etag);
        // Last-Modified header
        response.setDateHeader(HttpHeaders.LAST_MODIFIED, attr.lastModifiedTime().toMillis());
    }
    ServletOutputStream ostream = null;
    if (serveContent) {
        ostream = response.getOutputStream();
    }

    String disposition = contentDisposition.getValue(context);
    if (disposition != null) {
        response.setHeader(HttpHeaders.CONTENT_DISPOSITION, disposition);
    }

    // Check to see if a Filter, Valve of wrapper has written some content.
    // If it has, disable range requests and setting of a content length
    // since neither can be done reliably.
    if (isError || ranges == FULL) {
        // Set the appropriate output headers
        if (contentType != null) {
            log.debug("serveFile: contentType='{}'", contentType);
            response.setContentType(contentType);
        }
        if (contentLength >= 0) {
            setContentLengthLong(response, contentLength);
        }
        // Copy the input stream to our output stream (if requested)
        if (serveContent) {
            log.trace("Serving bytes");
            Files.copy(path, ostream);
        }
    } else if (ranges != null && ranges.length != 0) {
        // Partial content response.
        response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);
        if (ranges.length == 1) {
            Range range = ranges[0];
            response.addHeader(HttpHeaders.CONTENT_RANGE, range.toString());
            long length = range.end - range.start + 1;
            setContentLengthLong(response, length);
            if (contentType != null) {
                log.debug("serveFile: contentType='{}'", contentType);
                response.setContentType(contentType);
            }
            if (serveContent) {
                try (InputStream stream = Files.newInputStream(path)) {
                    copyRange(stream, ostream, range, new byte[Math.min((int) length, 8192)]);
                }
            }
        } else {
            response.setContentType("multipart/byteranges; boundary=" + MIME_SEPARATION);
            if (serveContent) {
                copy(path, ostream, ranges, contentType, new byte[Math.min((int) contentLength, 8192)]);
            }
        }
    }
}

From source file:org.jitsi.rest.AbstractJSONHandler.java

/**
 * Gets a JSON representation of the {@code Version} of the associated
 * server/service.//from   w  w  w  .  j  a  v  a2  s  .  c o m
 *
 * @param baseRequest the original unwrapped {@link Request} object
 * @param request the request either as the {@code Request} object or a
 * wrapper of that request
 * @param response the response either as the {@code Response} object or a
 * wrapper of that response
 * @throws IOException
 * @throws ServletException
 */
protected void doGetVersionJSON(Request baseRequest, HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    beginResponse(/*target*/ null, baseRequest, request, response);

    BundleContext bundleContext = getBundleContext();
    int status = HttpServletResponse.SC_SERVICE_UNAVAILABLE;

    if (bundleContext != null) {
        VersionService versionService = ServiceUtils.getService(bundleContext, VersionService.class);

        if (versionService != null) {
            org.jitsi.service.version.Version version = versionService.getCurrentVersion();
            JSONObject versionJSONObject = new JSONObject();

            versionJSONObject.put("name", version.getApplicationName());
            versionJSONObject.put("version", version.toString());
            versionJSONObject.put("os", System.getProperty("os.name"));

            Writer writer = response.getWriter();

            response.setStatus(status = HttpServletResponse.SC_OK);
            versionJSONObject.writeJSONString(writer);
        }
    }

    if (response.getStatus() != status)
        response.setStatus(status);

    endResponse(/*target*/ null, baseRequest, request, response);
}

From source file:org.auraframework.impl.adapter.ServletUtilAdapterImplUnitTest.java

/**
 * Verifies first exception within handleServletException is caught and processed
 * we throw 'EmptyStackException' when getting InstanceStack, then verify
 * exceptionAdapter.handleException(death) is called with it
 *///from www.  j  a  v a  2  s  .c om
@Test
public void testHandleExceptionDeathCaught() throws Exception {
    PrintWriter writer = Mockito.mock(PrintWriter.class);
    HttpServletRequest mockRequest = Mockito.mock(HttpServletRequest.class);
    HttpServletResponse mockResponse = Mockito.mock(HttpServletResponse.class);
    ContextService mockContextService = Mockito.mock(ContextService.class);
    AuraContext mockContext = Mockito.mock(AuraContext.class);
    ConfigAdapter mockConfigAdapter = Mockito.mock(ConfigAdapter.class);
    ExceptionAdapter mockExceptionAdapter = Mockito.mock(ExceptionAdapter.class);

    Throwable firstException = new EmptyStackException();

    Mockito.when(mockResponse.getWriter()).thenReturn(writer);
    Mockito.when(mockResponse.getStatus()).thenReturn(HttpStatus.SC_OK);
    Mockito.when(mockContext.getFormat()).thenReturn(AuraContext.Format.JSON);
    Mockito.when(mockContext.getMode()).thenReturn(Mode.PROD);
    Mockito.when(mockConfigAdapter.isProduction()).thenReturn(true);
    Mockito.when(mockContextService.getCurrentContext()).thenReturn(mockContext);
    Mockito.when(mockContext.getInstanceStack()).thenThrow(firstException);

    Throwable exception = new InterruptedException("opps");

    ServletUtilAdapterImpl adapter = Mockito.spy(new ServletUtilAdapterImpl());
    adapter.setContextService(mockContextService);
    adapter.setConfigAdapter(mockConfigAdapter);
    adapter.setExceptionAdapter(mockExceptionAdapter);
    adapter.handleServletException(exception, true, mockContext, mockRequest, mockResponse, true);

    ArgumentCaptor<Throwable> handledException = ArgumentCaptor.forClass(Throwable.class);
    Mockito.verify(mockExceptionAdapter, Mockito.times(2)).handleException(handledException.capture());

    assertTrue("Should handle EmptyStackException",
            handledException.getAllValues().get(1) instanceof EmptyStackException);

    Mockito.verify(mockResponse, Mockito.atLeastOnce()).setStatus(HttpStatus.SC_OK);
    Mockito.verify(mockContextService, Mockito.atLeastOnce()).endContext();
    Mockito.verify(adapter, Mockito.times(1)).setNoCache(mockResponse);
}

From source file:org.auraframework.http.resource.InlineJs.java

@Override
public void write(HttpServletRequest request, HttpServletResponse response, AuraContext context)
        throws IOException {
    try {/*from w ww .j a v  a 2s. c o  m*/
        // For appcached apps, inline is not expected to return a CSRF token
        if (!manifestUtil.isManifestEnabled()) {
            String token = request.getParameter("jwt");
            if (!configAdapter.validateBootstrap(token)) {
                throw new AuraJWTError("Invalid jwt parameter");
            }
        }
        DefDescriptor<? extends BaseComponentDef> appDefDesc = context.getLoadingApplicationDescriptor();
        internalWrite(request, response, appDefDesc, context);
    } catch (Throwable t) {
        if (t instanceof AuraJWTError) {
            // If jwt validation fails, just 404. Do not gack.
            try {
                servletUtilAdapter.send404(request.getServletContext(), request, response);
            } catch (ServletException e) {
                // ignore
            }
        } else {
            servletUtilAdapter.handleServletException(t, false, context, request, response, false);
            exceptionAdapter.handleException(new AuraResourceException(getName(), response.getStatus(), t));
        }
    }
}