Java Code Examples for org.apache.cxf.Bus

The following are top voted examples for showing how to use org.apache.cxf.Bus. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: Equella   File: SoapClientFactory.java   View source code 8 votes vote down vote up
public <T> T createSoapClient(Class<T> serviceClass, URL endpoint, String namespace)
{
	ClientProxyFactoryBean factory = new ClientProxyFactoryBean();
	Bus bus = new ExtensionManagerBus(null, null, Bus.class.getClassLoader());
	factory.setBus(bus);
	factory.setServiceClass(serviceClass);
	factory.setServiceName(new QName(namespace, serviceClass.getSimpleName()));
	factory.setAddress(endpoint.toString());
	factory.getServiceFactory().getServiceConfigurations().add(0, new XFireCompatabilityConfiguration());
	factory.setDataBinding(new AegisDatabinding());
	@SuppressWarnings("unchecked")
	T soapClient = (T) factory.create();
	Client client = ClientProxy.getClient(soapClient);
	client.getRequestContext().put(Message.MAINTAIN_SESSION, true);
	HTTPClientPolicy policy = new HTTPClientPolicy();
	policy.setReceiveTimeout(600000);
	policy.setAllowChunking(false);
	HTTPConduit conduit = (HTTPConduit) client.getConduit();
	conduit.setClient(policy);
	return soapClient;
}
 
Example 2
Project: cas-5.1.0   File: SecurityTokenServiceClientBuilder.java   View source code 6 votes vote down vote up
/**
 * Build client for security token requests.
 *
 * @param service the rp
 * @return the security token service client
 */
public SecurityTokenServiceClient buildClientForSecurityTokenRequests(final WSFederationRegisteredService service) {
    final Bus cxfBus = BusFactory.getDefaultBus();
    final SecurityTokenServiceClient sts = new SecurityTokenServiceClient(cxfBus);
    sts.setAddressingNamespace(StringUtils.defaultIfBlank(service.getAddressingNamespace(), WSFederationConstants.HTTP_WWW_W3_ORG_2005_08_ADDRESSING));
    sts.setTokenType(StringUtils.defaultIfBlank(service.getTokenType(), WSConstants.WSS_SAML2_TOKEN_TYPE));
    sts.setKeyType(WSFederationConstants.HTTP_DOCS_OASIS_OPEN_ORG_WS_SX_WS_TRUST_200512_BEARER);
    sts.setWsdlLocation(prepareWsdlLocation(service));
    if (StringUtils.isNotBlank(service.getPolicyNamespace())) {
        sts.setWspNamespace(service.getPolicyNamespace());
    }
    final String namespace = StringUtils.defaultIfBlank(service.getNamespace(), WSFederationConstants.HTTP_DOCS_OASIS_OPEN_ORG_WS_SX_WS_TRUST_200512);
    sts.setServiceQName(new QName(namespace, StringUtils.defaultIfBlank(service.getWsdlService(), WSFederationConstants.SECURITY_TOKEN_SERVICE)));
    sts.setEndpointQName(new QName(namespace, service.getWsdlEndpoint()));
    sts.getProperties().putAll(new HashMap<>());
    return sts;
}
 
Example 3
Project: cas-5.1.0   File: SecurityTokenServiceClientBuilder.java   View source code 6 votes vote down vote up
/**
 * Build client for relying party token responses.
 *
 * @param securityToken the security token
 * @param service       the service
 * @return the security token service client
 */
public SecurityTokenServiceClient buildClientForRelyingPartyTokenResponses(final SecurityToken securityToken,
                                                                           final WSFederationRegisteredService service) {
    final Bus cxfBus = BusFactory.getDefaultBus();
    final SecurityTokenServiceClient sts = new SecurityTokenServiceClient(cxfBus);
    sts.setAddressingNamespace(StringUtils.defaultIfBlank(service.getAddressingNamespace(), WSFederationConstants.HTTP_WWW_W3_ORG_2005_08_ADDRESSING));
    sts.setWsdlLocation(prepareWsdlLocation(service));
    final String namespace = StringUtils.defaultIfBlank(service.getNamespace(), WSFederationConstants.HTTP_DOCS_OASIS_OPEN_ORG_WS_SX_WS_TRUST_200512);
    sts.setServiceQName(new QName(namespace, service.getWsdlService()));
    sts.setEndpointQName(new QName(namespace, service.getWsdlEndpoint()));
    sts.setEnableAppliesTo(StringUtils.isNotBlank(service.getAppliesTo()));
    sts.setOnBehalfOf(securityToken.getToken());
    sts.setKeyType(WSFederationConstants.HTTP_DOCS_OASIS_OPEN_ORG_WS_SX_WS_TRUST_200512_BEARER);
    sts.setTokenType(StringUtils.defaultIfBlank(service.getTokenType(), WSConstants.WSS_SAML2_TOKEN_TYPE));

    if (StringUtils.isNotBlank(service.getPolicyNamespace())) {
        sts.setWspNamespace(service.getPolicyNamespace());
    }

    return sts;
}
 
Example 4
Project: steve-plugsurfing   File: MediatorInInterceptor.java   View source code 6 votes vote down vote up
/**
 * Iterate over all available servers registered on the bus and build a map
 * consisting of (namespace, server) pairs for later lookup, so we can
 * redirect to the version-specific implementation according to the namespace
 * of the incoming message.
 */
private void initServerLookupMap(SoapMessage message) {
    Bus bus = message.getExchange().getBus();

    ServerRegistry serverRegistry = bus.getExtension(ServerRegistry.class);
    if (serverRegistry == null) {
        return;
    }

    List<Server> temp = serverRegistry.getServers();
    for (Server server : temp) {
        EndpointInfo info = server.getEndpoint().getEndpointInfo();
        String address = info.getAddress();

        // exclude the 'dummy' routing server
        if (CONFIG.getRouterEndpointPath().equals(address)) {
            continue;
        }

        String serverNamespace = info.getName().getNamespaceURI();
        actualServers.put(serverNamespace, server);
    }
}
 
