类javax.ws.rs.client.Client源码实例Demo

下面列出了怎么用javax.ws.rs.client.Client的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: gitlab4j-api   文件: GitLabApiClient.java
protected Client createApiClient() {

        // Explicitly use an instance of the JerseyClientBuilder, this allows this
        // library to work when both Jersey and Resteasy are present
        ClientBuilder clientBuilder = new JerseyClientBuilder().withConfig(clientConfig);

        // Register JacksonJson as the ObjectMapper provider.
        clientBuilder.register(JacksonJson.class);

        if (ignoreCertificateErrors) {
            clientBuilder.sslContext(openSslContext).hostnameVerifier(openHostnameVerifier);
        }

        apiClient = clientBuilder.build();
        return (apiClient);
    }
 
源代码2 项目: mattermost4j   文件: FilesApiTest.java
@Test
public void getPublicFileLink() throws URISyntaxException, IOException {
  Path filePath = th.getResourcePath(TestHelper.EMOJI_GLOBE);
  String channelId = th.basicChannel().getId();
  FileUploadResult uploadResult = assertNoError(client.uploadFile(channelId, filePath)).readEntity();
  FileInfo fileInfo = uploadResult.getFileInfos()[0];
  String fileId = fileInfo.getId();

  Post post = new Post(channelId, "file attached post");
  post.setFileIds(Collections.singletonList(fileId));
  post = assertNoError(client.createPost(post)).readEntity();

  String publicLink = assertNoError(client.getPublicFileLink(fileId)).readEntity();

  Client jaxrsClient = ClientBuilder.newClient();
  WebTarget target = jaxrsClient.target(publicLink);
  Response response = target.request().get();
  InputStream downloadFile = response.readEntity(InputStream.class);
  Path tempFile = Files.createTempFile(null, null);
  Files.copy(downloadFile, tempFile, StandardCopyOption.REPLACE_EXISTING);

  assertSameFile(filePath, tempFile);
}
 
@Before
public void setUp() {
    when(mockConfiguration.getLedgerUrl()).thenReturn(ledgerRule.getUrl());
    when(mockConfiguration.getConnectorUrl()).thenReturn(connectorRule.getUrl());
    when(mockConfiguration.getBaseUrl()).thenReturn("http://publicapi.test.localhost/");

    PublicApiUriGenerator publicApiUriGenerator = new PublicApiUriGenerator(mockConfiguration);
    LedgerUriGenerator ledgerUriGenerator = new LedgerUriGenerator(mockConfiguration);

    Client client = RestClientFactory.buildClient(new RestClientConfig(false));
    LedgerService ledgerService = new LedgerService(client, ledgerUriGenerator);

    ConnectorUriGenerator connectorUriGenerator = new ConnectorUriGenerator(mockConfiguration);
    ConnectorService connectorService = new ConnectorService(client, connectorUriGenerator);

    getPaymentRefundsService = new GetPaymentRefundsService(connectorService, ledgerService, publicApiUriGenerator);
}
 
源代码4 项目: boost   文件: SystemEndpointIT.java
@Test
public void testGetProperties() {
    // String port = System.getProperty("liberty.test.port");
    String port = System.getProperty("boost_http_port");
    // String port = "9000";
    String url = "http://localhost:" + port + "/";

    Client client = ClientBuilder.newClient();
    client.register(JsrJsonpProvider.class);

    WebTarget target = client.target(url + "system/properties");
    Response response = target.request().get();

    assertEquals("Incorrect response code from " + url, 200, response.getStatus());

    JsonObject obj = response.readEntity(JsonObject.class);

    assertEquals("The system property for the local and remote JVM should match", System.getProperty("os.name"),
            obj.getString("os.name"));

    response.close();
}
 
