org.apache.cxf.jaxrs.client.Client Java Examples

The following examples show how to use org.apache.cxf.jaxrs.client.Client. 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: JAXRSMultithreadedClientTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
private void invoke(int ind) throws Exception {

            String actualHeaderName = bookHeader + ind;
            String actualBookName = bookName + ind;

            if (stateCanBeChanged) {
                Client c = WebClient.client(proxy);
                MultivaluedMap<String, String> map = c.getHeaders();
                map.putSingle("CustomHeader", actualHeaderName);
                c.headers(map);
                proxy.echoBookNameAndHeader2(actualBookName);
                verifyResponse(c.getResponse(), actualBookName, actualHeaderName);
            } else {
                verifyResponse(proxy.echoBookNameAndHeader(actualHeaderName, actualBookName),
                               actualBookName, actualHeaderName);
            }
        }
 
Example #2
Source File: JAXRSClientConduitWebSocketTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testBookWithWebSocket() throws Exception {
    String address = "ws://localhost:" + getPort() + "/websocket";

    BookStoreWebSocket resource = JAXRSClientFactory.create(address, BookStoreWebSocket.class);
    Client client = WebClient.client(resource);
    client.header(HttpHeaders.USER_AGENT, JAXRSClientConduitWebSocketTest.class.getName());

    // call the GET service
    assertEquals("CXF in Action", new String(resource.getBookName()));

    // call the GET service in text mode
    //TODO add some way to control the client to switch between the bytes and text modes
    assertEquals("CXF in Action", new String(resource.getBookName()));

    // call another GET service
    Book book = resource.getBook(123);
    assertEquals("CXF in Action", book.getName());

    // call the POST service
    assertEquals(Long.valueOf(123), resource.echoBookId(123));

    // call the same POST service in the text mode
    //TODO add some way to control the client to switch between the bytes and text modes
    assertEquals(Long.valueOf(123), resource.echoBookId(123));

    // call the GET service returning a continous stream output
    //TODO there is no way to get the continuous stream at the moment
    //resource.getBookBought();

}
 
Example #3
Source File: BatchEEJAXRS1CxfClient.java    From incubator-batchee with Apache License 2.0 5 votes vote down vote up
@Override
protected void close() {
    try { // not in cxf 2.6 but in cxf 2.7
        Client.class.getDeclaredMethod("close").invoke(client);
    } catch (final Exception e) {
        // no-op
    }
}
 
Example #4
Source File: ResourceProducer.java    From gazpachoquest with GNU General Public License v3.0 5 votes vote down vote up
@Produces
@GazpachoResource
@RequestScoped
public QuestionnaireResource createQuestionnairResource(HttpServletRequest request) {
    RespondentAccount principal = (RespondentAccount) request.getUserPrincipal();
    String apiKey = principal.getApiKey();
    String secret = principal.getSecret();

    logger.info("Getting QuestionnaireResource using api key {}/{} ", apiKey, secret);

    JacksonJsonProvider jacksonProvider = new JacksonJsonProvider();
    ObjectMapper mapper = new ObjectMapper();
    // mapper.findAndRegisterModules();
    mapper.registerModule(new JSR310Module());
    mapper.setSerializationInclusion(Include.NON_EMPTY);
    mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);

    jacksonProvider.setMapper(mapper);

    QuestionnaireResource resource = JAXRSClientFactory.create(BASE_URI, QuestionnaireResource.class,
            Collections.singletonList(jacksonProvider), null);
    // proxies
    // WebClient.client(resource).header("Authorization", "GZQ " + apiKey);

    Client client = WebClient.client(resource);
    ClientConfiguration config = WebClient.getConfig(client);
    config.getOutInterceptors().add(new HmacAuthInterceptor(apiKey, secret));
    return resource;
}
 
Example #5
Source File: ClientInterceptorTest.java    From gazpachoquest with GNU General Public License v3.0 5 votes vote down vote up
private QuestionnaireResource getQuestionnaireResource() {
    QuestionnaireResource questionnaireResource = JAXRSClientFactory.create(BASE_URI, QuestionnaireResource.class,
            Collections.singletonList(getJacksonProvider()), null);

    Client client = WebClient.client(questionnaireResource);
    ClientConfiguration config = WebClient.getConfig(client);

    String apiKey = "FGFQM8T6YPVSW4Q";
    String secret = "39JYOYPWYR46R38OAOTVRZJMEXNJ46HL";
    config.getOutInterceptors().add(new HmacAuthInterceptor(apiKey, secret));
    return questionnaireResource;
}
 