Example 5
Project: Camel   File: CxfConsumerWSRMTest.java   View source code 6 votes vote down vote up
@Test
public void testInvokeGreeter() throws Exception {
    MockEndpoint mock = getMockEndpoint("mock:result");
    mock.expectedMessageCount(1);

    Bus clientBus = context.getRegistry().lookupByNameAndType("client-bus", Bus.class);
    assertNotNull(clientBus);
    
    BusFactory.setThreadDefaultBus(clientBus);
    try {
        Service service = Service.create(SERVICE_NAME);
        service.addPort(PORT_NAME, "http://schemas.xmlsoap.org/soap/",
                        "http://localhost:" + CXFTestSupport.getPort1() + "/CxfConsumerWSRMTest/router"); 
        Greeter greeter = service.getPort(PORT_NAME, Greeter.class);
        
        greeter.greetMeOneWay("test");
    } finally {
        BusFactory.setThreadDefaultBus(null);
    }

    assertMockEndpointsSatisfied();
}
 
Example 6
Project: Camel   File: PayLoadDataFormatFeature.java   View source code 6 votes vote down vote up
@Override
public void initialize(Client client, Bus bus) {
    client.getEndpoint().put("org.apache.cxf.binding.soap.addNamespaceContext", "true");
    removeFaultInInterceptorFromClient(client);
    
    // Need to remove some interceptors that are incompatible
    // We don't support JAX-WS Holders for PAYLOAD (not needed anyway)
    // and thus we need to remove those interceptors to prevent Holder
    // object from being created and stuck into the contents list
    // instead of Source objects
    removeInterceptor(client.getEndpoint().getInInterceptors(), 
                      HolderInInterceptor.class);
    removeInterceptor(client.getEndpoint().getOutInterceptors(), 
                      HolderOutInterceptor.class);
    // The SoapHeaderInterceptor maps various headers onto method parameters.
    // At this point, we expect all the headers to remain as headers, not
    // part of the body, so we remove that one.
    removeInterceptor(client.getEndpoint().getBinding().getInInterceptors(), 
                      SoapHeaderInterceptor.class);
    client.getEndpoint().getBinding().getInInterceptors().add(new ConfigureDocLitWrapperInterceptor(true));
    resetPartTypes(client.getEndpoint().getBinding());

    LOG.info("Initialized CXF Client: {} in Payload mode with allow streaming: {}", client, allowStreaming);
}
 
Example 7
Project: Camel   File: PayLoadDataFormatFeature.java   View source code 6 votes vote down vote up
@Override
public void initialize(Server server, Bus bus) {
    server.getEndpoint().put("org.apache.cxf.binding.soap.addNamespaceContext", "true");
    server.getEndpoint().getBinding().getInInterceptors().add(new ConfigureDocLitWrapperInterceptor(true));
    if (server.getEndpoint().getBinding() instanceof SoapBinding) {
        server.getEndpoint().getBinding().getOutInterceptors().add(new SetSoapVersionInterceptor());
    }
    // Need to remove some interceptors that are incompatible
    // See above.
    removeInterceptor(server.getEndpoint().getInInterceptors(), 
                      HolderInInterceptor.class);
    removeInterceptor(server.getEndpoint().getOutInterceptors(), 
                      HolderOutInterceptor.class);
    removeInterceptor(server.getEndpoint().getBinding().getInInterceptors(), 
                      SoapHeaderInterceptor.class);
    resetPartTypes(server.getEndpoint().getBinding());

    LOG.info("Initialized CXF Server: {} in Payload mode with allow streaming: {}", server, allowStreaming);
}
 
Example 8
Project: Camel   File: CxfEndpointBeanBusSettingTest.java   View source code 6 votes vote down vote up
@Test
public void testBusInjectedBySpring() throws Exception {
    CamelContext camelContext = (CamelContext) ctx.getBean("camel");
    
    CxfEndpoint endpoint = camelContext.getEndpoint("cxf:bean:routerEndpoint", CxfEndpoint.class);
    assertEquals("Get a wrong endpoint uri", "cxf://bean:routerEndpoint", endpoint.getEndpointUri());       
    Bus cxf1 = endpoint.getBus();
    
    assertEquals(cxf1, ctx.getBean("cxf1"));
    assertEquals(cxf1, endpoint.getBus());
    assertEquals("barf", endpoint.getBus().getProperty("foo"));
    
    endpoint = camelContext.getEndpoint("cxf:bean:serviceEndpoint", CxfEndpoint.class);
    assertEquals("Get a wrong endpoint uri", "cxf://bean:serviceEndpoint", endpoint.getEndpointUri());
    Bus cxf2 = endpoint.getBus();
    
    assertEquals(cxf2, ctx.getBean("cxf2"));
    assertEquals(cxf2, endpoint.getBus());
    assertEquals("snarf", endpoint.getBus().getProperty("foo"));
    
    
}
 
Example 9
Project: Camel   File: CxfCustomerStartStopTest.java   View source code 6 votes vote down vote up
@Test
public void startAndStopService() throws Exception {
    CamelContext context = new DefaultCamelContext();
    // start a server    
    context.addRoutes(new RouteBuilder() {
        public void configure() {
            from("cxf:http://localhost:" + PORT1 + "/test?serviceClass=org.apache.camel.component.cxf.HelloService")
                .to("log:endpoint");
        }
    });
    
    context.start();
    Thread.sleep(300);
    context.stop();
    Bus bus = BusFactory.getDefaultBus();
    JettyHTTPServerEngineFactory factory = bus.getExtension(JettyHTTPServerEngineFactory.class);
    JettyHTTPServerEngine engine = factory.retrieveJettyHTTPServerEngine(PORT1);
    assertNotNull("Jetty engine should be found there", engine);
    // Need to call the bus shutdown ourselves.
    String orig = System.setProperty("org.apache.cxf.transports.http_jetty.DontClosePort", "false");
    bus.shutdown(true);
    System.setProperty("org.apache.cxf.transports.http_jetty.DontClosePort",
                       orig == null ? "true" : "false");
    engine = factory.retrieveJettyHTTPServerEngine(PORT1);
    assertNull("Jetty engine should be removed", engine);
}
 
