Java Code Examples for org.apache.cxf.jaxrs.client.WebClient#accept()

The following examples show how to use org.apache.cxf.jaxrs.client.WebClient#accept() . 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: JAXRSHttpsBookTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetBook123ProxyFromSpringWildcard() throws Exception {
    ClassPathXmlApplicationContext ctx =
        new ClassPathXmlApplicationContext(new String[] {CLIENT_CONFIG_FILE4});
    Object bean = ctx.getBean("bookService.proxyFactory");
    assertNotNull(bean);
    JAXRSClientFactoryBean cfb = (JAXRSClientFactoryBean) bean;

    BookStore bs = cfb.create(BookStore.class);
    assertEquals("https://localhost:" + PORT, WebClient.client(bs).getBaseURI().toString());

    WebClient wc = WebClient.fromClient(WebClient.client(bs));
    assertEquals("https://localhost:" + PORT, WebClient.client(bs).getBaseURI().toString());
    wc.accept("application/xml");
    wc.path("bookstore/securebooks/123");
    TheBook b = wc.get(TheBook.class);

    assertEquals(b.getId(), 123);
    b = wc.get(TheBook.class);
    assertEquals(b.getId(), 123);
    ctx.close();
}
 
Example 2
Source File: TestService.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
@Test
public void testPdpXML() {
    if (!waitForWADL()) {
        return;
    }

    WebClient client = WebClient.create(ENDPOINT_ADDRESS);

    client.header("Authorization", "Basic YWRtaW46YWRtaW4=");
    client.type("application/xml");
    client.accept("application/xml");

    client.path("pdp");

    String request = readReource("xml/request-pdp-1.xml");
    String response = readReource("xml/response-pdp-1.xml");

    String webRespose = client.post(request, String.class);
    assertEquals(response, webRespose);
}
 
Example 3
Source File: SakaiScriptChangeSiteMemberStatusTest.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
@Test
public void testChangeSiteMemberStatus() {
	WebClient client = WebClient.create(getFullEndpointAddress());

	addClientMocks(client);

	// client call
	client.accept("text/plain");
	client.path("/" + getOperation());
	client.query("sessionid", SESSION_ID);
	client.query("siteid", "siteid");
	client.query("eid", "userEid");
	client.query("active", true);


	// client result
	String result = client.get(String.class);

	// test verifications
	assertNotNull(result);
	assertEquals("success", result);
}
 
Example 4
Source File: TestService.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetDecisionByAttributesBooleanJSON() {
    if (!waitForWADL()) {
        return;
    }

    WebClient client = WebClient.create(ENDPOINT_ADDRESS);

    client.header("Authorization", "Basic YWRtaW46YWRtaW4=");
    client.type("application/json");
    client.accept("application/json");

    client.path("by-attrib-boolean");

    String request = readReource("json/request-by-attrib-bool-1.json");
    String response = readReource("json/response-by-attrib-bool-1.json");

    String webRespose = client.post(request, String.class);
    assertEquals(response, webRespose);
}
 
Example 5
Source File: OIDCKeysServiceTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@org.junit.Test
public void testGetRSAPublicKey() throws Exception {
    URL busFile = OIDCFlowTest.class.getResource("client.xml");

    String address = "https://localhost:" + JCACHE_SERVER.getPort() + "/services/";
    WebClient client = WebClient.create(address, OAuth2TestUtils.setupProviders(),
                                        "alice", "security", busFile.toString());
    client.accept("application/json");

    client.path("keys/");
    Response response = client.get();
    JsonWebKeys jsonWebKeys = response.readEntity(JsonWebKeys.class);

    assertEquals(1, jsonWebKeys.getKeys().size());

    JsonWebKey jsonWebKey = jsonWebKeys.getKeys().get(0);
    assertEquals(KeyType.RSA, jsonWebKey.getKeyType());
    assertEquals("alice", jsonWebKey.getKeyId());
    assertNotNull(jsonWebKey.getProperty("n"));
    assertNotNull(jsonWebKey.getProperty("e"));
    // Check we don't send the private key back
    checkPrivateKeyParametersNotPresent(jsonWebKeys);
}
 
