當前位置: 首頁>>代碼示例>>Java>>正文


Java WebApplicationException.getResponse方法代碼示例

本文整理匯總了Java中javax.ws.rs.WebApplicationException.getResponse方法的典型用法代碼示例。如果您正苦於以下問題:Java WebApplicationException.getResponse方法的具體用法?Java WebApplicationException.getResponse怎麽用?Java WebApplicationException.getResponse使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在javax.ws.rs.WebApplicationException的用法示例。


在下文中一共展示了WebApplicationException.getResponse方法的13個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: toResponse

import javax.ws.rs.WebApplicationException; //導入方法依賴的package包/類
/**
 * Maps an unhandled {@link WebApplicationException} to a {@link Response}.
 *
 * @param exception the {@link WebApplicationException} that was not handled
 * @return a {@link Response} object with a status of the {@link WebApplicationException} or 500
 *     if the exception's response is null, content-type of 'application/json', and a
 *     {@link JsonError} entity containing details about the unhandled exception in JSON format
 */
@Override
public Response toResponse(WebApplicationException exception) {

  Response response = exception.getResponse();
  int code = response == null ? INTERNAL_SERVER_ERROR.getStatusCode() : response.getStatus();

  if (code >= 400 && code < 500) {
    logger.warn("An unhandled exception was thrown.", exception);
  } else if (code >= 500) {
    logger.error("An unhandled exception was thrown.", exception);
  }

  return Optional.ofNullable(exception.getResponse())
      .map(Response::fromResponse)
      .orElse(Response.status(code))
      .entity(
          JsonError.builder()
              .code(code)
              .message(getMessage(code))
              .build())
      .type(MediaType.APPLICATION_JSON)
      .build();
}
 
開發者ID:cerner,項目名稱:beadledom,代碼行數:32,代碼來源:WebApplicationExceptionMapper.java

示例2: toResponse

import javax.ws.rs.WebApplicationException; //導入方法依賴的package包/類
@SuppressWarnings("nls")
@Override
public Response toResponse(Throwable t)
{
	final WebApplicationException webAppException = mapException(t);

	Response response = webAppException.getResponse();
	final int status = response.getStatus();
	if( status >= 500 )
	{
		LOGGER.error("REST API error", t);
	}
	if( response.getEntity() == null )
	{
		ResponseBuilder builder = Response.fromResponse(response);
		response = builder.entity(convertExceptionToJsonResponse(response.getStatus(), webAppException))
			.type(MediaType.APPLICATION_JSON).build();
	}

	return response;
}
 
開發者ID:equella,項目名稱:Equella,代碼行數:22,代碼來源:RestEasyExceptionMapper.java

示例3: testPropagationOfResponseDetailsFromDefaultMapper

import javax.ws.rs.WebApplicationException; //導入方法依賴的package包/類
@Test
public void testPropagationOfResponseDetailsFromDefaultMapper() throws Exception {
    stubFor(get(urlEqualTo("/")).willReturn(aResponse().withStatus(STATUS).withBody(BODY)));

    SimpleGetApi simpleGetApi = RestClientBuilder.newBuilder()
        .baseUrl(getServerURL())
        .build(SimpleGetApi.class);

    try {
        simpleGetApi.executeGet();
        fail("A "+WebApplicationException.class+" should have been thrown automatically");
    }
    catch (WebApplicationException w) {
        Response response = w.getResponse();
        // the response should have the response code from the api call
        assertEquals(response.getStatus(), STATUS,
            "The 401 from the response should be propagated");
        String body = response.readEntity(String.class);
        assertEquals(body, BODY,
            "The body of the response should be propagated");
        response.close();
    }
}
 
開發者ID:eclipse,項目名稱:microprofile-rest-client,代碼行數:24,代碼來源:DefaultExceptionMapperTest.java

示例4: exceptionToJson

