javax.ws.rs.client.ClientBuilder Java Examples

The following examples show how to use javax.ws.rs.client.ClientBuilder. 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: UserInfoTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void testSuccess_postMethod_header() throws Exception {
    Client client = ClientBuilder.newClient();

    try {
        AccessTokenResponse accessTokenResponse = executeGrantAccessTokenRequest(client);

        WebTarget userInfoTarget = UserInfoClientUtil.getUserInfoWebTarget(client);
        Response response = userInfoTarget.request()
                .header(HttpHeaders.AUTHORIZATION, "bearer " + accessTokenResponse.getToken())
                .post(Entity.form(new Form()));

        testSuccessfulUserInfoResponse(response);

    } finally {
        client.close();
    }
}
 
Example #2
Source File: CalcTest.java    From tomee with Apache License 2.0 6 votes vote down vote up
@Test
public void testAddASync() throws Exception {
    final WebTarget webTarget = ClientBuilder.newClient().target(base.toURI());

    final Response response = webTarget
            .queryParam("op", "add")
            .queryParam("x", "10")
            .queryParam("y", "20")
            .queryParam("async", "true")
            .queryParam("delay", "2000")
            .queryParam("timeout", "10000")
            .request()
            .accept(MediaType.MEDIA_TYPE_WILDCARD)
            .get();

    Assert.assertEquals(200, response.getStatus());
    final InputStream is = (InputStream) response.getEntity();
    final String responsePayload = IO.slurp(is);

    Assert.assertEquals("30", responsePayload);
}
 
Example #3
Source File: PrivateKeyAsJWKSClasspathTest.java    From microprofile-jwt-auth with Apache License 2.0 6 votes vote down vote up
@RunAsClient
@Test(groups = TEST_GROUP_CONFIG,
    description = "Validate specifying the mp.jwt.decrypt.key.location as resource path to a JWKS key")
public void testKeyAsLocation() throws Exception {
    Reporter.log("testKeyAsLocation, expect HTTP_OK");

    PublicKey publicKey = TokenUtils.readJwkPublicKey("/encryptorPublicKey.jwk");
    String kid = "mp-jwt-set";
    String token = TokenUtils.encryptClaims(publicKey, kid, "/Token1.json");

    String uri = baseURL.toExternalForm() + "jwks/endp/verifyKeyLocationAsJWKSResource";
    WebTarget echoEndpointTarget = ClientBuilder.newClient()
        .target(uri)
        .queryParam("kid", kid);
    Response response = echoEndpointTarget.request(APPLICATION_JSON).header(HttpHeaders.AUTHORIZATION, "Bearer "+token).get();
    Assert.assertEquals(response.getStatus(), HttpURLConnection.HTTP_OK);
    String replyString = response.readEntity(String.class);
    JsonReader jsonReader = Json.createReader(new StringReader(replyString));
    JsonObject reply = jsonReader.readObject();
    Reporter.log(reply.toString());
    Assert.assertTrue(reply.getBoolean("pass"), reply.getString("msg"));
}
 
