javax.ws.rs.BadRequestException Java Examples
The following examples show how to use
javax.ws.rs.BadRequestException.
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: CatalogResource.java From dremio-oss with Apache License 2.0 | 6 votes |
@GET @Path("/by-path/{segment:.*}") public CatalogEntity getCatalogItemByPath(@PathParam("segment") List<PathSegment> segments) throws NamespaceException, BadRequestException { List<String> pathList = new ArrayList<>(); for (PathSegment segment : segments) { pathList.add(segment.getPath()); } Optional<CatalogEntity> entity = catalogServiceHelper.getCatalogEntityByPath(pathList); if (!entity.isPresent()) { throw new NotFoundException(String.format("Could not find entity with path [%s]", pathList)); } return entity.get(); }
Example #2
Source File: PatchHandlerTest.java From trellis with Apache License 2.0 | 6 votes |
@Test void testNoLdpRsSupport() { when(mockTrellisRequest.getContentType()).thenReturn(APPLICATION_SPARQL_UPDATE); when(mockResourceService.supportedInteractionModels()).thenReturn(emptySet()); final PatchHandler patchHandler = new PatchHandler(mockTrellisRequest, insert, mockBundler, extensions, false, null, null); try (final Response res = assertThrows(BadRequestException.class, () -> patchHandler.initialize(mockParent, mockResource), "No exception for an unsupported IXN model!").getResponse()) { assertEquals(BAD_REQUEST, res.getStatusInfo(), ERR_RESPONSE_CODE); assertTrue(res.getLinks().stream().anyMatch(link -> link.getUri().toString().equals(UnsupportedInteractionModel.getIRIString()) && link.getRel().equals(LDP.constrainedBy.getIRIString())), "Missing Link header with constraint!"); } }
Example #3
Source File: ProviderParameterCalculator.java From cloudbreak with Apache License 2.0 | 6 votes |
private Mappable getMappable(ProviderParametersBase source, CloudPlatform cloudPlatform) { switch (cloudPlatform) { case AWS: return source.createAws(); case GCP: return source.createGcp(); case MOCK: return source.createMock(); case YARN: return source.createYarn(); case AZURE: return source.createAzure(); case OPENSTACK: return source.createOpenstack(); default: throw new BadRequestException(format("No mappable for cloudplatform [%s] and source [%s]", cloudPlatform, source.getClass())); } }
Example #4
Source File: VirtualNetworkWebResourceTest.java From onos with Apache License 2.0 | 6 votes |
/** * Tests adding of a null virtual link using POST via JSON stream. */ @Test public void testPostVirtualLinkNullJsonStream() { NetworkId networkId = networkId3; replay(mockVnetAdminService); WebTarget wt = target(); try { String reqLocation = "vnets/" + networkId.toString() + "/links"; wt.path(reqLocation) .request(MediaType.APPLICATION_JSON_TYPE) .post(Entity.json(null), String.class); fail("POST of null virtual link did not throw an exception"); } catch (BadRequestException ex) { assertThat(ex.getMessage(), containsString("HTTP 400 Bad Request")); } verify(mockVnetAdminService); }
Example #5
Source File: JSONProviderTest.java From cxf with Apache License 2.0 | 6 votes |
@Test(expected = BadRequestException.class) public void testIgnoreNamespacesPackageInfo() throws Exception { JSONProvider<Book2> p = new JSONProvider<>(); p.setIgnoreNamespaces(true); Book2 book = new Book2(123); book.setName("CXF"); ByteArrayOutputStream os = new ByteArrayOutputStream(); p.writeTo(book, Book2.class, Book2.class, Book2.class.getAnnotations(), MediaType.APPLICATION_JSON_TYPE, new MetadataMap<String, Object>(), os); String s = os.toString(); assertEquals("{\"thebook2\":{\"id\":123,\"name\":\"CXF\"}}", s); p.readFrom(Book2.class, null, Book2.class.getAnnotations(), MediaType.APPLICATION_JSON_TYPE, null, new ByteArrayInputStream(s.getBytes())); }
Example #6
Source File: ClusterTemplateTest.java From cloudbreak with Apache License 2.0 | 6 votes |
@Test(dataProvider = TEST_CONTEXT_WITH_MOCK) @Description( given = "there is a running cloudbreak", when = "a cluster template create request with null environment name is sent", then = "the cluster template is cannot be created" ) public void testCreateClusterTemplateWithoutEnvironmentName(TestContext testContext) { String generatedKey = resourcePropertyProvider().getName(); testContext.given(DistroXTemplateTestDto.class) .withEnvironmentName(null) .given(ClusterTemplateTestDto.class) .withDistroXTemplate() .when(clusterTemplateTestClient.createV4(), RunningParameter.key(generatedKey)) .expect(BadRequestException.class, RunningParameter.key(generatedKey) .withExpectedMessage("The environmentName cannot be null.")) .validate(); }
Example #7
Source File: AzureNetworkConnectorTest.java From cloudbreak with Apache License 2.0 | 6 votes |
@Test public void testGetNetworWhenAzureNetworkNull() { String networkId = "vnet-1"; String resourceGroupName = "resourceGroupName"; Network network = new Network(null, Map.of(AzureUtils.NETWORK_ID, networkId)); CloudCredential credential = new CloudCredential(); when(azureClientService.getClient(credential)).thenReturn(azureClient); when(azureUtils.getCustomResourceGroupName(network)).thenReturn(resourceGroupName); when(azureUtils.getCustomNetworkId(network)).thenReturn(networkId); when(azureClient.getNetworkByResourceGroup(resourceGroupName, networkId)).thenReturn(null); thrown.expect(BadRequestException.class); thrown.expectMessage(String.format("Network could not be fetch from Azure with resource group name: %s and network id: %s", resourceGroupName, networkId)); underTest.getNetworkCidr(network, credential); }
Example #8
Source File: WorldParamConverter.java From Web-API with MIT License | 6 votes |
@Override public CachedWorld fromString(String value) { // If we didn't request a world don't try to find one if (value == null) return null; if (!Util.isValidUUID(value)) throw new BadRequestException("Invalid world uuid"); CacheService srv = WebAPI.getCacheService(); Optional<CachedWorld> optWorld = srv.getWorld(UUID.fromString(value)); if (!optWorld.isPresent()) throw new NotFoundException("Could not find world with uuid " + value); return optWorld.get(); }
Example #9
Source File: TestSitePageResource.java From fenixedu-cms with GNU Lesser General Public License v3.0 | 6 votes |
@Test public void createNoNamePage() { // prepare User user = CmsTestUtils.createAuthenticatedUser("createNoNamePage"); Site site = CmsTestUtils.createSite(user, "createNoNamePage"); PageBean pageBean = new PageBean(); DateTime creationDate = new DateTime(); // execute try { String response = getSitePagesTarget(site).request().post(Entity.entity(pageBean.toJson(), MediaType.APPLICATION_JSON), String.class); fail(); } catch (BadRequestException ex) { LOGGER.debug(ex.getMessage()); } }
Example #10
Source File: VaultMock.java From component-runtime with Apache License 2.0 | 6 votes |
@POST @Path("decrypt/{tenant}") public VaultService.DecryptResponse decrypt(@HeaderParam("X-Vault-Token") final String token, @PathParam("tenant") final String tenant, final VaultService.DecryptRequest request) { if (!"client-test-token".equals(token) || tenant == null || tenant.isEmpty() || "x-talend-tenant-id".equals(tenant)) { throw new ForbiddenException(); } if (!"vault:v1:hcccVPODe9oZpcr/sKam8GUrbacji8VkuDRGfuDt7bg7VA==" .equals(request.getBatchInput().iterator().next().getCiphertext())) { throw new BadRequestException(); } final VaultService.DecryptResult result = new VaultService.DecryptResult(); result.setPlaintext(Base64.getEncoder().encodeToString("test".getBytes(StandardCharsets.UTF_8))); final VaultService.DecryptData data = new VaultService.DecryptData(); data.setBatchResults(singletonList(result)); final VaultService.DecryptResponse response = new VaultService.DecryptResponse(); response.setData(data); return response; }
Example #11
Source File: EnvironmentModificationServiceTest.java From cloudbreak with Apache License 2.0 | 6 votes |
@Test void editByNameSecurityAccessChangeHasSecurityAccessError() { ValidationResult validationResultError = ValidationResult.builder().error("sec access error").build(); SecurityAccessDto securityAccessDto = SecurityAccessDto.builder().withCidr("test").build(); EnvironmentEditDto environmentDto = EnvironmentEditDto.builder() .withAccountId(ACCOUNT_ID) .withSecurityAccess(securityAccessDto) .build(); Environment value = new Environment(); when(environmentService .findByNameAndAccountIdAndArchivedIsFalse(eq(ENVIRONMENT_NAME), eq(ACCOUNT_ID))).thenReturn(Optional.of(value)); when(environmentService.getValidatorService()).thenReturn(validatorService); when(validatorService.validateSecurityAccessModification(any(), any())).thenReturn(validationResultError); BadRequestException actual = assertThrows(BadRequestException.class, () -> environmentModificationServiceUnderTest.editByName(ENVIRONMENT_NAME, environmentDto)); assertEquals("1. sec access error", actual.getMessage()); verify(environmentService, times(0)).editSecurityAccess(eq(value), eq(securityAccessDto)); }
Example #12
Source File: IdResourceTest.java From snowizard with BSD 3-Clause "New" or "Revised" License | 6 votes |
@Test public void testGetIdAsJSONInvalidAgent() throws Exception { when(worker.getId(AGENT)).thenThrow(new InvalidUserAgentError()); try { resources.client().target("/").request(MediaType.APPLICATION_JSON) .header(HttpHeaders.USER_AGENT, AGENT) .get(ClientResponse.class); failBecauseExceptionWasNotThrown(BadRequestException.class); } catch (final BadRequestException e) { final ObjectMapper mapper = resources.getObjectMapper(); final String expected = mapper.writeValueAsString(AGENT_ERROR); final Response response = e.getResponse(); assertThat(response.getStatus()).isEqualTo(400); assertThat(response.readEntity(String.class)).isEqualTo(expected); } verify(worker).getId(AGENT); }
Example #13
Source File: ServiceProviderCredentialAdapter.java From cloudbreak with Apache License 2.0 | 6 votes |
public Credential initCodeGrantFlow(Credential credential, String accountId, String userId) { CloudContext cloudContext = new CloudContext(credential.getId(), credential.getName(), credential.getCloudPlatform(), userId, accountId); CloudCredential cloudCredential = credentialConverter.convert(credential); LOGGER.debug("Requesting code grant flow cloudPlatform {} and creator {}.", credential.getCloudPlatform(), userId); InitCodeGrantFlowRequest request = requestProvider.getInitCodeGrantFlowRequest(cloudContext, cloudCredential); LOGGER.info("Triggering event: {}", request); eventBus.notify(request.selector(), eventFactory.createEvent(request)); try { InitCodeGrantFlowResponse res = request.await(); LOGGER.info("Result: {}", res); if (res.getStatus() != EventStatus.OK) { String message = "Authorization code grant based credential creation couldn't be initialized: "; LOGGER.error(message, res.getErrorDetails()); throw new BadRequestException(message + res.getErrorDetails(), res.getErrorDetails()); } Map<String, String> codeGrantFlowInitParams = res.getCodeGrantFlowInitParams(); addCodeGrantFlowInitAttributesToCredential(credential, codeGrantFlowInitParams); return credential; } catch (InterruptedException e) { LOGGER.error("Error while executing initialization of authorization code grant based credential creation:", e); throw new OperationException(e); } }
Example #14
Source File: ImageCatalogTest.java From cloudbreak with Apache License 2.0 | 6 votes |
@Test(dataProvider = TEST_CONTEXT_WITH_MOCK) @Description( given = "image catalog invalid URL but too long name", when = "calling create image catalog with that URL and name", then = "getting a BadRequestException") public void testImageCatalogCreationWhenNameIsTooLong(TestContext testContext) { String imgCatalogName = resourcePropertyProvider().getName().concat(getLongNameGenerator().stringGenerator(100)); testContext .given(imgCatalogName, ImageCatalogTestDto.class) .withName(imgCatalogName) .withUrl(IMG_CATALOG_URL) .when(imageCatalogTestClient.createV4(), key(imgCatalogName)) .expect(BadRequestException.class, key(imgCatalogName) .withExpectedMessage(".*The length of the credential's name has to be in range of 5 to 100")) .validate(); }
Example #15
Source File: EnvironmentModificationServiceTest.java From cloudbreak with Apache License 2.0 | 6 votes |
@Test void testEditAuthenticationIfChangedWhenHasValidationError() { AuthenticationDto authenticationDto = AuthenticationDto.builder().build(); EnvironmentEditDto environmentEditDto = EnvironmentEditDto.builder().withAuthentication(authenticationDto).build(); Environment environment = new Environment(); ValidationResult validationResult = ValidationResult.builder().error("Error").build(); when(environmentService.getValidatorService()).thenReturn(validatorService); when(validatorService.validateAuthenticationModification(environmentEditDto, environment)).thenReturn(validationResult); BadRequestException badRequestException = assertThrows(BadRequestException.class, () -> environmentModificationServiceUnderTest.editAuthenticationIfChanged(environmentEditDto, environment)); assertEquals(badRequestException.getMessage(), "1. Error"); }
Example #16
Source File: ProxyConfigTest.java From cloudbreak with Apache License 2.0 | 6 votes |
@Test(dataProvider = TEST_CONTEXT_WITH_MOCK) @Description( given = "an invalid proxy request with too short name", when = "calling create proxy", then = "getting back a BadRequestException") public void testCreateProxyWithShortName(TestContext testContext) { String name = resourcePropertyProvider().getName(); testContext .given(ProxyTestDto.class) .withName(SHORT_PROXY_NAME) .withDescription(PROXY_DESCRIPTION) .withServerHost(PROXY_HOST) .withServerPort(PROXY_PORT) .withServerUser(PROXY_USER) .withPassword(PROXY_PASSWORD) .withProtocol(HTTP) .when(proxyTestClient.create(), key(name)) .expect(BadRequestException.class, expectedMessage("The length of the name has to be in range of 4 to 100").withKey(name)) .validate(); }
Example #17
Source File: AvroSchemaRegistryClientTest.java From registry with Apache License 2.0 | 6 votes |
/** * Return true if the schema creation failed as expected */ private void testCreate(SchemaRegistryClient client) { boolean failedAsExpected = false; SchemaMetadata schemaMetadata = new SchemaMetadata.Builder(name).type(type).schemaGroup(group). description("description").build(); try { client.registerSchemaMetadata(schemaMetadata); } catch (BadRequestException ex) { Response resp = ex.getResponse(); Assert.assertEquals(test + " - http response unexpected", expectedHttpResponse.getStatusCode(), resp.getStatus()); CatalogResponse catalogResponse = SchemaRegistryClient.readCatalogResponse(resp.readEntity(String.class)); Assert.assertEquals(test + " - catalog response unexpected", expectedCatalogResponse.getCode(), catalogResponse.getResponseCode()); failedAsExpected = true; } Assert.assertTrue(test + " - did not fail as expected", failedAsExpected); }
Example #18
Source File: ProxyConfigTest.java From cloudbreak with Apache License 2.0 | 6 votes |
@Test(dataProvider = TEST_CONTEXT_WITH_MOCK) @Description( given = "an invalid proxy request without port", when = "calling create proxy", then = "getting back a BadRequestException") public void testCreateProxyWithoutPort(TestContext testContext) { String name = resourcePropertyProvider().getName(); String key = "noport"; testContext .given(ProxyTestDto.class) .withName(name) .withDescription(PROXY_DESCRIPTION) .withServerHost(PROXY_HOST) .withServerPort(null) .withServerUser(PROXY_USER) .withPassword(PROXY_PASSWORD) .withProtocol(HTTP) .when(proxyTestClient.create(), key(key)) .expect(BadRequestException.class, expectedMessage("Server port is required") .withKey(key)) .validate(); }
Example #19
Source File: RsProtectTest.java From oxd with Apache License 2.0 | 6 votes |
@Parameters({"host", "redirectUrls", "opHost", "rsProtect"}) @Test public void overwriteFalse(String host, String redirectUrls, String opHost, String rsProtect) throws IOException { ClientInterface client = Tester.newClient(host); final RegisterSiteResponse site = RegisterSiteTest.registerSite(client, opHost, redirectUrls); List<RsResource> resources = UmaFullTest.resourceList(rsProtect).getResources(); protectResources(client, site, resources); final RsProtectParams2 params = new RsProtectParams2(); params.setOxdId(site.getOxdId()); params.setResources(Jackson2.createJsonMapper().readTree(Jackson2.asJsonSilently(resources))); try { client.umaRsProtect(Tester.getAuthorization(site), null, params); } catch (BadRequestException e) { assertEquals("uma_protection_exists", TestUtils.asError(e).getError()); return; } throw new AssertionError("Expected 400 (bad request) but got successful result."); }
Example #20
Source File: ScriptBasedAuthenticatorTest.java From keycloak with Apache License 2.0 | 6 votes |
@Test public void checkIfTurnedOffWithProductProfile() throws InterruptedException { ProfileAssume.assumePreviewDisabled(); HashMap<String, String> params = new HashMap<>(); params.put("newName", "Copy-of-browser"); authMgmtResource.copy("browser", params); params.put("provider", "auth-script-based"); try { authMgmtResource.addExecution("Copy-of-browser", params); Assert.fail("Adding script based authenticator should fail with product profile"); } catch (BadRequestException ex) { //Expected } }
Example #21
Source File: UserFederationLdapConnectionTest.java From keycloak with Apache License 2.0 | 6 votes |
@Test public void testLdapCapabilities() { // Query the rootDSE success TestLdapConnectionRepresentation config = new TestLdapConnectionRepresentation( LDAPServerCapabilitiesManager.QUERY_SERVER_CAPABILITIES, "ldap://localhost:10389", "uid=admin,ou=system", "secret", "false", null, "false", LDAPConstants.AUTH_TYPE_SIMPLE); List<LDAPCapabilityRepresentation> ldapCapabilities = realm.ldapServerCapabilities(config); Assert.assertThat(ldapCapabilities, Matchers.hasItem(new LDAPCapabilityRepresentation(PasswordModifyRequest.PASSWORD_MODIFY_OID, LDAPCapabilityRepresentation.CapabilityType.EXTENSION))); // Query the rootDSE failure try { config = new TestLdapConnectionRepresentation( LDAPServerCapabilitiesManager.QUERY_SERVER_CAPABILITIES, "ldap://localhost:10389", "foo", "bar", "false", null, "false", LDAPConstants.AUTH_TYPE_SIMPLE); realm.ldapServerCapabilities(config); Assert.fail("It wasn't expected to successfully sent the request for query capabilities"); } catch (BadRequestException bre) { // Expected } }
Example #22
Source File: AlertController.java From cloudbreak with Apache License 2.0 | 6 votes |
private void validateAlertForUpdate(Cluster cluster, Long alertId, AlertType alertType) { Optional alert; switch (alertType) { case LOAD: alert = cluster.getLoadAlerts().stream().map(LoadAlert::getId) .filter(loadAlertId -> loadAlertId.equals(alertId)) .findAny(); break; case TIME: alert = cluster.getTimeAlerts().stream().map(TimeAlert::getId) .filter(timeAlertId -> timeAlertId.equals(alertId)) .findAny(); break; default: //Prometheus and Metrics Alerts not supported. throw new BadRequestException(messagesService .getMessage(MessageCode.UNSUPPORTED_AUTOSCALING_TYPE, List.of(alertType, cluster.getStackName()))); } if (alert.isEmpty()) { throw new NotFoundException( messagesService.getMessage(MessageCode.AUTOSCALING_CONFIG_NOT_FOUND, List.of(alertType, alertId, cluster.getStackName()))); } }
Example #23
Source File: ThingResource.java From openhab-core with Eclipse Public License 2.0 | 5 votes |
private URI getConfigDescriptionURI(ChannelUID channelUID) { String uriString = "channel:" + channelUID; try { return new URI(uriString); } catch (URISyntaxException e) { throw new BadRequestException("Invalid URI syntax: " + uriString); } }
Example #24
Source File: BadRequestMapper.java From ballerina-message-broker with Apache License 2.0 | 5 votes |
@Override public Response toResponse(BadRequestException exception) { LOGGER.debug("Bad request.", exception); Map<String, Object> errorResponse = new HashMap<>(); errorResponse.put("message", exception.getMessage()); return Response.status(Response.Status.BAD_REQUEST) .entity(errorResponse) .type(MediaType.APPLICATION_JSON_TYPE) .build(); }
Example #25
Source File: FailureTypeUtilTest.java From robozonky with Apache License 2.0 | 5 votes |
@Test void expectedReasonMatches() { final String reason = UUID.randomUUID() .toString(); final Response response = Response.status(400) .entity(reason) .build(); final ClientErrorException actual = new BadRequestException(response); final Class<? extends ClientErrorException> expected = actual.getClass(); assertThat(FailureTypeUtil.matches(expected, actual, reason)).isTrue(); }
Example #26
Source File: TestingResourceProvider.java From keycloak with Apache License 2.0 | 5 votes |
/** * Generate new client scope for specified service client. The "Frontend" clients, who will use this client scope, will be able to * send their access token to authenticate against specified service client * * @param clientId Client ID of service client (typically bearer-only client) * @return ID of the newly generated clientScope */ @Path("generate-audience-client-scope") @POST @NoCache public String generateAudienceClientScope(@QueryParam("realm") final String realmName, final @QueryParam("clientId") String clientId) { try { RealmModel realm = getRealmByName(realmName); ClientModel serviceClient = realm.getClientByClientId(clientId); if (serviceClient == null) { throw new NotFoundException("Referenced service client doesn't exists"); } ClientScopeModel clientScopeModel = realm.addClientScope(clientId); clientScopeModel.setProtocol(serviceClient.getProtocol()==null ? OIDCLoginProtocol.LOGIN_PROTOCOL : serviceClient.getProtocol()); clientScopeModel.setDisplayOnConsentScreen(true); clientScopeModel.setConsentScreenText(clientId); clientScopeModel.setIncludeInTokenScope(true); // Add audience protocol mapper ProtocolMapperModel audienceMapper = AudienceProtocolMapper.createClaimMapper("Audience for " + clientId, clientId, null,true, false); clientScopeModel.addProtocolMapper(audienceMapper); return clientScopeModel.getId(); } catch (ModelDuplicateException e) { throw new BadRequestException("Client Scope " + clientId + " already exists"); } }
Example #27
Source File: LoggersApiDelegate.java From ballerina-message-broker with Apache License 2.0 | 5 votes |
public Response updateLogger(Subject subject, LoggerMetadata requestLogger) { try { authHandler.handle(ResourceAuthScope.LOGGERS_UPDATE, subject); Logger logger = LogManager.exists(requestLogger.getName()); if (logger == null) { throw new NotFoundException("Logger not found"); } else if (!isLogLevelValid(requestLogger.getLevel())) { String errorMessage = "'" + requestLogger.getLevel() + "' is not a valid log level.\n Valid log " + "levels : " + Level.OFF.toString() + " , " + Level.TRACE.toString() + " , " + Level.DEBUG.toString() + " , " + Level.INFO.toString() + " , " + Level.WARN.toString() + " , " + Level.ERROR.toString() + " , " + Level.FATAL.toString(); throw new BadRequestException(errorMessage); } else { String oldLevel = logger.getEffectiveLevel().toString(); logger.setLevel(Level.toLevel(requestLogger.getLevel())); String responseMessage = "Logger : " + requestLogger.getName() + "\nChanged log level : " + oldLevel + " ->" + " " + logger.getEffectiveLevel().toString(); return Response.ok().entity(new ResponseMessage().message(responseMessage)).build(); } } catch (AuthException e) { throw new NotAuthorizedException(e.getMessage(), e); } }
Example #28
Source File: CustomerService.java From if1007 with MIT License | 5 votes |
public Customer register(Customer customer) { Optional<Customer> dbCustomer = Customer.findByName(customer.getName()); if (dbCustomer.isPresent()) { throw new BadRequestException(); } customer.persist(); log.info("sending message: " + customer.getEmail()); registeredCustomerEmitter.send(customer.getEmail()); return customer; }
Example #29
Source File: SubjectVersionsResourceImpl.java From apicurio-registry with Apache License 2.0 | 5 votes |
@Override public int deleteSchemaVersion( String subject, String version) throws Exception { try { return facade.deleteSchema(subject, version); } catch (IllegalArgumentException ex) { throw new BadRequestException(ex); // TODO } }
Example #30
Source File: DefaultTenantProvisioningService.java From cloud-s4-sdk-examples with Apache License 2.0 | 5 votes |
@Override public void unsubscribeTenant(final String tenantId) { try { Validate.isTrue(isValidTenantId(tenantId), String.format("Invalid tenant id: \"%s\"", tenantId)); final String schemaName = TenantUtil.createSchemaName(tenantId); final Connection connection = dataSource.getConnection(); try (Statement statement = connection.createStatement()) { statement.execute(String.format("DROP SCHEMA IF EXISTS \"%s\" CASCADE", schemaName)); } } catch (SQLException | IllegalArgumentException e) { final BadRequestException badRequestException = new BadRequestException(); logger.error("Tenant unsubscription failed for {}.", tenantId, e); throw badRequestException; } }