Example 6
Source File: SampleRestApplicationTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testHelloRequest() throws Exception {
    WebClient wc = WebClient.create("http://localhost:" + port + "/services/helloservice");
    wc.accept("text/plain");
    
    // HelloServiceImpl1
    wc.path("sayHello").path("ApacheCxfUser");
    String greeting = wc.get(String.class);
    Assert.assertEquals("Hello ApacheCxfUser, Welcome to CXF RS Spring Boot World!!!", greeting); 
 
    // Reverse to the starting URI
    wc.back(true);

    // HelloServiceImpl2
    wc.path("sayHello2").path("ApacheCxfUser");
    greeting = wc.get(String.class);
    Assert.assertEquals("Hello2 ApacheCxfUser, Welcome to CXF RS Spring Boot World!!!", greeting); 
}
 
Example 7
Source File: SakaiScriptAddMemberToSiteWithRoleBatchTest.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
@Test
	public void testRemoveMemberFromSiteBatchNotExistingSite() {
		WebClient client = WebClient.create(getFullEndpointAddress());
//MODIFY
		addClientMocks(client);

		// client call
		client.accept("text/plain");
		client.path("/" + getOperation());
		client.query("sessionid", SESSION_ID);
		client.query("siteid", "nosite");
		client.query("eids", "user1,nouser");
		client.query("roleid", "student");

		// client result
		thrown.expect(RuntimeException.class);
		client.get(String.class);

	}
 
Example 8
Source File: JAXRSClientServerSpringBookTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetBookWithoutJsonpCallback() throws Exception {
    String url = "http://localhost:" + PORT + "/the/jsonp/books/123";
    WebClient client = WebClient.create(url);
    client.accept("application/json, application/x-javascript");
    WebClient.getConfig(client).getHttpConduit().getClient().setReceiveTimeout(1000000L);
    Response r = client.get();
    assertEquals("application/json", r.getMetadata().getFirst("Content-Type"));
    assertEquals("{\"Book\":{\"id\":123,\"name\":\"CXF in Action\"}}",
                 IOUtils.readStringFromStream((InputStream)r.getEntity()));
}
 
Example 9
Source File: JAXRSClientServerBookTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testDropJSONRootDynamically() {
    WebClient wc = WebClient.create("http://localhost:" + PORT + "/bookstore/dropjsonroot");
    wc.accept("application/json");
    String response = wc.get(String.class);
    // with root: {"Book":{"id":123,"name":"CXF in Action"}}
    assertEquals("{\"id\":123,\"name\":\"CXF in Action\"}", response);
}
 
Example 10
Source File: PeerWebClient.java    From peer-os with Apache License 2.0 5 votes vote down vote up
public HostInterfaces getInterfaces() throws PeerException
{
    WebClient client = null;
    Response response;
    try
    {
        remotePeer.checkRelation();
        String path = "/interfaces";

        client = WebClientBuilder.buildPeerWebClient( peerInfo, path, provider );

        client.type( MediaType.APPLICATION_JSON );
        client.accept( MediaType.APPLICATION_JSON );
        response = client.get();
    }
    catch ( Exception e )
    {
        LOG.error( e.getMessage(), e );
        throw new PeerException( String.format( "Error getting interfaces: %s", e.getMessage() ) );
    }
    finally
    {
        WebClientBuilder.close( client );
    }

    return WebClientBuilder.checkResponse( response, HostInterfaces.class );
}
 
Example 11
Source File: PeerWebClient.java    From peer-os with Apache License 2.0 5 votes vote down vote up
public void updateEnvironmentPubKey( PublicKeyContainer publicKeyContainer ) throws PeerException
{
    WebClient client = null;
    Response response;
    try
    {
        remotePeer.checkRelation();
        String path = "/pek";

        client = WebClientBuilder.buildPeerWebClient( peerInfo, path, provider );

        client.type( MediaType.APPLICATION_JSON );
        client.accept( MediaType.APPLICATION_JSON );
        response = client.put( publicKeyContainer );
    }
    catch ( Exception e )
    {
        LOG.error( e.getMessage(), e );
        throw new PeerException( String.format( "Error updating peer environment key: %s", e.getMessage() ) );
    }
    finally
    {
        WebClientBuilder.close( client );
    }

    WebClientBuilder.checkResponse( response );
}
 