Example 10
Project: Camel   File: CxfCustomerStartStopTest.java   View source code 6 votes vote down vote up
@Test
public void startAndStopServiceFromSpring() throws Exception {
    System.setProperty("CamelCxfConsumerContext.port2", Integer.toString(PORT2));
    
    ClassPathXmlApplicationContext applicationContext = 
        new ClassPathXmlApplicationContext("org/apache/camel/component/cxf/CamelCxfConsumerContext.xml");
    Bus bus = applicationContext.getBean("cxf", Bus.class);
    // Bus shutdown will be called when the application context is closed.
    String orig = System.setProperty("org.apache.cxf.transports.http_jetty.DontClosePort", "false");
    IOHelper.close(applicationContext);
    System.setProperty("org.apache.cxf.transports.http_jetty.DontClosePort",
                       orig == null ? "true" : "false");
    JettyHTTPServerEngineFactory factory = bus.getExtension(JettyHTTPServerEngineFactory.class);
    // test if the port is still used
    JettyHTTPServerEngine engine = factory.retrieveJettyHTTPServerEngine(PORT2);
    assertNull("Jetty engine should be removed", engine);
}
 
Example 11
Project: Camel   File: WSSecurityRouteTest.java   View source code 6 votes vote down vote up
@Test
public void testSignature() throws Exception {
    SpringBusFactory bf = new SpringBusFactory();
    URL busFile = WSSecurityRouteTest.class.getResource("../client/wssec.xml");

    Bus bus = bf.createBus(busFile.toString());
    BusFactory.setDefaultBus(bus);
    BusFactory.setThreadDefaultBus(bus);
    
    GreeterService gs = new GreeterService();
    Greeter greeter = gs.getGreeterSignaturePort();
     
    ((BindingProvider)greeter).getRequestContext().put(
            BindingProvider.ENDPOINT_ADDRESS_PROPERTY,
            "http://localhost:" + CXFTestSupport.getPort2() 
            + "/WSSecurityRouteTest/GreeterSignaturePort"
    );
    
    assertEquals("Get a wrong response", "Hello Security", greeter.greetMe("Security"));
}
 
Example 12
Project: Camel   File: WSSecurityRouteTest.java   View source code 6 votes vote down vote up
@Test
public void testUsernameToken() throws Exception {
    SpringBusFactory bf = new SpringBusFactory();
    URL busFile = WSSecurityRouteTest.class.getResource("../client/wssec.xml");

    Bus bus = bf.createBus(busFile.toString());
    BusFactory.setDefaultBus(bus);
    BusFactory.setThreadDefaultBus(bus);
    
    GreeterService gs = new GreeterService();
    Greeter greeter = gs.getGreeterUsernameTokenPort();
     
    ((BindingProvider)greeter).getRequestContext().put(
            BindingProvider.ENDPOINT_ADDRESS_PROPERTY,
            "http://localhost:" + CXFTestSupport.getPort2() 
            + "/WSSecurityRouteTest/GreeterUsernameTokenPort"
    );
    
    assertEquals("Get a wrong response", "Hello Security", greeter.greetMe("Security"));
}
 
Example 13
Project: Camel   File: WSSecurityRouteTest.java   View source code 6 votes vote down vote up
@Test
public void testEncryption() throws Exception {
    SpringBusFactory bf = new SpringBusFactory();
    URL busFile = WSSecurityRouteTest.class.getResource("../client/wssec.xml");

    Bus bus = bf.createBus(busFile.toString());
    BusFactory.setDefaultBus(bus);
    BusFactory.setThreadDefaultBus(bus);
    
    GreeterService gs = new GreeterService();
    Greeter greeter = gs.getGreeterEncryptionPort();
     
    ((BindingProvider)greeter).getRequestContext().put(
            BindingProvider.ENDPOINT_ADDRESS_PROPERTY,
            "http://localhost:" + CXFTestSupport.getPort2() 
            + "/WSSecurityRouteTest/GreeterEncryptionPort"
    );
    
    assertEquals("Get a wrong response", "Hello Security", greeter.greetMe("Security"));
}
 
Example 14
Project: Camel   File: WSSecurityRouteTest.java   View source code 6 votes vote down vote up
@Test
public void testSecurityPolicy() throws Exception {
    SpringBusFactory bf = new SpringBusFactory();
    URL busFile = WSSecurityRouteTest.class.getResource("../client/wssec.xml");

    Bus bus = bf.createBus(busFile.toString());
    BusFactory.setDefaultBus(bus);
    BusFactory.setThreadDefaultBus(bus);
    
    GreeterService gs = new GreeterService();
    Greeter greeter = gs.getGreeterSecurityPolicyPort();
     
    ((BindingProvider)greeter).getRequestContext().put(
            BindingProvider.ENDPOINT_ADDRESS_PROPERTY,
            "http://localhost:" + CXFTestSupport.getPort2() 
            + "/WSSecurityRouteTest/GreeterSecurityPolicyPort"
    );
    
    assertEquals("Get a wrong response", "Hello Security", greeter.greetMe("Security"));
}
 
