Java Code Examples for org.apache.cxf.frontend.ClientProxy

The following examples show how to use org.apache.cxf.frontend.ClientProxy. 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 want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: cxf   Source File: ProtocolVariationsTest.java    License: Apache License 2.0 6 votes vote down vote up
private void stopClient() {
    if (null != greeterBus) {

        //ensure we close the decoupled destination of the conduit,
        //so that release the port if the destination reference count hit zero
        if (greeter != null) {
            ClientProxy.getClient(greeter).getConduit().close();
        }
        if (dispatch != null) {
            ((DispatchImpl<?>)dispatch).getClient().getConduit().close();
        }
        greeterBus.shutdown(true);
        greeter = null;
        dispatch = null;
        greeterBus = null;
    }
}
 
Example 2
Source Project: cxf   Source File: JaxwsBasicAuthTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testUseBasicAuthFromClient() throws Exception {
    // setup the feature by using JAXWS front-end API
    JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean();
    // set a fake address to kick off the failover feature
    factory.setAddress("http://localhost:" + PORT + "/SoapContext/GreeterPort");
    factory.setServiceClass(Greeter.class);
    Greeter proxy = factory.create(Greeter.class);

    Client clientProxy = ClientProxy.getClient(proxy);
    HTTPConduit conduit = (HTTPConduit) clientProxy.getConduit();
    conduit.getAuthorization().setAuthorizationType("Basic");
    conduit.getAuthorization().setUserName("user");
    conduit.getAuthorization().setPassword("test");
    
    final BindingProvider bindingProvider = (BindingProvider) proxy;
    bindingProvider.getRequestContext().put("encode.basicauth.with.iso8859", true);

    String response = proxy.greetMe("cxf");
    assertThat("CXF is protected: cxf", equalTo(response));
}
 
Example 3
Source Project: cxf   Source File: DOMMappingTest.java    License: Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() throws Exception {
    super.setUp();
    createService(DocumentService.class, "DocService");
    ClientProxyFactoryBean proxyFac = new ClientProxyFactoryBean();
    ReflectionServiceFactoryBean factory = new ReflectionServiceFactoryBean();
    factory.getServiceConfigurations()
        .add(0, new org.apache.cxf.aegis.databinding.XFireCompatibilityServiceConfiguration());
    proxyFac.setServiceFactory(factory);
    proxyFac.setDataBinding(new AegisDatabinding());

    proxyFac.setAddress("local://DocService");
    proxyFac.setBus(getBus());

    Object proxyObj = proxyFac.create(IDocumentService.class);
    docClient = (IDocumentService)proxyObj;
    Client client = ClientProxy.getClient(proxyObj);
    ClientImpl clientImpl = (ClientImpl)client;
    clientImpl.setSynchronousTimeout(1000000000);
}
 
Example 4
Source Project: servicemix   Source File: Client.java    License: Apache License 2.0 6 votes vote down vote up
public void sendRequest() throws Exception {
    JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean();
    factory.setServiceClass(HelloWorld.class);
    factory.setAddress("http://localhost:8181/cxf/HelloWorldSecurity");
    HelloWorld client = (HelloWorld) factory.create();
    
    Map<String, Object> outProps = new HashMap<String, Object>();
    outProps.put("action", "UsernameToken");

    //add a CustomerSecurityInterceptor for client side to init wss4j staff
    //retrieve and set user/password,  users can easily add this interceptor
    //through spring configuration also
    ClientProxy.getClient(client).getOutInterceptors().add(new CustomerSecurityInterceptor());
    ClientProxy.getClient(client).getOutInterceptors().add(new WSS4JOutInterceptor());
    String ret = client.sayHi("ffang");
    System.out.println(ret);
}
 
