下面列出了怎么用javax.ws.rs.core.Response.StatusType的API类实例代码及写法,或者点击链接到github查看源代码。
@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);
}
@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;
}
@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);
}
@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;
}
};
}
@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));
}
@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);
}
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"));
}
}
}
public static InvocationException create(StatusType status,
Object exceptionOrErrorData) {
if (InvocationException.class.isInstance(exceptionOrErrorData)) {
return (InvocationException) exceptionOrErrorData;
}
return doCreate(status, exceptionOrErrorData);
}
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);
}
@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;
}
};
}
@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;
}
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);
}
@Override
public StatusType getStatusType() {
if (statusType == null) {
statusType = new HttpStatus(serverResponse.getStatusCode(), serverResponse.getStatusMessage());
}
return statusType;
}
@Override
public StatusType getStatusType() {
if (statusType == null) {
statusType = new HttpStatus(clientResponse.statusCode(), clientResponse.statusMessage());
}
return statusType;
}
@Test
public void getStatusType() {
StatusType status = response.getStatusType();
Assert.assertSame(status, response.getStatusType());
Assert.assertEquals(123, httpStatus.getStatusCode());
Assert.assertEquals("default", httpStatus.getReasonPhrase());
}
@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());
}
@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());
}
public void addStatusType(StatusType status) {
if (statusMap.containsKey(status.getStatusCode())) {
throw new IllegalStateException("repeated status code: " + status.getStatusCode());
}
statusMap.put(status.getStatusCode(), status);
}
public StatusType getOrCreateByStatusCode(int code) {
StatusType statusType = statusMap.get(code);
if (statusType != null) {
return statusType;
}
statusType = new HttpStatus(code, "");
addStatusType(statusType);
return statusType;
}
@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);
}
@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);
}
@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());
}
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();
}
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));
}
@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);
}
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);
}
}
@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);
}
@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;
}
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());
}
}
private static HttpResponseStatus getStatus(final ContainerResponse containerResponse) {
final StatusType statusInfo = containerResponse.getStatusInfo();
return statusInfo instanceof Status ? RESPONSE_STATUSES.get(statusInfo) :
HttpResponseStatus.of(statusInfo.getStatusCode(), statusInfo.getReasonPhrase());
}