javax.ws.rs.core.Response.StatusType Java Examples

The following examples show how to use javax.ws.rs.core.Response.StatusType. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ProcessInstanceManagementResourceTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test
public void testRetriggerErrorInfo() {

    doAnswer(new Answer<Void>() {

        @Override
        public Void answer(InvocationOnMock invocation) throws Throwable {
            when(processInstance.status()).thenReturn(ProcessInstance.STATE_ACTIVE);
            return null;
        }
    }).when(error).retrigger();

    Response response = resource.retriggerInstanceInError(PROCESS_ID, PROCESS_INSTANCE_ID);
    assertThat(response).isNotNull();

    verify(responseBuilder, times(1)).status((StatusType) Status.OK);
    verify(responseBuilder, times(1)).entity(any());

    verify(processInstance, times(2)).error();
    verify(error, times(1)).retrigger();
    verify(error, times(0)).skip();

    verify(resource).doRetriggerInstanceInError(PROCESS_ID, PROCESS_INSTANCE_ID);
}
 
Example #2
Source File: ImageCatalogValidator.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
@Override
public boolean isValid(String value, ConstraintValidatorContext context) {
    LOGGER.info("Image Catalog validation was called: {}", value);
    try {
        if (value == null || !HTTP_CONTENT_SIZE_VALIDATOR.isValid(value, context)) {
            return false;
        }
        Pair<StatusType, String> content = HTTP_HELPER.getContent(value);
        if (content.getKey().getFamily().equals(Family.SUCCESSFUL)) {
            return imageCatalogParsable(context, content.getValue());
        }
        String msg = String.format(FAILED_TO_GET_BY_FAMILY_TYPE, value, content.getKey().getReasonPhrase());
        context.buildConstraintViolationWithTemplate(msg).addConstraintViolation();
    } catch (Throwable throwable) {
        context.buildConstraintViolationWithTemplate(String.format(FAILED_TO_GET_WITH_EXCEPTION, value)).addConstraintViolation();
        LOGGER.debug("Failed to validate the specified image catalog URL: " + value, throwable);
    }
    return false;
}
 
Example #3
Source File: SnsRequestHandlerTest.java    From jrestless with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void createResponseWriter_writeResponse_Always_ShouldDelegateResponseToHandler() throws IOException {
	SnsRecordAndLambdaContext reqAndContext = mock(SnsRecordAndLambdaContext.class);
	SNS sns = new SNS();
	sns.setTopicArn(":t");
	SNSRecord snsRecord = new SNSRecord();
	snsRecord.setSns(sns);
	when(reqAndContext.getSnsRecord()).thenReturn(snsRecord);

	StatusType statusType = mock(StatusType.class);
	Map<String, List<String>> headers = mock(Map.class);
	ByteArrayOutputStream entityOutputStream = mock(ByteArrayOutputStream.class);
	snsHandler.createResponseWriter(reqAndContext).writeResponse(statusType, headers, entityOutputStream);
	verify(snsHandler).handleReponse(reqAndContext, statusType, headers, entityOutputStream);
}
 
Example #4
Source File: ConstraintViolationExceptionConverter.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
@Override
public InvocationException convert(Invocation invocation, ConstraintViolationException throwable,
    StatusType genericStatus) {
  List<ValidateDetail> details = throwable.getConstraintViolations().stream()
      .map(violation -> new ValidateDetail(violation.getPropertyPath().toString(), violation.getMessage()))
      .collect(Collectors.toList());

  CommonExceptionData exceptionData = new CommonExceptionData(code.get(), "invalid parameters.");
  exceptionData.putDynamic("validateDetail", details);
  return new InvocationException(BAD_REQUEST, exceptionData);
}
 
Example #5
Source File: WebActionRequestHandler.java    From jrestless with Apache License 2.0 5 votes vote down vote up
@Override
public void writeResponse(StatusType statusType, Map<String, List<String>> headers,
		OutputStream entityOutputStream) throws IOException {
	Map<String, String> flattenedHeaders = HeaderUtils.flattenHeaders(headers);
	String body = ((ByteArrayOutputStream) entityOutputStream).toString(StandardCharsets.UTF_8.name());
	response = createJsonResponse(body, flattenedHeaders, statusType);
}
 
