下面列出了javax.ws.rs.NotSupportedException#javax.ws.rs.ClientErrorException 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Rename an environment across all integrations.
*/
@PUT
@Path("{env}")
@Consumes(MediaType.APPLICATION_JSON)
public void renameEnvironment(@NotNull @PathParam("env") @Parameter(required = true) String environment, @NotNull @Parameter(required = true) String newEnvironment) {
validateEnvironment(ENVIRONMENT, environment);
validateEnvironment("newEnvironment", newEnvironment);
// ignore request if names are the same
if (environment.equals(newEnvironment)) {
return;
}
// check if the new environment name is in use
if (fetchEnvironment(newEnvironment).isPresent()) {
throw new ClientErrorException("Duplicate environment " + newEnvironment, Response.Status.BAD_REQUEST);
}
// find existing environment
final Environment env = getEnvironment(environment);
// update environment name
getDataManager().update(new Environment.Builder().createFrom(env).name(newEnvironment).build());
}
/**
* We should get an exception if the property value
* is missing from the clause
* @throws IOException
*/
@Test
public void exceptionOnMissingPropertyValue() throws IOException {
int numOfEntities = 1;
String collectionName = "thesethings";
//create our test entities
generateTestEntities(numOfEntities, collectionName);
//Issue an invalid query
String query = "select * where name != ";
try {
QueryParameters params = new QueryParameters().setQuery(query);
this.app().collection(collectionName).get(params);
fail("This should throw an exception");
} catch (ClientErrorException uie) {
//Check for an exception
assertEquals(400, uie.getResponse().getStatus());
}
}
public PulsarAdminException getApiException(Response response) {
if (response.getStatusInfo().equals(Response.Status.OK)) {
return null;
}
try {
if (response.getStatus() >= 500) {
throw new ServerErrorException(response);
} else if (response.getStatus() >= 400) {
throw new ClientErrorException(response);
} else {
throw new WebApplicationException(response);
}
} catch (Exception e) {
return getApiException(e);
}
}
@Test
public void exportPostCollectionNullPointerStorageProvider() throws Exception {
HashMap<String, Object> payload = payloadBuilder();
HashMap<String, Object> properties = ( HashMap<String, Object> ) payload.get( "properties" );
//remove storage_info field
properties.remove( "storage_provider" );
try {
management().orgs().org( clientSetup.getOrganizationName() )
.app().addToPath( clientSetup.getAppUuid() )
.addToPath( "collection" ).addToPath( "users" )
.addToPath( "export" ).post( ApiResponse.class,
payload );
fail( "Should not have passed as we were missing an important part of the payload" );
}
catch ( ClientErrorException uie ) {
assertEquals( Response.Status.BAD_REQUEST.getStatusCode(), uie.getResponse().getStatus() );
}
}
/**
* Stop Integration.
*/
@PUT
@Path("integrations/{id}/deployments/stop")
@Produces(MediaType.APPLICATION_JSON)
public void stopIntegration(@Context final SecurityContext sec, @NotNull @PathParam("id") @Parameter(required = true) final String integrationId) {
final Integration integration = getIntegration(integrationId);
IntegrationDeploymentHandler.TargetStateRequest targetState = new IntegrationDeploymentHandler.TargetStateRequest(IntegrationDeploymentState.Unpublished);
// find current deployment
final String id = integration.getId().get();
final IntegrationDeployment deployment = dataMgr.fetchAllByPropertyValue(IntegrationDeployment.class, PROPERTY_INTEGRATION_ID, id)
.filter(d -> d.getTargetState() == IntegrationDeploymentState.Published)
.findFirst()
.orElse(null);
if (deployment != null) {
deploymentHandler.updateTargetState(id, deployment.getVersion(), targetState);
} else {
throw new ClientErrorException("Integration " + integrationId + " is not published", Response.Status.FORBIDDEN);
}
}
private void expectNotFound(PermissionsTest.InvocationWithResponse invocation, RealmResource realm) {
int statusCode = 0;
try {
AtomicReference<Response> responseReference = new AtomicReference<>();
invocation.invoke(realm, responseReference);
Response response = responseReference.get();
if (response != null) {
statusCode = response.getStatus();
} else {
fail("Expected failure");
}
} catch (ClientErrorException e) {
statusCode = e.getResponse().getStatus();
}
assertEquals(404, statusCode);
}
public Credential getCredentialByEnvCrn(String envCrn) {
CredentialResponse credentialResponse = null;
try {
credentialResponse = credentialEndpoint.getByEnvironmentCrn(envCrn);
} catch (ClientErrorException e) {
try (Response response = e.getResponse()) {
if (Response.Status.NOT_FOUND.getStatusCode() == response.getStatus()) {
throw new BadRequestException(String.format("Credential not found by environment CRN: %s", envCrn), e);
}
String errorMessage = webApplicationExceptionMessageExtractor.getErrorMessage(e);
throw new CloudbreakServiceException(String.format("Failed to get credential: %s", errorMessage), e);
}
}
SecretResponse secretResponse = credentialResponse.getAttributes();
String attributes = secretService.getByResponse(secretResponse);
return new Credential(credentialResponse.getCloudPlatform(), credentialResponse.getName(), attributes, credentialResponse.getCrn());
}
@Test
public void shouldGetConflictWhenCreatingNewBuildConfigurationWithTheSameNameAndProjectId() throws ClientException {
BuildConfigurationClient client = new BuildConfigurationClient(RestClientConfiguration.asUser());
BuildConfiguration bc = client.getSpecific(configurationId);
BuildConfiguration duplicate = BuildConfiguration.builder()
.name(bc.getName())
.buildScript(bc.getBuildScript())
.project(bc.getProject())
.environment(bc.getEnvironment())
.parameters(bc.getParameters())
.scmRepository(bc.getScmRepository())
.buildType(bc.getBuildType())
.build();
assertThatThrownBy(() -> client.createNew(duplicate)).hasCauseInstanceOf(ClientErrorException.class)
.has(
new Condition<Throwable>(
(e -> ((ClientErrorException) e.getCause()).getResponse().getStatus() == 409),
"HTTP 409 Conflict"));
}
public String QuerryBillStatus(String merchant_trans_id, String good_code, String trans_id, String merchant_code,
String secure_hash) throws ClientErrorException {
WebTarget resource = webTarget;
if (merchant_code != null) {
resource = resource.queryParam("merchant_code", merchant_code);
}
if (good_code != null) {
resource = resource.queryParam("good_code", good_code);
}
if (merchant_trans_id != null) {
resource = resource.queryParam("merchant_trans_id", merchant_trans_id);
}
if (secure_hash != null) {
resource = resource.queryParam("secure_hash", secure_hash);
}
if (trans_id != null) {
resource = resource.queryParam("trans_id", trans_id);
}
resource = resource.path("QuerryBillStatus");
return resource.request(javax.ws.rs.core.MediaType.APPLICATION_JSON).get(String.class);
}
@Test
public void exportPostCollectionNullPointerStorageInfo() throws Exception {
HashMap<String, Object> payload = payloadBuilder();
HashMap<String, Object> properties = ( HashMap<String, Object> ) payload.get( "properties" );
//remove storage_info field
properties.remove( "storage_info" );
try {
management().orgs().org( clientSetup.getOrganizationName() )
.app().addToPath( clientSetup.getAppUuid() )
.addToPath( "collection" ).addToPath( "users" )
.addToPath( "export" ).post( ApiResponse.class,
payload );
fail( "Should not have passed as we were missing an important part of the payload" );
}
catch ( ClientErrorException uie ) {
assertEquals( Response.Status.BAD_REQUEST.getStatusCode(), uie.getResponse().getStatus() );
}
}
/**
* We should get an exception if the clause contains
* an invalid operator.
* (eg. "name != 'go'" instead of "NOT name = 'go'")
* @throws IOException
*/
@Test
public void exceptionOnInvalidOperator() throws IOException {
int numOfEntities = 1;
String collectionName = "things";
//create our test entities
generateTestEntities(numOfEntities, collectionName);
//Issue an invalid query
String query = "select * where name != 'go'";
try {
QueryParameters params = new QueryParameters().setQuery(query);
this.app().collection(collectionName).get(params);
fail("This should throw an exception");
} catch (ClientErrorException uie) {
//Check for an exception
assertEquals(400, uie.getResponse().getStatus());
}
}
public static String getErrorMessage(Exception ex) {
if (ex instanceof ClientErrorException) {
try {
String responseJson = ((ClientErrorException) ex).getResponse().readEntity(String.class);
if (JsonUtil.isValid(responseJson)) {
JsonNode jsonNode = JsonUtil.readTree(responseJson);
if (jsonNode.has("message")) {
return jsonNode.get("message").asText();
}
}
return responseJson;
} catch (IOException ignore) {
}
}
return ex.getMessage();
}
/**
* We should get an exception if the clause contains
* a string that is surrounded by double-quotes
* @throws IOException
*/
@Test
public void exceptionOnDoubleQuotes() throws IOException {
int numOfEntities = 1;
String collectionName = "otherthings";
//create our test entities
generateTestEntities(numOfEntities, collectionName);
//Issue an invalid query
String query = "select * where NOT name = \"go\"";
try {
QueryParameters params = new QueryParameters().setQuery(query);
this.app().collection(collectionName).get(params);
fail("This should throw an exception");
} catch (ClientErrorException uie) {
//Check for an exception
assertEquals(400, uie.getResponse().getStatus());
}
}
public static Class<?> getWebApplicationExceptionClass(Response exResponse,
Class<?> defaultExceptionType) {
int status = exResponse.getStatus();
Class<?> cls = EXCEPTIONS_MAP.get(status);
if (cls == null) {
int family = status / 100;
if (family == 3) {
cls = RedirectionException.class;
} else if (family == 4) {
cls = ClientErrorException.class;
} else if (family == 5) {
cls = ServerErrorException.class;
}
}
return cls == null ? defaultExceptionType : cls;
}
private static OIDCProviderDiscoveryDocument getDiscoveryDocument(final String issuer) {
String discoveryDocumentURL = issuer + "/.well-known/openid-configuration";
WebClient client = WebClient.create(discoveryDocumentURL, List.of(new JacksonJsonProvider())).
accept(MediaType.APPLICATION_JSON);
try {
return client.get(OIDCProviderDiscoveryDocument.class);
} catch (ClientErrorException e) {
LOG.error("While getting the Discovery Document at {}", discoveryDocumentURL, e);
if (e instanceof javax.ws.rs.NotFoundException) {
throw new NotFoundException("Discovery Document cannot be found at " + discoveryDocumentURL);
} else {
SyncopeClientException sce = SyncopeClientException.build(ClientExceptionType.Unknown);
sce.getElements().add(e.getMessage());
throw sce;
}
}
}
@Test
void investFailure() {
final ControlApi control = mock(ControlApi.class);
doThrow(new ClientErrorException(Response.Status.FORBIDDEN)).when(control)
.invest(any());
final Api<ControlApi> ca = mockApi(control);
final PaginatedApi<LoanImpl, LoanApi> la = mockApi();
final int loanId = 1;
final Loan loan = mock(LoanImpl.class);
when(loan.getId()).thenReturn(loanId);
when(loan.getAmount()).thenReturn(Money.from(200.0));
when(loan.getRemainingInvestment()).thenReturn(Money.from(200.0));
when(la.execute(any())).thenReturn(loan);
final Zonky z = mockZonky(ca, la);
final Loan l = z.getLoan(loanId);
final InvestmentImpl i = mockInvestment(l, 200);
assertThat(z.invest(l, 200)
.getFailureType()).contains(InvestmentFailureType.UNKNOWN);
}
@Test
public void ttlNan() throws Exception {
Map<String, String> payload = hashMap( "grant_type", "password" )
.map( "username", clientSetup.getUsername() )
.map( "password", clientSetup.getPassword() )
.map( "ttl", "derp" );
Response.Status responseStatus = null;
try {
management.token().post( JsonNode.class, payload );
}
catch ( ClientErrorException uie ) {
responseStatus = Response.Status.fromStatusCode( uie.getResponse().getStatus());
}
assertEquals( Response.Status.BAD_REQUEST, responseStatus );
}
/**
* We should get an exception if the clause contains
* a string that is not properly quoted
* @throws IOException
*/
@Test
public void exceptionOnMissingQuotes() throws IOException {
int numOfEntities = 1;
String collectionName = "stillotherthings";
//create our test entities
generateTestEntities(numOfEntities, collectionName);
//Issue an invalid query
String query = "select * where name != go";
try {
QueryParameters params = new QueryParameters().setQuery(query);
this.app().collection(collectionName).get(params);
fail("This should throw an exception");
} catch (ClientErrorException uie) {
//Check for an exception
assertEquals(400, uie.getResponse().getStatus());
}
}
/**
* {@inheritDoc}
*/
@Override
public Response toResponse(final ClientErrorException exception) {
if (L.isDebugEnabled()) {
L.debug(Strings.substitute(R.getString("D-REST-JERSEY-MAPPER#0002"), Maps.hash("statusCode", exception.getResponse().getStatus())));
}
ErrorMessage error = ErrorMessages.create(exception)
.code(ErrorCode.get(exception.getResponse().getStatus()).code())
.resolve()
.get();
L.warn(error.log(), exception);
return Response.status(exception.getResponse().getStatusInfo())
.entity(error)
.type(MediaType.APPLICATION_JSON)
.build();
}
@Test
public void updateUserWithNewUsernameAccessingViaOldUsername() {
switchEditUsernameAllowedOn(true);
createUser();
try {
UserResource user = realm.users().get("user1");
UserRepresentation userRep = user.toRepresentation();
userRep.setUsername("user1");
updateUser(user, userRep);
realm.users().get("user11").toRepresentation();
fail("Expected failure");
} catch (ClientErrorException e) {
assertEquals(404, e.getResponse().getStatus());
} finally {
switchEditUsernameAllowedOn(false);
}
}
@Test
public void failUploadFileWithBadFileName() throws IOException, ArchivaRestServiceException {
FileUploadService service = getUploadService();
try {
Path file = getProjectDirectory().resolve("src/test/repositories/snapshot-repo/org/apache/archiva/archiva-model/1.4-M4-SNAPSHOT/archiva-model-1.4-M4-20130425.081822-1.jar");
final Attachment fileAttachment = new AttachmentBuilder().object(Files.newInputStream(file)).contentDisposition(new ContentDisposition("form-data; filename=\"/../TestFile.testext\"; name=\"files[]\"")).build();
MultipartBody body = new MultipartBody(fileAttachment);
try {
service.post(body);
fail("FileNames with path contents should not be allowed.");
} catch (ClientErrorException e) {
assertEquals(422, e.getResponse().getStatus());
}
} finally {
service.clearUploadedFiles();
}
}
@ParameterizedTest
@ArgumentsSource(SessionType.class)
void knownFail(final SessionInfo sessionType) {
final boolean isDryRun = sessionType.isDryRun();
final Tenant t = mockTenant(zonky, isDryRun);
final Response failure = Response.status(400)
.entity(InvestmentFailureType.INSUFFICIENT_BALANCE.getReason()
.get())
.build();
when(zonky.invest(notNull(), anyInt())).thenReturn(InvestmentResult.failure(new BadRequestException(failure)));
final Investor i = Investor.build(t);
final RecommendedLoan r = DESCRIPTOR.recommend(Money.from(200))
.orElse(null);
final Either<InvestmentFailureType, Money> result = i.invest(r);
if (isDryRun) { // the endpoint is not actually called, therefore cannot return error
assertThat(result.get()).isEqualTo(Money.from(200));
} else {
assertThat((Predicate<ClientErrorException>) result.getLeft())
.isEqualTo(InvestmentFailureType.INSUFFICIENT_BALANCE);
}
}
@ParameterizedTest
@ArgumentsSource(SessionType.class)
void unknownFail(final SessionInfo sessionType) {
final boolean isDryRun = sessionType.isDryRun();
final Tenant t = mockTenant(zonky, isDryRun);
final Response failure = Response.status(400)
.build();
when(zonky.invest(notNull(), anyInt())).thenReturn(InvestmentResult.failure(new BadRequestException(failure)));
final Investor i = Investor.build(t);
final RecommendedLoan r = DESCRIPTOR.recommend(Money.from(200))
.orElse(null);
final Either<InvestmentFailureType, Money> result = i.invest(r);
if (isDryRun) { // the endpoint is not actually called, therefore cannot return error
assertThat(result.get()).isEqualTo(Money.from(200));
} else {
assertThat((Predicate<ClientErrorException>) result.getLeft()).isEqualTo(InvestmentFailureType.UNKNOWN);
}
}
@Override
public void run() {
try {
admin().realms().realm(realm.getRealm()).roles().create(role);
} catch (ClientErrorException e) {
if (e.getMessage().endsWith("409 Conflict") && ignoreConflicts) {
log.warn("Ignoring conflict when creating a realm role: " + role.getName());
role = admin().realms().realm(realm.getRealm()).roles().get(role.getName()).toRepresentation();
} else {
throw e;
}
}
// we need the id but it's not returned by REST API - we have to perform a get on the created role and save the returned id
RoleRepresentation rr = admin().realms().realm(realm.getRealm()).roles().get(role.getName()).toRepresentation();
realmRoleIdMap.put(rr.getName(), rr.getId());
}
@Test
void longerDelayWhenHttp429Encountered() {
final Availability a = new AvailabilityImpl(s);
final Instant now = Instant.now();
setClock(Clock.fixed(now, Defaults.ZONE_ID));
final Exception ex = new ClientErrorException(Response.Status.TOO_MANY_REQUESTS);
final boolean reg = a.registerException(ex);
assertSoftly(softly -> {
softly.assertThat(reg)
.isTrue();
softly.assertThat(a.isAvailable())
.isFalse();
softly.assertThat(a.nextAvailabilityCheck())
.isEqualTo(now.plus(Duration.ofSeconds(60 + 1)));
});
}
@Test
public void exportPostOrganizationNullPointerStorageProvider() throws Exception {
HashMap<String, Object> payload = payloadBuilder();
HashMap<String, Object> properties = ( HashMap<String, Object> ) payload.get( "properties" );
//remove storage_info field
properties.remove( "storage_provider" );
try {
management().orgs().org( clientSetup.getOrganizationName() )
.addToPath( "export" ).post( ApiResponse.class, payload );
fail( "Should not have passed as we were missing an important part of the payload" );
}
catch ( ClientErrorException uie ) {
assertEquals( Response.Status.BAD_REQUEST.getStatusCode(), uie.getResponse().getStatus() );
}
}
/**
* We should get an exception if the property name
* is missing from the clause
* @throws IOException
*/
@Test
public void exceptionOnMissingProperty() throws IOException {
int numOfEntities = 1;
String collectionName = "yetotherthings";
//create our test entities
generateTestEntities(numOfEntities, collectionName);
//Issue an invalid query
String query = "select * where != 'go'";
try {
QueryParameters params = new QueryParameters().setQuery(query);
this.app().collection(collectionName).get(params);
fail("This should throw an exception");
} catch (ClientErrorException uie) {
//Check for an exception
assertEquals(400, uie.getResponse().getStatus());
}
}
/**
* Test to ensure that an error is returned when
* attempting to POST multiple entities to the
* same collection with the same name
*/
@Test
public void duplicateNamePrevention() {
String collectionName = "things";
Entity entity = new Entity();
entity.put("name", "enzo");
//Create an entity named "enzo" in the "things" collection
entity = this.app().collection(collectionName).post(entity);
waitForQueueDrainAndRefreshIndex();
try {
// Try to create a second entity in "things" with the name "enzo".
this.app().collection(collectionName).post(entity);
// fail if the POST did not return an exception
fail("Should not have created duplicate entity");
} catch (ClientErrorException uie) {
//Check for an exception
assertEquals(400, uie.getResponse().getStatus());
}
}
public BookStorePerRequest(@Context HttpHeaders headers,
@HeaderParam("BOOK") List<String> bookIds) {
if (!bookIds.contains("3")) {
throw new ClientErrorException(Response.status(400).type("text/plain")
.entity("Constructor: Header value 3 is required").build());
}
httpHeaders = headers;
this.bookIds = bookIds;
init();
}
@Test
public void putAddToOrganizationFail() throws Exception {
Map<String, Object> originalProperties = getRemoteTestProperties();
try {
setTestProperty(PROPERTIES_SYSADMIN_APPROVES_ADMIN_USERS, "false");
setTestProperty(PROPERTIES_SYSADMIN_APPROVES_ORGANIZATIONS, "false");
setTestProperty(PROPERTIES_ADMIN_USERS_REQUIRE_CONFIRMATION, "false");
setTestProperty(PROPERTIES_DEFAULT_SYSADMIN_EMAIL, "[email protected]");
String t = this.getAdminToken().getAccessToken();
Form form = new Form();
form.param( "foo", "bar" );
try {
this.org().getTarget(false).path("/users/[email protected]")
.queryParam("access_token", t)
.request()
.accept(MediaType.APPLICATION_JSON)
.put( javax.ws.rs.client.Entity.form(form) );
} catch (ClientErrorException e) {
assertEquals("Should receive a 404 Not Found", 404, e.getResponse().getStatus());
}
} finally {
setTestProperties(originalProperties);
}
}