Example #4
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 #5
Source File: Cafe.java    From jakartaee-azure with MIT License 6 votes vote down vote up
@PostConstruct
private void init() {
	try {
		InetAddress inetAddress = InetAddress.getByName(
				((HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest())
						.getServerName());

		baseUri = FacesContext.getCurrentInstance().getExternalContext().getRequestScheme() + "://"
				+ inetAddress.getHostName() + ":"
				+ FacesContext.getCurrentInstance().getExternalContext().getRequestServerPort()
				+ "/jakartaee-cafe/rest/coffees";
		this.client = ClientBuilder.newClient();
		this.getAllCoffees();
	} catch (IllegalArgumentException | NullPointerException | WebApplicationException | UnknownHostException ex) {
		logger.severe("Processing of HTTP response failed.");
		ex.printStackTrace();
	}
}
 
Example #6
Source File: ProviderInjectionTest.java    From microprofile-jwt-auth with Apache License 2.0 6 votes vote down vote up
@RunAsClient
@Test(groups = TEST_GROUP_CDI_PROVIDER,
    description = "Verify that the injected aud claim is as expected")
public void verifyInjectedAudience2() throws Exception {
    Reporter.log("Begin verifyInjectedAudience\n");
    String uri = baseURL.toExternalForm() + "endp/verifyInjectedAudience";
    WebTarget echoEndpointTarget = ClientBuilder.newClient()
        .target(uri)
        .queryParam(Claims.aud.name(), "s6BhdRkqt3")
        .queryParam(Claims.auth_time.name(), authTimeClaim);
    Response response = echoEndpointTarget.request(MediaType.APPLICATION_JSON).header(HttpHeaders.AUTHORIZATION, "Bearer " + token).get();
    Assert.assertEquals(response.getStatus(), HttpURLConnection.HTTP_OK);
    String replyString = response.readEntity(String.class);
    JsonReader jsonReader = Json.createReader(new StringReader(replyString));
    JsonObject reply = jsonReader.readObject();
    Reporter.log(reply.toString());
    Assert.assertTrue(reply.getBoolean("pass"), reply.getString("msg"));
}
 
Example #7
Source File: AdminApiKeyStoreTlsAuthTest.java    From pulsar with Apache License 2.0 6 votes vote down vote up
WebTarget buildWebClient() throws Exception {
    ClientConfig httpConfig = new ClientConfig();
    httpConfig.property(ClientProperties.FOLLOW_REDIRECTS, true);
    httpConfig.property(ClientProperties.ASYNC_THREADPOOL_SIZE, 8);
    httpConfig.register(MultiPartFeature.class);

    ClientBuilder clientBuilder = ClientBuilder.newBuilder().withConfig(httpConfig)
        .register(JacksonConfigurator.class).register(JacksonFeature.class);

    SSLContext sslCtx = KeyStoreSSLContext.createClientSslContext(
            KEYSTORE_TYPE,
            CLIENT_KEYSTORE_FILE_PATH,
            CLIENT_KEYSTORE_PW,
            KEYSTORE_TYPE,
            BROKER_TRUSTSTORE_FILE_PATH,
            BROKER_TRUSTSTORE_PW);

    clientBuilder.sslContext(sslCtx).hostnameVerifier(NoopHostnameVerifier.INSTANCE);
    Client client = clientBuilder.build();

    return client.target(brokerUrlTls.toString());
}
 
Example #8
Source File: SWARM_513Test.java    From thorntail with Apache License 2.0 6 votes vote down vote up
@Test
@RunAsClient
@InSequence(1)
public void testCreateTicketClient() throws Exception {
    StringBuffer sb = new StringBuffer();
    sb.append("<ticketDTO>");
    sb.append("<price>12.00</price>");
    sb.append("</ticketDTO>");

    Client client = ClientBuilder.newClient();
    WebTarget target = client.target("http://localhost:8080").path("tickets");

    javax.ws.rs.core.Response response = target.request(MediaType.TEXT_XML)
            .post(Entity.entity(sb.toString(), MediaType.TEXT_XML));

    Assert.assertEquals(201, response.getStatus());
    Assert.assertTrue(response.getHeaders().keySet().contains("Location"));
}
 
Example #9
Source File: SchemaRegistryRestAPIClient.java    From apicurio-registry with Apache License 2.0 6 votes vote down vote up
private static Client getJAXRSClient(boolean skipSSLValidation) throws KeyManagementException, NoSuchAlgorithmException {
    ClientBuilder cb = ClientBuilder.newBuilder();

    cb.connectTimeout(10, TimeUnit.SECONDS);

    Client newClient;
    if (skipSSLValidation) {
        SSLContext nullSSLContext = SSLContext.getInstance("TLSv1.2");
        nullSSLContext.init(null, nullTrustManager, null);
        cb.hostnameVerifier(NullHostnameVerifier.INSTANCE)
          .sslContext(nullSSLContext);

        newClient = cb.build();
    } else {
        newClient = cb.build();
    }

    newClient.register(JacksonJsonProvider.class);

    return newClient;
}
 
Example #10
Source File: JSAPITest.java    From resteasy-examples with Apache License 2.0 6 votes vote down vote up
@Test
public void testService() throws Exception
{
   Client client = ClientBuilder.newClient();
   WebTarget target = client.target("http://localhost:9095/rest/mine/pairs");
   Invocation.Builder request = target.request();
   request.accept("application/json");
   String rtn = request.get().readEntity(String.class);
   String expected = "{\"key\":\"key22\",\"value\":\"value22\"}";
   Assert.assertTrue("Expected json response", rtn.contains(expected));

   target = client.target("http://localhost:9095/rest/mine/pairs");
   request = target.request();
   request.accept("application/xml");
   rtn = request.get().readEntity(String.class);
   Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new ByteArrayInputStream(rtn.getBytes()));
   Assert.assertTrue("Expected xml element",doc.getDocumentElement().getElementsByTagName("pair").getLength() == 23);
}
 
