Java Code Examples for org.apache.cxf.jaxrs.client.WebClient

The following examples show how to use org.apache.cxf.jaxrs.client.WebClient. These examples are extracted from open source projects. 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 Project: cxf   Source File: JAXRSHTTPSignatureTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testPropertiesWrongSignatureVerification() {

    URL busFile = JAXRSHTTPSignatureTest.class.getResource("client.xml");

    List<Object> providers = new ArrayList<>();
    providers.add(new CreateSignatureInterceptor());
    providers.add(new VerifySignatureClientFilter());
    String address = "http://localhost:" + PORT + "/httpsigresponse/bookstore/books";
    WebClient client = WebClient.create(address, providers, busFile.toString());
    client.type("application/xml").accept("application/xml");

    Map<String, Object> properties = new HashMap<>();
    properties.put("rs.security.signature.out.properties",
        "org/apache/cxf/systest/jaxrs/security/httpsignature/alice.httpsig.properties");
    properties.put("rs.security.signature.in.properties",
                   "org/apache/cxf/systest/jaxrs/security/httpsignature/alice.httpsig.properties");
    WebClient.getConfig(client).getRequestContext().putAll(properties);

    try {
        client.post(new Book("CXF", 126L));
        fail("Failure expected on the wrong signature verification keystore");
    } catch (Exception ex) {
        // expected
    }
}
 
Example 2
Source Project: cxf   Source File: JAXRS20ClientServerBookTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testPreMatchContainerFilterThrowsException() {
    String address = "http://localhost:" + PORT + "/throwException";
    WebClient wc = WebClient.create(address);
    Response response = wc.get();
    assertEquals(500, response.getStatus());
    assertEquals("Prematch filter error", response.readEntity(String.class));
    assertEquals("prematch", response.getHeaderString("FilterException"));
    assertEquals("OK", response.getHeaderString("Response"));
    assertEquals("OK2", response.getHeaderString("Response2"));
    assertNull(response.getHeaderString("IOException"));
    assertNull(response.getHeaderString("DynamicResponse"));
    assertNull(response.getHeaderString("Custom"));
    assertEquals("serverWrite", response.getHeaderString("ServerWriterInterceptor"));
    assertEquals("serverWrite2", response.getHeaderString("ServerWriterInterceptor2"));
    assertEquals("serverWriteHttpResponse",
                 response.getHeaderString("ServerWriterInterceptorHttpResponse"));
    assertEquals("text/plain;charset=us-ascii", response.getMediaType().toString());
}
 
Example 3
Source Project: cxf   Source File: PublicClientTest.java    License: Apache License 2.0 6 votes vote down vote up
@org.junit.Test
public void testAuthorizationCodeGrant() throws Exception {
    URL busFile = PublicClientTest.class.getResource("publicclient.xml");

    String address = "https://localhost:" + JCACHE_PORT + "/services/";
    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);
    assertNotNull(code);

    // Now get the access token - note services2 doesn't require basic auth
    String address2 = "https://localhost:" + JCACHE_PORT + "/services2/";
    client = WebClient.create(address2, busFile.toString());

    ClientAccessToken accessToken =
        OAuth2TestUtils.getAccessTokenWithAuthorizationCode(client, code);
    assertNotNull(accessToken.getTokenKey());
}
 
Example 4
Source Project: cxf   Source File: Client.java    License: Apache License 2.0 6 votes vote down vote up
public static void main(final String[] args) throws Exception {
    final Tracer tracer = new Configuration("tracer-client") 
        .withSampler(new SamplerConfiguration().withType(ConstSampler.TYPE).withParam(1))
        .withReporter(new ReporterConfiguration().withSender(
            new SenderConfiguration() {
                @Override
                public Sender getSender() {
                    return new Slf4jLogSender();
                }
            }
        ))
        .getTracer();
    final OpenTracingClientProvider provider = new OpenTracingClientProvider(tracer);

    final Response response = WebClient
        .create("http://localhost:9000/catalog", Arrays.asList(provider))
        .accept(MediaType.APPLICATION_JSON)
        .get();

    System.out.println(response.readEntity(String.class));
    response.close();
}
 