public VerifyServiceProviderFactory(
        VerifyServiceProviderConfiguration configuration,
        MetadataResolverBundle<VerifyServiceProviderConfiguration> verifyMetadataBundler,
        MetadataResolverBundle<VerifyServiceProviderConfiguration> msaMetadataBundle,
        Client client) throws KeyException {
    this.configuration = configuration;
    List<KeyPair> decryptionKeyPairs = getDecryptionKeyPairs(
            configuration.getSamlPrimaryEncryptionKey(),
            configuration.getSamlSecondaryEncryptionKey()
    );
    this.keyStore = new IdaKeyStore(null, decryptionKeyPairs);
    this.responseFactory = new ResponseFactory(decryptionKeyPairs);
    this.dateTimeComparator = new DateTimeComparator(configuration.getClockSkew());
    this.entityIdService = new EntityIdService(configuration.getServiceEntityIds());
    this.verifyMetadataBundler = verifyMetadataBundler;
    this.msaMetadataBundle = msaMetadataBundle;
    this.manifestReader = new ManifestReader();
    this.client = client;
    this.hubSignatureValidator = new SignatureValidatorFactory().getSignatureValidator(getHubSignatureTrustEngine());
}
 
源代码6 项目: javaee8-cookbook   文件: MpMetricsResource.java
private String getResource() {
    Client client = null;
    String response;

    try {
        client = ClientBuilder.newClient();
        WebTarget target = client.target("https://eldermoraes.com/book");
        response = target.request()
                .header("Content-Type", "application/json")
                .get(String.class);
    } finally {
        if (client != null) {
            client.close();
        }
    }

    return response;
}
 
/**
 * Utility method that safely closes a client instance without throwing an exception.
 *
 * @param clients client instances to close. Each instance may be {@code null}.
 * @since 2.5
 */
public final void close(final Client... clients) {
    if (clients == null || clients.length == 0) {
        return;
    }

    for (Client c : clients) {
        if (c == null) {
            continue;
        }
        try {
            c.close();
        } catch (Throwable t) {
            LOGGER.log(Level.WARNING, "Error closing a client instance.", t);
        }

    }
}
 
源代码8 项目: cxf   文件: JAXRSAsyncClientTest.java
@Test
public void testNonExistentJaxrs20WithGet() throws Exception {
    String address = "http://168.168.168.168/bookstore";
    Client c = ClientBuilder.newClient();
    c.register(new TestResponseFilter());
    WebTarget t1 = c.target(address);
    Future<Response> future = t1.request().async().get();
    try {
        future.get();
        fail("Exception expected");
    } catch (ExecutionException ex) {
        Throwable cause = ex.getCause();
        assertTrue(cause instanceof ProcessingException);
        assertTrue(ex.getCause().getCause() instanceof IOException);
    } finally {
        c.close();
    }
}
 
源代码9 项目: keycloak   文件: FlowOverrideTest.java
@Test
public void testGrantAccessTokenWithClientOverride() throws Exception {
    String clientId = TEST_APP_DIRECT_OVERRIDE;
    Client httpClient = javax.ws.rs.client.ClientBuilder.newClient();
    String grantUri = oauth.getResourceOwnerPasswordCredentialGrantUrl();
    WebTarget grantTarget = httpClient.target(grantUri);

    {   // test no password
        String header = BasicAuthHelper.createHeader(clientId, "password");
        Form form = new Form();
        form.param(OAuth2Constants.GRANT_TYPE, OAuth2Constants.PASSWORD);
        form.param("username", "[email protected]");
        Response response = grantTarget.request()
                .header(HttpHeaders.AUTHORIZATION, header)
                .post(Entity.form(form));
        assertEquals(200, response.getStatus());
        response.close();
    }

    httpClient.close();
    events.clear();
}
 
源代码10 项目: cloudbreak   文件: PrincipalCreator.java
private void checkTheAvailabilityWithResourceLogin(String objectId, String tenantId, AzureApplication app, Client client) {
    WebTarget loginResource = client.target(LOGIN_MICROSOFTONLINE + tenantId);
    Map<String, String> formData = new HashMap<>();
    formData.put("grant_type", "client_credentials");
    formData.put("client_id", app.getAppId());
    formData.put("client_secret", app.getAzureApplicationCreationView().getAppSecret());
    formData.put("resource", app.getAzureApplicationCreationView().getAppIdentifierURI());
    try (Response loginResponse = loginResource.path("/oauth2/token")
            .request()
            .accept(MediaType.APPLICATION_JSON)
            .header("Content-Type", "application/x-www-form-urlencoded")
            .post(Entity.form(new MultivaluedHashMap<>(formData)))) {
        if (loginResponse.getStatus() != HttpStatus.SC_OK) {
            throw new RetryException("Principal with objectId (" + objectId + ") hasn't been available yet");
        }
    }
}
 
