org.switchyard.ServiceDomain - java examples

Here are the examples of the java api org.switchyard.ServiceDomain taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

142 Examples 7

19 View Complete Implementation : BaseActivator.java
Copyright Apache License 2.0
Author : jboss-switchyard
/**
 * Sets the service domain instance of this activator.
 * @param serviceDomain the service domain
 */
public void setServiceDomain(ServiceDomain serviceDomain) {
    _serviceDomain = serviceDomain;
}

19 View Complete Implementation : EventsTest.java
Copyright Apache License 2.0
Author : jboss-switchyard
/**
 *  Tests for events generated by the core runtime.
 */
public clreplaced EventsTest {

    private ServiceDomain _domain;

    private DummyObserver _observer;

    @Before
    public void setUp() throws Exception {
        _domain = new MockDomain();
        _observer = new DummyObserver();
    }

    @Test
    public void testTransformerEvents() {
        _domain.addEventObserver(_observer, TransformerAddedEvent.clreplaced).addEventObserver(_observer, TransformerRemovedEvent.clreplaced);
        Transformer<String, String> t = new BaseTransformer<String, String>() {

            public String transform(String from) {
                return null;
            }
        };
        _domain.getTransformerRegistry().addTransformer(t);
        replacedert.replacedertTrue(_observer.addTransformerCalled);
        _domain.getTransformerRegistry().removeTransformer(t);
        replacedert.replacedertTrue(_observer.removeTransformerCalled);
    }

    @Test
    public void testValidatorEvents() {
        _domain.addEventObserver(_observer, ValidatorAddedEvent.clreplaced).addEventObserver(_observer, ValidatorRemovedEvent.clreplaced);
        Validator<String> t = new BaseValidator<String>() {

            public ValidationResult validate(String name) {
                return new ValidationResult() {

                    public boolean isValid() {
                        return false;
                    }

                    public String getDetail() {
                        return "error";
                    }
                };
            }
        };
        _domain.getValidatorRegistry().addValidator(t);
        replacedert.replacedertTrue(_observer.addValidatorCalled);
        _domain.getValidatorRegistry().removeValidator(t);
        replacedert.replacedertTrue(_observer.removeValidatorCalled);
    }

    @Test
    public void testReferenceEvents() {
        _domain.addEventObserver(_observer, ReferenceRegistrationEvent.clreplaced).addEventObserver(_observer, ReferenceUnregistrationEvent.clreplaced);
        ServiceReference ref = _domain.registerServiceReference(new QName("test"), new InOutService());
        replacedert.replacedertTrue(_observer.referenceRegistrationCalled);
        ref.unregister();
        replacedert.replacedertTrue(_observer.referenceUnregistrationCalled);
    }

    @Test
    public void testServiceEvents() {
        _domain.addEventObserver(_observer, ServiceRegistrationEvent.clreplaced).addEventObserver(_observer, ServiceUnregistrationEvent.clreplaced);
        Service service = _domain.registerService(new QName("test"), new InOutService(), new BaseHandler());
        replacedert.replacedertTrue(_observer.serviceRegistrationCalled);
        service.unregister();
        replacedert.replacedertTrue(_observer.serviceUnregistrationCalled);
    }
}

19 View Complete Implementation : AbstractInflowEndpoint.java
Copyright Apache License 2.0
Author : jboss-switchyard
/**
 * set ServiceDomain.
 * @param domain ServiceDomain
 * @return this instance
 */
public AbstractInflowEndpoint setServiceDomain(ServiceDomain domain) {
    _domain = domain;
    return this;
}

19 View Complete Implementation : AddressingHandler.java
Copyright Apache License 2.0
Author : jboss-switchyard
/**
 * The AddressingHandler resolves service instances based on a service reference.
 */
public clreplaced AddressingHandler extends BaseHandler {

    private ServiceDomain _domain;

    /**
     * Create a new AddressingHandler for the specified domain.
     * @param domain services available for routing
     */
    public AddressingHandler(ServiceDomain domain) {
        _domain = domain;
    }

    @Override
    public void handleMessage(Exchange exchange) throws HandlerException {
        // only set the provider on the 'IN' phase
        if (ExchangePhase.IN != exchange.getPhase()) {
            return;
        }
        // is a provider already set?
        if (exchange.getProvider() != null) {
            return;
        }
        List<Service> services = _domain.getServices(exchange.getConsumer().getTargetServiceName());
        if (services == null || services.isEmpty()) {
            throw RuntimeMessages.MESSAGES.noRegisteredService(exchange.getConsumer().getName().toString());
        }
        // At this stage, just pick the first service implementation we find and go with
        // it.  In the future, it would be nice if we could make this pluggable.
        Service service = services.get(0);
        ServiceOperation consumerOp = exchange.getContract().getConsumerOperation();
        ServiceOperation providerOp = service.getInterface().getOperation(consumerOp.getName());
        if (providerOp == null) {
            // try for a default operation
            if (service.getInterface().getOperations().size() == 1) {
                providerOp = service.getInterface().getOperations().iterator().next();
            } else {
                throw RuntimeMessages.MESSAGES.operationNotIncluded(consumerOp.getName(), service.getName().toString());
            }
        }
        // set provider contract and details on exchange
        exchange.provider(service, providerOp);
        for (Policy policy : service.getServiceMetadata().getRequiredPolicies()) {
            PolicyUtil.require(exchange, policy);
        }
    }
}

19 View Complete Implementation : KnowledgeBuilder.java
Copyright Apache License 2.0
Author : jboss-switchyard
/**
 * KnowledgeBuilder.
 *
 * @author David Ward <<a href="mailto:[email protected]">[email protected]</a>> © 2014 Red Hat Inc.
 */
public abstract clreplaced KnowledgeBuilder {

    private final ClreplacedLoader _clreplacedLoader;

    private final ServiceDomain _serviceDomain;

    /**
     * Creates a new KnowledgeBuilder.
     */
    public KnowledgeBuilder() {
        this(null, null);
    }

    /**
     * Creates a new KnowledgeBuilder.
     * @param clreplacedLoader clreplacedLoader
     */
    public KnowledgeBuilder(ClreplacedLoader clreplacedLoader) {
        this(clreplacedLoader, null);
    }

    /**
     * Creates a new KnowledgeBuilder.
     * @param clreplacedLoader clreplacedLoader
     * @param serviceDomain serviceDomain
     */
    public KnowledgeBuilder(ClreplacedLoader clreplacedLoader, ServiceDomain serviceDomain) {
        _clreplacedLoader = clreplacedLoader != null ? clreplacedLoader : getClreplaced().getClreplacedLoader();
        _serviceDomain = serviceDomain;
    }

    /**
     * Gets the clreplacedLoader.
     * @return the clreplacedLoader
     */
    public final ClreplacedLoader getClreplacedLoader() {
        return _clreplacedLoader;
    }

    /**
     * Gets the serviceDomain.
     * @return the serviceDomain
     */
    public final ServiceDomain getServiceDomain() {
        return _serviceDomain;
    }
}

19 View Complete Implementation : OSGiEntityManagerFactoryLoader.java
Copyright Apache License 2.0
Author : jboss-switchyard
private Bundle getApplicationBundle(ServiceDomain domain) {
    return (Bundle) domain.getProperty("switchyard.deployment.bundle");
}

19 View Complete Implementation : CamelContextConfiguratorTest.java
Copyright Apache License 2.0
Author : jboss-switchyard
/**
 * Test configuration of CamelContext through properties and a callback clreplaced.
 */
public clreplaced CamelContextConfiguratorTest {

    private static final String PATH_CAMEL_CONTEXT_XML = "org/switchyard/common/camel/CamelContextConfiguratorTest-camel-context.xml";

    private SwitchYardCamelContextImpl context;

    private ServiceDomain domain;

    @Before
    public void setUp() {
        context = new SwitchYardCamelContextImpl();
        domain = new MockDomain();
        context.setServiceDomain(domain);
    }

    @After
    public void clean() throws Exception {
        context.stop();
        domain.destroy();
    }

    @Test
    public void configureShutdownTimeout() throws Exception {
        final int timeout = 12345;
        domain.setProperty(CamelContextConfigurator.SHUTDOWN_TIMEOUT, timeout);
        CamelContextConfigurator.configure(context, domain);
        replacedert.replacedertEquals(timeout, context.getShutdownStrategy().getTimeout());
    }

    @Test
    public void configurePerformanceStatistics() throws Exception {
        domain.setProperty(CamelContextConfigurator.PERFORMANCE_STATISTICS, "RoutesOnly");
        CamelContextConfigurator.configure(context, domain);
        replacedert.replacedertEquals(ManagementStatisticsLevel.RoutesOnly, context.getManagementStrategy().getStatisticsLevel());
        domain.setProperty(CamelContextConfigurator.PERFORMANCE_STATISTICS, "Off");
        CamelContextConfigurator.configure(context, domain);
        replacedert.replacedertEquals(ManagementStatisticsLevel.Off, context.getManagementStrategy().getStatisticsLevel());
        domain.setProperty(CamelContextConfigurator.PERFORMANCE_STATISTICS, "All");
        CamelContextConfigurator.configure(context, domain);
        replacedert.replacedertEquals(ManagementStatisticsLevel.All, context.getManagementStrategy().getStatisticsLevel());
    }

    @Test
    public void configureCamelContextAware() throws Exception {
        // specify the CamelContextAware clreplaced
        domain.setProperty(CamelContextConfigurator.CAMEL_CONTEXT_CONFIG, MyCustomContextAware.clreplaced.getName());
        // configure the context and check results
        CamelContextConfigurator.configure(context, domain);
        replacedert.replacedertNotNull(context.getProperty("abc"));
        replacedert.replacedertEquals("xyz", context.getProperty("abc"));
    }

    @Test
    public void configureCamelContextXML() throws Exception {
        domain.setProperty(CamelContextConfigurator.CAMEL_CONTEXT_CONFIG_XML, PATH_CAMEL_CONTEXT_XML);
        replacedert.replacedertNull(context.getProperty("abc"));
        replacedert.replacedertNotEquals("foobar-camel-context", context.getName());
        replacedert.replacedertEquals(false, context.isUseMDCLogging());
        replacedert.replacedertEquals(ManagementStatisticsLevel.All, context.getManagementStrategy().getStatisticsLevel());
        replacedert.replacedertEquals(true, context.isAllowUseOriginalMessage());
        replacedert.replacedertEquals(false, context.isStreamCaching());
        context.start();
        replacedert.replacedertNotNull(context.getProperty("abc"));
        replacedert.replacedertEquals("xyz", context.getProperty("abc"));
        replacedert.replacedertEquals("foobar-camel-context", context.getName());
        replacedert.replacedertEquals(true, context.isUseMDCLogging());
        replacedert.replacedertEquals(ManagementStatisticsLevel.RoutesOnly, context.getManagementStrategy().getStatisticsLevel());
        replacedert.replacedertEquals(false, context.isAllowUseOriginalMessage());
        replacedert.replacedertEquals(true, context.isStreamCaching());
        DataFormatDefinition dfd = context.getDataFormats().get("transform-json");
        replacedert.replacedertNotNull(dfd);
        replacedert.replacedertEquals("json-jackson", dfd.getDataFormatName());
        replacedert.replacedertTrue(dfd instanceof JsonDataFormat);
        MockEndpoint mock = context.getEndpoint("mock:output", MockEndpoint.clreplaced);
        mock.expectedMessageCount(1);
        mock.expectedBodiesReceived("foobar-input");
        context.createProducerTemplate().sendBody("direct:input", "foobar-input");
        mock.replacedertIsSatisfied();
    }
}

19 View Complete Implementation : SwitchYardServiceInvoker.java
Copyright Apache License 2.0
Author : jboss-switchyard
/**
 * SwitchYardServiceInvoker.
 *
 * @author David Ward <<a href="mailto:[email protected]">[email protected]</a>> © 2013 Red Hat Inc.
 */