Example 15
Project: Camel   File: CamelConduit.java   View source code 6 votes vote down vote up
public CamelConduit(CamelContext context, Bus b, EndpointInfo epInfo, EndpointReferenceType targetReference,
        HeaderFilterStrategy headerFilterStrategy) {
    super(getTargetReference(epInfo, targetReference, b));
    String address = epInfo.getAddress();
    if (address != null) {
        targetCamelEndpointUri = address.substring(CamelTransportConstants.CAMEL_TRANSPORT_PREFIX.length());
        if (targetCamelEndpointUri.startsWith("//")) {
            targetCamelEndpointUri = targetCamelEndpointUri.substring(2);
        }
    }
    camelContext = context;
    endpointInfo = epInfo;
    bus = b;
    initConfig();
    this.headerFilterStrategy = headerFilterStrategy;
    Endpoint target = getCamelContext().getEndpoint(targetCamelEndpointUri);
    try {
        producer = target.createProducer();
        producer.start();
    } catch (Exception e) {
        throw new RuntimeCamelException("Cannot create the producer rightly", e);
    }
}
 
Example 16
Project: Camel   File: CamelDestinationTest.java   View source code 6 votes vote down vote up
@Test
public void testCamelDestinationConfiguration() throws Exception {
    QName testEndpointQName = new QName("http://camel.apache.org/camel-test", "port");
    // set up the bus with configure file
    SpringBusFactory bf = new SpringBusFactory();
    BusFactory.setDefaultBus(null);
    Bus bus = bf.createBus("/org/apache/camel/component/cxf/transport/CamelDestination.xml");
    BusFactory.setDefaultBus(bus);

    endpointInfo.setAddress("camel://direct:EndpointA");
    endpointInfo.setName(testEndpointQName);
    CamelDestination destination = new CamelDestination(null, bus, null, endpointInfo);

    assertEquals("{http://camel.apache.org/camel-test}port.camel-destination", destination.getBeanName());
    CamelContext context = destination.getCamelContext();

    assertNotNull("The camel context which get from camel destination is not null", context);
    assertEquals("Get the wrong camel context", context.getName(), "dest_context");
    assertEquals("The camel context should has two routers", context.getRoutes().size(), 2);
    bus.shutdown(false);
}
 
Example 17
Project: jbossws-cxf   File: Helper.java   View source code 6 votes vote down vote up
/**
 * Verify a JAXWS client can be properly created and used to invoke a ws endpoint
 * 
 * @return
 * @throws Exception
 */
public boolean testJAXWSClient() throws Exception
{
   Bus bus = BusFactory.newInstance().createBus();
   try
   {
      BusFactory.setThreadDefaultBus(bus);

      URL wsdlURL = new URL(targetEndpoint + "?wsdl");
      QName serviceName = new QName("http://org.jboss.ws/spring", "EndpointService");

      Service service = Service.create(wsdlURL, serviceName);
      Endpoint port = (Endpoint) service.getPort(Endpoint.class);
      return "Hello".equals(port.echo("Hello"));
   }
   finally
   {
      bus.shutdown(true);
   }
}
 
Example 18
Project: jbossws-cxf   File: OasisCatalogHelloWSTestCase.java   View source code 6 votes vote down vote up
@Test
@RunAsClient
public void testCatalogOnServerSide() throws Exception
{
   Bus bus = BusFactory.newInstance().createBus();
   try {
      BusFactory.setThreadDefaultBus(bus);

      QName serviceName = new QName(
         org.jboss.test.ws.jaxws.cxf.catalog.HelloWs.TARGET_NAMESPACE,
         org.jboss.test.ws.jaxws.cxf.catalog.HelloWs.NAME);
      URL wsdlURL = new URL(baseURL + "HelloService?wsdl");
      Service service = Service.create(wsdlURL, serviceName);
      HelloWs proxy = service.getPort(HelloWs.class);
      HelloRequest helloReq = new HelloRequest();
      helloReq.setInput("Anyone home?");
      proxy.doHello(helloReq);

   } finally {
      bus.shutdown(true);
   }
}
 
Example 19
Project: jbossws-cxf   File: HTTPConduitTestCase.java   View source code 6 votes vote down vote up
@Test
@RunAsClient
public void testDefaultWrapperInstalled() throws Exception {
   Bus bus = BusFactory.newInstance().createBus();
   try {
      HTTPConduitFactory hcf = bus.getExtension(HTTPConduitFactory.class);
      assertNotNull(hcf);
      assertTrue(hcf instanceof DefaultHTTPConduitFactoryWrapper);
      
      URL wsdlURL = new URL(baseURL + "/ServiceOne" + "?wsdl");
      Service service = Service.create(wsdlURL, new QName("http://org.jboss.ws.jaxws.cxf/httpConduit", "ServiceOne"));
      EndpointOne port = service.getPort(new QName("http://org.jboss.ws.jaxws.cxf/httpConduit", "EndpointOnePort"), EndpointOne.class);
      assertEquals("Foo", port.echo("Foo"));
   } finally {
      bus.shutdown(true);
   }
}
 
Example 20
Project: jbossws-cxf   File: Helper.java   View source code 6 votes vote down vote up
public boolean testGZIPUsingFeatureOnClient() throws Exception
{
   Bus bus = BusFactory.newInstance().createBus();
   try
   {
      BusFactory.setThreadDefaultBus(bus);
      
      HelloWorld port = getPort();
      
      ClientConfigurer configurer = ClientConfigUtil.resolveClientConfigurer();
      configurer.setConfigProperties(port, "jaxws-client-config.xml", "Feature Client Config");
      
      return "foo".equals(port.echo("foo"));
   }
   finally
   {
      bus.shutdown(true);
   }
}
 
Example 21
Project: jbossws-cxf   File: Helper.java   View source code 6 votes vote down vote up
public boolean testGZIPServerSideOnlyInterceptorOnClient() throws Exception
{
   Bus bus = BusFactory.newInstance().createBus();
   try
   {
      BusFactory.setThreadDefaultBus(bus);
      
      HelloWorld port = getPort();
      Client client = ClientProxy.getClient(port);
      HTTPConduit conduit = (HTTPConduit)client.getConduit();
      HTTPClientPolicy policy = conduit.getClient();
      //enable Accept gzip, otherwise the server will not try to reply using gzip
      policy.setAcceptEncoding("gzip;q=1.0, identity; q=0.5, *;q=0");
      //add interceptor for decoding gzip message
      client.getInInterceptors().add(new GZIPEnforcingInInterceptor());
      return ("foo".equals(port.echo("foo")));
   }
   finally
   {
      bus.shutdown(true);
   }
}
 