Example #6
Source File: ClientInterceptorTest.java    From gazpachoquest with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void authenticateTest() {
    AuthenticationResource authenticationResource = JAXRSClientFactory.create(BASE_URI,
            AuthenticationResource.class, Collections.singletonList(new JacksonJsonProvider()), null);
    Client client = WebClient.client(authenticationResource);
    Account account = authenticationResource.authenticate("YAS5ICHRBE");
}
 
Example #7
Source File: AbstractJaxRsClientConfiguration.java    From cxf with Apache License 2.0 5 votes vote down vote up
protected Client createClient() {
    JAXRSClientFactoryBean bean = new JAXRSClientFactoryBean();
    bean.setBus(bus);
    bean.setAddress(address);
    bean.setThreadSafe(threadSafe);
    setJaxrsResources(bean);

    for (String beanName : context.getBeanDefinitionNames()) {
        if (context.findAnnotationOnBean(beanName, Provider.class) != null) {
            bean.setProvider(context.getBean(beanName));
        } else if (context.findAnnotationOnBean(beanName, org.apache.cxf.annotations.Provider.class) != null) {
            addCxfProvider(bean, context.getBean(beanName));
        }
    }

    Map<String, String> extraHeaders = new HashMap<>();
    if (!StringUtils.isEmpty(accept)) {
        extraHeaders.put("Accept", accept);
    }
    if (!StringUtils.isEmpty(contentType)) {
        extraHeaders.put("Content-Type", contentType);
    }
    if (!extraHeaders.isEmpty()) {
        bean.setHeaders(extraHeaders);
    }
    return bean.create();
}
 
Example #8
Source File: JAXRSClientConduitWebSocketTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testCallsWithIDReferences() throws Exception {
    String address = "ws://localhost:" + getPort() + "/websocket";

    BookStoreWebSocket resource = JAXRSClientFactory.create(address, BookStoreWebSocket.class, null, true);
    Client client = WebClient.client(resource);
    client.header(HttpHeaders.USER_AGENT, JAXRSClientConduitWebSocketTest.class.getName());

    // call the POST service twice (a unique requestId is automatically included to correlate the response)
    EchoBookIdRunner[] runners = new EchoBookIdRunner[2];
    runners[0] = new EchoBookIdRunner(resource, 549);
    runners[1] = new EchoBookIdRunner(resource, 495);

    new Thread(runners[0]).start();
    new Thread(runners[1]).start();

    long timetowait = 5000;
    while (timetowait > 0) {
        if (runners[0].isCompleted() && runners[1].isCompleted()) {
            break;
        }
        Thread.sleep(500);
        timetowait -= 500;
    }
    assertEquals(Long.valueOf(549), runners[0].getValue());
    assertEquals(Long.valueOf(495), runners[1].getValue());
}
 
Example #9
Source File: ReconciliationITCase.java    From syncope with Apache License 2.0 5 votes vote down vote up
@Test
public void importCSV() {
    ReconciliationService service = adminClient.getService(ReconciliationService.class);
    Client client = WebClient.client(service);
    client.type(RESTHeaders.TEXT_CSV);

    CSVPullSpec spec = new CSVPullSpec.Builder(AnyTypeKind.USER.name(), "username").build();
    InputStream csv = getClass().getResourceAsStream("/test1.csv");

    List<ProvisioningReport> results = service.pull(spec, csv);
    assertEquals(AnyTypeKind.USER.name(), results.get(0).getAnyType());
    assertNotNull(results.get(0).getKey());
    assertEquals("donizetti", results.get(0).getName());
    assertEquals("donizetti", results.get(0).getUidValue());
    assertEquals(ResourceOperation.CREATE, results.get(0).getOperation());
    assertEquals(ProvisioningReport.Status.SUCCESS, results.get(0).getStatus());

    UserTO donizetti = userService.read(results.get(0).getKey());
    assertNotNull(donizetti);
    assertEquals("Gaetano", donizetti.getPlainAttr("firstname").get().getValues().get(0));
    assertEquals(1, donizetti.getPlainAttr("loginDate").get().getValues().size());

    UserTO cimarosa = userService.read(results.get(1).getKey());
    assertNotNull(cimarosa);
    assertEquals("Domenico Cimarosa", cimarosa.getPlainAttr("fullname").get().getValues().get(0));
    assertEquals(2, cimarosa.getPlainAttr("loginDate").get().getValues().size());
}
 
Example #10
Source File: SAML2IdPsRestClient.java    From syncope with Apache License 2.0 5 votes vote down vote up
public static void importIdPs(final InputStream input) {
    SAML2IdPService service = getService(SAML2IdPService.class);
    Client client = WebClient.client(service);
    client.type(MediaType.APPLICATION_XML);

    service.importFromMetadata(input);

    SyncopeConsoleSession.get().resetClient(SAML2IdPService.class);
}
 