Example 12
Source File: EnvironmentWebClient.java    From peer-os with Apache License 2.0 5 votes vote down vote up
public Containers configureSshInEnvironment( final EnvironmentId environmentId, final SshKeys sshKeys )
        throws PeerException
{
    WebClient client = null;
    Response response;
    try
    {
        String path = String.format( "/%s/containers/sshkeys", environmentId.getId() );

        client = WebClientBuilder.buildEnvironmentWebClient( peerInfo, path, provider );

        client.type( MediaType.APPLICATION_JSON );
        client.accept( MediaType.APPLICATION_JSON );

        response = client.post( sshKeys );
    }
    catch ( Exception e )
    {
        LOG.error( e.getMessage(), e );
        throw new PeerException( "Error configuring ssh in environment: " + e.getMessage() );
    }
    finally
    {
        WebClientBuilder.close( client );
    }

    return WebClientBuilder.checkResponse( response, Containers.class );
}
 
Example 13
Source File: JAXRSSpringSecurityClassTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testBookFromForm() throws Exception {

    WebClient wc = WebClient.create("http://localhost:" + PORT + "/bookstorestorage/bookforms",
                                    "foo", "bar", null);
    wc.accept("application/xml");
    Response r = wc.form(new Form().param("name", "CXF Rocks").param("id", "123"));

    Book b = readBook((InputStream)r.getEntity());
    assertEquals("CXF Rocks", b.getName());
    assertEquals(123L, b.getId());
}
 
Example 14
Source File: JAXRSLocalTransportTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testWebClientPipedDispatch() throws Exception {
    WebClient localClient = WebClient.create("local://books");
    localClient.accept("text/xml");
    localClient.path("bookstore/books");
    Book book = localClient.type("application/xml").post(new Book("New", 124L), Book.class);
    assertEquals(124L, book.getId());
}
 
Example 15
Source File: JAXRSMultipartTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
private void doTestGetBookAsPlainContent(String address) throws Exception {
    WebClient wc = WebClient.create(address);
    WebClient.getConfig(wc).getHttpConduit().getClient().setReceiveTimeout(10000000);
    wc.accept("multipart/mixed");
    MultipartBody book = wc.get(MultipartBody.class);
    Book b = book.getRootAttachment().getObject(Book.class);
    assertEquals(888L, b.getId());
}
 
Example 16
Source File: AbstractJAXRSContinuationsTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testImmediateResumeSubresource() throws Exception {
    WebClient wc = WebClient.create("http://localhost:" + getPort()
                                    + getBaseAddress() + "/books/subresources/books/resume");
    wc.accept("text/plain");
    String str = wc.get(String.class);
    assertEquals("immediateResume", str);
}
 
Example 17
Source File: RegistrationClientImpl.java    From peer-os with Apache License 2.0 5 votes vote down vote up
@Override
public void sendUnregisterRequest( final String destinationHost, final RegistrationData registrationData )
        throws PeerException
{
    WebClient client = null;
    Response response;

    try
    {
        client = restUtil.getTrustedWebClient( buildUrl( destinationHost, "unregister" ), provider );
        client.type( MediaType.APPLICATION_JSON );
        client.accept( MediaType.APPLICATION_JSON );

        response = client.post( registrationData );
    }
    catch ( Exception e )
    {
        throw new PeerException(
                String.format( "Error requesting remote peer '%s': %s.", destinationHost, e.getMessage() ) );
    }
    finally
    {
        WebClientBuilder.close( client );
    }

    WebClientBuilder.checkResponse( response, Response.Status.OK );
}
 
Example 18
Source File: JAXRSSimpleRequestDispatcherTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetTextWelcomeFile() throws Exception {
    String address = "http://localhost:" + PORT + "/dispatch/welcome.txt";
    WebClient client = WebClient.create(address);

    client.accept("text/plain");
    String welcome = client.get(String.class);
    assertEquals("Welcome", welcome);
}
 