Example 22
Project: jbossws-cxf   File: PolicyInterceptorProviderTestCase.java   View source code 6 votes vote down vote up
/**
 * Verifies the policy-enabled client can be configured to ignore a given policy in the wsdl contract
 * 
 * @throws Exception
 */
@Test
@RunAsClient
public void testUnsupportedPolicy() throws Exception
{
   Bus bus = BusFactory.newInstance().createBus();
   try
   {
      BusFactory.setThreadDefaultBus(bus);
      
      PolicyInterceptorProviderRegistry reg = bus.getExtension(PolicyInterceptorProviderRegistry.class);
      reg.register(new IgnorablePolicyInterceptorProvider(new QName("http://my.custom.org/policy", "MyPolicy")));
      
      URL wsdlURL = new URL(baseURL + "/jaxws-cxf-policy/PIPService/PIPEndpoint?wsdl");
      QName serviceName = new QName("http://policy.cxf.jaxws.ws.test.jboss.org/", "PIPService");
      Service service = Service.create(wsdlURL, serviceName, new UseThreadBusFeature());
      QName portQName = new QName("http://policy.cxf.jaxws.ws.test.jboss.org/", "PIPEndpointPort");
      PIPEndpoint port = (PIPEndpoint)service.getPort(portQName, PIPEndpoint.class);

      assertEquals("foo", port.echo("foo"));
   }
   finally
   {
      bus.shutdown(true);
   }
}
 
Example 23
Project: teiid   File: WSConnectionImpl.java   View source code 6 votes vote down vote up
public <T> Dispatch<T> createDispatch(Class<T> type, Mode mode) throws IOException {
	if (this.wsdlService == null) {
		Bus bus = BusFactory.getThreadDefaultBus();
		BusFactory.setThreadDefaultBus(this.mcf.getBus());
		try {
			this.wsdlService = Service.create(this.mcf.getWsdlUrl(), this.mcf.getServiceQName());
		} finally {
			BusFactory.setThreadDefaultBus(bus);
		}
		if (LogManager.isMessageToBeRecorded(LogConstants.CTX_WS, MessageLevel.DETAIL)) {
			LogManager.logDetail(LogConstants.CTX_WS, "Created the WSDL service for", this.mcf.getWsdl()); //$NON-NLS-1$
		}
	}
	Dispatch<T> dispatch = this.wsdlService.createDispatch(this.mcf.getPortQName(), type, mode);
	configureWSSecurity(dispatch);
	setDispatchProperties(dispatch, "SOAP12"); //$NON-NLS-1$
	return dispatch;
}
 
Example 24
Project: jbossws-cxf   File: AsyncClientTestCase.java   View source code 6 votes vote down vote up
@Test
@RunAsClient
public void testAysncClientWithPolicy () throws Exception 
{
   Bus bus = BusFactory.newInstance().createBus();
   AsyncEnabledInfoInterceptor asyncInfo = new AsyncEnabledInfoInterceptor();
   try
   {
      bus.setProperty("use.async.http.conduit", "ASYNC_ONLY");
      bus.getOutInterceptors().add(asyncInfo);
      BusFactory.setThreadDefaultBus(bus);
      Endpoint proxy = initPort();
      assertEquals("Echo:1000", proxy.echo(1000));
      assertFalse("Async client is expected disabled", asyncInfo.isAsyncEnabled());
      assertEquals("Echo:1000", proxy.echoAsync(1000).get());
      assertTrue("Async client is expected enabled", asyncInfo.isAsyncEnabled());
   }
   finally
   {
      bus.shutdown(true);
   }
}
 
Example 25
Project: jbossws-cxf   File: ProviderImpl.java   View source code 6 votes vote down vote up
@SuppressWarnings("rawtypes")
@Override
public ServiceDelegate createServiceDelegate(URL url, QName qname, Class cls)
{
   final String busStrategy = ClientBusSelector.getInstance().selectStrategy();
   ClassLoader origClassLoader = getContextClassLoader();
   boolean restoreTCCL = false;
   Bus orig = null;
   try
   {
      restoreTCCL = checkAndFixContextClassLoader(origClassLoader);
      orig = BusFactory.getThreadDefaultBus(false);          
      Bus bus = getOrCreateBus(busStrategy, origClassLoader);
      ServiceDelegate serviceDelegate = new JBossWSServiceImpl(bus, url, qname, cls);
      setDisableCacheSchema(bus);
      return serviceDelegate;
   }
   finally
   {
      restoreThreadDefaultBus(busStrategy, orig);
      if (restoreTCCL)
         setContextClassLoader(origClassLoader);
   }
}
 
Example 26
Project: SecureBPMN   File: WebServiceProviderServlet.java   View source code 6 votes vote down vote up
@Override
public void loadBus(ServletConfig servletConfig) throws ServletException {
    super.loadBus(servletConfig);
    
    // TODO: Hacky first version to get default Process Engine
    ProcessEngine processEngine = ProcessEngineConfiguration
      .createProcessEngineConfigurationFromResourceDefault()
      .buildProcessEngine();
    
    Bus bus = getBus();
    BusFactory.setDefaultBus(bus); 
    Endpoint.publish("/RuntimeService", new RuntimeWebServiceImpl(processEngine));
    
    // You can als use the simple frontend API to do this
    ServerFactoryBean factory = new ServerFactoryBean();
    factory.setBus(bus);
    factory.setServiceClass(RuntimeWebServiceImpl.class);
    factory.setAddress("/RuntimeService");
    factory.create();              
}
 
Example 27
Project: jbossws-cxf   File: Helper.java   View source code 6 votes vote down vote up
/**
 * Setup binding customization on client side using the JBossWSConfigurer
 *
 * @throws Exception
 */
