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

The following examples show how to use org.apache.cxf.jaxrs.client.WebClient#fromClient() . 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: JAXRSMultithreadedClientTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
private void runWebClients(WebClient client, int numberOfClients,
    boolean threadSafe, boolean stateCanBeChanged) throws Exception {
    ThreadPoolExecutor executor = new ThreadPoolExecutor(5, 5, 0, TimeUnit.SECONDS,
                                                         new ArrayBlockingQueue<Runnable>(10));
    CountDownLatch startSignal = new CountDownLatch(1);
    CountDownLatch doneSignal = new CountDownLatch(numberOfClients);

    for (int i = 1; i <= numberOfClients; i++) {
        WebClient wc = !threadSafe ? WebClient.fromClient(client) : client;
        String bookName = stateCanBeChanged ? Integer.toString(i) : "TheBook";
        String bookHeader = stateCanBeChanged ? "value" + i : "CustomValue";

        executor.execute(new WebClientWorker(wc, bookName, bookHeader,
                         startSignal, doneSignal, stateCanBeChanged));
    }
    startSignal.countDown();
    doneSignal.await(60, TimeUnit.SECONDS);
    executor.shutdownNow();
    assertEquals("Not all invocations have completed", 0, doneSignal.getCount());
}
 
Example 3
Source File: AccessTokenValidatorClient.java    From cxf with Apache License 2.0 6 votes vote down vote up
public AccessTokenValidation validateAccessToken(MessageContext mc,
                                                 String authScheme,
                                                 String authSchemeData,
                                                 MultivaluedMap<String, String> extraProps)
    throws OAuthServiceException {
    WebClient client = WebClient.fromClient(tokenValidatorClient, true);
    MultivaluedMap<String, String> props = new MetadataMap<>();
    props.putSingle(OAuthConstants.AUTHORIZATION_SCHEME_TYPE, authScheme);
    props.putSingle(OAuthConstants.AUTHORIZATION_SCHEME_DATA, authSchemeData);
    if (extraProps != null) {
        props.putAll(extraProps);
    }
    try {
        return client.post(props, AccessTokenValidation.class);
    } catch (WebApplicationException ex) {
        throw new OAuthServiceException(ex);
    }
}
 
Example 4
Source File: GSuiteDirectoryServiceImpl.java    From g-suite-identity-sync with Apache License 2.0 5 votes vote down vote up
@Override
public GSuiteGroup getGroup(String groupKey) {
    String path = MessageFormat.format("/admin/directory/v1/groups/{0}", new Object[]{groupKey});

    WebClient webClient = WebClient.fromClient(directoryApiClient, true);
    webClient.authorization(tokenCache.getToken());
    GSuiteGroup group = webClient.path(path).get(GSuiteGroup.class);
    return group;
}
 
Example 5
Source File: GSuiteDirectoryServiceImpl.java    From g-suite-identity-sync with Apache License 2.0 5 votes vote down vote up
@Override
public GSuiteUser getUser(String userKey) {
    String path = MessageFormat.format("/admin/directory/v1/users/{0}", new Object[]{userKey});
    WebClient webClient = WebClient.fromClient(directoryApiClient, true);

    ClientAccessToken accessToken = tokenCache.getToken();
    webClient.authorization(accessToken);
    GSuiteUser user = webClient.path(path).get(GSuiteUser.class);
    return user;
}
 
Example 6
Source File: GSuiteDirectoryServiceImpl.java    From g-suite-identity-sync with Apache License 2.0 5 votes vote down vote up
@Override
public void updateUserPassword(String userKey, String password) throws InvalidPasswordException {
    String path = MessageFormat.format("/admin/directory/v1/users/{0}", new Object[]{userKey});
    WebClient webClient = WebClient.fromClient(directoryApiClient, true);

    ClientAccessToken accessToken = tokenCache.getToken();
    webClient.authorization(accessToken);
    GSuiteUser user = new GSuiteUser();
    user.setPassword(password);
    Response response = webClient.path(path).put(user);
    if (response.getStatus() != Response.Status.OK.getStatusCode()) {
        throw new InvalidPasswordException("Can't change password. Response: " + response.readEntity(String.class));
    }
}
 
Example 7
Source File: AbstractITCase.java    From syncope with Apache License 2.0 5 votes vote down vote up
public static <T> T getObject(final URI location, final Class<?> serviceClass, final Class<T> resultClass) {
    WebClient webClient = WebClient.fromClient(WebClient.client(adminClient.getService(serviceClass)));
    webClient.accept(clientFactory.getContentType().getMediaType()).to(location.toASCIIString(), false);

    return webClient.
            header(RESTHeaders.DOMAIN, adminClient.getDomain()).
            header(HttpHeaders.AUTHORIZATION, "Bearer " + adminClient.getJWT()).
            get(resultClass);
}
 
Example 8
Source File: BaseRestClient.java    From syncope with Apache License 2.0 5 votes vote down vote up
protected static <E extends JAXRSService, T> T getObject(
        final E service, final URI location, final Class<T> resultClass) {

    WebClient webClient = WebClient.fromClient(WebClient.client(service));
    webClient.accept(SyncopeConsoleSession.get().getMediaType()).to(location.toASCIIString(), false);
    return webClient.
            header(RESTHeaders.DOMAIN, SyncopeConsoleSession.get().getDomain()).
            header(HttpHeaders.AUTHORIZATION, "Bearer " + SyncopeConsoleSession.get().getJWT()).
            get(resultClass);
}
 