源代码11 项目: apicurio-studio   文件: Keycloak.java
public void login() {
    Client client = ClientBuilder.newClient();

    Form form = new Form();
    form.param("client_id", "admin-cli");
    form.param("username", "admin");
    form.param("password", "admin");
    form.param("grant_type", "password");
    Entity<Form> entity = Entity.form(form);

    Response response = client.target(baseUrl + "/auth/realms/master/protocol/openid-connect/token")
            .request(MediaType.APPLICATION_JSON_TYPE)
            .post(entity);
    JsonObject data = (JsonObject) asJson(response);
    this.token = data.getString("access_token");
}
 
源代码12 项目: keycloak   文件: FlowOverrideTest.java
@Test
public void testClientOverrideFlowUsingDirectGrantHttpChallenge() {
    Client httpClient = javax.ws.rs.client.ClientBuilder.newClient();
    String grantUri = oauth.getResourceOwnerPasswordCredentialGrantUrl();
    WebTarget grantTarget = httpClient.target(grantUri);

    // no username/password
    Form form = new Form();
    form.param(OAuth2Constants.GRANT_TYPE, OAuth2Constants.PASSWORD);
    form.param(OAuth2Constants.CLIENT_ID, TEST_APP_HTTP_CHALLENGE);
    Response response = grantTarget.request()
            .post(Entity.form(form));
    assertEquals("Basic realm=\"test\"", response.getHeaderString(HttpHeaders.WWW_AUTHENTICATE));
    assertEquals(401, response.getStatus());
    response.close();

    // now, username password using basic challenge response
    response = grantTarget.request()
            .header(HttpHeaders.AUTHORIZATION, BasicAuthHelper.createHeader("[email protected]", "password"))
            .post(Entity.form(form));
    assertEquals(200, response.getStatus());
    response.close();

    httpClient.close();
    events.clear();
}
 
源代码13 项目: sample-acmegifts   文件: OccasionResourceTest.java
/**
 * Helper method to send a simple http request without a payload
 *
 * @param url the url to call
 * @param requestType the http method to invoke
 * @return the response from the server
 */
public Response sendRequest(String url, String requestType) {
  String method = "sendRequest";
  logger.entering(clazz, method);
  logger.fine("  url: " + url);
  logger.fine("  requestType: " + requestType);

  String jwt = null;
  try {
    jwt = new JWTVerifier().createJWT("fred");
  } catch (Throwable t) {
    throw new RuntimeException(t);
  }

  Client client = ClientBuilder.newClient();
  WebTarget target = client.target(url);
  Invocation.Builder invoBuild = target.request();

  invoBuild.header(HttpHeaders.AUTHORIZATION, "Bearer " + jwt);
  Response response = invoBuild.build(requestType).invoke();

  logger.exiting(
      clazz, method, "\n\n- - - - - Exiting " + method + " with: " + response + "\n\n");
  return response;
}
 
源代码14 项目: mangooio   文件: ServerSentEventServiceTest.java
@Test
public void testCloseConnection() throws InterruptedException {
	//given
	ServerSentEventService ServerSentEventService = Application.getInstance(ServerSentEventService.class);
	Config config = Application.getInstance(Config.class);
	Client client = ClientBuilder.newClient();

	//when
	WebTarget webTarget = client.target("http://" + config.getConnectorHttpHost() + ":" + config.getConnectorHttpPort() + "/sse");
	SseEventSource sseEventSource = SseEventSource.target(webTarget).build();
	sseEventSource.register((sseEvent) -> {eventData = sseEvent.readData();}, (e) -> e.printStackTrace());
	sseEventSource.open();
	ServerSentEventService.close("/sse");
	sseEventSource.close();
	client.close();

	//then
	assertThat(ServerSentEventService.getConnections("/sse"), not(nullValue()));
	assertThat(ServerSentEventService.getConnections("/sse").size(), equalTo(0));
}
 