Example #6
Source File: SimpleRequestHandlerIntTest.java    From jrestless with Apache License 2.0 5 votes vote down vote up
@Override
public SimpleResponseWriter<SimpleContainerResponse> createResponseWriter(JRestlessContainerRequest containerRequest) {
	return new SimpleResponseWriter<SimpleContainerResponse>() {

		private SimpleContainerResponse response = onRequestFailure(null, null, null);

		@Override
		public OutputStream getEntityOutputStream() {
			return new ByteArrayOutputStream();
		}

		@Override
		public void writeResponse(StatusType statusType, Map<String, List<String>> headers,
				OutputStream entityOutputStream) throws IOException {
			response = new SimpleContainerResponse(statusType, entityOutputStream.toString(), headers);
		}

		@Override
		public SimpleContainerResponse getResponse() {
			return response;
		}
	};
}
 
Example #7
Source File: RestServiceTestApplication.java    From packt-java-ee-7-code-samples with GNU General Public License v2.0 5 votes vote down vote up
private void bookSeats(Collection<SeatDto> seats) {
    for (SeatDto seat : seats) {
        try {
            final String idOfSeat = Integer.toString(seat.getId());
            seatResource.path(idOfSeat).request().post(Entity.json(""), String.class);
            System.out.println(seat + " booked");
        } catch (WebApplicationException e) {
            final Response response = e.getResponse();
            StatusType statusInfo = response.getStatusInfo();
            System.out.println(seat + " not booked (" + statusInfo.getReasonPhrase() + "): "
                + response.readEntity(JsonObject.class).getString("entity"));
        }

    }
}
 
Example #8
Source File: ProcessInstanceManagementResourceTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetErrorInfo() {

    Response response = resource.getInstanceInError("test", "xxxxx");
    assertThat(response).isNotNull();

    verify(responseBuilder, times(1)).status((StatusType) Status.OK);
    verify(responseBuilder, times(1)).entity(any());

    verify(processInstance, times(2)).error();
    verify(error, times(0)).retrigger();
    verify(error, times(0)).skip();

    verify(resource).doGetInstanceInError(PROCESS_ID, PROCESS_INSTANCE_ID);
}
 
Example #9
Source File: ExceptionFactory.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
public static InvocationException create(StatusType status,
    Object exceptionOrErrorData) {
  if (InvocationException.class.isInstance(exceptionOrErrorData)) {
    return (InvocationException) exceptionOrErrorData;
  }

  return doCreate(status, exceptionOrErrorData);
}
 
Example #10
Source File: WebActionHttpRequestHandler.java    From jrestless with Apache License 2.0 5 votes vote down vote up
@Override
protected JsonObject createJsonResponse(@Nullable String body, @Nonnull Map<String, String> responseHeaders,
		@Nonnull StatusType statusType) {
	requireNonNull(responseHeaders);
	requireNonNull(statusType);
	JsonObject response = new JsonObject();
	if (body != null) {
		response.addProperty("body", body);
	}
	response.addProperty("statusCode", statusType.getStatusCode());
	response.add("headers", GSON.toJsonTree(responseHeaders, Map.class));
	return response;
}
 
Example #11
Source File: Response.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
public static Response create(StatusType status, Object result) {
  Response response = Response.status(status);
  if (response.isFailed()) {
    result = ExceptionFactory.create(status, result);
  }
  return response.entity(result);
}
 
Example #12
Source File: GatewayResponseTest.java    From jrestless with Apache License 2.0 5 votes vote down vote up
private Constructor<GatewayResponse> getConstructor() {
	try {
		return GatewayResponse.class.getConstructor(String.class, Map.class, StatusType.class, boolean.class);
	} catch (NoSuchMethodException | SecurityException e) {
		throw new RuntimeException(e);
	}
}
 
Example #13
Source File: GatewayRequestHandler.java    From jrestless with Apache License 2.0 5 votes vote down vote up
@Override
public void writeResponse(StatusType statusType, Map<String, List<String>> headers,
		OutputStream entityOutputStream) throws IOException {
	List<String> binaryResponseHeader = headers.get(HEADER_BINARY_RESPONSE);
	boolean binaryResponse = binaryResponseHeader != null
			&& binaryResponseHeader.size() == 1
			&& "true".equals(binaryResponseHeader.get(0));
	Map<String, String> flattenedHeaders = HeaderUtils.flattenHeaders(headers,
			headerName -> !HEADER_BINARY_RESPONSE.equals(headerName));
	String body = ((ByteArrayOutputStream) entityOutputStream).toString(StandardCharsets.UTF_8.name());
	response = new GatewayResponse(body, flattenedHeaders, statusType, binaryResponse);
}
 