Example #11
Source File: RestDemoServiceIT.java    From demo-restWS-spring-jersey-jpa2-hibernate with MIT License 6 votes vote down vote up
@Test
public void testGetPodcast() 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/2");

	Builder request = webTarget.request(MediaType.APPLICATION_JSON);

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

	Podcast podcast = response.readEntity(Podcast.class);

	ObjectMapper mapper = new ObjectMapper();
	System.out
			.print("Received podcast from LEGACY database *************************** "
					+ mapper.writerWithDefaultPrettyPrinter()
							.writeValueAsString(podcast));

}
 
Example #12
Source File: IssValidationTest.java    From microprofile-jwt-auth with Apache License 2.0 6 votes vote down vote up
@RunAsClient
@Test(groups = TEST_GROUP_CONFIG,
    description = "Validate that JWK with iss that matches mp.jwt.verify.issuer returns HTTP_OK")
public void testRequiredIss() throws Exception {
    Reporter.log("testRequiredIss, expect HTTP_OK");

    String uri = baseURL.toExternalForm() + "endp/verifyIssIsOk";
    WebTarget echoEndpointTarget = ClientBuilder.newClient()
        .target(uri)
        ;
    Response response = echoEndpointTarget.request(APPLICATION_JSON).header(HttpHeaders.AUTHORIZATION, "Bearer "+token).get();
    Assert.assertEquals(response.getStatus(), HttpURLConnection.HTTP_OK);
    String replyString = response.readEntity(String.class);
    JsonReader jsonReader = Json.createReader(new StringReader(replyString));
    JsonObject reply = jsonReader.readObject();
    Reporter.log(reply.toString());
    Assert.assertTrue(reply.getBoolean("pass"), reply.getString("msg"));
}
 
Example #13
Source File: SnomedClientRest.java    From SNOMED-in-5-minutes with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the concept for the specified concept id.
 *
 * @param conceptId the concept id
 * @return the concept for id
 * @throws Exception the exception
 */
public Concept findByConceptId(String conceptId) throws Exception {
  Logger.getLogger(getClass()).debug(
      "Snomed Client - find concept by concept id " + conceptId);

  validateNotEmpty(conceptId, "conceptId");

  final Client client = ClientBuilder.newClient();
  final WebTarget target = client.target(getUrl() + "/concepts/" + conceptId);
  final Response response = target.request(MediaType.APPLICATION_JSON).get();
  final String resultString = response.readEntity(String.class);
  if (response.getStatusInfo().getFamily() == Family.SUCCESSFUL) {
    // n/a
  } else {
    throw new Exception(response.toString());
  }

  // converting to object
  return Utility.getGraphForJson(resultString, Concept.class);
}
 
Example #14
Source File: DriverUploadTest.java    From syndesis with Apache License 2.0 6 votes vote down vote up
@Test @Ignore //Easy way to quickly upload an extension when running Application.main()
public void upload2Server() throws IOException {

    URL driverClasspath = DriverUploadTest.class.getClassLoader().getResource(FILE_CLASSPATH);
    assertThat(driverClasspath).isNotNull();

    final WebTarget target = ClientBuilder.newClient()
            .target(String.format("http://%s/api/v1/drivers",
                    "localhost:8080"));

    MultipartFormDataOutput multipart = new MultipartFormDataOutput();
    multipart.addFormData("fileName", "myExtDir", MediaType.TEXT_PLAIN_TYPE);
    multipart.addFormData("file", driverClasspath.openStream(), MediaType.APPLICATION_OCTET_STREAM_TYPE);

    GenericEntity<MultipartFormDataOutput> entity = new GenericEntity<MultipartFormDataOutput>(multipart) {};
    target.request().post(Entity.entity(entity, MediaType.MULTIPART_FORM_DATA_TYPE),Boolean.class);

}
 
