Java Code Examples for javax.ws.rs.client.Client#target()

The following examples show how to use javax.ws.rs.client.Client#target() . 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: CollectionServiceImpl.java    From AIDR with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public int getRunningCollectionsCountFromCollector() {
   	int runningCollections = 0;
	try {
		Client client = ClientBuilder.newBuilder().register(JacksonFeature.class).build();
		WebTarget webResource = client.target(fetchMainUrl + "/manage/ping");

		ObjectMapper objectMapper = JacksonWrapper.getObjectMapper();
		Response clientResponse = webResource.request(MediaType.APPLICATION_JSON).get();

		String jsonResponse = clientResponse.readEntity(String.class);

		PingResponse pingResponse = objectMapper.readValue(jsonResponse, PingResponse.class);
		if (pingResponse != null && "RUNNING".equals(pingResponse.getCurrentStatus())) {
			runningCollections = Integer.parseInt(pingResponse.getRunningCollectionsCount());
		} 
	} catch (Exception e) {
		logger.error("Collector is not reachable");
	}
	return runningCollections;
}
 
Example 2
Source File: SimpleClientTest.java    From resteasy-examples with Apache License 2.0 6 votes vote down vote up
@Test
public void testCustomer() throws Exception
{
   // fill out a query param and execute a get request
   Client client = ClientBuilder.newClient();
   WebTarget target = client.target("http://localhost:9095/customers");
   try
   {
      // extract customer directly expecting success
      Customer cust = target.queryParam("name", "Bill").request().get(Customer.class);
      Assert.assertEquals("Bill", cust.getName());
   }
   finally
   {
      client.close();
   }
}
 
Example 3
Source File: ChannelBufferManager.java    From AIDR with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * 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?
}
 
Example 4
Source File: SimpleClientTest.java    From resteasy-examples with Apache License 2.0 6 votes vote down vote up
@Test
public void testResponse() throws Exception
{
   // fill out a query param and execute a get request
   Client client = ClientBuilder.newClient();
   WebTarget target = client.target("http://localhost:9095/customers");
   Response response = target.queryParam("name", "Bill").request().get();
   try
   {
      Assert.assertEquals(200, response.getStatus());
      Customer cust = response.readEntity(Customer.class);
      Assert.assertEquals("Bill", cust.getName());
   }
   finally
   {
      response.close();
      client.close();
   }
}
 
Example 5
Source File: ClientImplTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
/**
 * This test checks that we do not lose track of registered interceptors
 * on the original client implementation after we create a new impl with
 * the path(...) method - particularly when the path passed in to the
 * path(...) method contains a template.
 */
@Test
public void testClientConfigCopiedOnPathCallWithTemplates() {
    Client client = ClientBuilder.newClient();
    WebTarget webTarget = client.target("http://localhost:8080/");
    WebClient webClient = getWebClient(webTarget);
    
    ClientConfiguration clientConfig = WebClient.getConfig(webClient);
    clientConfig.setOutInterceptors(Arrays.asList(new MyInterceptor()));
    assertTrue("Precondition failed - original WebTarget is missing expected interceptor",
               doesClientConfigHaveMyInterceptor(webClient));

    WebTarget webTargetAfterPath = webTarget.path("/rest/{key}/").resolveTemplate("key", "myKey");
    WebClient webClientAfterPath = getWebClient(webTargetAfterPath);
    assertTrue("New WebTarget is missing expected interceptor specified on 'parent' WebTarget's client impl",
               doesClientConfigHaveMyInterceptor(webClientAfterPath));
}
 
Example 6
Source File: DemoServletsAdapterTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void testBadUser() {
    Client client = ClientBuilder.newClient();
    URI uri = OIDCLoginProtocolService.tokenUrl(authServerPage.createUriBuilder()).build("demo");
    WebTarget target = client.target(uri);
    String header = BasicAuthHelper.createHeader("customer-portal", "password");
    Form form = new Form();
    form.param(OAuth2Constants.GRANT_TYPE, OAuth2Constants.PASSWORD)
            .param("username", "[email protected]")
            .param("password", "password");
    Response response = target.request()
            .header(HttpHeaders.AUTHORIZATION, header)
            .post(Entity.form(form));
    assertEquals(401, response.getStatus());
    response.close();
    client.close();
}
 