Example #14
Source File: TestSpringmvcProducerResponseMapper.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
@Before
public void setup() {
  mapper = new SpringmvcProducerResponseMapper(realMapper);

  new MockUp<ProducerResponseMapper>(realMapper) {
    @Mock
    Response mapResponse(StatusType status, Object response) {
      if (HttpStatus.isSuccess(status.getStatusCode())) {
        return Response.ok(Arrays.asList(arrResult));
      }

      return null;
    }
  };
}
 
Example #15
Source File: JaxrsProducerResponseMapper.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
@Override
public Response mapResponse(StatusType status, Object response) {
  javax.ws.rs.core.Response jaxrsResponse = (javax.ws.rs.core.Response) response;

  Response cseResponse = Response.status(jaxrsResponse.getStatusInfo()).entity(jaxrsResponse.getEntity());
  MultivaluedMap<String, Object> headers = jaxrsResponse.getHeaders();
  for (Entry<String, List<Object>> entry : headers.entrySet()) {
    if (entry.getValue() == null || entry.getValue().isEmpty()) {
      continue;
    }

    cseResponse.getHeaders().addHeader(entry.getKey(), entry.getValue());
  }
  return cseResponse;
}
 
Example #16
Source File: ApiUtil.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public static String getCreatedId(Response response) {
    URI location = response.getLocation();
    if (!response.getStatusInfo().equals(Status.CREATED)) {
        StatusType statusInfo = response.getStatusInfo();
        response.bufferEntity();
        String body = response.readEntity(String.class);
        throw new WebApplicationException("Create method returned status "
                + statusInfo.getReasonPhrase() + " (Code: " + statusInfo.getStatusCode() + "); expected status: Created (201). Response body: " + body, response);
    }
    if (location == null) {
        return null;
    }
    String path = location.getPath();
    return path.substring(path.lastIndexOf('/') + 1);
}
 
Example #17
Source File: ValidationErrorsIT.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
private void put_single_manual_validation(final MediaType... mediaTypes) throws Exception {
  UserXO sent = new UserXO();

  Response response = client().target(url("validationErrors/manual/single")).request()
      .accept(mediaTypes)
      .put(Entity.entity(sent, mediaTypes[0]), Response.class);

  assertThat(response.getStatusInfo(), is(equalTo((StatusType)Status.BAD_REQUEST)));
  assertThat(response.getMediaType(), is(equalTo(mediaTypes[1])));

  List<ValidationErrorXO> errors = response.readEntity(new GenericType<List<ValidationErrorXO>>() {});
  assertThat(errors, hasSize(1));
}
 
Example #18
Source File: VertxServerResponseToHttpServletResponse.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
@Override
public StatusType getStatusType() {
  if (statusType == null) {
    statusType = new HttpStatus(serverResponse.getStatusCode(), serverResponse.getStatusMessage());
  }
  return statusType;
}
 
Example #19
Source File: VertxClientResponseToHttpServletResponse.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
@Override
public StatusType getStatusType() {
  if (statusType == null) {
    statusType = new HttpStatus(clientResponse.statusCode(), clientResponse.statusMessage());
  }
  return statusType;
}
 
Example #20
Source File: MCRORCIDException.java    From mycore with GNU General Public License v3.0 5 votes vote down vote up
public MCRORCIDException(Response response) throws IOException {
    StatusType status = response.getStatusInfo();
    String responseBody = response.readEntity(String.class);

    StringBuilder sb = new StringBuilder();
    if (responseBody.startsWith("{")) {
        JsonNode json = new ObjectMapper().readTree(responseBody);
        addJSONField(json, "error-code", sb, ": ");
        addJSONField(json, "developer-message", sb, "");
        addJSONField(json, "error_description", sb, "");
    } else {
        sb.append(status.getStatusCode()).append(": ").append(status.getReasonPhrase());
    }
    this.message = sb.toString();
}
 
Example #21
Source File: TestVertxServerResponseToHttpServletResponse.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
@Test
public void getStatusType() {
  StatusType status = response.getStatusType();

  Assert.assertSame(status, response.getStatusType());
  Assert.assertEquals(123, httpStatus.getStatusCode());
  Assert.assertEquals("default", httpStatus.getReasonPhrase());
}
 