Example #15
Source File: PrimitiveInjectionTest.java    From microprofile-jwt-auth with Apache License 2.0 6 votes vote down vote up
@RunAsClient
@Test(groups = TEST_GROUP_CDI_PROVIDER,
    description = "Verify that the injected exp claim is as expected")
public void verifyInjectedExpiration() throws Exception {
    Reporter.log("Begin verifyInjectedExpiration\n");
    String uri = baseURL.toExternalForm() + "endp/verifyInjectedExpiration";
    WebTarget echoEndpointTarget = ClientBuilder.newClient()
        .target(uri)
        .queryParam(Claims.exp.name(), expClaim)
        .queryParam(Claims.auth_time.name(), authTimeClaim);
    Response response = echoEndpointTarget.request(MediaType.APPLICATION_JSON).header(HttpHeaders.AUTHORIZATION, "Bearer " + token).get();
    Assert.assertEquals(response.getStatus(), HttpURLConnection.HTTP_OK);
    String replyString = response.readEntity(String.class);
    JsonReader jsonReader = Json.createReader(new StringReader(replyString));
    JsonObject reply = jsonReader.readObject();
    Reporter.log(reply.toString());
    Assert.assertTrue(reply.getBoolean("pass"), reply.getString("msg"));
}
 
Example #16
Source File: CalcTest.java    From tomee with Apache License 2.0 6 votes vote down vote up
@Test
public void tesSubtractASyncTimeout() throws Exception {
    final WebTarget webTarget = ClientBuilder.newClient().target(base.toURI());

    final Response response = webTarget
            .queryParam("op", "subtract")
            .queryParam("x", "50")
            .queryParam("y", "34")
            .queryParam("async", "true")
            .queryParam("delay", "10000")
            .queryParam("timeout", "1000")
            .request()
            .accept(MediaType.MEDIA_TYPE_WILDCARD)
            .get();

    Assert.assertEquals(500, response.getStatus());
    final InputStream is = (InputStream) response.getEntity();
    final String responsePayload = IO.slurp(is);
    System.out.println(responsePayload);
}
 
Example #17
Source File: ClientTokenExchangeTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
private Response checkTokenExchange() {
    Client httpClient = ClientBuilder.newClient();
    WebTarget exchangeUrl = httpClient.target(OAuthClient.AUTH_SERVER_ROOT)
            .path("/realms")
            .path(TEST)
            .path("protocol/openid-connect/token");

    Response response = exchangeUrl.request()
            .header(HttpHeaders.AUTHORIZATION, BasicAuthHelper.createHeader("direct-exchanger", "secret"))
            .post(Entity.form(
                    new Form()
                            .param(OAuth2Constants.GRANT_TYPE, OAuth2Constants.TOKEN_EXCHANGE_GRANT_TYPE)
                            .param(OAuth2Constants.REQUESTED_SUBJECT, "impersonated-user")

            ));
    return response;
}
 
Example #18
Source File: JAXRSAsyncClientTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testNonExistentJaxrs20WithPost() throws Exception {
    Client client = ClientBuilder.newClient();
    WebTarget target = client.target("http://168.168.168.168/");
    Invocation.Builder builder = target.request();
    Entity<String> entity = Entity.entity("entity", MediaType.WILDCARD_TYPE);
    Invocation invocation = builder.buildPost(entity);
    Future<String> future = invocation.submit(
        new GenericType<String>() {
        }
    );

    try {
        future.get();
    } catch (Exception ex) {
        Throwable cause = ex.getCause();
        assertTrue(cause instanceof ProcessingException);
    }
}
 
Example #19
Source File: RestClient.java    From dubbox-hystrix with Apache License 2.0 6 votes vote down vote up
private static void registerUser(String url, MediaType mediaType) {
    System.out.println("Registering user via " + url);
    User user = new User(1L, "larrypage");
    Client client = ClientBuilder.newClient();
    WebTarget target = client.target(url);
    Response response = target.request().post(Entity.entity(user, mediaType));

    try {
        if (response.getStatus() != 200) {
            throw new RuntimeException("Failed with HTTP error code : " + response.getStatus());
        }
        System.out.println("Successfully got result: " + response.readEntity(String.class));
    } finally {
        response.close();
        client.close();
    }
}
 