public clreplaced SwitchYardServiceInvoker {

    private final ServiceDomain _serviceDomain;

    private final String _targetNamespace;

    /**
     * Constructs a new SwitchYardServiceInvoker with the specified service domain.
     * @param serviceDomain the service domain
     */
    public SwitchYardServiceInvoker(ServiceDomain serviceDomain) {
        this(serviceDomain, null);
    }

    /**
     * Constructs a new SwitchYardServiceInvoker with the specified service domain and target namespace.
     * @param serviceDomain the service domain
     * @param targetNamespace the target namespace
     */
    public SwitchYardServiceInvoker(ServiceDomain serviceDomain, String targetNamespace) {
        _serviceDomain = serviceDomain;
        _targetNamespace = targetNamespace;
    }

    /**
     * Gets the service domain.
     * @return the service domain
     */
    public ServiceDomain getServiceDomain() {
        return _serviceDomain;
    }

    /**
     * Gets the target namespace.
     * @return the target namespace
     */
    public String getTargetNamespace() {
        return _targetNamespace;
    }

    /**
     * Invokes the request and returns the response.
     * @param request the request
     * @return the response
     */
    public SwitchYardServiceResponse invoke(SwitchYardServiceRequest request) {
        Map<String, Object> contextOut = new HashMap<String, Object>();
        Object contentOut = null;
        Object fault = null;
        try {
            QName serviceName = request.getServiceName();
            if (serviceName == null) {
                throw CommonKnowledgeMessages.MESSAGES.serviceNameNull();
            } else if (Strings.trimToNull(serviceName.getNamespaceURI()) == null) {
                String tns = getTargetNamespace();
                if (tns != null) {
                    serviceName = XMLHelper.createQName(tns, serviceName.getLocalPart());
                }
            }
            ServiceDomain serviceDomain = getServiceDomain();
            if (serviceDomain == null) {
                throw CommonKnowledgeMessages.MESSAGES.serviceDomainNull();
            }
            ServiceReference serviceReference = serviceDomain.getServiceReference(serviceName);
            if (serviceReference == null) {
                throw CommonKnowledgeMessages.MESSAGES.serviceReferenceNull(serviceName.toString());
            }
            final Exchange exchangeIn;
            FaultHandler handler = new FaultHandler();
            String operationName = request.getOperationName();
            if (operationName != null) {
                exchangeIn = serviceReference.createExchange(operationName, handler);
            } else {
                exchangeIn = serviceReference.createExchange(handler);
            }
            Message messageIn = exchangeIn.createMessage();
            Context contextIn = exchangeIn.getContext(messageIn);
            for (Map.Entry<String, Object> entry : request.getContext().entrySet()) {
                contextIn.setProperty(entry.getKey(), entry.getValue());
            }
            Object contentIn = request.getContent();
            if (contentIn != null) {
                messageIn.setContent(contentIn);
            }
            exchangeIn.send(messageIn);
            if (ExchangePattern.IN_OUT.equals(exchangeIn.getContract().getConsumerOperation().getExchangePattern())) {
                Exchange exchangeOut = handler.waitForOut();
                Message messageOut = exchangeOut.getMessage();
                contentOut = messageOut.getContent();
                for (Property property : exchangeOut.getContext(messageOut).getProperties()) {
                    contextOut.put(property.getName(), property.getValue());
                }
            }
            fault = handler.getFault();
        } catch (Throwable t) {
            fault = t;
        }
        return new SwitchYardServiceResponse(contentOut, contextOut, fault);
    }

    private static final clreplaced FaultHandler extends SynchronousInOutHandler {

        private Object _fault;

        private Object getFault() {
            return _fault;
        }

        @Override
        public void handleFault(Exchange exchange) {
            _fault = exchange.getMessage().getContent();
            super.handleFault(exchange);
        }
    }
}

19 View Complete Implementation : BaseServiceHandler.java
Copyright Apache License 2.0
Author : jboss-switchyard
/**
 * NOP implementation of ServiceHandler.
 */
public clreplaced BaseServiceHandler extends BaseHandler implements ServiceHandler {

    private State _state = State.NONE;

    final private ServiceDomain _domain;

    /**
     * Creates a service handler that will not override the context clreplaced loader
     * used when start/stop are invoked.
     */
    public BaseServiceHandler() {
        this(null);
    }

    protected BaseServiceHandler(ServiceDomain domain) {
        _domain = domain;
    }

    @Override
    public synchronized void start() {
        if (_state == State.STARTED) {
            // already started
            return;
        } else if ((_state == State.STARTING) || (_state == State.STARTED) || (_state == State.STOPPING)) {
            throw BaseDeployMessages.MESSAGES.invalidHandlerState();
        }
        final ClreplacedLoader oldTCCL = Thread.currentThread().getContextClreplacedLoader();
        try {
            final ClreplacedLoader deploymentCL = getDeploymentClreplacedLoader();
            if (deploymentCL != null) {
                Thread.currentThread().setContextClreplacedLoader(deploymentCL);
            }
            setState(State.STARTING);
            try {
                doStart();
                setState(State.STARTED);
            } catch (RuntimeException e) {
                setState(State.NONE);
                throw e;
            }
        } finally {
            Thread.currentThread().setContextClreplacedLoader(oldTCCL);
        }
    }

    protected void doStart() {
    }

    @Override
    public synchronized void stop() {
        if ((_state == State.NONE) || (_state == State.STOPPED)) {
            // already stopped
            return;
        } else if (_state != State.STARTED) {
            throw BaseDeployMessages.MESSAGES.invalidHandlerState();
        }
        final ClreplacedLoader oldTCCL = Thread.currentThread().getContextClreplacedLoader();
        try {
            final ClreplacedLoader deploymentCL = getDeploymentClreplacedLoader();
            if (deploymentCL != null) {
                Thread.currentThread().setContextClreplacedLoader(deploymentCL);
            }
            setState(State.STOPPING);
            try {
                doStop();
                setState(State.STOPPED);
            } catch (RuntimeException e) {
                setState(State.STARTED);
                throw e;
            }
        } finally {
            Thread.currentThread().setContextClreplacedLoader(oldTCCL);
        }
    }

    protected void doStop() {
    }

    @Override
    public State getState() {
        return _state;
    }

    /**
     * @param newState the new state of the service handler.
     */
    protected void setState(State newState) {
        if (newState == null) {
            throw BaseDeployMessages.MESSAGES.stateCannotBeNull();
        }
        _state = newState;
    }

    /**
     * @return the clreplaced loader for the deployment using this handler.
     */
    protected ClreplacedLoader getDeploymentClreplacedLoader() {
        return _domain == null ? null : (ClreplacedLoader) _domain.getProperty(CLreplacedLOADER_PROPERTY);
    }
}

18 View Complete Implementation : RiftsawBPELOSGiExchangeHandler.java
Copyright Apache License 2.0
Author : jboss-switchyard
/**
 * Specialized for use in OSGi environments.
 */