Example 7
Source File: OIDCWellKnownProviderTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Test
public void corsTest() {
    Client client = ClientBuilder.newClient();
    UriBuilder builder = UriBuilder.fromUri(OAuthClient.AUTH_SERVER_ROOT);
    URI oidcDiscoveryUri = RealmsResource.wellKnownProviderUrl(builder).build("test", OIDCWellKnownProviderFactory.PROVIDER_ID);
    WebTarget oidcDiscoveryTarget = client.target(oidcDiscoveryUri);


    Invocation.Builder request = oidcDiscoveryTarget.request();
    request.header(Cors.ORIGIN_HEADER, "http://somehost");
    Response response = request.get();

    assertEquals("http://somehost", response.getHeaders().getFirst(Cors.ACCESS_CONTROL_ALLOW_ORIGIN));
}
 
Example 8
Source File: TechnologyEndpointTest.java    From tool.accelerate.core with Apache License 2.0 5 votes vote down vote up
private < E > E getObjectFromEndpoint(Class<E> klass, String extension, MediaType mediaType) {
    String port = System.getProperty("liberty.test.port");
    String url = "http://localhost:" + port + endpoint + extension;
    System.out.println("Getting object from url " + url);
    Client client = ClientBuilder.newClient();
    WebTarget target = client.target(url);
    Invocation.Builder invoBuild = target.request();
    E object = invoBuild.accept(mediaType).get(klass);
    client.close();
    return object;
}
 
Example 9
Source File: EndpointTest.java    From tool.accelerate.core with Apache License 2.0 5 votes vote down vote up
public Response sendRequest(String url, String requestType) {
    Client client = ClientBuilder.newClient();
    System.out.println("Testing " + url);
    WebTarget target = client.target(url);
    Invocation.Builder invoBuild = target.request();
    Response response = invoBuild.build(requestType).invoke();
    return response;
}
 
Example 10
Source File: JBossRESTEasyClientITest.java    From hawkular-apm with Apache License 2.0 5 votes vote down vote up
@Test
public void testJaxRSClientPUT() {
    Client client = ClientBuilder.newClient();
    WebTarget target = client.target(SAY_HELLO_URL);
    Response response = target.request().header("test-header", "test-value").put(Entity.<String> text(SAY_HELLO));

    processResponse(response, false, false, false);
}
 
Example 11
Source File: TestMultiMaster.java    From dremio-oss with Apache License 2.0 4 votes vote down vote up
private static WebTarget newApiV2Target(Client client, DACDaemon daemon) {
  WebTarget rootTarget = client.target("http://localhost:" + daemon.getWebServer().getPort());
  return rootTarget.path(API_LOCATION);
}
 
Example 12
Source File: JerseyRestUtils.java    From java-client with Apache License 2.0 4 votes vote down vote up
public static void delete(String resourceUrl, String id, Class clazz) throws BlockCypherException {
    Client client = ClientBuilder.newClient(new ClientConfig());
    WebTarget webTarget = client.target(resourceUrl);
    delete(webTarget, clazz);
}
 
Example 13
Source File: EmployeeResourceTest.java    From wildfly-samples with MIT License 4 votes vote down vote up
@Before
public void setUp() throws MalformedURLException {
    Client client = ClientBuilder.newClient();
    target = client.target(URI.create(new URL(base, "registry/employee").toExternalForm()));
    target.register(Employee.class);
}
 