Example 5
Source Project: cxf   Source File: ClientNonSpring.java    License: Apache License 2.0 6 votes vote down vote up
private static void setupTLS(Greeter port)
    throws IOException, GeneralSecurityException {
    final TLSClientParameters tlsCP = new TLSClientParameters();
    tlsCP.setDisableCNCheck(true);

    final KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
    try (InputStream is = new FileInputStream("src/main/config/clientKeystore.jks")) {
        keyStore.load(is, "cspass".toCharArray());
    }

    KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    kmf.init(keyStore, "ckpass".toCharArray());
    tlsCP.setKeyManagers(kmf.getKeyManagers());

    TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    tmf.init(keyStore);
    tlsCP.setTrustManagers(tmf.getTrustManagers());

    ((HTTPConduit) ClientProxy.getClient(port).getConduit()).setTlsClientParameters(tlsCP);
}
 
Example 6
Source Project: cxf   Source File: DOMToStaxRoundTripTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testTimestamp() throws Exception {
    // Create + configure service
    Service service = createService();

    WSSSecurityProperties inProperties = new WSSSecurityProperties();
    WSS4JStaxInInterceptor inhandler = new WSS4JStaxInInterceptor(inProperties);
    service.getInInterceptors().add(inhandler);

    // Create + configure client
    Echo echo = createClientProxy();

    Client client = ClientProxy.getClient(echo);
    client.getInInterceptors().add(new LoggingInInterceptor());
    client.getOutInterceptors().add(new LoggingOutInterceptor());

    Map<String, Object> properties = new HashMap<>();
    properties.put(ConfigurationConstants.ACTION, ConfigurationConstants.TIMESTAMP);

    WSS4JOutInterceptor ohandler = new WSS4JOutInterceptor(properties);
    client.getOutInterceptors().add(ohandler);

    assertEquals("test", echo.echo("test"));
}
 
Example 7
Source Project: cxf   Source File: JMSSoapActionTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testSayHi2() throws Exception {
    QName serviceName = new QName("http://cxf.apache.org/hello_world_jms", "HelloWorldServiceSoapAction");
    QName portName = new QName("http://cxf.apache.org/hello_world_jms", "HelloWorldPort");
    URL wsdl = getWSDLURL("/wsdl/jms_test.wsdl");
    HelloWorldService service = new HelloWorldService(wsdl, serviceName);

    HelloWorldPortType greeter = service.getPort(portName, HelloWorldPortType.class);

    ClientProxy.getClient(greeter).getOutInterceptors().add(new LoggingOutInterceptor());
    ClientProxy.getClient(greeter).getOutInterceptors().add(new LoggingInInterceptor());

    ((BindingProvider)greeter).getRequestContext().put(BindingProvider.SOAPACTION_USE_PROPERTY, "true");
    ((BindingProvider)greeter).getRequestContext().put(
        BindingProvider.SOAPACTION_URI_PROPERTY, "SAY_HI_2"
    );

    try {
        greeter.sayHi();
        fail("Failure expected on spoofing attack");
    } catch (Exception ex) {
        // expected
    }
        
    ((java.io.Closeable)greeter).close();
}
 
Example 8
Source Project: cxf   Source File: FailoverAddressOverrideTest.java    License: Apache License 2.0 6 votes vote down vote up
protected void enableWSAForCurrentEndpoint() {
    Endpoint provider = ClientProxy.getClient(greeter).getEndpoint();
    mapAggregator = new MAPAggregator();
    mapCodec = MAPCodec.getInstance(ClientProxy.getClient(greeter).getBus());
    provider.getInInterceptors().add(mapAggregator);
    provider.getInInterceptors().add(mapCodec);

    provider.getOutInterceptors().add(mapAggregator);
    provider.getOutInterceptors().add(mapCodec);

    provider.getInFaultInterceptors().add(mapAggregator);
    provider.getInFaultInterceptors().add(mapCodec);

    provider.getOutFaultInterceptors().add(mapAggregator);
    provider.getOutFaultInterceptors().add(mapCodec);
}
 
