@Test public void getStatusType() { new Expectations() { { clientResponse.statusCode(); result = 123; clientResponse.statusMessage(); result = "test"; } }; StatusType type = response.getStatusType(); Assert.assertSame(type, response.getStatusType()); Assert.assertEquals(123, type.getStatusCode()); Assert.assertEquals("test", type.getReasonPhrase()); }
@Override public Response toResponse(@NonNull Exception exception) { ResponseBuilder builder; StatusType statusInfo; if (exception instanceof WebApplicationException) { Response response = ((WebApplicationException) exception).getResponse(); builder = Response.fromResponse(response); statusInfo = response.getStatusInfo(); } else { builder = Response.serverError(); statusInfo = Status.INTERNAL_SERVER_ERROR; } SimpleExceptionJson simpleExceptionJson = new SimpleExceptionJson(statusInfo.getReasonPhrase(), statusInfo.getStatusCode(), exception.getMessage()); builder.entity(simpleExceptionJson); builder.type("application/problem+json"); if (statusInfo.getFamily() == Family.CLIENT_ERROR) { log.debug("Got client Exception", exception); } else { log.error("Sending error to client", exception); } return builder.build(); }
protected javax.ws.rs.core.Response davPropFind(Long id, UriInfo uriInfo, String depth, Providers providers) throws AuthenticationException, AuthorisationException, ServiceException { final Response folder = new Response(new HRef(uriInfo.getRequestUri()), null, null, null, new PropStat(new Prop(new DisplayName("My Collection"), new CreationDate(new Date()), new GetLastModified(new Date()), COLLECTION), new Status((StatusType) OK))); if (depth.equals(DEPTH_0) || id == null) { return javax.ws.rs.core.Response.status(MULTI_STATUS).entity(new MultiStatus(folder)).build(); } final Collection<Response> responses = new LinkedList<Response>(singletonList(folder)); Iterator<FileOutVO> it = WebUtil.getServiceLocator().getFileService().getFiles(getAuth(), getFileModule(), id, null, null, null).iterator(); if (it != null) { while (it.hasNext()) { FileOutVO out = it.next(); // responses.add(buildResponse(f, uriInfo.getAbsolutePathBuilder().path(format("%s", c.getMatchCode())).build(), providers)); FilePathSplitter filePath = new FilePathSplitter(out.getFileName()); String extension = filePath.getExtension(); if (isTempFile(extension) || isEditableFile(extension)) { responses.add(buildResponse(out, uriInfo.getAbsolutePathBuilder().path(getDavFileName(out)).build(), providers)); } } } return javax.ws.rs.core.Response.status(MULTI_STATUS).entity(new MultiStatus(responses.toArray(new Response[0]))).build(); }
/** * Creates an ErrorContent for a HTTP {@link ErrorSource#CLIENT_ERROR client}- or * {@link ErrorSource#SERVER_ERROR server} error. * * @param position the content position * @param response the HTTP response. This must either by a client-error response or a server-error response. * @param startedTs the timestamp when fetching the content has started. * @return ErrorContent * @throws IllegalArgumentException if the response is not a client- or server error response. */ public static ErrorContent httpErrorContent(final String source, final Position position, final Response response, final long startedTs) { final StatusType statusInfo = response.getStatusInfo(); final Family family = statusInfo.getFamily(); checkArgument(HTTP_ERRORS.contains(family), "Response is not a HTTP client or server error"); final ErrorSource errorSource = family == CLIENT_ERROR ? ErrorSource.CLIENT_ERROR : ErrorSource.SERVER_ERROR; return new ErrorContent(source, position, statusInfo.getReasonPhrase(), errorSource, startedTs); }
static void status(final StatusType statusInfo, final Family expectedFamily, final Status... expectedStatuses) { requireNonNull(statusInfo, "null statusInfo"); final Family actualFamily = statusInfo.getFamily(); final int statusCode = statusInfo.getStatusCode(); final String reasonPhrase = statusInfo.getReasonPhrase(); logger.debug("-> response.status: {} {}", statusCode, reasonPhrase); if (expectedFamily != null) { assertEquals(actualFamily, expectedFamily); } if (expectedStatuses != null && expectedStatuses.length > 0) { assertTrue( Stream.of(expectedStatuses).map(Status::getStatusCode) .filter(v -> v == statusCode) .findAny() .isPresent() ); } }
@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; } }; }
/** * Builds error response from exception. * * @param status the response status * @param druidQuery failed Druid Query if available or null * @param cause exception * @param writer The Writer to use for writing errors * * @return Response */ public static Response makeErrorResponse( StatusType status, DruidQuery<?> druidQuery, Throwable cause, ObjectWriter writer ) { String reason = null; String description = null; // do not return JAX-RS processing exception, only the cause if (cause instanceof ProcessingException && cause.getCause() != null) { cause = cause.getCause(); } if (cause != null) { reason = cause.getClass().getName(); description = String.valueOf(cause.getMessage()); } return makeErrorResponse(status.getStatusCode(), reason, description, druidQuery, writer); }
public URI insertAppointment(AppointmentType resource) { Response response = client.target(connection) .path("/rest/api/appointments") .request() // overrides previous headers: Content-Type, Content-Language, Content-Encoding .post(xml(resource)); response.close(); if (response.getStatus() >= HTTP_BAD_REQUEST) { StatusType stat = response.getStatusInfo(); throw new IllegalStateException(stat.getStatusCode() + "/" + stat.getFamily().name() + " " + stat.getReasonPhrase()); } return response.getLocation(); }
public void updateIssueWithoutCharset(int issueId, ResourcesType resource) { Response response = client.target(connection) .path("/rest/api/2.0-alpha1/issues/{id}") .resolveTemplate("id", issueId) .request() // overrides previous headers: Content-Type, Content-Language, Content-Encoding .put(xml(resource)); response.close(); if (response.getStatus() >= HTTP_BAD_REQUEST) { StatusType stat = response.getStatusInfo(); throw new IllegalStateException(stat.getStatusCode() + "/" + stat.getFamily().name() + " " + stat.getReasonPhrase()); } }
public void updateIssue(int issueId, ResourcesType resource) { Response response = client.target(connection) .path("/rest/api/2.0-alpha1/issues/{id}") .resolveTemplate("id", issueId) .request() // overrides previous headers: Content-Type, Content-Language, Content-Encoding .put(entity(resource, MediaType.valueOf(APPLICATION_XML + "; charset=UTF-8"))); response.close(); if (response.getStatus() >= HTTP_BAD_REQUEST) { StatusType stat = response.getStatusInfo(); throw new IllegalStateException(stat.getStatusCode() + "/" + stat.getFamily().name() + " " + stat.getReasonPhrase()); } }
public void updateIssueAsJson(int issueId, ResourcesType resource) { Response response = client.target(connection) .path("/rest/api/2.0-alpha1/issues/{id}") .resolveTemplate("id", issueId) .request() // overrides previous headers: Content-Type, Content-Language, Content-Encoding .put(entity(resource, MediaType.valueOf(APPLICATION_JSON))); response.close(); if (response.getStatus() >= HTTP_BAD_REQUEST) { StatusType stat = response.getStatusInfo(); throw new IllegalStateException(stat.getStatusCode() + "/" + stat.getFamily().name() + " " + stat.getReasonPhrase()); } }
public boolean updateIssueIfLast(int issueId, ResourcesType resource, String md5) { MultivaluedMap<String, Object> headers = new MultivaluedHashMap<>(); headers.putSingle("If-Match", md5); Response response = client.target(connection) .path("/rest/api/2.0-alpha1/issues/{id}") .resolveTemplate("id", issueId) .request() .headers(headers) // overrides previous headers: Content-Type, Content-Language, Content-Encoding .put(entity(resource, MediaType.valueOf(APPLICATION_XML + "; charset=UTF-8"))); response.close(); if (response.getStatus() != HTTP_OK && response.getStatus() != HTTP_NOT_MODIFIED) { StatusType stat = response.getStatusInfo(); throw new IllegalStateException(stat.getStatusCode() + "/" + stat.getFamily().name() + " " + stat.getReasonPhrase()); } return response.getStatus() == HTTP_OK; }
@Nonnull private static Response toResponseBadApiCall( @Nonnull final Logger log, @Nonnull final StatusType status, @Nonnull final Throwable exception) { assert log != null; assert status != null; assert exception != null; final ExceptionDTO exceptionDTO = new ExceptionDTO(exception, UTCTime.now()); log.info(createLogMessage("toResponseBadApiCall: Bad API call", exception, exceptionDTO, status)); // Explicitly set media type, to overwrite media content type. return status(status).entity(exceptionDTO). type(MediaType.APPLICATION_JSON_TYPE). build(); }
@Nonnull private static String createLogMessage( @Nonnull final String prefix, @Nonnull final Throwable exception, @Nonnull final ExceptionDTO exceptionDTO, @Nonnull final StatusType status) { assert prefix != null; assert exception != null; assert exceptionDTO != null; assert status != null; if (verboseMode) { return String.format(LOG_MESSAGE_TEMPLATE_VERBOSE, prefix, exceptionDTO.getReference(), status, status.getStatusCode(), exception.getMessage(), exceptionDTO.getTime()); } else { return String.format(LOG_MESSAGE_TEMPLATE_COMPACT, status, status.getStatusCode(), exception.getMessage()); } }
private String requestExtensionTypes() { StatusType status; String content; try { Response response = target.path("/osiam/extension-definition") .request(MediaType.APPLICATION_JSON) .header("Authorization", BEARER + sessionData.getAccessToken().getToken()) .get(); status = response.getStatusInfo(); content = response.readEntity(String.class); } catch (ProcessingException e) { throw new NullPointerException(); } checkAndHandleResponse(content, status); return content; }
/** * See {@link OsiamConnector#getCurrentUserBasic(AccessToken)} * * @deprecated The BasicUser class has been deprecated. Use {@link #getMe(AccessToken)} with OSIAM 3.x. This method * is going to go away with version 1.12 or 2.0. */ @Deprecated BasicUser getCurrentUserBasic(AccessToken accessToken) { checkAccessTokenIsNotNull(accessToken); StatusType status; String content; try { Response response = targetEndpoint.path("me").request(MediaType.APPLICATION_JSON) .header("Authorization", BEARER + accessToken.getToken()) .property(ClientProperties.CONNECT_TIMEOUT, getConnectTimeout()) .property(ClientProperties.READ_TIMEOUT, getReadTimeout()) .get(); status = response.getStatusInfo(); content = response.readEntity(String.class); } catch (ProcessingException e) { throw new ConnectionInitializationException(CONNECTION_SETUP_ERROR_STRING, e); } checkAndHandleResponse(content, status, accessToken); return mapToType(content, BasicUser.class); }
void deleteResource(String id, AccessToken accessToken) { checkArgument(!Strings.isNullOrEmpty(id), "The given id must not be null nor empty."); checkAccessTokenIsNotNull(accessToken); StatusType status; String content; try { Response response = targetEndpoint.path(typeName + "s").path(id).request(MediaType.APPLICATION_JSON) .header(AUTHORIZATION, BEARER + accessToken.getToken()) .property(ClientProperties.CONNECT_TIMEOUT, connectTimeout) .property(ClientProperties.READ_TIMEOUT, readTimeout) .delete(); status = response.getStatusInfo(); content = response.readEntity(String.class); } catch (ProcessingException e) { throw new ConnectionInitializationException(CONNECTION_SETUP_ERROR_STRING, e); } checkAndHandleResponse(content, status, accessToken); }
private String extractErrorMessage(String content, StatusType status) { String message; if (version == Version.OSIAM_2_LEGACY_SCHEMAS) { message = getScimErrorMessageLegacy(content); } else { message = getScimErrorMessage(content); } if (message == null) { message = getOAuthErrorMessage(content); } if (message == null) { message = String.format("Could not deserialize the error response for the HTTP status '%s'.", status.getReasonPhrase()); if (content != null) { message += String.format(" Original response: %s", content); } } return message; }
/** * @see OsiamConnector#validateAccessToken(AccessToken) */ AccessToken validateAccessToken(AccessToken tokenToValidate) { checkNotNull(tokenToValidate, "The tokenToValidate must not be null."); StatusType status; String content; try { Response response = targetEndpoint.path(TOKEN_VALIDATION_ENDPOINT) .request(MediaType.APPLICATION_JSON) .property(HttpAuthenticationFeature.HTTP_AUTHENTICATION_USERNAME, clientId) .property(HttpAuthenticationFeature.HTTP_AUTHENTICATION_PASSWORD, clientSecret) .property(ClientProperties.CONNECT_TIMEOUT, connectTimeout) .property(ClientProperties.READ_TIMEOUT, readTimeout) .header(AUTHORIZATION_HEADER, BEARER + tokenToValidate.getToken()) .post(Entity.json("")); status = response.getStatusInfo(); content = response.readEntity(String.class); } catch (ProcessingException e) { throw createGeneralConnectionInitializationException(e); } checkAndHandleResponse(content, status, tokenToValidate); return getAccessToken(content); }
void revokeAccessToken(AccessToken tokenToRevoke) { StatusType status; String content; try { Response response = targetEndpoint.path(TOKEN_REVOCATION_ENDPOINT) .request(MediaType.APPLICATION_JSON) .property(HttpAuthenticationFeature.HTTP_AUTHENTICATION_USERNAME, clientId) .property(HttpAuthenticationFeature.HTTP_AUTHENTICATION_PASSWORD, clientSecret) .property(ClientProperties.CONNECT_TIMEOUT, connectTimeout) .property(ClientProperties.READ_TIMEOUT, readTimeout) .header(AUTHORIZATION_HEADER, BEARER + tokenToRevoke.getToken()) .post(Entity.json("")); status = response.getStatusInfo(); content = response.readEntity(String.class); } catch (ProcessingException e) { throw createGeneralConnectionInitializationException(e); } checkAndHandleResponse(content, status, tokenToRevoke); }
void revokeAllAccessTokens(String id, AccessToken accessToken) { StatusType status; String content; try { Response response = targetEndpoint.path(TOKEN_REVOCATION_ENDPOINT).path(id) .request(MediaType.APPLICATION_JSON) .property(HttpAuthenticationFeature.HTTP_AUTHENTICATION_USERNAME, clientId) .property(HttpAuthenticationFeature.HTTP_AUTHENTICATION_PASSWORD, clientSecret) .property(ClientProperties.CONNECT_TIMEOUT, connectTimeout) .property(ClientProperties.READ_TIMEOUT, readTimeout) .header(AUTHORIZATION_HEADER, BEARER + accessToken.getToken()) .post(Entity.json("")); status = response.getStatusInfo(); content = response.readEntity(String.class); } catch (ProcessingException e) { throw createGeneralConnectionInitializationException(e); } checkAndHandleResponse(content, status, accessToken); }
void deleteClient(String deleteClientId, AccessToken accessToken) { StatusType status; String content; try { Response response = targetEndpoint.path(CLIENT_ENDPOINT).path(deleteClientId) .request(MediaType.APPLICATION_JSON) .property(HttpAuthenticationFeature.HTTP_AUTHENTICATION_USERNAME, clientId) .property(HttpAuthenticationFeature.HTTP_AUTHENTICATION_PASSWORD, clientSecret) .property(ClientProperties.CONNECT_TIMEOUT, connectTimeout) .property(ClientProperties.READ_TIMEOUT, readTimeout) .header(AUTHORIZATION_HEADER, BEARER + accessToken.getToken()) .delete(); status = response.getStatusInfo(); content = response.readEntity(String.class); } catch (ProcessingException e) { throw createGeneralConnectionInitializationException(e); } checkAndHandleResponse(content, status, accessToken); }
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; }
@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()); }
public HttpStatusManager() { for (Status status : Status.values()) { statusMap.put(status.getStatusCode(), status); } SPIServiceUtils.getAllService(StatusType.class).forEach(this::addStatusType); }
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; }
public void setStatusInfo(final StatusType statusInfo) { if (statusInfo != null) { statusCode = statusInfo.getStatusCode(); family = statusInfo.getFamily(); reasonPhrase = statusInfo.getReasonPhrase(); } else { setStatusInfo(Status.OK); } }
protected javax.ws.rs.core.Response davPropPatch(InputStream body, UriInfo uriInfo, Providers providers, HttpHeaders httpHeaders) throws IOException { final PropertyUpdate propertyUpdate = providers.getMessageBodyReader(PropertyUpdate.class, PropertyUpdate.class, new Annotation[0], APPLICATION_XML_TYPE).readFrom(PropertyUpdate.class, PropertyUpdate.class, new Annotation[0], APPLICATION_XML_TYPE, httpHeaders.getRequestHeaders(), body); // System.out.println("PATCH PROPERTIES: " + propertyUpdate.list()); /* TODO Patch properties in database. */ final Collection<PropStat> propstats = new LinkedList<PropStat>(); for (final RemoveOrSet removeOrSet : propertyUpdate.list()) { propstats.add(new PropStat(removeOrSet.getProp(), new Status((StatusType) FORBIDDEN))); } return javax.ws.rs.core.Response.status(MULTI_STATUS) .entity(new MultiStatus(new Response(new HRef(uriInfo.getRequestUri()), null, null, null, propstats))).build(); }
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(); }
@Override protected int assertSuccesfulAuthentication(final Response response) { final StatusType statusInfo = response.getStatusInfo(); final Family family = statusInfo.getFamily(); final int statusCode = statusInfo.getStatusCode(); final String reasonPhrase = statusInfo.getReasonPhrase(); assertEquals(family, SUCCESSFUL, "status: " + statusCode + " " + reasonPhrase); return statusCode; }
public static void assertSuccessful(Response response) { final StatusType responseStatus = response.getStatusInfo(); if (responseStatus.getFamily() != Status.Family.SUCCESSFUL) { final StringBuilder sb = new StringBuilder(); sb.append("Response ").append(responseStatus.getStatusCode()).append(" ").append(responseStatus.getReasonPhrase()); if (response.hasEntity()) { sb.append(", Response: ").append(response.readEntity(String.class)); } throw new AssertionError(sb); } }
/** * Check the response code. If successful, return the entity with the given return type, * otherwise throw an exception. * @param response * @param returnType * @return The entity from the given {@link ClientResponse} if available */ protected <T> T checkResponseAndGetOutput(String httpMethod, Builder builder, Response response, Class<T> returnType) { StatusType status = response.getStatusInfo(); if ( status != null && status.getFamily() == Family.SUCCESSFUL ) { return getSuccessfulResponse(response, returnType, status); } else { throw getUnsuccesfulResponseException(response); } }
/** * Get the return value for a successful response. * @param response * @param returnType * @param status * @return */ @SuppressWarnings("unchecked") protected <T> T getSuccessfulResponse(Response response, Class<T> returnType, StatusType status) { if ( returnType == null || status.getStatusCode() == Status.NO_CONTENT.getStatusCode() ) { return null; } else if ( returnType.isAssignableFrom(response.getClass()) ) { return (T)response; } else { return response.readEntity(returnType); } }