@SuppressWarnings("unchecked")
private Bus setBindingCustomizationOnClientSide() throws Exception
{
   BindingCustomization jaxbCustomizations = new JAXBBindingCustomization();
   if (jaxbIntroUrl == null)
   {
      jaxbIntroUrl = Thread.currentThread().getContextClassLoader().getResource("jaxb-intros.xml");
   }
   BindingCustomizationFactory.populateBindingCustomization(jaxbIntroUrl.openStream(), jaxbCustomizations);

   Bus bus = BusFactory.newInstance().createBus();
   BusFactory.setThreadDefaultBus(bus);
   JBossWSConfigurer configurer = (JBossWSConfigurer)bus.getExtension(Configurer.class);
   configurer.getCustomizer().setBindingCustomization(jaxbCustomizations);
   return bus;
}
 
Example 28
Project: jbossws-cxf   File: AbstractHTTPConduitFactoryWrapper.java   View source code 6 votes vote down vote up
@Override
public HTTPConduit createConduit(HTTPTransportFactory f, Bus b, EndpointInfo localInfo, EndpointReferenceType target)
      throws IOException
{
   HTTPConduit conduit = null;
   if (delegate != null)
   {
      conduit = delegate.createConduit(f, b, localInfo, target);
   }
   else
   {
      conduit = createNewConduit(f, b, localInfo, target);
   }
   if (conduit != null)
   {
      configureConduit(conduit);
   }
   return conduit;
}
 
Example 29
Project: jbossws-cxf   File: AbstractClient.java   View source code 6 votes vote down vote up
public static void testBusCreation() throws BusTestException
{
   Bus initialDefaultBus = BusFactory.getDefaultBus(false);
   Bus initialThreadBus = BusFactory.getThreadDefaultBus(false);
   BusFactory factory = BusFactory.newInstance();
   Bus bus = factory.createBus();
   assert (bus != null);
   if (initialThreadBus == null) //if the thread bus was not set before, it should now be
   {
      checkThreadBus(bus);
   }
   checkDefaultBus(initialDefaultBus);
   BusFactory.setThreadDefaultBus(initialThreadBus);
   checkThreadBus(initialThreadBus);
   checkDefaultBus(initialDefaultBus);
}
 
Example 30
Project: jbossws-cxf   File: AbstractClient.java   View source code 6 votes vote down vote up
public static void testSOAPConnection(String host) throws BusTestException, Exception
{
   Bus initialDefaultBus = BusFactory.getDefaultBus(false);
   Bus initialThreadBus = BusFactory.getThreadDefaultBus(false);
   //first call... the thread bus is reused if not null, otherwise a new one is created
   performSOAPCall(getEndpointURL(host));
   checkDefaultBus(initialDefaultBus);
   if (initialThreadBus != null)
   {
      checkThreadBus(initialThreadBus);
   }
   else
   {
      initialThreadBus = BusFactory.getThreadDefaultBus(false);
   }
   //second call...
   performSOAPCall(getEndpointURL(host));
   checkThreadBus(initialThreadBus);
   checkDefaultBus(initialDefaultBus);
}
 
Example 31
Project: jbossws-cxf   File: AbstractClient.java   View source code 6 votes vote down vote up
public static void testWebServiceRef(Endpoint port) throws BusTestException
{
   Bus initialDefaultBus = BusFactory.getDefaultBus(false);
   Bus threadBus = BusFactory.getThreadDefaultBus(false);
   performInvocation(port); //does not change anything to the bus, as the port is already created when injecting serviceref
   checkDefaultBus(initialDefaultBus);
   checkThreadBus(threadBus);
   try
   {
      BusFactory.setThreadDefaultBus(null);
      performInvocation(port); //does not change anything to the bus, as the port is already created when injecting serviceref
      checkDefaultBus(initialDefaultBus);
      checkThreadBus(null);
      BusFactory factory = BusFactory.newInstance();
      Bus bus = factory.createBus(); //internally sets the thread bus
      performInvocation(port); //does not change anything to the bus, as the port is already created when injecting serviceref
      checkDefaultBus(initialDefaultBus);
      checkThreadBus(bus);
   }
   finally
   {
      BusFactory.setThreadDefaultBus(threadBus);
   }
}
 
Example 32
Project: jbossws-cxf   File: ServletHelper.java   View source code 6 votes vote down vote up
public static void callRequestHandler(HttpServletRequest req, HttpServletResponse res, ServletContext ctx, Bus bus,
      Endpoint endpoint) throws ServletException
{
   try
   {
      BusFactory.setThreadDefaultBus(bus);
      //set the current endpoint into the threadlocal association that is later
      //used by the EndpointAssociationInterceptor for linking the message exchange
      //related to this invocation to the proper endpoint serving it (the bus, and
      //hence the interceptor, can span multiple invocation related to multiple
      //endpoints)
      EndpointAssociation.setEndpoint(endpoint);
      RequestHandler requestHandler = (RequestHandler) endpoint.getRequestHandler();
      requestHandler.handleHttpRequest(endpoint, req, res, ctx);
   }
   catch (IOException ioe)
   {
      throw new ServletException(ioe);
   }
   finally
   {
      EndpointAssociation.removeEndpoint();
      BusFactory.setThreadDefaultBus(null);
   }
}
 