Example 9
Source Project: cxf   Source File: FailoverTest.java    License: Apache License 2.0 6 votes vote down vote up
protected void setupGreeter() throws Exception {
    ClusteredGreeterService cs = new ClusteredGreeterService();
    // REVISIT: why doesn't the generic (i.e. non-Port-specific)
    // Service.getPort() load the <jaxws:client> configuration?
    greeter = cs.getReplicatedPortA();
    updateAddressPort(greeter, PORT_A);
    assertTrue("unexpected conduit selector: "
               + ClientProxy.getClient(greeter).getConduitSelector().getClass().getName(),
               ClientProxy.getClient(greeter).getConduitSelector()
               instanceof FailoverTargetSelector);

    updateWsdlExtensors("9051", PORT_A);
    updateWsdlExtensors("9052", PORT_B);
    updateWsdlExtensors("9053", PORT_C);
    updateWsdlExtensors("9055", PORT_E);
}
 
Example 10
Source Project: cxf   Source File: FailoverTest.java    License: Apache License 2.0 6 votes vote down vote up
protected void enableWSAForCurrentEndpoint() {
    Endpoint provider = ClientProxy.getClient(greeter).getEndpoint();
    mapAggregator = new MAPAggregator();
    mapCodec = MAPCodec.getInstance(ClientProxy.getClient(greeter).getBus());
    provider.getInInterceptors().add(mapAggregator);
    provider.getInInterceptors().add(mapCodec);

    provider.getOutInterceptors().add(mapAggregator);
    provider.getOutInterceptors().add(mapCodec);

    provider.getInFaultInterceptors().add(mapAggregator);
    provider.getInFaultInterceptors().add(mapCodec);

    provider.getOutFaultInterceptors().add(mapAggregator);
    provider.getOutFaultInterceptors().add(mapCodec);
}
 
Example 11
Source Project: cxf   Source File: ProtocolVariationsTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testInvalidWSRMMustUnderstandOnReceive() throws Exception {
    init("org/apache/cxf/systest/ws/rm/rminterceptors.xml", false);

    // WS-RM 1.0 using the WS-A 1.0 namespace
    Client client = ClientProxy.getClient(greeter);
    client.getRequestContext().put(RMManager.WSRM_VERSION_PROPERTY, RM10Constants.NAMESPACE_URI);
    client.getRequestContext().put(RMManager.WSRM_WSA_VERSION_PROPERTY, Names200408.WSA_NAMESPACE_NAME);

    // rewrite the outgoing message's WS-RM namespace to an invalid one
    TransformOutInterceptor trans = new TransformOutInterceptor();
    Map<String, String> outElements = new HashMap<>();
    outElements.put("{" + RM10Constants.NAMESPACE_URI + "}*", "{http://cxf.apache.org/invalid}*");
    trans.setOutTransformElements(outElements);

    client.getOutInterceptors().add(trans);
    try {
        greeter.greetMe("one");
        fail("invalid wsrm header");
    } catch (Exception e) {
        assertTrue(e.getCause() instanceof SoapFault);
        final String text = "WS-ReliableMessaging is required";
        assertTrue(e.getCause().getMessage(), e.getCause().getMessage() != null
            && e.getCause().getMessage().indexOf(text) >= 0);
    }
}
 