源代码15 项目: istio-tutorial   文件: PreferenceEndpoint.java
@GET
@Produces("text/plain")
public Response getPreference(@HeaderParam("user-agent") String userAgent) {
    try {
        Client client = ClientBuilder.newClient();
        Response res = client.target(remoteURL).request("text/plain").header("user-agent", userAgent).get();
        if (res.getStatus() == Response.Status.OK.getStatusCode()){
            return Response.ok(String.format(RESPONSE_STRING_FORMAT, res.readEntity(String.class))).build();
        }else{
            logger.warn("Non HTTP 20x trying to get the response from preference service: " + res.getStatus());
            return Response
                    .status(Response.Status.SERVICE_UNAVAILABLE)
                    .entity(String.format(RESPONSE_STRING_FORMAT,
                            String.format("Error: %d - %s", res.getStatus(), res.readEntity(String.class)))
                    )
                    .build();
        }
    } catch (ProcessingException ex) {
        logger.warn("Exception trying to get the response from recommendation service.", ex);
        return Response
                .status(Response.Status.SERVICE_UNAVAILABLE)
                .entity(String.format(RESPONSE_STRING_FORMAT, ex.getCause().getClass().getSimpleName() + ": " + ex.getCause().getMessage()))
                .build();
    }
}
 
源代码16 项目: aries-jax-rs-whiteboard   文件: TestHelper.java
protected WebTarget createDefaultTarget() {
    Client client = createClient();

    String[] runtimes = canonicalize(
        _runtimeServiceReference.getProperty("osgi.jaxrs.endpoint"));

    if (runtimes.length == 0) {
        throw new IllegalStateException(
            "No runtimes could be found on \"osgi.jaxrs.endpoint\" " +
                "runtime service property ");
    }

    String runtime = runtimes[0];

    return client.target(runtime);
}
 
源代码17 项目: AIDR   文件: ChannelBufferManager.java
/**
 * Calls the manager's public collection REST API.
 * @return publiclyListed value of given channel name
 */
@SuppressWarnings("unchecked")
public Boolean getChannelPublicStatus(String channelName) {
	String channelCode = parseChannelName(channelName);
	Response clientResponse = null;
	Client client = ClientBuilder.newBuilder().register(JacksonFeature.class).build();
	try {
		WebTarget webResource = client.target(managerMainUrl 
				+ "/public/collection/getChannelPublicFlagStatus?channelCode=" + channelCode);

		clientResponse = webResource.request(MediaType.APPLICATION_JSON).get();
		Map<String, Boolean> collectionMap = new HashMap<String, Boolean>();

		if (clientResponse.getStatus() == 200) {
			//convert JSON string to Map
			collectionMap = clientResponse.readEntity(Map.class);
			logger.info("Channel info received from manager: " + collectionMap);
			if (collectionMap != null) {
				return collectionMap.get(channelCode);
			}
		} else {
			logger.warn("Couldn't contact AIDRFetchManager for publiclyListed status, channel: " + channelName);
		}
	} catch (Exception e) {
		logger.error("Error in querying manager for running collections: " + clientResponse);
	}
	return true;		// Question: should default be true or false?
}
 
public WebTarget build() {
    ConfigKey configKey = new ConfigKey(secure, debug, ignorePreValidation, TWO_MINUTES_IN_MILLIS);
    Client client = RestClientUtil.get(configKey);
    client.register(clientRequestFilter);
    if (tracer != null) {
        client.register(tracer);
    }
    WebTarget webTarget = client.target(serviceAddress).path(apiRoot);
    LOGGER.info("WebTarget has been created with token: service address: {}, configKey: {}", serviceAddress, configKey);
    return webTarget;
}
 
源代码19 项目: cxf   文件: FormBehaviorTest.java
@Test
public void testInterceptorInvokedOnFormAndFormParamMatchesFormValue() throws Exception {
    Client client = ClientBuilder.newClient();
    String uri = "http://localhost:" + PORT + "/form";
    Form f = new Form("value", "ORIGINAL");
    Response r = client.target(uri)
                       .request(MediaType.APPLICATION_FORM_URLENCODED)
                       .post(Entity.form(f));

    Assert.assertEquals("MODIFIED", r.getHeaderString("FromForm"));
    Assert.assertEquals("MODIFIED", r.getHeaderString("FromFormParam"));
}
 