Example 5
Source Project: archiva   Source File: BrowseServiceTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void readArtifactContentTextPom()
    throws Exception
{
    BrowseService browseService = getBrowseService( authorizationHeader, true );

    WebClient.client( browseService ).accept( MediaType.TEXT_PLAIN );

    String text =
        browseService.getArtifactContentText( "commons-logging", "commons-logging", "1.1", null, "pom", null,
                                              TEST_REPO_ID ).getContent();

    log.info( "text: {}", text );

    assertThat( text ).contains(
        "<url>http://jakarta.apache.org/commons/${pom.artifactId.substring(8)}/</url>" ).contains(
        "<subscribe>[email protected]</subscribe>" );
}
 
Example 6
Source Project: cxf   Source File: JAXRSOAuth2Test.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testJWTNoExpiry() throws Exception {
    String address = "https://localhost:" + port + "/oauth2-auth-jwt/token";
    WebClient wc = createWebClient(address);

    // Create the JWT Token
    String token = OAuth2TestUtils.createToken("resourceOwner", "alice",
                                               address, false, true);

    Map<String, String> extraParams = new HashMap<>();
    extraParams.put(Constants.CLIENT_AUTH_ASSERTION_TYPE,
                    "urn:ietf:params:oauth:client-assertion-type:jwt-bearer");
    extraParams.put(Constants.CLIENT_AUTH_ASSERTION_PARAM, token);

    try {
        OAuthClientUtils.getAccessToken(wc, new CustomGrant(), extraParams);
        fail("Failure expected on no expiry");
    } catch (Exception ex) {
        // expected
    }
}
 
Example 7
Source Project: cxf   Source File: JAXRSHTTPSignatureTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testUnknownKeyId() throws Exception {

    URL busFile = JAXRSHTTPSignatureTest.class.getResource("client.xml");

    CreateSignatureInterceptor signatureFilter = new CreateSignatureInterceptor();
    KeyStore keyStore = KeyStore.getInstance("JKS");
    keyStore.load(ClassLoaderUtils.getResourceAsStream("keys/alice.jks", this.getClass()),
                  "password".toCharArray());
    PrivateKey privateKey = (PrivateKey)keyStore.getKey("alice", "password".toCharArray());
    assertNotNull(privateKey);

    MessageSigner messageSigner = new MessageSigner(keyId -> privateKey, "unknown-key-id");
    signatureFilter.setMessageSigner(messageSigner);

    String address = "http://localhost:" + PORT + "/httpsig/bookstore/books";
    WebClient client =
        WebClient.create(address, Collections.singletonList(signatureFilter), busFile.toString());
    client.type("application/xml").accept("application/xml");

    Response response = client.post(new Book("CXF", 126L));
    assertEquals(400, response.getStatus());
}
 
Example 8
Source Project: cxf   Source File: JAXRSOAuth2Test.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testBasicAuthClientCred() throws Exception {
    String address = "https://localhost:" + port + "/oauth2/token";
    WebClient wc = createWebClient(address);
    ClientCredentialsGrant grant = new ClientCredentialsGrant();
    // Pass client_id & client_secret as form properties
    // (instead WebClient can be initialized with username & password)
    grant.setClientId("bob");
    grant.setClientSecret("bobPassword");
    try {
        OAuthClientUtils.getAccessToken(wc, grant);
        fail("Form based authentication is not supported");
    } catch (OAuthServiceException ex) {
        assertEquals(OAuthConstants.UNAUTHORIZED_CLIENT, ex.getError().getError());
    }

    ClientAccessToken at = OAuthClientUtils.getAccessToken(wc,
                                                           new Consumer("bob", "bobPassword"),
                                                           new ClientCredentialsGrant(),
                                                           true);
    assertNotNull(at.getTokenKey());
}
 