Example 12
Source Project: cxf   Source File: ClientServerMiscTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testSimpleClientWithWsdlAndBindingId() throws Exception {
    QName portName = new QName("http://cxf.apache.org/systest/jaxws/DocLitWrappedCodeFirstService",
        "DocLitWrappedCodeFirstServicePort");
    QName servName = new QName("http://cxf.apache.org/systest/jaxws/DocLitWrappedCodeFirstService",
        "DocLitWrappedCodeFirstService");

    ClientProxyFactoryBean factory = new ClientProxyFactoryBean();
    factory.setBindingId("http://cxf.apache.org/bindings/xformat");
    factory.setWsdlURL(ServerMisc.DOCLIT_CODEFIRST_URL_XMLBINDING + "?wsdl");
    factory.setServiceName(servName);
    factory.setServiceClass(DocLitWrappedCodeFirstService.class);
    factory.setEndpointName(portName);
    factory.setAddress(ServerMisc.DOCLIT_CODEFIRST_URL_XMLBINDING);
    DocLitWrappedCodeFirstService port = (DocLitWrappedCodeFirstService) factory.create();
    assertNotNull(port);
    assertEquals(factory.getBindingId(), "http://cxf.apache.org/bindings/xformat");
    assertTrue(ClientProxy.getClient(port).getEndpoint().getBinding() instanceof XMLBinding);

    String echoMsg = port.echo("Hello");
    assertEquals("Hello", echoMsg);
}
 
Example 13
Source Project: cxf   Source File: BusShutdownTest.java    License: Apache License 2.0 6 votes vote down vote up
private void doWork(URL wsdlUrl, String address) {
    SOAPService service = new SOAPService(wsdlUrl);
    assertNotNull(service);
    Greeter greeter = service.getSoapPort();

    // overwrite client address
    InvocationHandler handler = Proxy.getInvocationHandler(greeter);
    BindingProvider bp = (BindingProvider)handler;
    bp.getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY,
                               address);
    Client client = ClientProxy.getClient(greeter);
    HTTPConduit c = (HTTPConduit)client.getConduit();
    c.setClient(new HTTPClientPolicy());
    c.getClient().setConnection(ConnectionType.CLOSE);

    // invoke twoway call
    greeter.sayHi();
}
 
Example 14
Source Project: cxf   Source File: JaxWsClientTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testThreadLocalRequestContextIsIsolated() throws InterruptedException {
    URL url = getClass().getResource("/wsdl/hello_world.wsdl");
    javax.xml.ws.Service s = javax.xml.ws.Service.create(url, SERVICE_NAME);
    final Greeter handler = s.getPort(PORT_NAME, Greeter.class);
    final AtomicBoolean isPropertyAPresent = new AtomicBoolean(false);
    // Makes request context thread local
    ClientProxy.getClient(handler).setThreadLocalRequestContext(true);
    // PropertyA should be added to the request context of current thread only
    ClientProxy.getClient(handler).getRequestContext().put("PropertyA", "PropertyAVal");
    Runnable checkRequestContext = new Runnable() {
        @Override
        public void run() {
            if (ClientProxy.getClient(handler).getRequestContext().containsKey("PropertyA")) {
                isPropertyAPresent.set(true);
            }
        }
    };
    Thread thread = new Thread(checkRequestContext);
    thread.start();
    thread.join(60000);

    assertFalse("If we have per thread isolation propertyA should be not present in the context of another thread.",
                isPropertyAPresent.get());
}
 
Example 15
Source Project: cxf   Source File: ClientServerWrappedContinuationTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testHttpWrappedContinuations() throws Exception {
    SpringBusFactory bf = new SpringBusFactory();
    Bus bus = bf.createBus(CLIENT_CONFIG_FILE);
    BusFactory.setDefaultBus(bus);

    QName serviceName = new QName("http://cxf.apache.org/systest/jaxws", "HelloContinuationService");

    URL wsdlURL = new URL("http://localhost:" + PORT + "/hellocontinuation?wsdl");

    HelloContinuationService service = new HelloContinuationService(wsdlURL, serviceName);
    assertNotNull(service);
    final HelloContinuation helloPort = service.getHelloContinuationPort();
    ClientProxy.getClient(helloPort).getInInterceptors().add(new LoggingInInterceptor());
    ClientProxy.getClient(helloPort).getOutInterceptors().add(new LoggingOutInterceptor());
    doTest(helloPort);
    bus.shutdown(true);
}
 