源代码20 项目: shiro-jersey   文件: AnnotationAuthTest.java
private Client newClient(Map<String, Object> props) {
    ClientConfig config = new ClientConfig().connectorProvider(new ApacheConnectorProvider());
    if (props != null)
        for (Entry<String, Object> entry : props.entrySet())
            config.property(entry.getKey(), entry.getValue());
    return ClientBuilder.newClient(config);
}
 
@Test
public void shouldReturn400WhenPassedNoEntityIdForMultiTenantApplication() throws Exception {
    Client client = new JerseyClientBuilder(multiTenantApplication.getEnvironment()).build("Test Client");

    setupComplianceToolWithEntityId(client, MULTI_ENTITY_ID_1);

    Response authnResponse = client
        .target(URI.create(String.format("http://localhost:%d/generate-request", multiTenantApplication.getLocalPort())))
        .request()
        .buildPost(Entity.json(new RequestGenerationBody(null)))
        .invoke();

    assertThat(authnResponse.getStatus()).isEqualTo(BAD_REQUEST.getStatusCode());
}
 
@Before
public void setup() {
    when(configuration.getConnectorUrl()).thenReturn(connectorRule.getUrl()); // We will actually send real requests here, which will be intercepted by pact        

    ConnectorUriGenerator connectorUriGenerator = new ConnectorUriGenerator(configuration);
    Client client = RestClientFactory.buildClient(new RestClientConfig(false));

    createTelephonePaymentService = new CreateTelephonePaymentService(client, connectorUriGenerator);
}
 
@Test
public void testGetLegacyPodcasts() throws JsonGenerationException,
		JsonMappingException, IOException {

	ClientConfig clientConfig = new ClientConfig();
	clientConfig.register(JacksonFeature.class);

	Client client = ClientBuilder.newClient(clientConfig);

	WebTarget webTarget = client
			.target("http://localhost:8888/demo-rest-spring-jersey-jpa2-hibernate-0.0.1-SNAPSHOT/legacy/podcasts/");

	Builder request = webTarget.request();
	request.header("Content-type", MediaType.APPLICATION_JSON);

	Response response = request.get();
	Assert.assertTrue(response.getStatus() == 200);

	List<Podcast> podcasts = response
			.readEntity(new GenericType<List<Podcast>>() {
			});

	ObjectMapper mapper = new ObjectMapper();
	System.out.print(mapper.writerWithDefaultPrettyPrinter()
			.writeValueAsString(podcasts));

	Assert.assertTrue("At least one podcast is present in the LEGACY",
			podcasts.size() > 0);
}
 
源代码24 项目: cloudbreak   文件: CloudbreakInfoTest.java
@Test
private void testInfo() {
    String infoUrl = getItContext().getContextParam(CLOUDBREAK_SERVER_ROOT);
    Client client = ClientBuilder.newBuilder().build();
    WebTarget target = client.target(infoUrl).path("info");
    CBVersion cbVersion = target.request().get().readEntity(CBVersion.class);

    Assert.assertEquals(cbVersion.getApp().getName(), "cloudbreak");
    if (getTestParameter().get("target.cbd.version") != null) {
        LOGGER.warn("TARGET_CBD_VERSION is provided.");
        Assert.assertEquals(cbVersion.getApp().getVersion(), getTestParameter().get("target.cbd.version"));
    } else {
        LOGGER.warn("TARGET_CBD_VERSION is not provided!");
    }
}
 
源代码25 项目: resteasy-examples   文件: SimpleClientTest.java
@Test
public void testProxy() throws Exception
{
   Client client = ClientBuilder.newClient();
   CustomerProxy proxy = ((ResteasyClient) client).target("http://localhost:9095").proxy(CustomerProxy.class);
   Customer cust = proxy.getCustomer("Monica");
   Assert.assertEquals("Monica", cust.getName());
   client.close();
}
 
源代码26 项目: java-jaxrs   文件: AbstractServerTest.java
@Test
public void testTracedFalseMethod() {
    Client client = ClientBuilder.newClient();
    Response response = client.target(url("/tracedFalseIn"))
        .request()
        .get();
    response.close();
    List<MockSpan> mockSpans = mockTracer.finishedSpans();
    Assert.assertEquals(0, mockSpans.size());
}
 