Example 9
Source Project: cxf   Source File: JAXRSOAuth2Test.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testSAMLAudRestr() throws Exception {
    String address = "https://localhost:" + port + "/oauth2-auth/token";
    WebClient wc = createWebClient(address);

    String audienceURI = "https://localhost:" + port + "/oauth2-auth/token2";
    String assertion = OAuth2TestUtils.createToken(audienceURI, true, true);
    String encodedAssertion = Base64UrlUtility.encode(assertion);

    Map<String, String> extraParams = new HashMap<>();
    extraParams.put(Constants.CLIENT_AUTH_ASSERTION_TYPE, Constants.CLIENT_AUTH_SAML2_BEARER);
    extraParams.put(Constants.CLIENT_AUTH_ASSERTION_PARAM, encodedAssertion);

    try {
        OAuthClientUtils.getAccessToken(wc, new CustomGrant(), extraParams);
        fail("Failure expected on a bad audience restriction");
    } catch (OAuthServiceException ex) {
        // expected
    }
}
 
Example 10
private List<Element> getWadlResourcesInfo(String baseURI, String requestURI, int size) throws Exception {
    WebClient client = WebClient.create(requestURI + "?_wadl&_type=xml");
    WebClient.getConfig(client).getHttpConduit().getClient().setReceiveTimeout(10000000);
    Document doc = StaxUtils.read(new InputStreamReader(client.get(InputStream.class), StandardCharsets.UTF_8));
    Element root = doc.getDocumentElement();
    assertEquals(WadlGenerator.WADL_NS, root.getNamespaceURI());
    assertEquals("application", root.getLocalName());
    List<Element> resourcesEls = DOMUtils.getChildrenWithName(root,
                                                              WadlGenerator.WADL_NS, "resources");
    assertEquals(1, resourcesEls.size());
    Element resourcesEl = resourcesEls.get(0);
    assertEquals(baseURI, resourcesEl.getAttribute("base"));
    List<Element> resourceEls =
        DOMUtils.getChildrenWithName(resourcesEl,
                                     WadlGenerator.WADL_NS, "resource");
    assertEquals(size, resourceEls.size());
    return resourceEls;
}
 
Example 11
Source Project: cxf   Source File: JAXRSSamlTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testInvalidSAMLTokenAsHeader() throws Exception {
    String address = "https://localhost:" + PORT + "/samlheader/bookstore/books/123";

    JAXRSClientFactoryBean bean = new JAXRSClientFactoryBean();
    bean.setAddress(address);

    SpringBusFactory bf = new SpringBusFactory();
    URL busFile = JAXRSSamlTest.class.getResource("client.xml");
    Bus springBus = bf.createBus(busFile.toString());
    bean.setBus(springBus);

    WebClient wc = bean.createWebClient();
    wc.header("Authorization", "SAML invalid_grant");
    Response r = wc.get();
    assertEquals(401, r.getStatus());
}
 
Example 12
/**
 * 删除已经部署的请假流程
 *
 * @return
 * @throws java.io.IOException
 */
private static void deleteLeaveDeployment() throws IOException {
    WebClient client = createClient("repository/deployments");
    Response response = client.get();
    printResult("查询leave.bpmn", response);

    response = client.get();
    InputStream stream = (InputStream) response.getEntity();
    JsonNode responseNode = objectMapper.readTree(stream);
    Iterator<JsonNode> elements = responseNode.elements();
    JsonNode next = elements.next();
    ArrayNode arrayNode = (ArrayNode) next;
    for (JsonNode jsonNode : arrayNode) {
        String deploymentId = jsonNode.get("id").asText();
        if (StringUtils.isBlank(deploymentId)) {
            continue;
        }
        String url = "/repository/deployments/" + deploymentId + "?cascade=true";
        client = createClient(url);
        response = client.delete();
        printResult("删除deployment", response);
    }
}
 