import javax.ws.rs.WebApplicationException; //導入方法依賴的package包/類
public static JsonObject exceptionToJson(Throwable e, int depth) {
    JsonArrayBuilder stackElements = createArrayBuilder();
    StackTraceElement[] stackTrace = e.getStackTrace();
    JsonObjectBuilder builder = createObjectBuilder()
            .add("type", e.getClass().getName());

    add(builder, "message", e.getMessage());
    add(builder, "localizedMessage", e.getLocalizedMessage());
    add(builder, "forgeVersion", Versions.getImplementationVersionFor(UIContext.class).toString());

    if (stackTrace != null) {
        for (StackTraceElement element : stackTrace) {
            stackElements.add(stackTraceElementToJson(element));
        }
        builder.add("stackTrace", stackElements);
    }

    if (depth > 0) {
        Throwable cause = e.getCause();
        if (cause != null && cause != e) {
            builder.add("cause", exceptionToJson(cause, depth - 1));
        }
    }
    if (e instanceof WebApplicationException) {
        WebApplicationException webApplicationException = (WebApplicationException) e;
        Response response = webApplicationException.getResponse();
        if (response != null) {
            builder.add("status", response.getStatus());
        }
    }
    return builder.build();
}
 
開發者ID:fabric8-launcher,項目名稱:launcher-backend,代碼行數:33,代碼來源:JsonOperations.java

示例5: toResponse

import javax.ws.rs.WebApplicationException; //導入方法依賴的package包/類
public Response toResponse(RuntimeException e) {
    // don't try to handle jersey exceptions ourselves
    if (e instanceof WebApplicationException) { 
        WebApplicationException ie =(WebApplicationException) e; 
        return ie.getResponse(); 
    } 

    return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(
            new ZError(ui.getRequestUri().toString(),
                    "Error processing request due to " + e
                    )).build();
}
 
開發者ID:maoling,項目名稱:fuck_zookeeper,代碼行數:13,代碼來源:RuntimeExceptionMapper.java

示例6: toResponse

import javax.ws.rs.WebApplicationException; //導入方法依賴的package包/類
@Override
public Response toResponse(final Throwable exception) {

    log(exception);
    int status = Status.INTERNAL_SERVER_ERROR.getStatusCode();
    if (exception instanceof WebApplicationException) {
        final WebApplicationException internalException = (WebApplicationException) exception;
        if (internalException.getResponse().hasEntity()) {
            return internalException.getResponse();
        } else {
            status = internalException.getResponse().getStatus();
        }
    }
    final MediaType mediaType = getAppropriateMediaType();

    if (mediaType.isCompatible(MediaType.TEXT_PLAIN_TYPE) || mediaType.isCompatible(MediaType.TEXT_HTML_TYPE)) {
        return Response.status(status)
            .entity(exception.getMessage())
            .type(mediaType)
            .build();
    } else {
        return Response.status(status)
            .entity(new ErrorResponse(exception, uriInfo, showStackTrace))
            .type(mediaType)
            .build();
    }
}
 
開發者ID:trajano,項目名稱:app-ms,代碼行數:28,代碼來源:JsonExceptionMapper.java

示例7: toResponse

import javax.ws.rs.WebApplicationException; //導入方法依賴的package包/類
@Override
public Response toResponse(WebApplicationException exception) {

  LOGGER.error("WebApplicationException:", exception);
  LOGGER.debug("Constructing Error Response for: [{}]", exception.toString());
  ErrorResponse errorResponse = new ErrorResponse();

  Response exceptionResponse = exception.getResponse();
  Response.StatusType statusInfo = exceptionResponse.getStatusInfo();

  errorResponse.setCode(statusInfo.getStatusCode());
  errorResponse.setStatus(statusInfo.getReasonPhrase());
  errorResponse.setMessage(exception.getMessage());

  Response.ResponseBuilder responseBuilder = Response.status(statusInfo)
      .entity(errorResponse)
      .type(MediaType.APPLICATION_JSON);

  MultivaluedMap<String, Object> headers = exceptionResponse.getHeaders();
  if (headers.size() > 0) {
    LOGGER.debug("Adding headers:");
    for (Map.Entry<String, List<Object>> entry : headers.entrySet()) {
      String headerKey = entry.getKey();
      List<Object> headerValues = entry.getValue();
      LOGGER.debug("  {} -> {}", headerKey, headerValues);
      if (headerValues.size() == 1) {
        responseBuilder.header(headerKey, headerValues.get(0));
      } else {
        responseBuilder.header(headerKey, headerValues);
      }
    }
  }

  return responseBuilder.build();
}
 