Example 14
Source File: FlowOverrideTest.java    From keycloak with Apache License 2.0 4 votes vote down vote up
@Test
public void testDirectGrantHttpChallengeUserDisabled() {
    setupBruteForce();

    Client httpClient = javax.ws.rs.client.ClientBuilder.newClient();
    String grantUri = oauth.getResourceOwnerPasswordCredentialGrantUrl();
    WebTarget grantTarget = httpClient.target(grantUri);

    Form form = new Form();
    form.param(OAuth2Constants.GRANT_TYPE, OAuth2Constants.PASSWORD);
    form.param(OAuth2Constants.CLIENT_ID, TEST_APP_HTTP_CHALLENGE);

    UserRepresentation user = adminClient.realm("test").users().search("test-user@localhost").get(0);
    user.setEnabled(false);
    adminClient.realm("test").users().get(user.getId()).update(user);

    // user disabled
    Response response = grantTarget.request()
            .header(HttpHeaders.AUTHORIZATION, BasicAuthHelper.createHeader("test-user@localhost", "password"))
            .post(Entity.form(form));
    assertEquals(401, response.getStatus());
    assertEquals("Unauthorized", response.getStatusInfo().getReasonPhrase());
    response.close();

    user.setEnabled(true);
    adminClient.realm("test").users().get(user.getId()).update(user);

    // lock the user account
    grantTarget.request()
            .header(HttpHeaders.AUTHORIZATION, BasicAuthHelper.createHeader("test-user@localhost", "wrongpassword"))
            .post(Entity.form(form));
    grantTarget.request()
            .header(HttpHeaders.AUTHORIZATION, BasicAuthHelper.createHeader("test-user@localhost", "wrongpassword"))
            .post(Entity.form(form));
    // user is temporarily disabled
    response = grantTarget.request()
            .header(HttpHeaders.AUTHORIZATION, BasicAuthHelper.createHeader("test-user@localhost", "password"))
            .post(Entity.form(form));
    assertEquals(401, response.getStatus());
    assertEquals("Unauthorized", response.getStatusInfo().getReasonPhrase());
    response.close();

    clearBruteForce();

    httpClient.close();
    events.clear();
}
 
Example 15
Source File: RestAgent.java    From micro-server with Apache License 2.0 3 votes vote down vote up
public String post(String url) {
    Client client = ClientBuilder.newClient();

    WebTarget resource = client.target(url);

    Builder request = resource.request();
    request.accept(MediaType.APPLICATION_JSON);

    return request.post(null, String.class);
}
 
Example 16
Source File: RestAgent.java    From micro-server with Apache License 2.0 3 votes vote down vote up
public<T> T post(String url, Object payload,Class<T> type) {
	Client client = ClientBuilder.newClient();

	WebTarget resource = client.target(url);

	Builder request = resource.request();
	request.accept(MediaType.APPLICATION_JSON);

	return request.post(Entity.entity(JacksonUtil.serializeToJson(payload),MediaType.APPLICATION_JSON), type);
}
 
Example 17
Source File: RestAgent.java    From micro-server with Apache License 2.0 3 votes vote down vote up
public String getJson(String url) {

		Client client = ClientBuilder.newClient();

		WebTarget resource = client.target(url);

		Builder request = resource.request();
		request.accept(MediaType.APPLICATION_JSON);

		return request.get(String.class);

	}
 
Example 18
Source File: RestAgent.java    From micro-server with Apache License 2.0 3 votes vote down vote up
public String get(String url) {

		Client client = ClientBuilder.newClient();

		WebTarget resource = client.target(url);

		Builder request = resource.request();
		request.accept(MediaType.TEXT_PLAIN);

		return request.get(String.class);

	}
 
Example 19
Source File: RestAgent.java    From micro-server with Apache License 2.0 3 votes vote down vote up
public<T> T post(String url, Object payload,Class<T> type) {
	Client client = ClientBuilder.newClient();

	WebTarget resource = client.target(url);

	Builder request = resource.request();
	request.accept(MediaType.APPLICATION_JSON);

	return request.post(Entity.entity(JacksonUtil.serializeToJson(payload),MediaType.APPLICATION_JSON), type);
}
 
Example 20
Source File: SingleClassTest.java    From micro-server with Apache License 2.0 3 votes vote down vote up
@Test
public void runAppAndBasicTest() throws InterruptedException, ExecutionException{
	
	Client client = ClientBuilder.newClient();

	WebTarget resource = client.target("http://localhost:8080/simple-app/single/ping");

	Builder request = resource.request();
	request.accept(MediaType.TEXT_PLAIN);
	assertFalse(request.get().getHeaders().containsKey("Access-Control-Allow-Origin"));
	
	

}