Example 13
Source Project: cxf   Source File: JAXRSMultipartTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testAddGetJaxbBooksWebClient() throws Exception {
    String address = "http://localhost:" + PORT + "/bookstore/books/jaxbonly";
    WebClient client = WebClient.create(address);

    client.type("multipart/mixed;type=application/xml").accept("multipart/mixed");

    Book b = new Book("jaxb", 1L);
    Book b2 = new Book("jaxb2", 2L);
    List<Book> books = new ArrayList<>();
    books.add(b);
    books.add(b2);
    Collection<? extends Book> coll = client.postAndGetCollection(books, Book.class);
    List<Book> result = new ArrayList<>(coll);
    Book jaxb = result.get(0);
    assertEquals("jaxb", jaxb.getName());
    assertEquals(1L, jaxb.getId());
    Book jaxb2 = result.get(1);
    assertEquals("jaxb2", jaxb2.getName());
    assertEquals(2L, jaxb2.getId());
}
 
Example 14
Source Project: cxf   Source File: JAXRSHTTPSignatureTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testWrongHTTPMethod() throws Exception {

    URL busFile = JAXRSHTTPSignatureTest.class.getResource("client.xml");

    ClientTestFilter signatureFilter = new ClientTestFilter();
    signatureFilter.setHttpMethod("GET");

    KeyStore keyStore = KeyStore.getInstance("JKS");
    keyStore.load(ClassLoaderUtils.getResourceAsStream("keys/alice.jks", this.getClass()),
                  "password".toCharArray());
    PrivateKey privateKey = (PrivateKey)keyStore.getKey("alice", "password".toCharArray());
    assertNotNull(privateKey);

    MessageSigner messageSigner = new MessageSigner(keyId -> privateKey, "alice-key-id");
    signatureFilter.setMessageSigner(messageSigner);

    String address = "http://localhost:" + PORT + "/httpsig/bookstore/books";
    WebClient client =
        WebClient.create(address, Collections.singletonList(signatureFilter), busFile.toString());
    client.type("application/xml").accept("application/xml");

    Response response = client.post(new Book("CXF", 126L));
    assertEquals(400, response.getStatus());
}
 
Example 15
Source Project: cxf   Source File: JAXRSClientServerQueryParamBookTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testListOfStringsWebClient() throws Exception {
    WebClient wc = createWebClient();
    
    Response r = wc
            .path("/bookstore/querysub/listofstrings")
            .query("value", "this is")
            .query("value", "the book")
            .query("value", "title")
            .accept("text/xml")
            .get();

    assertThat(wc.getCurrentURI().toString(), endsWith("value=this+is&value=the+book&value=title"));
    try (InputStream is = (InputStream)r.getEntity()) {
        XMLSource source = new XMLSource(is);
        assertEquals("this is the book title", source.getValue("Book/name"));
    }
}
 
Example 16
Source Project: cxf   Source File: JAXRSHttpsBookTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testCustomVerbProxyFromSpringWildcard() throws Exception {
    ClassPathXmlApplicationContext ctx =
        new ClassPathXmlApplicationContext(new String[] {CLIENT_CONFIG_FILE3});
    Object bean = ctx.getBean("bookService.proxyFactory");
    assertNotNull(bean);
    JAXRSClientFactoryBean cfb = (JAXRSClientFactoryBean) bean;

    BookStore bs = cfb.create(BookStore.class);
    WebClient.getConfig(bs).getRequestContext().put("use.httpurlconnection.method.reflection", true);
    // CXF RS Client code will set this property to true if the http verb is unknown
    // and this property is not already set. The async conduit is loaded in the tests module
    // but we do want to test HTTPUrlConnection reflection hence we set this property to false
    WebClient.getConfig(bs).getRequestContext().put("use.async.http.conduit", false);

    Book book = bs.retrieveBook(new Book("Retrieve", 123L));
    assertEquals("Retrieve", book.getName());

    ctx.close();
}
 