源代码27 项目: tessera   文件: PartyInfoResourceTest.java
@Before
public void onSetup() {
    this.partyInfoService = mock(PartyInfoService.class);
    this.partyInfoParser = mock(PartyInfoParser.class);
    this.enclave = mock(Enclave.class);
    this.restClient = mock(Client.class);
    this.payloadEncoder = mock(PayloadEncoder.class);
    this.partyInfoResource =
            new PartyInfoResource(partyInfoService, partyInfoParser, restClient, enclave, payloadEncoder, true);
}
 
源代码28 项目: tenacity   文件: TenacityClientBuilder.java
public TenacityClient build() {
    final Client client = new JerseyClientBuilder(environment)
            .using(jerseyConfiguration)
            .build("tenacity-" + tenacityPropertyKey);
    return new TenacityClient(environment.metrics(), TenacityJerseyClientBuilder
            .builder(tenacityPropertyKey)
            .build(client));
}
 
@Test
public void testGetLegacyPodcasts() throws JsonGenerationException,
		JsonMappingException, IOException {

	ClientConfig clientConfig = new ClientConfig();
	clientConfig.register(JacksonFeature.class);

	Client client = ClientBuilder.newClient(clientConfig);

	WebTarget webTarget = client
			.target("http://localhost:8888/demo-rest-jersey-spring/legacy/podcasts/");

	Builder request = webTarget.request();
	request.header("Content-type", MediaType.APPLICATION_JSON);

	Response response = request.get();
	Assert.assertTrue(response.getStatus() == 200);

	List<Podcast> podcasts = response
			.readEntity(new GenericType<List<Podcast>>() {
			});

	ObjectMapper mapper = new ObjectMapper();
	System.out.print(mapper.writerWithDefaultPrettyPrinter()
			.writeValueAsString(podcasts));

	Assert.assertTrue("At least one podcast is present in the LEGACY",
			podcasts.size() > 0);
}
 
源代码30 项目: cloudbreak   文件: AzureRoleManager.java
@Retryable(value = InteractiveLoginException.class, maxAttempts = 15, backoff = @Backoff(delay = 1000))
public void assignRole(String accessToken, String subscriptionId, String roleDefinitionId, String principalObjectId) throws InteractiveLoginException {
    Client client = ClientBuilder.newClient();
    WebTarget resource = client.target(AZURE_MANAGEMENT);
    Builder request = resource.path("subscriptions/" + subscriptionId + "/providers/Microsoft.Authorization/roleAssignments/"
            + UUID.randomUUID()).queryParam("api-version", "2015-07-01").request();
    request.accept(MediaType.APPLICATION_JSON);

    request.header("Authorization", "Bearer " + accessToken);

    JsonObject properties = new JsonObject();
    properties.addProperty("roleDefinitionId", roleDefinitionId);
    properties.addProperty("principalId", principalObjectId);

    JsonObject jsonObject = new JsonObject();
    jsonObject.add("properties", properties);

    try (Response response = request.put(Entity.entity(jsonObject.toString(), MediaType.APPLICATION_JSON))) {
        if (response.getStatusInfo().getFamily() != Family.SUCCESSFUL) {
            String errorResponse = response.readEntity(String.class);
            LOGGER.info("Assign role request error - status code: {} - error message: {}", response.getStatus(), errorResponse);
            if (response.getStatusInfo().getStatusCode() == Status.FORBIDDEN.getStatusCode()) {
                throw new InteractiveLoginException("You don't have enough permissions to assign roles, please contact with your administrator");
            } else {
                try {
                    String errorMessage = new ObjectMapper().readTree(errorResponse).get("error").get("message").asText();
                    throw new InteractiveLoginException("Failed to assing role: " + errorMessage);
                } catch (IOException e) {
                    throw new InteractiveLoginException("Failed to assing role (status " + response.getStatus() + "): " + errorResponse);
                }
            }
        } else {
            LOGGER.debug("Role assigned successfully. subscriptionId '{}', roleDefinitionId {}, principalObjectId {}",
                    subscriptionId, roleDefinitionId, principalObjectId);
        }
    }
}
 
 类所在包
 同包方法