Example #20
Source File: AuthenticationDevice.java    From java-oauth-server with Apache License 2.0 5 votes vote down vote up
private static Client createClient(int readTimeout, int connectTimeout)
{
    // Client configuration.
    ClientConfig config = new ClientConfig();

    // Read timeout.
    config.property(READ_TIMEOUT, readTimeout);

    // Connect timeout.
    config.property(CONNECT_TIMEOUT, connectTimeout);

    // The client that synchronously communicates with the authentication device simulator.
    return ClientBuilder.newClient(config);
}
 
Example #21
Source File: SimpleBankAPITest.java    From reladomo-kata with Apache License 2.0 5 votes vote down vote up
private WebTarget webTarget(String path)
{
    Client client = ClientBuilder.newClient();
    client.register(JacksonFeature.class);
    client.register(SimpleBankJacksonObjectMapperProvider.class);
    return client.target("http://localhost:9998").path(path);
}
 
Example #22
Source File: ClientResponseFilterTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testAsyncClientResponseFilterWhenNotFound() throws Exception {
    try (Response response = ClientBuilder.newClient()
         .register(AddHeaderClientResponseFilter.class)
         .target(ADDRESS)
         .request()
         .async()
         .put(null)
         .get(10, TimeUnit.SECONDS)) {
        assertEquals(404, response.getStatus());
        assertEquals("true", response.getHeaderString("X-Done"));
    }
}
 
Example #23
Source File: BasicAuthServletTest.java    From tomee with Apache License 2.0 5 votes vote down vote up
@Test
public void noUser() throws Exception {
    final String servlet = "http://localhost:" + container.getConfiguration().getHttpPort() + "/basic";
    assertEquals(401, ClientBuilder.newBuilder().register(new BasicAuthFilter("unknown", "tomcat")).build()
                                   .target(servlet)
                                   .request()
                                   .get().getStatus());
}
 
Example #24
Source File: BaseResourceTest.java    From incubator-pinot with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("SuspiciousMethodCalls")
@BeforeClass
public void setUp()
    throws Exception {
  FileUtils.deleteQuietly(INDEX_DIR);
  Assert.assertTrue(INDEX_DIR.mkdirs());
  URL resourceUrl = getClass().getClassLoader().getResource(AVRO_DATA_PATH);
  Assert.assertNotNull(resourceUrl);
  _avroFile = new File(resourceUrl.getFile());

  // Mock the instance data manager
  InstanceDataManager instanceDataManager = mock(InstanceDataManager.class);
  when(instanceDataManager.getTableDataManager(anyString()))
      .thenAnswer(invocation -> _tableDataManagerMap.get(invocation.getArguments()[0]));
  when(instanceDataManager.getAllTables()).thenReturn(_tableDataManagerMap.keySet());

  // Mock the server instance
  ServerInstance serverInstance = mock(ServerInstance.class);
  when(serverInstance.getInstanceDataManager()).thenReturn(instanceDataManager);
  when(serverInstance.getInstanceDataManager().getSegmentFileDirectory()).thenReturn(FileUtils.getTempDirectoryPath());
  // Add the default tables and segments.
  String realtimeTableName = TableNameBuilder.REALTIME.tableNameWithType(TABLE_NAME);
  String offlineTableName = TableNameBuilder.OFFLINE.tableNameWithType(TABLE_NAME);

  addTable(realtimeTableName);
  addTable(offlineTableName);
  setUpSegment(realtimeTableName, "default", _realtimeIndexSegments);
  setUpSegment(offlineTableName, "default", _offlineIndexSegments);

  _adminApiApplication = new AdminApiApplication(serverInstance, new AllowAllAccessFactory());
  _adminApiApplication.start(CommonConstants.Server.DEFAULT_ADMIN_API_PORT);
  _webTarget = ClientBuilder.newClient().target(_adminApiApplication.getBaseUri());
}
 