Example 33
Project: jbossws-cxf   File: BusHolder.java   View source code 6 votes vote down vote up
protected void setInterceptors(Bus bus, Deployment dep, Map<String, String> props)
{
   //Install the EndpointAssociationInterceptor for linking every message exchange
   //with the proper spi Endpoint retrieved in CXFServletExt
   bus.getInInterceptors().add(new EndpointAssociationInterceptor());
   bus.getInInterceptors().add(new NsCtxSelectorStoreInterceptor());
   bus.getInInterceptors().add(new GracefulShutdownInterceptor());
   
   final String p = (props != null) ? props.get(Constants.JBWS_CXF_DISABLE_HANDLER_AUTH_CHECKS) : null;
   if ((p == null || (!"true".equalsIgnoreCase(p) && !"1".equalsIgnoreCase(p))) && !Boolean.getBoolean(Constants.JBWS_CXF_DISABLE_HANDLER_AUTH_CHECKS)) {
      bus.getInInterceptors().add(new HandlerAuthInterceptor());
   }
   
   final SOAPAddressRewriteMetadata sarm = dep.getAttachment(SOAPAddressRewriteMetadata.class);
   if (SoapAddressRewriteHelper.isPathRewriteRequired(sarm) || SoapAddressRewriteHelper.isSchemeRewriteRequired(sarm)) {
      bus.getInInterceptors().add(new WSDLSoapAddressRewriteInterceptor(sarm));
   }
   
   InterceptorUtils.addInterceptors(bus, props);
}
 
Example 34
Project: jbossws-cxf   File: WSTrustTestCase.java   View source code 6 votes vote down vote up
/**
 *  Request a security token that allows it to act as if it were somebody else.
 *
 * @throws Exception
 */
@Test
@RunAsClient
@OperateOnDeployment(ACT_AS_SERVER_DEP)
@WrapThreadContextClassLoader
public void testActAs() throws Exception
{
   Bus bus = BusFactory.newInstance().createBus();
   try
   {
      BusFactory.setThreadDefaultBus(bus);

      final QName serviceName = new QName("http://www.jboss.org/jbossws/ws-extensions/actaswssecuritypolicy", "ActAsService");
      final URL wsdlURL = new URL(serviceURL + "ActAsService?wsdl");
      Service service = Service.create(wsdlURL, serviceName);
      ActAsServiceIface proxy = (ActAsServiceIface) service.getPort(ActAsServiceIface.class);

      WSTrustTestUtils.setupWsseAndSTSClientActAs((BindingProvider) proxy, bus);

      assertEquals("ActAs WS-Trust Hello World!", proxy.sayHello(getServerHost(), String.valueOf(getServerPort())));
   }
   finally
   {
      bus.shutdown(true);
   }
}
 
Example 35
Project: jbossws-cxf   File: WSTrustTestUtils.java   View source code 6 votes vote down vote up
/**
 * A PASSWORD is provided in place of the ClientCallbackHandler in the
 * STSClient.  A USERNAME and PASSWORD is required by CXF in the msg.
 *
 * @param proxy
 * @param bus
 * @param stsWsdlLocation
 * @param stsService
 * @param stsPort
 * @see org.apache.cxf.ws.security.SecurityConstants#PASSWORD
 */
public static void setupWsseAndSTSClientNoCallbackHandler(ServiceIface proxy, Bus bus, String stsWsdlLocation, QName stsService, QName stsPort) {
   Map<String, Object> ctx = ((BindingProvider) proxy).getRequestContext();
   setServiceContextAttributes(ctx);

   STSClient stsClient = new STSClient(bus);
   if (stsWsdlLocation != null) {
      stsClient.setWsdlLocation(stsWsdlLocation);
      stsClient.setServiceQName(stsService);
      stsClient.setEndpointQName(stsPort);
   }
   Map<String, Object> props = stsClient.getProperties();
   props.put(SecurityConstants.USERNAME, "alice");
   props.put(SecurityConstants.PASSWORD, "clarinet");
   props.put(SecurityConstants.ENCRYPT_PROPERTIES, Thread.currentThread().getContextClassLoader().getResource("META-INF/clientKeystore.properties"));
   props.put(SecurityConstants.ENCRYPT_USERNAME, "mystskey");
   props.put(SecurityConstants.STS_TOKEN_USERNAME, "myclientkey");
   props.put(SecurityConstants.STS_TOKEN_PROPERTIES, Thread.currentThread().getContextClassLoader().getResource("META-INF/clientKeystore.properties"));
   props.put(SecurityConstants.STS_TOKEN_USE_CERT_FOR_KEYINFO, "true");
   ctx.put(SecurityConstants.STS_CLIENT, stsClient);
}
 
Example 36
Project: jbossws-cxf   File: WSTrustTestUtils.java   View source code 6 votes vote down vote up
public static void setupWsseAndSTSClientBearer(BindingProvider proxy, Bus bus) {

      Map<String, Object> ctx = proxy.getRequestContext();

      STSClient stsClient = new STSClient(bus);

      ctx.put(SecurityConstants.CALLBACK_HANDLER, new ClientCallbackHandler());
      ctx.put(SecurityConstants.SIGNATURE_PROPERTIES, Thread.currentThread().getContextClassLoader().getResource("META-INF/clientKeystore.properties"));
      ctx.put(SecurityConstants.ENCRYPT_PROPERTIES, Thread.currentThread().getContextClassLoader().getResource("META-INF/clientKeystore.properties"));
      ctx.put(SecurityConstants.SIGNATURE_USERNAME, "myclientkey");
      ctx.put(SecurityConstants.ENCRYPT_USERNAME, "myservicekey");
      ctx.put(appendIssuedTokenSuffix(SecurityConstants.USERNAME), "alice");
      ctx.put(appendIssuedTokenSuffix(SecurityConstants.CALLBACK_HANDLER), new ClientCallbackHandler());
      ctx.put(appendIssuedTokenSuffix(SecurityConstants.ENCRYPT_PROPERTIES), Thread.currentThread().getContextClassLoader().getResource("META-INF/clientKeystore.properties"));
      ctx.put(appendIssuedTokenSuffix(SecurityConstants.ENCRYPT_USERNAME), "mystskey");
      ctx.put(appendIssuedTokenSuffix(SecurityConstants.STS_TOKEN_USERNAME), "myclientkey");
      ctx.put(appendIssuedTokenSuffix(SecurityConstants.STS_TOKEN_PROPERTIES), Thread.currentThread().getContextClassLoader().getResource("META-INF/clientKeystore.properties"));
      ctx.put(appendIssuedTokenSuffix(SecurityConstants.STS_TOKEN_USE_CERT_FOR_KEYINFO), "true");

      ctx.put(SecurityConstants.STS_CLIENT, stsClient);
   }
 