Example 16
Source Project: cxf   Source File: ProtocolVariationsTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testInvalidRM11WSA200408() throws Exception {
    init("org/apache/cxf/systest/ws/rm/rminterceptors.xml", false);

    // WS-RM 1.1, but using the WS-A 1.0 namespace
    Client client = ClientProxy.getClient(greeter);
    client.getRequestContext().put(RMManager.WSRM_VERSION_PROPERTY, RM11Constants.NAMESPACE_URI);
    client.getRequestContext().put(RMManager.WSRM_WSA_VERSION_PROPERTY, Names200408.WSA_NAMESPACE_NAME);

    try {
        greeter.greetMe("one");
        fail("invalid namespace combination accepted");
    } catch (Exception e) {
        assertTrue(e.getCause() instanceof RMException);
        // verify a partial error text match to exclude an unexpected exception
        // (see UNSUPPORTED_NAMESPACE in Messages.properties)
        final String text = Names200408.WSA_NAMESPACE_NAME + " is not supported";
        assertTrue(e.getCause().getMessage() != null
                   && e.getCause().getMessage().indexOf(text) >= 0);
    }

}
 
Example 17
Source Project: cxf   Source File: NettyHttpConduitTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testNoTimeoutAsync() throws Exception {
    updateAddressPort(g, PORT);
    HTTPConduit c = (HTTPConduit)ClientProxy.getClient(g).getConduit();
    c.getClient().setReceiveTimeout(2000);
    c.getClient().setAsyncExecuteTimeout(2000);

    Response<GreetMeLaterResponse> future = g.greetMeLaterAsync(-100L);
    future.get();
    
    Response<GreetMeLaterResponse> future2 = g.greetMeLaterAsync(-100L);
    future2.get();
    
    Thread.sleep(3000);
}
 
Example 18
/**
 * Configures the SSL environment.
 */
protected void configureSSL() {
	TLSClientParameters tlsParams = new TLSClientParameters();
	tlsParams.setDisableCNCheck(true);
	tlsParams.setTrustManagers(new TrustManager[] { new EasyX509TrustManager() });

	org.apache.cxf.endpoint.Client cl = ClientProxy.getClient(client);
	HTTPConduit httpConduit = (HTTPConduit) cl.getConduit();
	httpConduit.setTlsClientParameters(tlsParams);
}
 
Example 19
Source Project: cxf   Source File: JavaFirstSchemaValidationTest.java    License: Apache License 2.0 5 votes vote down vote up
private static <T> T createClient(String port, Class<T> serviceClass, SchemaValidationType type,
        Feature ... features) {
    JaxWsProxyFactoryBean clientFactory = new JaxWsProxyFactoryBean();
    clientFactory.setServiceClass(serviceClass);


    clientFactory.setAddress(getAddress(port, serviceClass));

    if (features != null) {
        Collections.addAll(clientFactory.getFeatures(), features);
    }

    @SuppressWarnings("unchecked")
    T newClient = (T)clientFactory.create();

    Client proxy = ClientProxy.getClient(newClient);

    if (type != null) {
        proxy.getRequestContext().put(Message.SCHEMA_VALIDATION_ENABLED, type);
    }

    HTTPConduit conduit = (HTTPConduit) proxy.getConduit();
    // give me longer debug times
    HTTPClientPolicy clientPolicy = new HTTPClientPolicy();
    clientPolicy.setConnectionTimeout(1000000);
    clientPolicy.setReceiveTimeout(1000000);
    conduit.setClient(clientPolicy);

    return newClient;
}
 