Example #22
Source File: ResponseImplTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testStatuInfoForOKStatus() {
    StatusType si = new ResponseImpl(200, "").getStatusInfo();
    assertNotNull(si);
    assertEquals(200, si.getStatusCode());
    assertEquals(Status.Family.SUCCESSFUL, si.getFamily());
    assertEquals("OK", si.getReasonPhrase());
}
 
Example #23
Source File: ResponseImplTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testStatuInfoForClientErrorStatus2() {
    StatusType si = new ResponseImpl(499, "").getStatusInfo();
    assertNotNull(si);
    assertEquals(499, si.getStatusCode());
    assertEquals(Status.Family.CLIENT_ERROR, si.getFamily());
    assertEquals("", si.getReasonPhrase());
}
 
Example #24
Source File: HttpStatusManager.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
public void addStatusType(StatusType status) {
  if (statusMap.containsKey(status.getStatusCode())) {
    throw new IllegalStateException("repeated status code: " + status.getStatusCode());
  }

  statusMap.put(status.getStatusCode(), status);
}
 
Example #25
Source File: HttpStatusManager.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
public StatusType getOrCreateByStatusCode(int code) {
  StatusType statusType = statusMap.get(code);
  if (statusType != null) {
    return statusType;
  }

  statusType = new HttpStatus(code, "");
  addStatusType(statusType);

  return statusType;
}
 
Example #26
Source File: ResponseImplTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testStatuInfoForClientErrorStatus() {
    StatusType si = new ResponseImpl(400, "").getStatusInfo();
    assertNotNull(si);
    assertEquals(400, si.getStatusCode());
    assertEquals(Status.Family.CLIENT_ERROR, si.getFamily());
    assertEquals("Bad Request", si.getReasonPhrase());
}
 
Example #27
Source File: DefaultExceptionConverter.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
@Override
public InvocationException convert(@Nullable Invocation invocation, Throwable throwable, StatusType genericStatus) {
  LOGGER.error("convert unknown exception to InvocationException.", throwable);

  String msg = throwable.getMessage();
  if (msg == null) {
    msg = "Unexpected exception when processing.";
  }

  return new InvocationException(genericStatus, ExceptionConverter.getGenericCode(genericStatus),
      msg, throwable);
}
 
Example #28
Source File: ProcessInstanceManagementResourceTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings({"rawtypes", "unchecked"})
@BeforeEach
public void setup() {

    responseBuilder = mock(ResponseBuilder.class);
    Response response = mock(Response.class);

    when((runtimeDelegate).createResponseBuilder()).thenReturn(responseBuilder);
    lenient().when((responseBuilder).status(any(StatusType.class))).thenReturn(responseBuilder);
    lenient().when((responseBuilder).entity(any())).thenReturn(responseBuilder);
    lenient().when((responseBuilder).build()).thenReturn(response);

    application = mock(Application.class);
    processes = mock(Processes.class);
    Process process = mock(Process.class);
    ProcessInstances instances = mock(ProcessInstances.class);
    processInstance = mock(ProcessInstance.class);
    error = mock(ProcessError.class);

    lenient().when(processes.processById(anyString())).thenReturn(process);
    lenient().when(process.instances()).thenReturn(instances);
    lenient().when(instances.findById(anyString())).thenReturn(Optional.of(processInstance));
    lenient().when(processInstance.error()).thenReturn(Optional.of(error));
    lenient().when(processInstance.id()).thenReturn("abc-def");
    lenient().when(processInstance.status()).thenReturn(ProcessInstance.STATE_ACTIVE);
    lenient().when(error.failedNodeId()).thenReturn("xxxxx");
    lenient().when(error.errorMessage()).thenReturn("Test error message");

    lenient().when(application.unitOfWorkManager()).thenReturn(new DefaultUnitOfWorkManager(new CollectingUnitOfWorkFactory()));
    resource = spy(new ProcessInstanceManagementResource(processes, application));
}
 
Example #29
Source File: HttpHelper.java    From cloudbreak with Apache License 2.0 4 votes vote down vote up
public Pair<StatusType, Integer> getContentLength(String url) {
    WebTarget target = client.target(url);
    try (Response response = target.request().head()) {
        return new ImmutablePair<>(response.getStatusInfo(), response.getLength());
    }
}
 
Example #30
Source File: AbstractResponseContextImpl.java    From cxf with Apache License 2.0 4 votes vote down vote up
public void setStatusInfo(StatusType status) {
    setStatus(status.getStatusCode());
}