Example #25
Source File: StaticResourcesTest.java    From rest-utils with Apache License 2.0 5 votes vote down vote up
private void testGet(String path, int expectedStatus, String expectedMessage) {
  Response response = ClientBuilder.newClient(app.resourceConfig.getConfiguration())
      .target("http://localhost:" + config.getInt(RestConfig.PORT_CONFIG))
      .path(path)
      .request()
      .get();
  assertEquals(expectedStatus, response.getStatus());
  final String entity = response.readEntity(String.class);
  assertEquals(expectedMessage, entity == null ? null : entity.trim());
}
 
Example #26
Source File: OAuthResource.java    From clouditor with Apache License 2.0 5 votes vote down vote up
private TokenResponse retrieveAccessToken(String code) {
  var tokenUrl = this.engine.getOAuthTokenUrl();

  LOGGER.info("Trying to retrieve access token from {}", tokenUrl);

  var uri =
      UriBuilder.fromUri(tokenUrl)
          .queryParam("grant_type", "authorization_code")
          .queryParam("code", code)
          .build();

  var client =
      ClientBuilder.newClient()
          .register(
              (ClientRequestFilter)
                  requestContext -> {
                    var headers = requestContext.getHeaders();
                    headers.add(
                        "Authorization",
                        "Basic "
                            + Base64.getEncoder()
                                .encodeToString(
                                    (this.engine.getOAuthClientId()
                                            + ":"
                                            + this.engine.getOAuthClientSecret())
                                        .getBytes()));
                  })
          .register(
              (ClientResponseFilter)
                  (requestContext, responseContext) -> {
                    // stupid workaround because some oauth servers incorrectly sends two
                    // Content-Type
                    // headers! fix it!
                    var contentType = responseContext.getHeaders().getFirst("Content-Type");
                    responseContext.getHeaders().putSingle("Content-Type", contentType);
                  });

  return client.target(uri).request().post(null, TokenResponse.class);
}
 
Example #27
Source File: AutoBValTest.java    From tomee with Apache License 2.0 5 votes vote down vote up
@Test
public void outFailing() {
    final Payload payload = new Payload();
    payload.setName("empty");
    assertEquals(
            Response.Status.BAD_REQUEST.getStatusCode(), // thanks to the mapper
            ClientBuilder.newClient().target(base.toExternalForm()).path("openejb/test").request(MediaType.APPLICATION_JSON_TYPE)
                    .post(Entity.entity(payload, MediaType.APPLICATION_JSON_TYPE)).getStatus());
}
 
Example #28
Source File: ControllerRestApiTest.java    From pravega with Apache License 2.0 5 votes vote down vote up
public ControllerRestApiTest() {

        org.glassfish.jersey.client.ClientConfig clientConfig = new org.glassfish.jersey.client.ClientConfig();
        clientConfig.register(JacksonJsonProvider.class);
        clientConfig.property("sun.net.http.allowRestrictedHeaders", "true");

        if (Utils.AUTH_ENABLED) {
            HttpAuthenticationFeature feature = HttpAuthenticationFeature.basic("admin", "1111_aaaa");
            clientConfig.register(feature);
        }

        client = ClientBuilder.newClient(clientConfig);
    }
 
Example #29
Source File: TrialResource.java    From Java-EE-8-and-Angular with MIT License 5 votes vote down vote up
private void rx() {
    System.out.println("rx called");
    Client client = ClientBuilder.newClient();
    WebTarget base = client.target("http://localhost:8080/ims-micro-users/resources/trials/slow");
    CompletionStage<User> csf = base.request("application/json")
            .rx()
            .get(User.class);
    System.out.println("rx get done");
    csf.thenAccept(System.out::println);
    System.out.println("accept ended");
}
 
Example #30
Source File: SubResourceTest.java    From tomee with Apache License 2.0 5 votes vote down vote up
@Test
public void rest() throws IOException {
    final String response = ClientBuilder.newClient()
            .target("http://127.0.0.1:" + port + "/SubResourceTest/")
            .path("sub1/sub2/value")
            .request()
            .accept(MediaType.TEXT_PLAIN_TYPE)
            .get(String.class);
    assertEquals("2", response);
}