javax.ws.rs.NotSupportedException#javax.ws.rs.ClientErrorException源码实例Demo

下面列出了javax.ws.rs.NotSupportedException#javax.ws.rs.ClientErrorException 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: syndesis   文件: EnvironmentHandler.java
/**
 * 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());

}
 
源代码2 项目: usergrid   文件: BadGrammarQueryTest.java
/**
 * 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());
    }
}
 
源代码3 项目: pulsar   文件: BaseResource.java
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);
    }
}
 
源代码4 项目: usergrid   文件: ExportResourceIT.java
@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() );
    }
}
 
源代码5 项目: syndesis   文件: PublicApiHandler.java
/**
 * 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);
    }
}
 
源代码6 项目: keycloak   文件: CrossRealmPermissionsTest.java
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);
}
 
源代码7 项目: cloudbreak   文件: CredentialService.java
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());
}
 
源代码8 项目: pnc   文件: BuildConfigurationEndpointTest.java
@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"));
}
 
源代码9 项目: opencps-v2   文件: KPJsonRest.java
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);
}
 
源代码10 项目: usergrid   文件: ExportResourceIT.java
@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() );
    }
}
 
源代码11 项目: usergrid   文件: BadGrammarQueryTest.java
/**
 * 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());
    }
}
 
源代码12 项目: cloudbreak   文件: ResponseUtil.java
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();
}
 
源代码13 项目: usergrid   文件: BadGrammarQueryTest.java
/**
 * 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());
    }
}
 
源代码14 项目: cxf   文件: SpecExceptions.java
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;
}
 
源代码15 项目: syncope   文件: OIDCProviderLogic.java
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;
        }
    }
}
 
源代码16 项目: robozonky   文件: ZonkyTest.java
@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);
}
 
源代码17 项目: usergrid   文件: ManagementResourceIT.java
@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 );
}
 
源代码18 项目: usergrid   文件: BadGrammarQueryTest.java
/**
 * 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());
    }
}
 
源代码19 项目: sinavi-jfw   文件: ClientErrorExceptionMapper.java
/**
 * {@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();
}
 
源代码20 项目: keycloak   文件: UserTest.java
@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);
    }
}
 
源代码21 项目: archiva   文件: UploadArtifactsTest.java
@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();
    }
}
 
源代码22 项目: robozonky   文件: InvestorTest.java
@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);
    }
}
 
源代码23 项目: robozonky   文件: InvestorTest.java
@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);
    }
}
 
源代码24 项目: keycloak   文件: RealmsConfigurationLoader.java
@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());
}
 
源代码25 项目: robozonky   文件: AvailabilityImplTest.java
@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)));
    });
}
 
源代码26 项目: usergrid   文件: ExportResourceIT.java
@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() );
    }
}
 
源代码27 项目: usergrid   文件: BadGrammarQueryTest.java
/**
 * 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());
    }
}
 
源代码28 项目: usergrid   文件: DuplicateNameIT.java
/**
 * 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());
    }
}
 
源代码29 项目: cxf   文件: BookStorePerRequest.java
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();
}
 
源代码30 项目: usergrid   文件: RegistrationIT.java
@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);
    }
}