Example #11
Source File: BatchRequest.java    From syncope with Apache License 2.0 5 votes vote down vote up
public <T> T getService(final Class<T> serviceClass) {
    bcfb.setServiceClass(serviceClass);
    T serviceInstance = bcfb.create(serviceClass);

    Client client = WebClient.client(serviceInstance);
    client.type(mediaType).accept(mediaType);

    return serviceInstance;
}
 
Example #12
Source File: SyncopeClient.java    From syncope with Apache License 2.0 5 votes vote down vote up
/**
 * Creates an instance of the given service class, with configured content type and authentication.
 *
 * @param <T> any service class
 * @param serviceClass service class reference
 * @return service instance of the given reference class
 */
public <T> T getService(final Class<T> serviceClass) {
    synchronized (restClientFactory) {
        restClientFactory.setServiceClass(serviceClass);
        T serviceInstance = restClientFactory.create(serviceClass);

        Client client = WebClient.client(serviceInstance);
        client.type(mediaType).accept(mediaType);
        if (serviceInstance instanceof AnyService || serviceInstance instanceof ExecutableService) {
            client.accept(RESTHeaders.MULTIPART_MIXED);
        }

        ClientConfiguration config = WebClient.getConfig(client);
        config.getRequestContext().put(HEADER_SPLIT_PROPERTY, true);
        config.getRequestContext().put(URLConnectionHTTPConduit.HTTPURL_CONNECTION_METHOD_REFLECTION, true);
        if (useCompression) {
            config.getInInterceptors().add(new GZIPInInterceptor());
            config.getOutInterceptors().add(new GZIPOutInterceptor());
        }
        if (tlsClientParameters != null) {
            HTTPConduit httpConduit = (HTTPConduit) config.getConduit();
            httpConduit.setTlsClientParameters(tlsClientParameters);
        }

        return serviceInstance;
    }
}
 
Example #13
Source File: AbstractAnyRestClient.java    From syncope with Apache License 2.0 5 votes vote down vote up
public Map<String, String> deassociate(
        final ResourceDeassociationAction action,
        final String etag,
        final String key,
        final List<StatusBean> statuses) {

    Map<String, String> result = new LinkedHashMap<>();
    synchronized (this) {
        AnyService<?> service = getService(etag, getAnyServiceClass());
        Client client = WebClient.client(service);
        List<String> accept = client.getHeaders().get(HttpHeaders.ACCEPT);
        if (!accept.contains(RESTHeaders.MULTIPART_MIXED)) {
            client.accept(RESTHeaders.MULTIPART_MIXED);
        }

        ResourceDR resourceDR = new ResourceDR.Builder().key(key).
                action(action).
                resources(StatusUtils.statusR(statuses).build().getResources()).build();
        try {
            List<BatchResponseItem> items = parseBatchResponse(service.deassociate(resourceDR));
            for (int i = 0; i < items.size(); i++) {
                result.put(
                        resourceDR.getResources().get(i),
                        getStatus(items.get(i).getStatus()));
            }
        } catch (IOException e) {
            LOG.error("While processing Batch response", e);
        }

        resetClient(getAnyServiceClass());
    }
    return result;
}
 
Example #14
Source File: AbstractAnyRestClient.java    From syncope with Apache License 2.0 5 votes vote down vote up
public Map<String, String> associate(
        final ResourceAssociationAction action,
        final String etag,
        final String key,
        final List<StatusBean> statuses) {

    Map<String, String> result = new LinkedHashMap<>();
    synchronized (this) {
        AnyService<?> service = getService(etag, getAnyServiceClass());
        Client client = WebClient.client(service);
        List<String> accept = client.getHeaders().get(HttpHeaders.ACCEPT);
        if (!accept.contains(RESTHeaders.MULTIPART_MIXED)) {
            client.accept(RESTHeaders.MULTIPART_MIXED);
        }

        StatusR statusR = StatusUtils.statusR(statuses).build();

        ResourceAR resourceAR = new ResourceAR.Builder().key(key).
                action(action).
                onSyncope(statusR.isOnSyncope()).
                resources(statusR.getResources()).build();
        try {
            List<BatchResponseItem> items = parseBatchResponse(service.associate(resourceAR));
            for (int i = 0; i < items.size(); i++) {
                result.put(
                        resourceAR.getResources().get(i),
                        getStatus(items.get(i).getStatus()));
            }
        } catch (IOException e) {
            LOG.error("While processing Batch response", e);
        }

        resetClient(getAnyServiceClass());
    }
    return result;
}
 