Example 37
Project: jbossws-cxf   File: WSTrustTestUtils.java   View source code 6 votes vote down vote up
public static void setupWsseAndSTSClientHolderOfKey(BindingProvider proxy, Bus bus) {

      Map<String, Object> ctx = proxy.getRequestContext();

      STSClient stsClient = new STSClient(bus);

      ctx.put(SecurityConstants.CALLBACK_HANDLER, new ClientCallbackHandler());
      ctx.put(SecurityConstants.SIGNATURE_PROPERTIES, Thread.currentThread().getContextClassLoader().getResource("META-INF/clientKeystore.properties"));
      ctx.put(SecurityConstants.ENCRYPT_PROPERTIES, Thread.currentThread().getContextClassLoader().getResource("META-INF/clientKeystore.properties"));
      ctx.put(SecurityConstants.SIGNATURE_USERNAME, "myclientkey");
      ctx.put(SecurityConstants.ENCRYPT_USERNAME, "myservicekey");
      ctx.put(appendIssuedTokenSuffix(SecurityConstants.USERNAME), "alice");
      ctx.put(appendIssuedTokenSuffix(SecurityConstants.CALLBACK_HANDLER), new ClientCallbackHandler());
      ctx.put(appendIssuedTokenSuffix(SecurityConstants.ENCRYPT_PROPERTIES), Thread.currentThread().getContextClassLoader().getResource("META-INF/clientKeystore.properties"));
      ctx.put(appendIssuedTokenSuffix(SecurityConstants.ENCRYPT_USERNAME), "mystskey");
      ctx.put(appendIssuedTokenSuffix(SecurityConstants.STS_TOKEN_USERNAME), "myclientkey");
      ctx.put(appendIssuedTokenSuffix(SecurityConstants.STS_TOKEN_PROPERTIES), Thread.currentThread().getContextClassLoader().getResource("META-INF/clientKeystore.properties"));
      ctx.put(appendIssuedTokenSuffix(SecurityConstants.STS_TOKEN_USE_CERT_FOR_KEYINFO), "true");

      ctx.put(SecurityConstants.STS_CLIENT, stsClient);
   }
 
Example 38
Project: Equella   File: CXFHandler.java   View source code 5 votes vote down vote up
@Override
protected void loadBus(ServletConfig sc)
{
	Thread currentThread = Thread.currentThread();
	ClassLoader oldLoader = currentThread.getContextClassLoader();
	try
	{
		currentThread.setContextClassLoader(getClass().getClassLoader());
		Bus bus = new ExtensionManagerBus();
		setBus(bus);
		List<Extension> exts = interceptorTracker.getExtensions();
		List<Interceptor<? extends Message>> inInterceptors = bus.getInInterceptors();
		for( Extension extension : exts )
		{
			Collection<Parameter> inParams = extension.getParameters("inBean");
			for( Parameter inParam : inParams )
			{
				inInterceptors.add(interceptorTracker.getBeanByParameter(extension, inParam));
			}
			Collection<Parameter> outParams = extension.getParameters("outBean");
			for( Parameter outParam : outParams )
			{
				bus.getOutInterceptors().add(interceptorTracker.getBeanByParameter(extension, outParam));
			}
		}
		inInterceptors.add(new WebServiceContextIntercept());
		bus.setProperty("org.apache.cxf.logging.FaultListener", new SoapFaultListener());
	}
	finally
	{
		currentThread.setContextClassLoader(oldLoader);
	}
}
 
Example 39
Project: Equella   File: EquellaRepoServiceImpl.java   View source code 5 votes vote down vote up
protected SoapHarvesterService getNewClient(String url, String sharedId, String sharedValue, String username)
{
	try
	{
		final URL endpointUrl = new URL(new URL(url), HARVESTER_ENDPOINT);

		ClientProxyFactoryBean factory = new ClientProxyFactoryBean();
		Bus bus = new ExtensionManagerBus(null, null, Bus.class.getClassLoader());
		factory.setBus(bus);
		factory.setServiceClass(SoapHarvesterService.class);
		factory.setServiceName(
			new QName("http://soap.harvester.core.tle.com", SoapHarvesterService.class.getSimpleName()));
		factory.setAddress(endpointUrl.toString());
		factory.setDataBinding(new AegisDatabinding());
		List<AbstractServiceConfiguration> configs = factory.getServiceFactory().getServiceConfigurations();
		configs.add(0, new XFireReturnTypeConfig());
		SoapHarvesterService soapClient = (SoapHarvesterService) factory.create();
		Client client = ClientProxy.getClient(soapClient);
		client.getRequestContext().put(Message.MAINTAIN_SESSION, true);
		HTTPClientPolicy policy = new HTTPClientPolicy();
		policy.setReceiveTimeout(600000);
		policy.setAllowChunking(false);
		HTTPConduit conduit = (HTTPConduit) client.getConduit();
		// Works?
		// conduit.getTlsClientParameters().setSSLSocketFactory(BlindSSLSocketFactory.getDefaultSSL());
		conduit.setClient(policy);

		soapClient.loginWithToken(TokenGenerator.createSecureToken(username, sharedId, sharedValue, null));
		return soapClient;
	}
	catch( Exception x )
	{
		LOGGER.error("Error connecting to remote EQUELLA server", x);
		throw new RuntimeException(
			CurrentLocale.get("com.tle.core.remoterepo.equella.error.communication", x.getMessage()));
	}
}
 
Example 40
Project: cxf-jaxws   File: EndpointConfig.java   View source code 5 votes vote down vote up
@Bean
public Bus bus() {
  cxfBus.setFeatures(
      new ArrayList<>(Arrays.asList(loggingFeature())));

  return cxfBus;
}