Example 17
Source Project: carbon-identity-framework   Source File: TestService.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testHomeXML() {
    if (!waitForWADL()) {
        return;
    }

    WebClient client = WebClient.create(ENDPOINT_ADDRESS);

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

    client.path("home");

    String response = readReource("xml/response-home.xml");

    String webRespose = client.get(String.class);
    assertEquals(response, webRespose);
}
 
Example 18
Source Project: cxf   Source File: JAXRSHTTPSignatureTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testHttpSignatureRsaSha512ServiceProperties() throws Exception {

    URL busFile = JAXRSHTTPSignatureTest.class.getResource("client.xml");

    CreateSignatureInterceptor signatureFilter = new CreateSignatureInterceptor();
    KeyStore keyStore = KeyStore.getInstance("JKS");
    keyStore.load(ClassLoaderUtils.getResourceAsStream("keys/alice.jks", this.getClass()),
                  "password".toCharArray());
    PrivateKey privateKey = (PrivateKey)keyStore.getKey("alice", "password".toCharArray());
    assertNotNull(privateKey);

    MessageSigner messageSigner = new MessageSigner("rsa-sha512", keyId -> privateKey, "alice-key-id");
    signatureFilter.setMessageSigner(messageSigner);

    String address = "http://localhost:" + PORT + "/httpsigrsasha512props/bookstore/books";
    WebClient client =
        WebClient.create(address, Collections.singletonList(signatureFilter), busFile.toString());
    client.type("application/xml").accept("application/xml");

    Response response = client.post(new Book("CXF", 126L));
    assertEquals(200, response.getStatus());

    Book returnedBook = response.readEntity(Book.class);
    assertEquals(126L, returnedBook.getId());
}
 
Example 19
Source Project: archiva   Source File: AbstractArchivaRestTest.java    License: Apache License 2.0 6 votes vote down vote up
protected CommonServices getCommonServices( String authzHeader )
{
    CommonServices service =
        JAXRSClientFactory.create( getBaseUrl() + "/" + getRestServicesPath() + "/archivaServices/",
                                   CommonServices.class,
                                   Arrays.asList( new JacksonJaxbJsonProvider( ), new JacksonJaxbXMLProvider( ) )  );

    if ( authzHeader != null )
    {
        WebClient.client( service ).header( "Authorization", authzHeader );
    }
    WebClient.client(service).header("Referer","http://localhost:"+getServerPort());
    WebClient.getConfig( service ).getHttpConduit().getClient().setReceiveTimeout( 100000000 );
    WebClient.client( service ).accept( MediaType.APPLICATION_JSON_TYPE );
    WebClient.client( service ).type( MediaType.APPLICATION_JSON_TYPE );
    return service;
}
 