Example 20
Source Project: cxf   Source File: DOMToStaxSamlTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testSaml2SignedSenderVouches() throws Exception {
    // Create + configure service
    Service service = createService();

    WSSSecurityProperties inProperties = new WSSSecurityProperties();
    Properties cryptoProperties =
        CryptoFactory.getProperties("insecurity.properties", this.getClass().getClassLoader());
    inProperties.setSignatureVerificationCryptoProperties(cryptoProperties);
    WSS4JStaxInInterceptor inhandler = new WSS4JStaxInInterceptor(inProperties);
    service.getInInterceptors().add(inhandler);

    // Create + configure client
    Echo echo = createClientProxy();

    Client client = ClientProxy.getClient(echo);
    client.getInInterceptors().add(new LoggingInInterceptor());
    client.getOutInterceptors().add(new LoggingOutInterceptor());

    Map<String, Object> properties = new HashMap<>();
    properties.put(ConfigurationConstants.ACTION, ConfigurationConstants.SAML_TOKEN_SIGNED);
    properties.put(ConfigurationConstants.SAML_CALLBACK_REF, new SAML2CallbackHandler());

    properties.put(ConfigurationConstants.SIG_KEY_ID, "DirectReference");
    properties.put(ConfigurationConstants.USER, "alice");
    properties.put(ConfigurationConstants.PW_CALLBACK_REF, new PasswordCallbackHandler());
    properties.put(ConfigurationConstants.SIG_PROP_FILE, "alice.properties");

    WSS4JOutInterceptor ohandler = new WSS4JOutInterceptor(properties);
    client.getOutInterceptors().add(ohandler);

    assertEquals("test", echo.echo("test"));
}
 
Example 21
Source Project: cxf   Source File: ClientServerTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testClientServer() {
    ctx =
        new ClassPathXmlApplicationContext(new String[] {"/org/apache/cxf/frontend/spring/rountrip.xml"});

    HelloService greeter = (HelloService) ctx.getBean("client");
    assertNotNull(greeter);

    String result = greeter.sayHello();
    assertEquals("We get the wrong sayHello result", "hello", result);


    Client c = ClientProxy.getClient(greeter);
    TestInterceptor out = new TestInterceptor();
    TestInterceptor in = new TestInterceptor();
    c.getRequestContext().put(Message.OUT_INTERCEPTORS, Arrays.asList(new Interceptor[] {out}));
    result = greeter.sayHello();
    assertTrue(out.wasCalled());
    out.reset();

    c.getRequestContext().put(Message.IN_INTERCEPTORS, Arrays.asList(new Interceptor[] {in}));
    result = greeter.sayHello();
    assertTrue(out.wasCalled());
    assertTrue(in.wasCalled());
    ctx.close();
    BusFactory.setDefaultBus(null);
}
 
Example 22
Source Project: cxf-jaxws   Source File: ClientConfig.java    License: MIT License 5 votes vote down vote up
@Bean
public HTTPConduit ticketAgentConduit()
    throws NoSuchAlgorithmException, KeyStoreException,
    CertificateException, IOException {
  Client client = ClientProxy.getClient(ticketAgentProxy());

  HTTPConduit httpConduit = (HTTPConduit) client.getConduit();
  httpConduit.setTlsClientParameters(tlsClientParameters());

  return httpConduit;
}
 
Example 23
Source Project: cxf   Source File: StaxToDOMSamlTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testSaml1Config() throws Exception {
    // Create + configure service
    Service service = createService();

    Map<String, Object> inProperties = new HashMap<>();
    inProperties.put(ConfigurationConstants.ACTION, ConfigurationConstants.SAML_TOKEN_UNSIGNED);
    final Map<QName, Object> customMap = new HashMap<>();
    CustomSamlValidator validator = new CustomSamlValidator();
    customMap.put(WSConstants.SAML_TOKEN, validator);
    customMap.put(WSConstants.SAML2_TOKEN, validator);
    inProperties.put(WSS4JInInterceptor.VALIDATOR_MAP, customMap);
    inProperties.put(SecurityConstants.VALIDATE_SAML_SUBJECT_CONFIRMATION, "false");

    WSS4JInInterceptor inInterceptor = new WSS4JInInterceptor(inProperties);
    service.getInInterceptors().add(inInterceptor);
    service.put(SecurityConstants.VALIDATE_SAML_SUBJECT_CONFIRMATION, "false");

    // Create + configure client
    Echo echo = createClientProxy();

    Client client = ClientProxy.getClient(echo);
    client.getInInterceptors().add(new LoggingInInterceptor());
    client.getOutInterceptors().add(new LoggingOutInterceptor());

    Map<String, Object> outConfig = new HashMap<>();
    outConfig.put(ConfigurationConstants.ACTION, ConfigurationConstants.SAML_TOKEN_UNSIGNED);
    outConfig.put(ConfigurationConstants.SAML_CALLBACK_REF, new SAML1CallbackHandler());
    WSS4JStaxOutInterceptor ohandler = new WSS4JStaxOutInterceptor(outConfig);

    client.getOutInterceptors().add(ohandler);

    assertEquals("test", echo.echo("test"));
}
 