Example 19
Source File: ContentHostingSiteHideResources.java    From sakai with Educational Community License v2.0 4 votes vote down vote up
@Test
public void testSiteHideResourcesParams() {
	WebClient client = WebClient.create(getFullEndpointAddress());

	addClientMocks(client);

	// client call
	client.accept("text/plain");
	client.path("/" + getOperation());

	// test empty sessionid
	client.query("sessionid", "");
	client.query("siteid", SITE_ID);
	client.query("hidden", "true");

	// client result
	String result = client.get(String.class);

	// test verifications
	assertNotNull(result);
	assertEquals("failure", result);
	
	// test empty siteid
	client.query("sessionid", SESSION_ID);
	client.query("siteid", "");
	client.query("hidden", "true");

	// client result
	result = client.get(String.class);

	// test verifications
	assertNotNull(result);
	assertEquals("failure", result);
	
	// test empty hidden
	client.query("sessionid", SESSION_ID);
	client.query("siteid", SITE_ID);
	client.query("hidden", "");

	// client result
	result = client.get(String.class);

	// test verifications
	assertNotNull(result);
	assertEquals("failure", result);
}
 
Example 20
Source File: UserInfoTest.java    From cxf with Apache License 2.0 4 votes vote down vote up
@org.junit.Test
public void testSignedUserInfo() throws Exception {
    URL busFile = UserInfoTest.class.getResource("client.xml");

    String address = "https://localhost:" + port + "/services/oidc";
    WebClient client = WebClient.create(address, OAuth2TestUtils.setupProviders(),
                                        "alice", "security", busFile.toString());

    // Save the Cookie for the second request...
    WebClient.getConfig(client).getRequestContext().put(
        org.apache.cxf.message.Message.MAINTAIN_SESSION, Boolean.TRUE);

    // Get Authorization Code
    String code = OAuth2TestUtils.getAuthorizationCode(client, "openid");
    assertNotNull(code);

    // Now get the access token
    client = WebClient.create(address, OAuth2TestUtils.setupProviders(),
                              "consumer-id", "this-is-a-secret", busFile.toString());
    // Save the Cookie for the second request...
    WebClient.getConfig(client).getRequestContext().put(
        org.apache.cxf.message.Message.MAINTAIN_SESSION, Boolean.TRUE);

    ClientAccessToken accessToken =
        OAuth2TestUtils.getAccessTokenWithAuthorizationCode(client, code);
    assertNotNull(accessToken.getTokenKey());
    assertTrue(accessToken.getApprovedScope().contains("openid"));

    String idToken = accessToken.getParameters().get("id_token");
    assertNotNull(idToken);
    validateIdToken(idToken, null);

    // Now invoke on the UserInfo service with the access token
    String userInfoAddress = "https://localhost:" + port + "/services/signed/userinfo";
    WebClient userInfoClient = WebClient.create(userInfoAddress, OAuth2TestUtils.setupProviders(),
                                                busFile.toString());
    userInfoClient.accept("application/jwt");
    userInfoClient.header("Authorization", "Bearer " + accessToken.getTokenKey());

    Response serviceResponse = userInfoClient.get();
    assertEquals(serviceResponse.getStatus(), 200);

    String token = serviceResponse.readEntity(String.class);
    assertNotNull(token);

    JwsJwtCompactConsumer jwtConsumer = new JwsJwtCompactConsumer(token);
    JwtToken jwt = jwtConsumer.getJwtToken();

    assertEquals("alice", jwt.getClaim(JwtConstants.CLAIM_SUBJECT));
    assertEquals("consumer-id", jwt.getClaim(JwtConstants.CLAIM_AUDIENCE));

    KeyStore keystore = KeyStore.getInstance("JKS");
    keystore.load(ClassLoaderUtils.getResourceAsStream("keys/alice.jks", this.getClass()),
                  "password".toCharArray());
    Certificate cert = keystore.getCertificate("alice");
    assertNotNull(cert);

    assertTrue(jwtConsumer.verifySignatureWith((X509Certificate)cert,
                                                      SignatureAlgorithm.RS256));
}