Example #15
Source File: ReconciliationRestClient.java    From syncope with Apache License 2.0 5 votes vote down vote up
public static ArrayList<ProvisioningReport> pull(final CSVPullSpec spec, final InputStream csv) {
    ReconciliationService service = getService(ReconciliationService.class);
    Client client = WebClient.client(service);
    client.type(RESTHeaders.TEXT_CSV);

    ArrayList<ProvisioningReport> result = service.pull(spec, csv).stream().
            collect(Collectors.toCollection(ArrayList::new));

    SyncopeConsoleSession.get().resetClient(ReconciliationService.class);

    return result;
}
 
Example #16
Source File: ReconciliationRestClient.java    From syncope with Apache License 2.0 5 votes vote down vote up
public static Response push(final AnyQuery anyQuery, final CSVPushSpec spec) {
    ReconciliationService service = getService(ReconciliationService.class);
    Client client = WebClient.client(service);
    client.accept(RESTHeaders.TEXT_CSV);

    Response response = service.push(anyQuery, spec);

    SyncopeConsoleSession.get().resetClient(ReconciliationService.class);

    return response;
}
 
Example #17
Source File: BpmnProcessRestClient.java    From syncope with Apache License 2.0 4 votes vote down vote up
private static BpmnProcessService getService(final MediaType mediaType) {
    BpmnProcessService service = getService(BpmnProcessService.class);
    Client client = WebClient.client(service);
    client.type(mediaType);
    return service;
}
 
Example #18
Source File: JaxRsWebClientConfiguration.java    From cxf with Apache License 2.0 4 votes vote down vote up
@Bean
protected Client jaxRsWebClient() {
    return super.createClient();
}
 
Example #19
Source File: JaxRsProxyClientConfiguration.java    From cxf with Apache License 2.0 4 votes vote down vote up
@Bean
protected Client jaxRsProxyClient() {
    return super.createClient();
}
 
Example #20
Source File: JAXRSClientFactoryBeanDefinitionParser.java    From cxf with Apache License 2.0 4 votes vote down vote up
public String getFactoryCreateType(Element element) {
    return Client.class.getName();
}
 
Example #21
Source File: ReconciliationITCase.java    From syncope with Apache License 2.0 4 votes vote down vote up
@Test
public void exportCSV() throws IOException {
    ReconciliationService service = adminClient.getService(ReconciliationService.class);
    Client client = WebClient.client(service);
    client.accept(RESTHeaders.TEXT_CSV);

    AnyQuery anyQuery = new AnyQuery.Builder().realm(SyncopeConstants.ROOT_REALM).
            fiql(SyncopeClient.getUserSearchConditionBuilder().is("username").equalTo("*ini").query()).
            page(1).
            size(1000).
            orderBy("username ASC").
            build();

    CSVPushSpec spec = new CSVPushSpec.Builder(AnyTypeKind.USER.name()).ignorePaging(true).
            field("username").
            field("status").
            plainAttr("firstname").
            plainAttr("surname").
            plainAttr("email").
            plainAttr("loginDate").
            build();

    Response response = service.push(anyQuery, spec);
    assertEquals(Response.Status.OK.getStatusCode(), response.getStatus());
    assertEquals(
            "attachment; filename=" + SyncopeConstants.MASTER_DOMAIN + ".csv",
            response.getHeaderString(HttpHeaders.CONTENT_DISPOSITION));

    PagedResult<UserTO> users = userService.search(anyQuery);
    assertNotNull(users);

    MappingIterator<Map<String, String>> reader = new CsvMapper().readerFor(Map.class).
            with(CsvSchema.emptySchema().withHeader()).readValues((InputStream) response.getEntity());

    int rows = 0;
    for (; reader.hasNext(); rows++) {
        Map<String, String> row = reader.next();

        assertEquals(users.getResult().get(rows).getUsername(), row.get("username"));
        assertEquals(users.getResult().get(rows).getStatus(), row.get("status"));

        switch (row.get("username")) {
            case "rossini":
                assertEquals(spec.getNullValue(), row.get("email"));
                assertTrue(row.get("loginDate").contains(spec.getArrayElementSeparator()));
                break;

            case "verdi":
                assertEquals("[email protected]", row.get("email"));
                assertEquals(spec.getNullValue(), row.get("loginDate"));
                break;

            case "bellini":
                assertEquals(spec.getNullValue(), row.get("email"));
                assertFalse(row.get("loginDate").contains(spec.getArrayElementSeparator()));
                break;

            default:
                break;
        }
    }
    assertEquals(rows, users.getTotalCount());
}