Example 24
Source Project: dubbox   Source File: WebServiceProtocol.java    License: Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
  protected <T> T doRefer(final Class<T> serviceType, final URL url) throws RpcException {
  	ClientProxyFactoryBean proxyFactoryBean = new ClientProxyFactoryBean();
  	proxyFactoryBean.setAddress(url.setProtocol("http").toIdentityString());
  	proxyFactoryBean.setServiceClass(serviceType);
  	proxyFactoryBean.setBus(bus);
  	T ref = (T) proxyFactoryBean.create();
  	Client proxy = ClientProxy.getClient(ref);  
HTTPConduit conduit = (HTTPConduit) proxy.getConduit();
HTTPClientPolicy policy = new HTTPClientPolicy();
policy.setConnectionTimeout(url.getParameter(Constants.CONNECT_TIMEOUT_KEY, Constants.DEFAULT_CONNECT_TIMEOUT));
policy.setReceiveTimeout(url.getParameter(Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT));
conduit.setClient(policy);
      return ref;
  }
 
Example 25
Source Project: cxf   Source File: ServiceImplTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testServiceImpl() throws Exception {
    SOAPService service = new SOAPService();

    Greeter proxy = service.getSoapPort();

    Client client = ClientProxy.getClient(proxy);
    assertEquals("bar", client.getEndpoint().get("foo"));
    assertNotNull("expected ConduitSelector", client.getConduitSelector());
    assertTrue("unexpected ConduitSelector",
               client.getConduitSelector() instanceof NullConduitSelector);
}
 
Example 26
Source Project: cxf   Source File: SEIWithJAXBAnnoTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testXMLList() throws Exception {

    AddNumbersImpl serviceImpl = new AddNumbersImpl();
    Endpoint.publish("local://localhost:9000/Hello", serviceImpl);

    JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean();
    factory.setBus(BusFactory.getDefaultBus());
    factory.setServiceClass(AddNumbers.class);

    factory.setAddress(address);
    AddNumbers proxy = (AddNumbers)factory.create();
    StringWriter strWriter = new StringWriter();
    LoggingOutInterceptor log = new LoggingOutInterceptor(new PrintWriter(strWriter));
    ClientProxy.getClient(proxy).getOutInterceptors().add(log);

    List<String> args = new ArrayList<>();
    args.add("str1");
    args.add("str2");
    args.add("str3");
    List<Integer> result = proxy.addNumbers(args);
    String expected = "<arg0>str1 str2 str3</arg0>";
    assertTrue("Client does not use the generated wrapper class to marshal request parameters",
                 strWriter.toString().indexOf(expected) > -1);
    assertEquals("Get the wrong result", 100, (int)result.get(0));

}
 
Example 27
public void destroy() throws Exception {
    if (obj != null) {
        if (obj instanceof Closeable) {
            ((Closeable)obj).close();
        } else {
            Client c = ClientProxy.getClient(obj);
            c.destroy();
        }
        obj = null;
    }
}
 