開發者ID:durimkryeziu,項目名稱:jersey-2.x-webapp-for-servlet-container,代碼行數:36,代碼來源:WebApplicationExceptionMapper.java

示例8: handleWebApplicationException

import javax.ws.rs.WebApplicationException; //導入方法依賴的package包/類
private Response handleWebApplicationException(final WebApplicationException webappException) {
    Response res = webappException.getResponse();
    if (HttpStatus.SC_METHOD_NOT_ALLOWED == res.getStatus()) {
        return this.handlePersoniumCoreException(PersoniumCoreException.Misc.METHOD_NOT_ALLOWED);
    } else if (HttpStatus.SC_NOT_FOUND == res.getStatus()) {
        return this.handlePersoniumCoreException(PersoniumCoreException.Misc.NOT_FOUND);
    }
    return res;
}
 
開發者ID:personium,項目名稱:personium-core,代碼行數:10,代碼來源:PersoniumCoreExceptionMapper.java

示例9: toResponse

import javax.ws.rs.WebApplicationException; //導入方法依賴的package包/類
@Override
public Response toResponse(final WebApplicationException exception) {

    return exception.getResponse();
}
 
開發者ID:trajano,項目名稱:app-ms,代碼行數:6,代碼來源:WebApplicationExceptionMapper.java

示例10: toResponse

import javax.ws.rs.WebApplicationException; //導入方法依賴的package包/類
@Override
public Response toResponse(WebApplicationException exception) {
    logger.error("Web App Error!", exception);
    return exception.getResponse();
}
 
開發者ID:Lambda-3,項目名稱:Indra,代碼行數:6,代碼來源:ErrorMapper.java

示例11: main

import javax.ws.rs.WebApplicationException; //導入方法依賴的package包/類
public static void main(String[] args) {
        try {
            final Client client = ClientBuilder.newClient();

            // create some buckets
            final int numBuckets = 20;
            final List<Bucket> createdBuckets = new ArrayList<>();

            for (int i=0; i < numBuckets; i++) {
                final Bucket createdBucket = createBucket(client, i);
                System.out.println("Created bucket # " + i + " with id " + createdBucket.getIdentifier());
                createdBuckets.add(createdBucket);
            }

            // create some flows
            final int numFlowsPerBucket = 10;
            final List<VersionedFlow> allFlows = new ArrayList<>();

            for (final Bucket bucket : createdBuckets) {
                final List<VersionedFlow> createdFlows = createFlows(client, bucket, numFlowsPerBucket);
                allFlows.addAll(createdFlows);
            }

            // create some snapshots
            final int numSnapshotsPerFlow = 10;
            for (final VersionedFlow flow : allFlows) {
                createSnapshots(client, flow, numSnapshotsPerFlow);
            }

            // Retrieve the flow by id
//            final Response flowResponse = client.target(REGISTRY_API_FLOWS_URL)
//                    .path("/{flowId}")
//                    .resolveTemplate("flowId", createdFlow.getIdentifier())
//                    .request()
//                    .get();
//
//            final String flowJson = flowResponse.readEntity(String.class);
//            System.out.println("Flow: " + flowJson);

        } catch (WebApplicationException e) {
            LOGGER.error(e.getMessage(), e);

            final Response response = e.getResponse();
            LOGGER.error(response.readEntity(String.class));
        }
    }
 
開發者ID:apache,項目名稱:nifi-registry,代碼行數:47,代碼來源:TestRestAPI.java

示例12: PersoniumCoreContainerFilter

import javax.ws.rs.WebApplicationException; //導入方法依賴的package包/類
/**
 * 認証なしのOPTIONSメソッドがリクエストされた場合にpersoniumで受け付けている全メソッドが返卻されること.
 * @throws URISyntaxException URISyntaxException
 */