Example 9
Source File: JAXRSSpringSecurityInterfaceTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
private void doGetBookWebClient(String address, String username, String password, int expectedStatus) {
    WebClient wc = WebClient.create(address, username, password, null);
    Response r = wc.get();
    assertEquals(expectedStatus, r.getStatus());
    WebClient wc2 = WebClient.fromClient(wc);
    r = wc2.get();
    assertEquals(expectedStatus, r.getStatus());
}
 
Example 10
Source File: JAXRSHttpsBookTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetBook123ProxyToWebClient() throws Exception {

    BookStore bs = JAXRSClientFactory.create("https://localhost:" + PORT, BookStore.class,
                                             CLIENT_CONFIG_FILE1);
    Book b = bs.getSecureBook("123");
    assertEquals(b.getId(), 123);
    WebClient wc = WebClient.fromClient(WebClient.client(bs));
    wc.path("/bookstore/securebooks/123").accept(MediaType.APPLICATION_XML_TYPE);
    Book b2 = wc.get(Book.class);
    assertEquals(123, b2.getId());
}
 
Example 11
Source File: AccessTokenIntrospectionClient.java    From cxf with Apache License 2.0 5 votes vote down vote up
public AccessTokenValidation validateAccessToken(MessageContext mc,
                                                 String authScheme,
                                                 String authSchemeData,
                                                 MultivaluedMap<String, String> extraProps)
    throws OAuthServiceException {
    WebClient client = WebClient.fromClient(tokenValidatorClient, true);
    MultivaluedMap<String, String> props = new MetadataMap<>();
    props.putSingle(OAuthConstants.TOKEN_ID, authSchemeData);
    try {
        TokenIntrospection response = client.post(props, TokenIntrospection.class);
        return convertIntrospectionToValidation(response);
    } catch (WebApplicationException ex) {
        throw new OAuthServiceException(ex);
    }
}
 
Example 12
Source File: ClientImpl.java    From cxf with Apache License 2.0 5 votes vote down vote up
private WebTarget newWebTarget(UriBuilder newBuilder) {
    WebClient newClient;
    if (targetClient != null) {
        newClient = WebClient.fromClient(targetClient);
    } else {
        newClient = null;
    }
    return new WebTargetImpl(newBuilder, getConfiguration(), newClient);
}
 
Example 13
Source File: ClientImpl.java    From cxf with Apache License 2.0 4 votes vote down vote up
@Override
public Builder request() {
    checkClosed();
    Map<String, Object> configProps = getConfiguration().getProperties();

    initTargetClientIfNeeded(configProps);

    ClientProviderFactory pf =
        ClientProviderFactory.getInstance(WebClient.getConfig(targetClient).getEndpoint());
    List<Object> providers = new LinkedList<>();
    List<org.apache.cxf.feature.Feature> cxfFeatures =
        new LinkedList<>();
    Configuration cfg = configImpl.getConfiguration();
    for (Object p : cfg.getInstances()) {
        if (p instanceof org.apache.cxf.feature.Feature) {
            cxfFeatures.add((org.apache.cxf.feature.Feature)p);
        } else if (!(p instanceof Feature)) {
            Map<Class<?>, Integer> contracts = cfg.getContracts(p.getClass());
            if (contracts == null || contracts.isEmpty()) {
                providers.add(p);
            } else {
                final Class<?> providerCls = ClassHelper.getRealClass(pf.getBus(), p);
                providers.add(new FilterProviderInfo<Object>(p.getClass(),
                    providerCls, p, pf.getBus(), contracts));
            }
        }
    }

    pf.setUserProviders(providers);
    ClientConfiguration clientCfg = WebClient.getConfig(targetClient);

    clientCfg.getRequestContext().putAll(configProps);
    clientCfg.getRequestContext().put(Client.class.getName(), ClientImpl.this);
    clientCfg.getRequestContext().put(Configuration.class.getName(),
                                                              getConfiguration());

    // Response auto-close
    Boolean responseAutoClose = getBooleanValue(configProps.get(HTTP_RESPONSE_AUTOCLOSE_PROP));
    if (responseAutoClose != null) {
        clientCfg.getResponseContext().put("response.stream.auto.close", responseAutoClose);
    }
    // TLS
    TLSClientParameters tlsParams = secConfig.getTlsClientParams();
    if (tlsParams.getSSLSocketFactory() != null
        || tlsParams.getTrustManagers() != null
        || tlsParams.getHostnameVerifier() != null) {
        clientCfg.getHttpConduit().setTlsClientParameters(tlsParams);
    }
    // Executor for the asynchronous calls
    Object executorServiceProp = configProps.get(AbstractClient.EXECUTOR_SERVICE_PROPERTY);
    if (executorServiceProp != null) {
        clientCfg.getResponseContext().put(AbstractClient.EXECUTOR_SERVICE_PROPERTY, executorServiceProp);
    }
    setConnectionProperties(configProps, clientCfg);
    // CXF Features
    for (org.apache.cxf.feature.Feature cxfFeature : cxfFeatures) {
        cxfFeature.initialize(clientCfg, clientCfg.getBus());
    }
    // Start building the invocation
    return new InvocationBuilderImpl(WebClient.fromClient(targetClient),
                                     getConfiguration());
}