Example 28
Source Project: cxf   Source File: StaxToDOMEncryptionIdentifierTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testEncryptIssuerSerial() throws Exception {
    // Create + configure service
    Service service = createService();

    Map<String, Object> inProperties = new HashMap<>();
    inProperties.put(ConfigurationConstants.ACTION, ConfigurationConstants.ENCRYPTION);
    inProperties.put(ConfigurationConstants.PW_CALLBACK_REF, new TestPwdCallback());
    inProperties.put(ConfigurationConstants.DEC_PROP_FILE, "insecurity.properties");
    WSS4JInInterceptor inInterceptor = new WSS4JInInterceptor(inProperties);
    service.getInInterceptors().add(inInterceptor);

    // Create + configure client
    Echo echo = createClientProxy();

    Client client = ClientProxy.getClient(echo);
    client.getInInterceptors().add(new LoggingInInterceptor());
    client.getOutInterceptors().add(new LoggingOutInterceptor());

    WSSSecurityProperties properties = new WSSSecurityProperties();
    List<WSSConstants.Action> actions = new ArrayList<>();
    actions.add(XMLSecurityConstants.ENCRYPTION);
    properties.setActions(actions);
    properties.setEncryptionUser("myalias");
    properties.setEncryptionKeyIdentifier(
        WSSecurityTokenConstants.KeyIdentifier_IssuerSerial
    );
    properties.setEncryptionSymAlgorithm(XMLSecurityConstants.NS_XENC_AES128);

    Properties cryptoProperties =
        CryptoFactory.getProperties("outsecurity.properties", this.getClass().getClassLoader());
    properties.setEncryptionCryptoProperties(cryptoProperties);
    properties.setCallbackHandler(new TestPwdCallback());
    WSS4JStaxOutInterceptor ohandler = new WSS4JStaxOutInterceptor(properties);
    client.getOutInterceptors().add(ohandler);

    assertEquals("test", echo.echo("test"));
}
 
Example 29
Source Project: cxf   Source File: NettyHttpConduitTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testTimeoutAsync() throws Exception {
    updateAddressPort(g, PORT);
    HTTPConduit c = (HTTPConduit)ClientProxy.getClient(g).getConduit();
    c.getClient().setReceiveTimeout(3000);
    c.getClient().setAsyncExecuteTimeout(3000);
    try {
        Response<GreetMeLaterResponse> future = g.greetMeLaterAsync(-5000L);
        future.get();
        fail();
    } catch (Exception ex) {
        //expected!!!
    }
}
 
Example 30
Source Project: rice   Source File: RemoteTestHarness.java    License: Educational Community License v2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
/**
 * Creates a published endpoint from the passed in serviceImplementation and also returns a proxy implementation
 * of the passed in interface for clients to use to hit the created endpoint.
 */
public <T> T publishEndpointAndReturnProxy(Class<T> jaxWsAnnotatedInterface, T serviceImplementation) {
    if (jaxWsAnnotatedInterface.isInterface() &&
            jaxWsAnnotatedInterface.getAnnotation(WebService.class) != null &&
            jaxWsAnnotatedInterface.isInstance(serviceImplementation)) {

        String endpointUrl = getAvailableEndpointUrl();
        LOG.info("Publishing service to: " + endpointUrl);
        endpoint = Endpoint.publish(endpointUrl, serviceImplementation);

        JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean();
        factory.setServiceClass(jaxWsAnnotatedInterface);
        factory.setAddress(endpointUrl);

        T serviceProxy = (T) factory.create();

        /* Add the ImmutableCollectionsInInterceptor to mimic interceptors added in the KSB */
        Client cxfClient = ClientProxy.getClient(serviceProxy);
        cxfClient.getInInterceptors().add(new ImmutableCollectionsInInterceptor());

        return serviceProxy;
    } else {
        throw new IllegalArgumentException("Passed in interface class type must be annotated with @WebService " +
                "and object reference must be an implementing class of that interface.");

    }
}