@Test
public void 認証なしのOPTIONSメソッドがリクエストされた場合にpersoniumで受け付けている全メソッドが返卻されること() throws URISyntaxException {
    // 被テストオブジェクトを準備
    PersoniumCoreContainerFilter containerFilter = new PersoniumCoreContainerFilter();
    // ContainerRequiestを準備
    WebApplication wa = mock(WebApplication.class);
    InBoundHeaders headers = new InBoundHeaders();
    // X-FORWARDED-* 係のヘッダ設定
    String scheme = "https";
    String host = "example.org";
    headers.add(PersoniumCoreUtils.HttpHeaders.X_FORWARDED_PROTO, scheme);
    headers.add(PersoniumCoreUtils.HttpHeaders.X_FORWARDED_HOST, host);
    ContainerRequest request = new ContainerRequest(wa, HttpMethod.OPTIONS,
            new URI("http://dc1.example.com/hoge"),
            new URI("http://dc1.example.com/hoge/hoho"),
            headers, null);
    // HttpServletRequestのmockを準備
    HttpServletRequest mockServletRequest = mock(HttpServletRequest.class);
    when(mockServletRequest.getRequestURL()).thenReturn(new StringBuffer("http://dc1.example.com"));
    ServletContext mockServletContext = mock(ServletContext.class);
    when(mockServletContext.getContextPath()).thenReturn("");
    when(mockServletRequest.getServletContext()).thenReturn(mockServletContext);
    containerFilter.setHttpServletRequest(mockServletRequest);
    try {
        containerFilter.filter(request);
    } catch (WebApplicationException e) {
        Response response = e.getResponse();
        assertEquals(response.getStatus(), HttpStatus.SC_OK);
        MultivaluedMap<String, Object> meta = response.getMetadata();
        List<Object> values = meta.get("Access-Control-Allow-Methods");
        assertEquals(values.size(), 1);
        String value = (String) values.get(0);
        String[] methods = value.split(",");
        Map<String, String> masterMethods = new HashMap<String, String>();
        masterMethods.put(HttpMethod.OPTIONS, "");
        masterMethods.put(HttpMethod.GET, "");
        masterMethods.put(HttpMethod.POST, "");
        masterMethods.put(HttpMethod.PUT, "");
        masterMethods.put(HttpMethod.DELETE, "");
        masterMethods.put(HttpMethod.HEAD, "");
        masterMethods.put(io.personium.common.utils.PersoniumCoreUtils.HttpMethod.MERGE, "");
        masterMethods.put(io.personium.common.utils.PersoniumCoreUtils.HttpMethod.MKCOL, "");
        masterMethods.put(io.personium.common.utils.PersoniumCoreUtils.HttpMethod.MOVE, "");
        masterMethods.put(io.personium.common.utils.PersoniumCoreUtils.HttpMethod.PROPFIND, "");
        masterMethods.put(io.personium.common.utils.PersoniumCoreUtils.HttpMethod.PROPPATCH, "");
        masterMethods.put(io.personium.common.utils.PersoniumCoreUtils.HttpMethod.ACL, "");
        for (String method : methods) {
            if (method.trim() == "") {
                continue;
            }
            String m = masterMethods.remove(method.trim());
            if (m == null) {
                fail("Method " + method + " is not defined.");
            }
        }
        if (!masterMethods.isEmpty()) {
            fail("UnExcpected Error.");
        }
    }
}
 
開發者ID:personium,項目名稱:personium-core,代碼行數:65,代碼來源:OptionsMethodTest.java

示例13: toResponse

import javax.ws.rs.WebApplicationException; //導入方法依賴的package包/類
/**
 * Extracts and returns the response from a WebApplicationException.
 *
 * @param e WebApplicationException that was thrown
 * @return precomputed Response from the exception
 */
@Override
public Response toResponse(WebApplicationException e) {
    return e.getResponse();
}
 
開發者ID:shlee89,項目名稱:athena,代碼行數:11,代碼來源:WebApplicationExceptionMapper.java


注:本文中的javax.ws.rs.WebApplicationException.getResponse方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。