public clreplaced RiftsawBPELOSGiExchangeHandler extends RiftsawBPELExchangeHandler {

    private static final Logger LOG = Logger.getLogger(RiftsawBPELOSGiExchangeHandler.clreplaced);

    private final ServiceDomain _domain;

    protected RiftsawBPELOSGiExchangeHandler(ServiceDomain domain) {
        super(domain);
        _domain = domain;
    }

    @Override
    protected File getDeployment() throws Exception {
        final Bundle applicationBundle = getApplicationBundle();
        final Enumeration<URL> deploymentEntries = applicationBundle.findEntries("/", "deploy.xml", false);
        if (deploymentEntries.hasMoreElements()) {
            return expandDeployment(applicationBundle, deploymentEntries.nextElement());
        }
        throw new Exception("Bundle does not contain deploy.xml file: " + applicationBundle.getSymbolicName());
    }

    @Override
    protected String getDeploymentName() throws Exception {
        return getApplicationBundle().getSymbolicName();
    }

    private Bundle getApplicationBundle() throws Exception {
        return (Bundle) _domain.getProperty(SwitchYardContainerImpl.SWITCHYARD_DEPLOYMENT_BUNDLE);
    }

    private File expandDeployment(Bundle applicationBundle, URL deployXmlUrl) throws IOException {
        final File rootDirectory = getDataDirectory(applicationBundle);
        copyFile(deployXmlUrl, rootDirectory);
        final Enumeration<URL> bpelFiles = applicationBundle.findEntries("/", "*.bpel*", true);
        if (bpelFiles != null) {
            while (bpelFiles.hasMoreElements()) {
                copyFile(bpelFiles.nextElement(), rootDirectory);
            }
        }
        return rootDirectory;
    }

    private void copyFile(URL source, File rootDirectory) throws IOException {
        final File destination = new File(rootDirectory, source.getPath());
        if (!destination.getName().matches(".+\\.bpel(-\\d+)?") && !"deploy.xml".equals(destination.getName())) {
            LOG.warnf("Skipping file copy for \"%s\", not a *.bpel or deploy.xml file.", destination.getName());
            return;
        }
        destination.getParentFile().mkdirs();
        ReadableByteChannel input = null;
        FileChannel output = null;
        try {
            final ByteBuffer buffer = ByteBuffer.allocate(0x100000);
            input = Channels.newChannel(source.openStream());
            output = new FileOutputStream(destination).getChannel();
            while (input.read(buffer) > 0) {
                buffer.flip();
                output.write(buffer);
                buffer.clear();
            }
        } finally {
            if (input != null) {
                try {
                    input.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (output != null) {
                try {
                    output.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private File getDataDirectory(final Bundle bundle) {
        final File dataDirectory = bundle.getDataFile("");
        final File deploymentsDirectory = new File(dataDirectory, "bpel");
        if (!deploymentsDirectory.exists()) {
            deploymentsDirectory.mkdirs();
            deploymentsDirectory.deleteOnExit();
        }
        return deploymentsDirectory;
    }
}

18 View Complete Implementation : EntityManagerFactoryLoader.java
Copyright Apache License 2.0
Author : jboss-switchyard
/**
 * @param domain the service domain
 * @return the BPM EMF replacedociated with the specified domain.
 */
public EnreplacedyManagerFactory getEnreplacedyManagerFactory(ServiceDomain domain) {
    return Persistence.createEnreplacedyManagerFactory(UNIT_NAME);
}

18 View Complete Implementation : HttpComponent.java
Copyright Apache License 2.0
Author : jboss-switchyard
/**
 * {@inheritDoc}
 */
@Override
public Activator createActivator(ServiceDomain domain) {
    HttpActivator activator = new HttpActivator();
    activator.setServiceDomain(domain);
    activator.setEnvironment(getConfig());
    return activator;
}

18 View Complete Implementation : LocalExchangeBus.java
Copyright Apache License 2.0
Author : jboss-switchyard
clreplaced LocalDispatcher implements Dispatcher {

    private HandlerChain _requestChain;

    private HandlerChain _replyChain;

    private ServiceReference _reference;

    private ServiceDomain _domain;

    /**
     * Constructor.
     * @param _domain
     * @param handlerChain handler chain
     */
    LocalDispatcher(ServiceDomain domain, final ServiceReference reference, final HandlerChain requestChain, final HandlerChain replyChain) {
        this._domain = domain;
        _reference = reference;
        _requestChain = requestChain;
        _replyChain = replyChain;
    }

    @Override
    public void dispatch(final Exchange exchange) {
        switch(exchange.getPhase()) {
            case IN:
                _requestChain.handle(exchange);
                break;
            case OUT:
                ExchangeHandler replyHandler = ((ExchangeImpl) exchange).getReplyHandler();
                if (replyHandler != null) {
                    _replyChain.replace(HandlerChain.CONSUMER_HANDLER, replyHandler);
                }
                _replyChain.handle(exchange);
                break;
            default:
                throw RuntimeMessages.MESSAGES.invalidPhaseForDispatch(exchange.getPhase().toString());
        }
    }

    @Override
    public ServiceReference getServiceReference() {
        return _reference;
    }

    @Override
    public Exchange createExchange(ExchangeHandler handler, ExchangePattern pattern) {
        ExchangeImpl exchangeImpl = new ExchangeImpl(_domain, this, handler);
        return exchangeImpl;
    }
}

18 View Complete Implementation : ClojureComponent.java
Copyright Apache License 2.0
Author : jboss-switchyard
/* (non-Javadoc)
     * @see org.switchyard.deploy.Component#createActivator(org.switchyard.ServiceDomain)
     */
@Override
public Activator createActivator(ServiceDomain domain) {
    ClojureActivator activator = new ClojureActivator();
    activator.setServiceDomain(domain);
    return activator;
}

18 View Complete Implementation : RiftsawBPELOSGiExchangeHandlerFactory.java
Copyright Apache License 2.0
Author : jboss-switchyard
@Override
public BPELExchangeHandler newBPELExchangeHandler(ServiceDomain serviceDomain) {
    return new RiftsawBPELOSGiExchangeHandler(serviceDomain);
}

18 View Complete Implementation : BeanComponent.java
Copyright Apache License 2.0
Author : jboss-switchyard
/* (non-Javadoc)
     * @see org.switchyard.deploy.Component#createActivator(org.switchyard.ServiceDomain)
     */
@Override
public Activator createActivator(ServiceDomain domain) {
    BeanComponentActivator activator = new BeanComponentActivator();
    activator.setServiceDomain(domain);
    return activator;
}

18 View Complete Implementation : JCAComponent.java
Copyright Apache License 2.0
Author : jboss-switchyard
/* (non-Javadoc)
     * @see org.switchyard.deploy.Component#createActivator(org.switchyard.ServiceDomain)
     */
@Override
public Activator createActivator(ServiceDomain domain) {
    JCAActivator activator = new JCAActivator();
    activator.setServiceDomain(domain);
    activator.setResourceAdapterRepository(_raRepository);
    return activator;
}

18 View Complete Implementation : RESTEasyComponent.java
Copyright Apache License 2.0
Author : jboss-switchyard
/**
 * {@inheritDoc}
 */
@Override
public Activator createActivator(ServiceDomain domain) {
    RESTEasyActivator activator = new RESTEasyActivator();
    activator.setServiceDomain(domain);
    activator.setEnvironment(getConfig());
    return activator;
}

18 View Complete Implementation : RulesComponent.java
Copyright Apache License 2.0
Author : jboss-switchyard
/**
 * {@inheritDoc}
 */
@Override
public Activator createActivator(ServiceDomain domain) {
    RulesActivator activator = new RulesActivator();
    activator.setServiceDomain(domain);
    return activator;
}

18 View Complete Implementation : BeanActivatorWithoutConfigExcludeTest.java
Copyright Apache License 2.0
Author : jboss-switchyard
@RunWith(SwitchYardRunner.clreplaced)
@SwitchYardTestCaseConfig(mixins = CDIMixIn.clreplaced, exclude = BeanComponentActivator.BEAN_TYPE)
public clreplaced BeanActivatorWithoutConfigExcludeTest {

    private ServiceDomain domain;

    @Test
    public void test() {
        List<Service> services = ((DomainImpl) domain).getServiceRegistry().getServices(QName.valueOf("ConsumerService"));
        replacedert.replacedertEquals(0, services.size());
    }
}

18 View Complete Implementation : RulesServiceTests.java
Copyright Apache License 2.0
Author : jboss-switchyard
/**
 * Tests the Rules implementation.
 *
 * @author David Ward <<a href="mailto:[email protected]">[email protected]</a>> © 2013 Red Hat Inc.
 */
@RunWith(SwitchYardRunner.clreplaced)
public clreplaced RulesServiceTests {

    private static final String ACCESS_ATTACHMENT_DRL = "org/switchyard/component/rules/service/RulesServiceTests-AccessAttachment.drl";

    private static final String DECISION_TABLE_XLS = "org/switchyard/component/rules/service/RulesServiceTests-DecisionTable.xls";

    private static final String DECLARE_FACTS_DRL = "org/switchyard/component/rules/service/RulesServiceTests-DeclareFacts.drl";

    private ServiceDomain serviceDomain;

    @Rules(manifest = @Manifest(resources = @Resource(location = ACCESS_ATTACHMENT_DRL, type = "DRL")))
    public interface AccessAttachment {

        @Execute(inputs = { @Input(from = "message.attachmentMap['someAttach']"), @Input(from = "message.content") })
        public Object process(Object content);
    }

    @Test
    public void testAccessAttachment() throws Exception {
        final Holder holder = new Holder();
        RulesComponentImplementationModel rci_model = (RulesComponentImplementationModel) new RulesSwitchYardScanner().scan(AccessAttachment.clreplaced).getImplementation();
        QName serviceName = new QName("AccessAttachment");
        RulesExchangeHandler handler = new RulesExchangeHandler(rci_model, serviceDomain, serviceName);
        Service service = serviceDomain.registerService(serviceName, JavaService.fromClreplaced(AccessAttachment.clreplaced), handler);
        serviceDomain.registerServiceReference(service.getName(), service.getInterface(), service.getProviderHandler());
        handler.start();
        DataSource attachment = new TestDataSource("someAttach", "text/plain", "someAttachData");
        new Invoker(serviceDomain, serviceName).operation("process").attachment(attachment.getName(), attachment).sendInOnly(holder);
        handler.stop();
        replacedert.replacedertEquals("someAttachData", holder.getValue());
    }

    @Rules(manifest = @Manifest(resources = @Resource(location = DECISION_TABLE_XLS, type = "DTABLE")))
    public interface DecisionTable {

        @Insert(globals = @Global(from = "context['list']", to = "list"), inputs = @Input(from = "message.content"))
        public Object insert(Object content);

        @FireAllRules
        public Object fireAllRules();
    }

    @Test
    public void testDecisionTable() throws Exception {
        RulesComponentImplementationModel rci_model = (RulesComponentImplementationModel) new RulesSwitchYardScanner().scan(DecisionTable.clreplaced).getImplementation();
        QName serviceName = new QName("DecisionTable");
        RulesExchangeHandler handler = new RulesExchangeHandler(rci_model, serviceDomain, serviceName);
        Service service = serviceDomain.registerService(serviceName, JavaService.fromClreplaced(DecisionTable.clreplaced), handler);
        serviceDomain.registerServiceReference(service.getName(), service.getInterface(), service.getProviderHandler());
        handler.start();
        List<Object> list = new ArrayList<Object>();
        Invoker invoker = new Invoker(serviceDomain, serviceName);
        invoker.operation("insert").property("list", list).sendInOnly(new Cheese("stilton", 42));
        invoker.operation("insert").sendInOnly(new Person("michael", "stilton", 42));
        invoker.operation("fireAllRules").sendInOnly(null);
        replacedert.replacedertEquals(1, list.size());
        replacedert.replacedertEquals("Old man stilton", list.get(0));
        handler.stop();
    }

    @Rules(manifest = @Manifest(resources = @Resource(location = DECISION_TABLE_XLS, type = "DTABLE", detail = @ResourceDetail(inputType = "XLS", worksheetName = "Tables_2"))))
    public interface NamedWorksheet {

        @Insert(globals = @Global(from = "context['list']", to = "list"), inputs = @Input(from = "message.content"))
        public Object insert(Object content);

        @FireAllRules
        public Object fireAllRules();
    }

    @Test
    public void testNamedWorksheet() throws Exception {
        RulesComponentImplementationModel rci_model = (RulesComponentImplementationModel) new RulesSwitchYardScanner().scan(NamedWorksheet.clreplaced).getImplementation();
        QName serviceName = new QName("NamedWorksheet");
        RulesExchangeHandler handler = new RulesExchangeHandler(rci_model, serviceDomain, serviceName);
        Service service = serviceDomain.registerService(serviceName, JavaService.fromClreplaced(NamedWorksheet.clreplaced), handler);
        serviceDomain.registerServiceReference(service.getName(), service.getInterface(), service.getProviderHandler());
        handler.start();
        List<Object> list = new ArrayList<Object>();
        Invoker invoker = new Invoker(serviceDomain, serviceName);
        invoker.operation("insert").property("list", list).sendInOnly(new Cheese("cheddar", 42));
        invoker.operation("insert").sendInOnly(new Person("michael", "stilton", 25));
        invoker.operation("fireAllRules").sendInOnly(null);
        replacedert.replacedertEquals(1, list.size());
        replacedert.replacedertEquals("Young man cheddar", list.get(0));
        handler.stop();
    }

    @Rules(manifest = @Manifest(resources = @Resource(location = DECLARE_FACTS_DRL, type = "DRL")))
    public interface DeclareFacts {

        @Execute(inputs = { @Input(from = "message.content") })
        public Object process(Object content);
    }

    @Test
    public void testDeclareFacts() throws Exception {
        final Holder holder = new Holder();
        RulesComponentImplementationModel rci_model = (RulesComponentImplementationModel) new RulesSwitchYardScanner().scan(DeclareFacts.clreplaced).getImplementation();
        QName serviceName = new QName("DeclareFacts");
        RulesExchangeHandler handler = new RulesExchangeHandler(rci_model, serviceDomain, serviceName);
        Service service = serviceDomain.registerService(serviceName, JavaService.fromClreplaced(DeclareFacts.clreplaced), handler);
        serviceDomain.registerServiceReference(service.getName(), service.getInterface(), service.getProviderHandler());
        handler.start();
        new Invoker(serviceDomain, serviceName).operation("process").sendInOnly(holder);
        handler.stop();
        replacedert.replacedertEquals("handled", holder.getValue());
    }

    public static final clreplaced Holder {

        private String _value;

        public String getValue() {
            return _value;
        }

        public void setValue(String value) {
            _value = value;
        }

        public String toString() {
            return _value;
        }
    }
}

18 View Complete Implementation : SOAPComponent.java
Copyright Apache License 2.0
Author : jboss-switchyard
/**
 * {@inheritDoc}
 */
@Override
public Activator createActivator(ServiceDomain domain) {
    SOAPActivator activator = new SOAPActivator();
    activator.setServiceDomain(domain);
    activator.setEnvironment(getConfig());
    return activator;
}

18 View Complete Implementation : BeanActivatorWithoutConfigIncludeTest.java
Copyright Apache License 2.0
Author : jboss-switchyard
@RunWith(SwitchYardRunner.clreplaced)
@SwitchYardTestCaseConfig(mixins = CDIMixIn.clreplaced, include = BeanComponentActivator.BEAN_TYPE)
public clreplaced BeanActivatorWithoutConfigIncludeTest {

    private ServiceDomain domain;

    @Test
    public void test() {
        List<Service> services = ((DomainImpl) domain).getServiceRegistry().getServices(QName.valueOf("ConsumerService"));
        replacedert.replacedertEquals(1, services.size());
    }
}

18 View Complete Implementation : AbstractEndpointPublisher.java
Copyright Apache License 2.0
Author : jboss-switchyard
/**
 * {@inheritDoc}
 */
public synchronized Endpoint publish(ServiceDomain domain, final SOAPBindingModel config, final String bindingId, final InboundHandler handler) {
    return publish(domain, config, bindingId, handler, (WebServiceFeature) null);
}

18 View Complete Implementation : SwitchYardBuilderTest.java
Copyright Apache License 2.0
Author : jboss-switchyard
clreplaced MockDeployment extends Deployment {

    private ServiceDomain _domain;

    private QName _name;

    MockDeployment(SwitchYardModel config, QName name, ServiceDomainManager sdm) {
        super(config);
        _name = name;
        _domain = sdm.createDomain(name, config);
    }

    @Override
    public QName getName() {
        return _name;
    }

    @Override
    public ServiceDomain getDomain() {
        return _domain;
    }
}

18 View Complete Implementation : RiftsawBPELExchangeHandlerFactory.java
Copyright Apache License 2.0
Author : jboss-switchyard
/**
 * {@inheritDoc}
 */
@Override
public BPELExchangeHandler newBPELExchangeHandler(ServiceDomain serviceDomain) {
    return new RiftsawBPELExchangeHandler(serviceDomain);
}

18 View Complete Implementation : ExchangeDispatcherTest.java
Copyright Apache License 2.0
Author : jboss-switchyard
public clreplaced ExchangeDispatcherTest {

    private static final String REQUEST = "REQUEST";

    private ServiceDomain _domain;

    private CamelExchangeBus _provider;

    private SwitchYardCamelContextImpl _camelContext;

    @Before
    public void setUp() throws Exception {
        _domain = new MockDomain();
        initDomain(_domain);
    }

    @After
    public void tearDown() throws Exception {
        _camelContext.stop();
    }

    @Test
    public void testDispatchInOnly() throws Exception {
        QName name = new QName("testDispatchInOnly");
        ExchangeSink sink = new ExchangeSink();
        Service service = new MockService(name, new InOnlyService(), sink);
        ServiceReference reference = new ServiceReferenceImpl(name, new InOnlyService(), null, null);
        ExchangeDispatcher dispatch = _provider.createDispatcher(reference);
        Exchange exchange = new CamelExchange(dispatch, new DefaultExchange(_camelContext), sink);
        exchange.consumer(reference, reference.getInterface().getOperation(ServiceInterface.DEFAULT_OPERATION));
        exchange.provider(service, service.getInterface().getOperation(ServiceInterface.DEFAULT_OPERATION));
        Message message = exchange.createMessage();
        exchange.send(message);
        Thread.sleep(200);
        replacedert.replacedertEquals(message.getContext().getProperty(Exchange.MESSAGE_ID), sink.getLastExchange().getMessage().getContext().getProperty(Exchange.MESSAGE_ID));
    }

    @Test
    public void throttle() throws Exception {
        QName name = new QName("testDispatchInOnly");
        final ExchangeSink sink = new ExchangeSink(1000);
        final Service service = new MockService(name, new InOnlyService(), sink);
        final ServiceReference reference = new ServiceReferenceImpl(name, new InOnlyService(), null, null);
        final ExchangeDispatcher dispatch = _provider.createDispatcher(reference);
        // Set throttling to 1 per second
        Throttling throttle = new Throttling().setMaxRequests(1);
        ServiceMetadataBuilder.update(reference.getServiceMetadata()).throttling(throttle);
        final int NUM_SENDS = 5;
        for (int i = 0; i < NUM_SENDS; i++) {
            new Thread(new Runnable() {

                public void run() {
                    Exchange exchange = dispatch.createExchange(sink, ExchangePattern.IN_ONLY);
                    exchange.consumer(reference, reference.getInterface().getOperation(ServiceInterface.DEFAULT_OPERATION));
                    exchange.provider(service, service.getInterface().getOperation(ServiceInterface.DEFAULT_OPERATION));
                    Message message = exchange.createMessage();
                    exchange.send(message);
                }
            }).start();
        }
        Thread.sleep(500);
        replacedert.replacedertTrue("Concurrent requests were not throttled!", sink.getReceivedCount() < NUM_SENDS);
    }

    @Test
    public void throttleWithTimePeriod() throws Exception {
        ServiceDomain domain = new MockDomain();
        domain.setProperty(CamelContextConfigurator.SHUTDOWN_TIMEOUT, "5");
        initDomain(domain);
        QName name = new QName("testThrottleTimePeriod");
        final ExchangeSink sink = new ExchangeSink();
        final Service service = new MockService(name, new InOnlyService(), sink);
        final ServiceReference reference = new ServiceReferenceImpl(name, new InOnlyService(), null, null);
        // Set throttling to 1 per minute (60000 ms)
        Throttling throttle = new Throttling().setMaxRequests(1).setTimePeriod(60 * 1000);
        ServiceMetadataBuilder.update(reference.getServiceMetadata()).throttling(throttle);
        final ExchangeDispatcher dispatch = _provider.createDispatcher(reference);
        final int NUM_SENDS = 5;
        for (int i = 0; i < NUM_SENDS; i++) {
            new Thread(new Runnable() {

                public void run() {
                    Exchange exchange = dispatch.createExchange(sink, ExchangePattern.IN_ONLY);
                    exchange.consumer(reference, reference.getInterface().getOperation(ServiceInterface.DEFAULT_OPERATION));
                    exchange.provider(service, service.getInterface().getOperation(ServiceInterface.DEFAULT_OPERATION));
                    Message message = exchange.createMessage();
                    exchange.send(message);
                }
            }).start();
        }
        Thread.sleep(4000);
        replacedert.replacedertEquals("Received more than one message per minute - throttling policy violated!", 1, sink.getReceivedCount());
    }

    @Test
    public void testDispatchInOut() throws Exception {
        QName name = new QName("testDispatchInOut");
        // provider handler
        ExchangeSink inHandler = new ExchangeSink(true);
        // consumer handler
        ExchangeSink outHandler = new ExchangeSink();
        Service service = new MockService(name, new InOutService(), inHandler);
        ServiceReference reference = new ServiceReferenceImpl(name, new InOutService(), null, null);
        Dispatcher dispatch = _provider.createDispatcher(reference);
        Exchange exchange = dispatch.createExchange(outHandler, ExchangePattern.IN_OUT);
        exchange.consumer(reference, reference.getInterface().getOperation(ServiceInterface.DEFAULT_OPERATION));
        exchange.provider(service, service.getInterface().getOperation(ServiceInterface.DEFAULT_OPERATION));
        Message message = exchange.createMessage();
        exchange.send(message.setContent(REQUEST));
        Thread.sleep(400);
        Exchange lastExchange = outHandler.getLastExchange();
        replacedertNotNull(lastExchange);
        // replacedertEquals(REQUEST, lastExchange.getMessage().getContent());
        Property messageId = message.getContext().getProperty(Exchange.MESSAGE_ID);
        replacedertNotNull("Message id must be available after sending message and receiving response", messageId);
        Property relatesTo = lastExchange.getContext().getProperty(Exchange.RELATES_TO);
        replacedertNotNull("Relates to must be specified for outgoing message", relatesTo);
        replacedertEquals("Relates to property should point to in message id", messageId.getValue(), relatesTo.getValue());
    }

    private void initDomain(ServiceDomain domain) throws Exception {
        _camelContext = new SwitchYardCamelContextImpl();
        _camelContext.setServiceDomain(domain);
        _provider = new CamelExchangeBus(_camelContext);
        _provider.init(domain);
        _camelContext.start();
    }

    /**
     * Holds a reference to the most recent exchange received by the handler.
     */
    clreplaced ExchangeSink extends BaseHandler {

        static final String REPLY = "REPLY";

        private Exchange _lastExchange;

        private boolean _reply;

        private int _wait;

        private AtomicInteger _numExchanges = new AtomicInteger();

        ExchangeSink() {
            this(false);
        }

        ExchangeSink(int wait) {
            _wait = wait;
        }

        ExchangeSink(boolean reply) {
            _reply = reply;
        }

        @Override
        public void handleMessage(Exchange exchange) throws HandlerException {
            _numExchanges.incrementAndGet();
            _lastExchange = exchange;
            try {
                Thread.sleep(_wait);
            } catch (InterruptedException ex) {
                throw new RuntimeException(ex);
            }
            if (_reply) {
                exchange.getContext().setProperty(REPLY, true);
                exchange.send(exchange.createMessage().setContent(REPLY));
            }
        }

        public int getReceivedCount() {
            return _numExchanges.get();
        }

        Exchange getLastExchange() {
            return _lastExchange;
        }
    }
}

18 View Complete Implementation : LocalExchangeBus.java
Copyright Apache License 2.0
Author : jboss-switchyard
/**
 * Default endpoint provider.
 */
public clreplaced LocalExchangeBus implements ExchangeBus {

    private ConcurrentHashMap<QName, Dispatcher> _dispatchers = new ConcurrentHashMap<QName, Dispatcher>();

    private HandlerChain _requestChain;

    private HandlerChain _replyChain;

    private ServiceDomain _domain;

    /**
     * Create a new LocalExchangeBus.
     */
    public LocalExchangeBus() {
    }

    @Override
    public void init(ServiceDomain domain) {
        _domain = domain;
        TransactionHandler transactionHandler = new TransactionHandler();
        TransformHandler transformHandler = new TransformHandler(domain.getTransformerRegistry());
        ValidateHandler validateHandler = new ValidateHandler(domain.getValidatorRegistry());
        // Build out the request and reply handler chains.
        _requestChain = new DefaultHandlerChain();
        _requestChain.addLast("addressing", new AddressingHandler(_domain));
        _requestChain.addLast("transaction-pre-invoke", transactionHandler);
        _requestChain.addLast("security-process", new SecurityHandler(_domain, SecurityAction.PROCESS));
        _requestChain.addLast("generic-policy", new PolicyHandler());
        _requestChain.addLast("validation-before-transform", validateHandler);
        _requestChain.addLast("transformation", transformHandler);
        _requestChain.addLast("validation-after-transform", validateHandler);
        _requestChain.addLast("provider", new ProviderHandler(_domain));
        _requestChain.addLast("security-cleanup", new SecurityHandler(_domain, SecurityAction.CLEANUP));
        _requestChain.addLast("transaction-post-invoke", transactionHandler);
        _replyChain = new DefaultHandlerChain();
        _replyChain.addLast("validation-before-transform", validateHandler);
        _replyChain.addLast("transformation", transformHandler);
        _replyChain.addLast("validation-after-transform", validateHandler);
        _replyChain.addLast(HandlerChain.CONSUMER_HANDLER, new BaseHandler());
    }

    @Override
    public void start() {
    // NOP
    }

    @Override
    public void stop() {
        _dispatchers.clear();
    }

    @Override
    public synchronized Dispatcher createDispatcher(ServiceReference reference) {
        HandlerChain requestChain = _requestChain.copy();
        HandlerChain replyChain = _replyChain.copy();
        Dispatcher dispatcher = new LocalDispatcher(_domain, reference, requestChain, replyChain);
        _dispatchers.put(reference.getName(), dispatcher);
        return dispatcher;
    }

    @Override
    public Dispatcher getDispatcher(ServiceReference reference) {
        return _dispatchers.get(reference.getName());
    }
}

18 View Complete Implementation : SwitchYardComponentTestBase.java
Copyright Apache License 2.0
Author : jboss-switchyard
/**
 * Base clreplaced for switchyard-camel integration.
 */
public abstract clreplaced SwitchYardComponentTestBase extends CamelTestSupport {

    protected ServiceDomain _serviceDomain;

    protected SwitchYardCamelContextImpl _camelContext;

    @Override
    protected CamelContext createCamelContext() throws Exception {
        _camelContext = new SwitchYardCamelContextImpl(false);
        _camelContext.setServiceDomain(_serviceDomain);
        return _camelContext;
    }
}

18 View Complete Implementation : SecurityMetadata.java
Copyright Apache License 2.0
Author : jboss-switchyard
/**
 * SecurityMetadata.
 *
 * @author David Ward <<a href="mailto:[email protected]">[email protected]</a>> © 2014 Red Hat Inc.
 */
public final clreplaced SecurityMetadata {

    private final Source _source;

    private final ServiceDomain _serviceDomain;

    private final ServiceSecurity _serviceSecurity;

    private SecurityMetadata(Source source, ServiceDomain serviceDomain, ServiceSecurity serviceSecurity) {
        _source = source;
        _serviceDomain = serviceDomain;
        _serviceSecurity = serviceSecurity;
    }

    /**
     * If the source is the provider Service.
     * @return if true
     */
    public boolean isProvider() {
        return _source == Source.PROVIDER;
    }

    /**
     * If the source is the consumer ServiceReference.
     * @return if true
     */
    public boolean isConsumer() {
        return _source == Source.CONSUMER;
    }

    /**
     * Gets the ServiceDomain.
     * @return the ServiceDomain
     */
    public ServiceDomain getServiceDomain() {
        return _serviceDomain;
    }

    /**
     * Gets the ServiceSecurity.
     * @return the ServiceSecurity
     */
    public ServiceSecurity getServiceSecurity() {
        return _serviceSecurity;
    }

    /**
     * Gets the ServiceDomain from the Exchange.
     * @param exchange the Exchange
     * @return the ServiceDomain
     */
    public static final ServiceDomain getServiceDomain(Exchange exchange) {
        return getSecurityMetadata(exchange).getServiceDomain();
    }

    /**
     * Gets the ServiceSecurity from the Exchange.
     * @param exchange the Exchange
     * @return the ServiceSecurity
     */
    public static final ServiceSecurity getServiceSecurity(Exchange exchange) {
        return getSecurityMetadata(exchange).getServiceSecurity();
    }

    /**
     * Gets the SecurityMetadata from the Exchange.
     * @param exchange the Exchange
     * @return the SecurityMetadata
     */
    public static final SecurityMetadata getSecurityMetadata(Exchange exchange) {
        Source source = null;
        ServiceDomain serviceDomain = null;
        ServiceSecurity serviceSecurity = null;
        Service service = exchange.getProvider();
        if (service != null) {
            source = Source.PROVIDER;
            serviceDomain = service.getDomain();
            serviceSecurity = service.getServiceMetadata().getSecurity();
        }
        if (serviceSecurity == null) {
            ServiceReference serviceReference = exchange.getConsumer();
            if (serviceReference != null) {
                source = Source.CONSUMER;
                serviceDomain = serviceReference.getDomain();
                serviceSecurity = serviceReference.getServiceMetadata().getSecurity();
            }
        }
        return new SecurityMetadata(source, serviceDomain, serviceSecurity);
    }

    private static enum Source {

        PROVIDER, CONSUMER
    }
}

18 View Complete Implementation : ExchangeEventsTest.java
Copyright Apache License 2.0
Author : jboss-switchyard
public clreplaced ExchangeEventsTest {

    private static final String REQUEST = "REQUEST";

    private ServiceDomain _domain;

    private CamelExchangeBus _provider;

    private SwitchYardCamelContextImpl _camelContext;

    @Before
    public void setUp() throws Exception {
        _domain = new MockDomain();
        _camelContext = new SwitchYardCamelContextImpl();
        _camelContext.setServiceDomain(_domain);
        _provider = new CamelExchangeBus(_camelContext);
        _provider.init(_domain);
        _camelContext.start();
    }

    @After
    public void tearDown() throws Exception {
        _camelContext.stop();
    }

    @Test
    public void testExchangeEventsForInOnly() throws Exception {
        EventCounter counter = new EventCounter();
        _domain.addEventObserver(counter, ExchangeInitiatedEvent.clreplaced);
        _domain.addEventObserver(counter, ExchangeCompletionEvent.clreplaced);
        QName name = new QName("testDispatchInOnly");
        ExchangeSink sink = new ExchangeSink();
        Service service = new MockService(name, new InOnlyService(), sink);
        ServiceReference reference = new ServiceReferenceImpl(name, new InOnlyService(), null, null);
        ExchangeDispatcher dispatch = _provider.createDispatcher(reference);
        Exchange exchange = new CamelExchange(dispatch, new DefaultExchange(_camelContext), sink);
        exchange.consumer(reference, reference.getInterface().getOperation(ServiceInterface.DEFAULT_OPERATION));
        exchange.provider(service, service.getInterface().getOperation(ServiceInterface.DEFAULT_OPERATION));
        Message message = exchange.createMessage();
        exchange.send(message);
        Thread.sleep(200);
        replacedert.replacedertEquals(1, counter.initiatedCount);
        replacedert.replacedertEquals(1, counter.completedCount);
    }

    @Test
    public void testExchangeEventsForInOut() throws Exception {
        EventCounter counter = new EventCounter();
        _domain.addEventObserver(counter, ExchangeInitiatedEvent.clreplaced);
        _domain.addEventObserver(counter, ExchangeCompletionEvent.clreplaced);
        QName name = new QName("testDispatchInOut");
        // provider handler
        ExchangeSink inHandler = new ExchangeSink(true);
        // consumer handler
        ExchangeSink outHandler = new ExchangeSink();
        Service service = new MockService(name, new InOutService(), inHandler);
        ServiceReference reference = new ServiceReferenceImpl(name, new InOutService(), null, null);
        Dispatcher dispatch = _provider.createDispatcher(reference);
        Exchange exchange = dispatch.createExchange(outHandler, ExchangePattern.IN_OUT);
        exchange.consumer(reference, reference.getInterface().getOperation(ServiceInterface.DEFAULT_OPERATION));
        exchange.provider(service, service.getInterface().getOperation(ServiceInterface.DEFAULT_OPERATION));
        Message message = exchange.createMessage();
        exchange.send(message.setContent(REQUEST));
        Thread.sleep(400);
        Exchange lastExchange = outHandler.getLastExchange();
        replacedertNotNull(lastExchange);
        replacedert.replacedertEquals(1, counter.initiatedCount);
        replacedert.replacedertEquals(1, counter.completedCount);
    }

    clreplaced EventCounter implements EventObserver {

        int initiatedCount;

        int completedCount;

        public void notify(EventObject event) {
            if (event instanceof ExchangeInitiatedEvent) {
                ++initiatedCount;
            } else if (event instanceof ExchangeCompletionEvent) {
                ++completedCount;
            }
        }
    }

    /**
     * Holds a reference to the most recent exchange received by the handler.
     */
    clreplaced ExchangeSink extends BaseHandler {

        static final String REPLY = "REPLY";

        private Exchange _lastExchange;

        private boolean _reply;

        ExchangeSink() {
            this(false);
        }

        ExchangeSink(boolean reply) {
            _reply = reply;
        }

        @Override
        public void handleMessage(Exchange exchange) throws HandlerException {
            _lastExchange = exchange;
            if (_reply) {
                exchange.getContext().setProperty(REPLY, true);
                exchange.send(exchange.createMessage().setContent(REPLY));
            }
        }

        Exchange getLastExchange() {
            return _lastExchange;
        }
    }
}

18 View Complete Implementation : BPMComponent.java
Copyright Apache License 2.0
Author : jboss-switchyard
/**
 * {@inheritDoc}
 */
@Override
public Activator createActivator(ServiceDomain domain) {
    BPMActivator activator = new BPMActivator();
    activator.setServiceDomain(domain);
    return activator;
}

18 View Complete Implementation : SwitchYardCamelContextImpl.java
Copyright Apache License 2.0
Author : jboss-switchyard
/**
 * replacedociates camel context with given service domain.
 *
 * @param domain Domain to replacedociate.
 */
public void setServiceDomain(ServiceDomain domain) {
    _domain = domain;
    for (EventNotifier notifier : getManagementStrategy().getEventNotifiers()) {
        if (notifier instanceof CamelEventBridge) {
            ((CamelEventBridge) notifier).setEventPublisher(domain.getEventPublisher());
        }
    }
    PackageScanClreplacedResolver packageScanClreplacedResolver = findPackageScanClreplacedResolver();
    if (packageScanClreplacedResolver != null) {
        setPackageScanClreplacedResolver(packageScanClreplacedResolver);
    }
    _domain.setProperty(CAMEL_CONTEXT_PROPERTY, this);
}

18 View Complete Implementation : BaseActivator.java
Copyright Apache License 2.0
Author : jboss-switchyard
/**
 * Base implementation of Activator which provides a convenience implementation
 * for declaring activation types.
 */
public abstract clreplaced BaseActivator implements Activator {

    private List<String> _activationTypes = new LinkedList<String>();

    private ServiceDomain _serviceDomain;

    protected BaseActivator(String... types) {
        if (types != null) {
            _activationTypes.addAll(Arrays.asList(types));
        }
    }

    @Override
    public ServiceHandler activateBinding(QName name, BindingModel config) {
        throw BaseDeployMessages.MESSAGES.activateBindingNotSupported(getClreplaced().getName());
    }

    @Override
    public ServiceHandler activateService(QName name, ComponentModel config) {
        throw BaseDeployMessages.MESSAGES.activateServiceNotSupported(getClreplaced().getName());
    }

    @Override
    public void deactivateBinding(QName name, ServiceHandler handler) {
        throw BaseDeployMessages.MESSAGES.deactivateBindingNotSupported(getClreplaced().getName());
    }

    @Override
    public void deactivateService(QName name, ServiceHandler handler) {
        throw BaseDeployMessages.MESSAGES.deactivateServiceNotSupported(getClreplaced().getName());
    }

    /**
     * Sets the service domain instance of this activator.
     * @param serviceDomain the service domain
     */
    public void setServiceDomain(ServiceDomain serviceDomain) {
        _serviceDomain = serviceDomain;
    }

    /**
     * Gets the service domain instance of this activator.
     * @return the service domain
     */
    public ServiceDomain getServiceDomain() {
        return _serviceDomain;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public boolean canActivate(String type) {
        return _activationTypes.contains(type);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Collection<String> getActivationTypes() {
        return Collections.unmodifiableList(_activationTypes);
    }

    @Override
    public void destroy() {
    // NOP so that Activator impls don't have to bother with this method
    // if they don't have anything to do in destroy().
    }
}

18 View Complete Implementation : BPMServiceTests.java
Copyright Apache License 2.0
Author : jboss-switchyard
/**
 * Tests the BPM implementation.
 *
 * @author David Ward <<a href="mailto:[email protected]">[email protected]</a>> © 2012 Red Hat Inc.
 */
@RunWith(SwitchYardRunner.clreplaced)
public clreplaced BPMServiceTests {

    private static final String ACCESS_ATTACHMENT_BPMN = "org/switchyard/component/bpm/service/BPMServiceTests-AccessAttachment.bpmn";

    private static final String CALL_SERVICE_BPMN = "org/switchyard/component/bpm/service/BPMServiceTests-CallService.bpmn";

    private static final String CONTROL_PROCESS_BPMN = "org/switchyard/component/bpm/service/BPMServiceTests-ControlProcess.bpmn";

    private static final String FAULT_RESULT_PROCESS_BPMN = "org/switchyard/component/bpm/service/BPMServiceTests-FaultResultProcess.bpmn";

    private static final String FAULT_EVENT_PROCESS_BPMN = "org/switchyard/component/bpm/service/BPMServiceTests-FaultEventProcess.bpmn";

    private static final String FAULT_BOUNDARY_PROCESS_BPMN = "org/switchyard/component/bpm/service/BPMServiceTests-FaultBoundaryProcess.bpmn";

    private static final String REUSE_HANDLER_BPMN = "org/switchyard/component/bpm/service/BPMServiceTests-ReuseHandler.bpmn";

    private static final String RULES_FIRED_BPMN = "org/switchyard/component/bpm/service/BPMServiceTests-RulesFired.bpmn";

    private static final String RULES_FIRED_DRL = "org/switchyard/component/bpm/service/BPMServiceTests-RulesFired.drl";

    private static final String SIGNAL_PROCESS_BPMN = "org/switchyard/component/bpm/service/BPMServiceTests-SignalProcess.bpmn";

    private ServiceDomain serviceDomain;

    @Test
    public void testCallService() throws Exception {
        final Holder holder = new Holder();
        serviceDomain.registerService(new QName("CallService"), new InOnlyService(), new BaseHandler() {

            public void handleMessage(Exchange exchange) throws HandlerException {
                holder.setValue("message handled");
            }
        });
        serviceDomain.registerServiceReference(new QName("CallService"), new InOnlyService());
        KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
        kbuilder.add(ResourceFactory.newClreplacedPathResource(CALL_SERVICE_BPMN), ResourceType.BPMN2);
        KieBase kbase = kbuilder.newKnowledgeBase();
        KieSession ksession = kbase.newKieSession();
        SwitchYardServiceTaskHandler ssth = new SwitchYardServiceTaskHandler();
        ssth.setProcessRuntime(ksession);
        ssth.setInvoker(new SwitchYardServiceInvoker(serviceDomain));
        ksession.getWorkItemManager().registerWorkItemHandler(SWITCHYARD_SERVICE_TASK, ssth);
        ksession.startProcess("CallService");
        ksession.halt();
        ksession.dispose();
        replacedert.replacedertEquals("message handled", holder.getValue());
    }

    @BPM(processId = "AccessAttachment", manifest = @Manifest(resources = @Resource(location = ACCESS_ATTACHMENT_BPMN, type = "BPMN2")))
    public interface AccessAttachment {

        @StartProcess(inputs = { @Input(from = "message.attachmentMap['someAttach']", to = "attachment"), @Input(from = "message.content", to = "holder") })
        public Object process(Object content);
    }

    @Test
    public void testAccessAttachment() throws Exception {
        final Holder holder = new Holder();
        BPMComponentImplementationModel bci_model = (BPMComponentImplementationModel) new BPMSwitchYardScanner().scan(AccessAttachment.clreplaced).getImplementation();
        QName serviceName = new QName("AccessAttachment");
        BPMExchangeHandler handler = new BPMExchangeHandler(bci_model, serviceDomain, serviceName);
        Service service = serviceDomain.registerService(serviceName, JavaService.fromClreplaced(AccessAttachment.clreplaced), handler);
        serviceDomain.registerServiceReference(service.getName(), service.getInterface(), service.getProviderHandler());
        handler.start();
        DataSource attachment = new TestDataSource("someAttach", "text/plain", "someAttachData");
        new Invoker(serviceDomain, serviceName).operation("process").attachment(attachment.getName(), attachment).sendInOnly(holder);
        handler.stop();
        replacedert.replacedertEquals("someAttachData", holder.getValue());
    }

    @BPM(processId = "ControlProcess", manifest = @Manifest(resources = @Resource(location = CONTROL_PROCESS_BPMN, type = "BPMN2")))
    public interface ControlProcess {

        @StartProcess
        public Object process(Object content);

        @SignalEvent(eventId = "test")
        public void signal(Object content);
    }

    @Test
    public void testControlProcess() throws Exception {
        final Holder holder = new Holder();
        Service callService = serviceDomain.registerService(new QName("CallService"), new InOnlyService(), new BaseHandler() {

            public void handleMessage(Exchange exchange) throws HandlerException {
                holder.setValue("message handled");
            }
        });
        serviceDomain.registerServiceReference(callService.getName(), callService.getInterface(), callService.getProviderHandler());
        BPMComponentImplementationModel bci_model = (BPMComponentImplementationModel) new BPMSwitchYardScanner().scan(ControlProcess.clreplaced).getImplementation();
        // setting the component name to null so that the service reference doesn't use the component-qualified name
        bci_model.getComponent().setName(null);
        QName serviceName = new QName("ControlProcess");
        BPMExchangeHandler handler = new BPMExchangeHandler(bci_model, serviceDomain, serviceName);
        Service controlService = serviceDomain.registerService(serviceName, JavaService.fromClreplaced(ControlProcess.clreplaced), handler);
        serviceDomain.registerServiceReference(controlService.getName(), controlService.getInterface(), controlService.getProviderHandler());
        handler.start();
        Invoker processInvoker = new Invoker(serviceDomain, serviceName);
        Message processResponse = processInvoker.operation("process").sendInOut(null);
        Long processInstanceId = (Long) processResponse.getContext().getPropertyValue(PROCESSS_INSTANCE_ID_PROPERTY);
        Invoker signalInvoker = new Invoker(serviceDomain, serviceName);
        signalInvoker.operation("signal").property(PROCESSS_INSTANCE_ID_PROPERTY, processInstanceId).sendInOut(null);
        handler.stop();
        replacedert.replacedertEquals("message handled", holder.getValue());
    }

    @Test
    public void testCorrelateProcessSuccess() throws Exception {
        runCorrelateProcess(false);
    }

    @Test
    public void testCorrelateProcessFailure() throws Exception {
        runCorrelateProcess(true);
    }

    private void runCorrelateProcess(final boolean bomb) throws Exception {
        final AtomicInteger counter = new AtomicInteger();
        final Holder holder = new Holder();
        Service callService = serviceDomain.registerService(new QName("CallService"), new InOnlyService(), new BaseHandler() {

            public void handleMessage(Exchange exchange) throws HandlerException {
                int count = counter.incrementAndGet();
                holder.setValue(String.valueOf(count));
            }
        });
        serviceDomain.registerServiceReference(callService.getName(), callService.getInterface(), callService.getProviderHandler());
        BPMComponentImplementationModel bci_model = (BPMComponentImplementationModel) new BPMSwitchYardScanner().scan(ControlProcess.clreplaced).getImplementation();
        // setting the component name to null so that the service reference doesn't use the component-qualified name
        bci_model.getComponent().setName(null);
        QName serviceName = new QName("ControlProcess");
        BPMExchangeHandler handler = new BPMExchangeHandler(bci_model, serviceDomain, serviceName);
        Service controlService = serviceDomain.registerService(serviceName, JavaService.fromClreplaced(ControlProcess.clreplaced), handler);
        serviceDomain.registerServiceReference(controlService.getName(), controlService.getInterface(), controlService.getProviderHandler());
        handler.start();
        new Invoker(serviceDomain, serviceName).operation("process").property(CORRELATION_KEY_PROPERTY, "A").sendInOnly(null);
        new Invoker(serviceDomain, serviceName).operation("process").property(CORRELATION_KEY_PROPERTY, "B").sendInOnly(null);
        new Invoker(serviceDomain, serviceName).operation("signal").property(CORRELATION_KEY_PROPERTY, "A").sendInOnly(null);
        InvocationFaultException fault = null;
        try {
            new Invoker(serviceDomain, serviceName).operation("signal").property(CORRELATION_KEY_PROPERTY, bomb ? "A" : "B").sendInOut(null);
        } catch (InvocationFaultException ife) {
            fault = ife;
        }
        handler.stop();
        if (bomb) {
            replacedert.replacedertNotNull(fault);
            replacedert.replacedertEquals("1", holder.getValue());
        } else {
            replacedert.replacedertNull(fault);
            replacedert.replacedertEquals("2", holder.getValue());
        }
    }

    @BPM(processId = "ControlProcess", manifest = @Manifest(resources = @Resource(location = CONTROL_PROCESS_BPMN, type = "BPMN2")))
    public interface SignalAllProcesses {

        @StartProcess
        public Object process(Object content);

        @SignalEventAll(eventId = "test")
        public void signal(Object content);
    }

    @Test
    public void testSignalAllProcesses() throws Exception {
        final AtomicInteger counter = new AtomicInteger();
        final Holder holder = new Holder();
        Service callService = serviceDomain.registerService(new QName("CallService"), new InOnlyService(), new BaseHandler() {

            public void handleMessage(Exchange exchange) throws HandlerException {
                int count = counter.incrementAndGet();
                holder.setValue(String.valueOf(count));
            }
        });
        serviceDomain.registerServiceReference(callService.getName(), callService.getInterface(), callService.getProviderHandler());
        BPMComponentImplementationModel bci_model = (BPMComponentImplementationModel) new BPMSwitchYardScanner().scan(SignalAllProcesses.clreplaced).getImplementation();
        // setting the component name to null so that the service reference doesn't use the component-qualified name
        bci_model.getComponent().setName(null);
        QName serviceName = new QName("ControlProcess");
        BPMExchangeHandler handler = new BPMExchangeHandler(bci_model, serviceDomain, serviceName);
        Service controlService = serviceDomain.registerService(serviceName, JavaService.fromClreplaced(SignalAllProcesses.clreplaced), handler);
        serviceDomain.registerServiceReference(controlService.getName(), controlService.getInterface(), controlService.getProviderHandler());
        handler.start();
        new Invoker(serviceDomain, serviceName).operation("process").sendInOnly(null);
        new Invoker(serviceDomain, serviceName).operation("process").sendInOnly(null);
        new Invoker(serviceDomain, serviceName).operation("signal").sendInOnly(null);
        handler.stop();
        replacedert.replacedertEquals("2", holder.getValue());
    }

    @Test
    public void testFaultResultProcessSuccess() throws Exception {
        runFaultResultProcess(false);
    }

    @Test
    public void testFaultResultProcessFailure() throws Exception {
        runFaultResultProcess(true);
    }

    private void runFaultResultProcess(final boolean bomb) throws Exception {
        serviceDomain.registerService(new QName("TestService"), new InOnlyService(), new BaseHandler() {

            public void handleMessage(Exchange exchange) throws HandlerException {
                if (bomb) {
                    throw new HandlerException("BOOM!");
                }
            }
        });
        serviceDomain.registerServiceReference(new QName("TestService"), new InOutService());
        KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
        kbuilder.add(ResourceFactory.newClreplacedPathResource(FAULT_RESULT_PROCESS_BPMN), ResourceType.BPMN2);
        KieBase kbase = kbuilder.newKnowledgeBase();
        KieSession ksession = kbase.newKieSession();
        SwitchYardServiceTaskHandler ssth = new SwitchYardServiceTaskHandler();
        ssth.setProcessRuntime(ksession);
        ssth.setInvoker(new SwitchYardServiceInvoker(serviceDomain));
        ksession.getWorkItemManager().registerWorkItemHandler(SWITCHYARD_SERVICE_TASK, ssth);
        WorkflowProcessInstance wpi = (WorkflowProcessInstance) ksession.startProcess("FaultResultProcess");
        HandlerException he = (HandlerException) wpi.getVariable("faultResult");
        if (bomb) {
            replacedert.replacedertNotNull(he);
            replacedert.replacedertEquals("BOOM!", he.getMessage());
        } else {
            replacedert.replacedertNull(he);
        }
        ksession.halt();
        ksession.dispose();
    }

    @Test
    public void testFaultEventProcessSuccess() throws Exception {
        runFaultEventProcess(false);
    }

    @Test
    public void testFaultEventProcessFailure() throws Exception {
        runFaultEventProcess(true);
    }

    private void runFaultEventProcess(final boolean bomb) throws Exception {
        serviceDomain.registerService(new QName("TestService"), new InOnlyService(), new BaseHandler() {

            public void handleMessage(Exchange exchange) throws HandlerException {
                if (bomb) {
                    throw new HandlerException("BOOM!");
                }
            }
        });
        serviceDomain.registerServiceReference(new QName("TestService"), new InOutService());
        KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
        kbuilder.add(ResourceFactory.newClreplacedPathResource(FAULT_EVENT_PROCESS_BPMN), ResourceType.BPMN2);
        KieBase kbase = kbuilder.newKnowledgeBase();
        KieSession ksession = kbase.newKieSession();
        SwitchYardServiceTaskHandler ssth = new SwitchYardServiceTaskHandler();
        ssth.setProcessRuntime(ksession);
        ssth.setInvoker(new SwitchYardServiceInvoker(serviceDomain));
        ksession.getWorkItemManager().registerWorkItemHandler(SWITCHYARD_SERVICE_TASK, ssth);
        WorkflowProcessInstance wpi = (WorkflowProcessInstance) ksession.startProcess("FaultEventProcess");
        HandlerException he = (HandlerException) wpi.getVariable("faultEvent");
        if (bomb) {
            replacedert.replacedertNotNull(he);
            replacedert.replacedertEquals("BOOM!", he.getMessage());
        } else {
            replacedert.replacedertNull(he);
        }
        ksession.halt();
        ksession.dispose();
    }

    @Test
    public void testFaultBoundaryProcessSuccess() throws Exception {
        runFaultBoundaryProcess(false);
    }

    @Test
    public void testFaultBoundaryProcessFailure() throws Exception {
        runFaultBoundaryProcess(true);
    }

    private void runFaultBoundaryProcess(final boolean bomb) throws Exception {
        serviceDomain.registerService(new QName("TestService"), new InOnlyService(), new BaseHandler() {

            public void handleMessage(Exchange exchange) throws HandlerException {
                if (bomb) {
                    throw new HandlerException("BOOM!");
                }
            }
        });
        serviceDomain.registerServiceReference(new QName("TestService"), new InOutService());
        KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
        kbuilder.add(ResourceFactory.newClreplacedPathResource(FAULT_BOUNDARY_PROCESS_BPMN), ResourceType.BPMN2);
        KieBase kbase = kbuilder.newKnowledgeBase();
        KieSession ksession = kbase.newKieSession();
        SwitchYardServiceTaskHandler ssth = new SwitchYardServiceTaskHandler();
        ssth.setProcessRuntime(ksession);
        ssth.setInvoker(new SwitchYardServiceInvoker(serviceDomain));
        ksession.getWorkItemManager().registerWorkItemHandler(SWITCHYARD_SERVICE_TASK, ssth);
        WorkflowProcessInstance wpi = (WorkflowProcessInstance) ksession.startProcess("FaultBoundaryProcess");
        String output = (String) wpi.getVariable("TestOutput");
        replacedert.replacedertEquals(bomb ? "Failure" : "Success", output);
        ksession.halt();
        ksession.dispose();
    }

    @BPM(processId = "ReuseHandler", manifest = @Manifest(resources = @Resource(location = REUSE_HANDLER_BPMN, type = "BPMN2")), workItemHandlers = @WorkItemHandler(name = "ReuseHandler", value = ReuseHandler.clreplaced))
    public interface ReuseHandlerProcess {

        @StartProcess(inputs = @Input(from = "message.content", to = "holder"))
        public void process(Object content);
    }

    @Test
    public void testReuseHandler() throws Exception {
        BPMComponentImplementationModel bci_model = (BPMComponentImplementationModel) new BPMSwitchYardScanner().scan(ReuseHandlerProcess.clreplaced).getImplementation();
        QName serviceName = new QName("ReuseHandler");
        BPMExchangeHandler handler = new BPMExchangeHandler(bci_model, serviceDomain, serviceName);
        Service service = serviceDomain.registerService(serviceName, new InOnlyService("process"), handler);
        serviceDomain.registerServiceReference(service.getName(), service.getInterface(), service.getProviderHandler());
        handler.start();
        new Invoker(serviceDomain, serviceName).operation("process").sendInOnly(null);
        handler.stop();
        replacedert.replacedertEquals("handler executed", ReuseHandler._holder.getValue());
        ReuseHandler._holder.setValue(null);
    }

    @BPM(processId = "RulesFired", manifest = @Manifest(resources = { @Resource(location = RULES_FIRED_BPMN, type = "BPMN2"), @Resource(location = RULES_FIRED_DRL, type = "DRL") }))
    public interface RulesFiredProcess {

        @StartProcess(inputs = @Input(from = "message.content", to = "holder"))
        public void process(Object content);
    }

    @Test
    public void testRulesFired() throws Exception {
        final Holder holder = new Holder();
        BPMComponentImplementationModel bci_model = (BPMComponentImplementationModel) new BPMSwitchYardScanner().scan(RulesFiredProcess.clreplaced).getImplementation();
        QName serviceName = new QName("RulesFired");
        BPMExchangeHandler handler = new BPMExchangeHandler(bci_model, serviceDomain, serviceName);
        Service service = serviceDomain.registerService(serviceName, new InOnlyService("process"), handler);
        serviceDomain.registerServiceReference(service.getName(), service.getInterface(), service.getProviderHandler());
        handler.start();
        new Invoker(serviceDomain, serviceName).operation("process").sendInOnly(holder);
        handler.stop();
        replacedert.replacedertEquals("rules fired", holder.getValue());
    }

    @BPM(processId = "SignalProcess", manifest = @Manifest(resources = @Resource(location = SIGNAL_PROCESS_BPMN, type = "BPMN2")))
    public interface SignalProcess {

        @StartProcess(inputs = { @Input(from = "message.content", to = "Parameter") }, outputs = { @Output(from = "Result", to = "message.content") })
        public Object process(Object content);

        @SignalEvent(eventId = "TestSignal1", inputs = { @Input(from = "message.content", to = "Parameter") }, outputs = { @Output(from = "Result", to = "message.content") })
        public Object signal(Object content);
    }

    @Test
    public void testSignalProcess() throws Exception {
        final Map<String, String> testreplacedertionMap = new HashMap<String, String>();
        Service serviceOne = serviceDomain.registerService(new QName("ServiceOne"), new InOutService(), new BaseHandler() {

            public void handleMessage(Exchange exchange) throws HandlerException {
                Holder h = exchange.getMessage().getContent(Holder.clreplaced);
                testreplacedertionMap.put("ServiceOne", h.getValue());
            }
        });
        Service serviceTwo = serviceDomain.registerService(new QName("ServiceTwo"), new InOutService(), new BaseHandler() {

            public void handleMessage(Exchange exchange) throws HandlerException {
                Holder h = exchange.getMessage().getContent(Holder.clreplaced);
                testreplacedertionMap.put("ServiceTwo", h.getValue());
            }
        });
        serviceDomain.registerServiceReference(serviceOne.getName(), serviceOne.getInterface(), serviceOne.getProviderHandler());
        serviceDomain.registerServiceReference(serviceTwo.getName(), serviceTwo.getInterface(), serviceTwo.getProviderHandler());
        BPMComponentImplementationModel bci_model = (BPMComponentImplementationModel) new BPMSwitchYardScanner().scan(SignalProcess.clreplaced).getImplementation();
        // setting the component name to null so that the service reference doesn't use the component-qualified name
        bci_model.getComponent().setName(null);
        QName serviceName = new QName("SignalProcess");
        BPMExchangeHandler handler = new BPMExchangeHandler(bci_model, serviceDomain, serviceName);
        Service signalService = serviceDomain.registerService(serviceName, JavaService.fromClreplaced(SignalProcess.clreplaced), handler);
        serviceDomain.registerServiceReference(signalService.getName(), signalService.getInterface(), signalService.getProviderHandler());
        handler.start();
        Invoker processInvoker = new Invoker(serviceDomain, serviceName);
        Holder holderOne = new Holder();
        holderOne.setValue("HolderOne");
        Message processResponse = processInvoker.operation("process").sendInOut(holderOne);
        Long processInstanceId = (Long) processResponse.getContext().getPropertyValue(PROCESSS_INSTANCE_ID_PROPERTY);
        Invoker signalInvoker = new Invoker(serviceDomain, serviceName);
        Holder holderTwo = new Holder();
        holderTwo.setValue("HolderTwo");
        Message signalResponse = signalInvoker.operation("signal").property(PROCESSS_INSTANCE_ID_PROPERTY, processInstanceId).sendInOut(holderTwo);
        Holder holderResponse = signalResponse.getContent(Holder.clreplaced);
        handler.stop();
        replacedert.replacedertEquals(holderOne.getValue(), testreplacedertionMap.get("ServiceOne"));
        replacedert.replacedertEquals(holderTwo.getValue(), testreplacedertionMap.get("ServiceTwo"));
        replacedert.replacedertEquals(holderTwo.getValue(), holderResponse.getValue());
    }

    public static final clreplaced Holder {

        private String _value;

        public String getValue() {
            return _value;
        }

        public void setValue(String value) {
            _value = value;
        }

        public String toString() {
            return _value;
        }
    }
}

18 View Complete Implementation : MockComponent.java
Copyright Apache License 2.0
Author : jboss-switchyard
@Override
public Activator createActivator(ServiceDomain domain) {
    return new MockActivator();
}

17 View Complete Implementation : ReferenceTest.java
Copyright Apache License 2.0
Author : jboss-switchyard
@RunWith(SwitchYardRunner.clreplaced)
@SwitchYardTestCaseConfig(mixins = CDIMixIn.clreplaced)
public clreplaced ReferenceTest {

    private ServiceDomain domain;

    @Test
    public void verifyReferenceIsRegistered() {
        replacedert.replacedertNotNull(domain.getServiceReference(new QName("ConsumerService")));
    }
}

17 View Complete Implementation : BPELComponent.java
Copyright Apache License 2.0
Author : jboss-switchyard
protected BPELEngine getEngine(final ServiceDomain domain) {
    synchronized (BPELComponent.clreplaced) {
        if (_engine == null) {
            initConfig();
            try {
                _engine = _bpelEngineInstance.getBPELEngine();
            } catch (Exception e) {
                throw BPELMessages.MESSAGES.failedToInitializeTheEngine(e);
            }
            _engine.register(new BPELEngineListener() {

                public void onEvent(BpelEvent bpelEvent) {
                    domain.getEventPublisher().publish(bpelEvent);
                }
            });
        }
    }
    return _engine;
}

17 View Complete Implementation : BPELComponent.java
Copyright Apache License 2.0
Author : jboss-switchyard
/* (non-Javadoc)
     * @see org.switchyard.deploy.Component#createActivator(org.switchyard.ServiceDomain)
     */
@Override
public Activator createActivator(ServiceDomain domain) {
    if (domain == null) {
        throw new NullPointerException("domain cannot be null");
    }
    BPELEngine engine = getEngine(domain);
    BPELActivator activator = new BPELActivator(engine, (RiftsawServiceLocator) engine.getServiceLocator(), _config);
    activator.setServiceDomain(domain);
    return activator;
}

17 View Complete Implementation : RiftsawServiceLocator.java
Copyright Apache License 2.0
Author : jboss-switchyard
/**
 * Add a service -> service domain mapping.
 * @param serviceName service name
 * @param serviceDomain The service domain
 */
public void addServiceDomain(QName serviceName, ServiceDomain serviceDomain) {
    _serviceDomains.put(serviceName, serviceDomain);
}

17 View Complete Implementation : StandaloneEndpointPublisher.java
Copyright Apache License 2.0
Author : jboss-switchyard
/**
 * {@inheritDoc}
 */
public Endpoint publish(ServiceDomain domain, String context, InboundHandler handler) throws Exception {
    HttpContext httpContext = null;
    if (!context.startsWith("/")) {
        context = "/" + context;
    }
    if (_httpServer != null) {
        httpContext = _httpServer.createContext(context, new StandaloneHandler(handler));
    }
    return new StandaloneEndpoint(httpContext);
}

17 View Complete Implementation : AbstractInflowEndpoint.java
Copyright Apache License 2.0
Author : jboss-switchyard
/**
 * Abstract message endpoint clreplaced for JCA inflow.
 *
 * @author <a href="mailto:[email protected]">Tomohisa Igarashi</a>
 */
public abstract clreplaced AbstractInflowEndpoint {

    private JCABindingModel _jcaBindingModel;

    private ServiceDomain _domain;

    private QName _serviceQName;

    private ServiceReference _serviceRef;

    private boolean _transacted = false;

    private ClreplacedLoader _appClreplacedLoader;

    private String _gatewayName;

    /**
     * initialize.
     */
    public void initialize() {
        _serviceRef = _domain.getServiceReference(_serviceQName);
    }

    /**
     * uninitialize.
     */
    public void uninitialize() {
    }

    /**
     * set {@link JCABindingModel}.
     *
     * @param model {@link JCABindingModel}
     * @return {@link AbstractInflowEndpoint} to support method chaining
     */
    public AbstractInflowEndpoint setJCABindingModel(JCABindingModel model) {
        _jcaBindingModel = model;
        _gatewayName = model.getName();
        return this;
    }

    /**
     * get {@link JCABindingModel}.
     *
     * @return {@link JCABindingModel}
     */
    public JCABindingModel getJCABindingModel() {
        return _jcaBindingModel;
    }

    /**
     * set ServiceDomain.
     * @param domain ServiceDomain
     * @return this instance
     */
    public AbstractInflowEndpoint setServiceDomain(ServiceDomain domain) {
        _domain = domain;
        return this;
    }

    /**
     * get ServiceDomain.
     * @return ServiceDomain
     */
    public ServiceDomain getServiceDomain() {
        return _domain;
    }

    /**
     * set service QName.
     * @param qname service QName
     * @return this instance
     */
    public AbstractInflowEndpoint setServiceQName(QName qname) {
        _serviceQName = qname;
        return this;
    }

    /**
     * get Service QName.
     * @return Service QName
     */
    public QName getServiceQName() {
        return _serviceQName;
    }

    /**
     * set service reference.
     * @param ref service reference
     * @return this instance
     */
    public AbstractInflowEndpoint setServiceReference(ServiceReference ref) {
        _serviceRef = ref;
        return this;
    }

    /**
     * get ServiceReference.
     * @return ServiceReference
     */
    public ServiceReference getServiceReference() {
        return _serviceRef;
    }

    /**
     * return whether the delivery is transacted or not.
     *
     * @return true if transacted
     */
    public boolean isDeliveryTransacted() {
        return _transacted;
    }

    /**
     * set whether the delivery is transacted or not.
     *
     * @param transacted true if transacted
     * @return this instance
     */
    public AbstractInflowEndpoint setDeliveryTransacted(boolean transacted) {
        _transacted = transacted;
        return this;
    }

    /**
     * set application clreplaced loader.
     *
     * @param loader application clreplaced loader
     * @return this instance
     */
    public AbstractInflowEndpoint setApplicationClreplacedLoader(ClreplacedLoader loader) {
        _appClreplacedLoader = loader;
        return this;
    }

    /**
     * get application clreplaced loader.
     *
     * @return application clreplaced loader
     */
    public ClreplacedLoader getApplicationClreplacedLoader() {
        return _appClreplacedLoader;
    }

    protected Exchange createExchange(String operation, ExchangeHandler handler) {
        if (_serviceRef == null) {
            throw JCAMessages.MESSAGES.initializeMustBeCalledBeforeExchange();
        }
        if (operation == null) {
            final Set<ServiceOperation> operations = _serviceRef.getInterface().getOperations();
            if (operations.size() != 1) {
                throw JCAMessages.MESSAGES.noOperationSelectorConfigured(operations.toString());
            }
            final ServiceOperation serviceOperation = operations.iterator().next();
            operation = serviceOperation.getName();
        }
        Exchange exchange = _serviceRef.createExchange(operation, handler);
        if (_transacted) {
            PolicyUtil.provide(exchange, TransactionPolicy.PROPAGATES_TRANSACTION);
            PolicyUtil.provide(exchange, TransactionPolicy.MANAGED_TRANSACTION_GLOBAL);
        }
        // identify ourselves
        exchange.getContext().setProperty(ExchangeCompletionEvent.GATEWAY_NAME, _gatewayName, Scope.EXCHANGE).addLabels(BehaviorLabel.TRANSIENT.label());
        return exchange;
    }

    protected Exchange createExchange(String operation) {
        return createExchange(operation, null);
    }

    protected <D extends JCABindingData> MessageComposer<D> getMessageComposer(Clreplaced<D> clazz) {
        return JCAComposition.getMessageComposer(_jcaBindingModel, clazz);
    }

    protected <D extends JCABindingData> OperationSelector<D> getOperationSelector(Clreplaced<D> clazz) {
        return OperationSelectorFactory.getOperationSelectorFactory(clazz).newOperationSelector(_jcaBindingModel.getOperationSelector());
    }
}

17 View Complete Implementation : SCAComponent.java
Copyright Apache License 2.0
Author : jboss-switchyard
@Override
public Activator createActivator(ServiceDomain domain) {
    if (_cache == null) {
        lookupCache(_cacheName);
        if (_cache == null) {
            SCALogger.ROOT_LOGGER.unableToResolveCacheContainer(_cacheName);
        }
    }
    SCAActivator activator = new SCAActivator(_cache);
    activator.setServiceDomain(domain);
    activator.setEndpointPublisher(_endpointPublisher);
    activator.setDisableRemoteTransaction(_disableRemoteTransaction);
    return activator;
}

17 View Complete Implementation : NOPEndpointPublisher.java
Copyright Apache License 2.0
Author : jboss-switchyard
@Override
public void addService(QName serviceName, ServiceDomain domain) {
// TODO Auto-generated method stub
}

17 View Complete Implementation : NOPEndpointPublisher.java
Copyright Apache License 2.0
Author : jboss-switchyard
@Override
public void removeService(QName serviceName, ServiceDomain domain) {
// TODO Auto-generated method stub
}

17 View Complete Implementation : ExchangeDispatcherTest.java
Copyright Apache License 2.0
Author : jboss-switchyard
private void initDomain(ServiceDomain domain) throws Exception {
    _camelContext = new SwitchYardCamelContextImpl();
    _camelContext.setServiceDomain(domain);
    _provider = new CamelExchangeBus(_camelContext);
    _provider.init(domain);
    _camelContext.start();
}

17 View Complete Implementation : CamelContextConfigurator.java
Copyright Apache License 2.0
Author : jboss-switchyard
/**
 * Configure CamelContext based on a ServiceDomain instance.
 * @param context CamelContext to configure
 * @param domain domain used to configure CamelContext
 */
public static final void configure(CamelContext context, ServiceDomain domain) {
    configure(context, domain.getProperties());
}

17 View Complete Implementation : SwitchYardCamelContextImpl.java
Copyright Apache License 2.0
Author : jboss-switchyard
/**
 * Extension of default camel context. Supports access to mutable registry and
 * provides integration with SwitchYard eventing model.
 */
public clreplaced SwitchYardCamelContextImpl extends DefaultCamelContext implements SwitchYardCamelContext {

    private final SimpleRegistry _writeableRegistry = new SimpleRegistry();

    private ServiceDomain _domain;

    private AtomicInteger _count = new AtomicInteger();

    private static final int DEFAULT_TIMEOUT = 30;

    /**
     * Flag to turn on/off cdi integration.
     */
    private boolean _cdiIntegration;

    /**
     * Creates new camel context.
     */
    public SwitchYardCamelContextImpl() {
        this(true);
    }

    /**
     * Creates new camel context.
     * @param autoDetectCdi Should cdi integration be auto detected and enabled.
     */
    public SwitchYardCamelContextImpl(boolean autoDetectCdi) {
        _cdiIntegration = autoDetectCdi;
        if (isEnableCdiIntegration()) {
            CDISupport.setCdiInjector(this);
        } else {
            CommonCamelLogger.ROOT_LOGGER.cdiNotDetected();
        }
        getManagementStrategy().addEventNotifier(new CamelEventBridge());
    }

    /**
     * replacedociates camel context with given service domain.
     *
     * @param domain Domain to replacedociate.
     */
    public void setServiceDomain(ServiceDomain domain) {
        _domain = domain;
        for (EventNotifier notifier : getManagementStrategy().getEventNotifiers()) {
            if (notifier instanceof CamelEventBridge) {
                ((CamelEventBridge) notifier).setEventPublisher(domain.getEventPublisher());
            }
        }
        PackageScanClreplacedResolver packageScanClreplacedResolver = findPackageScanClreplacedResolver();
        if (packageScanClreplacedResolver != null) {
            setPackageScanClreplacedResolver(packageScanClreplacedResolver);
        }
        _domain.setProperty(CAMEL_CONTEXT_PROPERTY, this);
    }

    /**
     * Gets mutable registry replacedociated with context. Allows to dynamically register
     * bean instances.
     *
     * @return Registry which allows to put new objects.
     */
    public SimpleRegistry getWritebleRegistry() {
        return _writeableRegistry;
    }

    /**
     * Get the first PackageScanClreplacedResolver Service found on the clreplacedpath.
     *
     * @return The first PackageScanClreplacedResolver Service found on the clreplacedpath.
     */
    public PackageScanClreplacedResolver findPackageScanClreplacedResolver() {
        final ServiceLoader<PackageScanClreplacedResolver> resolverLoaders = ServiceLoader.load(PackageScanClreplacedResolver.clreplaced);
        for (PackageScanClreplacedResolver packageScanClreplacedResolver : resolverLoaders) {
            return packageScanClreplacedResolver;
        }
        return null;
    }

    protected CompositeRegistry createRegistry() {
        final ServiceLoader<Registry> registriesLoaders = ServiceLoader.load(Registry.clreplaced, getClreplaced().getClreplacedLoader());
        final List<Registry> registries = new ArrayList<Registry>();
        registries.add(new JndiRegistry());
        if (isEnableCdiIntegration()) {
            registries.add(new CdiBeanRegistry());
        }
        registries.add(_writeableRegistry);
        for (Registry registry : registriesLoaders) {
            registries.add(registry);
        }
        return new CompositeRegistry(registries);
    }

    /**
     * Gets SwitchYard domain replacedociated with this context.
     *
     * @return SwitchYard domain.
     */
    public ServiceDomain getServiceDomain() {
        return _domain;
    }

    /**
     * Checks if CDI runtime is enabled for this deployment.
     *
     * @return True if CDI runtime is detected.
     */
    public boolean isEnableCdiIntegration() {
        if (!_cdiIntegration) {
            return false;
        }
        return CDISupport.isCDIEnabled();
    }

    /**
     * Start camel context and/or increment counter with number of start attempts.
     *
     * @throws Exception is thrown if starting failed
     */
    @Override
    public void start() throws Exception {
        if (_count.incrementAndGet() == 1) {
            applyConfiguration();
            super.start();
        }
    }

    /**
     * Decrement counter with number of start attempts and/or stop camel context.
     *
     * @throws Exception is thrown if stopping failed
     */
    @Override
    public void stop() throws Exception {
        if (_count.decrementAndGet() == 0) {
            super.stop();
        }
    }

    // Applies domain configuration to this camel context
    private void applyConfiguration() {
        if (_domain == null || _domain.getProperties() == null) {
            // no config to apply
            return;
        }
        // set shutdown timeout default - this can still be overriden by domain props
        getShutdownStrategy().setTimeout(DEFAULT_TIMEOUT);
        // configure context with domain properties
        CamelContextConfigurator.configure(this, _domain);
    }

    static clreplaced CDISupport {

        static boolean isCDIEnabled() {
            try {
                return CDIUtil.lookupBeanManager() != null;
            } catch (NoClreplacedDefFoundError e) {
                return false;
            }
        }

        static void addCdiRegistry(List<Registry> registries) {
            registries.add(new CdiBeanRegistry());
        }

        public static void setCdiInjector(SwitchYardCamelContextImpl context) {
            context.setInjector(new CdiInjector(context.getInjector()));
        }
    }
}

17 View Complete Implementation : ActivatorLoader.java
Copyright Apache License 2.0
Author : jboss-switchyard
/**
 * Creates a List of component Activators using the List of already discovered components.
 *
 * @param serviceDomain The service domain to be used by the activator.
 * @param components The components from which the activators are created.
 * @param types List of types to be activated
 * @return A List of activators.
 */
public static List<Activator> createActivators(ServiceDomain serviceDomain, List<Component> components, List<String> types) {
    List<Activator> activators = new ArrayList<Activator>();
    for (Component component : components) {
        if (canActivate(component, types)) {
            Activator activator = component.createActivator(serviceDomain);
            _log.debug("Registered activator " + activator.getClreplaced());
            activators.add(activator);
        }
    }
    return activators;
}

16 View Complete Implementation : CamelJMSTest.java
Copyright Apache License 2.0
Author : jboss-switchyard
/**
 * Test using Camel's JMS Component in SwitchYard.
 *
 * @author Daniel Bevenius
 */
@SwitchYardTestCaseConfig(config = "switchyard-jms-test.xml", mixins = { CDIMixIn.clreplaced, HornetQMixIn.clreplaced })
@RunWith(SwitchYardRunner.clreplaced)
public clreplaced CamelJMSTest {

    private ServiceDomain _domain;

    private SwitchYardTestKit _testKit;

    @Test
    public void sendOneWayTextMessageToJMSQueue() throws Exception {
        sendAndreplacedertOneMessage();
    }

    @Test
    public void stopAndStartCamelActivator() throws Exception {
        sendAndreplacedertOneMessage();
        stopCamelActivator();
        Thread.sleep(2000);
        startCamelActivator();
        sendAndreplacedertOneMessage();
    }

    private void stopCamelActivator() throws Exception {
        CamelContext context = (CamelContext) _domain.getProperty(SwitchYardCamelContext.CAMEL_CONTEXT_PROPERTY);
        context.suspend();
    }

    private void startCamelActivator() throws Exception {
        CamelContext context = (CamelContext) _domain.getProperty(SwitchYardCamelContext.CAMEL_CONTEXT_PROPERTY);
        context.resume();
    }

    private void sendAndreplacedertOneMessage() throws Exception, InterruptedException {
        final String payload = "dummy payload";
        // remove the currently registered service for SimpleCamelService
        _testKit.removeService("SimpleCamelService");
        final MockHandler simpleCamelService = _testKit.registerInOnlyService("SimpleCamelService");
        sendTextToQueue(payload, "testQueue");
        // Allow for the JMS Message to be processed.
        Thread.sleep(3000);
        final LinkedBlockingQueue<Exchange> recievedMessages = simpleCamelService.getMessages();
        replacedertThat(recievedMessages, is(notNullValue()));
        final Exchange recievedExchange = recievedMessages.iterator().next();
        replacedertThat(recievedExchange.getMessage().getContent(String.clreplaced), is(equalTo(payload)));
    }

    private void sendTextToQueue(final String text, final String destinationName) throws Exception {
        InitialContext initialContext = null;
        Connection connection = null;
        Session session = null;
        MessageProducer producer = null;
        try {
            initialContext = new InitialContext();
            final ConnectionFactory connectionFactory = (ConnectionFactory) initialContext.lookup("ConnectionFactory");
            final Destination destination = (Destination) initialContext.lookup(destinationName);
            connection = connectionFactory.createConnection();
            connection.start();
            session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            producer = session.createProducer(destination);
            producer.send(session.createTextMessage(text));
        } finally {
            if (producer != null) {
                producer.close();
            }
            if (session != null) {
                session.close();
            }
            if (connection != null) {
                connection.close();
            }
            if (initialContext != null) {
                initialContext.close();
            }
        }
    }
}