Example 20
Source Project: cxf   Source File: JAXRSHttpsBookTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testGetBook123WebClientFromSpringWildcard() throws Exception {
    ClassPathXmlApplicationContext ctx =
        new ClassPathXmlApplicationContext(new String[] {CLIENT_CONFIG_FILE5});
    Object bean = ctx.getBean("bookService.proxyFactory");
    assertNotNull(bean);
    JAXRSClientFactoryBean cfb = (JAXRSClientFactoryBean) bean;

    WebClient wc = (WebClient)cfb.create();
    assertEquals("https://localhost:" + PORT, wc.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 21
Source Project: cxf   Source File: STSRESTTest.java    License: Apache License 2.0 6 votes vote down vote up
@org.junit.Test
public void testIssueSymmetricKeySaml1ShortKeyType() throws Exception {
    WebClient client = webClient()
        .path("saml1.1")
        .query("keyType", "SymmetricKey")
        .accept(MediaType.APPLICATION_XML);

    Document assertionDoc = client.get(Document.class);

    SamlAssertionWrapper assertion = validateSAMLToken(assertionDoc);
    assertTrue(assertion.getSaml2() == null && assertion.getSaml1() != null);

    List<String> methods = assertion.getConfirmationMethods();
    String confirmMethod = null;
    if (methods != null && !methods.isEmpty()) {
        confirmMethod = methods.get(0);
    }
    assertTrue(OpenSAMLUtil.isMethodHolderOfKey(confirmMethod));
    SAMLKeyInfo subjectKeyInfo = assertion.getSubjectKeyInfo();
    assertNotNull(subjectKeyInfo.getSecret());
}
 
Example 22
Source Project: tomee   Source File: MovieServiceTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testInvalidIssuer() throws Exception {
    final WebClient webClient = createWebClient(base);

    final String claims = "{" +
            "  \"sub\":\"Jane Awesome\"," +
            "  \"iss\":\"https://server.example.com\"," +
            "  \"groups\":[\"manager\",\"user\"]," +
            "  \"jti\":\"uB3r7zOr\"," +
            "  \"exp\":2552047942" +
            "}";

    final String token = Tokens.asToken(claims);
    final Response response = webClient.reset()
            .path("/api/movies")
            .header("Content-Type", "application/json")
            .header("Authorization", "Bearer " + token)
            .get();
    assertEquals(403, response.getStatus());
}
 
Example 23
Source Project: cxf   Source File: JAXRSHTTPSignatureTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testHttpSignature() throws Exception {

    URL busFile = JAXRSHTTPSignatureTest.class.getResource("client.xml");

    CreateSignatureInterceptor signatureFilter = new CreateSignatureInterceptor();
    KeyStore keyStore = KeyStore.getInstance("JKS");
    keyStore.load(ClassLoaderUtils.getResourceAsStream("keys/alice.jks", this.getClass()),
                  "password".toCharArray());
    PrivateKey privateKey = (PrivateKey)keyStore.getKey("alice", "password".toCharArray());
    assertNotNull(privateKey);

    MessageSigner messageSigner = new MessageSigner(keyId -> privateKey, "alice-key-id");
    signatureFilter.setMessageSigner(messageSigner);

    String address = "http://localhost:" + PORT + "/httpsig/bookstore/books";
    WebClient client =
        WebClient.create(address, Collections.singletonList(signatureFilter), busFile.toString());
    client.type("application/xml").accept("application/xml");

    Response response = client.post(new Book("CXF", 126L));
    assertEquals(200, response.getStatus());

    Book returnedBook = response.readEntity(Book.class);
    assertEquals(126L, returnedBook.getId());
}
 
Example 24
Source Project: peer-os   Source File: PeerWebClient.java    License: Apache License 2.0 6 votes vote down vote up
public void joinP2PSwarm( final P2PConfig config ) throws PeerException
{
    WebClient client = null;
    Response response;
    try
    {
        remotePeer.checkRelation();
        String path = "/p2ptunnel";

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

        client.type( MediaType.APPLICATION_JSON );
        response = client.post( config );
    }
    catch ( Exception e )
    {
        LOG.error( e.getMessage(), e );
        throw new PeerException( String.format( "Error joining P2P swarm: %s", e.getMessage() ) );
    }
    finally
    {
        WebClientBuilder.close( client );
    }

    WebClientBuilder.checkResponse( response );
}
 
Example 25
Source Project: carbon-identity-framework   Source File: TestService.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testGetDecisionByAttributesBooleanXML() {
    if (!waitForWADL()) {
        return;
    }

    WebClient client = WebClient.create(ENDPOINT_ADDRESS);

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

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

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

    String webRespose = client.post(request, String.class);

    assertEquals(response, webRespose);
}
 
Example 26
Source Project: cxf   Source File: JweJwsReferenceTest.java    License: Apache License 2.0 5 votes vote down vote up
@org.junit.Test
public void testSignatureIncludeCertNegativeTest() throws Exception {

    URL busFile = JweJwsReferenceTest.class.getResource("client.xml");

    List<Object> providers = new ArrayList<>();
    providers.add(new JacksonJsonProvider());
    providers.add(new JwsWriterInterceptor());

    String address = "http://localhost:" + PORT + "/jwsincludecert/bookstore/books";
    WebClient client =
        WebClient.create(address, providers, busFile.toString());
    client.type("application/json").accept("application/json");

    Map<String, Object> properties = new HashMap<>();
    properties.put("rs.security.keystore.type", "jks");
    properties.put("rs.security.keystore.alias", "morpit");
    properties.put("rs.security.keystore.password", "password");
    properties.put("rs.security.key.password", "password");
    properties.put("rs.security.keystore.file", "keys/Morpit.jks");
    properties.put("rs.security.signature.include.cert", "true");
    WebClient.getConfig(client).getRequestContext().putAll(properties);

    // Failure expected as we are signing using a cert not trusted by cxfca.jks
    Response response = client.post(new Book("book", 123L));
    assertNotEquals(response.getStatus(), 200);
}
 
Example 27
Source Project: tomee   Source File: MissingRequiredClaimsTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
    public void testMissingExpiration() throws Exception {
        final Tokens tokens = Tokens.rsa(2048, 256);
        final File appJar = Archive.archive()
                .add(MissingRequiredClaimsTest.class)
                .add(ColorService.class)
                .add(Api.class)
                .add("META-INF/microprofile-config.properties", "#\n" +
                        "mp.jwt.verify.publickey=" + Base64.getEncoder().encodeToString(tokens.getPublicKey().getEncoded()))
                .asJar();

        final ArrayList<String> output = new ArrayList<>();
        final TomEE tomee = TomEE.microprofile()
                .add("webapps/test/WEB-INF/beans.xml", "")
                .add("webapps/test/WEB-INF/lib/app.jar", appJar)
                .watch("org.apache.tomee.microprofile.jwt.", "\n", output::add)
//                .update()
                .build();

        final WebClient webClient = createWebClient(tomee.toURI().resolve("/test").toURL());

        final String claims = "{" +
                "  \"sub\":\"Jane Awesome\"" +
                "}";

        {// invalid token
            final String token = tokens.asToken(claims);
            final Response response = webClient.reset()
                    .path("/movies")
                    .header("Content-Type", "application/json")
                    .header("Authorization", "Bearer " + token)
                    .get();
            assertEquals(401, response.getStatus());
        }

        assertPresent(output, "rejected due to invalid claims");
        assertPresent(output, "No Expiration Time (exp) claim present.");
        assertNotPresent(output, "\tat org."); // no stack traces
    }
 
Example 28
Source Project: cxf   Source File: JAXRS20ClientServerBookTest.java    License: Apache License 2.0 5 votes vote down vote up
private void doTestGetBook(String address, boolean useAsync) {
    WebClient wc = createWebClient(address);
    if (useAsync) {
        WebClient.getConfig(wc).getRequestContext().put("use.async.http.conduit", true);
    }
    Book book = wc.get(Book.class);
    assertEquals(124L, book.getId());
    validateResponse(wc);
}
 
Example 29
protected void runListAllPerformanceTest(String methodName, final String urlPath, final GenericType<? extends List<?>> returnType) {
    runPerformanceTest(
            "CatalogResourcePerformanceTest."+methodName, 
            new Function<WebClient, Void>() {
                @Override
                public Void apply(WebClient client) {
                    List<?> result = client.path(urlPath).get(returnType);
                    assertTrue(result.size() > 0, "size="+result.size());
                    return null;
                }});
}
 
Example 30
Source Project: openapi-generator   Source File: AnotherFakeApiTest.java    License: Apache License 2.0 5 votes vote down vote up
@Before
public void setup() {
    List<?> providers = Arrays.asList(new JacksonJsonProvider(), new JacksonXMLProvider(), new MultipartProvider());

    api = JAXRSClientFactory.create("http://localhost:" + serverPort + "/services", AnotherFakeApi.class, providers);
    org.apache.cxf.jaxrs.client.Client client = WebClient.client(api);

    ClientConfiguration config = WebClient.getConfig(client); 
}