diff options
Diffstat (limited to 'sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java')
191 files changed, 19859 insertions, 0 deletions
diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/bootstrap/BootstrapperTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/bootstrap/BootstrapperTestCase.java new file mode 100644 index 0000000000..deb4ae3f62 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/bootstrap/BootstrapperTestCase.java @@ -0,0 +1,42 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.bootstrap; + +import junit.framework.TestCase; + +import org.apache.tuscany.core.deployer.DeployerImpl; +import org.apache.tuscany.core.monitor.NullMonitorFactory; + +/** + * Verifies the default bootstrapper can be instantiated + * + * @version $Rev$ $Date$ + */ +public class BootstrapperTestCase extends TestCase { + private Bootstrapper bootstrapper; + + public void testDeployerBootstrap() { + DeployerImpl deployer = (DeployerImpl) bootstrapper.createDeployer(); + } + + protected void setUp() throws Exception { + super.setUp(); + bootstrapper = new DefaultBootstrapper(new NullMonitorFactory(), null); + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/builder/BuilderRegistryTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/builder/BuilderRegistryTestCase.java new file mode 100644 index 0000000000..5a33950cc4 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/builder/BuilderRegistryTestCase.java @@ -0,0 +1,75 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.builder; + +import org.apache.tuscany.spi.builder.BuilderConfigException; +import org.apache.tuscany.spi.builder.ComponentBuilder; +import org.apache.tuscany.spi.component.Component; +import org.apache.tuscany.spi.component.CompositeComponent; +import org.apache.tuscany.spi.deployer.DeploymentContext; +import org.apache.tuscany.spi.model.ComponentDefinition; +import org.apache.tuscany.spi.model.CompositeComponentType; +import org.apache.tuscany.spi.model.CompositeImplementation; +import org.apache.tuscany.spi.wire.WireService; + +import junit.framework.TestCase; +import org.apache.tuscany.core.deployer.RootDeploymentContext; +import org.easymock.EasyMock; + +/** + * @version $Rev$ $Date$ + */ +public class BuilderRegistryTestCase extends TestCase { + private DeploymentContext deploymentContext; + private BuilderRegistryImpl registry; + + public void testRegistrationWithoutGenerics() { + RawBuilder builder = new RawBuilder(); + registry.register(CompositeImplementation.class, builder); + CompositeImplementation implementation = new CompositeImplementation(); + ComponentDefinition<CompositeImplementation> componentDefinition = + new ComponentDefinition<CompositeImplementation>(implementation); + componentDefinition.getImplementation().setComponentType(new CompositeComponentType()); + registry.build(null, componentDefinition, deploymentContext); + } + + protected void setUp() throws Exception { + super.setUp(); + registry = new BuilderRegistryImpl(); + WireService service = EasyMock.createNiceMock(WireService.class); + registry.setWireService(service); + deploymentContext = new RootDeploymentContext(null, null, null, null); + } + + public static class GenerifiedBuilder implements ComponentBuilder<CompositeImplementation> { + public Component build(CompositeComponent parent, + ComponentDefinition<CompositeImplementation> componentDefinition, + DeploymentContext deploymentContext) { + return null; + } + } + + public static class RawBuilder implements ComponentBuilder<CompositeImplementation> { + public Component build(CompositeComponent parent, + ComponentDefinition componentDefinition, + DeploymentContext deploymentContext) throws BuilderConfigException { + return null; + } + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/builder/ConnectorImplTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/builder/ConnectorImplTestCase.java new file mode 100644 index 0000000000..967c17ece0 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/builder/ConnectorImplTestCase.java @@ -0,0 +1,416 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.builder; + +import java.lang.reflect.Type; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.apache.tuscany.spi.QualifiedName; +import org.apache.tuscany.spi.component.AtomicComponent; +import org.apache.tuscany.spi.component.CompositeComponent; +import org.apache.tuscany.spi.component.Reference; +import org.apache.tuscany.spi.component.Service; +import org.apache.tuscany.spi.idl.java.JavaServiceContract; +import org.apache.tuscany.spi.model.Operation; +import org.apache.tuscany.spi.model.Scope; +import org.apache.tuscany.spi.model.ServiceContract; +import org.apache.tuscany.spi.wire.InboundInvocationChain; +import org.apache.tuscany.spi.wire.InboundWire; +import org.apache.tuscany.spi.wire.Interceptor; +import org.apache.tuscany.spi.wire.OutboundInvocationChain; +import org.apache.tuscany.spi.wire.OutboundWire; +import org.apache.tuscany.spi.wire.TargetInvoker; + +import junit.framework.TestCase; +import org.apache.tuscany.core.wire.SynchronousBridgingInterceptor; +import org.easymock.EasyMock; + +/** + * @version $Rev$ $Date$ + */ +public class ConnectorImplTestCase extends TestCase { + + private ConnectorImpl connector; + private ServiceContract contract; + private Operation<Type> operation; + private Interceptor headInterceptor; + private Interceptor tailInterceptor; + + public void testConnectReferenceWires() { + + // create the inbound wire and chain + InboundInvocationChain inboundChain = EasyMock.createMock(InboundInvocationChain.class); + EasyMock.expect(inboundChain.getOperation()).andReturn(operation).atLeastOnce(); + inboundChain.addInterceptor(EasyMock.isA(SynchronousBridgingInterceptor.class)); + inboundChain.setTargetInvoker(null); + inboundChain.prepare(); + EasyMock.replay(inboundChain); + Map<Operation<?>, InboundInvocationChain> inboundChains = new HashMap<Operation<?>, InboundInvocationChain>(); + inboundChains.put(operation, inboundChain); + InboundWire inboundWire = EasyMock.createMock(InboundWire.class); + EasyMock.expect(inboundWire.getServiceContract()).andReturn(contract).anyTimes(); + EasyMock.expect(inboundWire.getInvocationChains()).andReturn(inboundChains).atLeastOnce(); + EasyMock.replay(inboundWire); + + OutboundInvocationChain outboundChain = EasyMock.createMock(OutboundInvocationChain.class); + EasyMock.expect(outboundChain.getHeadInterceptor()).andReturn(headInterceptor); + EasyMock.replay(outboundChain); + Map<Operation<?>, OutboundInvocationChain> outboundChains = + new HashMap<Operation<?>, OutboundInvocationChain>(); + outboundChains.put(operation, outboundChain); + OutboundWire outboundWire = EasyMock.createMock(OutboundWire.class); + EasyMock.expect(outboundWire.getServiceContract()).andReturn(contract).anyTimes(); + EasyMock.expect(outboundWire.getTargetName()).andReturn(new QualifiedName("target/FooService")).anyTimes(); + EasyMock.expect(outboundWire.getInvocationChains()).andReturn(outboundChains).anyTimes(); + EasyMock.replay(outboundWire); + + Reference reference = EasyMock.createMock(Reference.class); + EasyMock.expect(reference.getParent()).andReturn(null); + EasyMock.expect(reference.createTargetInvoker(contract, operation)).andReturn(null); + EasyMock.expect(reference.getInboundWire()).andReturn(inboundWire); + EasyMock.expect(reference.getOutboundWire()).andReturn(outboundWire); + EasyMock.replay(reference); + + connector.connect(reference); + + EasyMock.verify(reference); + EasyMock.verify(inboundWire); + EasyMock.verify(outboundWire); + EasyMock.verify(inboundChain); + EasyMock.verify(outboundChain); + } + + public void testConnectServiceWires() { + // create the inbound wire and chain for the target + InboundInvocationChain targetChain = EasyMock.createMock(InboundInvocationChain.class); + EasyMock.expect(targetChain.getOperation()).andReturn(operation).atLeastOnce(); + EasyMock.expect(targetChain.getHeadInterceptor()).andReturn(headInterceptor); + targetChain.prepare(); + EasyMock.replay(targetChain); + Map<Operation<?>, InboundInvocationChain> targetChains = new HashMap<Operation<?>, InboundInvocationChain>(); + targetChains.put(operation, targetChain); + InboundWire targetWire = EasyMock.createMock(InboundWire.class); + EasyMock.expect(targetWire.getServiceContract()).andReturn(contract).anyTimes(); + EasyMock.expect(targetWire.getInvocationChains()).andReturn(targetChains); + targetWire.getSourceCallbackInvocationChains("source"); + EasyMock.expectLastCall().andReturn(Collections.emptyMap()); + + // create the target + AtomicComponent target = EasyMock.createMock(AtomicComponent.class); + EasyMock.expect(target.getScope()).andReturn(Scope.MODULE); + EasyMock.expect(target.isSystem()).andReturn(false).atLeastOnce(); + target.getInboundWire(EasyMock.eq("FooService")); + EasyMock.expectLastCall().andReturn(targetWire).atLeastOnce(); + target.createTargetInvoker(EasyMock.eq("FooService"), EasyMock.eq(operation)); + EasyMock.expectLastCall().andReturn(null); + EasyMock.replay(target); + + EasyMock.expect(targetWire.getContainer()).andReturn(target); + EasyMock.replay(targetWire); + + // create the parent composite + CompositeComponent parent = EasyMock.createMock(CompositeComponent.class); + EasyMock.expect(parent.getChild("target")).andReturn(target); + EasyMock.replay(parent); + + // create the inbound wire and chain for the source service + InboundInvocationChain inboundChain = EasyMock.createMock(InboundInvocationChain.class); + EasyMock.expect(inboundChain.getOperation()).andReturn(operation).atLeastOnce(); + inboundChain.addInterceptor(EasyMock.isA(SynchronousBridgingInterceptor.class)); + inboundChain.setTargetInvoker(null); + EasyMock.replay(inboundChain); + Map<Operation<?>, InboundInvocationChain> inboundChains = new HashMap<Operation<?>, InboundInvocationChain>(); + inboundChains.put(operation, inboundChain); + InboundWire inboundWire = EasyMock.createMock(InboundWire.class); + EasyMock.expect(inboundWire.getServiceContract()).andReturn(contract).anyTimes(); + EasyMock.expect(inboundWire.getInvocationChains()).andReturn(inboundChains).atLeastOnce(); + EasyMock.replay(inboundWire); + + // create the outbound wire and chain for the source service + OutboundInvocationChain outboundChain = EasyMock.createMock(OutboundInvocationChain.class); + EasyMock.expect(outboundChain.getHeadInterceptor()).andReturn(headInterceptor); + outboundChain.setTargetInterceptor(EasyMock.isA(SynchronousBridgingInterceptor.class)); + outboundChain.prepare(); + outboundChain.setTargetInvoker(null); + EasyMock.expect(outboundChain.getOperation()).andReturn(operation); + EasyMock.replay(outboundChain); + Map<Operation<?>, OutboundInvocationChain> outboundChains = + new HashMap<Operation<?>, OutboundInvocationChain>(); + outboundChains.put(operation, outboundChain); + OutboundWire outboundWire = EasyMock.createMock(OutboundWire.class); + outboundWire.getTargetCallbackInvocationChains(); + EasyMock.expectLastCall().andReturn(Collections.emptyMap()); + EasyMock.expect(outboundWire.getServiceContract()).andReturn(contract).anyTimes(); + EasyMock.expect(outboundWire.getTargetName()).andReturn(new QualifiedName("target/FooService")).anyTimes(); + EasyMock.expect(outboundWire.getInvocationChains()).andReturn(outboundChains).anyTimes(); + + // create the service + Service service = EasyMock.createMock(Service.class); + EasyMock.expect(service.getName()).andReturn("source"); + EasyMock.expect(service.isSystem()).andReturn(false).atLeastOnce(); + EasyMock.expect(service.getParent()).andReturn(parent).atLeastOnce(); + EasyMock.expect(service.getInboundWire()).andReturn(inboundWire).atLeastOnce(); + EasyMock.expect(service.getScope()).andReturn(Scope.COMPOSITE); + EasyMock.expect(service.getOutboundWire()).andReturn(outboundWire); + EasyMock.replay(service); + + EasyMock.expect(outboundWire.getContainer()).andReturn(service); + EasyMock.replay(outboundWire); + + connector.connect(service); + + EasyMock.verify(service); + EasyMock.verify(inboundWire); + EasyMock.verify(outboundWire); + EasyMock.verify(inboundChain); + EasyMock.verify(outboundChain); + } + + /** + * Verifies connecting a wire from an atomic component to a target atomic component with one synchronous operation + */ + public void testConnectAtomicComponentToAtomicComponentSyncWire() throws Exception { + + // create the inbound wire and chain + InboundInvocationChain inboundChain = EasyMock.createMock(InboundInvocationChain.class); + EasyMock.expect(inboundChain.getOperation()).andReturn(operation).atLeastOnce(); + EasyMock.expect(inboundChain.getHeadInterceptor()).andReturn(headInterceptor); + EasyMock.replay(inboundChain); + Map<Operation<?>, InboundInvocationChain> inboundChains = new HashMap<Operation<?>, InboundInvocationChain>(); + inboundChains.put(operation, inboundChain); + InboundWire targetWire = EasyMock.createMock(InboundWire.class); + EasyMock.expect(targetWire.getServiceContract()).andReturn(contract).anyTimes(); + EasyMock.expect(targetWire.getInvocationChains()).andReturn(inboundChains); + targetWire.getSourceCallbackInvocationChains("source"); + EasyMock.expectLastCall().andReturn(Collections.emptyMap()); + + // create the target + AtomicComponent target = EasyMock.createMock(AtomicComponent.class); + EasyMock.expect(target.getScope()).andReturn(Scope.MODULE); + target.getInboundWire(EasyMock.eq("FooService")); + EasyMock.expectLastCall().andReturn(targetWire); + target.createTargetInvoker(EasyMock.eq("FooService"), EasyMock.eq(operation)); + EasyMock.expectLastCall().andReturn(null); + EasyMock.replay(target); + + EasyMock.expect(targetWire.getContainer()).andReturn(target); + EasyMock.replay(targetWire); + + // create the parent composite + CompositeComponent parent = EasyMock.createMock(CompositeComponent.class); + EasyMock.expect(parent.getChild("target")).andReturn(target); + EasyMock.replay(parent); + + // create the outbound wire and chain from the source component + OutboundInvocationChain outboundChain = EasyMock.createMock(OutboundInvocationChain.class); + EasyMock.expect(outboundChain.getOperation()).andReturn(operation).atLeastOnce(); + outboundChain.setTargetInterceptor(EasyMock.isA(SynchronousBridgingInterceptor.class)); + outboundChain.setTargetInvoker(null); + outboundChain.prepare(); + EasyMock.replay(outboundChain); + Map<Operation<?>, OutboundInvocationChain> outboundChains = + new HashMap<Operation<?>, OutboundInvocationChain>(); + outboundChains.put(operation, outboundChain); + OutboundWire outboundWire = EasyMock.createMock(OutboundWire.class); + EasyMock.expect(outboundWire.getServiceContract()).andReturn(contract).anyTimes(); + EasyMock.expect(outboundWire.getTargetName()).andReturn(new QualifiedName("target/FooService")).anyTimes(); + EasyMock.expect(outboundWire.getInvocationChains()).andReturn(outboundChains).anyTimes(); + outboundWire.getTargetCallbackInvocationChains(); + EasyMock.expectLastCall().andReturn(Collections.emptyMap()); + + Map<String, List<OutboundWire>> outboundWires = new HashMap<String, List<OutboundWire>>(); + List<OutboundWire> list = new ArrayList<OutboundWire>(); + list.add(outboundWire); + outboundWires.put("fooService", list); + + // create the source + AtomicComponent source = EasyMock.createMock(AtomicComponent.class); + EasyMock.expect(source.isSystem()).andReturn(false).atLeastOnce(); + EasyMock.expect(source.getScope()).andReturn(Scope.MODULE); + EasyMock.expect(source.getParent()).andReturn(parent).atLeastOnce(); + EasyMock.expect(source.getOutboundWires()).andReturn(outboundWires); + EasyMock.expect(source.getName()).andReturn("source"); + source.getInboundWires(); + EasyMock.expectLastCall().andReturn(Collections.emptyMap()); + EasyMock.replay(source); + + EasyMock.expect(outboundWire.getContainer()).andReturn(source); + EasyMock.replay(outboundWire); + + connector.connect(source); + EasyMock.verify(outboundWire); + EasyMock.verify(targetWire); + EasyMock.verify(outboundChain); + EasyMock.verify(inboundChain); + EasyMock.verify(source); + EasyMock.verify(target); + } + + public void testConnectInboundAtomicComponentWires() { + // create the inbound wire and chain + InboundInvocationChain chain = EasyMock.createMock(InboundInvocationChain.class); + EasyMock.expect(chain.getOperation()).andReturn(operation).atLeastOnce(); + chain.setTargetInvoker(null); + chain.prepare(); + EasyMock.replay(chain); + Map<Operation<?>, InboundInvocationChain> inboundChains = new HashMap<Operation<?>, InboundInvocationChain>(); + inboundChains.put(operation, chain); + InboundWire wire = EasyMock.createMock(InboundWire.class); + EasyMock.expect(wire.getServiceName()).andReturn("FooService"); + EasyMock.expect(wire.getServiceContract()).andReturn(contract).anyTimes(); + EasyMock.expect(wire.getInvocationChains()).andReturn(inboundChains); + EasyMock.replay(wire); + + Map<String, InboundWire> wires = new HashMap<String, InboundWire>(); + wires.put("FooService", wire); + + AtomicComponent source = EasyMock.createMock(AtomicComponent.class); + EasyMock.expect(source.getParent()).andReturn(null); + source.getOutboundWires(); + EasyMock.expectLastCall().andReturn(Collections.emptyMap()); + source.getInboundWires(); + EasyMock.expectLastCall().andReturn(wires); + source.createTargetInvoker(EasyMock.eq("FooService"), EasyMock.eq(operation)); + EasyMock.expectLastCall().andReturn(null); + EasyMock.replay(source); + + connector.connect(source); + + EasyMock.verify(source); + EasyMock.verify(wire); + EasyMock.verify(chain); + } + + public void testOutboundToInboundOptimization() { + InboundWire inboundWire = EasyMock.createMock(InboundWire.class); + EasyMock.expect(inboundWire.getContainer()).andReturn(null); + inboundWire.getInvocationChains(); + EasyMock.expectLastCall().andReturn(Collections.emptyMap()); + EasyMock.replay(inboundWire); + + OutboundWire outboundWire = EasyMock.createMock(OutboundWire.class); + outboundWire.getInvocationChains(); + EasyMock.expectLastCall().andReturn(Collections.emptyMap()); + outboundWire.setTargetWire(inboundWire); + EasyMock.expect(outboundWire.getContainer()).andReturn(null); + EasyMock.expect(outboundWire.getServiceContract()).andReturn(null); + EasyMock.replay(outboundWire); + + connector.connect(outboundWire, inboundWire, true); + EasyMock.verify(inboundWire); + EasyMock.verify(outboundWire); + } + + public void testOutboundToInboundChainConnect() { + + TargetInvoker invoker = EasyMock.createMock(TargetInvoker.class); + EasyMock.replay(invoker); + + InboundInvocationChain inboundChain = EasyMock.createMock(InboundInvocationChain.class); + EasyMock.expect(inboundChain.getHeadInterceptor()).andReturn(headInterceptor); + EasyMock.replay(inboundChain); + + OutboundInvocationChain outboundChain = EasyMock.createMock(OutboundInvocationChain.class); + outboundChain.prepare(); + outboundChain.setTargetInterceptor(EasyMock.isA(SynchronousBridgingInterceptor.class)); + outboundChain.setTargetInvoker(invoker); + EasyMock.replay(outboundChain); + connector.connect(outboundChain, inboundChain, invoker, false); + EasyMock.verify(outboundChain); + } + + public void testInboundToOutboundChainConnect() { + InboundInvocationChain inboundChain = EasyMock.createMock(InboundInvocationChain.class); + inboundChain.addInterceptor(EasyMock.isA(SynchronousBridgingInterceptor.class)); + EasyMock.replay(inboundChain); + + OutboundInvocationChain outboundChain = EasyMock.createMock(OutboundInvocationChain.class); + EasyMock.expect(outboundChain.getHeadInterceptor()).andReturn(headInterceptor); + outboundChain.prepare(); + outboundChain.setTargetInterceptor(headInterceptor); + EasyMock.replay(outboundChain); + connector.connect(inboundChain, outboundChain); + EasyMock.verify(inboundChain); + } + + public void testOutboundWireToInboundReferenceTarget() { + AtomicComponent component = EasyMock.createMock(AtomicComponent.class); + EasyMock.expect(component.getName()).andReturn("foo"); + EasyMock.replay(component); + // create the inbound wire and chain + InboundInvocationChain inboundChain = EasyMock.createMock(InboundInvocationChain.class); + EasyMock.expect(inboundChain.getOperation()).andReturn(operation).atLeastOnce(); + EasyMock.expect(inboundChain.getHeadInterceptor()).andReturn(headInterceptor); + EasyMock.replay(inboundChain); + Map<Operation<?>, InboundInvocationChain> inboundChains = new HashMap<Operation<?>, InboundInvocationChain>(); + inboundChains.put(operation, inboundChain); + InboundWire targetWire = EasyMock.createMock(InboundWire.class); + EasyMock.expect(targetWire.getServiceContract()).andReturn(contract).anyTimes(); + EasyMock.expect(targetWire.getInvocationChains()).andReturn(inboundChains); + targetWire.getSourceCallbackInvocationChains("foo"); + EasyMock.expectLastCall().andReturn(Collections.emptyMap()); + Reference target = EasyMock.createMock(Reference.class); + EasyMock.expect(target.createTargetInvoker(EasyMock.isA(ServiceContract.class), EasyMock.isA(Operation.class))) + .andReturn(null); + EasyMock.replay(target); + + EasyMock.expect(targetWire.getContainer()).andReturn(target); + EasyMock.replay(targetWire); + + // create the outbound wire and chain from the source component + OutboundInvocationChain outboundChain = EasyMock.createMock(OutboundInvocationChain.class); + EasyMock.expect(outboundChain.getOperation()).andReturn(operation).atLeastOnce(); + outboundChain.setTargetInterceptor(EasyMock.isA(SynchronousBridgingInterceptor.class)); + outboundChain.setTargetInvoker(null); + outboundChain.prepare(); + EasyMock.replay(outboundChain); + Map<Operation<?>, OutboundInvocationChain> outboundChains = + new HashMap<Operation<?>, OutboundInvocationChain>(); + outboundChains.put(operation, outboundChain); + OutboundWire sourceWire = EasyMock.createMock(OutboundWire.class); + EasyMock.expect(sourceWire.getContainer()).andReturn(component); + EasyMock.expect(sourceWire.getServiceContract()).andReturn(contract).anyTimes(); + EasyMock.expect(sourceWire.getTargetName()).andReturn(new QualifiedName("target/FooService")).anyTimes(); + EasyMock.expect(sourceWire.getInvocationChains()).andReturn(outboundChains).anyTimes(); + sourceWire.getTargetCallbackInvocationChains(); + EasyMock.expectLastCall().andReturn(Collections.emptyMap()); + EasyMock.replay(sourceWire); + + connector.connect(sourceWire, targetWire, false); + EasyMock.verify(inboundChain); + EasyMock.verify(targetWire); + EasyMock.verify(target); + } + + protected void setUp() throws Exception { + super.setUp(); + connector = new ConnectorImpl(); + contract = new JavaServiceContract(String.class); + operation = new Operation<Type>("bar", null, null, null); + headInterceptor = EasyMock.createMock(Interceptor.class); + EasyMock.replay(headInterceptor); + tailInterceptor = EasyMock.createMock(Interceptor.class); + EasyMock.replay(tailInterceptor); + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/builder/ConnectorPostProcessTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/builder/ConnectorPostProcessTestCase.java new file mode 100644 index 0000000000..366a4a57b2 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/builder/ConnectorPostProcessTestCase.java @@ -0,0 +1,99 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.builder; + +import java.util.HashMap; +import java.util.Map; + +import org.apache.tuscany.spi.builder.WirePostProcessorRegistry; +import org.apache.tuscany.spi.component.Component; +import org.apache.tuscany.spi.model.Operation; +import org.apache.tuscany.spi.model.ServiceContract; +import org.apache.tuscany.spi.wire.InboundInvocationChain; +import org.apache.tuscany.spi.wire.InboundWire; +import org.apache.tuscany.spi.wire.OutboundInvocationChain; +import org.apache.tuscany.spi.wire.OutboundWire; +import org.apache.tuscany.spi.wire.WireService; + +import junit.framework.TestCase; +import org.easymock.EasyMock; +import static org.easymock.EasyMock.createMock; +import static org.easymock.EasyMock.createNiceMock; +import static org.easymock.EasyMock.expect; +import static org.easymock.EasyMock.expectLastCall; +import static org.easymock.EasyMock.replay; +import static org.easymock.EasyMock.verify; + +/** + * @version $Rev$ $Date$ + */ +public class ConnectorPostProcessTestCase extends TestCase { + + public void testInboundToOutboundPostProcessCalled() throws Exception { + OutboundWire owire = createNiceMock(OutboundWire.class); + replay(owire); + InboundWire iwire = createNiceMock(InboundWire.class); + Map<Operation<?>, InboundInvocationChain> chains = new HashMap<Operation<?>, InboundInvocationChain>(); + expect(iwire.getInvocationChains()).andReturn(chains); + replay(iwire); + WirePostProcessorRegistry registry = createMock(WirePostProcessorRegistry.class); + registry.process(EasyMock.eq(iwire), EasyMock.eq(owire)); + replay(registry); + WireService wireService = createMock(WireService.class); + wireService.checkCompatibility((ServiceContract<?>) EasyMock.anyObject(), + (ServiceContract<?>) EasyMock.anyObject(), EasyMock.eq(false)); + expectLastCall().anyTimes(); + replay(wireService); + ConnectorImpl connector = new ConnectorImpl(wireService, registry, null, null); + connector.connect(iwire, owire, false); + verify(registry); + } + + public void testOutboundToInboundPostProcessCalled() throws Exception { + Component source = createNiceMock(Component.class); + expect(source.getName()).andReturn("Component"); + replay(source); + + OutboundWire owire = createNiceMock(OutboundWire.class); + EasyMock.expect(owire.getContainer()).andReturn(source); + + Map<Operation<?>, OutboundInvocationChain> chains = new HashMap<Operation<?>, OutboundInvocationChain>(); + expect(owire.getInvocationChains()).andReturn(chains); + Map<Operation<?>, InboundInvocationChain> ichains = new HashMap<Operation<?>, InboundInvocationChain>(); + expect(owire.getTargetCallbackInvocationChains()).andReturn(ichains); + replay(owire); + InboundWire iwire = createNiceMock(InboundWire.class); + expect(iwire.getSourceCallbackInvocationChains("Component")).andReturn(chains); + replay(iwire); + WirePostProcessorRegistry registry = createMock(WirePostProcessorRegistry.class); + registry.process(EasyMock.eq(owire), EasyMock.eq(iwire)); + replay(registry); + WireService wireService = createMock(WireService.class); + wireService.checkCompatibility((ServiceContract<?>) EasyMock.anyObject(), + (ServiceContract<?>) EasyMock.anyObject(), EasyMock.eq(false)); + expectLastCall().anyTimes(); + replay(wireService); + ConnectorImpl connector = new ConnectorImpl(wireService, registry, null, null); + + connector.connect(owire, iwire, false); + verify(registry); + } + + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/builder/InboundtoOutboundConnectTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/builder/InboundtoOutboundConnectTestCase.java new file mode 100644 index 0000000000..c12bca58ea --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/builder/InboundtoOutboundConnectTestCase.java @@ -0,0 +1,187 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.builder; + +import java.util.ArrayList; +import java.util.List; + +import org.apache.tuscany.spi.idl.InvalidServiceContractException; +import org.apache.tuscany.spi.idl.java.JavaInterfaceProcessorRegistry; +import org.apache.tuscany.spi.model.Operation; +import org.apache.tuscany.spi.model.ServiceContract; +import org.apache.tuscany.spi.wire.InboundInvocationChain; +import org.apache.tuscany.spi.wire.Interceptor; +import org.apache.tuscany.spi.wire.Message; +import org.apache.tuscany.spi.wire.MessageImpl; +import org.apache.tuscany.spi.wire.OutboundInvocationChain; +import org.apache.tuscany.spi.wire.TargetInvoker; + +import junit.framework.TestCase; +import org.apache.tuscany.core.idl.java.JavaInterfaceProcessorRegistryImpl; +import org.apache.tuscany.core.mock.component.SimpleTarget; +import org.apache.tuscany.core.mock.wire.MockSyncInterceptor; +import org.apache.tuscany.core.wire.InboundInvocationChainImpl; +import org.apache.tuscany.core.wire.InvokerInterceptor; +import org.apache.tuscany.core.wire.OutboundInvocationChainImpl; +import org.easymock.EasyMock; +import static org.easymock.EasyMock.createNiceMock; +import static org.easymock.EasyMock.expect; +import static org.easymock.EasyMock.replay; +import static org.easymock.EasyMock.verify; + +/** + * Verifies connection strategies between {@link org.apache.tuscany.spi.wire.OutboundInvocationChain}s and {@link + * org.apache.tuscany.spi.wire.InboundInvocationChain}s + * + * @version $$Rev$$ $$Date$$ + */ +public class InboundtoOutboundConnectTestCase extends TestCase { + private Operation operation; + + public void testNoInterceptorsNoHandlers() throws Exception { + ConnectorImpl connector = new ConnectorImpl(); + InboundInvocationChain inboundChain = setupInbound(null); + OutboundInvocationChain outboundChain = setupOutbound(null); + String[] val = new String[]{"foo"}; + TargetInvoker invoker = createNiceMock(TargetInvoker.class); + expect(invoker.invokeTarget(EasyMock.eq(val))).andReturn(val); + replay(invoker); + connector.connect(inboundChain, outboundChain); + inboundChain.setTargetInvoker(invoker); + inboundChain.prepare(); + inboundChain.getTargetInvoker().invokeTarget(val); + verify(invoker); + } + + + /** + * Verifies an invocation with a single source interceptor + */ + public void testSourceInterceptor() throws Exception { + ConnectorImpl connector = new ConnectorImpl(); + MockSyncInterceptor interceptor = new MockSyncInterceptor(); + List<Interceptor> interceptors = new ArrayList<Interceptor>(); + interceptors.add(interceptor); + + InboundInvocationChain inboundChain = setupInbound(interceptors); + OutboundInvocationChain outboundChain = setupOutbound(null); + Message msg = new MessageImpl(); + TargetInvoker invoker = createNiceMock(TargetInvoker.class); + expect(invoker.invoke(EasyMock.eq(msg))).andReturn(msg); + replay(invoker); + assertEquals(0, interceptor.getCount()); + connector.connect(inboundChain, outboundChain); + inboundChain.setTargetInvoker(invoker); + inboundChain.prepare(); + msg.setTargetInvoker(inboundChain.getTargetInvoker()); + assertEquals(msg, inboundChain.getHeadInterceptor().invoke(msg)); + assertEquals(1, interceptor.getCount()); + verify(invoker); + } + + /** + * Verifies an invocation with a single target interceptor + */ + public void testTargetInterceptor() throws Exception { + ConnectorImpl connector = new ConnectorImpl(); + MockSyncInterceptor interceptor = new MockSyncInterceptor(); + List<Interceptor> interceptors = new ArrayList<Interceptor>(); + interceptors.add(interceptor); + + InboundInvocationChain inboundChain = setupInbound(interceptors); + OutboundInvocationChain outboundChain = setupOutbound(null); + Message msg = new MessageImpl(); + TargetInvoker invoker = createNiceMock(TargetInvoker.class); + expect(invoker.invoke(EasyMock.eq(msg))).andReturn(msg); + replay(invoker); + assertEquals(0, interceptor.getCount()); + connector.connect(inboundChain, outboundChain); + inboundChain.setTargetInvoker(invoker); + inboundChain.prepare(); + msg.setTargetInvoker(inboundChain.getTargetInvoker()); + assertEquals(msg, inboundChain.getHeadInterceptor().invoke(msg)); + assertEquals(1, interceptor.getCount()); + verify(invoker); + } + + /** + * Verifies an invocation with a source and target interceptor + */ + public void testSourceTargetInterceptor() throws Exception { + ConnectorImpl connector = new ConnectorImpl(); + MockSyncInterceptor sourceInterceptor = new MockSyncInterceptor(); + List<Interceptor> sourceInterceptors = new ArrayList<Interceptor>(); + sourceInterceptors.add(sourceInterceptor); + MockSyncInterceptor targetInterceptor = new MockSyncInterceptor(); + List<Interceptor> targetInterceptors = new ArrayList<Interceptor>(); + targetInterceptors.add(targetInterceptor); + + OutboundInvocationChain outboundChain = setupOutbound(sourceInterceptors); + InboundInvocationChain inboundChain = setupInbound(targetInterceptors); + Message msg = new MessageImpl(); + TargetInvoker invoker = createNiceMock(TargetInvoker.class); + expect(invoker.invoke(EasyMock.eq(msg))).andReturn(msg); + replay(invoker); + assertEquals(0, sourceInterceptor.getCount()); + assertEquals(0, targetInterceptor.getCount()); + connector.connect(inboundChain, outboundChain); + inboundChain.setTargetInvoker(invoker); + inboundChain.prepare(); + msg.setTargetInvoker(inboundChain.getTargetInvoker()); + assertEquals(msg, inboundChain.getHeadInterceptor().invoke(msg)); + assertEquals(1, sourceInterceptor.getCount()); + assertEquals(1, targetInterceptor.getCount()); + verify(invoker); + } + + public InboundInvocationChain setupInbound(List<Interceptor> interceptors) { + + InboundInvocationChainImpl chain = new InboundInvocationChainImpl(operation); + if (interceptors != null) { + for (Interceptor interceptor : interceptors) { + chain.addInterceptor(interceptor); + } + } + return chain; + } + + public OutboundInvocationChain setupOutbound(List<Interceptor> interceptors) { + + OutboundInvocationChainImpl chain = new OutboundInvocationChainImpl(operation); + if (interceptors != null) { + for (Interceptor interceptor : interceptors) { + chain.addInterceptor(interceptor); + } + } + chain.addInterceptor(new InvokerInterceptor()); // add tail interceptor + return chain; + } + + protected void setUp() throws Exception { + super.setUp(); + JavaInterfaceProcessorRegistry registry = new JavaInterfaceProcessorRegistryImpl(); + ServiceContract<?> contract; + try { + contract = registry.introspect(SimpleTarget.class); + } catch (InvalidServiceContractException e) { + throw new AssertionError(); + } + operation = contract.getOperations().get("echo"); + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/builder/OutboundToInboundConnectTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/builder/OutboundToInboundConnectTestCase.java new file mode 100644 index 0000000000..009eba0fbd --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/builder/OutboundToInboundConnectTestCase.java @@ -0,0 +1,183 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.builder; + +import java.util.ArrayList; +import java.util.List; + +import org.apache.tuscany.spi.idl.InvalidServiceContractException; +import org.apache.tuscany.spi.idl.java.JavaInterfaceProcessorRegistry; +import org.apache.tuscany.spi.model.Operation; +import org.apache.tuscany.spi.model.ServiceContract; +import org.apache.tuscany.spi.wire.InboundInvocationChain; +import org.apache.tuscany.spi.wire.Interceptor; +import org.apache.tuscany.spi.wire.Message; +import org.apache.tuscany.spi.wire.MessageImpl; +import org.apache.tuscany.spi.wire.OutboundInvocationChain; +import org.apache.tuscany.spi.wire.TargetInvoker; + +import junit.framework.TestCase; +import org.apache.tuscany.core.idl.java.JavaInterfaceProcessorRegistryImpl; +import org.apache.tuscany.core.mock.component.SimpleTarget; +import org.apache.tuscany.core.mock.wire.MockSyncInterceptor; +import org.apache.tuscany.core.wire.InboundInvocationChainImpl; +import org.apache.tuscany.core.wire.InvokerInterceptor; +import org.apache.tuscany.core.wire.OutboundInvocationChainImpl; +import org.easymock.EasyMock; +import static org.easymock.EasyMock.createNiceMock; +import static org.easymock.EasyMock.expect; +import static org.easymock.EasyMock.replay; +import static org.easymock.EasyMock.verify; + +/** + * Verifies connection strategies between {@link org.apache.tuscany.spi.wire.OutboundInvocationChain}s and {@link + * org.apache.tuscany.spi.wire.InboundInvocationChain}s + * + * @version $$Rev$$ $$Date$$ + */ +public class OutboundToInboundConnectTestCase extends TestCase { + + public void testNoInterceptorsNoHandlers() throws Exception { + ConnectorImpl connector = new ConnectorImpl(); + InboundInvocationChain inboundChain = setupTarget(null); + OutboundInvocationChain outboundChain = setupSource(null); + String[] val = new String[]{"foo"}; + TargetInvoker invoker = createNiceMock(TargetInvoker.class); + expect(invoker.invokeTarget(EasyMock.eq(val))).andReturn(val); + replay(invoker); + connector.connect(outboundChain, inboundChain, invoker, false); + inboundChain.prepare(); + assertEquals(val, outboundChain.getTargetInvoker().invokeTarget(val)); + verify(invoker); + } + + + /** + * Verifies an invocation with a single source interceptor + */ + public void testSourceInterceptor() throws Exception { + ConnectorImpl connector = new ConnectorImpl(); + MockSyncInterceptor interceptor = new MockSyncInterceptor(); + List<Interceptor> interceptors = new ArrayList<Interceptor>(); + interceptors.add(interceptor); + OutboundInvocationChain outboundChain = setupSource(interceptors); + InboundInvocationChain inboundChain = setupTarget(null); + Message msg = new MessageImpl(); + TargetInvoker invoker = createNiceMock(TargetInvoker.class); + expect(invoker.invoke(EasyMock.eq(msg))).andReturn(msg); + replay(invoker); + assertEquals(0, interceptor.getCount()); + connector.connect(outboundChain, inboundChain, invoker, false); + inboundChain.prepare(); + msg.setTargetInvoker(outboundChain.getTargetInvoker()); + assertEquals(msg, outboundChain.getHeadInterceptor().invoke(msg)); + assertEquals(1, interceptor.getCount()); + verify(invoker); + } + + /** + * Verifies an invocation with a single target interceptor + */ + public void testTargetInterceptor() throws Exception { + ConnectorImpl connector = new ConnectorImpl(); + MockSyncInterceptor interceptor = new MockSyncInterceptor(); + List<Interceptor> interceptors = new ArrayList<Interceptor>(); + interceptors.add(interceptor); + OutboundInvocationChain outboundChain = setupSource(null); + InboundInvocationChain inboundChain = setupTarget(interceptors); + Message msg = new MessageImpl(); + TargetInvoker invoker = createNiceMock(TargetInvoker.class); + expect(invoker.invoke(EasyMock.eq(msg))).andReturn(msg); + replay(invoker); + assertEquals(0, interceptor.getCount()); + connector.connect(outboundChain, inboundChain, invoker, false); + inboundChain.prepare(); + msg.setTargetInvoker(outboundChain.getTargetInvoker()); + assertEquals(msg, outboundChain.getHeadInterceptor().invoke(msg)); + assertEquals(1, interceptor.getCount()); + verify(invoker); + } + + /** + * Verifies an invocation with a source and target interceptor + */ + public void testSourceTargetInterceptor() throws Exception { + ConnectorImpl connector = new ConnectorImpl(); + MockSyncInterceptor sourceInterceptor = new MockSyncInterceptor(); + List<Interceptor> sourceInterceptors = new ArrayList<Interceptor>(); + sourceInterceptors.add(sourceInterceptor); + MockSyncInterceptor targetInterceptor = new MockSyncInterceptor(); + List<Interceptor> targetInterceptors = new ArrayList<Interceptor>(); + targetInterceptors.add(targetInterceptor); + OutboundInvocationChain outboundChain = setupSource(sourceInterceptors); + InboundInvocationChain inboundChain = setupTarget(targetInterceptors); + Message msg = new MessageImpl(); + TargetInvoker invoker = createNiceMock(TargetInvoker.class); + expect(invoker.invoke(EasyMock.eq(msg))).andReturn(msg); + replay(invoker); + assertEquals(0, sourceInterceptor.getCount()); + assertEquals(0, targetInterceptor.getCount()); + connector.connect(outboundChain, inboundChain, invoker, false); + inboundChain.prepare(); + msg.setTargetInvoker(outboundChain.getTargetInvoker()); + assertEquals(msg, outboundChain.getHeadInterceptor().invoke(msg)); + assertEquals(1, sourceInterceptor.getCount()); + assertEquals(1, targetInterceptor.getCount()); + verify(invoker); + } + + + public InboundInvocationChain setupTarget(List<Interceptor> interceptors) { + JavaInterfaceProcessorRegistry registry = new JavaInterfaceProcessorRegistryImpl(); + ServiceContract<?> contract; + try { + contract = registry.introspect(SimpleTarget.class); + } catch (InvalidServiceContractException e) { + throw new AssertionError(); + } + Operation operation = contract.getOperations().get("echo"); + InboundInvocationChainImpl chain = new InboundInvocationChainImpl(operation); + if (interceptors != null) { + for (Interceptor interceptor : interceptors) { + chain.addInterceptor(interceptor); + } + } + chain.addInterceptor(new InvokerInterceptor()); // add tail interceptor + return chain; + } + + public OutboundInvocationChain setupSource(List<Interceptor> interceptors) { + JavaInterfaceProcessorRegistry registry = new JavaInterfaceProcessorRegistryImpl(); + ServiceContract<?> contract; + try { + contract = registry.introspect(SimpleTarget.class); + } catch (InvalidServiceContractException e) { + throw new AssertionError(); + } + Operation operation = contract.getOperations().get("echo"); + OutboundInvocationChainImpl chain = new OutboundInvocationChainImpl(operation); + if (interceptors != null) { + for (Interceptor interceptor : interceptors) { + chain.addInterceptor(interceptor); + } + } + return chain; + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/builder/WirePostProcessorRegistryImplTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/builder/WirePostProcessorRegistryImplTestCase.java new file mode 100644 index 0000000000..3e0e5c7bce --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/builder/WirePostProcessorRegistryImplTestCase.java @@ -0,0 +1,63 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.builder; + +import org.apache.tuscany.spi.builder.WirePostProcessor; +import org.apache.tuscany.spi.builder.WirePostProcessorRegistry; +import org.apache.tuscany.spi.wire.InboundWire; +import org.apache.tuscany.spi.wire.OutboundWire; + +import junit.framework.TestCase; +import org.easymock.EasyMock; +import static org.easymock.EasyMock.createMock; +import static org.easymock.EasyMock.verify; + +/** + * @version $Rev$ $Date$ + */ +public class WirePostProcessorRegistryImplTestCase extends TestCase { + + public void testRegisterUnregister() throws Exception { + WirePostProcessorRegistry registry = new WirePostProcessorRegistryImpl(); + OutboundWire owire = EasyMock.createMock(OutboundWire.class); + InboundWire iwire = EasyMock.createMock(InboundWire.class); + WirePostProcessor processor = createMock(WirePostProcessor.class); + processor.process(EasyMock.eq(owire), EasyMock.eq(iwire)); + EasyMock.replay(processor); + registry.register(processor); + registry.process(owire, iwire); + registry.unregister(processor); + registry.process(owire, iwire); + verify(processor); + } + + public void testProcessInboundToOutbound() throws Exception { + WirePostProcessorRegistry registry = new WirePostProcessorRegistryImpl(); + OutboundWire owire = EasyMock.createMock(OutboundWire.class); + InboundWire iwire = EasyMock.createMock(InboundWire.class); + WirePostProcessor processor = createMock(WirePostProcessor.class); + processor.process(EasyMock.eq(iwire), EasyMock.eq(owire)); + EasyMock.replay(processor); + registry.register(processor); + registry.process(iwire, owire); + verify(processor); + } + + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/component/event/EventTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/component/event/EventTestCase.java new file mode 100644 index 0000000000..79b9757c2c --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/component/event/EventTestCase.java @@ -0,0 +1,72 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.component.event; + +import org.apache.tuscany.spi.component.CompositeComponent; + +import junit.framework.TestCase; +import org.easymock.EasyMock; + +/** + * @version $Rev$ $Date$ + */ +public class EventTestCase extends TestCase { + + private CompositeComponent component; + + public void testCompositeStart() { + CompositeStart event = new CompositeStart(this, component); + assertEquals(component, event.getComposite()); + } + + public void testCompositeStop() { + CompositeStop event = new CompositeStop(this, component); + assertEquals(component, event.getComposite()); + } + + public void testHttpSessionStart() { + Object id = new Object(); + HttpSessionEvent event = new HttpSessionStart(this, id); + assertEquals(this, event.getSource()); + assertEquals(id, event.getId()); + } + + public void testHttpSessionEnd() { + Object id = new Object(); + HttpSessionEvent event = new HttpSessionEnd(this, id); + assertEquals(this, event.getSource()); + assertEquals(id, event.getId()); + } + + public void testRequestStart() { + RequestStart event = new RequestStart(this); + assertEquals(this, event.getSource()); + } + + public void testReequestEnd() { + RequestEnd event = new RequestEnd(this); + assertEquals(this, event.getSource()); + } + + + protected void setUp() throws Exception { + super.setUp(); + component = EasyMock.createNiceMock(CompositeComponent.class); + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/component/scope/AbstractScopeContainerTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/component/scope/AbstractScopeContainerTestCase.java new file mode 100644 index 0000000000..a99dbf072a --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/component/scope/AbstractScopeContainerTestCase.java @@ -0,0 +1,141 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.component.scope; + +import org.apache.tuscany.spi.component.AtomicComponent; +import org.apache.tuscany.spi.component.WorkContext; +import org.apache.tuscany.spi.event.Event; +import org.apache.tuscany.spi.event.EventFilter; +import org.apache.tuscany.spi.event.RuntimeEventListener; +import org.apache.tuscany.spi.event.TrueFilter; +import org.apache.tuscany.spi.model.Scope; + +import junit.framework.TestCase; +import org.apache.tuscany.core.component.WorkContextImpl; +import org.easymock.EasyMock; + +/** + * @version $Rev$ $Date$ + */ +public class AbstractScopeContainerTestCase extends TestCase { + + public void testSetWorkContext() { + TestContainer container = new TestContainer("foo"); + WorkContext ctx = new WorkContextImpl(); + container.setWorkContext(ctx); + assertEquals(ctx, container.getWorkContext()); + + } + + public void testFireListener() { + TestContainer container = new TestContainer("foo"); + RuntimeEventListener listener = EasyMock.createMock(RuntimeEventListener.class); + Event event = new TestEvent(); + listener.onEvent(EasyMock.eq(event)); + EasyMock.replay(listener); + container.addListener(listener); + container.publish(event); + EasyMock.verify(listener); + } + + public void testRemoveListener() { + TestContainer container = new TestContainer("foo"); + RuntimeEventListener listener = EasyMock.createMock(RuntimeEventListener.class); + EasyMock.replay(listener); + Event event = new TestEvent(); + container.addListener(listener); + container.removeListener(listener); + container.publish(event); + EasyMock.verify(listener); + } + + public void testFalseFilterListener() { + TestContainer container = new TestContainer("foo"); + RuntimeEventListener listener = EasyMock.createMock(RuntimeEventListener.class); + Event event = new TestEvent(); + EasyMock.replay(listener); + container.addListener(new FalseFilter(), listener); + container.publish(event); + EasyMock.verify(listener); + } + + public void testTrueFilterListener() { + TestContainer container = new TestContainer("foo"); + RuntimeEventListener listener = EasyMock.createMock(RuntimeEventListener.class); + Event event = new TestEvent(); + listener.onEvent(EasyMock.eq(event)); + EasyMock.replay(listener); + container.addListener(new TrueFilter(), listener); + container.publish(event); + EasyMock.verify(listener); + } + + public void testToString() { + TestContainer container = new TestContainer("foo"); + assertNotNull(container.toString()); + } + + public void testGetName() { + TestContainer container = new TestContainer("foo"); + assertEquals("foo", container.getName()); + } + + + private class TestContainer extends AbstractScopeContainer { + + public TestContainer(String name) { + super(name, null); + } + + protected InstanceWrapper getInstanceWrapper(AtomicComponent component) { + return null; + } + + public Scope getScope() { + return null; + } + + public void register(AtomicComponent component) { + + } + + public void onEvent(Event event) { + + } + + public WorkContext getWorkContext() { + return super.getWorkContext(); + } + } + + private class TestEvent implements Event { + public Object getSource() { + return null; + } + } + + private class FalseFilter implements EventFilter { + + public boolean match(Event event) { + return false; + } + } + + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/component/scope/BasicHttpSessionScopeTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/component/scope/BasicHttpSessionScopeTestCase.java new file mode 100644 index 0000000000..dc8da77490 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/component/scope/BasicHttpSessionScopeTestCase.java @@ -0,0 +1,116 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.component.scope; + +import org.apache.tuscany.spi.component.ScopeContainer; +import org.apache.tuscany.spi.component.WorkContext; + +import junit.framework.TestCase; +import org.apache.tuscany.core.component.WorkContextImpl; +import org.apache.tuscany.core.component.event.HttpSessionEnd; +import org.apache.tuscany.core.implementation.PojoConfiguration; +import org.apache.tuscany.spi.component.SystemAtomicComponent; +import org.apache.tuscany.core.implementation.system.component.SystemAtomicComponentImpl; +import org.apache.tuscany.core.injection.EventInvoker; +import org.apache.tuscany.core.injection.MethodEventInvoker; +import org.apache.tuscany.core.injection.PojoObjectFactory; +import org.apache.tuscany.core.mock.component.SessionScopeInitDestroyComponent; + +/** + * @version $$Rev$$ $$Date$$ + */ +public class BasicHttpSessionScopeTestCase extends TestCase { + + private EventInvoker<Object> initInvoker; + private EventInvoker<Object> destroyInvoker; + private PojoObjectFactory<?> factory; + + public void testLifecycleManagement() throws Exception { + WorkContext workContext = new WorkContextImpl(); + HttpSessionScopeContainer scopeContext = new HttpSessionScopeContainer(workContext); + scopeContext.start(); + SystemAtomicComponent atomicContext = createContext(scopeContext); + // start the request + Object session = new Object(); + workContext.setIdentifier(HttpSessionScopeContainer.HTTP_IDENTIFIER, session); + SessionScopeInitDestroyComponent o1 = + (SessionScopeInitDestroyComponent) scopeContext.getInstance(atomicContext); + assertTrue(o1.isInitialized()); + assertFalse(o1.isDestroyed()); + SessionScopeInitDestroyComponent o2 = + (SessionScopeInitDestroyComponent) scopeContext.getInstance(atomicContext); + assertSame(o1, o2); + scopeContext.onEvent(new HttpSessionEnd(this, session)); + assertTrue(o1.isDestroyed()); + scopeContext.stop(); + } + + public void testSessionIsolation() throws Exception { + WorkContext workContext = new WorkContextImpl(); + HttpSessionScopeContainer scopeContext = new HttpSessionScopeContainer(workContext); + scopeContext.start(); + + SystemAtomicComponent atomicContext = createContext(scopeContext); + + Object session1 = new Object(); + workContext.setIdentifier(HttpSessionScopeContainer.HTTP_IDENTIFIER, session1); + SessionScopeInitDestroyComponent o1 = + (SessionScopeInitDestroyComponent) scopeContext.getInstance(atomicContext); + assertTrue(o1.isInitialized()); + + Object session2 = new Object(); + workContext.setIdentifier(HttpSessionScopeContainer.HTTP_IDENTIFIER, session2); + SessionScopeInitDestroyComponent o2 = + (SessionScopeInitDestroyComponent) scopeContext.getInstance(atomicContext); + assertNotSame(o1, o2); + + scopeContext.onEvent(new HttpSessionEnd(this, session1)); + assertTrue(o1.isDestroyed()); + assertFalse(o2.isDestroyed()); + scopeContext.onEvent(new HttpSessionEnd(this, session2)); + assertTrue(o2.isDestroyed()); + scopeContext.stop(); + } + + protected void setUp() throws Exception { + super.setUp(); + factory = new PojoObjectFactory<SessionScopeInitDestroyComponent>( + SessionScopeInitDestroyComponent.class.getConstructor((Class[]) null)); + initInvoker = new MethodEventInvoker<Object>( + SessionScopeInitDestroyComponent.class.getMethod("init", (Class[]) null)); + destroyInvoker = new MethodEventInvoker<Object>( + SessionScopeInitDestroyComponent.class.getMethod("destroy", (Class[]) null)); + } + + protected void tearDown() throws Exception { + super.tearDown(); + } + + private SystemAtomicComponent createContext(ScopeContainer scopeContainer) { + PojoConfiguration configuration = new PojoConfiguration(); + configuration.setScopeContainer(scopeContainer); + configuration.addServiceInterface(SessionScopeInitDestroyComponent.class); + configuration.setInstanceFactory(factory); + configuration.setInitInvoker(initInvoker); + configuration.setDestroyInvoker(destroyInvoker); + SystemAtomicComponentImpl context = new SystemAtomicComponentImpl("foo", configuration); + context.start(); + return context; + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/component/scope/BasicModuleScopeTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/component/scope/BasicModuleScopeTestCase.java new file mode 100644 index 0000000000..a4db2aef85 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/component/scope/BasicModuleScopeTestCase.java @@ -0,0 +1,107 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.component.scope; + +import org.apache.tuscany.spi.component.ScopeContainer; +import org.apache.tuscany.spi.component.WorkContext; +import org.apache.tuscany.spi.component.SystemAtomicComponent; + +import junit.framework.TestCase; +import org.apache.tuscany.core.component.WorkContextImpl; +import org.apache.tuscany.core.component.event.CompositeStop; +import org.apache.tuscany.core.implementation.PojoConfiguration; +import org.apache.tuscany.core.implementation.system.component.SystemAtomicComponentImpl; +import org.apache.tuscany.core.injection.EventInvoker; +import org.apache.tuscany.core.injection.MethodEventInvoker; +import org.apache.tuscany.core.injection.PojoObjectFactory; +import org.apache.tuscany.core.mock.component.ModuleScopeInitDestroyComponent; + +/** + * @version $$Rev$$ $$Date$$ + */ +public class BasicModuleScopeTestCase extends TestCase { + + private EventInvoker<Object> initInvoker; + private EventInvoker<Object> destroyInvoker; + private PojoObjectFactory<?> factory; + + public void testLifecycleManagement() throws Exception { + WorkContext workContext = new WorkContextImpl(); + ModuleScopeContainer scopeContext = new ModuleScopeContainer(workContext); + scopeContext.start(); + SystemAtomicComponent atomicContext = createContext(scopeContext); + // start the request + ModuleScopeInitDestroyComponent o1 = + (ModuleScopeInitDestroyComponent) scopeContext.getInstance(atomicContext); + assertTrue(o1.isInitialized()); + assertFalse(o1.isDestroyed()); + ModuleScopeInitDestroyComponent o2 = + (ModuleScopeInitDestroyComponent) scopeContext.getInstance(atomicContext); + assertEquals(o1, o2); + scopeContext.onEvent(new CompositeStop(this, null)); + assertTrue(o1.isDestroyed()); + scopeContext.stop(); + } + + public void testModuleIsolation() throws Exception { + WorkContext workContext = new WorkContextImpl(); + ModuleScopeContainer scopeContext = new ModuleScopeContainer(workContext); + scopeContext.start(); + + SystemAtomicComponent atomicContext = createContext(scopeContext); + + ModuleScopeInitDestroyComponent o1 = + (ModuleScopeInitDestroyComponent) scopeContext.getInstance(atomicContext); + assertTrue(o1.isInitialized()); + assertFalse(o1.isDestroyed()); + + ModuleScopeInitDestroyComponent o2 = + (ModuleScopeInitDestroyComponent) scopeContext.getInstance(atomicContext); + assertSame(o1, o2); + scopeContext.onEvent(new CompositeStop(this, null)); + assertTrue(o1.isDestroyed()); + scopeContext.stop(); + } + + protected void setUp() throws Exception { + super.setUp(); + factory = new PojoObjectFactory<ModuleScopeInitDestroyComponent>( + ModuleScopeInitDestroyComponent.class.getConstructor((Class[]) null)); + initInvoker = new MethodEventInvoker<Object>(ModuleScopeInitDestroyComponent.class.getMethod( + "init", (Class[]) null)); + destroyInvoker = new MethodEventInvoker<Object>(ModuleScopeInitDestroyComponent.class.getMethod( + "destroy", (Class[]) null)); + } + + protected void tearDown() throws Exception { + super.tearDown(); + } + + private SystemAtomicComponent createContext(ScopeContainer scopeContainer) { + PojoConfiguration configuration = new PojoConfiguration(); + configuration.setScopeContainer(scopeContainer); + configuration.addServiceInterface(ModuleScopeInitDestroyComponent.class); + configuration.setInstanceFactory(factory); + configuration.setInitInvoker(initInvoker); + configuration.setDestroyInvoker(destroyInvoker); + SystemAtomicComponentImpl context = new SystemAtomicComponentImpl("foo", configuration); + context.start(); + return context; + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/component/scope/BasicRequestScopeTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/component/scope/BasicRequestScopeTestCase.java new file mode 100644 index 0000000000..cb6a7c1673 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/component/scope/BasicRequestScopeTestCase.java @@ -0,0 +1,104 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.component.scope; + +import org.apache.tuscany.spi.component.ScopeContainer; +import org.apache.tuscany.spi.component.SystemAtomicComponent; + +import junit.framework.TestCase; +import org.apache.tuscany.core.component.event.RequestEnd; +import org.apache.tuscany.core.implementation.PojoConfiguration; +import org.apache.tuscany.core.implementation.system.component.SystemAtomicComponentImpl; +import org.apache.tuscany.core.injection.EventInvoker; +import org.apache.tuscany.core.injection.MethodEventInvoker; +import org.apache.tuscany.core.injection.PojoObjectFactory; +import org.apache.tuscany.core.mock.component.RequestScopeInitDestroyComponent; + +/** + * @version $$Rev$$ $$Date$$ + */ +public class BasicRequestScopeTestCase extends TestCase { + + private EventInvoker<Object> initInvoker; + private EventInvoker<Object> destroyInvoker; + private PojoObjectFactory<?> factory; + + public void testLifecycleManagement() throws Exception { + RequestScopeContainer scopeContext = new RequestScopeContainer(null); + scopeContext.start(); + SystemAtomicComponent atomicContext = createContext(scopeContext); + // start the request + RequestScopeInitDestroyComponent o1 = + (RequestScopeInitDestroyComponent) scopeContext.getInstance(atomicContext); + assertTrue(o1.isInitialized()); + assertFalse(o1.isDestroyed()); + RequestScopeInitDestroyComponent o2 = + (RequestScopeInitDestroyComponent) scopeContext.getInstance(atomicContext); + assertSame(o1, o2); + scopeContext.onEvent(new RequestEnd(this)); + assertTrue(o1.isDestroyed()); + scopeContext.stop(); + } + + public void testRequestIsolation() throws Exception { + RequestScopeContainer scopeContext = new RequestScopeContainer(null); + scopeContext.start(); + + SystemAtomicComponent atomicContext = createContext(scopeContext); + + RequestScopeInitDestroyComponent o1 = + (RequestScopeInitDestroyComponent) scopeContext.getInstance(atomicContext); + assertTrue(o1.isInitialized()); + scopeContext.onEvent(new RequestEnd(this)); + assertTrue(o1.isDestroyed()); + + RequestScopeInitDestroyComponent o2 = + (RequestScopeInitDestroyComponent) scopeContext.getInstance(atomicContext); + assertNotSame(o1, o2); + scopeContext.onEvent(new RequestEnd(this)); + assertTrue(o2.isDestroyed()); + scopeContext.stop(); + } + + protected void setUp() throws Exception { + super.setUp(); + factory = new PojoObjectFactory<RequestScopeInitDestroyComponent>( + RequestScopeInitDestroyComponent.class.getConstructor((Class[]) null)); + initInvoker = new MethodEventInvoker<Object>( + RequestScopeInitDestroyComponent.class.getMethod("init", (Class[]) null)); + destroyInvoker = new MethodEventInvoker<Object>( + RequestScopeInitDestroyComponent.class.getMethod("destroy", (Class[]) null)); + } + + protected void tearDown() throws Exception { + super.tearDown(); + } + + private SystemAtomicComponent createContext(ScopeContainer scopeContainer) { + PojoConfiguration configuration = new PojoConfiguration(); + configuration.setScopeContainer(scopeContainer); + configuration.addServiceInterface(RequestScopeInitDestroyComponent.class); + configuration.setInstanceFactory(factory); + configuration.setInitInvoker(initInvoker); + configuration.setDestroyInvoker(destroyInvoker); + SystemAtomicComponentImpl component = new SystemAtomicComponentImpl("foo", configuration); + scopeContainer.register(component); + return component; + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/component/scope/BasicStatelessScopeTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/component/scope/BasicStatelessScopeTestCase.java new file mode 100644 index 0000000000..a38abdc390 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/component/scope/BasicStatelessScopeTestCase.java @@ -0,0 +1,89 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.component.scope; + +import org.apache.tuscany.spi.component.WorkContext; +import org.apache.tuscany.spi.component.SystemAtomicComponent; + +import junit.framework.Assert; +import junit.framework.TestCase; +import org.apache.tuscany.core.component.WorkContextImpl; +import org.apache.tuscany.core.mock.component.StatelessComponent; +import org.apache.tuscany.core.mock.component.StatelessComponentImpl; +import org.apache.tuscany.core.mock.factories.MockFactory; + +/** + * Unit tests for the module scope container + * + * @version $Rev$ $Date$ + */ +public class BasicStatelessScopeTestCase extends TestCase { + + /** + * Tests instance identity is properly maintained + */ + public void testInstanceManagement() throws Exception { + WorkContext ctx = new WorkContextImpl(); + StatelessScopeContainer scope = new StatelessScopeContainer(ctx); + scope.start(); + SystemAtomicComponent context1 = + MockFactory.createAtomicComponent("comp1", scope, StatelessComponentImpl.class); + scope.register(context1); + SystemAtomicComponent context2 = + MockFactory.createAtomicComponent("comp2", scope, StatelessComponentImpl.class); + scope.register(context2); + StatelessComponentImpl comp1 = (StatelessComponentImpl) scope.getInstance(context1); + Assert.assertNotNull(comp1); + StatelessComponentImpl comp2 = (StatelessComponentImpl) scope.getInstance(context2); + Assert.assertNotNull(comp2); + Assert.assertNotSame(comp1, comp2); + scope.stop(); + } + + public void testRegisterContextAfterRequest() throws Exception { + WorkContext ctx = new WorkContextImpl(); + StatelessScopeContainer scope = new StatelessScopeContainer(ctx); + + scope.start(); + SystemAtomicComponent context1 = + MockFactory.createAtomicComponent("comp1", scope, StatelessComponentImpl.class); + scope.register(context1); + StatelessComponent comp1 = (StatelessComponentImpl) scope.getInstance(context1); + Assert.assertNotNull(comp1); + SystemAtomicComponent context2 = + MockFactory.createAtomicComponent("comp2", scope, StatelessComponentImpl.class); + scope.register(context2); + StatelessComponentImpl comp2 = (StatelessComponentImpl) scope.getInstance(context2); + Assert.assertNotNull(comp2); + scope.stop(); + } + + + /** + * Tests setting no components in the scope + */ + public void testSetNullComponents() throws Exception { + WorkContext ctx = new WorkContextImpl(); + StatelessScopeContainer scope = new StatelessScopeContainer(ctx); + scope.start(); + scope.stop(); + } + + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/component/scope/DependencyLifecycleTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/component/scope/DependencyLifecycleTestCase.java new file mode 100644 index 0000000000..ec23914acc --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/component/scope/DependencyLifecycleTestCase.java @@ -0,0 +1,172 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.component.scope; + +import java.util.Map; + +import org.apache.tuscany.spi.component.AtomicComponent; +import org.apache.tuscany.spi.component.WorkContext; + +import junit.framework.TestCase; +import org.apache.tuscany.core.component.WorkContextImpl; +import org.apache.tuscany.core.component.event.CompositeStart; +import org.apache.tuscany.core.component.event.CompositeStop; +import org.apache.tuscany.core.component.event.HttpSessionEnd; +import org.apache.tuscany.core.component.event.RequestEnd; +import org.apache.tuscany.core.component.event.RequestStart; +import org.apache.tuscany.core.mock.component.OrderedDependentPojo; +import org.apache.tuscany.core.mock.component.OrderedDependentPojoImpl; +import org.apache.tuscany.core.mock.component.OrderedInitPojo; +import org.apache.tuscany.core.mock.component.OrderedInitPojoImpl; +import org.apache.tuscany.core.mock.factories.MockFactory; + +/** + * Tests dependencies are initalized and destroyed in the proper order (i.e. LIFO) + * + * @version $Rev$ $Date$ + */ +public class DependencyLifecycleTestCase extends TestCase { + + public void testInitDestroyOrderModuleScope() throws Exception { + WorkContext ctx = new WorkContextImpl(); + ModuleScopeContainer scopeCtx = new ModuleScopeContainer(ctx); + scopeCtx.start(); + Map<String, AtomicComponent> contexts = MockFactory.createWiredComponents("source", + OrderedDependentPojoImpl.class, + scopeCtx, + "target", + OrderedInitPojoImpl.class, + scopeCtx); + for (AtomicComponent component : contexts.values()) { + scopeCtx.register(component); + } + AtomicComponent sourceComponent = contexts.get("source"); + AtomicComponent targetComponent = contexts.get("target"); + scopeCtx.register(sourceComponent); + scopeCtx.register(targetComponent); + scopeCtx.onEvent(new CompositeStart(this, null)); + OrderedDependentPojo source = (OrderedDependentPojo) scopeCtx.getInstance(sourceComponent); + OrderedInitPojo target = (OrderedInitPojo) scopeCtx.getInstance(targetComponent); + assertNotNull(source.getPojo()); + assertNotNull(target); + assertEquals(2, source.getNumberInstantiated()); + scopeCtx.onEvent(new CompositeStop(this, null)); + assertEquals(0, source.getNumberInstantiated()); + scopeCtx.stop(); + } + + public void testInitDestroyOrderAfterStartModuleScope() throws Exception { + WorkContext ctx = new WorkContextImpl(); + ModuleScopeContainer scopeCtx = new ModuleScopeContainer(ctx); + scopeCtx.start(); + Map<String, AtomicComponent> contexts = MockFactory.createWiredComponents("source", + OrderedDependentPojoImpl.class, + scopeCtx, + "target", + OrderedInitPojoImpl.class, + scopeCtx); + AtomicComponent sourceComponent = contexts.get("source"); + AtomicComponent targetComponent = contexts.get("target"); + scopeCtx.onEvent(new CompositeStart(this, null)); + scopeCtx.register(sourceComponent); + scopeCtx.register(targetComponent); + OrderedDependentPojo source = (OrderedDependentPojo) scopeCtx.getInstance(sourceComponent); + OrderedInitPojo target = (OrderedInitPojo) scopeCtx.getInstance(targetComponent); + assertNotNull(source.getPojo()); + assertNotNull(target); + assertEquals(2, source.getNumberInstantiated()); + scopeCtx.onEvent(new CompositeStop(this, null)); + assertEquals(0, source.getNumberInstantiated()); + scopeCtx.stop(); + } + + + public void testInitDestroyOrderSessionScope() throws Exception { + WorkContext ctx = new WorkContextImpl(); + HttpSessionScopeContainer scopeCtx = new HttpSessionScopeContainer(ctx); + scopeCtx.start(); + Object session = new Object(); + Map<String, AtomicComponent> contexts = MockFactory.createWiredComponents("source", + OrderedDependentPojoImpl.class, + scopeCtx, + "target", + OrderedInitPojoImpl.class, + scopeCtx); + AtomicComponent sourceComponent = contexts.get("source"); + AtomicComponent targetComponent = contexts.get("target"); + scopeCtx.register(sourceComponent); + scopeCtx.register(targetComponent); + ctx.setIdentifier(HttpSessionScopeContainer.HTTP_IDENTIFIER, session); + OrderedDependentPojo source = (OrderedDependentPojo) scopeCtx.getInstance(sourceComponent); + assertNotNull(source.getPojo()); + assertEquals(2, source.getNumberInstantiated()); + scopeCtx.onEvent(new HttpSessionEnd(this, session)); + assertEquals(0, source.getNumberInstantiated()); + scopeCtx.stop(); + } + + + public void testInitDestroyOrderAfterStartSessionScope() throws Exception { + WorkContext ctx = new WorkContextImpl(); + HttpSessionScopeContainer scopeCtx = new HttpSessionScopeContainer(ctx); + scopeCtx.start(); + Object session = new Object(); + Map<String, AtomicComponent> contexts = MockFactory.createWiredComponents("source", + OrderedDependentPojoImpl.class, + scopeCtx, + "target", + OrderedInitPojoImpl.class, + scopeCtx); + AtomicComponent sourceComponent = contexts.get("source"); + AtomicComponent targetComponent = contexts.get("target"); + ctx.setIdentifier(HttpSessionScopeContainer.HTTP_IDENTIFIER, session); + scopeCtx.register(sourceComponent); + scopeCtx.register(targetComponent); + OrderedDependentPojo source = (OrderedDependentPojo) scopeCtx.getInstance(sourceComponent); + assertNotNull(source.getPojo()); + assertEquals(2, source.getNumberInstantiated()); + scopeCtx.onEvent(new HttpSessionEnd(this, session)); + assertEquals(0, source.getNumberInstantiated()); + scopeCtx.stop(); + } + + public void testInitDestroyOrderRequestScope() throws Exception { + WorkContext ctx = new WorkContextImpl(); + RequestScopeContainer scopeCtx = new RequestScopeContainer(ctx); + scopeCtx.start(); + scopeCtx.onEvent(new RequestStart(this)); + Map<String, AtomicComponent> contexts = MockFactory.createWiredComponents("source", + OrderedDependentPojoImpl.class, + scopeCtx, + "target", + OrderedInitPojoImpl.class, + scopeCtx); + AtomicComponent sourceComponent = contexts.get("source"); + AtomicComponent targetComponent = contexts.get("target"); + scopeCtx.register(sourceComponent); + scopeCtx.register(targetComponent); + OrderedDependentPojo source = (OrderedDependentPojo) scopeCtx.getInstance(sourceComponent); + assertNotNull(source.getPojo()); + assertEquals(2, source.getNumberInstantiated()); + scopeCtx.onEvent(new RequestEnd(this)); + assertEquals(0, source.getNumberInstantiated()); + scopeCtx.stop(); + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/component/scope/HttpSessionScopeInstanceLifecycleTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/component/scope/HttpSessionScopeInstanceLifecycleTestCase.java new file mode 100644 index 0000000000..4fe99e841c --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/component/scope/HttpSessionScopeInstanceLifecycleTestCase.java @@ -0,0 +1,165 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.component.scope; + +import org.apache.tuscany.spi.component.WorkContext; +import org.apache.tuscany.spi.component.SystemAtomicComponent; + +import junit.framework.Assert; +import junit.framework.TestCase; +import org.apache.tuscany.core.component.WorkContextImpl; +import org.apache.tuscany.core.component.event.HttpSessionEnd; +import org.apache.tuscany.core.component.event.HttpSessionStart; +import org.apache.tuscany.core.mock.component.OrderedEagerInitPojo; +import org.apache.tuscany.core.mock.component.OrderedInitPojo; +import org.apache.tuscany.core.mock.component.OrderedInitPojoImpl; +import org.apache.tuscany.core.mock.component.RequestScopeDestroyOnlyComponent; +import org.apache.tuscany.core.mock.component.RequestScopeInitDestroyComponent; +import org.apache.tuscany.core.mock.component.RequestScopeInitOnlyComponent; +import org.apache.tuscany.core.mock.factories.MockFactory; + +/** + * Lifecycle unit tests for the module scope container + * + * @version $Rev$ $Date$ + */ +public class HttpSessionScopeInstanceLifecycleTestCase extends TestCase { + + public void testInitDestroy() throws Exception { + WorkContext ctx = new WorkContextImpl(); + HttpSessionScopeContainer scope = new HttpSessionScopeContainer(ctx); + scope.start(); + + SystemAtomicComponent initDestroyContext = MockFactory.createAtomicComponent("InitDestroy", + scope, + RequestScopeInitDestroyComponent.class); + initDestroyContext.start(); + + SystemAtomicComponent initOnlyContext = MockFactory.createAtomicComponent("InitOnly", + scope, + RequestScopeInitOnlyComponent.class); + initOnlyContext.start(); + + SystemAtomicComponent destroyOnlyContext = MockFactory.createAtomicComponent("DestroyOnly", + scope, + RequestScopeDestroyOnlyComponent.class); + destroyOnlyContext.start(); + + Object session = new Object(); + ctx.setIdentifier(HttpSessionScopeContainer.HTTP_IDENTIFIER, session); + scope.onEvent(new HttpSessionStart(this, session)); + RequestScopeInitDestroyComponent initDestroy = + (RequestScopeInitDestroyComponent) scope.getInstance(initDestroyContext); + Assert.assertNotNull(initDestroy); + + RequestScopeInitOnlyComponent initOnly = + (RequestScopeInitOnlyComponent) scope.getInstance(initOnlyContext); + Assert.assertNotNull(initOnly); + + RequestScopeDestroyOnlyComponent destroyOnly = + (RequestScopeDestroyOnlyComponent) scope.getInstance(destroyOnlyContext); + Assert.assertNotNull(destroyOnly); + + Assert.assertTrue(initDestroy.isInitialized()); + Assert.assertTrue(initOnly.isInitialized()); + Assert.assertFalse(initDestroy.isDestroyed()); + Assert.assertFalse(destroyOnly.isDestroyed()); + + // expire module + scope.onEvent(new HttpSessionEnd(this, session)); + + Assert.assertTrue(initDestroy.isDestroyed()); + Assert.assertTrue(destroyOnly.isDestroyed()); + + scope.stop(); + } + + public void testDestroyOrder() throws Exception { + WorkContext ctx = new WorkContextImpl(); + HttpSessionScopeContainer scope = new HttpSessionScopeContainer(ctx); + scope.start(); + + SystemAtomicComponent oneCtx = + MockFactory.createAtomicComponent("one", scope, OrderedInitPojoImpl.class); + scope.register(oneCtx); + SystemAtomicComponent twoCtx = + MockFactory.createAtomicComponent("two", scope, OrderedInitPojoImpl.class); + scope.register(twoCtx); + SystemAtomicComponent threeCtx = + MockFactory.createAtomicComponent("three", scope, OrderedInitPojoImpl.class); + scope.register(threeCtx); + + Object session = new Object(); + ctx.setIdentifier(HttpSessionScopeContainer.HTTP_IDENTIFIER, session); + scope.onEvent(new HttpSessionStart(this, session)); + OrderedInitPojo one = (OrderedInitPojo) scope.getInstance(oneCtx); + Assert.assertNotNull(one); + Assert.assertEquals(1, one.getNumberInstantiated()); + Assert.assertEquals(1, one.getInitOrder()); + + OrderedInitPojo two = (OrderedInitPojo) scope.getInstance(twoCtx); + Assert.assertNotNull(two); + Assert.assertEquals(2, two.getNumberInstantiated()); + Assert.assertEquals(2, two.getInitOrder()); + + OrderedInitPojo three = (OrderedInitPojo) scope.getInstance(threeCtx); + Assert.assertNotNull(three); + Assert.assertEquals(3, three.getNumberInstantiated()); + Assert.assertEquals(3, three.getInitOrder()); + + // expire module + scope.onEvent(new HttpSessionEnd(this, session)); + Assert.assertEquals(0, one.getNumberInstantiated()); + scope.stop(); + } + + public void testEagerInitDestroyOrder() throws Exception { + WorkContext ctx = new WorkContextImpl(); + HttpSessionScopeContainer scope = new HttpSessionScopeContainer(ctx); + scope.start(); + + SystemAtomicComponent oneCtx = + MockFactory.createAtomicComponent("one", scope, OrderedEagerInitPojo.class); + scope.register(oneCtx); + SystemAtomicComponent twoCtx = + MockFactory.createAtomicComponent("two", scope, OrderedEagerInitPojo.class); + scope.register(twoCtx); + SystemAtomicComponent threeCtx = + MockFactory.createAtomicComponent("three", scope, OrderedEagerInitPojo.class); + scope.register(threeCtx); + + Object session = new Object(); + ctx.setIdentifier(HttpSessionScopeContainer.HTTP_IDENTIFIER, session); + scope.onEvent(new HttpSessionStart(this, session)); + OrderedEagerInitPojo one = (OrderedEagerInitPojo) scope.getInstance(oneCtx); + Assert.assertNotNull(one); + + OrderedEagerInitPojo two = (OrderedEagerInitPojo) scope.getInstance(twoCtx); + Assert.assertNotNull(two); + + OrderedEagerInitPojo three = (OrderedEagerInitPojo) scope.getInstance(threeCtx); + Assert.assertNotNull(three); + + // expire module + scope.onEvent(new HttpSessionEnd(this, session)); + Assert.assertEquals(0, one.getNumberInstantiated()); + scope.stop(); + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/component/scope/HttpSessionScopeRestartTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/component/scope/HttpSessionScopeRestartTestCase.java new file mode 100644 index 0000000000..0c781cac85 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/component/scope/HttpSessionScopeRestartTestCase.java @@ -0,0 +1,104 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.component.scope; + +import java.lang.reflect.Constructor; + +import org.apache.tuscany.spi.component.WorkContext; + +import junit.framework.TestCase; +import org.apache.tuscany.core.component.WorkContextImpl; +import org.apache.tuscany.core.component.event.HttpSessionEnd; +import org.apache.tuscany.core.component.event.HttpSessionStart; +import org.apache.tuscany.core.implementation.PojoConfiguration; +import org.apache.tuscany.spi.component.SystemAtomicComponent; +import org.apache.tuscany.core.implementation.system.component.SystemAtomicComponentImpl; +import org.apache.tuscany.core.injection.MethodEventInvoker; +import org.apache.tuscany.core.injection.PojoObjectFactory; + +/** + * Verifies the scope container properly disposes resources and canbe restarted + * + * @version $$Rev$$ $$Date$$ + */ +public class HttpSessionScopeRestartTestCase extends TestCase { + + public void testRestart() throws Exception { + WorkContext ctx = new WorkContextImpl(); + HttpSessionScopeContainer scope = new HttpSessionScopeContainer(ctx); + scope.start(); + MethodEventInvoker<Object> initInvoker = new MethodEventInvoker<Object>( + HttpSessionScopeRestartTestCase.InitDestroyOnce.class.getMethod("init")); + MethodEventInvoker<Object> destroyInvoker = + new MethodEventInvoker<Object>(InitDestroyOnce.class.getMethod("destroy")); + PojoConfiguration configuration = new PojoConfiguration(); + configuration.setScopeContainer(scope); + configuration.addServiceInterface(HttpSessionScopeRestartTestCase.InitDestroyOnce.class); + configuration.setInitInvoker(initInvoker); + configuration.setDestroyInvoker(destroyInvoker); + Constructor<InitDestroyOnce> ctr = InitDestroyOnce.class.getConstructor((Class<?>[]) null); + configuration.setInstanceFactory(new PojoObjectFactory<InitDestroyOnce>(ctr)); + SystemAtomicComponent context = new SystemAtomicComponentImpl("InitDestroy", configuration); + context.start(); + + Object session = new Object(); + ctx.setIdentifier(HttpSessionScopeContainer.HTTP_IDENTIFIER, session); + scope.onEvent(new HttpSessionStart(this, session)); + Object instance = context.getServiceInstance(); + assertSame(instance, context.getServiceInstance()); + + scope.onEvent(new HttpSessionEnd(this, session)); + scope.stop(); + context.stop(); + + scope.start(); + scope.onEvent(new HttpSessionStart(this, session)); + context.start(); + assertNotSame(instance, context.getServiceInstance()); + scope.onEvent(new HttpSessionEnd(this, session)); + scope.stop(); + context.stop(); + } + + public static class InitDestroyOnce { + + private boolean initialized; + private boolean destroyed; + + public InitDestroyOnce() { + } + + public void init() { + if (!initialized) { + initialized = true; + } else { + fail("Scope did not clean up properly - Init called more than once"); + } + } + + public void destroy() { + if (!destroyed) { + destroyed = true; + } else { + fail("Scope did not clean up properly - Destroyed called more than once"); + } + } + + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/component/scope/InstanceWrapperTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/component/scope/InstanceWrapperTestCase.java new file mode 100644 index 0000000000..5071196d5e --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/component/scope/InstanceWrapperTestCase.java @@ -0,0 +1,68 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.component.scope; + +import org.apache.tuscany.spi.Lifecycle; +import org.apache.tuscany.spi.component.AtomicComponent; + +import junit.framework.TestCase; +import org.easymock.EasyMock; + +/** + * @version $Rev$ $Date$ + */ +public class InstanceWrapperTestCase extends TestCase { + + + public void testExceptionInit() throws Exception { + AtomicComponent component = getComponent(); + InstanceWrapper wrapper = new InstanceWrapperImpl(component, new Object()); + try { + wrapper.start(); + fail(); + } catch (SomeException e) { + // expected + } + assertEquals(Lifecycle.ERROR, wrapper.getLifecycleState()); + EasyMock.verify(component); + } + + public void testNonStart() throws Exception { + AtomicComponent comp = EasyMock.createNiceMock(AtomicComponent.class); // class-level one has an expects + InstanceWrapper wrapper = new InstanceWrapperImpl(comp, new Object()); + try { + wrapper.getInstance(); + fail(); + } catch (IllegalStateException e) { + // expected + } + } + + private AtomicComponent getComponent() throws Exception { + // do not use setUp() since we do not need this in all testcases + AtomicComponent comp = EasyMock.createMock(AtomicComponent.class); + comp.init(EasyMock.isA(Object.class)); + EasyMock.expectLastCall().andThrow(new SomeException()); + EasyMock.replay(comp); + return comp; + } + + private class SomeException extends RuntimeException { + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/component/scope/ModuleScopeInstanceLifecycleTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/component/scope/ModuleScopeInstanceLifecycleTestCase.java new file mode 100644 index 0000000000..fce04967fc --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/component/scope/ModuleScopeInstanceLifecycleTestCase.java @@ -0,0 +1,165 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.component.scope; + + +import org.apache.tuscany.spi.component.WorkContext; +import org.apache.tuscany.spi.component.SystemAtomicComponent; + +import junit.framework.Assert; +import junit.framework.TestCase; +import org.apache.tuscany.core.component.WorkContextImpl; +import org.apache.tuscany.core.component.event.CompositeStart; +import org.apache.tuscany.core.component.event.CompositeStop; +import org.apache.tuscany.core.mock.component.ModuleScopeDestroyOnlyComponent; +import org.apache.tuscany.core.mock.component.ModuleScopeInitDestroyComponent; +import org.apache.tuscany.core.mock.component.ModuleScopeInitOnlyComponent; +import org.apache.tuscany.core.mock.component.OrderedEagerInitPojo; +import org.apache.tuscany.core.mock.component.OrderedInitPojo; +import org.apache.tuscany.core.mock.component.OrderedInitPojoImpl; +import org.apache.tuscany.core.mock.factories.MockFactory; + +/** + * Lifecycle unit tests for the module scope container + * + * @version $Rev$ $Date$ + */ +public class ModuleScopeInstanceLifecycleTestCase extends TestCase { + + public void testInitDestroy() throws Exception { + WorkContext ctx = new WorkContextImpl(); + ModuleScopeContainer scope = new ModuleScopeContainer(ctx); + scope.start(); + + SystemAtomicComponent initDestroyContext = MockFactory.createAtomicComponent("InitDestroy", + scope, + ModuleScopeInitDestroyComponent.class); + initDestroyContext.start(); + + SystemAtomicComponent initOnlyContext = MockFactory.createAtomicComponent("InitOnly", + scope, + ModuleScopeInitOnlyComponent.class); + initOnlyContext.start(); + + SystemAtomicComponent destroyOnlyContext = MockFactory.createAtomicComponent("DestroyOnly", + scope, + ModuleScopeDestroyOnlyComponent.class); + destroyOnlyContext.start(); + + scope.onEvent(new CompositeStart(this, null)); + ModuleScopeInitDestroyComponent initDestroy = + (ModuleScopeInitDestroyComponent) scope.getInstance(initDestroyContext); + Assert.assertNotNull(initDestroy); + + ModuleScopeInitOnlyComponent initOnly = (ModuleScopeInitOnlyComponent) scope.getInstance(initOnlyContext); + Assert.assertNotNull(initOnly); + + ModuleScopeDestroyOnlyComponent destroyOnly = + (ModuleScopeDestroyOnlyComponent) scope.getInstance(destroyOnlyContext); + Assert.assertNotNull(destroyOnly); + + Assert.assertTrue(initDestroy.isInitialized()); + Assert.assertTrue(initOnly.isInitialized()); + Assert.assertFalse(initDestroy.isDestroyed()); + Assert.assertFalse(destroyOnly.isDestroyed()); + + // expire module + scope.onEvent(new CompositeStop(this, null)); + + Assert.assertTrue(initDestroy.isDestroyed()); + Assert.assertTrue(destroyOnly.isDestroyed()); + + scope.stop(); + } + + public void testDestroyOrder() throws Exception { + WorkContext ctx = new WorkContextImpl(); + ModuleScopeContainer scope = new ModuleScopeContainer(ctx); + scope.start(); + + SystemAtomicComponent oneCtx = MockFactory.createAtomicComponent("one", + scope, + OrderedInitPojoImpl.class); + scope.register(oneCtx); + SystemAtomicComponent twoCtx = MockFactory.createAtomicComponent("two", + scope, + OrderedInitPojoImpl.class); + scope.register(twoCtx); + SystemAtomicComponent threeCtx = MockFactory.createAtomicComponent("three", + scope, + OrderedInitPojoImpl.class); + scope.register(threeCtx); + + scope.onEvent(new CompositeStart(this, null)); + OrderedInitPojo one = (OrderedInitPojo) scope.getInstance(oneCtx); + Assert.assertNotNull(one); + Assert.assertEquals(1, one.getNumberInstantiated()); + Assert.assertEquals(1, one.getInitOrder()); + + OrderedInitPojo two = (OrderedInitPojo) scope.getInstance(twoCtx); + Assert.assertNotNull(two); + Assert.assertEquals(2, two.getNumberInstantiated()); + Assert.assertEquals(2, two.getInitOrder()); + + OrderedInitPojo three = (OrderedInitPojo) scope.getInstance(threeCtx); + Assert.assertNotNull(three); + Assert.assertEquals(3, three.getNumberInstantiated()); + Assert.assertEquals(3, three.getInitOrder()); + + // expire module + scope.onEvent(new CompositeStop(this, null)); + Assert.assertEquals(0, one.getNumberInstantiated()); + scope.stop(); + } + + public void testEagerInitDestroyOrder() throws Exception { + WorkContext ctx = new WorkContextImpl(); + ModuleScopeContainer scope = new ModuleScopeContainer(ctx); + scope.start(); + + SystemAtomicComponent oneCtx = MockFactory.createAtomicComponent("one", + scope, + OrderedEagerInitPojo.class); + scope.register(oneCtx); + SystemAtomicComponent twoCtx = MockFactory.createAtomicComponent("two", + scope, + OrderedEagerInitPojo.class); + scope.register(twoCtx); + SystemAtomicComponent threeCtx = MockFactory.createAtomicComponent("three", + scope, + OrderedEagerInitPojo.class); + scope.register(threeCtx); + + scope.onEvent(new CompositeStart(this, null)); + OrderedEagerInitPojo one = (OrderedEagerInitPojo) scope.getInstance(oneCtx); + Assert.assertNotNull(one); + + OrderedEagerInitPojo two = (OrderedEagerInitPojo) scope.getInstance(twoCtx); + Assert.assertNotNull(two); + + OrderedEagerInitPojo three = (OrderedEagerInitPojo) scope.getInstance(threeCtx); + Assert.assertNotNull(three); + + // expire module + scope.onEvent(new CompositeStop(this, null)); + Assert.assertEquals(0, one.getNumberInstantiated()); + scope.stop(); + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/component/scope/ModuleScopeObjectFactoryTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/component/scope/ModuleScopeObjectFactoryTestCase.java new file mode 100644 index 0000000000..69ebc96d95 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/component/scope/ModuleScopeObjectFactoryTestCase.java @@ -0,0 +1,38 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.component.scope; + +import org.apache.tuscany.spi.component.ScopeRegistry; +import org.apache.tuscany.spi.model.Scope; + +import junit.framework.TestCase; +import org.easymock.EasyMock; + +/** + * @version $Rev$ $Date$ + */ +public class ModuleScopeObjectFactoryTestCase extends TestCase { + + public void testCreation() { + ScopeRegistry registry = EasyMock.createMock(ScopeRegistry.class); + registry.registerFactory(EasyMock.isA(Scope.class), EasyMock.isA(ModuleScopeObjectFactory.class)); + + assertNotNull(new ModuleScopeObjectFactory(registry).getInstance()); + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/component/scope/ModuleScopeRestartTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/component/scope/ModuleScopeRestartTestCase.java new file mode 100644 index 0000000000..4c57b81953 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/component/scope/ModuleScopeRestartTestCase.java @@ -0,0 +1,102 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.component.scope; + +import java.lang.reflect.Constructor; + +import org.apache.tuscany.spi.component.WorkContext; + +import junit.framework.TestCase; +import org.apache.tuscany.core.component.WorkContextImpl; +import org.apache.tuscany.core.component.event.CompositeStart; +import org.apache.tuscany.core.component.event.CompositeStop; +import org.apache.tuscany.core.implementation.PojoConfiguration; +import org.apache.tuscany.spi.component.SystemAtomicComponent; +import org.apache.tuscany.core.implementation.system.component.SystemAtomicComponentImpl; +import org.apache.tuscany.core.injection.MethodEventInvoker; +import org.apache.tuscany.core.injection.PojoObjectFactory; + +/** + * Verifies the scope container properly disposes resources and canbe restarted + * + * @version $$Rev$$ $$Date$$ + */ +public class ModuleScopeRestartTestCase extends TestCase { + + public void testRestart() throws Exception { + WorkContext ctx = new WorkContextImpl(); + ModuleScopeContainer scope = new ModuleScopeContainer(ctx); + scope.start(); + MethodEventInvoker<Object> initInvoker = + new MethodEventInvoker<Object>(InitDestroyOnce.class.getMethod("init")); + MethodEventInvoker<Object> destroyInvoker = + new MethodEventInvoker<Object>(InitDestroyOnce.class.getMethod("destroy")); + PojoConfiguration configuration = new PojoConfiguration(); + configuration.setScopeContainer(scope); + configuration.addServiceInterface(InitDestroyOnce.class); + configuration.setInitInvoker(initInvoker); + configuration.setDestroyInvoker(destroyInvoker); + Constructor<InitDestroyOnce> ctr = InitDestroyOnce.class.getConstructor((Class<?>[]) null); + configuration.setInstanceFactory(new PojoObjectFactory<InitDestroyOnce>(ctr)); + SystemAtomicComponent context = new SystemAtomicComponentImpl("InitDestroy", configuration); + context.start(); + + scope.onEvent(new CompositeStart(this, null)); + Object instance = context.getServiceInstance(); + assertSame(instance, context.getServiceInstance()); + + scope.onEvent(new CompositeStop(this, null)); + scope.stop(); + context.stop(); + + scope.start(); + scope.onEvent(new CompositeStart(this, null)); + context.start(); + assertNotSame(instance, context.getServiceInstance()); + scope.onEvent(new CompositeStop(this, null)); + scope.stop(); + context.stop(); + } + + public static class InitDestroyOnce { + + private boolean initialized; + private boolean destroyed; + + public InitDestroyOnce() { + } + + public void init() { + if (!initialized) { + initialized = true; + } else { + fail("Scope did not clean up properly - Init called more than once"); + } + } + + public void destroy() { + if (!destroyed) { + destroyed = true; + } else { + fail("Scope did not clean up properly - Destroyed called more than once"); + } + } + + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/component/scope/RequestScopeInstanceLifecycleTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/component/scope/RequestScopeInstanceLifecycleTestCase.java new file mode 100644 index 0000000000..52f27ee869 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/component/scope/RequestScopeInstanceLifecycleTestCase.java @@ -0,0 +1,155 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.component.scope; + +import org.apache.tuscany.spi.component.WorkContext; +import org.apache.tuscany.spi.component.SystemAtomicComponent; + +import junit.framework.Assert; +import junit.framework.TestCase; +import org.apache.tuscany.core.component.WorkContextImpl; +import org.apache.tuscany.core.component.event.RequestEnd; +import org.apache.tuscany.core.component.event.RequestStart; +import org.apache.tuscany.core.mock.component.OrderedEagerInitPojo; +import org.apache.tuscany.core.mock.component.OrderedInitPojo; +import org.apache.tuscany.core.mock.component.OrderedInitPojoImpl; +import org.apache.tuscany.core.mock.component.RequestScopeDestroyOnlyComponent; +import org.apache.tuscany.core.mock.component.RequestScopeInitDestroyComponent; +import org.apache.tuscany.core.mock.component.RequestScopeInitOnlyComponent; +import org.apache.tuscany.core.mock.factories.MockFactory; + +/** + * Lifecycle unit tests for the module scope container + * + * @version $Rev$ $Date$ + */ +public class RequestScopeInstanceLifecycleTestCase extends TestCase { + + public void testInitDestroy() throws Exception { + WorkContext ctx = new WorkContextImpl(); + RequestScopeContainer scope = new RequestScopeContainer(ctx); + scope.start(); + + SystemAtomicComponent initDestroyContext = MockFactory + .createAtomicComponent("InitDestroy", scope, RequestScopeInitDestroyComponent.class); + initDestroyContext.start(); + + SystemAtomicComponent initOnlyContext = + MockFactory.createAtomicComponent("InitOnly", scope, RequestScopeInitOnlyComponent.class); + initOnlyContext.start(); + + SystemAtomicComponent destroyOnlyContext = MockFactory + .createAtomicComponent("DestroyOnly", scope, RequestScopeDestroyOnlyComponent.class); + destroyOnlyContext.start(); + + scope.onEvent(new RequestStart(this)); + RequestScopeInitDestroyComponent initDestroy = + (RequestScopeInitDestroyComponent) scope.getInstance(initDestroyContext); + Assert.assertNotNull(initDestroy); + + RequestScopeInitOnlyComponent initOnly = (RequestScopeInitOnlyComponent) scope.getInstance(initOnlyContext); + Assert.assertNotNull(initOnly); + + RequestScopeDestroyOnlyComponent destroyOnly = + (RequestScopeDestroyOnlyComponent) scope.getInstance(destroyOnlyContext); + Assert.assertNotNull(destroyOnly); + + Assert.assertTrue(initDestroy.isInitialized()); + Assert.assertTrue(initOnly.isInitialized()); + Assert.assertFalse(initDestroy.isDestroyed()); + Assert.assertFalse(destroyOnly.isDestroyed()); + + // expire module + scope.onEvent(new RequestEnd(this)); + + Assert.assertTrue(initDestroy.isDestroyed()); + Assert.assertTrue(destroyOnly.isDestroyed()); + + scope.stop(); + } + + public void testDestroyOrder() throws Exception { + WorkContext ctx = new WorkContextImpl(); + RequestScopeContainer scope = new RequestScopeContainer(ctx); + scope.start(); + + SystemAtomicComponent oneCtx = + MockFactory.createAtomicComponent("one", scope, OrderedInitPojoImpl.class); + scope.register(oneCtx); + SystemAtomicComponent twoCtx = + MockFactory.createAtomicComponent("two", scope, OrderedInitPojoImpl.class); + scope.register(twoCtx); + SystemAtomicComponent threeCtx = + MockFactory.createAtomicComponent("three", scope, OrderedInitPojoImpl.class); + scope.register(threeCtx); + + scope.onEvent(new RequestStart(this)); + OrderedInitPojo one = (OrderedInitPojo) scope.getInstance(oneCtx); + Assert.assertNotNull(one); + Assert.assertEquals(1, one.getNumberInstantiated()); + Assert.assertEquals(1, one.getInitOrder()); + + OrderedInitPojo two = (OrderedInitPojo) scope.getInstance(twoCtx); + Assert.assertNotNull(two); + Assert.assertEquals(2, two.getNumberInstantiated()); + Assert.assertEquals(2, two.getInitOrder()); + + OrderedInitPojo three = (OrderedInitPojo) scope.getInstance(threeCtx); + Assert.assertNotNull(three); + Assert.assertEquals(3, three.getNumberInstantiated()); + Assert.assertEquals(3, three.getInitOrder()); + + // expire module + scope.onEvent(new RequestEnd(this)); + Assert.assertEquals(0, one.getNumberInstantiated()); + scope.stop(); + } + + public void testEagerInitDestroyOrder() throws Exception { + WorkContext ctx = new WorkContextImpl(); + RequestScopeContainer scope = new RequestScopeContainer(ctx); + scope.start(); + + SystemAtomicComponent oneCtx = + MockFactory.createAtomicComponent("one", scope, OrderedEagerInitPojo.class); + scope.register(oneCtx); + SystemAtomicComponent twoCtx = + MockFactory.createAtomicComponent("two", scope, OrderedEagerInitPojo.class); + scope.register(twoCtx); + SystemAtomicComponent threeCtx = + MockFactory.createAtomicComponent("three", scope, OrderedEagerInitPojo.class); + scope.register(threeCtx); + + scope.onEvent(new RequestStart(this)); + OrderedEagerInitPojo one = (OrderedEagerInitPojo) scope.getInstance(oneCtx); + Assert.assertNotNull(one); + + OrderedEagerInitPojo two = (OrderedEagerInitPojo) scope.getInstance(twoCtx); + Assert.assertNotNull(two); + + OrderedEagerInitPojo three = (OrderedEagerInitPojo) scope.getInstance(threeCtx); + Assert.assertNotNull(three); + + // expire module + scope.onEvent(new RequestEnd(this)); + Assert.assertEquals(0, one.getNumberInstantiated()); + scope.stop(); + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/component/scope/RequestScopeRestartTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/component/scope/RequestScopeRestartTestCase.java new file mode 100644 index 0000000000..b4b835e742 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/component/scope/RequestScopeRestartTestCase.java @@ -0,0 +1,99 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.component.scope; + +import java.lang.reflect.Constructor; + +import org.apache.tuscany.spi.component.WorkContext; + +import junit.framework.TestCase; +import org.apache.tuscany.core.component.WorkContextImpl; +import org.apache.tuscany.core.component.event.RequestEnd; +import org.apache.tuscany.core.implementation.PojoConfiguration; +import org.apache.tuscany.spi.component.SystemAtomicComponent; +import org.apache.tuscany.core.implementation.system.component.SystemAtomicComponentImpl; +import org.apache.tuscany.core.injection.MethodEventInvoker; +import org.apache.tuscany.core.injection.PojoObjectFactory; + +/** + * Verifies the scope container properly disposes resources and canbe restarted + * + * @version $$Rev$$ $$Date$$ + */ +public class RequestScopeRestartTestCase extends TestCase { + + public void testRestart() throws Exception { + WorkContext ctx = new WorkContextImpl(); + RequestScopeContainer scope = new RequestScopeContainer(ctx); + scope.start(); + MethodEventInvoker<Object> initInvoker = + new MethodEventInvoker<Object>(InitDestroyOnce.class.getMethod("init")); + MethodEventInvoker<Object> destroyInvoker = + new MethodEventInvoker<Object>(InitDestroyOnce.class.getMethod("destroy")); + PojoConfiguration configuration = new PojoConfiguration(); + configuration.setScopeContainer(scope); + configuration.addServiceInterface(InitDestroyOnce.class); + configuration.setInitInvoker(initInvoker); + configuration.setDestroyInvoker(destroyInvoker); + Constructor<InitDestroyOnce> ctr = InitDestroyOnce.class.getConstructor((Class<?>[]) null); + configuration.setInstanceFactory(new PojoObjectFactory<InitDestroyOnce>(ctr)); + SystemAtomicComponent context = new SystemAtomicComponentImpl("InitDestroy", configuration); + context.start(); + + Object instance = context.getServiceInstance(); + assertSame(instance, context.getServiceInstance()); + + scope.onEvent(new RequestEnd(this)); + scope.stop(); + context.stop(); + + scope.start(); + context.start(); + assertNotSame(instance, context.getServiceInstance()); + scope.onEvent(new RequestEnd(this)); + scope.stop(); + context.stop(); + } + + public static class InitDestroyOnce { + + private boolean initialized; + private boolean destroyed; + + public InitDestroyOnce() { + } + + public void init() { + if (!initialized) { + initialized = true; + } else { + fail("Scope did not clean up properly - Init called more than once"); + } + } + + public void destroy() { + if (!destroyed) { + destroyed = true; + } else { + fail("Scope did not clean up properly - Destroyed called more than once"); + } + } + + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/component/scope/ScopeRegistryTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/component/scope/ScopeRegistryTestCase.java new file mode 100644 index 0000000000..d6000dd8c4 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/component/scope/ScopeRegistryTestCase.java @@ -0,0 +1,88 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.component.scope; + +import org.apache.tuscany.spi.component.ScopeContainer; +import org.apache.tuscany.spi.component.ScopeNotFoundException; +import org.apache.tuscany.spi.component.ScopeRegistry; +import org.apache.tuscany.spi.component.WorkContext; +import org.apache.tuscany.spi.model.Scope; + +import junit.framework.TestCase; +import org.apache.tuscany.core.component.WorkContextImpl; + +/** + * Verifies retrieval of standard scope contexts from the default scope registry + * + * @version $$Rev$$ $$Date$$ + */ +public class ScopeRegistryTestCase extends TestCase { + public void testScopeContextCreation() throws Exception { + WorkContext workContext = new WorkContextImpl(); + ScopeRegistry scopeRegistry = new ScopeRegistryImpl(workContext); + scopeRegistry.registerFactory(Scope.REQUEST, new RequestScopeObjectFactory()); + scopeRegistry.registerFactory(Scope.SESSION, new HttpSessionScopeObjectFactory(scopeRegistry)); + ScopeContainer request = scopeRegistry.getScopeContainer(Scope.REQUEST); + assertTrue(request instanceof RequestScopeContainer); + assertSame(request, scopeRegistry.getScopeContainer(Scope.REQUEST)); + ScopeContainer session = scopeRegistry.getScopeContainer(Scope.SESSION); + assertTrue(session instanceof HttpSessionScopeContainer); + assertSame(session, scopeRegistry.getScopeContainer(Scope.SESSION)); + assertNotSame(request, session); + } + + public void testDeregisterFactory() throws Exception { + WorkContext workContext = new WorkContextImpl(); + ScopeRegistry scopeRegistry = new ScopeRegistryImpl(workContext); + RequestScopeObjectFactory factory = new RequestScopeObjectFactory(); + scopeRegistry.registerFactory(Scope.REQUEST, factory); + scopeRegistry.deregisterFactory(Scope.REQUEST); + try { + scopeRegistry.getScopeContainer(Scope.REQUEST); + fail(); + } catch (ScopeNotFoundException e) { + // expected + } + } + + public void testScopeNotRegistered() throws Exception { + WorkContext workContext = new WorkContextImpl(); + ScopeRegistry scopeRegistry = new ScopeRegistryImpl(workContext); + try { + scopeRegistry.getScopeContainer(Scope.REQUEST); + fail(); + } catch (ScopeNotFoundException e) { + // expected + } + try { + scopeRegistry.getScopeContainer(Scope.SESSION); + fail(); + } catch (ScopeNotFoundException e) { + // expected + } + try { + scopeRegistry.getScopeContainer(Scope.STATELESS); + fail(); + } catch (ScopeNotFoundException e) { + // expected + } + } + + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/component/scope/StatelessScopeContainerTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/component/scope/StatelessScopeContainerTestCase.java new file mode 100644 index 0000000000..c69ce63b8b --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/component/scope/StatelessScopeContainerTestCase.java @@ -0,0 +1,48 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.component.scope; + +import junit.framework.TestCase; + +/** + * @version $Rev$ $Date$ + */ +public class StatelessScopeContainerTestCase extends TestCase { + + public void testBadStopWithoutStart() throws Exception { + StatelessScopeContainer container = new StatelessScopeContainer(); + try { + container.stop(); + fail(); + } catch (IllegalStateException e) { + //expected + } + } + + public void testBadDoubleStart() throws Exception { + StatelessScopeContainer container = new StatelessScopeContainer(); + try { + container.start(); + container.start(); + fail(); + } catch (IllegalStateException e) { + //expected + } + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/component/scope/StatelessScopeObjectFactoryTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/component/scope/StatelessScopeObjectFactoryTestCase.java new file mode 100644 index 0000000000..75f1682713 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/component/scope/StatelessScopeObjectFactoryTestCase.java @@ -0,0 +1,37 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.component.scope; + +import org.apache.tuscany.spi.component.ScopeRegistry; +import org.apache.tuscany.spi.model.Scope; + +import junit.framework.TestCase; +import org.easymock.EasyMock; + +/** + * @version $Rev$ $Date$ + */ +public class StatelessScopeObjectFactoryTestCase extends TestCase { + + public void testCreation() { + ScopeRegistry registry = EasyMock.createMock(ScopeRegistry.class); + registry.registerFactory(EasyMock.isA(Scope.class), EasyMock.isA(StatelessScopeObjectFactory.class)); + assertNotNull(new StatelessScopeObjectFactory(registry).getInstance()); + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/component/scope/WorkContextTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/component/scope/WorkContextTestCase.java new file mode 100644 index 0000000000..456bb5be78 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/component/scope/WorkContextTestCase.java @@ -0,0 +1,142 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.component.scope; + +import org.apache.tuscany.spi.component.CompositeComponent; +import org.apache.tuscany.spi.component.WorkContext; + +import junit.framework.TestCase; +import org.apache.tuscany.core.component.WorkContextImpl; +import org.easymock.EasyMock; + +/** + * @version $Rev$ $Date$ + */ +public class WorkContextTestCase extends TestCase { + + public void testRemoteComponent() throws Exception { + WorkContext ctx = new WorkContextImpl(); + CompositeComponent component = EasyMock.createNiceMock(CompositeComponent.class); + CompositeComponent component2 = EasyMock.createNiceMock(CompositeComponent.class); + ctx.setRemoteComponent(component); + assertEquals(component, ctx.getRemoteComponent()); + ctx.setRemoteComponent(component2); + assertEquals(component2, ctx.getRemoteComponent()); + } + + public void testNonSetRemoteComponent() throws Exception { + WorkContext ctx = new WorkContextImpl(); + assertNull(ctx.getRemoteComponent()); + } + + public void testIndentifier() throws Exception { + WorkContext ctx = new WorkContextImpl(); + Object id = new Object(); + ctx.setIdentifier(this, id); + assertEquals(id, ctx.getIdentifier(this)); + } + + public void testClearIndentifier() throws Exception { + WorkContext ctx = new WorkContextImpl(); + Object id = new Object(); + ctx.setIdentifier(this, id); + ctx.clearIdentifier(this); + assertNull(ctx.getIdentifier(this)); + } + + public void testClearIndentifiers() throws Exception { + WorkContext ctx = new WorkContextImpl(); + Object id = new Object(); + Object id2 = new Object(); + ctx.setIdentifier(id, id); + ctx.setIdentifier(id2, id2); + ctx.clearIdentifiers(); + assertNull(ctx.getIdentifier(id)); + assertNull(ctx.getIdentifier(id2)); + } + + public void testClearNonExistentIndentifier() throws Exception { + WorkContext ctx = new WorkContextImpl(); + ctx.clearIdentifier(this); + } + + public void testNullIndentifier() throws Exception { + WorkContext ctx = new WorkContextImpl(); + Object id = new Object(); + ctx.setIdentifier(this, id); + ctx.clearIdentifier(null); + assertEquals(id, ctx.getIdentifier(this)); + } + + public void testNoIndentifier() throws Exception { + WorkContext ctx = new WorkContextImpl(); + assertNull(ctx.getIdentifier(this)); + } + + public void testSetGetMessageIds() { + WorkContext context = new WorkContextImpl(); + context.setCurrentMessageId("msg-009"); + context.setCurrentCorrelationId("msg-005"); + assertEquals(context.getCurrentMessageId(), "msg-009"); + assertEquals(context.getCurrentCorrelationId(), "msg-005"); + context.setCurrentMessageId(null); + context.setCurrentCorrelationId(null); + assertNull(context.getCurrentMessageId()); + assertNull(context.getCurrentCorrelationId()); + } + + public void testSetGetMessageIdsInNewThread() throws InterruptedException { + WorkContext context = new WorkContextImpl(); + context.setCurrentMessageId("msg-009"); + context.setCurrentCorrelationId("msg-005"); + assertEquals(context.getCurrentMessageId(), "msg-009"); + assertEquals(context.getCurrentCorrelationId(), "msg-005"); + context.setIdentifier("TX", "002"); + ChildThread t = new ChildThread(context); + t.start(); + t.join(); + assertTrue(t.passed); + context.setCurrentMessageId(null); + context.setCurrentCorrelationId(null); + assertNull(context.getCurrentMessageId()); + assertNull(context.getCurrentCorrelationId()); + } + + private static class ChildThread extends Thread { + private WorkContext context; + private boolean passed = true; + + private ChildThread(WorkContext context) { + this.context = context; + } + + @Override + public void run() { + try { + assertNull(context.getCurrentMessageId()); + assertNull(context.getCurrentCorrelationId()); + assertEquals("002", context.getIdentifier("TX")); + } catch (AssertionError e) { + passed = false; + } + } + + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/databinding/impl/DataBindingInterceptorTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/databinding/impl/DataBindingInterceptorTestCase.java new file mode 100644 index 0000000000..720a3ef61e --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/databinding/impl/DataBindingInterceptorTestCase.java @@ -0,0 +1,135 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.tuscany.core.databinding.impl; + +import static org.easymock.EasyMock.createMock; +import static org.easymock.EasyMock.expect; +import static org.easymock.EasyMock.expectLastCall; +import static org.easymock.EasyMock.replay; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import junit.framework.Assert; +import junit.framework.TestCase; + +import org.apache.tuscany.spi.component.Component; +import org.apache.tuscany.spi.component.CompositeComponent; +import org.apache.tuscany.spi.databinding.Mediator; +import org.apache.tuscany.spi.model.DataType; +import org.apache.tuscany.spi.model.Operation; +import org.apache.tuscany.spi.wire.InboundWire; +import org.apache.tuscany.spi.wire.Interceptor; +import org.apache.tuscany.spi.wire.Message; +import org.apache.tuscany.spi.wire.OutboundWire; +import org.easymock.EasyMock; + +/** + * + */ +public class DataBindingInterceptorTestCase extends TestCase { + private DataBindingInteceptor interceptor; + + /** + * @see junit.framework.TestCase#setUp() + */ + protected void setUp() throws Exception { + super.setUp(); + } + + @SuppressWarnings("unchecked") + public final void testInvoke() { + DataType<Class> type1 = new DataType<Class>("xml:string", String.class, String.class); + List<DataType<Class>> types1 = new ArrayList<DataType<Class>>(); + types1.add(type1); + DataType<List<DataType<Class>>> inputType1 = + new DataType<List<DataType<Class>>>("xml:string", Object[].class, types1); + + DataType<Class> type2 = new DataType<Class>("foo", Foo.class, Foo.class); + List<DataType<Class>> types2 = new ArrayList<DataType<Class>>(); + types2.add(type2); + DataType<List<DataType<Class>>> inputType2 = + new DataType<List<DataType<Class>>>("foo", Object[].class, types2); + + Operation<Class> operation1 = + new Operation<Class>("call", inputType1, type1, null, false, "xml:string"); + Operation<Class> operation2 = + new Operation<Class>("call", inputType2, type2, null, false, "org.w3c.dom.Node"); + + DataType<DataType> outputType1 = + new DataType<DataType>("idl:output", Object.class, operation1.getOutputType()); + DataType<DataType> outputType2 = + new DataType<DataType>("idl:output", Object.class, operation2.getOutputType()); + + OutboundWire outboundWire = EasyMock.createMock(OutboundWire.class); + InboundWire inboundWire = EasyMock.createMock(InboundWire.class); + CompositeComponent composite = EasyMock.createMock(CompositeComponent.class); + Component component = EasyMock.createMock(Component.class); + EasyMock.expect(component.getParent()).andReturn(composite).once(); + EasyMock.expect(outboundWire.getContainer()).andReturn(component); + EasyMock.replay(outboundWire, inboundWire, composite, component); + + interceptor = new DataBindingInteceptor(outboundWire, operation1, inboundWire, operation2); + Mediator mediator = createMock(Mediator.class); + Object[] source = new Object[] {"<foo>bar</foo>"}; + Foo foo = new Foo(); + foo.bar = "bar"; + Object[] target = new Object[] {foo}; + expect(mediator.mediate(EasyMock.same(source), + EasyMock.same(inputType1), + EasyMock.same(inputType2), + EasyMock.isA(Map.class))).andReturn(target); + // expect(mediator.mediate(target[0], type2, + // type1)).andReturn(source[0]); + expect(mediator.mediate(EasyMock.same(target[0]), + EasyMock.eq(outputType2), + EasyMock.eq(outputType1), + EasyMock.isA(Map.class))).andReturn(source[0]); + replay(mediator); + interceptor.setMediator(mediator); + Message msg = createMock(Message.class); + msg.setBody(EasyMock.anyObject()); + expectLastCall().anyTimes(); + expect(msg.getBody()).andReturn(source).once().andReturn(target[0]).once().andReturn(source[0]); + expect(msg.isFault()).andReturn(false).once(); + replay(msg); + Interceptor next = createMock(Interceptor.class); + expect(next.invoke(msg)).andReturn(msg); + replay(next); + interceptor.setNext(next); + interceptor.invoke(msg); + String result = (String)msg.getBody(); + Assert.assertEquals(source[0], result); + EasyMock.verify(mediator, msg, next); + } + + private static class Foo { + private String bar; + + public String getBar() { + return bar; + } + + public void setBar(String bar) { + this.bar = bar; + } + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/databinding/impl/DataBindingJavaInterfaceProcessorTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/databinding/impl/DataBindingJavaInterfaceProcessorTestCase.java new file mode 100644 index 0000000000..6cbc8f01c2 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/databinding/impl/DataBindingJavaInterfaceProcessorTestCase.java @@ -0,0 +1,77 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.tuscany.core.databinding.impl; + +import java.lang.reflect.Type; +import java.util.HashMap; +import java.util.Map; + +import junit.framework.Assert; +import junit.framework.TestCase; + +import org.apache.tuscany.api.annotation.DataContext; +import org.apache.tuscany.api.annotation.DataType; +import org.apache.tuscany.spi.idl.InvalidServiceContractException; +import org.apache.tuscany.spi.idl.java.JavaServiceContract; +import org.apache.tuscany.spi.model.Operation; +import org.osoa.sca.annotations.Remotable; +import org.w3c.dom.Node; + +/** + * + */ +public class DataBindingJavaInterfaceProcessorTestCase extends TestCase { + + /** + * @see junit.framework.TestCase#setUp() + */ + protected void setUp() throws Exception { + super.setUp(); + } + + /** + * @throws InvalidServiceContractException + */ + public final void testVisitInterface() throws InvalidServiceContractException { + DataBindingJavaInterfaceProcessor processor = new DataBindingJavaInterfaceProcessor(); + JavaServiceContract contract = new JavaServiceContract(MockInterface.class); + Map<String, Operation<Type>> operations = new HashMap<String, Operation<Type>>(); + Operation<Type> operation = new Operation<Type>("call", null, null, null, false, null); + Operation<Type> operation1 = new Operation<Type>("call1", null, null, null, false, null); + operations.put("call", operation); + operations.put("call1", operation1); + contract.setOperations(operations); + processor.visitInterface(MockInterface.class, null, contract); + Assert.assertEquals("org.w3c.dom.Node", contract.getDataBinding()); + Assert.assertEquals("element", (String)contract.getMetaData().get("nodeType")); + Assert.assertEquals("org.w3c.dom.Node", contract.getOperations().get("call").getDataBinding()); + Assert.assertEquals("xml:string", contract.getOperations().get("call1").getDataBinding()); + } + + @DataType(name = "org.w3c.dom.Node", context = {@DataContext(key = "nodeType", value = "element")}) + @Remotable + public static interface MockInterface { + Node call(Node msg); + + @DataType(name = "xml:string") + String call1(String msg); + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/databinding/impl/DataBindingLoaderTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/databinding/impl/DataBindingLoaderTestCase.java new file mode 100644 index 0000000000..6941e10a0c --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/databinding/impl/DataBindingLoaderTestCase.java @@ -0,0 +1,79 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.tuscany.core.databinding.impl; + +import javax.xml.stream.XMLStreamConstants; +import javax.xml.stream.XMLStreamException; +import javax.xml.stream.XMLStreamReader; + +import junit.framework.Assert; +import junit.framework.TestCase; + +import org.apache.tuscany.spi.loader.InvalidValueException; +import org.apache.tuscany.spi.loader.LoaderException; +import org.apache.tuscany.spi.model.DataType; +import org.apache.tuscany.spi.model.ModelObject; +import org.easymock.EasyMock; + +/** + * Testcase for DataBindingLoader + */ +public class DataBindingLoaderTestCase extends TestCase { + private XMLStreamReader reader; + + /** + * @see junit.framework.TestCase#setUp() + */ + protected void setUp() throws Exception { + super.setUp(); + } + + public final void testLoad() throws LoaderException, XMLStreamException { + reader = EasyMock.createMock(XMLStreamReader.class); + // EasyMock.expect(reader.getEventType()).andReturn(XMLStreamConstants.START_ELEMENT); + EasyMock.expect(reader.hasNext()).andReturn(true).anyTimes(); + EasyMock.expect(reader.getName()).andReturn(DataTypeLoader.DATA_BINDING); + EasyMock.expect(reader.getAttributeValue(null, "name")).andReturn("ABC"); + EasyMock.expect(reader.next()).andReturn(XMLStreamConstants.END_ELEMENT); + EasyMock.replay(reader); + + ModelObject mo = new DataTypeLoader(null).load(null, reader, null); + Assert.assertTrue(mo instanceof DataType); + Assert.assertEquals("ABC", ((DataType<?>)mo).getDataBinding()); + EasyMock.verify(reader); + + EasyMock.reset(reader); + + // EasyMock.expect(reader.getEventType()).andReturn(XMLStreamConstants.START_ELEMENT); + EasyMock.expect(reader.hasNext()).andReturn(true).anyTimes(); + EasyMock.expect(reader.getName()).andReturn(DataTypeLoader.DATA_BINDING); + EasyMock.expect(reader.getAttributeValue(null, "name")).andReturn(null); + EasyMock.expect(reader.next()).andReturn(XMLStreamConstants.END_ELEMENT); + EasyMock.replay(reader); + try { + mo = new DataTypeLoader(null).load(null, reader, null); + Assert.fail("InvalidValueException should have been thrown"); + } catch (InvalidValueException e) { + Assert.assertTrue(true); + } + EasyMock.verify(reader); + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/databinding/impl/DataBindingRegistryImplTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/databinding/impl/DataBindingRegistryImplTestCase.java new file mode 100644 index 0000000000..30af31b1cb --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/databinding/impl/DataBindingRegistryImplTestCase.java @@ -0,0 +1,86 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.databinding.impl; + +import static org.easymock.EasyMock.createMock; +import static org.easymock.EasyMock.expect; +import static org.easymock.EasyMock.replay; + +import javax.xml.stream.XMLStreamReader; + +import junit.framework.Assert; +import junit.framework.TestCase; + +import org.apache.tuscany.spi.databinding.DataBinding; +import org.apache.tuscany.spi.databinding.DataBindingRegistry; +import org.apache.tuscany.spi.model.DataType; +import org.easymock.EasyMock; +import org.xml.sax.ContentHandler; + +/** + * + */ +public class DataBindingRegistryImplTestCase extends TestCase { + private DataBindingRegistry registry; + + /** + * @see junit.framework.TestCase#setUp() + */ + protected void setUp() throws Exception { + super.setUp(); + registry = new DataBindingRegistryImpl(); + } + + public void testRegistry() { + DataBinding db1 = createMock(DataBinding.class); + expect(db1.getName()).andReturn(ContentHandler.class.getName()).anyTimes(); + DataType<Class> dataType1 = new DataType<Class>(ContentHandler.class, ContentHandler.class); + expect(db1.introspect(ContentHandler.class)).andReturn(dataType1); + expect(db1.introspect((Class)EasyMock.anyObject())).andReturn(null).anyTimes(); + replay(db1); + + registry.register(db1); + + DataBinding db2 = createMock(DataBinding.class); + expect(db2.getName()).andReturn(XMLStreamReader.class.getName()).anyTimes(); + DataType<Class> dataType2 = new DataType<Class>(XMLStreamReader.class, XMLStreamReader.class); + expect(db2.introspect(XMLStreamReader.class)).andReturn(dataType2); + expect(db2.introspect((Class)EasyMock.anyObject())).andReturn(null).anyTimes(); + replay(db2); + + registry.register(db2); + + String name = db1.getName(); + DataBinding db3 = registry.getDataBinding(name); + Assert.assertTrue(db1 == db3); + + DataType<?> dt = registry.introspectType(ContentHandler.class); + Assert.assertEquals(dataType1, dt); + Assert.assertTrue(dt.getDataBinding().equalsIgnoreCase(name)); + + registry.unregister(name); + DataBinding db4 = registry.getDataBinding(name); + Assert.assertNull(db4); + + dt = registry.introspectType(ContentHandler.class); + Assert.assertNull(dt); + + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/databinding/impl/DataBindingTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/databinding/impl/DataBindingTestCase.java new file mode 100644 index 0000000000..de5c537274 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/databinding/impl/DataBindingTestCase.java @@ -0,0 +1,49 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.databinding.impl; + +import java.lang.reflect.Method; + +import junit.framework.Assert; +import junit.framework.TestCase; + +import org.apache.tuscany.api.annotation.DataContext; +import org.apache.tuscany.api.annotation.DataType; + +public class DataBindingTestCase extends TestCase { + @SuppressWarnings("unused") + public void testDataType() throws Exception { + Class<Test> testClass = Test.class; + DataType d = testClass.getAnnotation(DataType.class); + Assert.assertEquals(d.name(), "sdo"); + Assert.assertEquals(d.context().length, 0); + + Method method = testClass.getMethod("test", new Class[] {Object.class}); + DataType d2 = method.getAnnotation(DataType.class); + Assert.assertEquals(d2.name(), "jaxb"); + Assert.assertEquals(d2.context()[0].key(), "contextPath"); + Assert.assertEquals(d2.context()[0].value(), "com.example.ipo.jaxb"); + } + + @DataType(name = "sdo") + private static interface Test { + @DataType(name = "jaxb", context = {@DataContext(key = "contextPath", value = "com.example.ipo.jaxb")}) + Object test(Object object); + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/databinding/impl/DataBindingWirePostProcessorTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/databinding/impl/DataBindingWirePostProcessorTestCase.java new file mode 100644 index 0000000000..44ae07034f --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/databinding/impl/DataBindingWirePostProcessorTestCase.java @@ -0,0 +1,231 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.tuscany.core.databinding.impl; + +import static org.easymock.EasyMock.createMock; +import static org.easymock.EasyMock.expect; + +import java.lang.reflect.Type; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import junit.framework.TestCase; + +import org.apache.tuscany.spi.component.Component; +import org.apache.tuscany.spi.component.CompositeComponent; +import org.apache.tuscany.spi.component.Reference; +import org.apache.tuscany.spi.component.Service; +import org.apache.tuscany.spi.databinding.Mediator; +import org.apache.tuscany.spi.idl.java.JavaServiceContract; +import org.apache.tuscany.spi.model.DataType; +import org.apache.tuscany.spi.model.Operation; +import org.apache.tuscany.spi.model.ServiceContract; +import org.apache.tuscany.spi.wire.InboundInvocationChain; +import org.apache.tuscany.spi.wire.InboundWire; +import org.apache.tuscany.spi.wire.Interceptor; +import org.apache.tuscany.spi.wire.OutboundInvocationChain; +import org.apache.tuscany.spi.wire.OutboundWire; +import org.easymock.EasyMock; +import org.w3c.dom.Node; + +/** + * + */ +public class DataBindingWirePostProcessorTestCase extends TestCase { + private DataBindingWirePostProcessor processor; + + /** + * @see junit.framework.TestCase#setUp() + */ + protected void setUp() throws Exception { + super.setUp(); + Mediator mediator = new MediatorImpl(); + this.processor = new DataBindingWirePostProcessor(mediator); + } + + public void testProcess1() { + InboundWire inboundWire = createMock(InboundWire.class); + OutboundWire outboundWire = createMock(OutboundWire.class); + + Component component = createMock(Component.class); + CompositeComponent composite = createMock(CompositeComponent.class); + expect(component.getParent()).andReturn(composite); + expect(inboundWire.getContainer()).andReturn(component); + expect(outboundWire.getContainer()).andReturn(component); + + Map<Operation<?>, OutboundInvocationChain> outboundChains = + new HashMap<Operation<?>, OutboundInvocationChain>(); + DataType<Type> type1 = new DataType<Type>(String.class, String.class); + List<DataType<Type>> types = new ArrayList<DataType<Type>>(); + types.add(type1); + DataType<List<DataType<Type>>> inputType1 = new DataType<List<DataType<Type>>>(Object[].class, types); + DataType<Type> outputType1 = new DataType<Type>(String.class, String.class); + Operation<Type> op1 = new Operation<Type>("test", inputType1, outputType1, null); + ServiceContract<Type> outboundContract = new JavaServiceContract(null); + outboundContract.setDataBinding(String.class.getName()); + op1.setServiceContract(outboundContract); + + OutboundInvocationChain outboundChain = createMock(OutboundInvocationChain.class); + outboundChains.put(op1, outboundChain); + expect(outboundWire.getInvocationChains()).andReturn(outboundChains); + outboundChain.addInterceptor(EasyMock.anyInt(), (Interceptor)EasyMock.anyObject()); + + Map<Operation<?>, InboundInvocationChain> inboundChains = + new HashMap<Operation<?>, InboundInvocationChain>(); + DataType<Type> type2 = new DataType<Type>(Node.class, Node.class); + List<DataType<Type>> types2 = new ArrayList<DataType<Type>>(); + types2.add(type2); + DataType<List<DataType<Type>>> inputType2 = + new DataType<List<DataType<Type>>>(Object[].class, types2); + DataType<Type> outputType2 = new DataType<Type>(String.class, String.class); + Operation<Type> op2 = new Operation<Type>("test", inputType2, outputType2, null); + ServiceContract<Type> inboundContract = new JavaServiceContract(null); + inboundContract.setDataBinding(Node.class.getName()); + op2.setServiceContract(inboundContract); + + InboundInvocationChain inboundChain = createMock(InboundInvocationChain.class); + inboundChains.put(op2, inboundChain); + expect(inboundWire.getInvocationChains()).andReturn(inboundChains); + + ServiceContract<Type> contract = new JavaServiceContract(); + Map<String, Operation<Type>> operations = Collections.emptyMap(); + contract.setCallbackOperations(operations); + expect(outboundWire.getServiceContract()).andReturn(contract); + + EasyMock.replay(composite, component, inboundWire, outboundWire, inboundChain, outboundChain); + + processor.process(outboundWire, inboundWire); + } + + public void testProcess2() { + InboundWire inboundWire = createMock(InboundWire.class); + OutboundWire outboundWire = createMock(OutboundWire.class); + + Reference reference = createMock(Reference.class); + CompositeComponent composite = createMock(CompositeComponent.class); + expect(reference.getParent()).andReturn(composite); + expect(inboundWire.getContainer()).andReturn(reference).anyTimes(); + expect(outboundWire.getContainer()).andReturn(reference).anyTimes(); + + Map<Operation<?>, OutboundInvocationChain> outboundChains = + new HashMap<Operation<?>, OutboundInvocationChain>(); + DataType<Type> type1 = new DataType<Type>(String.class, String.class); + List<DataType<Type>> types = new ArrayList<DataType<Type>>(); + types.add(type1); + DataType<List<DataType<Type>>> inputType1 = new DataType<List<DataType<Type>>>(Object[].class, types); + DataType<Type> outputType1 = new DataType<Type>(String.class, String.class); + Operation<Type> op1 = new Operation<Type>("test", inputType1, outputType1, null); + ServiceContract<Type> outboundContract = new JavaServiceContract(null); + outboundContract.setDataBinding(String.class.getName()); + op1.setServiceContract(outboundContract); + + OutboundInvocationChain outboundChain = createMock(OutboundInvocationChain.class); + outboundChains.put(op1, outboundChain); + expect(outboundWire.getInvocationChains()).andReturn(outboundChains).anyTimes(); + outboundChain.addInterceptor(EasyMock.anyInt(), (Interceptor)EasyMock.anyObject()); + + Map<Operation<?>, InboundInvocationChain> inboundChains = + new HashMap<Operation<?>, InboundInvocationChain>(); + DataType<Type> type2 = new DataType<Type>(Node.class, Node.class); + List<DataType<Type>> types2 = new ArrayList<DataType<Type>>(); + types2.add(type2); + DataType<List<DataType<Type>>> inputType2 = + new DataType<List<DataType<Type>>>(Object[].class, types2); + DataType<Type> outputType2 = new DataType<Type>(String.class, String.class); + Operation<Type> op2 = new Operation<Type>("test", inputType2, outputType2, null); + ServiceContract<Type> inboundContract = new JavaServiceContract(null); + inboundContract.setDataBinding(Node.class.getName()); + op2.setServiceContract(inboundContract); + + InboundInvocationChain inboundChain = createMock(InboundInvocationChain.class); + inboundChains.put(op2, inboundChain); + expect(inboundWire.getInvocationChains()).andReturn(inboundChains).anyTimes(); + + ServiceContract<Type> contract = new JavaServiceContract(); + Map<String, Operation<Type>> operations = Collections.emptyMap(); + contract.setCallbackOperations(operations); + expect(inboundWire.getServiceContract()).andReturn(contract); + expect(inboundChain.getTailInterceptor()).andReturn(null); + + EasyMock.replay(composite, reference, inboundWire, outboundWire, inboundChain, outboundChain); + + processor.process(inboundWire, outboundWire); + } + + public void testProcess3() { + InboundWire inboundWire = createMock(InboundWire.class); + OutboundWire outboundWire = createMock(OutboundWire.class); + + Service service = createMock(Service.class); + CompositeComponent composite = createMock(CompositeComponent.class); + expect(service.getParent()).andReturn(composite); + expect(inboundWire.getContainer()).andReturn(service).anyTimes(); + expect(outboundWire.getContainer()).andReturn(service).anyTimes(); + + Map<Operation<?>, OutboundInvocationChain> outboundChains = + new HashMap<Operation<?>, OutboundInvocationChain>(); + DataType<Type> type1 = new DataType<Type>(String.class, String.class); + List<DataType<Type>> types = new ArrayList<DataType<Type>>(); + types.add(type1); + DataType<List<DataType<Type>>> inputType1 = new DataType<List<DataType<Type>>>(Object[].class, types); + DataType<Type> outputType1 = new DataType<Type>(String.class, String.class); + Operation<Type> op1 = new Operation<Type>("test", inputType1, outputType1, null); + ServiceContract<Type> outboundContract = new JavaServiceContract(null); + outboundContract.setDataBinding(String.class.getName()); + op1.setServiceContract(outboundContract); + + OutboundInvocationChain outboundChain = createMock(OutboundInvocationChain.class); + outboundChains.put(op1, outboundChain); + expect(outboundWire.getInvocationChains()).andReturn(outboundChains).anyTimes(); + // outboundChain.addInterceptor(EasyMock.anyInt(), (Interceptor) + // EasyMock.anyObject()); + + Map<Operation<?>, InboundInvocationChain> inboundChains = + new HashMap<Operation<?>, InboundInvocationChain>(); + DataType<Type> type2 = new DataType<Type>(Node.class, Node.class); + List<DataType<Type>> types2 = new ArrayList<DataType<Type>>(); + types2.add(type2); + DataType<List<DataType<Type>>> inputType2 = + new DataType<List<DataType<Type>>>(Object[].class, types2); + DataType<Type> outputType2 = new DataType<Type>(String.class, String.class); + Operation<Type> op2 = new Operation<Type>("test", inputType2, outputType2, null); + ServiceContract<Type> inboundContract = new JavaServiceContract(null); + inboundContract.setDataBinding(Node.class.getName()); + op2.setServiceContract(inboundContract); + + InboundInvocationChain inboundChain = createMock(InboundInvocationChain.class); + inboundChains.put(op2, inboundChain); + expect(inboundWire.getInvocationChains()).andReturn(inboundChains).anyTimes(); + inboundChain.addInterceptor(EasyMock.anyInt(), (Interceptor)EasyMock.anyObject()); + + ServiceContract<Type> contract = new JavaServiceContract(); + Map<String, Operation<Type>> operations = Collections.emptyMap(); + contract.setCallbackOperations(operations); + expect(inboundWire.getServiceContract()).andReturn(contract); + + EasyMock.replay(composite, service, inboundWire, outboundWire, inboundChain, outboundChain); + + processor.process(inboundWire, outboundWire); + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/databinding/impl/DirectedGraphTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/databinding/impl/DirectedGraphTestCase.java new file mode 100755 index 0000000000..70244df8e2 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/databinding/impl/DirectedGraphTestCase.java @@ -0,0 +1,89 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.databinding.impl; + +import java.util.List; + +import junit.framework.Assert; +import junit.framework.TestCase; + +import org.apache.tuscany.core.databinding.impl.DirectedGraph.Edge; +import org.apache.tuscany.core.databinding.impl.DirectedGraph.Vertex; + +public class DirectedGraphTestCase extends TestCase { + private DirectedGraph<String, Object> graph; + + protected void setUp() throws Exception { + super.setUp(); + graph = new DirectedGraph<String, Object>(); + graph.addEdge("a", "b", null, 3); + graph.addEdge("b", "c", null, 1); + graph.addEdge("a", "c", null, 8); + graph.addEdge("a", "d", null, 3); + graph.addEdge("b", "d", null, 2); + graph.addEdge("c", "b", null, 1); + graph.addEdge("c", "d", null, 2); + graph.addEdge("d", "b", null, 1); + graph.addEdge("a", "e", null, 8); + graph.addEdge("c", "c", null, 2); + } + + public void testGraph() { + // System.out.println(graph); + + Vertex vertex = graph.getVertex("a"); + Assert.assertNotNull(vertex); + Assert.assertEquals(vertex.getValue(), "a"); + + Assert.assertNull(graph.getVertex("1")); + + Edge edge = graph.getEdge("a", "b"); + Assert.assertNotNull(edge); + Assert.assertEquals(edge.getWeight(), 3); + + edge = graph.getEdge("b", "a"); + Assert.assertNull(edge); + + DirectedGraph<String, Object>.Path path = graph.getShortestPath("a", "c"); + + List<DirectedGraph<String, Object>.Edge> edges = path.getEdges(); + Assert.assertEquals(edges.size(), 2); + Assert.assertEquals(edges.get(0), graph.getEdge("a", "b")); + Assert.assertEquals(edges.get(1), graph.getEdge("b", "c")); + + Assert.assertEquals(path.getWeight(), 4); + + DirectedGraph<String, Object>.Path path2 = graph.getShortestPath("b", "e"); + Assert.assertNull(path2); + + DirectedGraph<String, Object>.Path path3 = graph.getShortestPath("a", "a"); + Assert.assertTrue(path3.getWeight() == 0 && path3.getEdges().isEmpty()); + + DirectedGraph<String, Object>.Path path4 = graph.getShortestPath("c", "c"); + Assert.assertTrue(path4.getWeight() == 2 && path4.getEdges().size() == 1); + + // System.out.println(path); + + } + + protected void tearDown() throws Exception { + super.tearDown(); + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/databinding/impl/IDLTransformerTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/databinding/impl/IDLTransformerTestCase.java new file mode 100644 index 0000000000..abd15a1947 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/databinding/impl/IDLTransformerTestCase.java @@ -0,0 +1,221 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.databinding.impl; + +import java.util.ArrayList; +import java.util.List; + +import javax.xml.namespace.QName; + +import junit.framework.TestCase; + +import org.apache.tuscany.core.databinding.xml.DOMDataBinding; +import org.apache.tuscany.core.databinding.xml.Node2Object; +import org.apache.tuscany.core.databinding.xml.Node2String; +import org.apache.tuscany.core.databinding.xml.Object2Node; +import org.apache.tuscany.core.databinding.xml.String2Node; +import org.apache.tuscany.spi.databinding.DataBindingRegistry; +import org.apache.tuscany.spi.databinding.TransformationContext; +import org.apache.tuscany.spi.databinding.extension.DOMHelper; +import org.apache.tuscany.spi.databinding.extension.SimpleTypeMapperExtension; +import org.apache.tuscany.spi.idl.ElementInfo; +import org.apache.tuscany.spi.idl.TypeInfo; +import org.apache.tuscany.spi.idl.WrapperInfo; +import org.apache.tuscany.spi.model.DataType; +import org.w3c.dom.Document; +import org.w3c.dom.Element; + +public class IDLTransformerTestCase extends TestCase { + private static final String IPO_XML = + "<?xml version=\"1.0\"?>" + "<order1" + + " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"" + + " xmlns:ipo=\"http://www.example.com/IPO\"" + + " xsi:schemaLocation=\"http://www.example.com/IPO ipo.xsd\"" + + " orderDate=\"1999-12-01\">" + + " <shipTo exportCode=\"1\" xsi:type=\"ipo:UKAddress\">" + + " <name>Helen Zoe</name>" + + " <street>47 Eden Street</street>" + + " <city>Cambridge</city>" + + " <postcode>CB1 1JR</postcode>" + + " </shipTo>" + + " <billTo xsi:type=\"ipo:USAddress\">" + + " <name>Robert Smith</name>" + + " <street>8 Oak Avenue</street>" + + " <city>Old Town</city>" + + " <state>PA</state>" + + " <zip>95819</zip>" + + " </billTo>" + + " <items>" + + " <item partNum=\"833-AA\">" + + " <productName>Lapis necklace</productName>" + + " <quantity>1</quantity>" + + " <USPrice>99.95</USPrice>" + + " <ipo:comment>Want this for the holidays</ipo:comment>" + + " <shipDate>1999-12-05</shipDate>" + + " </item>" + + " </items>" + + "</order1>"; + + private static final String OPERATION_KEY = org.apache.tuscany.spi.model.Operation.class.getName(); + + private static final String URI_ORDER_XSD = "http://example.com/order.xsd"; + + /** + * @see junit.framework.TestCase#setUp() + */ + protected void setUp() throws Exception { + super.setUp(); + } + + public void testTransform() throws Exception { + List<DataType<QName>> types0 = new ArrayList<DataType<QName>>(); + DataType<QName> wrapperType = + new DataType<QName>(null, Object.class, new QName(URI_ORDER_XSD, "checkOrderStatus")); + types0.add(wrapperType); + DataType<List<DataType<QName>>> inputType0 = + new DataType<List<DataType<QName>>>("idl:input", Object[].class, types0); + + List<DataType<QName>> types1 = new ArrayList<DataType<QName>>(); + DataType<QName> customerIdType = + new DataType<QName>(null, Object.class, new QName(URI_ORDER_XSD, "customerId")); + DataType<QName> orderType = + new DataType<QName>(null, Object.class, new QName(URI_ORDER_XSD, "order")); + DataType<QName> flagType = new DataType<QName>(null, Object.class, new QName(URI_ORDER_XSD, "flag")); + types1.add(customerIdType); + types1.add(orderType); + types1.add(flagType); + DataType<List<DataType<QName>>> inputType = + new DataType<List<DataType<QName>>>("idl:input", Object[].class, types1); + + DataType<QName> statusType = + new DataType<QName>(null, Object.class, new QName(URI_ORDER_XSD, "status")); + DataType<QName> responseType = + new DataType<QName>(null, Object.class, new QName(URI_ORDER_XSD, "checkOrderStatusResponse")); + + org.apache.tuscany.spi.model.Operation<QName> op = + new org.apache.tuscany.spi.model.Operation<QName>("checkOrderStatus", inputType0, responseType, + null); + op.setDataBinding(DOMDataBinding.NAME); + + inputType0.setMetadata(OPERATION_KEY, op); + op.setWrapperStyle(true); + ElementInfo inputElement = + new ElementInfo(new QName(URI_ORDER_XSD, "checkOrderStatus"), new TypeInfo(null, false, null)); + wrapperType.setMetadata(ElementInfo.class.getName(), inputElement); + + ElementInfo customerId = + new ElementInfo(new QName("", "customerId"), SimpleTypeMapperExtension.XSD_SIMPLE_TYPES + .get("string")); + ElementInfo order = + new ElementInfo(new QName("", "order"), new TypeInfo(new QName(URI_ORDER_XSD), false, null)); + ElementInfo flag = + new ElementInfo(new QName("", "flag"), SimpleTypeMapperExtension.XSD_SIMPLE_TYPES.get("int")); + + customerIdType.setMetadata(ElementInfo.class.getName(), customerId); + orderType.setMetadata(ElementInfo.class.getName(), order); + flagType.setMetadata(ElementInfo.class.getName(), flag); + + customerIdType.setMetadata(OPERATION_KEY, op); + orderType.setMetadata(OPERATION_KEY, op); + flagType.setMetadata(OPERATION_KEY, op); + + List<ElementInfo> inputElements = new ArrayList<ElementInfo>(); + inputElements.add(customerId); + inputElements.add(order); + inputElements.add(flag); + + ElementInfo statusElement = + new ElementInfo(new QName("", "status"), SimpleTypeMapperExtension.XSD_SIMPLE_TYPES.get("string")); + + statusType.setMetadata(ElementInfo.class.getName(), statusElement); + statusType.setMetadata(OPERATION_KEY, op); + + List<ElementInfo> outputElements = new ArrayList<ElementInfo>(); + outputElements.add(statusElement); + + ElementInfo outputElement = + new ElementInfo(new QName(URI_ORDER_XSD, "checkOrderStatusResponse"), new TypeInfo(null, false, + null)); + + responseType.setMetadata(ElementInfo.class.getName(), inputElement); + responseType.setMetadata(OPERATION_KEY, op); + + WrapperInfo wrapperInfo = + new WrapperInfo(inputElement, outputElement, inputElements, outputElements, inputType, statusType); + op.setWrapper(wrapperInfo); + op.setDataBinding(DOMDataBinding.NAME); + + MediatorImpl m = new MediatorImpl(); + TransformerRegistryImpl tr = new TransformerRegistryImpl(); + tr.registerTransformer(new String2Node()); + tr.registerTransformer(new Node2String()); + tr.registerTransformer(new Node2Object()); + tr.registerTransformer(new Object2Node()); + m.setTransformerRegistry(tr); + DataBindingRegistry dataBindingRegistry = new DataBindingRegistryImpl(); + dataBindingRegistry.register(new DOMDataBinding()); + m.setDataBindingRegistry(dataBindingRegistry); + + Object[] source = new Object[] {"cust001", IPO_XML, Integer.valueOf(1)}; + Input2InputTransformer t = new Input2InputTransformer(); + t.setDataBindingRegistry(dataBindingRegistry); + t.setMediator(m); + + TransformationContext context = new TransformationContextImpl(); + List<DataType<Class>> types = new ArrayList<DataType<Class>>(); + types.add(new DataType<Class>(Object.class.getName(), String.class, String.class)); + types.add(new DataType<Class>("java.lang.String", String.class, String.class)); + types.add(new DataType<Class>(Object.class.getName(), int.class, int.class)); + DataType<List<DataType<Class>>> inputType1 = + new DataType<List<DataType<Class>>>("idl:input", Object[].class, types); + context.setSourceDataType(inputType1); + context.setTargetDataType(op.getInputType()); + Object[] results = t.transform(source, context); + assertEquals(1, results.length); + assertTrue(results[0] instanceof Element); + Element element = (Element)results[0]; + assertEquals("http://example.com/order.xsd", element.getNamespaceURI()); + assertEquals("checkOrderStatus", element.getLocalName()); + + TransformationContext context1 = new TransformationContextImpl(); + DataType<DataType> sourceType = + new DataType<DataType>("idl:output", Object.class, op.getOutputType()); + sourceType.setMetadata(OPERATION_KEY, op.getOutputType().getMetadata(OPERATION_KEY)); + + context1.setSourceDataType(sourceType); + DataType<DataType> targetType = + new DataType<DataType>("idl:output", Object.class, + new DataType<Class>("java.lang.Object", String.class, String.class)); + context1.setTargetDataType(targetType); + + Document factory = DOMHelper.newDocument(); + Element responseElement = + factory.createElementNS("http://example.com/order.wsdl", "p:checkOrderStatusResponse"); + Element status = factory.createElement("status"); + responseElement.appendChild(status); + status.appendChild(factory.createTextNode("shipped")); + Output2OutputTransformer t2 = new Output2OutputTransformer(); + t2.setMediator(m); + t2.setDataBindingRegistry(dataBindingRegistry); + Object st = t2.transform(responseElement, context1); + assertEquals("shipped", st); + + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/databinding/impl/MediatorImplTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/databinding/impl/MediatorImplTestCase.java new file mode 100644 index 0000000000..3cb7f243a9 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/databinding/impl/MediatorImplTestCase.java @@ -0,0 +1,118 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.databinding.impl; + +import java.io.StringWriter; +import java.io.Writer; + +import junit.framework.Assert; +import junit.framework.TestCase; + +import org.apache.tuscany.core.databinding.xml.Node2String; +import org.apache.tuscany.core.databinding.xml.Node2Writer; +import org.apache.tuscany.core.databinding.xml.SAX2DOMPipe; +import org.apache.tuscany.core.databinding.xml.String2SAX; +import org.apache.tuscany.spi.databinding.DataBindingRegistry; +import org.apache.tuscany.spi.databinding.TransformationContext; +import org.apache.tuscany.spi.databinding.TransformerRegistry; +import org.apache.tuscany.spi.model.DataType; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.Node; + +/** + * Test case for MediatorImpl + */ +public class MediatorImplTestCase extends TestCase { + private static final String IPO_XML = + "<?xml version=\"1.0\"?>" + "<ipo:purchaseOrder" + + " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"" + + " xmlns:ipo=\"http://www.example.com/IPO\"" + + " xsi:schemaLocation=\"http://www.example.com/IPO ipo.xsd\"" + + " orderDate=\"1999-12-01\">" + + " <shipTo exportCode=\"1\" xsi:type=\"ipo:UKAddress\">" + + " <name>Helen Zoe</name>" + + " <street>47 Eden Street</street>" + + " <city>Cambridge</city>" + + " <postcode>CB1 1JR</postcode>" + + " </shipTo>" + + " <billTo xsi:type=\"ipo:USAddress\">" + + " <name>Robert Smith</name>" + + " <street>8 Oak Avenue</street>" + + " <city>Old Town</city>" + + "<state>PA</state>" + + " <zip>95819</zip>" + + " </billTo>" + + " <items>" + + " <item partNum=\"833-AA\">" + + " <productName>Lapis necklace</productName>" + + " <quantity>1</quantity>" + + "<USPrice>99.95</USPrice>" + + " <ipo:comment>Want this for the holidays</ipo:comment>" + + " <shipDate>1999-12-05</shipDate>" + + " </item>" + + " </items>" + + "</ipo:purchaseOrder>"; + + private MediatorImpl mediator; + + protected void setUp() throws Exception { + super.setUp(); + + TransformerRegistry registry = new TransformerRegistryImpl(); + registry.registerTransformer(new String2SAX()); + registry.registerTransformer(new SAX2DOMPipe()); + registry.registerTransformer(new Node2String()); + registry.registerTransformer(new Node2Writer()); + + mediator = new MediatorImpl(); + mediator.setTransformerRegistry(registry); + + DataBindingRegistry dataBindingRegistry = new DataBindingRegistryImpl(); + mediator.setDataBindingRegistry(dataBindingRegistry); + } + + private TransformationContext createTransformationContext(Class sourceType, Class targetType) { + TransformationContext context = new TransformationContextImpl(); + DataType sourceDataType = new DataType<Class>(sourceType, sourceType); + DataType targetDataType = new DataType<Class>(targetType, targetType); + context.setSourceDataType(sourceDataType); + context.setTargetDataType(targetDataType); + return context; + } + + public void testTransform1() { + TransformationContext context = createTransformationContext(String.class, Node.class); + Object node = + mediator.mediate(IPO_XML, context.getSourceDataType(), context.getTargetDataType(), null); + Assert.assertTrue(node instanceof Document); + Element root = ((Document)node).getDocumentElement(); + Assert.assertEquals(root.getNamespaceURI(), "http://www.example.com/IPO"); + Assert.assertEquals(root.getLocalName(), "purchaseOrder"); + } + + public void testTransform2() { + TransformationContext context = createTransformationContext(String.class, Writer.class); + Writer writer = new StringWriter(); + mediator.mediate(IPO_XML, writer, context.getSourceDataType(), context.getTargetDataType(), null); + String str = writer.toString(); + Assert.assertTrue(str != null && str.indexOf("<shipDate>1999-12-05</shipDate>") != -1); + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/databinding/impl/TransformerRegistryImplTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/databinding/impl/TransformerRegistryImplTestCase.java new file mode 100644 index 0000000000..6250efd897 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/databinding/impl/TransformerRegistryImplTestCase.java @@ -0,0 +1,106 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.tuscany.core.databinding.impl; + +import static org.easymock.EasyMock.createMock; +import static org.easymock.EasyMock.expect; +import static org.easymock.EasyMock.replay; + +import java.util.List; + +import junit.framework.Assert; +import junit.framework.TestCase; + +import org.apache.tuscany.spi.databinding.Transformer; +import org.apache.tuscany.spi.databinding.TransformerRegistry; + +/** + * + */ +public class TransformerRegistryImplTestCase extends TestCase { + private TransformerRegistry registry; + + /** + * @see junit.framework.TestCase#setUp() + */ + protected void setUp() throws Exception { + super.setUp(); + registry = new TransformerRegistryImpl(); + } + + public void testRegisterTransformer1() { + Transformer transformer = createMock(Transformer.class); + registry.registerTransformer("a", "b", 10, transformer); + Transformer t = registry.getTransformer("a", "b"); + Assert.assertSame(t, transformer); + } + + public void testRegisterTransformerTransformer() { + Transformer transformer = createMock(Transformer.class); + expect(transformer.getSourceDataBinding()).andReturn("a"); + expect(transformer.getTargetDataBinding()).andReturn("b"); + expect(transformer.getWeight()).andReturn(10); + replay(transformer); + registry.registerTransformer(transformer); + Transformer t = registry.getTransformer("a", "b"); + Assert.assertSame(t, transformer); + } + + public void testUnregisterTransformer() { + Transformer transformer = createMock(Transformer.class); + registry.registerTransformer("a", "b", 10, transformer); + boolean result = registry.unregisterTransformer("a", "b"); + Assert.assertTrue(result); + Transformer t = registry.getTransformer("a", "b"); + Assert.assertNull(t); + } + + public void testGetTransformerChain() { + Transformer t1 = createMock(Transformer.class); + expect(t1.getSourceDataBinding()).andReturn("a"); + expect(t1.getTargetDataBinding()).andReturn("b"); + expect(t1.getWeight()).andReturn(10); + replay(t1); + Transformer t2 = createMock(Transformer.class); + expect(t2.getSourceDataBinding()).andReturn("b"); + expect(t2.getTargetDataBinding()).andReturn("c"); + expect(t2.getWeight()).andReturn(20); + replay(t2); + + Transformer t3 = createMock(Transformer.class); + expect(t3.getSourceDataBinding()).andReturn("a"); + expect(t3.getTargetDataBinding()).andReturn("c"); + expect(t3.getWeight()).andReturn(120); + replay(t3); + + registry.registerTransformer(t1); + registry.registerTransformer(t2); + registry.registerTransformer(t3); + + List<Transformer> l1 = registry.getTransformerChain("a", "b"); + Assert.assertTrue(l1.size() == 1 && l1.get(0) == t1); + List<Transformer> l2 = registry.getTransformerChain("a", "c"); + Assert.assertTrue(l2.size() == 2 && l2.get(0) == t1 && l2.get(1) == t2); + List<Transformer> l3 = registry.getTransformerChain("a", "d"); + Assert.assertNull(l3); + + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/databinding/xml/DOM2StAXTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/databinding/xml/DOM2StAXTestCase.java new file mode 100644 index 0000000000..942b2d67e9 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/databinding/xml/DOM2StAXTestCase.java @@ -0,0 +1,76 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.databinding.xml; + +import javax.xml.stream.XMLStreamReader; + +import junit.framework.Assert; +import junit.framework.TestCase; + +import org.w3c.dom.Node; + +public class DOM2StAXTestCase extends TestCase { + private static final String IPO_XML = + "<?xml version=\"1.0\"?>" + "<ipo:purchaseOrder" + + " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"" + + " xmlns:ipo=\"http://www.example.com/IPO\"" + + " xsi:schemaLocation=\"http://www.example.com/IPO ipo.xsd\"" + + " orderDate=\"1999-12-01\">" + + " <shipTo exportCode=\"1\" xsi:type=\"ipo:UKAddress\">" + + " <name>Helen Zoe</name>" + + " <street>47 Eden Street</street>" + + " <city>Cambridge</city>" + + " <postcode>CB1 1JR</postcode>" + + " </shipTo>" + + " <billTo xsi:type=\"ipo:USAddress\">" + + " <name>Robert Smith</name>" + + " <street>8 Oak Avenue</street>" + + " <city>Old Town</city>" + + " <state>PA</state>" + + " <zip>95819</zip>" + + " </billTo>" + + " <items>" + + " <item partNum=\"833-AA\">" + + " <productName>Lapis necklace</productName>" + + " <quantity>1</quantity>" + + " <USPrice>99.95</USPrice>" + + " <ipo:comment>Want this for the holidays</ipo:comment>" + + " <shipDate>1999-12-05</shipDate>" + + " </item>" + + " </items>" + + "</ipo:purchaseOrder>"; + + /** + * @see junit.framework.TestCase#setUp() + */ + protected void setUp() throws Exception { + super.setUp(); + } + + public void testTransformation() { + String2Node t1 = new String2Node(); + Node node = t1.transform(IPO_XML, null); + Node2XMLStreamReader t2 = new Node2XMLStreamReader(); + XMLStreamReader reader = t2.transform(node, null); + XMLStreamReader2String t3 = new XMLStreamReader2String(); + String xml = t3.transform(reader, null); + Assert.assertTrue(xml != null && xml.indexOf("<shipDate>1999-12-05</shipDate>") != -1); + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/databinding/xml/DataPipeTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/databinding/xml/DataPipeTestCase.java new file mode 100644 index 0000000000..d4eaf9b2a9 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/databinding/xml/DataPipeTestCase.java @@ -0,0 +1,89 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.tuscany.core.databinding.xml; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.io.Reader; +import java.io.Writer; + +import junit.framework.Assert; +import junit.framework.TestCase; + +import org.apache.tuscany.core.databinding.impl.PipedTransformer; +import org.apache.tuscany.spi.databinding.extension.DOMHelper; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.Node; + +/** + * Test case for DataPipe + */ +public class DataPipeTestCase extends TestCase { + + public final void testStreamPipe() throws IOException { + byte[] bytes = new byte[] {1, 2, 3}; + StreamDataPipe pipe = new StreamDataPipe(); + Assert.assertSame(OutputStream.class, pipe.getSourceType()); + Assert.assertSame(InputStream.class, pipe.getTargetType()); + OutputStream os = pipe.getSink(); + os.write(bytes); + byte[] newBytes = new byte[16]; + int count = pipe.getResult().read(newBytes); + Assert.assertEquals(3, count); + for (int i = 0; i < bytes.length; i++) { + Assert.assertEquals(bytes[i], newBytes[i]); + } + } + + public final void testWriter2ReaderPipe() throws IOException { + String str = "ABC"; + Writer2ReaderDataPipe pipe = new Writer2ReaderDataPipe(); + Assert.assertSame(Writer.class, pipe.getSourceType()); + Assert.assertSame(Reader.class, pipe.getTargetType()); + pipe.getSink().write(str); + char[] buf = new char[16]; + int count = pipe.getResult().read(buf); + Assert.assertEquals(3, count); + for (int i = 0; i < str.length(); i++) { + Assert.assertEquals(str.charAt(i), buf[i]); + } + } + + public final void testPiped() throws Exception { + Node2Writer node2Writer = new Node2Writer(); + Writer2ReaderDataPipe pipe = new Writer2ReaderDataPipe(); + PipedTransformer<Node, Writer, Reader> transformer = + new PipedTransformer<Node, Writer, Reader>(node2Writer, pipe); + Document document = DOMHelper.newDocument(); + Element element = document.createElementNS("http://ns1", "root"); + document.appendChild(element); + Reader reader = transformer.transform(document, null); + Assert.assertEquals(transformer.getWeight(), node2Writer.getWeight() + pipe.getWeight()); + Assert.assertEquals(transformer.getSourceDataBinding(), node2Writer.getSourceDataBinding()); + Assert.assertEquals(transformer.getTargetDataBinding(), pipe.getTargetDataBinding()); + char[] buf = new char[120]; + int count = reader.read(buf); + String xml = new String(buf, 0, count); + Assert.assertTrue(xml.contains("<root xmlns=\"http://ns1\"/>")); + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/databinding/xml/Node2StringTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/databinding/xml/Node2StringTestCase.java new file mode 100755 index 0000000000..9b9aa3b893 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/databinding/xml/Node2StringTestCase.java @@ -0,0 +1,35 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.databinding.xml; + +import junit.framework.TestCase; + +import org.apache.tuscany.spi.databinding.extension.DOMHelper; +import org.w3c.dom.Document; +import org.w3c.dom.Element; + +public class Node2StringTestCase extends TestCase { + public void testTransformation() throws Exception { + Document document = DOMHelper.newDocument(); + Element element = document.createElementNS("http://ns1", "test"); + document.appendChild(element); + + new Node2String().transform(document, null); + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/databinding/xml/PushTransformationTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/databinding/xml/PushTransformationTestCase.java new file mode 100644 index 0000000000..a2318b2faa --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/databinding/xml/PushTransformationTestCase.java @@ -0,0 +1,81 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.databinding.xml; + +import javax.xml.stream.XMLStreamReader; + +import junit.framework.Assert; +import junit.framework.TestCase; + +import org.apache.tuscany.core.databinding.impl.PipedTransformer; +import org.w3c.dom.Node; +import org.xml.sax.ContentHandler; + +public class PushTransformationTestCase extends TestCase { + private static final String IPO_XML = + "<?xml version=\"1.0\"?>" + "<ipo:purchaseOrder" + + " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"" + + " xmlns:ipo=\"http://www.example.com/IPO\"" + + " xsi:schemaLocation=\"http://www.example.com/IPO ipo.xsd\"" + + " orderDate=\"1999-12-01\">" + + " <shipTo exportCode=\"1\" xsi:type=\"ipo:UKAddress\">" + + " <name>Helen Zoe</name>" + + " <street>47 Eden Street</street>" + + " <city>Cambridge</city>" + + " <postcode>CB1 1JR</postcode>" + + " </shipTo>" + + " <billTo xsi:type=\"ipo:USAddress\">" + + " <name>Robert Smith</name>" + + " <street>8 Oak Avenue</street>" + + " <city>Old Town</city>" + + " <state>PA</state>" + + " <zip>95819</zip>" + + " </billTo>" + + " <items>" + + " <item partNum=\"833-AA\">" + + " <productName>Lapis necklace</productName>" + + " <quantity>1</quantity>" + + " <USPrice>99.95</USPrice>" + + " <ipo:comment>Want this for the holidays</ipo:comment>" + + " <shipDate>1999-12-05</shipDate>" + + " </item>" + + " </items>" + + "</ipo:purchaseOrder>"; + + /** + * @see junit.framework.TestCase#setUp() + */ + protected void setUp() throws Exception { + super.setUp(); + } + + public void testTransformation() { + String2XMLStreamReader t1 = new String2XMLStreamReader(); + XMLStreamReader reader = t1.transform(IPO_XML, null); + XMLStreamReader2SAX t2 = new XMLStreamReader2SAX(); + PipedTransformer<XMLStreamReader, ContentHandler, Node> t3 = + new PipedTransformer<XMLStreamReader, ContentHandler, Node>(t2, new SAX2DOMPipe()); + Node node = t3.transform(reader, null); + Assert.assertNotNull(node); + Node2String t4 = new Node2String(); + String xml = t4.transform(node, null); + Assert.assertTrue(xml != null && xml.indexOf("<shipDate>1999-12-05</shipDate>") != -1); + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/databinding/xml/StAXHelperTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/databinding/xml/StAXHelperTestCase.java new file mode 100644 index 0000000000..7d18e83ac6 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/databinding/xml/StAXHelperTestCase.java @@ -0,0 +1,47 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.tuscany.core.databinding.xml; + +import javax.xml.stream.XMLStreamReader; + +import junit.framework.TestCase; + +/** + * Test Case for StAXHelper + */ +public class StAXHelperTestCase extends TestCase { + private static final String XML = + "<a:foo xmlns:a='http://a' name='foo'><bar name='bar'>" + "<doo a:name='doo' xmlns:a='http://doo'/>" + + "</bar></a:foo>"; + + /** + * @see junit.framework.TestCase#setUp() + */ + protected void setUp() throws Exception { + super.setUp(); + } + + public void testHelper() throws Exception { + XMLStreamReader reader = StAXHelper.createXMLStreamReader(XML); + String xml = StAXHelper.save(reader); + reader = StAXHelper.createXMLStreamReader(xml); + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/databinding/xml/TraxTransformerTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/databinding/xml/TraxTransformerTestCase.java new file mode 100644 index 0000000000..7e9494d423 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/databinding/xml/TraxTransformerTestCase.java @@ -0,0 +1,99 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.tuscany.core.databinding.xml; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.StringReader; +import java.io.StringWriter; +import java.io.Writer; +import java.net.URL; + +import junit.framework.TestCase; + +import org.w3c.dom.Node; +import org.xml.sax.Attributes; +import org.xml.sax.InputSource; +import org.xml.sax.SAXException; +import org.xml.sax.helpers.DefaultHandler; + +/** + * + */ +public class TraxTransformerTestCase extends TestCase { + private URL url; + + /** + * @see junit.framework.TestCase#setUp() + */ + protected void setUp() throws Exception { + super.setUp(); + url = getClass().getResource("foo.xml"); + } + + public void testTransformDOM() throws IOException { + InputStream is = url.openStream(); + InputStream2Node t1 = new InputStream2Node(); + Node node = t1.transform(is, null); + is.close(); + Writer writer = new StringWriter(); + Node2Writer t2 = new Node2Writer(); + t2.transform(node, writer, null); + String str = writer.toString(); + StringReader reader = new StringReader(str); + Reader2Node t3 = new Reader2Node(); + node = t3.transform(reader, null); + ByteArrayOutputStream os = new ByteArrayOutputStream(); + Node2OutputStream t4 = new Node2OutputStream(); + t4.transform(node, os, null); + InputSource inputSource = new InputSource(new ByteArrayInputStream(os.toByteArray())); + InputSource2Node t5 = new InputSource2Node(); + node = t5.transform(inputSource, null); + } + + public void testTransformSAX() throws IOException { + MyContentHandler handler = new MyContentHandler(); + InputStream is = url.openStream(); + InputStream2SAX t1 = new InputStream2SAX(); + t1.transform(is, handler, null); + is.close(); + + String xml = "<foo xmlns=\"http://foo\">bar</foo>"; + + InputSource inputSource = new InputSource(new StringReader(xml)); + InputSource2SAX t2 = new InputSource2SAX(); + MyContentHandler handler2 = new MyContentHandler(); + t2.transform(inputSource, handler2, null); + + } + + private static class MyContentHandler extends DefaultHandler { + + @Override + public void startElement(String namespaceURI, String localName, String qName, Attributes atts) + throws SAXException { + super.startElement(namespaceURI, localName, qName, atts); + } + + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/deployer/BootstrapDeployerTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/deployer/BootstrapDeployerTestCase.java new file mode 100644 index 0000000000..f988c5d3a4 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/deployer/BootstrapDeployerTestCase.java @@ -0,0 +1,163 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.deployer; + +import java.net.URL; +import java.util.Map; +import javax.xml.stream.XMLInputFactory; + +import org.apache.tuscany.spi.component.Component; +import org.apache.tuscany.spi.component.CompositeComponent; +import org.apache.tuscany.spi.component.SCAObject; +import org.apache.tuscany.spi.deployer.Deployer; +import org.apache.tuscany.spi.deployer.DeploymentContext; +import org.apache.tuscany.spi.loader.LoaderException; +import org.apache.tuscany.spi.model.BoundServiceDefinition; +import org.apache.tuscany.spi.model.ComponentDefinition; +import org.apache.tuscany.spi.model.ComponentType; +import org.apache.tuscany.spi.model.CompositeComponentType; +import org.apache.tuscany.spi.model.Implementation; +import org.apache.tuscany.spi.model.Include; +import org.apache.tuscany.spi.model.Property; +import org.apache.tuscany.spi.model.PropertyValue; +import org.apache.tuscany.spi.model.ReferenceDefinition; +import org.apache.tuscany.spi.model.ServiceDefinition; + +import junit.framework.TestCase; +import org.apache.tuscany.core.bootstrap.Bootstrapper; +import org.apache.tuscany.core.bootstrap.DefaultBootstrapper; +import org.apache.tuscany.core.implementation.system.model.SystemBinding; +import org.apache.tuscany.core.implementation.system.model.SystemCompositeImplementation; +import org.apache.tuscany.core.mock.component.BasicInterface; +import org.apache.tuscany.core.monitor.NullMonitorFactory; +import static org.easymock.EasyMock.createNiceMock; +import static org.easymock.EasyMock.isA; +import static org.easymock.EasyMock.replay; +import static org.easymock.EasyMock.verify; + +/** + * Verifies the default boostrap deployer + * + * @version $Rev$ $Date$ + */ +public class BootstrapDeployerTestCase extends TestCase { + private DeployerImpl deployer; + private DeploymentContext deploymentContext; + private ComponentDefinition<SystemCompositeImplementation> componentDefinition; + private SystemCompositeImplementation implementation; + + public void testBoot1Load() throws LoaderException { + CompositeComponent parent = createNiceMock(CompositeComponent.class); + URL scdl = BootstrapDeployerTestCase.class.getResource("boot1.scdl"); + implementation.setScdlLocation(scdl); + deployer.load(parent, componentDefinition, deploymentContext); + CompositeComponentType<ServiceDefinition, ReferenceDefinition, Property<?>> composite = + implementation.getComponentType(); + assertNotNull(composite); + assertEquals("boot1", composite.getName()); + + // check parse of <service> + Map<String, ServiceDefinition> services = composite.getDeclaredServices(); + assertEquals(1, services.size()); // included doesn't count + services = composite.getServices(); + assertEquals(2, services.size()); // included counts + BoundServiceDefinition serviceDefinition = (BoundServiceDefinition) services.get("service"); + assertNotNull(serviceDefinition); + assertEquals("service", serviceDefinition.getName()); + assertEquals(BasicInterface.class, serviceDefinition.getServiceContract().getInterfaceClass()); + assertTrue(serviceDefinition.getBinding() instanceof SystemBinding); + + // check parse of <component> + Map<String, ComponentDefinition<? extends Implementation<?>>> components = composite.getDeclaredComponents(); + assertEquals(1, components.size()); // included doesn't count + components = composite.getComponents(); + assertEquals(2, components.size()); // included counts + ComponentDefinition<? extends Implementation<?>> component = components.get("component"); + assertNotNull(component); + PropertyValue<?> propVal = component.getPropertyValues().get("publicProperty"); + assertEquals("propval", propVal.getValueFactory().getInstance()); + + // check introspection of implementation + ComponentType<?, ?, ?> componentType = component.getImplementation().getComponentType(); + assertNotNull(componentType); // details checked in SystemComponentTypeLoaderTestCase + + // check included component + Map<String, Include> includes = composite.getIncludes(); + assertEquals(1, includes.size()); + Include include = includes.get("boot1-include"); + assertNotNull(include); + CompositeComponentType included = include.getIncluded(); + assertNotNull(included); + assertEquals(1, included.getComponents().size()); + } + + public void testBoot1Deployment() throws LoaderException { + URL scdl = BootstrapDeployerTestCase.class.getResource("boot1.scdl"); + implementation.setScdlLocation(scdl); + CompositeComponent parent = createNiceMock(CompositeComponent.class); + parent.register(isA(SCAObject.class)); + replay(parent); + // load the boot1 file using the bootstrap deployer + componentDefinition.setName("simple"); + Component component = deployer.deploy(parent, componentDefinition); + assertNotNull(component); + verify(parent); + } + + public void testBoot2Deployment() throws LoaderException { + URL scdl = BootstrapDeployerTestCase.class.getResource("boot2.scdl"); + implementation.setScdlLocation(scdl); + CompositeComponent parent = createNiceMock(CompositeComponent.class); + parent.register(isA(SCAObject.class)); + replay(parent); + + // load the boot2 file using the bootstrap deployer + componentDefinition.setName("newDeployer"); + CompositeComponent component = (CompositeComponent) deployer.deploy(parent, componentDefinition); + assertNotNull(component); + verify(parent); + component.start(); + Deployer newDeployer = (Deployer) component.getSystemServiceInstance("deployer"); + assertNotNull(newDeployer); + +/* // FIXME + // load the boot2 file using the newly loaded deployer + parent.reset(); + parent.expects(once()).method("register").withAnyArguments(); + componentDefinition.setName("newDeployer2"); + component = newDeployer.deploy((CompositeComponent) parent.proxy(), componentDefinition); + assertNotNull(component); + parent.verify(); + component.start(); + Deployer newDeployer2 = (Deployer) component.getServiceInstance("deployer"); + assertNotNull(newDeployer2); +*/ + } + + protected void setUp() throws Exception { + super.setUp(); + XMLInputFactory xmlFactory = XMLInputFactory.newInstance(); + Bootstrapper bootstrapper = new DefaultBootstrapper(new NullMonitorFactory(), xmlFactory); + deployer = (DeployerImpl) bootstrapper.createDeployer(); + deploymentContext = new RootDeploymentContext(null, xmlFactory, null, null); + implementation = new SystemCompositeImplementation(); + implementation.setClassLoader(getClass().getClassLoader()); + componentDefinition = new ComponentDefinition<SystemCompositeImplementation>(implementation); + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/idl/java/JavaInterfaceProcessorRegistryImplTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/idl/java/JavaInterfaceProcessorRegistryImplTestCase.java new file mode 100644 index 0000000000..e3a7deb10a --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/idl/java/JavaInterfaceProcessorRegistryImplTestCase.java @@ -0,0 +1,100 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.idl.java; + +import java.lang.reflect.Type; +import java.util.List; +import java.util.Map; + +import org.apache.tuscany.spi.idl.InvalidServiceContractException; +import org.apache.tuscany.spi.idl.java.JavaInterfaceProcessor; +import org.apache.tuscany.spi.idl.java.JavaServiceContract; +import org.apache.tuscany.spi.model.DataType; +import org.apache.tuscany.spi.model.Operation; + +import junit.framework.TestCase; +import org.apache.tuscany.core.util.JavaIntrospectionHelper; +import org.easymock.EasyMock; + +import static org.easymock.EasyMock.createMock; +import static org.easymock.EasyMock.eq; +import static org.easymock.EasyMock.expectLastCall; +import static org.easymock.EasyMock.isA; +import static org.easymock.EasyMock.replay; +import static org.easymock.EasyMock.verify; + +/** + * @version $Rev$ $Date$ + */ +public class JavaInterfaceProcessorRegistryImplTestCase extends TestCase { + private JavaInterfaceProcessorRegistryImpl impl; + + public void testSimpleInterface() throws InvalidServiceContractException { + JavaServiceContract contract = impl.introspect(Simple.class); + // TODO spec to clairfy interface name + assertEquals(JavaIntrospectionHelper.getBaseName(Simple.class), contract.getInterfaceName()); + assertEquals(Simple.class, contract.getInterfaceClass()); + Map<String, Operation<Type>> operations = contract.getOperations(); + assertEquals(1, operations.size()); + Operation<Type> baseInt = operations.get("baseInt"); + assertNotNull(baseInt); + + DataType<Type> returnType = baseInt.getOutputType(); + assertEquals(Integer.TYPE, returnType.getPhysical()); + assertEquals(Integer.TYPE, returnType.getLogical()); + + List<DataType<Type>> parameterTypes = baseInt.getInputType().getLogical(); + assertEquals(1, parameterTypes.size()); + DataType<Type> arg0 = parameterTypes.get(0); + assertEquals(Integer.TYPE, arg0.getPhysical()); + assertEquals(Integer.TYPE, arg0.getLogical()); + + List<DataType<Type>> faultTypes = baseInt.getFaultTypes(); + assertEquals(1, faultTypes.size()); + DataType<Type> fault0 = faultTypes.get(0); + assertEquals(IllegalArgumentException.class, fault0.getPhysical()); + assertEquals(IllegalArgumentException.class, fault0.getLogical()); + } + + public void testUnregister() throws Exception { + JavaInterfaceProcessor processor = createMock(JavaInterfaceProcessor.class); + processor.visitInterface(eq(Base.class), EasyMock.same((Class)null), isA(JavaServiceContract.class)); + expectLastCall().once(); + replay(processor); + impl.registerProcessor(processor); + impl.introspect(Base.class); + impl.unregisterProcessor(processor); + impl.introspect(Base.class); + verify(processor); + } + + protected void setUp() throws Exception { + super.setUp(); + impl = new JavaInterfaceProcessorRegistryImpl(); + + } + + private static interface Base { + int baseInt(int param) throws IllegalArgumentException; + } + + private static interface Simple extends Base { + + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/IntrospectionRegistryTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/IntrospectionRegistryTestCase.java new file mode 100644 index 0000000000..fb5e7fbb1f --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/IntrospectionRegistryTestCase.java @@ -0,0 +1,124 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.implementation; + +import java.lang.reflect.Method; +import java.lang.reflect.Field; +import java.lang.reflect.Constructor; + +import org.apache.tuscany.spi.component.CompositeComponent; +import org.apache.tuscany.spi.deployer.DeploymentContext; +import org.apache.tuscany.spi.implementation.java.ImplementationProcessor; +import org.apache.tuscany.spi.implementation.java.JavaMappedProperty; +import org.apache.tuscany.spi.implementation.java.JavaMappedReference; +import org.apache.tuscany.spi.implementation.java.JavaMappedService; +import org.apache.tuscany.spi.implementation.java.PojoComponentType; + +import junit.framework.TestCase; +import org.apache.tuscany.core.implementation.IntrospectionRegistryImpl.Monitor; +import org.apache.tuscany.core.monitor.NullMonitorFactory; +import org.easymock.EasyMock; + +/** + * @version $Rev$ $Date$ + */ +public class IntrospectionRegistryTestCase extends TestCase { + + private Monitor monitor; + + public void testRegister() throws Exception { + IntrospectionRegistryImpl registry = new IntrospectionRegistryImpl(monitor); + ImplementationProcessor processor = EasyMock.createNiceMock(ImplementationProcessor.class); + registry.registerProcessor(processor); + } + + public void testUnegister() throws Exception { + IntrospectionRegistryImpl registry = new IntrospectionRegistryImpl(monitor); + ImplementationProcessor processor = EasyMock.createNiceMock(ImplementationProcessor.class); + registry.registerProcessor(processor); + registry.unregisterProcessor(processor); + } + + @SuppressWarnings("unchecked") + public void testWalk() throws Exception { + IntrospectionRegistryImpl registry = new IntrospectionRegistryImpl(monitor); + ImplementationProcessor processor = EasyMock.createMock(ImplementationProcessor.class); + processor.visitClass(EasyMock.isA(CompositeComponent.class), + EasyMock.eq(Bar.class), + EasyMock.isA(PojoComponentType.class), + EasyMock.isA(DeploymentContext.class)); + processor.visitConstructor(EasyMock.isA(CompositeComponent.class), + EasyMock.isA(Constructor.class), + EasyMock.isA(PojoComponentType.class), + EasyMock.isA(DeploymentContext.class)); + processor.visitMethod(EasyMock.isA(CompositeComponent.class), + EasyMock.isA(Method.class), + EasyMock.isA(PojoComponentType.class), + EasyMock.isA(DeploymentContext.class)); + processor.visitField(EasyMock.isA(CompositeComponent.class), + EasyMock.isA(Field.class), + EasyMock.isA(PojoComponentType.class), + EasyMock.isA(DeploymentContext.class)); + processor.visitSuperClass(EasyMock.isA(CompositeComponent.class), + EasyMock.isA(Class.class), + EasyMock.isA(PojoComponentType.class), + EasyMock.isA(DeploymentContext.class)); + processor.visitEnd(EasyMock.isA(CompositeComponent.class), + EasyMock.isA(Class.class), + EasyMock.isA(PojoComponentType.class), + EasyMock.isA(DeploymentContext.class)); + + // mock.expects(once()).method("visitClass"); +// mock.expects(once()).method("visitMethod"); +// mock.expects(once()).method("visitField"); +// mock.expects(once()).method("visitConstructor"); +// mock.expects(once()).method("visitSuperClass"); +// mock.expects(once()).method("visitEnd"); + EasyMock.replay(processor); + registry.registerProcessor(processor); + registry.introspect(EasyMock.createNiceMock(CompositeComponent.class), + Bar.class, + new PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>>(), + EasyMock.createNiceMock(DeploymentContext.class)); + EasyMock.verify(processor); + } + + + protected void setUp() throws Exception { + super.setUp(); + monitor = new NullMonitorFactory().getMonitor(Monitor.class); + } + + private class Baz { + + } + + private class Bar extends Baz { + + protected String bar; + + public Bar() { + } + + public void bar() { + } + + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/composite/AutowireResolutionTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/composite/AutowireResolutionTestCase.java new file mode 100644 index 0000000000..7d9e2a75ee --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/composite/AutowireResolutionTestCase.java @@ -0,0 +1,102 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.implementation.composite; + +import org.apache.tuscany.spi.component.CompositeComponent; + +import junit.framework.TestCase; +import org.easymock.EasyMock; +import static org.easymock.EasyMock.createMock; +import static org.easymock.EasyMock.eq; +import static org.easymock.EasyMock.replay; +import static org.easymock.EasyMock.verify; + +/** + * Verfies specific autowire resolution scenarios + * + * @version $Rev$ $Date$ + */ +public class AutowireResolutionTestCase extends TestCase { + + public void testConstruction() { + CompositeComponent parent = createMock(CompositeComponent.class); + replay(parent); + CompositeComponent component = new CompositeComponentImpl("test", parent, null, null); + assertEquals("test", component.getName()); + assertSame(parent, component.getParent()); + verify(parent); + } + + public void testResolveToSelf() { + CompositeComponent parent = createMock(CompositeComponent.class); + replay(parent); + CompositeComponent component = new CompositeComponentImpl("test", parent, null, null); + assertSame(component, component.resolveInstance(CompositeComponent.class)); + verify(parent); + } + + public void testSystemResolveToSelf() { + CompositeComponent parent = createMock(CompositeComponent.class); + replay(parent); + CompositeComponent component = new CompositeComponentImpl("test", parent, null, null); + assertSame(component, component.resolveSystemInstance(CompositeComponent.class)); + verify(parent); + } + + public void testResolvedByAutowire() { + Foo foo = new Foo() { + }; + CompositeComponent parent = createMock(CompositeComponent.class); + EasyMock.expect(parent.resolveInstance(eq(Foo.class))).andReturn(foo); + replay(parent); + CompositeComponent component = new CompositeComponentImpl("test", parent, null, null); + assertSame(foo, component.resolveInstance(Foo.class)); + verify(parent); + } + + public void testSystemResolvedByAutowire() { + Foo foo = new Foo() { + }; + CompositeComponent parent = createMock(CompositeComponent.class); + EasyMock.expect(parent.resolveSystemInstance(eq(Foo.class))).andReturn(foo); + replay(parent); + CompositeComponent component = new CompositeComponentImpl("test", parent, null, null); + assertSame(foo, component.resolveSystemInstance(Foo.class)); + verify(parent); + } + + /** + * Verify parent resolution strategy for application services + */ + public void testNamespaceIsolationAutowire() { + Foo foo = new Foo() { + }; + CompositeComponent parent = new CompositeComponentImpl("parent", null, null, null); + parent.registerJavaObject("foo", Foo.class, foo); + CompositeComponent component = new CompositeComponentImpl("test", parent, null, null); + assertNull(component.resolveInstance(Foo.class)); + } + + protected void setUp() throws Exception { + super.setUp(); + } + + public static interface Foo { + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/composite/AutowireTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/composite/AutowireTestCase.java new file mode 100644 index 0000000000..d565777cd2 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/composite/AutowireTestCase.java @@ -0,0 +1,231 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.implementation.composite; + +import java.util.ArrayList; +import java.util.List; + +import org.apache.tuscany.spi.component.AtomicComponent; +import org.apache.tuscany.spi.component.CompositeComponent; +import org.apache.tuscany.spi.component.Reference; +import org.apache.tuscany.spi.component.Service; +import org.apache.tuscany.spi.component.SystemAtomicComponent; + +import junit.framework.TestCase; +import org.apache.tuscany.core.implementation.system.component.SystemReference; +import org.apache.tuscany.core.implementation.system.component.SystemService; +import org.easymock.EasyMock; + +/** + * Performs basic autowiring tests to composite artifacts + * + * @version $$Rev$$ $$Date$$ + */ +public class AutowireTestCase extends TestCase { + + /** + * Tests autowiring to an system atomic component + */ + public void testSystemAtomicAutowire() throws Exception { + CompositeComponent parent = new CompositeComponentImpl("parent", null, null, null); + parent.start(); + + List<Class<?>> interfaces = new ArrayList<Class<?>>(); + interfaces.add(Source.class); + interfaces.add(Source2.class); + Source originalSource = new SourceImpl(); + SystemAtomicComponent component = EasyMock.createMock(SystemAtomicComponent.class); + EasyMock.expect(component.getName()).andReturn("source").atLeastOnce(); + EasyMock.expect(component.getServiceInstance()).andReturn(originalSource).atLeastOnce(); + EasyMock.expect(component.getServiceInterfaces()).andReturn(interfaces); + EasyMock.expect(component.isSystem()).andReturn(true).atLeastOnce(); + + EasyMock.replay(component); + parent.register(component); + + Source source = parent.resolveSystemInstance(Source.class); + assertNotNull(source); + Source2 source2 = parent.resolveSystemInstance(Source2.class); + assertSame(source, source2); + assertNull(parent.resolveSystemExternalInstance(Source.class)); + EasyMock.verify(component); + } + + /** + * Tests autowiring to an system atomic component + */ + public void testAtomicAutowire() throws Exception { + CompositeComponent parent = new CompositeComponentImpl("parent", null, null, null); + parent.start(); + + List<Class<?>> interfaces = new ArrayList<Class<?>>(); + interfaces.add(Source.class); + interfaces.add(Source2.class); + Source originalSource = new SourceImpl(); + AtomicComponent component = EasyMock.createMock(AtomicComponent.class); + EasyMock.expect(component.getName()).andReturn("source").atLeastOnce(); + EasyMock.expect(component.getServiceInstance()).andReturn(originalSource).atLeastOnce(); + EasyMock.expect(component.getServiceInterfaces()).andReturn(interfaces); + EasyMock.expect(component.isSystem()).andReturn(false).atLeastOnce(); + + EasyMock.replay(component); + parent.register(component); + + Source source = parent.resolveInstance(Source.class); + assertNotNull(source); + Source2 source2 = parent.resolveInstance(Source2.class); + assertSame(source, source2); + assertNull(parent.resolveExternalInstance(Source.class)); + EasyMock.verify(component); + } + + /** + * Tests autowiring to a system service which is wired to an atomic component. + */ + public void testSystemServiceAutowire() throws Exception { + CompositeComponent parent = new CompositeComponentImpl("parent", null, null, null); + parent.start(); + + List<Class<?>> interfaces = new ArrayList<Class<?>>(); + interfaces.add(Source.class); + interfaces.add(Source2.class); + + Source serviceSource = new SourceImpl(); + SystemService component = EasyMock.createMock(SystemService.class); + EasyMock.expect(component.getName()).andReturn("service").atLeastOnce(); + component.getInterface(); + EasyMock.expectLastCall().andReturn(Source.class).atLeastOnce(); + EasyMock.expect(component.isSystem()).andReturn(true).atLeastOnce(); + EasyMock.expect(component.getServiceInstance()).andReturn(serviceSource); + EasyMock.replay(component); + parent.register(component); + + + SystemAtomicComponent component2 = EasyMock.createMock(SystemAtomicComponent.class); + EasyMock.expect(component2.getName()).andReturn("source").atLeastOnce(); + EasyMock.expect(component2.getServiceInterfaces()).andReturn(interfaces).atLeastOnce(); + EasyMock.expect(component2.isSystem()).andReturn(true).atLeastOnce(); + EasyMock.replay(component2); + parent.register(component2); + + Source source = parent.resolveSystemExternalInstance(Source.class); + assertSame(serviceSource, source); + Source2 source2 = parent.resolveSystemExternalInstance(Source2.class); + assertNull(source2); + EasyMock.verify(component); + EasyMock.verify(component2); + } + + /** + * Tests autowiring to a system service which is wired to an atomic component. + */ + public void testServiceAutowire() throws Exception { + CompositeComponent parent = new CompositeComponentImpl("parent", null, null, null); + parent.start(); + + List<Class<?>> interfaces = new ArrayList<Class<?>>(); + interfaces.add(Source.class); + interfaces.add(Source2.class); + + Source serviceSource = new SourceImpl(); + Service component = EasyMock.createMock(Service.class); + EasyMock.expect(component.getName()).andReturn("service").atLeastOnce(); + component.getInterface(); + EasyMock.expectLastCall().andReturn(Source.class).atLeastOnce(); + EasyMock.expect(component.isSystem()).andReturn(false).atLeastOnce(); + EasyMock.expect(component.getServiceInstance()).andReturn(serviceSource); + EasyMock.replay(component); + parent.register(component); + + + AtomicComponent component2 = EasyMock.createMock(AtomicComponent.class); + EasyMock.expect(component2.getName()).andReturn("source").atLeastOnce(); + EasyMock.expect(component2.getServiceInterfaces()).andReturn(interfaces).atLeastOnce(); + EasyMock.expect(component2.isSystem()).andReturn(false).atLeastOnce(); + EasyMock.replay(component2); + parent.register(component2); + + Source source = parent.resolveExternalInstance(Source.class); + assertSame(serviceSource, source); + Source2 source2 = parent.resolveExternalInstance(Source2.class); + assertNull(source2); + EasyMock.verify(component); + EasyMock.verify(component2); + } + + + /** + * Tests autowiring to a system reference + */ + public void testSystemReferenceAutowire() throws Exception { + CompositeComponent parent = new CompositeComponentImpl("parent", null, null, null); + parent.start(); + + Source refSource = new SourceImpl(); + SystemReference reference = EasyMock.createMock(SystemReference.class); + EasyMock.expect(reference.getName()).andReturn("service").atLeastOnce(); + EasyMock.expect(reference.getServiceInstance()).andReturn(refSource); + EasyMock.expect(reference.isSystem()).andReturn(true).atLeastOnce(); + reference.getInterface(); + EasyMock.expectLastCall().andReturn(Source.class); + EasyMock.replay(reference); + parent.register(reference); + + Source source = parent.resolveSystemInstance(Source.class); + assertNotNull(source); + assertNull(parent.resolveSystemExternalInstance(Source.class)); + EasyMock.verify(reference); + } + + /** + * Tests autowiring to a reference + */ + public void testReferenceAutowire() throws Exception { + CompositeComponent parent = new CompositeComponentImpl("parent", null, null, null); + parent.start(); + Source refSource = new SourceImpl(); + Reference reference = EasyMock.createMock(Reference.class); + EasyMock.expect(reference.getName()).andReturn("service").atLeastOnce(); + EasyMock.expect(reference.getServiceInstance()).andReturn(refSource); + EasyMock.expect(reference.isSystem()).andReturn(false).atLeastOnce(); + reference.getInterface(); + EasyMock.expectLastCall().andReturn(Source.class); + EasyMock.replay(reference); + parent.register(reference); + + Source source = parent.resolveInstance(Source.class); + assertNotNull(source); + assertNull(parent.resolveExternalInstance(Source.class)); + EasyMock.verify(reference); + } + + + public static class SourceImpl implements Source, Source2 { + public SourceImpl() { + } + } + + public static interface Source { + + } + + public static interface Source2 { + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/composite/CompositeBuilderTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/composite/CompositeBuilderTestCase.java new file mode 100644 index 0000000000..fb665a55f4 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/composite/CompositeBuilderTestCase.java @@ -0,0 +1,235 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.implementation.composite; + +import java.net.URI; +import java.util.HashMap; +import java.util.Map; + +import org.apache.tuscany.spi.component.AtomicComponent; +import org.apache.tuscany.spi.component.CompositeComponent; +import org.apache.tuscany.spi.component.ScopeContainer; +import org.apache.tuscany.spi.deployer.DeploymentContext; +import org.apache.tuscany.spi.idl.java.JavaInterfaceProcessorRegistry; +import org.apache.tuscany.spi.idl.java.JavaServiceContract; +import org.apache.tuscany.spi.implementation.java.ConstructorDefinition; +import org.apache.tuscany.spi.implementation.java.JavaMappedProperty; +import org.apache.tuscany.spi.implementation.java.JavaMappedReference; +import org.apache.tuscany.spi.implementation.java.JavaMappedService; +import org.apache.tuscany.spi.implementation.java.PojoComponentType; +import org.apache.tuscany.spi.model.BindlessServiceDefinition; +import org.apache.tuscany.spi.model.ComponentDefinition; +import org.apache.tuscany.spi.model.CompositeComponentType; +import org.apache.tuscany.spi.model.CompositeImplementation; +import org.apache.tuscany.spi.model.ReferenceDefinition; +import org.apache.tuscany.spi.model.ReferenceTarget; +import org.apache.tuscany.spi.model.Scope; +import org.apache.tuscany.spi.model.ServiceContract; +import org.apache.tuscany.spi.model.ServiceDefinition; +import org.apache.tuscany.spi.wire.WireService; + +import junit.framework.TestCase; +import org.apache.tuscany.core.builder.BuilderRegistryImpl; +import org.apache.tuscany.core.builder.ConnectorImpl; +import org.apache.tuscany.core.deployer.RootDeploymentContext; +import org.apache.tuscany.core.idl.java.JavaInterfaceProcessorRegistryImpl; +import org.apache.tuscany.core.implementation.java.JavaComponentBuilder; +import org.apache.tuscany.core.implementation.java.JavaImplementation; +import org.apache.tuscany.core.implementation.java.mock.components.OtherTarget; +import org.apache.tuscany.core.implementation.java.mock.components.Source; +import org.apache.tuscany.core.implementation.java.mock.components.SourceImpl; +import org.apache.tuscany.core.implementation.java.mock.components.Target; +import org.apache.tuscany.core.implementation.java.mock.components.TargetImpl; +import org.apache.tuscany.core.wire.jdk.JDKWireService; +import org.easymock.EasyMock; +import org.easymock.IAnswer; + +/** + * @version $$Rev$$ $$Date$$ + */ +public class CompositeBuilderTestCase extends TestCase { + private DeploymentContext deploymentContext; + + protected void setUp() throws Exception { + super.setUp(); + ScopeContainer mock = createMock(); + deploymentContext = new RootDeploymentContext(null, null, mock, null); + } + + @SuppressWarnings("unchecked") + public void testBuildConnect() throws Exception { + CompositeComponent parent = new CompositeComponentImpl(null, null, null, null); + + CompositeBuilder builder = new CompositeBuilder(); + WireService wireService = new JDKWireService(); + builder.setWireService(wireService); + BuilderRegistryImpl builderRegistry = new BuilderRegistryImpl(); + builderRegistry.setWireService(wireService); + JavaComponentBuilder jBuilder = new JavaComponentBuilder(); + jBuilder.setWireService(wireService); + builderRegistry.register(JavaImplementation.class, jBuilder); + builderRegistry.register(CompositeImplementation.class, builder); + CompositeBindlessBuilder bindlessBuilder = new CompositeBindlessBuilder(); + bindlessBuilder.setWireService(wireService); + builderRegistry.register(bindlessBuilder); + builder.setBuilderRegistry(builderRegistry); + CompositeComponent component = + (CompositeComponent) builder.build(parent, createTopComponentDef(), deploymentContext); + + ConnectorImpl connector = new ConnectorImpl(); + connector.connect(component); + + deploymentContext.getModuleScope().start(); + component.start(); + CompositeComponent sourceComponent = (CompositeComponent) component.getChild("SourceComponent"); + Source source = (Source) sourceComponent.getServiceInstance("InnerSourceService"); + assertNotNull(source); + AtomicComponent innerSourceComponent = (AtomicComponent) sourceComponent.getChild("InnerSourceComponent"); + Source innerSourceInstance = (Source) deploymentContext.getModuleScope().getInstance(innerSourceComponent); + assertNotNull(innerSourceInstance); + component.stop(); + } + + private ComponentDefinition createTopComponentDef() throws Exception { + + CompositeComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>> outerType = + new CompositeComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>>(); + outerType.add(createSourceComponentDef()); + outerType.add(createTargetComponentDef()); + + CompositeImplementation outerImpl = new CompositeImplementation(); + outerImpl.setComponentType(outerType); + + return new ComponentDefinition<CompositeImplementation>(outerImpl); + } + + private ComponentDefinition<CompositeImplementation> createSourceComponentDef() throws Exception { + + CompositeComponentType<ServiceDefinition, ReferenceDefinition, JavaMappedProperty<?>> innerType = + new CompositeComponentType<ServiceDefinition, ReferenceDefinition, JavaMappedProperty<?>>(); + innerType.add(createInnerSourceComponentDef()); + ReferenceDefinition reference = new ReferenceDefinition(); + reference.setName("TargetComponentRef"); + JavaInterfaceProcessorRegistry registry = new JavaInterfaceProcessorRegistryImpl(); + JavaServiceContract targetContract = registry.introspect(Target.class); + reference.setServiceContract(targetContract); + innerType.add(reference); + BindlessServiceDefinition service = new BindlessServiceDefinition(); + service.setName("InnerSourceService"); + JavaServiceContract sourceContract = registry.introspect(Source.class); + service.setServiceContract(sourceContract); + service.setTarget(new URI("InnerSourceComponent")); + innerType.add(service); + + CompositeImplementation innerImpl = new CompositeImplementation(); + innerImpl.setComponentType(innerType); + + ComponentDefinition<CompositeImplementation> sourceComponentDefinition = + new ComponentDefinition<CompositeImplementation>("SourceComponent", innerImpl); + ReferenceTarget refTarget = new ReferenceTarget(); + refTarget.setReferenceName("TargetComponentRef"); + refTarget.addTarget(new URI("TargetComponent")); + sourceComponentDefinition.add(refTarget); + + return sourceComponentDefinition; + } + + private ComponentDefinition<JavaImplementation> createInnerSourceComponentDef() throws Exception { + + PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>> sourceType = + new PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>>(); + sourceType.setImplementationScope(Scope.MODULE); + JavaMappedReference reference = new JavaMappedReference(); + reference.setName("targetReference"); + JavaInterfaceProcessorRegistry registry = new JavaInterfaceProcessorRegistryImpl(); + ServiceContract<?> targetContract = registry.introspect(Target.class); + targetContract.setCallbackClass(OtherTarget.class); + targetContract.setCallbackName("OtherTarget"); + reference.setServiceContract(targetContract); + reference.setMember(SourceImpl.class.getMethod("setTarget", Target.class)); + sourceType.add(reference); + + ServiceContract<?> sourceContract = registry.introspect(Source.class); + + JavaMappedService sourceServiceDefinition = new JavaMappedService(); + sourceServiceDefinition.setName("Source"); + sourceServiceDefinition.setServiceContract(sourceContract); + + sourceType.add(sourceServiceDefinition); + sourceType.setConstructorDefinition(new ConstructorDefinition<SourceImpl>(SourceImpl.class.getConstructor())); + JavaImplementation sourceImpl = new JavaImplementation(); + sourceImpl.setComponentType(sourceType); + sourceImpl.setImplementationClass(SourceImpl.class); + ComponentDefinition<JavaImplementation> innerSourceComponentDefinition = + new ComponentDefinition<JavaImplementation>("InnerSourceComponent", sourceImpl); + ReferenceTarget refTarget = new ReferenceTarget(); + refTarget.setReferenceName("targetReference"); + refTarget.addTarget(new URI("TargetComponentRef")); + innerSourceComponentDefinition.add(refTarget); + + return innerSourceComponentDefinition; + } + + private ComponentDefinition<JavaImplementation> createTargetComponentDef() throws Exception { + + PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>> targetType = + new PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>>(); + targetType.setImplementationScope(Scope.MODULE); + + JavaInterfaceProcessorRegistry registry = new JavaInterfaceProcessorRegistryImpl(); + ServiceContract<?> targetContract = registry.introspect(Target.class); + targetContract.setCallbackClass(OtherTarget.class); + targetContract.setCallbackName("OtherTarget"); + + JavaMappedService serviceDefinition = new JavaMappedService(); + serviceDefinition.setName("Target"); + serviceDefinition.setServiceContract(targetContract); + serviceDefinition.setCallbackReferenceName("otherTarget"); + + targetType.add(serviceDefinition); + targetType.setConstructorDefinition(new ConstructorDefinition<TargetImpl>(TargetImpl.class.getConstructor())); + JavaImplementation targetImpl = new JavaImplementation(); + targetImpl.setComponentType(targetType); + targetImpl.setImplementationClass(TargetImpl.class); + return new ComponentDefinition<JavaImplementation>("TargetComponent", targetImpl); + } + + private ScopeContainer createMock() { + ScopeContainer container = EasyMock.createMock(ScopeContainer.class); + container.start(); + container.register(EasyMock.isA(AtomicComponent.class)); + EasyMock.expectLastCall().anyTimes(); + EasyMock.expect(container.getScope()).andReturn(Scope.MODULE).anyTimes(); + EasyMock.expect(container.getInstance(EasyMock.isA(AtomicComponent.class))).andAnswer(new IAnswer<Object>() { + private Map<AtomicComponent, Object> cache = new HashMap<AtomicComponent, Object>(); + + public Object answer() throws Throwable { + AtomicComponent component = (AtomicComponent) EasyMock.getCurrentArguments()[0]; + Object instance = cache.get(component); + if (instance == null) { + instance = component.createInstance(); + cache.put(component, instance); + } + return instance; + } + }); + EasyMock.replay(container); + return container; + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/composite/CompositeComponentImplBasicTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/composite/CompositeComponentImplBasicTestCase.java new file mode 100644 index 0000000000..8694d9ddc6 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/composite/CompositeComponentImplBasicTestCase.java @@ -0,0 +1,223 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.implementation.composite; + +import java.util.List; + +import org.apache.tuscany.spi.component.ComponentNotFoundException; +import org.apache.tuscany.spi.component.CompositeComponent; +import org.apache.tuscany.spi.component.IllegalTargetException; +import org.apache.tuscany.spi.component.Reference; +import org.apache.tuscany.spi.component.Service; +import org.apache.tuscany.spi.component.TargetNotFoundException; +import org.apache.tuscany.spi.event.Event; +import org.apache.tuscany.spi.event.RuntimeEventListener; +import org.apache.tuscany.spi.extension.ServiceExtension; +import org.apache.tuscany.spi.model.Scope; + +import junit.framework.Assert; +import junit.framework.TestCase; +import org.apache.tuscany.core.component.event.CompositeStart; +import org.easymock.EasyMock; +import static org.easymock.EasyMock.createMock; +import static org.easymock.EasyMock.eq; +import static org.easymock.EasyMock.expectLastCall; +import static org.easymock.EasyMock.isA; +import static org.easymock.EasyMock.replay; + +/** + * @version $Rev$ $Date$ + */ +public class CompositeComponentImplBasicTestCase extends TestCase { + + public void testGetScope() { + CompositeComponent composite = new CompositeComponentImpl("parent", null, null, null); + Assert.assertEquals(Scope.COMPOSITE, composite.getScope()); + } + + public void testGetChildren() { + CompositeComponent composite = new CompositeComponentImpl("parent", null, null, null); + composite.register(new ServiceExtension("foo", null, null, null)); + Assert.assertEquals(1, composite.getChildren().size()); + } + + public void testGetServices() { + CompositeComponent composite = new CompositeComponentImpl("parent", null, null, null); + composite.register(new ServiceExtension("foo", null, null, null)); + composite.register(getReference("bar")); + Assert.assertEquals(1, composite.getServices().size()); + } + + public void testGetService() { + CompositeComponent composite = new CompositeComponentImpl("parent", null, null, null); + composite.register(new ServiceExtension("foo", null, null, null)); + composite.start(); + assertNotNull(composite.getService("foo")); + } + + public void testServiceNotFound() { + CompositeComponent composite = new CompositeComponentImpl("parent", null, null, null); + composite.register(new ServiceExtension("foo", null, null, null)); + composite.start(); + try { + composite.getService("bar"); + fail(); + } catch (ComponentNotFoundException e) { + // expected + } + } + + public void testNotService() { + CompositeComponent composite = new CompositeComponentImpl("parent", null, null, null); + composite.register(getReference("foo")); + composite.start(); + try { + composite.getService("foo"); + fail(); + } catch (ComponentNotFoundException e) { + // expected + } + } + + public void testTargetNotFound() { + CompositeComponent composite = new CompositeComponentImpl("parent", null, null, null); + composite.register(getReference("foo")); + composite.start(); + try { + composite.locateService(Foo.class, "foo1"); + fail(); + } catch (TargetNotFoundException e) { + // expected + } + } + + public void testReferencesServices() { + CompositeComponent composite = new CompositeComponentImpl("parent", null, null, null); + composite.register(new ServiceExtension("foo", null, null, null)); + composite.register(getReference("bar")); + Assert.assertEquals(1, composite.getReferences().size()); + } + + public void testServiceInterfaces() { + CompositeComponent composite = new CompositeComponentImpl("parent", null, null, null); + Service service1 = getService("foo", Foo.class); + composite.register(service1); + Service service2 = getService("bar", Bar.class); + composite.register(service2); + + List<Class<?>> interfaces = composite.getServiceInterfaces(); + assertEquals(2, interfaces.size()); + for (Class o : interfaces) { + if (!(Foo.class.isAssignableFrom(o)) && !(Bar.class.isAssignableFrom(o))) { + fail(); + } + } + } + + public void testGetServiceInstanceByName() { + CompositeComponent composite = new CompositeComponentImpl("parent", null, null, null); + Service service = createMock(Service.class); + EasyMock.expect(service.isSystem()).andReturn(false).atLeastOnce(); + service.getName(); + expectLastCall().andReturn("foo").anyTimes(); + service.getInterface(); + expectLastCall().andReturn(Foo.class); + service.getServiceInstance(); + expectLastCall().andReturn(new Foo() { + }); + replay(service); + composite.register(service); + assertNotNull(composite.getServiceInstance("foo")); + } + + public void testGetServiceInstanceNotFound() { + CompositeComponent composite = new CompositeComponentImpl("parent", null, null, null); + Service service = getService("foo", Foo.class); + composite.register(service); + try { + composite.getServiceInstance("bar"); + fail(); + } catch (TargetNotFoundException e) { + //expected + } + } + + public void testGetServiceInstanceNotService() { + CompositeComponent composite = new CompositeComponentImpl("parent", null, null, null); + Reference reference = getReference("foo"); + composite.register(reference); + try { + composite.getServiceInstance("foo"); + fail(); + } catch (IllegalTargetException e) { + //expected + } + } + + public void testOnEvent() { + CompositeComponent composite = new CompositeComponentImpl("parent", null, null, null); + Event event = new Event() { + public Object getSource() { + return null; + } + }; + RuntimeEventListener listener = createMock(RuntimeEventListener.class); + listener.onEvent(isA(CompositeStart.class)); + listener.onEvent(eq(event)); + expectLastCall(); + replay(listener); + composite.addListener(listener); + composite.start(); + composite.onEvent(event); + } + + public void testPrepare() { + CompositeComponent composite = new CompositeComponentImpl("parent", null, null, null); + composite.prepare(); + } + + private Reference getReference(String name) { + Reference reference = EasyMock.createNiceMock(Reference.class); + EasyMock.expect(reference.isSystem()).andReturn(false).atLeastOnce(); + reference.getName(); + expectLastCall().andReturn(name).anyTimes(); + reference.getInterface(); + expectLastCall().andReturn(Object.class).atLeastOnce(); + replay(reference); + return reference; + } + + private Service getService(String name, Class<?> interfaze) { + Service service = createMock(Service.class); + EasyMock.expect(service.isSystem()).andReturn(false).atLeastOnce(); + service.getName(); + expectLastCall().andReturn(name).anyTimes(); + service.getInterface(); + expectLastCall().andReturn(interfaze).atLeastOnce(); + replay(service); + return service; + } + + private interface Foo { + } + + private interface Bar { + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/composite/CompositeComponentImplSystemWireTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/composite/CompositeComponentImplSystemWireTestCase.java new file mode 100644 index 0000000000..c3bf846400 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/composite/CompositeComponentImplSystemWireTestCase.java @@ -0,0 +1,168 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.implementation.composite; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.apache.tuscany.spi.QualifiedName; +import org.apache.tuscany.spi.builder.BuilderConfigException; +import org.apache.tuscany.spi.component.AtomicComponent; +import org.apache.tuscany.spi.component.CompositeComponent; +import org.apache.tuscany.spi.component.SystemAtomicComponent; +import org.apache.tuscany.spi.idl.java.JavaServiceContract; +import org.apache.tuscany.spi.model.Scope; +import org.apache.tuscany.spi.wire.InboundWire; +import org.apache.tuscany.spi.wire.OutboundWire; + +import junit.framework.TestCase; +import org.apache.tuscany.core.builder.ConnectorImpl; +import org.easymock.EasyMock; + +/** + * @version $Rev$ $Date$ + */ +public class CompositeComponentImplSystemWireTestCase extends TestCase { + + /** + * Verifies system services in a CompositeComponentImpl are wired during the parent composite's prepare callback + */ + public void testSystemServiceWire() { + InboundWire inbound = EasyMock.createMock(InboundWire.class); + EasyMock.expect(inbound.getServiceContract()).andReturn(new JavaServiceContract(Foo.class)); + inbound.getInvocationChains(); + EasyMock.expectLastCall().andReturn(Collections.emptyMap()); + + List<Class<?>> services = new ArrayList<Class<?>>(); + services.add(Foo.class); + QualifiedName qName = new QualifiedName("target/bar"); + OutboundWire outbound = EasyMock.createMock(OutboundWire.class); + EasyMock.expect(outbound.getTargetName()).andReturn(qName).atLeastOnce(); + outbound.getInvocationChains(); + EasyMock.expectLastCall().andReturn(Collections.emptyMap()); + outbound.setTargetWire(EasyMock.eq(inbound)); + EasyMock.expect(outbound.getServiceContract()).andReturn(new JavaServiceContract(Foo.class)).atLeastOnce(); + List<OutboundWire> wires = new ArrayList<OutboundWire>(); + wires.add(outbound); + Map<String, List<OutboundWire>> wireMap = new HashMap<String, List<OutboundWire>>(); + wireMap.put("ref", wires); + CompositeComponent parent = new CompositeComponentImpl("foo", "foo", null, new ConnectorImpl(), null); + SystemAtomicComponent source = EasyMock.createMock(SystemAtomicComponent.class); + EasyMock.expect(source.getScope()).andReturn(Scope.MODULE).atLeastOnce(); + EasyMock.expect(source.getName()).andReturn("source").atLeastOnce(); + EasyMock.expect(source.getServiceInterfaces()).andReturn(services); + EasyMock.expect(source.getOutboundWires()).andReturn(wireMap); + source.getInboundWires(); + EasyMock.expectLastCall().andReturn(Collections.emptyMap()); + EasyMock.expect(source.isSystem()).andReturn(true).atLeastOnce(); + EasyMock.expect(source.getParent()).andReturn(parent).atLeastOnce(); + + source.prepare(); + EasyMock.replay(source); + + EasyMock.expect(outbound.getContainer()).andReturn(source); + EasyMock.replay(outbound); + + parent.register(source); + + SystemAtomicComponent target = EasyMock.createMock(SystemAtomicComponent.class); + EasyMock.expect(target.getName()).andReturn("target").atLeastOnce(); + EasyMock.expect(target.getServiceInterfaces()).andReturn(services); + EasyMock.expect(target.getInboundWire("bar")).andReturn(inbound).atLeastOnce(); + EasyMock.expect(target.getScope()).andReturn(Scope.MODULE).atLeastOnce(); + EasyMock.expect(target.getParent()).andReturn(parent).atLeastOnce(); + target.getInboundWires(); + EasyMock.expectLastCall().andReturn(Collections.emptyMap()); + + target.prepare(); + target.getOutboundWires(); + EasyMock.expectLastCall().andReturn(Collections.emptyMap()); + EasyMock.expect(target.isSystem()).andReturn(true).atLeastOnce(); + EasyMock.replay(target); + + EasyMock.expect(inbound.getContainer()).andReturn(target); + EasyMock.replay(inbound); + + parent.register(target); + parent.prepare(); + EasyMock.verify(source); + EasyMock.verify(target); + EasyMock.verify(inbound); + EasyMock.verify(outbound); + } + + + /** + * Verifies an application component cannot be wired to a system service in the same composite + */ + public void testSystemServiceIsolationWire() { + InboundWire inbound = EasyMock.createMock(InboundWire.class); + EasyMock.replay(inbound); + + List<Class<?>> services = new ArrayList<Class<?>>(); + services.add(Foo.class); + QualifiedName qName = new QualifiedName("target/bar"); + OutboundWire outbound = EasyMock.createMock(OutboundWire.class); + EasyMock.expect(outbound.getReferenceName()).andReturn("foo"); + EasyMock.expect(outbound.getTargetName()).andReturn(qName).atLeastOnce(); + EasyMock.replay(outbound); + + List<OutboundWire> wires = new ArrayList<OutboundWire>(); + wires.add(outbound); + Map<String, List<OutboundWire>> wireMap = new HashMap<String, List<OutboundWire>>(); + wireMap.put("ref", wires); + CompositeComponent parent = new CompositeComponentImpl("foo", "foo", null, new ConnectorImpl(), null); + SystemAtomicComponent source = EasyMock.createMock(SystemAtomicComponent.class); + EasyMock.expect(source.getName()).andReturn("source").atLeastOnce(); + EasyMock.expect(source.getServiceInterfaces()).andReturn(services); + EasyMock.expect(source.getOutboundWires()).andReturn(wireMap); + EasyMock.expect(source.isSystem()).andReturn(true).atLeastOnce(); + EasyMock.expect(source.getParent()).andReturn(parent).atLeastOnce(); + EasyMock.replay(source); + + parent.register(source); + + AtomicComponent target = EasyMock.createMock(AtomicComponent.class); + EasyMock.expect(target.getName()).andReturn("target").atLeastOnce(); + EasyMock.expect(target.getServiceInterfaces()).andReturn(services); + EasyMock.expect(target.isSystem()).andReturn(false).atLeastOnce(); + EasyMock.replay(target); + + parent.register(target); + try { + parent.prepare(); + fail(); + } catch (BuilderConfigException e) { + //expected + } + EasyMock.verify(source); + EasyMock.verify(target); + EasyMock.verify(inbound); + EasyMock.verify(outbound); + } + + + private class Foo { + + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/composite/CompositeComponentImplTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/composite/CompositeComponentImplTestCase.java new file mode 100644 index 0000000000..29df7f0f85 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/composite/CompositeComponentImplTestCase.java @@ -0,0 +1,174 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.implementation.composite; + +import java.util.ArrayList; +import java.util.List; + +import org.apache.tuscany.spi.component.AtomicComponent; +import org.apache.tuscany.spi.component.CompositeComponent; +import org.apache.tuscany.spi.component.SystemAtomicComponent; + +import junit.framework.TestCase; +import org.easymock.EasyMock; + +/** + * @version $Rev$ $Date$ + */ +public class CompositeComponentImplTestCase extends TestCase { + + public void testSetUri() throws Exception { + CompositeComponentImpl component = new CompositeComponentImpl("foo", "foo/bar", null, null, null); + assertEquals("foo/bar", component.getURI()); + } + + public void testRegisterSystemService() throws Exception { + List<Class<?>> services = new ArrayList<Class<?>>(); + services.add(Foo.class); + CompositeComponent parent = new CompositeComponentImpl("foo", "foo", null, null, null); + SystemAtomicComponent component = EasyMock.createMock(SystemAtomicComponent.class); + EasyMock.expect(component.getName()).andReturn("bar").atLeastOnce(); + EasyMock.expect(component.getServiceInterfaces()).andReturn(services); + EasyMock.expect(component.isSystem()).andReturn(true).atLeastOnce(); + EasyMock.replay(component); + parent.register(component); + assertNull(parent.getChild("bar")); + assertNotNull(parent.getSystemChild("bar")); + EasyMock.verify(component); + } + + public void testRegister() throws Exception { + List<Class<?>> services = new ArrayList<Class<?>>(); + services.add(Foo.class); + CompositeComponent parent = new CompositeComponentImpl("foo", "foo", null, null, null); + AtomicComponent component = EasyMock.createMock(AtomicComponent.class); + EasyMock.expect(component.getName()).andReturn("bar").atLeastOnce(); + EasyMock.expect(component.getServiceInterfaces()).andReturn(services); + EasyMock.expect(component.isSystem()).andReturn(false).atLeastOnce(); + EasyMock.replay(component); + parent.register(component); + assertNull(parent.getSystemChild("bar")); + assertNotNull(parent.getChild("bar")); + EasyMock.verify(component); + } + + /** + * Verifies a system service and application component can be registered with the same name in a composite + */ + public void testSystemServiceApplicationNamespaceIsolation() throws Exception { + List<Class<?>> services = new ArrayList<Class<?>>(); + services.add(Foo.class); + CompositeComponent parent = new CompositeComponentImpl("foo", "foo", null, null, null); + SystemAtomicComponent component = EasyMock.createMock(SystemAtomicComponent.class); + EasyMock.expect(component.getName()).andReturn("bar").atLeastOnce(); + EasyMock.expect(component.getServiceInterfaces()).andReturn(services); + EasyMock.expect(component.isSystem()).andReturn(true).atLeastOnce(); + EasyMock.replay(component); + parent.register(component); + AtomicComponent component2 = EasyMock.createMock(AtomicComponent.class); + EasyMock.expect(component2.getName()).andReturn("bar").atLeastOnce(); + EasyMock.expect(component2.getServiceInterfaces()).andReturn(services); + EasyMock.expect(component2.isSystem()).andReturn(false).atLeastOnce(); + EasyMock.replay(component2); + parent.register(component2); + EasyMock.verify(component); + EasyMock.verify(component2); + } + + public void testSystemServiceLifecycle() throws Exception { + List<Class<?>> services = new ArrayList<Class<?>>(); + services.add(Foo.class); + CompositeComponent parent = new CompositeComponentImpl("foo", "foo", null, null, null); + SystemAtomicComponent component = EasyMock.createMock(SystemAtomicComponent.class); + component.start(); + EasyMock.expect(component.getName()).andReturn("bar").atLeastOnce(); + EasyMock.expect(component.getServiceInterfaces()).andReturn(services); + EasyMock.expect(component.isSystem()).andReturn(true).atLeastOnce(); + component.stop(); + EasyMock.replay(component); + parent.register(component); + parent.start(); + parent.stop(); + EasyMock.verify(component); + } + + public void testComponentLifecycle() throws Exception { + List<Class<?>> services = new ArrayList<Class<?>>(); + services.add(Foo.class); + CompositeComponent parent = new CompositeComponentImpl("foo", "foo", null, null, null); + AtomicComponent component = EasyMock.createMock(AtomicComponent.class); + component.start(); + EasyMock.expect(component.getName()).andReturn("bar").atLeastOnce(); + EasyMock.expect(component.getServiceInterfaces()).andReturn(services); + EasyMock.expect(component.isSystem()).andReturn(false).atLeastOnce(); + component.stop(); + EasyMock.replay(component); + parent.register(component); + parent.start(); + parent.stop(); + EasyMock.verify(component); + } + + public void testSystemServiceAutowire() throws Exception { + List<Class<?>> services = new ArrayList<Class<?>>(); + services.add(Foo.class); + CompositeComponent parent = new CompositeComponentImpl("foo", "foo", null, null, null); + SystemAtomicComponent component = EasyMock.createMock(SystemAtomicComponent.class); + component.start(); + EasyMock.expect(component.getName()).andReturn("bar").atLeastOnce(); + EasyMock.expect(component.getServiceInterfaces()).andReturn(services); + EasyMock.expect(component.getServiceInstance()).andReturn(new Foo() { + }); + EasyMock.expect(component.isSystem()).andReturn(true).atLeastOnce(); + component.stop(); + EasyMock.replay(component); + parent.register(component); + parent.start(); + assertNull(parent.resolveSystemExternalInstance(Foo.class)); + assertNotNull(parent.resolveSystemInstance(Foo.class)); + parent.stop(); + EasyMock.verify(component); + } + + + public void testAutowire() throws Exception { + List<Class<?>> services = new ArrayList<Class<?>>(); + services.add(Foo.class); + CompositeComponent parent = new CompositeComponentImpl("foo", "foo", null, null, null); + SystemAtomicComponent component = EasyMock.createMock(SystemAtomicComponent.class); + component.start(); + EasyMock.expect(component.getName()).andReturn("bar").atLeastOnce(); + EasyMock.expect(component.getServiceInterfaces()).andReturn(services); + EasyMock.expect(component.getServiceInstance()).andReturn(new Foo() { + }); + EasyMock.expect(component.isSystem()).andReturn(false).atLeastOnce(); + component.stop(); + EasyMock.replay(component); + parent.register(component); + parent.start(); + assertNull(parent.resolveExternalInstance(Foo.class)); + assertNotNull(parent.resolveInstance(Foo.class)); + parent.stop(); + EasyMock.verify(component); + } + + private class Foo { + + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/composite/CompositeComponentResolutionTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/composite/CompositeComponentResolutionTestCase.java new file mode 100644 index 0000000000..0ad1e6f649 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/composite/CompositeComponentResolutionTestCase.java @@ -0,0 +1,167 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.implementation.composite; + +import java.util.ArrayList; +import java.util.List; + +import org.apache.tuscany.spi.component.AtomicComponent; +import org.apache.tuscany.spi.component.ComponentNotFoundException; +import org.apache.tuscany.spi.component.CompositeComponent; +import org.apache.tuscany.spi.component.Service; +import org.apache.tuscany.spi.component.SystemAtomicComponent; + +import junit.framework.TestCase; +import org.apache.tuscany.core.mock.component.Source; +import org.apache.tuscany.core.mock.component.SourceImpl; +import org.easymock.EasyMock; + +/** + * Verifies an atomic component can be resolved from its parent + * + * @version $$Rev$$ $$Date$$ + */ +public class CompositeComponentResolutionTestCase extends TestCase { + + public void testSystemComponentResolution() throws NoSuchMethodException { + CompositeComponent parent = new CompositeComponentImpl("foo", null, null, null); + parent.start(); + List<Class<?>> interfaces = new ArrayList<Class<?>>(); + interfaces.add(Source.class); + Source originalSource = new SourceImpl(); + SystemAtomicComponent component = EasyMock.createMock(SystemAtomicComponent.class); + EasyMock.expect(component.getName()).andReturn("source").atLeastOnce(); + EasyMock.expect(component.getServiceInstance()).andReturn(originalSource); + EasyMock.expect(component.isSystem()).andReturn(true).atLeastOnce(); + EasyMock.expect(component.getServiceInterfaces()).andReturn(interfaces); + EasyMock.replay(component); + parent.register(component); + assertNull(parent.getChild("source")); + AtomicComponent target = (AtomicComponent) parent.getSystemChild("source"); + Source source = (Source) target.getServiceInstance(); + assertNotNull(source); + EasyMock.verify(component); + } + + public void testLocateSystemService() throws NoSuchMethodException { + CompositeComponent parent = new CompositeComponentImpl("foo", null, null, null); + parent.start(); + List<Class<?>> interfaces = new ArrayList<Class<?>>(); + interfaces.add(Source.class); + Source originalSource = new SourceImpl(); + SystemAtomicComponent component = EasyMock.createMock(SystemAtomicComponent.class); + EasyMock.expect(component.getName()).andReturn("source").atLeastOnce(); + EasyMock.expect(component.getServiceInstance()).andReturn(originalSource); + EasyMock.expect(component.isSystem()).andReturn(true).atLeastOnce(); + EasyMock.expect(component.getServiceInterfaces()).andReturn(interfaces); + EasyMock.replay(component); + parent.register(component); + Source source = parent.locateSystemService(Source.class, "source"); + assertNotNull(source); + EasyMock.verify(component); + } + + public void testLocateService() throws NoSuchMethodException { + CompositeComponent parent = new CompositeComponentImpl("foo", null, null, null); + parent.start(); + List<Class<?>> interfaces = new ArrayList<Class<?>>(); + interfaces.add(Source.class); + Source originalSource = new SourceImpl(); + AtomicComponent component = EasyMock.createMock(AtomicComponent.class); + EasyMock.expect(component.getName()).andReturn("source").atLeastOnce(); + EasyMock.expect(component.getServiceInstance()).andReturn(originalSource); + EasyMock.expect(component.isSystem()).andReturn(false).atLeastOnce(); + EasyMock.expect(component.getServiceInterfaces()).andReturn(interfaces); + EasyMock.replay(component); + parent.register(component); + Source source = parent.locateService(Source.class, "source"); + assertNotNull(source); + EasyMock.verify(component); + } + + public void testComponentResolution() throws NoSuchMethodException { + CompositeComponent parent = new CompositeComponentImpl("foo", null, null, null); + parent.start(); + List<Class<?>> interfaces = new ArrayList<Class<?>>(); + interfaces.add(Source.class); + Source originalSource = new SourceImpl(); + AtomicComponent component = EasyMock.createMock(AtomicComponent.class); + EasyMock.expect(component.getName()).andReturn("source").atLeastOnce(); + EasyMock.expect(component.getServiceInstance()).andReturn(originalSource); + EasyMock.expect(component.isSystem()).andReturn(false).atLeastOnce(); + EasyMock.expect(component.getServiceInterfaces()).andReturn(interfaces); + EasyMock.replay(component); + parent.register(component); + assertNull(parent.getSystemChild("source")); + AtomicComponent target = (AtomicComponent) parent.getChild("source"); + Source source = (Source) target.getServiceInstance(); + assertNotNull(source); + EasyMock.verify(component); + } + + + public void testGetService() throws NoSuchMethodException { + CompositeComponent parent = new CompositeComponentImpl("foo", null, null, null); + parent.start(); + Service service = EasyMock.createMock(Service.class); + EasyMock.expect(service.getName()).andReturn("source").atLeastOnce(); + EasyMock.expect(service.isSystem()).andReturn(false).atLeastOnce(); + service.getInterface(); + EasyMock.expectLastCall().andReturn(Source.class); + EasyMock.replay(service); + parent.register(service); + assertNotNull(parent.getService("source")); + try { + parent.getSystemService("source"); + fail(); + } catch (ComponentNotFoundException e) { + // expected + } + EasyMock.verify(service); + } + + public void testSystemGetService() throws NoSuchMethodException { + CompositeComponent parent = new CompositeComponentImpl("foo", null, null, null); + parent.start(); + Service service = EasyMock.createMock(Service.class); + EasyMock.expect(service.getName()).andReturn("source").atLeastOnce(); + EasyMock.expect(service.isSystem()).andReturn(true).atLeastOnce(); + service.getInterface(); + EasyMock.expectLastCall().andReturn(Source.class); + EasyMock.replay(service); + parent.register(service); + assertNotNull(parent.getSystemService("source")); + try { + parent.getService("source"); + fail(); + } catch (ComponentNotFoundException e) { + // expected + } + EasyMock.verify(service); + } + + + protected void setUp() throws Exception { + super.setUp(); + } + + protected void tearDown() throws Exception { + super.tearDown(); + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/composite/CompositeLifecycleTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/composite/CompositeLifecycleTestCase.java new file mode 100644 index 0000000000..5b0af72caa --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/composite/CompositeLifecycleTestCase.java @@ -0,0 +1,124 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.implementation.composite; + +import java.util.ArrayList; +import java.util.List; + +import org.apache.tuscany.spi.component.AtomicComponent; +import org.apache.tuscany.spi.component.CompositeComponent; +import org.apache.tuscany.spi.component.SystemAtomicComponent; + +import junit.framework.TestCase; +import org.apache.tuscany.core.mock.component.Source; +import org.apache.tuscany.core.mock.component.SourceImpl; +import org.easymock.EasyMock; + +/** + * @version $$Rev$$ $$Date$$ + */ +public class CompositeLifecycleTestCase extends TestCase { + + public void testLifecycle() throws Exception { + CompositeComponent composite = new CompositeComponentImpl("foo", null, null, null); + composite.start(); + assertNull(composite.getChild("nothtere")); + composite.stop(); + composite.start(); + assertNull(composite.getChild("nothtere")); + composite.stop(); + } + + public void testSystemRestart() throws NoSuchMethodException { + List<Class<?>> interfaces = new ArrayList<Class<?>>(); + interfaces.add(Source.class); + Source originalSource = new SourceImpl(); + SystemAtomicComponent component = EasyMock.createMock(SystemAtomicComponent.class); + component.start(); + component.stop(); + EasyMock.expectLastCall().times(2); + EasyMock.expect(component.getName()).andReturn("source").atLeastOnce(); + EasyMock.expect(component.isSystem()).andReturn(true).atLeastOnce(); + EasyMock.expect(component.getServiceInstance()).andReturn(originalSource).atLeastOnce(); + EasyMock.expect(component.getServiceInterfaces()).andReturn(interfaces); + EasyMock.replay(component); + + CompositeComponent composite = new CompositeComponentImpl("foo", null, null, null); + composite.start(); + composite.register(component); + + AtomicComponent atomicComponent = (AtomicComponent) composite.getSystemChild("source"); + Source source = (Source) atomicComponent.getServiceInstance(); + assertNotNull(source); + composite.stop(); + composite.start(); + atomicComponent = (AtomicComponent) composite.getSystemChild("source"); + Source source2 = (Source) atomicComponent.getServiceInstance(); + assertNotNull(source2); + composite.stop(); + EasyMock.verify(component); + } + + public void testRestart() throws NoSuchMethodException { + List<Class<?>> interfaces = new ArrayList<Class<?>>(); + interfaces.add(Source.class); + Source originalSource = new SourceImpl(); + AtomicComponent component = EasyMock.createMock(AtomicComponent.class); + component.start(); + component.stop(); + EasyMock.expectLastCall().times(2); + EasyMock.expect(component.getName()).andReturn("source").atLeastOnce(); + EasyMock.expect(component.isSystem()).andReturn(false).atLeastOnce(); + EasyMock.expect(component.getServiceInstance()).andReturn(originalSource).atLeastOnce(); + EasyMock.expect(component.getServiceInterfaces()).andReturn(interfaces); + EasyMock.replay(component); + + CompositeComponent composite = new CompositeComponentImpl("foo", null, null, null); + composite.start(); + composite.register(component); + + AtomicComponent atomicComponent = (AtomicComponent) composite.getChild("source"); + Source source = (Source) atomicComponent.getServiceInstance(); + assertNotNull(source); + composite.stop(); + composite.start(); + atomicComponent = (AtomicComponent) composite.getChild("source"); + Source source2 = (Source) atomicComponent.getServiceInstance(); + assertNotNull(source2); + composite.stop(); + EasyMock.verify(component); + } + + public void testChildStoppedBeforeParent() { + CompositeComponent parent = new CompositeComponentImpl("parent", null, null, null); + CompositeComponent child = new CompositeComponentImpl("child", null, null, null); + parent.register(child); + parent.start(); + child.stop(); + parent.stop(); + } + + protected void setUp() throws Exception { + super.setUp(); + } + + protected void tearDown() throws Exception { + super.tearDown(); + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/composite/CompositePropagationTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/composite/CompositePropagationTestCase.java new file mode 100644 index 0000000000..69b8c3f34f --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/composite/CompositePropagationTestCase.java @@ -0,0 +1,89 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.implementation.composite; + +import java.util.ArrayList; +import java.util.List; + +import org.apache.tuscany.spi.component.CompositeComponent; +import org.apache.tuscany.spi.component.SystemAtomicComponent; + +import junit.framework.TestCase; +import org.apache.tuscany.core.mock.component.Source; +import org.easymock.EasyMock; +import static org.easymock.EasyMock.createMock; +import static org.easymock.EasyMock.expect; +import static org.easymock.EasyMock.replay; +import static org.easymock.EasyMock.verify; + +/** + * + * @version $Rev$ $Date$ + */ +public class CompositePropagationTestCase extends TestCase { + + private CompositeComponent parent; + private CompositeComponent child2; + + public void testSystemLifecyclePropagation() throws NoSuchMethodException { + parent.start(); + List<Class<?>> interfaces = new ArrayList<Class<?>>(); + interfaces.add(Source.class); + SystemAtomicComponent component = createMock(SystemAtomicComponent.class); + expect(component.getName()).andReturn("source").anyTimes(); + component.stop(); + expect(component.getServiceInterfaces()).andReturn(interfaces); + EasyMock.expect(component.isSystem()).andReturn(true).atLeastOnce(); + replay(component); + child2.register(component); + parent.stop(); + verify(component); + } + + public void testLifecyclePropagation() throws NoSuchMethodException { + parent.start(); + List<Class<?>> interfaces = new ArrayList<Class<?>>(); + interfaces.add(Source.class); + SystemAtomicComponent component = createMock(SystemAtomicComponent.class); + expect(component.getName()).andReturn("source").anyTimes(); + component.stop(); + expect(component.getServiceInterfaces()).andReturn(interfaces); + EasyMock.expect(component.isSystem()).andReturn(false).atLeastOnce(); + replay(component); + child2.register(component); + parent.stop(); + verify(component); + } + + + protected void setUp() throws Exception { + super.setUp(); + parent = new CompositeComponentImpl("parent", null, null, null); + CompositeComponent child1 = new CompositeComponentImpl("child1", parent, null, null); + child2 = new CompositeComponentImpl("child2", child1, null, null); + child1.register(child2); + parent.register(child1); + } + + protected void tearDown() throws Exception { + parent.stop(); + super.tearDown(); + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/composite/CompositeReferenceCallbackTargetInvokerInvocationExceptionTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/composite/CompositeReferenceCallbackTargetInvokerInvocationExceptionTestCase.java new file mode 100644 index 0000000000..b1e850d703 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/composite/CompositeReferenceCallbackTargetInvokerInvocationExceptionTestCase.java @@ -0,0 +1,120 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.implementation.composite; + +import java.lang.reflect.Type; +import java.util.HashMap; +import java.util.Map; + +import org.apache.tuscany.spi.component.WorkContext; +import org.apache.tuscany.spi.model.Operation; +import org.apache.tuscany.spi.wire.InboundWire; +import org.apache.tuscany.spi.wire.Interceptor; +import org.apache.tuscany.spi.wire.Message; +import org.apache.tuscany.spi.wire.MessageImpl; +import org.apache.tuscany.spi.wire.OutboundInvocationChain; + +import junit.framework.TestCase; +import org.easymock.EasyMock; + +/** + * @version $Rev$ $Date$ + */ +public class CompositeReferenceCallbackTargetInvokerInvocationExceptionTestCase extends TestCase { + private InboundWire wire; + private WorkContext context; + private Message message; + private OutboundInvocationChain chain; + private CompositeReferenceCallbackTargetInvoker invoker; + + /** + * Verfies an InvocationTargetException thrown when invoking the target is propagated to the client correctly and + * the originating error is unwrapped + */ + public void testThrowableTargetInvocation() throws Exception { + Message response = invoker.invoke(message); + assertTrue(response.isFault()); + Object body = response.getBody(); + assertTrue(SomeException.class.equals(body.getClass())); + EasyMock.verify(wire); + EasyMock.verify(context); + EasyMock.verify(chain); + } + + protected void setUp() throws Exception { + super.setUp(); + Object id = new Object(); + Object corrId = new Object(); + Object targetAddress = new Object(); + message = new MessageImpl(); + message.setMessageId(id); + message.setCorrelationId(corrId); + message.setBody("foo"); + Message response = new MessageImpl(); + response.setBody("response"); + Operation<Type> operation = new Operation<Type>("echo", null, null, null); + Interceptor head = new ErrorInterceptor(); + chain = EasyMock.createMock(OutboundInvocationChain.class); + EasyMock.expect(chain.getTargetInvoker()).andReturn(null); + EasyMock.expect(chain.getHeadInterceptor()).andReturn(head); + EasyMock.replay(chain); + Map<Operation<?>, OutboundInvocationChain> chains = new HashMap<Operation<?>, OutboundInvocationChain>(); + chains.put(operation, chain); + wire = EasyMock.createMock(InboundWire.class); + EasyMock.expect(wire.retrieveMapping(corrId)).andReturn(targetAddress); + EasyMock.expect(wire.getSourceCallbackInvocationChains(targetAddress)).andReturn(chains); + EasyMock.expect(wire.getContainer()).andReturn(null); + EasyMock.replay(wire); + context = EasyMock.createMock(WorkContext.class); + context.setCurrentMessageId(EasyMock.eq(id)); + context.setCurrentMessageId(EasyMock.isNull()); + context.setCurrentCorrelationId(corrId); + context.setCurrentCorrelationId(EasyMock.isNull()); + EasyMock.expect(context.getCurrentMessageId()).andReturn(id); + EasyMock.expect(context.getCurrentCorrelationId()).andReturn(corrId); + EasyMock.replay(context); + invoker = new CompositeReferenceCallbackTargetInvoker(operation, wire, context); + } + + private class SomeException extends Exception { + + } + + private class ErrorInterceptor implements Interceptor { + + public Message invoke(Message msg) { + msg.setBodyWithFault(new SomeException()); + return msg; + } + + public void setNext(Interceptor next) { + + } + + public Interceptor getNext() { + return null; + } + + public boolean isOptimizable() { + return false; + } + } + + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/composite/CompositeReferenceCallbackTargetInvokerTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/composite/CompositeReferenceCallbackTargetInvokerTestCase.java new file mode 100644 index 0000000000..8e047e3ad1 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/composite/CompositeReferenceCallbackTargetInvokerTestCase.java @@ -0,0 +1,97 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.implementation.composite; + +import java.lang.reflect.Type; +import java.util.HashMap; +import java.util.Map; + +import org.apache.tuscany.spi.component.WorkContext; +import org.apache.tuscany.spi.model.Operation; +import org.apache.tuscany.spi.wire.InboundWire; +import org.apache.tuscany.spi.wire.Interceptor; +import org.apache.tuscany.spi.wire.Message; +import org.apache.tuscany.spi.wire.MessageImpl; +import org.apache.tuscany.spi.wire.OutboundInvocationChain; + +import junit.framework.TestCase; +import org.easymock.EasyMock; + +/** + * @version $Rev$ $Date$ + */ +public class CompositeReferenceCallbackTargetInvokerTestCase extends TestCase { + private InboundWire wire; + private WorkContext context; + private Message message; + private OutboundInvocationChain chain; + private Interceptor head; + private CompositeReferenceCallbackTargetInvoker invoker; + + /** + * Verfies the normal execution path through a callback + */ + public void testNormalPathMessageInvocation() throws Exception { + Message response = invoker.invoke(message); + assertEquals("response", response.getBody()); + EasyMock.verify(wire); + EasyMock.verify(context); + EasyMock.verify(chain); + EasyMock.verify(head); + } + + protected void setUp() throws Exception { + super.setUp(); + Object id = new Object(); + Object corrId = new Object(); + Object targetAddress = new Object(); + message = new MessageImpl(); + message.setMessageId(id); + message.setCorrelationId(corrId); + message.setBody("foo"); + Message response = new MessageImpl(); + response.setBody("response"); + Operation<Type> operation = new Operation<Type>("echo", null, null, null); + head = EasyMock.createMock(Interceptor.class); + EasyMock.expect(head.invoke(EasyMock.isA(Message.class))).andReturn(response); + EasyMock.replay(head); + chain = EasyMock.createMock(OutboundInvocationChain.class); + EasyMock.expect(chain.getTargetInvoker()).andReturn(null); + EasyMock.expect(chain.getHeadInterceptor()).andReturn(head); + EasyMock.replay(chain); + Map<Operation<?>, OutboundInvocationChain> chains = new HashMap<Operation<?>, OutboundInvocationChain>(); + chains.put(operation, chain); + wire = EasyMock.createMock(InboundWire.class); + EasyMock.expect(wire.retrieveMapping(corrId)).andReturn(targetAddress); + EasyMock.expect(wire.getSourceCallbackInvocationChains(targetAddress)).andReturn(chains); + EasyMock.expect(wire.getContainer()).andReturn(null); + EasyMock.replay(wire); + context = EasyMock.createMock(WorkContext.class); + context.setCurrentMessageId(EasyMock.eq(id)); + context.setCurrentMessageId(EasyMock.isNull()); + context.setCurrentCorrelationId(corrId); + context.setCurrentCorrelationId(EasyMock.isNull()); + EasyMock.expect(context.getCurrentMessageId()).andReturn(id); + EasyMock.expect(context.getCurrentCorrelationId()).andReturn(corrId); + EasyMock.replay(context); + invoker = new CompositeReferenceCallbackTargetInvoker(operation, wire, context); + } + + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/composite/CompositeReferenceCallbackTargetInvokerThrowableTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/composite/CompositeReferenceCallbackTargetInvokerThrowableTestCase.java new file mode 100644 index 0000000000..462b6a5680 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/composite/CompositeReferenceCallbackTargetInvokerThrowableTestCase.java @@ -0,0 +1,113 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.implementation.composite; + +import java.lang.reflect.Type; +import java.lang.reflect.UndeclaredThrowableException; +import java.util.HashMap; +import java.util.Map; + +import org.apache.tuscany.spi.component.WorkContext; +import org.apache.tuscany.spi.model.Operation; +import org.apache.tuscany.spi.wire.InboundWire; +import org.apache.tuscany.spi.wire.Interceptor; +import org.apache.tuscany.spi.wire.Message; +import org.apache.tuscany.spi.wire.MessageImpl; +import org.apache.tuscany.spi.wire.OutboundInvocationChain; + +import junit.framework.TestCase; +import org.easymock.EasyMock; +import org.easymock.IAnswer; + +/** + * @version $Rev$ $Date$ + */ +public class CompositeReferenceCallbackTargetInvokerThrowableTestCase extends TestCase { + private InboundWire wire; + private WorkContext context; + private Message message; + private OutboundInvocationChain chain; + private Interceptor head; + private CompositeReferenceCallbackTargetInvoker invoker; + + /** + * Verfies an exception thrown in the target is propagated to the client correctly + */ + public void testThrowableTargetInvocation() throws Exception { + Message response = invoker.invoke(message); + assertTrue(response.isFault()); + Object body = response.getBody(); + if (!(body instanceof UndeclaredThrowableException)) { + fail(); // EasyMock wraps the Throwable in an UndeclaredThrowableException + } + UndeclaredThrowableException e = (UndeclaredThrowableException) body; + assertTrue(InsidiousException.class.equals(e.getUndeclaredThrowable().getClass())); + EasyMock.verify(wire); + EasyMock.verify(context); + EasyMock.verify(chain); + EasyMock.verify(head); + } + + protected void setUp() throws Exception { + super.setUp(); + Object id = new Object(); + Object corrId = new Object(); + Object targetAddress = new Object(); + message = new MessageImpl(); + message.setMessageId(id); + message.setCorrelationId(corrId); + message.setBody("foo"); + Message response = new MessageImpl(); + response.setBody("response"); + Operation<Type> operation = new Operation<Type>("echo", null, null, null); + head = EasyMock.createMock(Interceptor.class); + EasyMock.expect(head.invoke(EasyMock.isA(Message.class))).andStubAnswer(new IAnswer() { + public Object answer() throws Throwable { + throw new InsidiousException(); // andThrow() does not seem to work here + } + }); + EasyMock.replay(head); + chain = EasyMock.createMock(OutboundInvocationChain.class); + EasyMock.expect(chain.getTargetInvoker()).andReturn(null); + EasyMock.expect(chain.getHeadInterceptor()).andReturn(head); + EasyMock.replay(chain); + Map<Operation<?>, OutboundInvocationChain> chains = new HashMap<Operation<?>, OutboundInvocationChain>(); + chains.put(operation, chain); + wire = EasyMock.createMock(InboundWire.class); + EasyMock.expect(wire.retrieveMapping(corrId)).andReturn(targetAddress); + EasyMock.expect(wire.getSourceCallbackInvocationChains(targetAddress)).andReturn(chains); + EasyMock.expect(wire.getContainer()).andReturn(null); + EasyMock.replay(wire); + context = EasyMock.createMock(WorkContext.class); + context.setCurrentMessageId(EasyMock.eq(id)); + context.setCurrentMessageId(EasyMock.isNull()); + context.setCurrentCorrelationId(corrId); + context.setCurrentCorrelationId(EasyMock.isNull()); + EasyMock.expect(context.getCurrentMessageId()).andReturn(id); + EasyMock.expect(context.getCurrentCorrelationId()).andReturn(corrId); + EasyMock.replay(context); + invoker = new CompositeReferenceCallbackTargetInvoker(operation, wire, context); + } + + private class InsidiousException extends Throwable { + + } + + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/composite/CompositeReferenceTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/composite/CompositeReferenceTestCase.java new file mode 100644 index 0000000000..fe62691820 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/composite/CompositeReferenceTestCase.java @@ -0,0 +1,63 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.implementation.composite; + +import java.lang.reflect.Type; + +import org.apache.tuscany.spi.model.Operation; +import org.apache.tuscany.spi.model.ServiceContract; +import org.apache.tuscany.spi.wire.TargetInvoker; + +import junit.framework.TestCase; + +/** + * + */ +public class CompositeReferenceTestCase extends TestCase { + + public void testCreateTargetInvoker() throws Exception { + + MyServiceContract serviceContract = new MyServiceContract(); + CompositeReference compositeReference = new CompositeReference("testCompositeReferemce", + null, + null, + serviceContract, + null); + Operation operation = new Operation<Type>("sayHi", null, null, null, false, null); + TargetInvoker targetInvoker = compositeReference.createTargetInvoker(serviceContract, operation); + assertNotNull(targetInvoker); + } + + public void testCreateCallbackTargetInvoker() throws Exception { + + MyServiceContract serviceContract = new MyServiceContract(); + CompositeReference compositeReference = new CompositeReference("testCompositeReferemce", + null, + null, + serviceContract, + null); + Operation operation = new Operation<Type>("sayHi", null, null, null, false, null); + TargetInvoker targetInvoker = compositeReference.createCallbackTargetInvoker(serviceContract, operation); + assertNotNull(targetInvoker); + } + + class MyServiceContract extends ServiceContract { + + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/composite/DuplicateRegistrationTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/composite/DuplicateRegistrationTestCase.java new file mode 100644 index 0000000000..33235983b9 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/composite/DuplicateRegistrationTestCase.java @@ -0,0 +1,101 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.implementation.composite; + +import java.util.ArrayList; +import java.util.List; + +import org.apache.tuscany.spi.component.CompositeComponent; +import org.apache.tuscany.spi.component.DuplicateNameException; +import org.apache.tuscany.spi.component.SystemAtomicComponent; + +import junit.framework.TestCase; +import org.apache.tuscany.core.mock.component.Source; +import org.easymock.EasyMock; + +/** + * Verfies children with the same name cannot be registered in the same composite + * + * @version $Rev$ $Date$ + */ +public class DuplicateRegistrationTestCase extends TestCase { + + public void testDuplicateRegistration() throws Exception { + CompositeComponent parent = new CompositeComponentImpl(null, null, null, null); + parent.start(); + + List<Class<?>> interfaces = new ArrayList<Class<?>>(); + interfaces.add(Source.class); + SystemAtomicComponent component1 = EasyMock.createMock(SystemAtomicComponent.class); + EasyMock.expect(component1.getName()).andReturn("source").atLeastOnce(); + EasyMock.expect(component1.isSystem()).andReturn(true).atLeastOnce(); + component1.stop(); + EasyMock.expect(component1.getServiceInterfaces()).andReturn(interfaces); + EasyMock.replay(component1); + + SystemAtomicComponent component2 = EasyMock.createMock(SystemAtomicComponent.class); + EasyMock.expect(component2.getName()).andReturn("source").atLeastOnce(); + EasyMock.expect(component2.isSystem()).andReturn(true).atLeastOnce(); + component2.stop(); + EasyMock.expect(component2.getServiceInterfaces()).andReturn(interfaces); + EasyMock.replay(component2); + + parent.register(component1); + try { + parent.register(component2); + fail(); + } catch (DuplicateNameException e) { + // ok + } + parent.stop(); + } + + public void testDuplicateNameSystemService() throws Exception { + List<Class<?>> services = new ArrayList<Class<?>>(); + services.add(Source.class); + CompositeComponent parent = new CompositeComponentImpl("foo", "foo", null, null, null); + SystemAtomicComponent component = EasyMock.createMock(SystemAtomicComponent.class); + EasyMock.expect(component.getName()).andReturn("bar").atLeastOnce(); + EasyMock.expect(component.getServiceInterfaces()).andReturn(services); + EasyMock.expect(component.isSystem()).andReturn(true).atLeastOnce(); + EasyMock.replay(component); + parent.register(component); + SystemAtomicComponent component2 = EasyMock.createMock(SystemAtomicComponent.class); + EasyMock.expect(component2.getName()).andReturn("bar").atLeastOnce(); + EasyMock.expect(component2.getServiceInterfaces()).andReturn(services); + EasyMock.expect(component2.isSystem()).andReturn(true).atLeastOnce(); + EasyMock.replay(component2); + try { + parent.register(component2); + fail(); + } catch (DuplicateNameException e) { + // expected + } + } + + + protected void setUp() throws Exception { + super.setUp(); + } + + protected void tearDown() throws Exception { + super.tearDown(); + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/composite/ImplementationCompositeLoaderTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/composite/ImplementationCompositeLoaderTestCase.java new file mode 100644 index 0000000000..67efb6fd4c --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/composite/ImplementationCompositeLoaderTestCase.java @@ -0,0 +1,192 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.implementation.composite; + +import java.net.MalformedURLException; +import java.net.URL; +import javax.xml.namespace.QName; +import static javax.xml.stream.XMLStreamConstants.END_ELEMENT; +import javax.xml.stream.XMLStreamException; +import javax.xml.stream.XMLStreamReader; + +import junit.framework.TestCase; +import static org.easymock.EasyMock.createMock; +import static org.easymock.EasyMock.expect; +import static org.easymock.EasyMock.replay; +import static org.easymock.EasyMock.reportMatcher; +import static org.easymock.EasyMock.verify; +import org.easymock.IArgumentMatcher; +import static org.osoa.sca.Version.XML_NAMESPACE_1_0; + +import org.apache.tuscany.spi.deployer.DeploymentContext; +import org.apache.tuscany.spi.deployer.CompositeClassLoader; +import org.apache.tuscany.spi.loader.LoaderException; +import org.apache.tuscany.spi.model.CompositeImplementation; +import org.apache.tuscany.spi.services.artifact.Artifact; +import org.apache.tuscany.spi.services.artifact.ArtifactRepository; + +/** + * @version $Rev$ $Date$ + */ +public class ImplementationCompositeLoaderTestCase extends TestCase { + private static final QName IMPLEMENTATION_COMPOSITE = new QName(XML_NAMESPACE_1_0, "implementation.composite"); + + private ClassLoader cl; + private ImplementationCompositeLoader loader; + private XMLStreamReader reader; + private DeploymentContext context; + private ArtifactRepository artifactRepository; + + public void testName() throws LoaderException, XMLStreamException, MalformedURLException { + String name = "foo"; + expect(reader.getName()).andReturn(IMPLEMENTATION_COMPOSITE); + expect(reader.getAttributeValue(null, "name")).andReturn(name); + expect(reader.getAttributeValue(null, "group")).andReturn(null); + expect(reader.getAttributeValue(null, "version")).andReturn(null); + expect(reader.getAttributeValue(null, "scdlLocation")).andReturn(null); + expect(reader.getAttributeValue(null, "jarLocation")).andReturn(null); + expect(reader.next()).andReturn(END_ELEMENT); + replay(reader); + + replay(context); + replay(artifactRepository); + + CompositeImplementation impl = loader.load(null, reader, context); + verify(reader); + verify(context); + verify(artifactRepository); + assertEquals(name, impl.getName()); + assertNull(impl.getScdlLocation()); + assertNull(impl.getClassLoader()); + } + + public void testWithArtifact() throws LoaderException, XMLStreamException, MalformedURLException { + String name = "foo"; + expect(reader.getName()).andReturn(IMPLEMENTATION_COMPOSITE); + expect(reader.getAttributeValue(null, "name")).andReturn(name); + expect(reader.getAttributeValue(null, "group")).andReturn("com.example"); + expect(reader.getAttributeValue(null, "version")).andReturn("1.0"); + expect(reader.getAttributeValue(null, "scdlLocation")).andReturn(null); + expect(reader.getAttributeValue(null, "jarLocation")).andReturn(null); + expect(reader.next()).andReturn(END_ELEMENT); + replay(reader); + + expect(context.getClassLoader()).andReturn(cl); + replay(context); + URL url = new URL("http://www.example.com/sca/base.jar"); + artifactRepository.resolve(artifactMatcher(url, "com.example", name, "1.0")); + replay(artifactRepository); + + CompositeImplementation impl = loader.load(null, reader, context); + verify(reader); + verify(context); + verify(artifactRepository); + assertEquals(name, impl.getName()); + assertEquals(new URL("jar:http://www.example.com/sca/base.jar!/META-INF/sca/default.scdl"), impl.getScdlLocation()); + assertTrue(impl.getClassLoader() instanceof CompositeClassLoader); + } + + public void testWithScdlLocation() throws LoaderException, XMLStreamException, MalformedURLException { + String name = "foo"; + expect(reader.getName()).andReturn(IMPLEMENTATION_COMPOSITE); + expect(reader.getAttributeValue(null, "name")).andReturn(name); + expect(reader.getAttributeValue(null, "group")).andReturn(null); + expect(reader.getAttributeValue(null, "version")).andReturn(null); + expect(reader.getAttributeValue(null, "scdlLocation")).andReturn("bar.scdl"); + expect(reader.getAttributeValue(null, "jarLocation")).andReturn(null); + expect(reader.next()).andReturn(END_ELEMENT); + replay(reader); + + expect(context.getScdlLocation()).andReturn(new URL("http://www.example.com/sca/base.scdl")); + expect(context.getClassLoader()).andReturn(cl); + replay(context); + replay(artifactRepository); + + CompositeImplementation impl = loader.load(null, reader, context); + verify(reader); + verify(context); + verify(artifactRepository); + assertEquals(name, impl.getName()); + assertEquals(new URL("http://www.example.com/sca/bar.scdl"), impl.getScdlLocation()); + assertSame(cl, impl.getClassLoader()); + } + + public void testWithJarLocation() throws LoaderException, XMLStreamException, MalformedURLException { + String name = "foo"; + expect(reader.getName()).andReturn(IMPLEMENTATION_COMPOSITE); + expect(reader.getAttributeValue(null, "name")).andReturn(name); + expect(reader.getAttributeValue(null, "group")).andReturn(null); + expect(reader.getAttributeValue(null, "version")).andReturn(null); + expect(reader.getAttributeValue(null, "scdlLocation")).andReturn(null); + expect(reader.getAttributeValue(null, "jarLocation")).andReturn("bar.jar"); + expect(reader.next()).andReturn(END_ELEMENT); + replay(reader); + + expect(context.getScdlLocation()).andReturn(new URL("http://www.example.com/sca/base.scdl")); + expect(context.getClassLoader()).andReturn(cl); + replay(context); + replay(artifactRepository); + + CompositeImplementation impl = loader.load(null, reader, context); + verify(reader); + verify(context); + verify(artifactRepository); + assertEquals(name, impl.getName()); + assertEquals(new URL("jar:http://www.example.com/sca/bar.jar!/META-INF/sca/default.scdl"), + impl.getScdlLocation()); + } + + protected void setUp() throws Exception { + super.setUp(); + artifactRepository = createMock(ArtifactRepository.class); + reader = createMock(XMLStreamReader.class); + context = createMock(DeploymentContext.class); + cl = getClass().getClassLoader(); + loader = new ImplementationCompositeLoader(null, artifactRepository); + } + + protected static Artifact artifactMatcher(final URL url, + final String group, + final String name, + final String version) { + reportMatcher(new IArgumentMatcher() { + + public boolean matches(Object object) { + if (!(object instanceof Artifact)) { + return false; + } + + Artifact artifact = (Artifact) object; + boolean match = group.equals(artifact.getGroup()) && + name.equals(artifact.getName()) && + version.equals(artifact.getVersion()) && + "jar".equals(artifact.getType()); + if (match) { + artifact.setUrl(url); + } + return match; + } + + public void appendTo(StringBuffer stringBuffer) { + stringBuffer.append(group).append(':').append(name).append(':').append(version); + } + }); + return null; + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/composite/JavaObjectRegistrationTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/composite/JavaObjectRegistrationTestCase.java new file mode 100644 index 0000000000..c3267f8ec6 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/composite/JavaObjectRegistrationTestCase.java @@ -0,0 +1,86 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.implementation.composite; + +import javax.naming.ConfigurationException; + +import org.apache.tuscany.spi.component.CompositeComponent; +import org.apache.tuscany.spi.component.DuplicateNameException; + +import junit.framework.TestCase; +import org.apache.tuscany.core.component.event.CompositeStart; +import org.apache.tuscany.core.component.event.CompositeStop; + +/** + * @version $Rev$ $Date$ + */ +public class JavaObjectRegistrationTestCase extends TestCase { + private CompositeComponent composite; + + public void testRegistration() throws Exception { + MockComponent instance = new MockComponent(); + composite.registerJavaObject("foo", MockComponent.class, instance); + MockComponent resolvedInstance = (MockComponent) composite.getSystemChild("foo").getServiceInstance(); + assertSame(instance, resolvedInstance); + } + + public void testDuplicateRegistration() throws ConfigurationException { + MockComponent instance = new MockComponent(); + composite.registerJavaObject("foo", MockComponent.class, instance); + try { + composite.registerJavaObject("foo", MockComponent.class, instance); + fail(); + } catch (DuplicateNameException e) { + // ok + } + } + + public void testSystemAutowireToObject() { + MockComponent instance = new MockComponent(); + composite.registerJavaObject("foo", MockComponent.class, instance); + assertSame(instance, composite.resolveSystemInstance(MockComponent.class)); + assertNull(composite.resolveSystemExternalInstance(MockComponent.class)); + } + + public void testApplicationAutowireToObject() { + MockComponent instance = new MockComponent(); + composite.registerJavaObject("foo", MockComponent.class, instance); + assertNull(composite.resolveInstance(MockComponent.class)); + assertNull(composite.resolveExternalInstance(MockComponent.class)); + } + + protected void setUp() throws Exception { + super.setUp(); + composite = new CompositeComponentImpl(null, null, null, null); + composite.start(); + composite.publish(new CompositeStart(this, null)); + } + + protected void tearDown() throws Exception { + composite.publish(new CompositeStop(this, null)); + composite.stop(); + super.tearDown(); + } + + private static class MockComponent { + public String hello(String message) { + return message; + } + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/java/AsyncJavaTargetInvokerTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/java/AsyncJavaTargetInvokerTestCase.java new file mode 100644 index 0000000000..77e48991d5 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/java/AsyncJavaTargetInvokerTestCase.java @@ -0,0 +1,101 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.implementation.java; + +import java.lang.reflect.Method; + +import org.apache.tuscany.spi.component.WorkContext; +import org.apache.tuscany.spi.services.work.WorkScheduler; +import org.apache.tuscany.spi.wire.InboundWire; +import org.apache.tuscany.spi.wire.Message; +import org.apache.tuscany.spi.wire.MessageImpl; + +import junit.framework.TestCase; +import static org.apache.tuscany.core.implementation.java.mock.MockFactory.createJavaComponent; +import org.apache.tuscany.core.implementation.java.mock.components.AsyncTarget; +import static org.easymock.EasyMock.createMock; +import static org.easymock.EasyMock.expectLastCall; +import static org.easymock.EasyMock.getCurrentArguments; +import static org.easymock.EasyMock.isA; +import static org.easymock.EasyMock.replay; +import static org.easymock.EasyMock.verify; +import org.easymock.IAnswer; + +/** + * @version $Rev$ $Date$ + */ +public class AsyncJavaTargetInvokerTestCase extends TestCase { + + public void testInvoke() throws Exception { + AsyncTarget target = createMock(AsyncTarget.class); + target.invoke(); + expectLastCall().once(); + replay(target); + JavaAtomicComponent component = createJavaComponent(target); + AsyncMonitor monitor = createMock(AsyncMonitor.class); + replay(monitor); + + Message msg = new MessageImpl(); + Object id = new Object(); + msg.setMessageId(id); + + WorkContext context = createMock(WorkContext.class); + context.setCurrentMessageId(null); + context.setCurrentCorrelationId(id); + replay(context); + Method method = AsyncTarget.class.getMethod("invoke"); + method.setAccessible(true); + InboundWire wire = createMock(InboundWire.class); + AsyncJavaTargetInvoker invoker = + new AsyncJavaTargetInvoker(method, wire, component, monitor, context); + invoker.invoke(msg); + verify(target); + } + + public void testClone() throws Exception { + AsyncTarget target = createMock(AsyncTarget.class); + target.invoke(); + expectLastCall().once(); + replay(target); + JavaAtomicComponent component = createJavaComponent(target); + AsyncMonitor monitor = createMock(AsyncMonitor.class); + replay(monitor); + WorkScheduler scheduler = createMock(WorkScheduler.class); + scheduler.scheduleWork(isA(Runnable.class)); + expectLastCall().andStubAnswer(new IAnswer<Object>() { + public Object answer() throws Throwable { + Runnable runnable = (Runnable) getCurrentArguments()[0]; + runnable.run(); + return null; + } + }); + replay(scheduler); + WorkContext context = createMock(WorkContext.class); + InboundWire wire = createMock(InboundWire.class); + Method method = AsyncTarget.class.getMethod("invoke"); + method.setAccessible(true); + AsyncJavaTargetInvoker invoker = + new AsyncJavaTargetInvoker(method, wire, component, monitor, context); + AsyncJavaTargetInvoker clone = invoker.clone(); + Message msg = new MessageImpl(); + clone.invoke(msg); + verify(target); + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/java/DifferentInterfaceWireTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/java/DifferentInterfaceWireTestCase.java new file mode 100644 index 0000000000..64a573c6e5 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/java/DifferentInterfaceWireTestCase.java @@ -0,0 +1,128 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.implementation.java; + +import java.lang.reflect.Member; +import java.lang.reflect.Method; +import java.lang.reflect.Proxy; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.apache.tuscany.spi.component.AtomicComponent; +import org.apache.tuscany.spi.component.ScopeContainer; +import org.apache.tuscany.spi.model.Scope; + +import junit.framework.TestCase; +import org.apache.tuscany.core.implementation.java.mock.MockFactory; +import org.apache.tuscany.core.implementation.java.mock.components.OtherTarget; +import org.apache.tuscany.core.implementation.java.mock.components.OtherTargetImpl; +import org.apache.tuscany.core.implementation.java.mock.components.Source; +import org.apache.tuscany.core.implementation.java.mock.components.SourceImpl; +import org.apache.tuscany.core.implementation.java.mock.components.Target; +import org.easymock.EasyMock; +import org.easymock.IAnswer; + + +/** + * Tests wires that have different interfaces on the source and target side + * + * @version $Rev$ $Date$ + */ +public class DifferentInterfaceWireTestCase extends TestCase { + + public void testDifferentInterfaceInjection() throws Exception { + Map<String, Member> members = new HashMap<String, Member>(); + Method m = SourceImpl.class.getMethod("setTarget", Target.class); + members.put("target", m); + ScopeContainer scope = createMock(); + scope.start(); + Map<String, AtomicComponent> contexts = + MockFactory.createWiredComponents("source", + SourceImpl.class, + Target.class, + scope, + members, + "target", + OtherTarget.class, + OtherTargetImpl.class, + scope); + AtomicComponent sourceComponent = contexts.get("source"); + Source source = (Source) sourceComponent.getServiceInstance(); + Target target = source.getTarget(); + assertTrue(Proxy.isProxyClass(target.getClass())); + assertNotNull(target); + scope.stop(); + EasyMock.verify(scope); + } + + public void testDifferentInterfaceMultiplicityInjection() throws Exception { + Map<String, Member> members = new HashMap<String, Member>(); + Method m = SourceImpl.class.getMethod("setTargets", List.class); + members.put("target", m); + ScopeContainer scope = createMock(); + scope.start(); + Map<String, AtomicComponent> contexts = + MockFactory.createWiredMultiplicity("source", SourceImpl.class, Target.class, scope, + "target", OtherTarget.class, OtherTargetImpl.class, members, scope); + AtomicComponent sourceComponent = contexts.get("source"); + Source source = (Source) sourceComponent.getServiceInstance(); + List<Target> targets = source.getTargets(); + assertEquals(1, targets.size()); + Target target = targets.get(0); + target.setString("foo"); + assertEquals("foo", target.getString()); + assertTrue(Proxy.isProxyClass(target.getClass())); + scope.stop(); + EasyMock.verify(scope); + } + + protected void setUp() throws Exception { + super.setUp(); + } + + protected void tearDown() throws Exception { + super.tearDown(); + } + + private ScopeContainer createMock() { + ScopeContainer scope = EasyMock.createMock(ScopeContainer.class); + scope.start(); + scope.stop(); + scope.register(EasyMock.isA(AtomicComponent.class)); + EasyMock.expectLastCall().atLeastOnce(); + EasyMock.expect(scope.getScope()).andReturn(Scope.MODULE).atLeastOnce(); + scope.getInstance(EasyMock.isA(AtomicComponent.class)); + EasyMock.expectLastCall().andAnswer(new IAnswer<Object>() { + private Map<AtomicComponent, Object> cache = new HashMap<AtomicComponent, Object>(); + + public Object answer() throws Throwable { + AtomicComponent component = (AtomicComponent) EasyMock.getCurrentArguments()[0]; + Object instance = cache.get(component); + if (instance == null) { + instance = component.createInstance(); + cache.put(component, instance); + } + return instance; + } + }).anyTimes(); + EasyMock.replay(scope); + return scope; + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/java/GetServiceByNameTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/java/GetServiceByNameTestCase.java new file mode 100644 index 0000000000..4695866232 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/java/GetServiceByNameTestCase.java @@ -0,0 +1,73 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.implementation.java; + +import java.util.HashMap; +import java.util.Map; + +import org.apache.tuscany.spi.component.ScopeContainer; +import org.apache.tuscany.spi.idl.java.JavaServiceContract; +import org.apache.tuscany.spi.model.Operation; +import org.apache.tuscany.spi.model.Scope; +import org.apache.tuscany.spi.wire.InboundInvocationChain; +import org.apache.tuscany.spi.wire.InboundWire; + +import junit.framework.TestCase; +import org.apache.tuscany.core.implementation.PojoConfiguration; +import org.apache.tuscany.core.implementation.java.mock.components.Target; +import org.apache.tuscany.core.implementation.java.mock.components.TargetImpl; +import org.apache.tuscany.core.injection.PojoObjectFactory; +import org.apache.tuscany.core.wire.jdk.JDKWireService; +import org.easymock.EasyMock; +import static org.easymock.EasyMock.createMock; +import static org.easymock.EasyMock.expect; +import static org.easymock.EasyMock.replay; + +/** + * @version $$Rev$$ $$Date$$ + */ +public class GetServiceByNameTestCase extends TestCase { + + public void testServiceLocate() throws Exception { + ScopeContainer scope = createMock(ScopeContainer.class); + scope.register(EasyMock.isA(JavaAtomicComponent.class)); + expect(scope.getScope()).andReturn(Scope.MODULE); + replay(scope); + PojoConfiguration configuration = new PojoConfiguration(); + configuration.setScopeContainer(scope); + configuration.setInstanceFactory(new PojoObjectFactory<TargetImpl>(TargetImpl.class.getConstructor())); + configuration.addServiceInterface(Target.class); + configuration.setWireService(new JDKWireService()); + final JavaAtomicComponent component = new JavaAtomicComponent("target", configuration, null); + + InboundWire wire = createMock(InboundWire.class); + + JavaServiceContract contract = new JavaServiceContract(Target.class); + EasyMock.expect(wire.getServiceContract()).andReturn(contract).anyTimes(); + expect(wire.getServiceName()).andReturn("Target"); + Map<Operation<?>, InboundInvocationChain> chains = new HashMap<Operation<?>, InboundInvocationChain>(); + expect(wire.getInvocationChains()).andReturn(chains); + expect(wire.getCallbackReferenceName()).andReturn(null); + replay(wire); + component.addInboundWire(wire); + component.prepare(); + component.start(); + assertTrue(component.getServiceInstance("Target") instanceof Target); + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/java/JavaAtomicComponentMetadataInjectionTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/java/JavaAtomicComponentMetadataInjectionTestCase.java new file mode 100644 index 0000000000..a907e047b8 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/java/JavaAtomicComponentMetadataInjectionTestCase.java @@ -0,0 +1,35 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.implementation.java; + +import junit.framework.TestCase; + +/** + * Tests SCA metadata such as <code>@ComponentName</code> and <code>@SCAObject</code> are handled properly + * + * @version $Rev$ $Date$ + */ +public class JavaAtomicComponentMetadataInjectionTestCase extends TestCase { + + public void testComponentNameSet() throws Exception { + } + + public void testModuleContextSet() throws Exception { + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/java/JavaAtomicComponentNegativeMetadataTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/java/JavaAtomicComponentNegativeMetadataTestCase.java new file mode 100644 index 0000000000..365de8e41f --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/java/JavaAtomicComponentNegativeMetadataTestCase.java @@ -0,0 +1,67 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.implementation.java; + +import junit.framework.TestCase; + + +/** + * Performs rudimentary negative testing by using malformed metadata on a POJO + * + * @version $Rev $Date + */ +public class JavaAtomicComponentNegativeMetadataTestCase extends TestCase { + + /** + * Tests that a pojo with <code>@ComponentName</code> specified on a non-String type generates an error. + * <p/> + * <strong>NB:</strong> the test assumes an error with a message containing "@ComponentName" is generated + */ + public void testBadNameType() throws Exception { +// CompositeComponent mc = new CompositeComponentImpl(); +// mc.setName("mc"); +// try { +// MockFactory.createPojoContext("BadNamePojo", BadNamePojo.class, Scope.MODULE, mc); +// } catch (NoSuchMethodException e) { +// if (e.getMessage().indexOf("@ComponentName") < 0) { +// throw e; +// } +// } +// + } + + /** + * Tests that a pojo with <code>@Context</code> specified on a non-ModuleContext type generates an error. + * <p/> + * <strong>NB:</strong> the test assumes an error with a message containing "@Context" is generated + */ + public void testContextType() throws Exception { +// CompositeComponent mc = new CompositeComponentImpl(); +// mc.setName("mc"); +// try { +// MockFactory.createPojoContext("BadContextPojo", BadContextPojo.class, Scope.MODULE, mc); +// } catch (NoSuchMethodException e) { +// if (e.getMessage().indexOf("@SCAObject") < 0) { +// throw e; +// } +// } +// + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/java/JavaComponentBuilderTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/java/JavaComponentBuilderTestCase.java new file mode 100644 index 0000000000..4877d06aba --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/java/JavaComponentBuilderTestCase.java @@ -0,0 +1,121 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.implementation.java; + +import java.lang.reflect.Constructor; +import java.util.HashMap; +import java.util.Map; + +import org.apache.tuscany.spi.component.AtomicComponent; +import org.apache.tuscany.spi.component.CompositeComponent; +import org.apache.tuscany.spi.component.ScopeContainer; +import org.apache.tuscany.spi.deployer.DeploymentContext; +import org.apache.tuscany.spi.idl.java.JavaServiceContract; +import org.apache.tuscany.spi.implementation.java.ConstructorDefinition; +import org.apache.tuscany.spi.implementation.java.JavaMappedProperty; +import org.apache.tuscany.spi.implementation.java.JavaMappedReference; +import org.apache.tuscany.spi.implementation.java.JavaMappedService; +import org.apache.tuscany.spi.implementation.java.PojoComponentType; +import org.apache.tuscany.spi.model.ComponentDefinition; +import org.apache.tuscany.spi.model.Scope; +import org.apache.tuscany.spi.model.ServiceContract; + +import junit.framework.TestCase; +import org.apache.tuscany.core.deployer.RootDeploymentContext; +import org.apache.tuscany.core.implementation.composite.CompositeComponentImpl; +import org.apache.tuscany.core.implementation.java.mock.components.Source; +import org.apache.tuscany.core.implementation.java.mock.components.SourceImpl; +import org.apache.tuscany.core.implementation.java.mock.components.Target; +import org.apache.tuscany.core.wire.jdk.JDKWireService; +import org.easymock.EasyMock; +import org.easymock.IAnswer; + +/** + * @version $$Rev$$ $$Date$$ + */ +public class JavaComponentBuilderTestCase extends TestCase { + private DeploymentContext deploymentContext; + + public void testBuild() throws Exception { + CompositeComponent parent = new CompositeComponentImpl(null, null, null, null); + + PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>> sourceType = + new PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>>(); + sourceType.setImplementationScope(Scope.MODULE); + JavaMappedReference reference = new JavaMappedReference(); + reference.setName("target"); + reference.setMember(SourceImpl.class.getMethod("setTarget", Target.class)); + sourceType.add(reference); + + ServiceContract<?> sourceContract = new JavaServiceContract(Source.class); + JavaMappedService sourceServiceDefinition = new JavaMappedService(); + sourceServiceDefinition.setName("Source"); + sourceServiceDefinition.setServiceContract(sourceContract); + + sourceType.add(sourceServiceDefinition); + Constructor<SourceImpl> constructor = SourceImpl.class.getConstructor((Class[]) null); + sourceType.setConstructorDefinition(new ConstructorDefinition<SourceImpl>(constructor)); + JavaImplementation sourceImpl = new JavaImplementation(); + sourceImpl.setComponentType(sourceType); + sourceImpl.setImplementationClass(SourceImpl.class); + ComponentDefinition<JavaImplementation> sourceComponentDefinition = + new ComponentDefinition<JavaImplementation>(sourceImpl); + + JavaComponentBuilder builder = new JavaComponentBuilder(); + builder.setWireService(new JDKWireService()); + JavaAtomicComponent component = + (JavaAtomicComponent) builder.build(parent, sourceComponentDefinition, deploymentContext); + deploymentContext.getModuleScope().start(); + component.start(); + Source source = (Source) component.getServiceInstance(); + assertNotNull(source); + component.stop(); + } + + protected void setUp() throws Exception { + super.setUp(); + deploymentContext = new RootDeploymentContext(null, null, createMock(), null); + } + + private ScopeContainer createMock() { + ScopeContainer scope = EasyMock.createMock(ScopeContainer.class); + scope.start(); + scope.stop(); + scope.register(EasyMock.isA(AtomicComponent.class)); + EasyMock.expectLastCall().atLeastOnce(); + EasyMock.expect(scope.getScope()).andReturn(Scope.MODULE).atLeastOnce(); + scope.getInstance(EasyMock.isA(AtomicComponent.class)); + EasyMock.expectLastCall().andAnswer(new IAnswer<Object>() { + private Map<AtomicComponent, Object> cache = new HashMap<AtomicComponent, Object>(); + + public Object answer() throws Throwable { + AtomicComponent component = (AtomicComponent) EasyMock.getCurrentArguments()[0]; + Object instance = cache.get(component); + if (instance == null) { + instance = component.createInstance(); + cache.put(component, instance); + } + return instance; + } + }).anyTimes(); + EasyMock.replay(scope); + return scope; + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/java/JavaReferenceWireTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/java/JavaReferenceWireTestCase.java new file mode 100644 index 0000000000..5afc8b6511 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/java/JavaReferenceWireTestCase.java @@ -0,0 +1,111 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.implementation.java; + +import java.lang.reflect.Constructor; +import java.util.HashMap; +import java.util.Map; + +import org.apache.tuscany.spi.component.AtomicComponent; +import org.apache.tuscany.spi.component.ScopeContainer; +import org.apache.tuscany.spi.model.Operation; +import org.apache.tuscany.spi.model.Scope; +import org.apache.tuscany.spi.wire.OutboundInvocationChain; +import org.apache.tuscany.spi.wire.OutboundWire; +import org.apache.tuscany.spi.wire.WireService; + +import junit.framework.TestCase; +import org.apache.tuscany.core.implementation.PojoConfiguration; +import org.apache.tuscany.core.implementation.java.mock.components.Source; +import org.apache.tuscany.core.implementation.java.mock.components.SourceImpl; +import org.apache.tuscany.core.implementation.java.mock.components.Target; +import org.apache.tuscany.core.implementation.java.mock.components.TargetImpl; +import org.apache.tuscany.core.injection.PojoObjectFactory; +import org.easymock.EasyMock; +import org.easymock.IAnswer; + +/** + * Validates wiring from a Java atomic context + * + * @version $$Rev$$ $$Date$$ + */ +public class JavaReferenceWireTestCase extends TestCase { + + public void testReferenceSet() throws Exception { + ScopeContainer scope = createMock(); + scope.start(); + final Target target = new TargetImpl(); + PojoConfiguration configuration = new PojoConfiguration(); + configuration.addReferenceSite("target", SourceImpl.class.getMethod("setTarget", Target.class)); + configuration.addServiceInterface(Source.class); + Constructor<SourceImpl> ctr = SourceImpl.class.getConstructor(); + configuration.setInstanceFactory(new PojoObjectFactory<SourceImpl>(ctr)); + configuration.setScopeContainer(scope); + OutboundWire wire = EasyMock.createMock(OutboundWire.class); + wire.getInvocationChains(); + EasyMock.expectLastCall().andReturn(new HashMap<Operation<?>, OutboundInvocationChain>()); + EasyMock.expect(wire.getReferenceName()).andReturn("target").atLeastOnce(); + EasyMock.replay(wire); + WireService service = EasyMock.createMock(WireService.class); + EasyMock.expect(service.createProxy(EasyMock.eq(wire))).andAnswer(new IAnswer<Object>() { + public Object answer() throws Throwable { + OutboundWire wire = (OutboundWire) EasyMock.getCurrentArguments()[0]; + wire.getInvocationChains(); + return target; + } + + }).atLeastOnce(); + EasyMock.replay(service); + configuration.setWireService(service); + JavaAtomicComponent sourceContext = new JavaAtomicComponent("source", configuration, null); + sourceContext.addOutboundWire(wire); + sourceContext.start(); + Source source = (Source) sourceContext.getServiceInstance(); + assertSame(target, source.getTarget()); + scope.stop(); + EasyMock.verify(wire); + EasyMock.verify(scope); + EasyMock.verify(service); + } + + private ScopeContainer createMock() { + ScopeContainer scope = EasyMock.createMock(ScopeContainer.class); + scope.start(); + scope.stop(); + scope.register(EasyMock.isA(AtomicComponent.class)); + EasyMock.expectLastCall().atLeastOnce(); + EasyMock.expect(scope.getScope()).andReturn(Scope.MODULE).atLeastOnce(); + scope.getInstance(EasyMock.isA(AtomicComponent.class)); + EasyMock.expectLastCall().andAnswer(new IAnswer<Object>() { + private Map<AtomicComponent, Object> cache = new HashMap<AtomicComponent, Object>(); + + public Object answer() throws Throwable { + AtomicComponent component = (AtomicComponent) EasyMock.getCurrentArguments()[0]; + Object instance = cache.get(component); + if (instance == null) { + instance = component.createInstance(); + cache.put(component, instance); + } + return instance; + } + }).anyTimes(); + EasyMock.replay(scope); + return scope; + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/java/JavaTargetInvokerTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/java/JavaTargetInvokerTestCase.java new file mode 100644 index 0000000000..018273be28 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/java/JavaTargetInvokerTestCase.java @@ -0,0 +1,79 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.implementation.java; + +import java.lang.reflect.Method; + +import org.apache.tuscany.spi.component.ScopeContainer; + +import junit.framework.Assert; +import junit.framework.TestCase; +import org.apache.tuscany.core.component.scope.ModuleScopeContainer; +import org.apache.tuscany.core.implementation.java.mock.MockFactory; + +public class JavaTargetInvokerTestCase extends TestCase { + + private Method echoMethod; + + public JavaTargetInvokerTestCase() { + super(); + } + + public JavaTargetInvokerTestCase(String arg0) { + super(arg0); + } + + public void setUp() throws Exception { + echoMethod = Echo.class.getDeclaredMethod("echo", String.class); + Assert.assertNotNull(echoMethod); + } + + public void testScopedInvoke() throws Exception { + ScopeContainer scope = new ModuleScopeContainer(null); + scope.start(); + JavaAtomicComponent component = + MockFactory.createJavaComponent("foo", scope, Echo.class); + scope.register(component); + JavaTargetInvoker invoker = new JavaTargetInvoker(echoMethod, component); + invoker.setCacheable(false); + assertEquals("foo", invoker.invokeTarget("foo")); + scope.stop(); + } + + public void testClone() throws Exception { + ScopeContainer scope = new ModuleScopeContainer(null); + scope.start(); + JavaAtomicComponent component = + MockFactory.createJavaComponent("foo", scope, Echo.class); + scope.register(component); + JavaTargetInvoker invoker = new JavaTargetInvoker(echoMethod, component); + invoker.setCacheable(false); + JavaTargetInvoker clone = invoker.clone(); + assertEquals("foo", clone.invokeTarget("foo")); + scope.stop(); + } + + public static class Echo { + public String echo(String message) throws Exception { + return message; + } + + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/java/MultiplicityTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/java/MultiplicityTestCase.java new file mode 100644 index 0000000000..92c8c7acfa --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/java/MultiplicityTestCase.java @@ -0,0 +1,61 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.implementation.java; + +import junit.framework.TestCase; + + +/** + * Tests wires that are configured with a multiplicity + * + * @version $Rev$ $Date$ + */ +public class MultiplicityTestCase extends TestCase { + + public void testMultiplicity() throws Exception { +// CompositeComponent context = createContext(); +// context.start(); +// context.registerModelObject(MockFactory.createModuleWithWiredComponents(Scope.MODULE, Scope.MODULE)); +// context.publish(new CompositeStart(this)); +// Source source = (Source) ((AtomicComponent) context.getContext("source")).getTargetInstance(); +// Assert.assertNotNull(source); +// Target target = (Target) ((AtomicComponent)context.getContext("target")).getTargetInstance(); +// Assert.assertNotNull(target); +// // test setter injection +// List<Target> targets = source.getTargets(); +// Assert.assertEquals(1, targets.size()); +// +// // test field injection +// targets = source.getTargetsThroughField(); +// Assert.assertEquals(1, targets.size()); + } + +// private CompositeComponent createContext() { +// CompositeComponentImpl context = new CompositeComponentImpl(); +// context.setName("system.context"); +// List<ContextFactoryBuilder>builders = MockFactory.createSystemBuilders(); +// WireService wireService = new DefaultWireFactoryService(new MessageFactoryImpl(), +// new JDKWireFactoryService(), new DefaultPolicyBuilderRegistry()); +// builders.add(new JavaContextFactoryBuilder(wireService)); +// List<WireBuilder> wireBuilders = new ArrayList<WireBuilder>(); +// wireBuilders.add(new JavaTargetWireBuilder()); +// context.setConfigurationContext(new MockConfigContext(builders,wireBuilders)); +// return context; +// } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/java/ReferenceInjectionTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/java/ReferenceInjectionTestCase.java new file mode 100644 index 0000000000..e6309e0c97 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/java/ReferenceInjectionTestCase.java @@ -0,0 +1,70 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.implementation.java; + +import java.lang.reflect.Member; +import java.lang.reflect.Method; +import java.lang.reflect.Proxy; +import java.util.HashMap; +import java.util.Map; + +import org.apache.tuscany.spi.component.AtomicComponent; +import org.apache.tuscany.spi.component.ScopeContainer; + +import junit.framework.TestCase; +import org.apache.tuscany.core.implementation.java.mock.MockFactory; +import org.apache.tuscany.core.implementation.java.mock.components.Source; +import org.apache.tuscany.core.implementation.java.mock.components.SourceImpl; +import org.apache.tuscany.core.implementation.java.mock.components.Target; +import org.apache.tuscany.core.implementation.java.mock.components.TargetImpl; +import org.apache.tuscany.core.component.scope.ModuleScopeContainer; + +/** + * @version $$Rev$$ $$Date$$ + */ +public class ReferenceInjectionTestCase extends TestCase { + + private Map<String, Member> members; + + public void testProxiedReferenceInjection() throws Exception { + ScopeContainer scope = new ModuleScopeContainer(null); + scope.start(); + Map<String, AtomicComponent> contexts = + MockFactory.createWiredComponents("source", SourceImpl.class, scope, + members, "target", Target.class, TargetImpl.class, scope); + AtomicComponent sourceComponent = contexts.get("source"); + Source source = (Source) sourceComponent.getServiceInstance(); + Target target = source.getTarget(); + assertTrue(Proxy.isProxyClass(target.getClass())); + + assertNotNull(target); + scope.stop(); + } + + protected void setUp() throws Exception { + super.setUp(); + members = new HashMap<String, Member>(); + Method m = SourceImpl.class.getMethod("setTarget", Target.class); + members.put("target", m); + } + + protected void tearDown() throws Exception { + super.tearDown(); + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/java/integration/component/CallbackInvocationTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/java/integration/component/CallbackInvocationTestCase.java new file mode 100644 index 0000000000..718fd50845 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/java/integration/component/CallbackInvocationTestCase.java @@ -0,0 +1,266 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.implementation.java.integration.component; + +import java.lang.reflect.Method; +import java.net.URI; +import java.net.URISyntaxException; + +import org.osoa.sca.annotations.Callback; + +import org.apache.tuscany.spi.builder.Connector; +import org.apache.tuscany.spi.component.CompositeComponent; +import org.apache.tuscany.spi.component.ScopeContainer; +import org.apache.tuscany.spi.component.WorkContext; +import org.apache.tuscany.spi.deployer.DeploymentContext; +import org.apache.tuscany.spi.idl.InvalidServiceContractException; +import org.apache.tuscany.spi.idl.java.JavaInterfaceProcessorRegistry; +import org.apache.tuscany.spi.implementation.java.ConstructorDefinition; +import org.apache.tuscany.spi.implementation.java.JavaMappedProperty; +import org.apache.tuscany.spi.implementation.java.JavaMappedReference; +import org.apache.tuscany.spi.implementation.java.JavaMappedService; +import org.apache.tuscany.spi.implementation.java.PojoComponentType; +import org.apache.tuscany.spi.model.ComponentDefinition; +import org.apache.tuscany.spi.model.ReferenceTarget; +import org.apache.tuscany.spi.model.Scope; +import org.apache.tuscany.spi.model.ServiceContract; +import org.apache.tuscany.spi.services.work.WorkScheduler; +import org.apache.tuscany.spi.wire.WireService; + +import junit.framework.TestCase; +import org.apache.tuscany.core.builder.ConnectorImpl; +import org.apache.tuscany.core.component.WorkContextImpl; +import org.apache.tuscany.core.component.scope.ModuleScopeContainer; +import org.apache.tuscany.core.idl.java.JavaInterfaceProcessorRegistryImpl; +import org.apache.tuscany.core.implementation.java.JavaAtomicComponent; +import org.apache.tuscany.core.implementation.java.JavaComponentBuilder; +import org.apache.tuscany.core.implementation.java.JavaImplementation; +import org.apache.tuscany.core.wire.jdk.JDKWireService; +import static org.easymock.EasyMock.createMock; +import static org.easymock.EasyMock.expectLastCall; +import static org.easymock.EasyMock.getCurrentArguments; +import static org.easymock.EasyMock.isA; +import static org.easymock.EasyMock.replay; +import org.easymock.IAnswer; + +/** + * Verifies callback integration scenarios. + * + * @version $Rev$ $Date$ + */ +public class CallbackInvocationTestCase extends TestCase { + + private ScopeContainer container; + private DeploymentContext context; + private JavaComponentBuilder builder; + private WireService wireService; + private WorkScheduler scheduler; + private WorkContext workContext; + /** + * Verifies callback wires are built and callback invocations are handled properly + */ + public void testComponentToComponentCallback() throws Exception { + ComponentDefinition<JavaImplementation> targetDefinition = createTarget(); + JavaAtomicComponent fooComponent = + (JavaAtomicComponent) builder.build(null, targetDefinition, context); + wireService.createWires(fooComponent, targetDefinition); + container.register(fooComponent); + + CompositeComponent parent = createMock(CompositeComponent.class); + parent.getChild(isA(String.class)); + expectLastCall().andReturn(fooComponent).anyTimes(); + replay(parent); + + ComponentDefinition<JavaImplementation> sourceDefinition = createSource("fooClient"); + JavaAtomicComponent clientComponent = + (JavaAtomicComponent) builder.build(parent, sourceDefinition, context); + wireService.createWires(clientComponent, sourceDefinition); + container.register(clientComponent); + + Connector connector = new ConnectorImpl(new JDKWireService(), null, scheduler , workContext); + + connector.connect(clientComponent); + FooClient client = (FooClient) clientComponent.getServiceInstance(); + client.invoke(); + assertTrue(client.invoked); + } + + /** + * Verifies a callback in response to an invocation from two different client components is routed back to the + * appropriate client. + */ + public void testTwoSourceComponentToComponentCallback() throws Exception { + ComponentDefinition<JavaImplementation> targetDefinition = createTarget(); + JavaAtomicComponent fooComponent = + (JavaAtomicComponent) builder.build(null, targetDefinition, context); + wireService.createWires(fooComponent, targetDefinition); + container.register(fooComponent); + + CompositeComponent parent = createMock(CompositeComponent.class); + parent.getChild(isA(String.class)); + expectLastCall().andReturn(fooComponent).anyTimes(); + replay(parent); + + ComponentDefinition<JavaImplementation> sourceDefinition1 = createSource("fooCleint1"); + ComponentDefinition<JavaImplementation> sourceDefinition2 = createSource("fooCleint2"); + JavaAtomicComponent clientComponent1 = + (JavaAtomicComponent) builder.build(parent, sourceDefinition1, context); + wireService.createWires(clientComponent1, sourceDefinition1); + container.register(clientComponent1); + JavaAtomicComponent clientComponent2 = + (JavaAtomicComponent) builder.build(parent, sourceDefinition2, context); + wireService.createWires(clientComponent2, sourceDefinition2); + container.register(clientComponent2); + + Connector connector = new ConnectorImpl(new JDKWireService(), null, scheduler, workContext); + connector.connect(clientComponent1); + connector.connect(clientComponent2); + FooClient client1 = (FooClient) clientComponent1.getServiceInstance(); + client1.invoke(); + assertTrue(client1.invoked); + FooClient client2 = (FooClient) clientComponent2.getServiceInstance(); + client2.invoke(); + assertTrue(client2.invoked); + } + + + private ComponentDefinition<JavaImplementation> createTarget() throws NoSuchMethodException, + InvalidServiceContractException { + ConstructorDefinition<FooImpl> ctorDef = new ConstructorDefinition<FooImpl>(FooImpl.class.getConstructor()); + PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>> type = + new PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>>(); + type.setConstructorDefinition(ctorDef); + type.setImplementationScope(Scope.MODULE); + Method method = FooImpl.class.getMethod("setCallback", FooCallback.class); + JavaInterfaceProcessorRegistry registry = new JavaInterfaceProcessorRegistryImpl(); + ServiceContract<?> contract = registry.introspect(Foo.class); + contract.setCallbackClass(FooCallback.class); + contract.setCallbackName("callback"); + JavaMappedService mappedService = new JavaMappedService("Foo", contract, false, "callback", method); + type.getServices().put("Foo", mappedService); + + JavaImplementation impl = new JavaImplementation(); + impl.setComponentType(type); + impl.setImplementationClass(FooImpl.class); + return new ComponentDefinition<JavaImplementation>("foo", impl); + } + + private ComponentDefinition<JavaImplementation> createSource(String name) + throws NoSuchMethodException, URISyntaxException, InvalidServiceContractException { + ConstructorDefinition<FooClient> ctorDef = + new ConstructorDefinition<FooClient>(FooClient.class.getConstructor()); + PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>> type = + new PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>>(); + type.setConstructorDefinition(ctorDef); + type.setImplementationScope(Scope.MODULE); + Method method = FooClient.class.getMethod("setFoo", Foo.class); + JavaInterfaceProcessorRegistry registry = new JavaInterfaceProcessorRegistryImpl(); + ServiceContract<?> contract = registry.introspect(Foo.class); + contract.setCallbackClass(FooCallback.class); + contract.setCallbackName("callback"); + JavaMappedReference mappedReference = new JavaMappedReference("foo", contract, method); + type.getReferences().put("foo", mappedReference); + ReferenceTarget refTarget = new ReferenceTarget(); + refTarget.setReferenceName("foo"); + refTarget.getTargets().add(new URI("foo")); + JavaImplementation impl = new JavaImplementation(); + impl.setComponentType(type); + impl.setImplementationClass(FooClient.class); + ComponentDefinition<JavaImplementation> def = new ComponentDefinition<JavaImplementation>(name, impl); + def.getReferenceTargets().put("foo", refTarget); + return def; + } + + @Callback(FooCallback.class) + public static interface Foo { + void call(); + } + + public static class FooImpl implements Foo { + private FooCallback callback; + + public FooImpl() { + } + + @Callback + public void setCallback(FooCallback callback) { + this.callback = callback; + } + + public void call() { + callback.callback(); + } + } + + public static class FooClient implements FooCallback { + + private Foo foo; + private boolean invoked; + + public FooClient() { + } + + public void setFoo(Foo foo) { + this.foo = foo; + } + + public void callback() { + if (invoked) { + fail(); + } + invoked = true; + } + + public void invoke() { + foo.call(); + } + } + + public interface FooCallback { + void callback(); + } + + protected void setUp() throws Exception { + super.setUp(); + wireService = new JDKWireService(); + container = new ModuleScopeContainer(); + container.start(); + context = createMock(DeploymentContext.class); + context.getModuleScope(); + expectLastCall().andReturn(container).anyTimes(); + replay(context); + + scheduler = createMock(WorkScheduler.class); + scheduler.scheduleWork(isA(Runnable.class)); + expectLastCall().andStubAnswer(new IAnswer<Object>() { + public Object answer() throws Throwable { + Runnable runnable = (Runnable) getCurrentArguments()[0]; + runnable.run(); + return null; + } + }); + replay(scheduler); + + builder = new JavaComponentBuilder(); + workContext = new WorkContextImpl(); + builder.setWorkContext(workContext); + builder.setWireService(new JDKWireService(workContext, null)); + builder.setWorkScheduler(scheduler); + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/java/integration/component/OneWayWireInvocationTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/java/integration/component/OneWayWireInvocationTestCase.java new file mode 100644 index 0000000000..91d31d2db2 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/java/integration/component/OneWayWireInvocationTestCase.java @@ -0,0 +1,88 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.implementation.java.integration.component; + +import java.lang.reflect.Method; +import java.util.Map; + +import org.apache.tuscany.spi.component.WorkContext; +import org.apache.tuscany.spi.model.Operation; +import org.apache.tuscany.spi.services.work.WorkScheduler; +import org.apache.tuscany.spi.wire.InboundInvocationChain; +import org.apache.tuscany.spi.wire.InboundWire; +import org.apache.tuscany.spi.wire.MessageImpl; +import org.apache.tuscany.spi.wire.WireService; + +import junit.framework.TestCase; +import org.apache.tuscany.core.implementation.java.AsyncJavaTargetInvoker; +import org.apache.tuscany.core.implementation.java.JavaAtomicComponent; +import org.apache.tuscany.core.implementation.java.mock.MockFactory; +import static org.apache.tuscany.core.implementation.java.mock.MockFactory.createServiceWire; +import org.apache.tuscany.core.implementation.java.mock.components.AsyncTarget; +import org.apache.tuscany.core.wire.jdk.JDKWireService; +import static org.easymock.EasyMock.createMock; +import static org.easymock.EasyMock.expectLastCall; +import static org.easymock.EasyMock.getCurrentArguments; +import static org.easymock.EasyMock.isA; +import static org.easymock.EasyMock.replay; +import static org.easymock.EasyMock.verify; +import org.easymock.IAnswer; + +/** + * Verifies non-blocking invocations are properly made through a wire + * + * @version $Rev$ $Date$ + */ +public class OneWayWireInvocationTestCase extends TestCase { + + WireService wireService = new JDKWireService(); + + public void testNoInterceptors() throws Exception { + AsyncTarget target = createMock(AsyncTarget.class); + target.invoke(); + expectLastCall().once(); + replay(target); + JavaAtomicComponent component = MockFactory.createJavaComponent(target); + WorkScheduler scheduler = createMock(WorkScheduler.class); + scheduler.scheduleWork(isA(Runnable.class)); + expectLastCall().andStubAnswer(new IAnswer<Object>() { + public Object answer() throws Throwable { + Runnable runnable = (Runnable) getCurrentArguments()[0]; + runnable.run(); + return null; + } + }); + replay(scheduler); + WorkContext context = createMock(WorkContext.class); + Method method = AsyncTarget.class.getMethod("invoke"); + method.setAccessible(true); + InboundWire inboundWire = createMock(InboundWire.class); + AsyncJavaTargetInvoker invoker = + new AsyncJavaTargetInvoker(method, inboundWire, component, null, context); + InboundWire wire = createServiceWire("foo", AsyncTarget.class, null); + Map<Operation<?>, InboundInvocationChain> chains = wire.getInvocationChains(); + InboundInvocationChain chain = chains.get(wire.getServiceContract().getOperations().get("invoke")); + chain.setTargetInvoker(invoker); + chain.prepare(); + MessageImpl msg = new MessageImpl(); + msg.setTargetInvoker(invoker); + chain.getHeadInterceptor().invoke(msg); + verify(target); + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/java/integration/component/OutboundWireToJavaTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/java/integration/component/OutboundWireToJavaTestCase.java new file mode 100644 index 0000000000..9ea0cd99e3 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/java/integration/component/OutboundWireToJavaTestCase.java @@ -0,0 +1,229 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.implementation.java.integration.component; + +import java.util.HashMap; +import java.util.Map; +import java.util.concurrent.Executor; +import java.util.concurrent.Executors; +import java.util.concurrent.FutureTask; + +import org.apache.tuscany.spi.QualifiedName; +import org.apache.tuscany.spi.component.CompositeComponent; +import org.apache.tuscany.spi.component.ScopeContainer; +import org.apache.tuscany.spi.component.WorkContext; +import org.apache.tuscany.spi.idl.InvalidServiceContractException; +import org.apache.tuscany.spi.idl.java.JavaInterfaceProcessorRegistry; +import org.apache.tuscany.spi.idl.java.JavaServiceContract; +import org.apache.tuscany.spi.model.Operation; +import org.apache.tuscany.spi.model.ServiceContract; +import org.apache.tuscany.spi.wire.InboundWire; +import org.apache.tuscany.spi.wire.OutboundInvocationChain; +import org.apache.tuscany.spi.wire.OutboundWire; +import org.apache.tuscany.spi.wire.WireService; + +import junit.framework.TestCase; +import org.apache.tuscany.core.builder.ConnectorImpl; +import org.apache.tuscany.core.component.WorkContextImpl; +import org.apache.tuscany.core.component.event.CompositeStart; +import org.apache.tuscany.core.component.event.CompositeStop; +import org.apache.tuscany.core.component.event.HttpSessionEnd; +import org.apache.tuscany.core.component.event.HttpSessionStart; +import org.apache.tuscany.core.component.event.RequestEnd; +import org.apache.tuscany.core.component.event.RequestStart; +import org.apache.tuscany.core.component.scope.HttpSessionScopeContainer; +import org.apache.tuscany.core.component.scope.ModuleScopeContainer; +import org.apache.tuscany.core.component.scope.RequestScopeContainer; +import org.apache.tuscany.core.component.scope.StatelessScopeContainer; +import org.apache.tuscany.core.idl.java.JavaInterfaceProcessorRegistryImpl; +import org.apache.tuscany.core.implementation.PojoConfiguration; +import org.apache.tuscany.core.implementation.java.JavaAtomicComponent; +import org.apache.tuscany.core.implementation.java.mock.MockFactory; +import org.apache.tuscany.core.implementation.java.mock.components.Target; +import org.apache.tuscany.core.implementation.java.mock.components.TargetImpl; +import org.apache.tuscany.core.injection.PojoObjectFactory; +import org.apache.tuscany.core.wire.OutboundInvocationChainImpl; +import org.apache.tuscany.core.wire.OutboundWireImpl; +import org.apache.tuscany.core.wire.jdk.JDKWireService; +import org.easymock.EasyMock; + +/** + * Validates wiring from a service context to Java atomic contexts by scope + * + * @version $$Rev$$ $$Date$$ + */ +public class OutboundWireToJavaTestCase extends TestCase { + private WorkContext workContext = new WorkContextImpl(); + private WireService wireService = new JDKWireService(new WorkContextImpl(), null); + + public void testToStatelessScope() throws Exception { + StatelessScopeContainer scope = new StatelessScopeContainer(workContext); + scope.start(); + final OutboundWire wire = getWire(scope); + Target service = (Target) wireService.createProxy(wire); + assertNotNull(service); + service.setString("foo"); + assertEquals(null, service.getString()); + scope.stop(); + } + + public void testToRequestScope() throws Exception { + final RequestScopeContainer scope = new RequestScopeContainer(workContext); + scope.start(); + + scope.onEvent(new RequestStart(this)); + + final OutboundWire wire = getWire(scope); + Target service = (Target) wireService.createProxy(wire); + assertNotNull(service); + service.setString("foo"); + + // another request + Executor executor = Executors.newSingleThreadExecutor(); + FutureTask<Void> future = new FutureTask<Void>(new Runnable() { + public void run() { + scope.onEvent(new RequestStart(this)); + Target service2 = (Target) wireService.createProxy(wire); + Target target2 = (Target) wireService.createProxy(wire); + assertEquals(null, service2.getString()); + service2.setString("bar"); + assertEquals("bar", service2.getString()); + assertEquals("bar", target2.getString()); + scope.onEvent(new RequestEnd(this)); + } + }, null); + executor.execute(future); + future.get(); + + assertEquals("foo", service.getString()); + scope.onEvent(new RequestEnd(this)); + scope.stop(); + } + + public void testToSessionScope() throws Exception { + HttpSessionScopeContainer scope = new HttpSessionScopeContainer(workContext); + scope.start(); + Object session1 = new Object(); + workContext.setIdentifier(HttpSessionScopeContainer.HTTP_IDENTIFIER, session1); + scope.onEvent(new HttpSessionStart(this, session1)); + + final OutboundWire wire = getWire(scope); + Target service = (Target) wireService.createProxy(wire); + Target target = (Target) wireService.createProxy(wire); + assertNotNull(service); + service.setString("foo"); + assertEquals("foo", service.getString()); + assertEquals("foo", target.getString()); + + workContext.clearIdentifier(HttpSessionScopeContainer.HTTP_IDENTIFIER); + + //second session + Object session2 = new Object(); + workContext.setIdentifier(HttpSessionScopeContainer.HTTP_IDENTIFIER, session2); + scope.onEvent(new HttpSessionStart(this, session2)); + + Target service2 = (Target) wireService.createProxy(wire); + assertNotNull(service2); + assertNull(service2.getString()); + Target target2 = (Target) wireService.createProxy(wire); + service2.setString("bar"); + assertEquals("bar", service2.getString()); + assertEquals("bar", target2.getString()); + + scope.onEvent(new HttpSessionEnd(this, session2)); + workContext.clearIdentifier(HttpSessionScopeContainer.HTTP_IDENTIFIER); + + workContext.setIdentifier(HttpSessionScopeContainer.HTTP_IDENTIFIER, session1); + assertEquals("foo", service.getString()); + + scope.onEvent(new HttpSessionEnd(this, session1)); + + scope.stop(); + } + + public void testToModuleScope() throws Exception { + + ModuleScopeContainer scope = new ModuleScopeContainer(workContext); + scope.start(); + scope.onEvent(new CompositeStart(this, null)); + final OutboundWire wire = getWire(scope); + Target service = (Target) wireService.createProxy(wire); + Target target = (Target) wireService.createProxy(wire); + assertNotNull(service); + service.setString("foo"); + assertEquals("foo", service.getString()); + assertEquals("foo", target.getString()); + scope.onEvent(new CompositeStop(this, null)); + scope.stop(); + } + + private OutboundWire getWire(ScopeContainer scope) throws NoSuchMethodException, + InvalidServiceContractException { + ConnectorImpl connector = new ConnectorImpl(); + + CompositeComponent parent = EasyMock.createMock(CompositeComponent.class); + + PojoConfiguration configuration = new PojoConfiguration(); + configuration.setScopeContainer(scope); + configuration.setInstanceFactory(new PojoObjectFactory<TargetImpl>(TargetImpl.class.getConstructor())); + configuration.addServiceInterface(Target.class); + configuration.setParent(parent); + + JavaAtomicComponent source = new JavaAtomicComponent("source", configuration, null); + OutboundWire outboundWire = createOutboundWire(new QualifiedName("target/Target"), Target.class); + outboundWire.setContainer(source); + source.addOutboundWire(outboundWire); + JavaAtomicComponent target = new JavaAtomicComponent("target", configuration, null); + InboundWire targetWire = MockFactory.createTargetWire("Target", Target.class); + targetWire.setContainer(target); + target.addInboundWire(targetWire); + InboundWire inboundWire = target.getInboundWire("Target"); + inboundWire.setContainer(target); + + EasyMock.expect(parent.getChild("target")).andReturn(target); + EasyMock.replay(parent); + + connector.connect(source); + target.start(); + return outboundWire; + } + + public static <T> OutboundWire createOutboundWire(QualifiedName targetName, Class<T> interfaze) + throws InvalidServiceContractException { + OutboundWire wire = new OutboundWireImpl(); + JavaServiceContract contract = new JavaServiceContract(interfaze); + wire.setServiceContract(contract); + wire.setTargetName(targetName); + wire.addInvocationChains(createInvocationChains(interfaze)); + return wire; + } + + private static Map<Operation<?>, OutboundInvocationChain> createInvocationChains(Class<?> interfaze) + throws InvalidServiceContractException { + Map<Operation<?>, OutboundInvocationChain> invocations = new HashMap<Operation<?>, OutboundInvocationChain>(); + JavaInterfaceProcessorRegistry registry = new JavaInterfaceProcessorRegistryImpl(); + ServiceContract<?> contract = registry.introspect(interfaze); + for (Operation operation : contract.getOperations().values()) { + OutboundInvocationChain chain = new OutboundInvocationChainImpl(operation); + invocations.put(operation, chain); + } + return invocations; + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/java/integration/component/ScopeReferenceTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/java/integration/component/ScopeReferenceTestCase.java new file mode 100644 index 0000000000..87a8be3a01 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/java/integration/component/ScopeReferenceTestCase.java @@ -0,0 +1,746 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.implementation.java.integration.component; + +import java.lang.reflect.Member; +import java.lang.reflect.Method; +import java.lang.reflect.Proxy; +import java.util.HashMap; +import java.util.Map; +import java.util.concurrent.Executor; +import java.util.concurrent.Executors; +import java.util.concurrent.FutureTask; + +import org.apache.tuscany.spi.component.AtomicComponent; +import org.apache.tuscany.spi.component.ScopeContainer; +import org.apache.tuscany.spi.component.WorkContext; + +import junit.framework.TestCase; +import org.apache.tuscany.core.component.WorkContextImpl; +import org.apache.tuscany.core.component.event.CompositeStart; +import org.apache.tuscany.core.component.event.CompositeStop; +import org.apache.tuscany.core.component.event.HttpSessionEnd; +import org.apache.tuscany.core.component.event.HttpSessionStart; +import org.apache.tuscany.core.component.event.RequestEnd; +import org.apache.tuscany.core.component.event.RequestStart; +import org.apache.tuscany.core.component.scope.HttpSessionScopeContainer; +import org.apache.tuscany.core.component.scope.ModuleScopeContainer; +import org.apache.tuscany.core.component.scope.RequestScopeContainer; +import org.apache.tuscany.core.component.scope.StatelessScopeContainer; +import org.apache.tuscany.core.implementation.java.mock.MockFactory; +import org.apache.tuscany.core.implementation.java.mock.components.Source; +import org.apache.tuscany.core.implementation.java.mock.components.SourceImpl; +import org.apache.tuscany.core.implementation.java.mock.components.Target; +import org.apache.tuscany.core.implementation.java.mock.components.TargetImpl; +import org.apache.tuscany.core.util.JavaIntrospectionHelper; + +/** + * Tests scoping is properly handled for service references + * + * @version $Rev$ $Date$ + */ +public class ScopeReferenceTestCase extends TestCase { + + private Map<String, Member> members; + + /** + * Tests a module-to-module scoped wire + */ + public void testModuleToModule() throws Exception { + ScopeContainer scope = new ModuleScopeContainer(null); + scope.start(); + + Map<String, AtomicComponent> contexts = MockFactory.createWiredComponents("source", SourceImpl.class, + scope, members, "target", Target.class, TargetImpl.class, scope); + scope.onEvent(new CompositeStart(this, null)); + AtomicComponent sourceComponent = contexts.get("source"); + AtomicComponent targetComponent = contexts.get("target"); + Source source = (Source) sourceComponent.getServiceInstance(); + Target target = (Target) targetComponent.getServiceInstance(); + assertNull(source.getTarget().getString()); + assertNull(target.getString()); + target.setString("foo"); + assertTrue(Proxy.isProxyClass(source.getTarget().getClass())); + assertEquals("foo", source.getTarget().getString()); + scope.onEvent(new CompositeStop(this, null)); + scope.stop(); + } + + /** + * Tests a module-to-session scoped wire is setup properly by the runtime + */ + public void testModuleToSession() throws Exception { + WorkContext ctx = new WorkContextImpl(); + ScopeContainer moduleScope = new ModuleScopeContainer(ctx); + moduleScope.start(); + ScopeContainer sessionScope = new HttpSessionScopeContainer(ctx); + sessionScope.start(); + + Map<String, AtomicComponent> contexts = MockFactory.createWiredComponents("source", SourceImpl.class, + moduleScope, members, "target", Target.class, TargetImpl.class, sessionScope); + moduleScope.onEvent(new CompositeStart(this, null)); + Object session1 = new Object(); + ctx.setIdentifier(HttpSessionScopeContainer.HTTP_IDENTIFIER, session1); + sessionScope.onEvent(new HttpSessionStart(this, session1)); + AtomicComponent sourceComponent = contexts.get("source"); + AtomicComponent targetComponent = contexts.get("target"); + Source source = (Source) sourceComponent.getServiceInstance(); + Target target = (Target) targetComponent.getServiceInstance(); + assertNull(source.getTarget().getString()); + assertNull(target.getString()); + target.setString("foo"); + assertTrue(Proxy.isProxyClass(source.getTarget().getClass())); + assertEquals("foo", source.getTarget().getString()); + ctx.clearIdentifier(HttpSessionScopeContainer.HTTP_IDENTIFIER); + sessionScope.onEvent(new HttpSessionEnd(this, session1)); + + //second session + Object session2 = new Object(); + ctx.setIdentifier(HttpSessionScopeContainer.HTTP_IDENTIFIER, session2); + sessionScope.onEvent(new HttpSessionStart(this, session2)); + + Target target2 = (Target) targetComponent.getServiceInstance(); + assertFalse("foo".equals(target2.getString())); + + assertFalse("foo".equals(source.getTarget().getString())); + source.getTarget().setString("bar"); + assertEquals("bar", target2.getString()); + assertEquals("bar", source.getTarget().getString()); + sessionScope.onEvent(new HttpSessionEnd(this, session2)); + + ctx.clearIdentifier(HttpSessionScopeContainer.HTTP_IDENTIFIER); + moduleScope.onEvent(new CompositeStop(this, null)); + sessionScope.stop(); + moduleScope.stop(); + } + + /** + * Tests a module-to-request scoped wire + */ + public void testModuleToRequest() throws Exception { + WorkContext ctx = new WorkContextImpl(); + ScopeContainer moduleScope = new ModuleScopeContainer(ctx); + moduleScope.start(); + final ScopeContainer requestScope = new RequestScopeContainer(ctx); + requestScope.start(); + + Map<String, AtomicComponent> contexts = MockFactory.createWiredComponents("source", SourceImpl.class, + moduleScope, members, "target", Target.class, TargetImpl.class, requestScope); + moduleScope.onEvent(new CompositeStart(this, null)); + requestScope.onEvent(new RequestStart(this)); + + AtomicComponent sourceComponent = contexts.get("source"); + final AtomicComponent targetComponent = contexts.get("target"); + final Source source = (Source) sourceComponent.getServiceInstance(); + Target target = (Target) targetComponent.getServiceInstance(); + assertNull(source.getTarget().getString()); + assertNull(target.getString()); + target.setString("foo"); + assertTrue(Proxy.isProxyClass(source.getTarget().getClass())); + assertEquals("foo", source.getTarget().getString()); + + // spin off another request + Executor executor = Executors.newSingleThreadExecutor(); + FutureTask<Void> future = new FutureTask<Void>(new Runnable() { + public void run() { + requestScope.onEvent(new RequestStart(this)); + Target target2 = (Target) targetComponent.getServiceInstance(); + assertFalse("foo".equals(target2.getString())); + assertFalse("foo".equals(source.getTarget().getString())); + source.getTarget().setString("bar"); + assertEquals("bar", target2.getString()); + assertEquals("bar", source.getTarget().getString()); + requestScope.onEvent(new RequestEnd(this)); + } + }, null); + executor.execute(future); + future.get(); + assertEquals("foo", source.getTarget().getString()); + requestScope.onEvent(new RequestEnd(this)); + moduleScope.onEvent(new CompositeStop(this, null)); + requestScope.stop(); + moduleScope.stop(); + } + + /** + * Tests a module-to-stateless scoped wire is setup properly by the runtime + */ + public void testModuleToStateless() throws Exception { + WorkContext ctx = new WorkContextImpl(); + ScopeContainer moduleScope = new ModuleScopeContainer(ctx); + moduleScope.start(); + ScopeContainer statelessScope = new StatelessScopeContainer(ctx); + statelessScope.start(); + + Map<String, AtomicComponent> contexts = MockFactory.createWiredComponents("source", SourceImpl.class, + moduleScope, members, "target", Target.class, TargetImpl.class, statelessScope); + moduleScope.onEvent(new CompositeStart(this, null)); + + AtomicComponent sourceComponent = contexts.get("source"); + AtomicComponent targetComponent = contexts.get("target"); + Source source = (Source) sourceComponent.getServiceInstance(); + Target target = (Target) targetComponent.getServiceInstance(); + assertTrue(Proxy.isProxyClass(source.getTarget().getClass())); + assertNull(source.getTarget().getString()); + assertNull(target.getString()); + target.setString("foo"); + assertFalse("foo".equals(source.getTarget().getString())); + Target target2 = (Target) targetComponent.getServiceInstance(); + assertFalse("foo".equals(target2.getString())); + source.getTarget().setString("bar"); + assertFalse("bar".equals(source.getTarget().getString())); + moduleScope.onEvent(new CompositeStop(this, null)); + moduleScope.stop(); + statelessScope.stop(); + } + + + /** + * Tests a session-to-session scoped wire + */ + public void testSessionToSession() throws Exception { + WorkContext ctx = new WorkContextImpl(); + ScopeContainer sessionScope = new HttpSessionScopeContainer(ctx); + sessionScope.start(); + + Map<String, AtomicComponent> contexts = MockFactory.createWiredComponents("source", SourceImpl.class, + sessionScope, members, "target", Target.class, TargetImpl.class, sessionScope); + + Object session1 = new Object(); + ctx.setIdentifier(HttpSessionScopeContainer.HTTP_IDENTIFIER, session1); + sessionScope.onEvent(new HttpSessionStart(this, session1)); + AtomicComponent sourceComponent = contexts.get("source"); + AtomicComponent targetComponent = contexts.get("target"); + Source source = (Source) sourceComponent.getServiceInstance(); + Target target = (Target) targetComponent.getServiceInstance(); + source.getTarget().setString("foo"); + source.getTarget().setString("foo"); + assertEquals("foo", target.getString()); + + ctx.clearIdentifier(HttpSessionScopeContainer.HTTP_IDENTIFIER); + sessionScope.onEvent(new HttpSessionEnd(this, session1)); + + //second session + Object session2 = new Object(); + ctx.setIdentifier(HttpSessionScopeContainer.HTTP_IDENTIFIER, session2); + sessionScope.onEvent(new HttpSessionStart(this, session2)); + + Source source2 = (Source) sourceComponent.getServiceInstance(); + assertNotNull(source2); + Target target2 = (Target) targetComponent.getServiceInstance(); + + assertNotNull(target2); + assertNull(target2.getString()); + assertEquals(null, source2.getTarget().getString()); + source2.getTarget().setString("baz"); + assertEquals("baz", source2.getTarget().getString()); + assertEquals("baz", target2.getString()); + ctx.clearIdentifier(HttpSessionScopeContainer.HTTP_IDENTIFIER); + sessionScope.onEvent(new HttpSessionEnd(this, session2)); + sessionScope.stop(); + } + + + /** + * Tests a session-to-module scoped wire + */ + public void testSessionToModule() throws Exception { + WorkContext ctx = new WorkContextImpl(); + ScopeContainer moduleScope = new ModuleScopeContainer(ctx); + moduleScope.start(); + ScopeContainer sessionScope = new HttpSessionScopeContainer(ctx); + sessionScope.start(); + + Map<String, AtomicComponent> contexts = MockFactory.createWiredComponents("source", SourceImpl.class, + sessionScope, members, "target", Target.class, TargetImpl.class, moduleScope); + moduleScope.onEvent(new CompositeStart(this, null)); + Object session1 = new Object(); + ctx.setIdentifier(HttpSessionScopeContainer.HTTP_IDENTIFIER, session1); + sessionScope.onEvent(new HttpSessionStart(this, session1)); + AtomicComponent sourceComponent = contexts.get("source"); + AtomicComponent targetComponent = contexts.get("target"); + Source source = (Source) sourceComponent.getServiceInstance(); + Target target = (Target) targetComponent.getServiceInstance(); + assertNull(source.getTarget().getString()); + assertNull(target.getString()); + target.setString("foo"); + assertTrue(Proxy.isProxyClass(source.getTarget().getClass())); + assertEquals("foo", source.getTarget().getString()); + ctx.clearIdentifier(HttpSessionScopeContainer.HTTP_IDENTIFIER); + sessionScope.onEvent(new HttpSessionEnd(this, session1)); + + //second session + Object session2 = new Object(); + ctx.setIdentifier(HttpSessionScopeContainer.HTTP_IDENTIFIER, session2); + sessionScope.onEvent(new HttpSessionStart(this, session2)); + + Target target2 = (Target) targetComponent.getServiceInstance(); + Source source2 = (Source) sourceComponent.getServiceInstance(); + assertEquals("foo", target2.getString()); + assertEquals("foo", source2.getTarget().getString()); + source2.getTarget().setString("baz"); + assertEquals("baz", source2.getTarget().getString()); + assertEquals("baz", target2.getString()); + assertEquals("baz", target.getString()); + ctx.clearIdentifier(HttpSessionScopeContainer.HTTP_IDENTIFIER); + sessionScope.onEvent(new HttpSessionEnd(this, session2)); + moduleScope.stop(); + sessionScope.stop(); + } + + /** + * Tests a session-to-request scoped wire is setup properly by the runtime + */ + public void testSessionToRequest() throws Exception { + WorkContext ctx = new WorkContextImpl(); + final ScopeContainer requestScope = new RequestScopeContainer(ctx); + requestScope.start(); + ScopeContainer sessionScope = new HttpSessionScopeContainer(ctx); + sessionScope.start(); + + Map<String, AtomicComponent> contexts = MockFactory.createWiredComponents("source", SourceImpl.class, + sessionScope, members, "target", Target.class, TargetImpl.class, requestScope); + Object session1 = new Object(); + ctx.setIdentifier(HttpSessionScopeContainer.HTTP_IDENTIFIER, session1); + sessionScope.onEvent(new HttpSessionStart(this, session1)); + requestScope.onEvent(new RequestStart(this)); + AtomicComponent sourceComponent = contexts.get("source"); + final AtomicComponent targetComponent = contexts.get("target"); + final Source source = (Source) sourceComponent.getServiceInstance(); + Target target = (Target) targetComponent.getServiceInstance(); + assertNull(source.getTarget().getString()); + assertNull(target.getString()); + target.setString("foo"); + assertTrue(Proxy.isProxyClass(source.getTarget().getClass())); + assertEquals("foo", source.getTarget().getString()); + + // spin off another request + Executor executor = Executors.newSingleThreadExecutor(); + FutureTask<Void> future = new FutureTask<Void>(new Runnable() { + public void run() { + requestScope.onEvent(new RequestStart(this)); + Target target2 = (Target) targetComponent.getServiceInstance(); + assertFalse("foo".equals(target2.getString())); + assertFalse("foo".equals(source.getTarget().getString())); + source.getTarget().setString("bar"); + assertEquals("bar", target2.getString()); + assertEquals("bar", source.getTarget().getString()); + requestScope.onEvent(new RequestEnd(this)); + } + }, null); + executor.execute(future); + future.get(); + assertEquals("foo", source.getTarget().getString()); + requestScope.onEvent(new RequestEnd(this)); + ctx.clearIdentifier(HttpSessionScopeContainer.HTTP_IDENTIFIER); + sessionScope.onEvent(new HttpSessionEnd(this, session1)); + requestScope.stop(); + sessionScope.stop(); + } + + + /** + * Tests a session-to-stateless scoped wire is setup properly by the runtime + */ + public void testSessionToStateless() throws Exception { + WorkContext ctx = new WorkContextImpl(); + ScopeContainer sessionScope = new HttpSessionScopeContainer(ctx); + sessionScope.start(); + ScopeContainer statelessScope = new StatelessScopeContainer(ctx); + statelessScope.start(); + + Map<String, AtomicComponent> contexts = MockFactory.createWiredComponents("source", SourceImpl.class, + sessionScope, members, "target", Target.class, TargetImpl.class, statelessScope); + + Object session1 = new Object(); + ctx.setIdentifier(HttpSessionScopeContainer.HTTP_IDENTIFIER, session1); + sessionScope.onEvent(new HttpSessionStart(this, session1)); + + AtomicComponent sourceComponent = contexts.get("source"); + AtomicComponent targetComponent = contexts.get("target"); + Source source = (Source) sourceComponent.getServiceInstance(); + Target target = (Target) targetComponent.getServiceInstance(); + assertTrue(Proxy.isProxyClass(source.getTarget().getClass())); + assertNull(source.getTarget().getString()); + assertNull(target.getString()); + target.setString("foo"); + assertFalse("foo".equals(source.getTarget().getString())); + Target target2 = (Target) targetComponent.getServiceInstance(); + assertFalse("foo".equals(target2.getString())); + source.getTarget().setString("bar"); + assertFalse("bar".equals(source.getTarget().getString())); + + ctx.clearIdentifier(HttpSessionScopeContainer.HTTP_IDENTIFIER); + sessionScope.onEvent(new HttpSessionEnd(this, session1)); + sessionScope.stop(); + statelessScope.stop(); + } + + /** + * Tests a request-to-request scoped wire is setup properly by the runtime + */ + public void testRequestToRequest() throws Exception { + WorkContext ctx = new WorkContextImpl(); + final ScopeContainer requestScope = new RequestScopeContainer(ctx); + requestScope.start(); + + Map<String, AtomicComponent> contexts = MockFactory.createWiredComponents("source", SourceImpl.class, + requestScope, members, "target", Target.class, TargetImpl.class, requestScope); + requestScope.onEvent(new RequestStart(this)); + + final AtomicComponent sourceComponent = contexts.get("source"); + final AtomicComponent targetComponent = contexts.get("target"); + Source source = (Source) sourceComponent.getServiceInstance(); + Target target = (Target) targetComponent.getServiceInstance(); + assertNull(source.getTarget().getString()); + assertNull(target.getString()); + target.setString("foo"); + assertTrue(Proxy.isProxyClass(source.getTarget().getClass())); + assertEquals("foo", source.getTarget().getString()); + + // spin off another request + Executor executor = Executors.newSingleThreadExecutor(); + FutureTask<Void> future = new FutureTask<Void>(new Runnable() { + public void run() { + requestScope.onEvent(new RequestStart(this)); + Source source2 = (Source) sourceComponent.getServiceInstance(); + Target target2 = (Target) targetComponent.getServiceInstance(); + assertFalse("foo".equals(target2.getString())); + assertFalse("foo".equals(source2.getTarget().getString())); + source2.getTarget().setString("bar"); + assertEquals("bar", target2.getString()); + assertEquals("bar", source2.getTarget().getString()); + requestScope.onEvent(new RequestEnd(this)); + } + }, null); + executor.execute(future); + future.get(); + requestScope.onEvent(new RequestEnd(this)); + requestScope.stop(); + } + + /** + * Tests a request-to-module scoped wire + */ + public void testRequestToModule() throws Exception { + WorkContext ctx = new WorkContextImpl(); + final ScopeContainer requestScope = new RequestScopeContainer(ctx); + final ScopeContainer moduleScope = new ModuleScopeContainer(ctx); + requestScope.start(); + moduleScope.start(); + moduleScope.onEvent(new CompositeStart(this, null)); + + Map<String, AtomicComponent> contexts = MockFactory.createWiredComponents("source", SourceImpl.class, + requestScope, members, "target", Target.class, TargetImpl.class, moduleScope); + requestScope.onEvent(new RequestStart(this)); + + final AtomicComponent sourceComponent = contexts.get("source"); + final AtomicComponent targetComponent = contexts.get("target"); + Source source = (Source) sourceComponent.getServiceInstance(); + Target target = (Target) targetComponent.getServiceInstance(); + assertNull(source.getTarget().getString()); + assertNull(target.getString()); + target.setString("foo"); + assertTrue(Proxy.isProxyClass(source.getTarget().getClass())); + assertEquals("foo", source.getTarget().getString()); + + // spin off another request + Executor executor = Executors.newSingleThreadExecutor(); + FutureTask<Void> future = new FutureTask<Void>(new Runnable() { + public void run() { + requestScope.onEvent(new RequestStart(this)); + Source source2 = (Source) sourceComponent.getServiceInstance(); + Target target2 = (Target) targetComponent.getServiceInstance(); + assertEquals("foo", target2.getString()); + assertEquals("foo", source2.getTarget().getString()); + source2.getTarget().setString("bar"); + assertEquals("bar", target2.getString()); + assertEquals("bar", source2.getTarget().getString()); + requestScope.onEvent(new RequestEnd(this)); + } + }, null); + executor.execute(future); + future.get(); + assertEquals("bar", target.getString()); + + requestScope.onEvent(new RequestEnd(this)); + requestScope.stop(); + moduleScope.onEvent(new CompositeStop(this, null)); + moduleScope.stop(); + } + + /** + * Tests a request-to-session scoped wire is setup properly by the runtime + */ + public void testRequestToSession() throws Exception { + WorkContext ctx = new WorkContextImpl(); + final ScopeContainer requestScope = new RequestScopeContainer(ctx); + final ScopeContainer sessionScope = new HttpSessionScopeContainer(ctx); + requestScope.start(); + sessionScope.start(); + + Object session1 = new Object(); + ctx.setIdentifier(HttpSessionScopeContainer.HTTP_IDENTIFIER, session1); + sessionScope.onEvent(new HttpSessionStart(this, session1)); + Map<String, AtomicComponent> contexts = MockFactory.createWiredComponents("source", SourceImpl.class, + requestScope, members, "target", Target.class, TargetImpl.class, sessionScope); + + final AtomicComponent sourceComponent = contexts.get("source"); + final AtomicComponent targetComponent = contexts.get("target"); + requestScope.onEvent(new RequestStart(this)); + Source source = (Source) sourceComponent.getServiceInstance(); + Target target = (Target) targetComponent.getServiceInstance(); + assertNull(source.getTarget().getString()); + assertNull(target.getString()); + target.setString("foo"); + assertTrue(Proxy.isProxyClass(source.getTarget().getClass())); + assertEquals("foo", source.getTarget().getString()); + + // spin off another request + Executor executor = Executors.newSingleThreadExecutor(); + FutureTask<Void> future = new FutureTask<Void>(new Runnable() { + public void run() { + requestScope.onEvent(new RequestStart(this)); + Source source2 = (Source) sourceComponent.getServiceInstance(); + Target target2 = (Target) targetComponent.getServiceInstance(); + assertEquals("foo", target2.getString()); + assertEquals("foo", source2.getTarget().getString()); + source2.getTarget().setString("bar"); + assertEquals("bar", target2.getString()); + assertEquals("bar", source2.getTarget().getString()); + requestScope.onEvent(new RequestEnd(this)); + } + }, null); + executor.execute(future); + future.get(); + assertEquals("bar", target.getString()); + + requestScope.onEvent(new RequestEnd(this)); + requestScope.stop(); + ctx.clearIdentifier(HttpSessionScopeContainer.HTTP_IDENTIFIER); + sessionScope.onEvent(new HttpSessionEnd(this, session1)); + sessionScope.stop(); + } + + + /** + * Tests a request-to-stateless scoped wire is setup properly by the runtime + */ + public void testRequestToStateless() throws Exception { + WorkContext ctx = new WorkContextImpl(); + ScopeContainer requestScope = new RequestScopeContainer(ctx); + requestScope.start(); + ScopeContainer statelessScope = new StatelessScopeContainer(ctx); + statelessScope.start(); + + Map<String, AtomicComponent> contexts = MockFactory.createWiredComponents("source", SourceImpl.class, + requestScope, members, "target", Target.class, TargetImpl.class, statelessScope); + + AtomicComponent sourceComponent = contexts.get("source"); + AtomicComponent targetComponent = contexts.get("target"); + requestScope.onEvent(new RequestStart(this)); + Source source = (Source) sourceComponent.getServiceInstance(); + Target target = (Target) targetComponent.getServiceInstance(); + assertTrue(Proxy.isProxyClass(source.getTarget().getClass())); + assertNull(source.getTarget().getString()); + assertNull(target.getString()); + target.setString("foo"); + assertFalse("foo".equals(source.getTarget().getString())); + Target target2 = (Target) targetComponent.getServiceInstance(); + assertFalse("foo".equals(target2.getString())); + source.getTarget().setString("bar"); + assertFalse("bar".equals(source.getTarget().getString())); + requestScope.onEvent(new RequestEnd(this)); + requestScope.stop(); + statelessScope.stop(); + } + + + /** + * Tests a stateless-to-stateless scoped wire is setup properly by the runtime + */ + public void testStatelessToStateless() throws Exception { + WorkContext ctx = new WorkContextImpl(); + ScopeContainer statelessScope = new StatelessScopeContainer(ctx); + statelessScope.start(); + + Map<String, AtomicComponent> contexts = MockFactory.createWiredComponents("source", SourceImpl.class, + statelessScope, members, "target", Target.class, TargetImpl.class, statelessScope); + + AtomicComponent sourceComponent = contexts.get("source"); + AtomicComponent targetComponent = contexts.get("target"); + Source source = (Source) sourceComponent.getServiceInstance(); + Target target = (Target) targetComponent.getServiceInstance(); + assertTrue(Proxy.isProxyClass(source.getTarget().getClass())); + assertNull(source.getTarget().getString()); + assertNull(target.getString()); + target.setString("foo"); + assertFalse("foo".equals(source.getTarget().getString())); + Target target2 = (Target) targetComponent.getServiceInstance(); + assertFalse("foo".equals(target2.getString())); + source.getTarget().setString("bar"); + assertFalse("bar".equals(source.getTarget().getString())); + statelessScope.stop(); + } + + /** + * Tests a stateless-to-request scoped wire is setup properly by the runtime + */ + public void testStatelessToRequest() throws Exception { + WorkContext ctx = new WorkContextImpl(); + final ScopeContainer requestScope = new RequestScopeContainer(ctx); + requestScope.start(); + ScopeContainer statelessScope = new StatelessScopeContainer(ctx); + statelessScope.start(); + + Map<String, AtomicComponent> contexts = MockFactory.createWiredComponents("source", SourceImpl.class, + statelessScope, members, "target", Target.class, TargetImpl.class, requestScope); + requestScope.onEvent(new RequestStart(this)); + AtomicComponent sourceComponent = contexts.get("source"); + final AtomicComponent targetComponent = contexts.get("target"); + final Source source = (Source) sourceComponent.getServiceInstance(); + Target target = (Target) targetComponent.getServiceInstance(); + assertNull(source.getTarget().getString()); + assertNull(target.getString()); + target.setString("foo"); + assertTrue(Proxy.isProxyClass(source.getTarget().getClass())); + assertEquals("foo", source.getTarget().getString()); + + // spin off another request + Executor executor = Executors.newSingleThreadExecutor(); + FutureTask<Void> future = new FutureTask<Void>(new Runnable() { + public void run() { + requestScope.onEvent(new RequestStart(this)); + Target target2 = (Target) targetComponent.getServiceInstance(); + assertFalse("foo".equals(target2.getString())); + assertFalse("foo".equals(source.getTarget().getString())); + source.getTarget().setString("bar"); + assertEquals("bar", target2.getString()); + assertEquals("bar", source.getTarget().getString()); + requestScope.onEvent(new RequestEnd(this)); + } + }, null); + executor.execute(future); + future.get(); + requestScope.stop(); + statelessScope.stop(); + } + + /** + * Tests a stateless-to-session scoped wire is setup properly by the runtime + */ + public void testStatelessToSession() throws Exception { + WorkContext ctx = new WorkContextImpl(); + ScopeContainer statelessScope = new StatelessScopeContainer(ctx); + statelessScope.start(); + ScopeContainer sessionScope = new HttpSessionScopeContainer(ctx); + sessionScope.start(); + + Map<String, AtomicComponent> contexts = MockFactory.createWiredComponents("source", SourceImpl.class, + statelessScope, members, "target", Target.class, TargetImpl.class, sessionScope); + Object session1 = new Object(); + ctx.setIdentifier(HttpSessionScopeContainer.HTTP_IDENTIFIER, session1); + sessionScope.onEvent(new HttpSessionStart(this, session1)); + AtomicComponent sourceComponent = contexts.get("source"); + AtomicComponent targetComponent = contexts.get("target"); + Source source = (Source) sourceComponent.getServiceInstance(); + Target target = (Target) targetComponent.getServiceInstance(); + assertNull(source.getTarget().getString()); + assertNull(target.getString()); + target.setString("foo"); + assertTrue(Proxy.isProxyClass(source.getTarget().getClass())); + assertEquals("foo", source.getTarget().getString()); + ctx.clearIdentifier(HttpSessionScopeContainer.HTTP_IDENTIFIER); + sessionScope.onEvent(new HttpSessionEnd(this, session1)); + + //second session + Object session2 = new Object(); + ctx.setIdentifier(HttpSessionScopeContainer.HTTP_IDENTIFIER, session2); + sessionScope.onEvent(new HttpSessionStart(this, session2)); + + Target target2 = (Target) targetComponent.getServiceInstance(); + assertFalse("foo".equals(target2.getString())); + + assertFalse("foo".equals(source.getTarget().getString())); + source.getTarget().setString("bar"); + assertEquals("bar", target2.getString()); + assertEquals("bar", source.getTarget().getString()); + sessionScope.onEvent(new HttpSessionEnd(this, session2)); + + ctx.clearIdentifier(HttpSessionScopeContainer.HTTP_IDENTIFIER); + sessionScope.stop(); + statelessScope.stop(); + } + + + /** + * Tests a stateless-to-module scoped wire is setup properly by the runtime + */ + public void testStatelessToModule() throws Exception { + WorkContext ctx = new WorkContextImpl(); + ScopeContainer statelessScope = new StatelessScopeContainer(ctx); + statelessScope.start(); + ScopeContainer moduleScope = new ModuleScopeContainer(ctx); + moduleScope.start(); + + Map<String, AtomicComponent> contexts = MockFactory.createWiredComponents("source", SourceImpl.class, + statelessScope, members, "target", Target.class, TargetImpl.class, moduleScope); + moduleScope.onEvent(new CompositeStart(this, null)); + AtomicComponent sourceComponent = contexts.get("source"); + AtomicComponent targetComponent = contexts.get("target"); + Source source = (Source) sourceComponent.getServiceInstance(); + Target target = (Target) targetComponent.getServiceInstance(); + assertNull(source.getTarget().getString()); + assertNull(target.getString()); + target.setString("foo"); + assertTrue(Proxy.isProxyClass(source.getTarget().getClass())); + assertEquals("foo", source.getTarget().getString()); + + //second session + Object session2 = new Object(); + ctx.setIdentifier(HttpSessionScopeContainer.HTTP_IDENTIFIER, session2); + moduleScope.onEvent(new HttpSessionStart(this, session2)); + + Target target2 = (Target) targetComponent.getServiceInstance(); + assertEquals("foo", target2.getString()); + + assertEquals("foo", source.getTarget().getString()); + source.getTarget().setString("bar"); + assertEquals("bar", target2.getString()); + assertEquals("bar", source.getTarget().getString()); + + moduleScope.onEvent(new CompositeStop(this, null)); + moduleScope.stop(); + statelessScope.stop(); + } + + protected void setUp() throws Exception { + super.setUp(); + members = new HashMap<String, Member>(); + Method[] methods = SourceImpl.class.getMethods(); + for (Method method : methods) { + if (method.getName().startsWith("set")) { + members.put(JavaIntrospectionHelper.toPropertyName(method.getName()), method); + } + } + } + + +} + diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/java/mock/MockFactory.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/java/mock/MockFactory.java new file mode 100644 index 0000000000..3c2093eee7 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/java/mock/MockFactory.java @@ -0,0 +1,381 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.implementation.java.mock; + +import java.lang.reflect.Member; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.apache.tuscany.spi.builder.BuilderConfigException; +import org.apache.tuscany.spi.component.AtomicComponent; +import org.apache.tuscany.spi.component.ScopeContainer; +import org.apache.tuscany.spi.idl.InvalidServiceContractException; +import org.apache.tuscany.spi.idl.java.JavaIDLUtils; +import org.apache.tuscany.spi.idl.java.JavaInterfaceProcessorRegistry; +import org.apache.tuscany.spi.model.Operation; +import org.apache.tuscany.spi.model.Scope; +import org.apache.tuscany.spi.model.ServiceContract; +import org.apache.tuscany.spi.wire.InboundInvocationChain; +import org.apache.tuscany.spi.wire.InboundWire; +import org.apache.tuscany.spi.wire.Interceptor; +import org.apache.tuscany.spi.wire.OutboundInvocationChain; +import org.apache.tuscany.spi.wire.OutboundWire; +import org.apache.tuscany.spi.wire.TargetInvoker; +import org.apache.tuscany.spi.wire.WireService; + +import org.apache.tuscany.core.component.WorkContextImpl; +import org.apache.tuscany.core.idl.java.JavaInterfaceProcessorRegistryImpl; +import org.apache.tuscany.core.implementation.PojoConfiguration; +import org.apache.tuscany.core.implementation.java.JavaAtomicComponent; +import org.apache.tuscany.core.implementation.java.JavaTargetInvoker; +import org.apache.tuscany.core.injection.PojoObjectFactory; +import org.apache.tuscany.core.wire.InboundInvocationChainImpl; +import org.apache.tuscany.core.wire.InboundWireImpl; +import org.apache.tuscany.core.wire.InvokerInterceptor; +import org.apache.tuscany.core.wire.OutboundInvocationChainImpl; +import org.apache.tuscany.core.wire.OutboundWireImpl; +import org.apache.tuscany.core.wire.jdk.JDKWireService; +import static org.easymock.EasyMock.createMock; +import static org.easymock.EasyMock.expectLastCall; +import static org.easymock.EasyMock.isA; +import static org.easymock.EasyMock.replay; + +/** + * @version $$Rev$$ $$Date$$ + */ +public final class MockFactory { + + private static final WireService WIRE_SERVICE = new JDKWireService(new WorkContextImpl(), null); + private static final JavaInterfaceProcessorRegistry REGISTRY = new JavaInterfaceProcessorRegistryImpl(); + + private MockFactory() { + } + + /** + * Creates a JavaAtomicComponent which returns the given instance + */ + @SuppressWarnings("unchecked") + public static <T> JavaAtomicComponent createJavaComponent(T instance) { + ScopeContainer scope = createMock(ScopeContainer.class); + scope.getScope(); + expectLastCall().andReturn(Scope.MODULE); + scope.getInstance(isA(JavaAtomicComponent.class)); + expectLastCall().andReturn(instance).anyTimes(); + replay(scope); + PojoConfiguration configuration = new PojoConfiguration(); + configuration.setScopeContainer(scope); + try { + configuration.setInstanceFactory(new PojoObjectFactory(DummyImpl.class.getConstructor())); + } catch (NoSuchMethodException e) { + throw new AssertionError(e); + } + configuration.addServiceInterface(DummyImpl.class); + configuration.setWireService(WIRE_SERVICE); + return new JavaAtomicComponent(instance.getClass().getName(), configuration, null); + } + + @SuppressWarnings("unchecked") + public static <T> JavaAtomicComponent createJavaComponent(String name, ScopeContainer scope, Class<T> clazz) + throws NoSuchMethodException { + PojoConfiguration configuration = new PojoConfiguration(); + configuration.setScopeContainer(scope); + configuration.setInstanceFactory(new PojoObjectFactory(clazz.getConstructor())); + configuration.addServiceInterface(clazz); + configuration.setWireService(WIRE_SERVICE); + return new JavaAtomicComponent(name, configuration, null); + + } + + /** + * Wires two contexts together where the reference interface is the same as target service + * + * @param sourceName + * @param sourceClass + * @param sourceScope + * @param members + * @param targetName + * @param targetService + * @param targetClass + * @param targetScope + * @return + * @throws Exception + */ + public static Map<String, AtomicComponent> createWiredComponents(String sourceName, + Class<?> sourceClass, + ScopeContainer sourceScope, + Map<String, Member> members, + String targetName, + Class<?> targetService, + Class<?> targetClass, + ScopeContainer targetScope) throws Exception { + return createWiredComponents(sourceName, sourceClass, targetService, sourceScope, members, targetName, + targetService, targetClass, targetScope); + + } + + /** + * Wires two contexts together where the reference interface may be different from the target service + */ + public static Map<String, AtomicComponent> createWiredComponents(String sourceName, Class<?> sourceClass, + Class<?> sourceReferenceClass, + ScopeContainer sourceScope, + Map<String, Member> members, + String targetName, + Class<?> targetService, + Class<?> targetClass, + ScopeContainer targetScope) throws Exception { + return createWiredComponents(sourceName, + sourceClass, + sourceReferenceClass, + sourceScope, + null, + members, + targetName, + targetService, + targetClass, + targetScope, + null); + } + + @SuppressWarnings("unchecked") + public static Map<String, AtomicComponent> createWiredComponents(String sourceName, Class<?> sourceClass, + Class<?> sourceReferenceClass, + ScopeContainer sourceScope, + Interceptor sourceHeadInterceptor, + Map<String, Member> members, + String targetName, Class<?> targetService, + Class<?> targetClass, + ScopeContainer targetScope, + Interceptor targetHeadInterceptor) + throws Exception { + + JavaAtomicComponent targetContext = + createJavaComponent(targetName, targetScope, targetClass); + String serviceName = targetService.getName().substring(targetService.getName().lastIndexOf('.') + 1); + InboundWire inboundWire = createServiceWire(serviceName, targetService, targetHeadInterceptor); + targetContext.addInboundWire(inboundWire); + + PojoConfiguration configuration = new PojoConfiguration(); + configuration.setScopeContainer(sourceScope); + configuration.setInstanceFactory(new PojoObjectFactory(sourceClass.getConstructor())); + configuration.addServiceInterface(sourceClass); + configuration.setWireService(WIRE_SERVICE); + for (Map.Entry<String, Member> entry : members.entrySet()) { + configuration.addReferenceSite(entry.getKey(), entry.getValue()); + } + JavaAtomicComponent sourceContext = new JavaAtomicComponent(sourceName, configuration, null); + OutboundWire outboundWire = createReferenceWire(targetName, sourceReferenceClass, sourceHeadInterceptor); + sourceContext.addOutboundWire(outboundWire); + targetScope.register(targetContext); + sourceScope.register(sourceContext); + connect(outboundWire, inboundWire, targetContext, false); + Map<String, AtomicComponent> contexts = new HashMap<String, AtomicComponent>(); + contexts.put(sourceName, sourceContext); + contexts.put(targetName, targetContext); + return contexts; + } + + + /** + * Wires two contexts using a multiplicity reference + * + * @param sourceName + * @param sourceClass + * @param sourceReferenceClass + * @param sourceScope + * @param targetName + * @param targetService + * @param targetClass + * @param members + * @param targetScope + * @return + * @throws Exception + */ + @SuppressWarnings("unchecked") + public static Map<String, AtomicComponent> createWiredMultiplicity(String sourceName, Class<?> sourceClass, + Class<?> sourceReferenceClass, + ScopeContainer sourceScope, + String targetName, Class<?> targetService, + Class<?> targetClass, + Map<String, Member> members, + ScopeContainer targetScope) throws Exception { + JavaAtomicComponent targetContext = + createJavaComponent(targetName, targetScope, targetClass); + String serviceName = targetService.getName().substring(targetService.getName().lastIndexOf('.') + 1); + InboundWire inboundWire = createServiceWire(serviceName, targetService, null); + targetContext.addInboundWire(inboundWire); + + PojoConfiguration configuration = new PojoConfiguration(); + configuration.setScopeContainer(sourceScope); + configuration.setInstanceFactory(new PojoObjectFactory(sourceClass.getConstructor())); + configuration.addServiceInterface(sourceClass); + configuration.setWireService(WIRE_SERVICE); + for (Map.Entry<String, Member> entry : members.entrySet()) { + configuration.addReferenceSite(entry.getKey(), entry.getValue()); + } + JavaAtomicComponent sourceContext = new JavaAtomicComponent(sourceName, configuration, null); + OutboundWire outboundWire = createReferenceWire(targetName, sourceReferenceClass, null); + List<OutboundWire> factories = new ArrayList<OutboundWire>(); + factories.add(outboundWire); + sourceContext.addOutboundWires(sourceReferenceClass, factories); + targetScope.register(targetContext); + sourceScope.register(sourceContext); + connect(outboundWire, inboundWire, targetContext, false); + Map<String, AtomicComponent> contexts = new HashMap<String, AtomicComponent>(); + contexts.put(sourceName, sourceContext); + contexts.put(targetName, targetContext); + return contexts; + } + + public static <T> InboundWire createTargetWire(String serviceName, Class<T> interfaze) + throws InvalidServiceContractException { + return createServiceWire(serviceName, interfaze, null); + } + + + public static <T> InboundWire createServiceWire(String serviceName, Class<T> interfaze, Interceptor interceptor) + throws InvalidServiceContractException { + InboundWire wire = new InboundWireImpl(); + ServiceContract<?> contract = REGISTRY.introspect(interfaze); + wire.setServiceContract(contract); + wire.setServiceName(serviceName); + wire.addInvocationChains( + createInboundChains(interfaze, interceptor)); + return wire; + } + + public static <T> OutboundWire createReferenceWire(String refName, Class<T> interfaze, Interceptor interceptor) + throws InvalidServiceContractException { + + OutboundWire wire = new OutboundWireImpl(); + wire.setReferenceName(refName); + Map<Operation<?>, OutboundInvocationChain> outboundChains = createOutboundChains(interfaze, interceptor); + wire.addInvocationChains(outboundChains); + ServiceContract<?> contract = REGISTRY.introspect(interfaze); + wire.setServiceContract(contract); + return wire; + } + + public static <T> OutboundWire createReferenceWire(String refName, Class<T> interfaze) + throws InvalidServiceContractException { + OutboundWire wire = new OutboundWireImpl(); + wire.setReferenceName(refName); + wire.addInvocationChains(createOutboundChains(interfaze)); + ServiceContract<?> contract = REGISTRY.introspect(interfaze); + wire.setServiceContract(contract); + return wire; + } + + + /** + * @param outboundWire + * @param inboundWire + * @param targetContext + * @param cacheable + * @throws Exception + */ + public static void connect(OutboundWire outboundWire, + InboundWire inboundWire, + JavaAtomicComponent targetContext, + boolean cacheable) throws Exception { + if (inboundWire != null) { + // if null, the target side has no interceptors or handlers + Map<Operation<?>, InboundInvocationChain> targetInvocationConfigs = inboundWire.getInvocationChains(); + for (OutboundInvocationChain outboundInvocationConfig : outboundWire.getInvocationChains().values()) { + // match wire chains + InboundInvocationChain inboundInvocationConfig = + targetInvocationConfigs.get(outboundInvocationConfig.getOperation()); + if (inboundInvocationConfig == null) { + BuilderConfigException e = + new BuilderConfigException("Incompatible source and target interface types for reference"); + e.setIdentifier(outboundWire.getReferenceName()); + throw e; + } + if (inboundInvocationConfig.getHeadInterceptor() == null) { + BuilderConfigException e = + new BuilderConfigException("No target handler or interceptor for operation"); + e.setIdentifier(inboundInvocationConfig.getOperation().getName()); + throw e; + } + if (!(outboundInvocationConfig.getTailInterceptor() instanceof InvokerInterceptor + && inboundInvocationConfig.getHeadInterceptor() instanceof InvokerInterceptor)) { + // check that we do not have the case where the only interceptors are invokers since we just + // need one + outboundInvocationConfig.setTargetInterceptor(inboundInvocationConfig.getHeadInterceptor()); + } + } + + for (OutboundInvocationChain chain : outboundWire.getInvocationChains().values()) { + //FIXME should use target method, not outboundInvocationConfig.getMethod() + Method[] methods = outboundWire.getServiceContract().getInterfaceClass().getMethods(); + Method m = JavaIDLUtils.findMethod(chain.getOperation(), methods); + TargetInvoker invoker = new JavaTargetInvoker(m, targetContext); + invoker.setCacheable(cacheable); + chain.setTargetInvoker(invoker); + } + } + } + + private static Map<Operation<?>, OutboundInvocationChain> createOutboundChains(Class<?> interfaze) + throws InvalidServiceContractException { + return createOutboundChains(interfaze, null); + } + + private static Map<Operation<?>, OutboundInvocationChain> createOutboundChains(Class<?> interfaze, + Interceptor interceptor) + throws InvalidServiceContractException { + Map<Operation<?>, OutboundInvocationChain> invocations = new HashMap<Operation<?>, OutboundInvocationChain>(); + ServiceContract<?> contract = REGISTRY.introspect(interfaze); + for (Operation<?> operation : contract.getOperations().values()) { + OutboundInvocationChain chain = new OutboundInvocationChainImpl(operation); + if (interceptor != null) { + chain.addInterceptor(interceptor); + } + invocations.put(operation, chain); + } + return invocations; + } + + private static Map<Operation<?>, InboundInvocationChain> createInboundChains(Class<?> interfaze, + Interceptor interceptor) + throws InvalidServiceContractException { + + Map<Operation<?>, InboundInvocationChain> invocations = new HashMap<Operation<?>, InboundInvocationChain>(); + ServiceContract<?> contract = REGISTRY.introspect(interfaze); + for (Operation<?> method : contract.getOperations().values()) { + InboundInvocationChain chain = new InboundInvocationChainImpl(method); + if (interceptor != null) { + chain.addInterceptor(interceptor); + } + // add tail interceptor + chain.addInterceptor(new InvokerInterceptor()); + invocations.put(method, chain); + } + return invocations; + } + + private static class DummyImpl { + public DummyImpl() { + } + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/java/mock/components/AsyncTarget.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/java/mock/components/AsyncTarget.java new file mode 100644 index 0000000000..1abc9781e3 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/java/mock/components/AsyncTarget.java @@ -0,0 +1,31 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.implementation.java.mock.components; + +import org.osoa.sca.annotations.OneWay; + +/** + * @version $Rev$ $Date$ + */ +public interface AsyncTarget { + @OneWay + void invoke(); + + int getCount(); +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/java/mock/components/OtherTarget.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/java/mock/components/OtherTarget.java new file mode 100644 index 0000000000..87b1fd87fa --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/java/mock/components/OtherTarget.java @@ -0,0 +1,31 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.implementation.java.mock.components; + +/** + * Implementations are used in wiring tests + * + * @version $Rev$ $Date$ + */ +public interface OtherTarget { + + String getString(); + + void setString(String val); +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/java/mock/components/OtherTargetImpl.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/java/mock/components/OtherTargetImpl.java new file mode 100644 index 0000000000..b32fc7547e --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/java/mock/components/OtherTargetImpl.java @@ -0,0 +1,39 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.implementation.java.mock.components; + +/** + * A target used for testing wires with a different source and target interface + * + * @version $Rev$ $Date$ + */ +public class OtherTargetImpl implements OtherTarget { + + private String theString; + + public String getString() { + return theString; + } + + public void setString(String val) { + theString = val; + } + + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/java/mock/components/Source.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/java/mock/components/Source.java new file mode 100644 index 0000000000..bffacc3c20 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/java/mock/components/Source.java @@ -0,0 +1,37 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.implementation.java.mock.components; + +import java.util.List; + + +/** + * Implementations are used in wiring tests + * + * @version $Rev$ $Date$ + */ +public interface Source { + + Target getTarget(); + + List<Target> getTargets(); + + List<Target> getTargetsThroughField(); + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/java/mock/components/SourceImpl.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/java/mock/components/SourceImpl.java new file mode 100644 index 0000000000..bf9e30b306 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/java/mock/components/SourceImpl.java @@ -0,0 +1,66 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.implementation.java.mock.components; + +import java.util.List; + + +/** + * Mock system component implementation used in wiring tests + * + * @version $Rev$ $Date$ + */ +public class SourceImpl implements Source { + + private Target target; + private List<Target> targets; + private Target[] targetsArray; + private List<Target> targetsThroughField; + + public void setTarget(Target target) { + this.target = target; + } + + public Target getTarget() { + return target; + } + + public List<Target> getTargets() { + return targets; + } + + public void setTargets(List<Target> targets) { + this.targets = targets; + } + + public List<Target> getTargetsThroughField() { + return targetsThroughField; + } + + + public Target[] getArrayOfTargets() { + return targetsArray; + } + + public void setArrayOfTargets(Target[] targets) { + targetsArray = targets; + } + + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/java/mock/components/Target.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/java/mock/components/Target.java new file mode 100644 index 0000000000..cafebc0801 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/java/mock/components/Target.java @@ -0,0 +1,31 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.implementation.java.mock.components; + +/** + * Implementations are used in wiring tests + * + * @version $Rev$ $Date$ + */ +public interface Target { + + String getString(); + + void setString(String val); +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/java/mock/components/TargetImpl.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/java/mock/components/TargetImpl.java new file mode 100644 index 0000000000..060ca292a9 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/java/mock/components/TargetImpl.java @@ -0,0 +1,38 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.implementation.java.mock.components; + +/** + * Mock system component implementation used in wiring tests + * + * @version $Rev$ $Date$ + */ +public class TargetImpl implements Target { + + private String theString; + + public String getString() { + return theString; + } + + public void setString(String val) { + theString = val; + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/processor/ConstructorAutowireTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/processor/ConstructorAutowireTestCase.java new file mode 100644 index 0000000000..c67d226b41 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/processor/ConstructorAutowireTestCase.java @@ -0,0 +1,154 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.implementation.processor; + +import java.lang.reflect.Constructor; +import java.util.List; + +import org.osoa.sca.annotations.Property; + +import org.apache.tuscany.spi.annotation.Autowire; +import org.apache.tuscany.spi.implementation.java.JavaMappedProperty; +import org.apache.tuscany.spi.implementation.java.JavaMappedReference; +import org.apache.tuscany.spi.implementation.java.JavaMappedService; +import org.apache.tuscany.spi.implementation.java.PojoComponentType; + +import junit.framework.TestCase; +import org.apache.tuscany.core.idl.java.JavaInterfaceProcessorRegistryImpl; + +/** + * @version $Rev$ $Date$ + */ +public class ConstructorAutowireTestCase extends TestCase { + + ConstructorProcessor processor = + new ConstructorProcessor(new ImplementationProcessorServiceImpl(new JavaInterfaceProcessorRegistryImpl())); + + public void testAutowire() throws Exception { + PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>> type = + new PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>>(); + Constructor<Foo> ctor = Foo.class.getConstructor(Bar.class); + processor.visitConstructor(null, ctor, type, null); + assertNotNull(type.getReferences().get("myRef")); + } + + public void testNamesOnConstructor() throws Exception { + PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>> type = + new PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>>(); + Constructor<Foo> ctor = Foo.class.getConstructor(Bar.class, Bar.class); + processor.visitConstructor(null, ctor, type, null); + assertEquals(2, type.getConstructorDefinition().getInjectionNames().size()); + assertNotNull(type.getReferences().get("myRef1")); + assertNotNull(type.getReferences().get("myRef2")); + } + + public void testNoName() throws Exception { + PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>> type = + new PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>>(); + Constructor<Foo2> ctor = Foo2.class.getConstructor(Bar.class); + processor.visitConstructor(null, ctor, type, null); + assertNotNull(type.getReferences().get(Bar.class.getName() + "0")); + } + + public void testInvalidNumberOfNames() throws Exception { + PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>> type = + new PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>>(); + Constructor<BadFoo> ctor = BadFoo.class.getConstructor(Bar.class, Bar.class); + try { + processor.visitConstructor(null, ctor, type, null); + fail(); + } catch (InvalidAutowireException e) { + // expected + } + } + + public void testNoMatchingNames() throws Exception { + PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>> type = + new PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>>(); + Constructor<BadFoo> ctor = BadFoo.class.getConstructor(List.class, List.class); + try { + processor.visitConstructor(null, ctor, type, null); + fail(); + } catch (InvalidConstructorException e) { + // expected + } + } + + /** + * Verifies processing executes with additional extension annotations + */ + public void testRandomAnnotation() throws Exception { + PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>> type = + new PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>>(); + Constructor<Foo3> ctor = Foo3.class.getConstructor(String.class, String.class); + processor.visitConstructor(null, ctor, type, null); + assertEquals(1, type.getProperties().size()); + assertNotNull(type.getProperties().get("prop1")); + } + + private static interface Bar { + + } + + private static class Foo { + + @org.osoa.sca.annotations.Constructor() + public Foo(@Autowire(name = "myRef") Bar ref) { + + } + + @org.osoa.sca.annotations.Constructor({"myRef1", "myRef2"}) + public Foo(@Autowire Bar ref1, @Autowire Bar ref2) { + + } + + } + + private static class Foo2 { + @org.osoa.sca.annotations.Constructor() + public Foo2(@Autowire Bar ref) { + + } + } + + private static class BadFoo { + + @org.osoa.sca.annotations.Constructor({"ref1"}) + public BadFoo(@Autowire Bar ref1, @Autowire Bar ref2) { + + } + + @org.osoa.sca.annotations.Constructor({"myRef", "myRef2"}) + public BadFoo(@Autowire List ref, @Autowire(name = "myOtherRef") List ref2) { + + } + + } + + public static class Foo3 { + + @org.osoa.sca.annotations.Constructor + public Foo3(@Property(name = "prop1") String prop, @Baz String baz) { + } + } + + public @interface Baz { + + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/processor/ConstructorProcessorExtensibilityTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/processor/ConstructorProcessorExtensibilityTestCase.java new file mode 100644 index 0000000000..25a8ab9a1a --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/processor/ConstructorProcessorExtensibilityTestCase.java @@ -0,0 +1,82 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.implementation.processor; + +import java.lang.reflect.Constructor; + +import org.osoa.sca.annotations.Property; + +import org.apache.tuscany.spi.implementation.java.ConstructorDefinition; +import org.apache.tuscany.spi.implementation.java.JavaMappedProperty; +import org.apache.tuscany.spi.implementation.java.JavaMappedReference; +import org.apache.tuscany.spi.implementation.java.JavaMappedService; +import org.apache.tuscany.spi.implementation.java.PojoComponentType; + +import junit.framework.TestCase; +import org.apache.tuscany.core.idl.java.JavaInterfaceProcessorRegistryImpl; + +/** + * Verifies the constructor processor works when parameters are marked with custom extension annotations + * + * @version $Rev$ $Date$ + */ +public class ConstructorProcessorExtensibilityTestCase extends TestCase { + private ConstructorProcessor processor = + new ConstructorProcessor(new ImplementationProcessorServiceImpl(new JavaInterfaceProcessorRegistryImpl())); + + public void testProcessFirst() throws Exception { + PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>> type = + new PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>>(); + Constructor<Foo> ctor1 = Foo.class.getConstructor(String.class, String.class); + processor.visitConstructor(null, ctor1, type, null); + assertEquals("foo", type.getConstructorDefinition().getInjectionNames().get(0)); + } + + /** + * Verifies the constructor processor can be called after another processor has evaluated the constructor and found + * an annotation + * + * @throws Exception + */ + public void testProcessLast() throws Exception { + PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>> type = + new PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>>(); + Constructor<Foo> ctor1 = Foo.class.getConstructor(String.class, String.class); + ConstructorDefinition<Foo> definition = new ConstructorDefinition<Foo>(ctor1); + definition.getInjectionNames().add(""); + definition.getInjectionNames().add("mybar"); + type.setConstructorDefinition(definition); + processor.visitConstructor(null, ctor1, type, null); + assertEquals("foo", type.getConstructorDefinition().getInjectionNames().get(0)); + } + + + private @interface Bar { + + } + + private static class Foo { + @org.osoa.sca.annotations.Constructor + public Foo(@Property(name = "foo") String foo, @Bar String bar) { + + } + } + + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/processor/ConstructorProcessorTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/processor/ConstructorProcessorTestCase.java new file mode 100644 index 0000000000..364bfcc274 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/processor/ConstructorProcessorTestCase.java @@ -0,0 +1,148 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.implementation.processor; + +import java.lang.reflect.Constructor; + +import org.osoa.sca.annotations.Property; +import org.osoa.sca.annotations.Reference; + +import org.apache.tuscany.spi.annotation.Autowire; +import org.apache.tuscany.spi.implementation.java.JavaMappedProperty; +import org.apache.tuscany.spi.implementation.java.JavaMappedReference; +import org.apache.tuscany.spi.implementation.java.JavaMappedService; +import org.apache.tuscany.spi.implementation.java.PojoComponentType; + +import junit.framework.TestCase; +import org.apache.tuscany.core.idl.java.JavaInterfaceProcessorRegistryImpl; + +/** + * @version $Rev$ $Date$ + */ +public class ConstructorProcessorTestCase extends TestCase { + private ConstructorProcessor processor = + new ConstructorProcessor(new ImplementationProcessorServiceImpl(new JavaInterfaceProcessorRegistryImpl())); + + public void testDuplicateConstructor() throws Exception { + PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>> type = + new PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>>(); + try { + processor.visitClass(null, BadFoo.class, type, null); + fail(); + } catch (DuplicateConstructorException e) { + // expected + } + } + + public void testConstructorAnnotation() throws Exception { + PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>> type = + new PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>>(); + Constructor<Foo> ctor1 = Foo.class.getConstructor(String.class); + processor.visitConstructor(null, ctor1, type, null); + assertEquals("foo", type.getConstructorDefinition().getInjectionNames().get(0)); + } + + public void testNoAnnotation() throws Exception { + PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>> type = + new PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>>(); + Constructor<NoAnnotation> ctor1 = NoAnnotation.class.getConstructor(); + processor.visitConstructor(null, ctor1, type, null); + assertNull(type.getConstructorDefinition()); + } + + public void testBadAnnotation() throws Exception { + PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>> type = + new PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>>(); + Constructor<BadAnnotation> ctor1 = BadAnnotation.class.getConstructor(String.class, Foo.class); + try { + processor.visitConstructor(null, ctor1, type, null); + fail(); + } catch (InvalidConstructorException e) { + // expected + } + } + + public void testMixedParameters() throws Exception { + PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>> type = + new PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>>(); + Constructor<Mixed> ctor1 = Mixed.class.getConstructor(String.class, String.class, String.class); + processor.visitConstructor(null, ctor1, type, null); + assertEquals("java.lang.String0", type.getConstructorDefinition().getInjectionNames().get(0)); + assertEquals("foo", type.getConstructorDefinition().getInjectionNames().get(1)); + assertEquals("bar", type.getConstructorDefinition().getInjectionNames().get(2)); + } + + public void testAllAutowireWithNoNames() throws Exception { + PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>> type = + new PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>>(); + Constructor<AllAutowireNoName> ctor1 = + AllAutowireNoName.class.getConstructor(String.class, String.class, String.class); + processor.visitConstructor(null, ctor1, type, null); + assertEquals("java.lang.String0", type.getConstructorDefinition().getInjectionNames().get(0)); + assertEquals("java.lang.String1", type.getConstructorDefinition().getInjectionNames().get(1)); + assertEquals("java.lang.String2", type.getConstructorDefinition().getInjectionNames().get(2)); + } + + private static class BadFoo { + + @org.osoa.sca.annotations.Constructor("foo") + public BadFoo(String foo) { + + } + + @org.osoa.sca.annotations.Constructor({"foo", "bar"}) + public BadFoo(String foo, String bar) { + + } + } + + private static class Foo { + @org.osoa.sca.annotations.Constructor("foo") + public Foo(String foo) { + + } + } + + private static class NoAnnotation { + public NoAnnotation() { + } + } + + private static class BadAnnotation { + @org.osoa.sca.annotations.Constructor("foo") + public BadAnnotation(String foo, Foo ref) { + } + } + + + public static final class Mixed { + @org.osoa.sca.annotations.Constructor + public Mixed(@Autowire String param1, + @Property(name = "foo") String param2, + @Reference(name = "bar") String param3) { + } + } + + public static final class AllAutowireNoName { + @org.osoa.sca.annotations.Constructor + public AllAutowireNoName(@Autowire String param1, @Autowire String param2, @Autowire String param3) { + } + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/processor/ConstructorPropertyTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/processor/ConstructorPropertyTestCase.java new file mode 100644 index 0000000000..ee461aead7 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/processor/ConstructorPropertyTestCase.java @@ -0,0 +1,171 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.implementation.processor; + +import java.lang.reflect.Constructor; +import java.util.List; + +import org.osoa.sca.annotations.Property; + +import org.apache.tuscany.spi.implementation.java.DuplicatePropertyException; +import org.apache.tuscany.spi.implementation.java.JavaMappedProperty; +import org.apache.tuscany.spi.implementation.java.JavaMappedReference; +import org.apache.tuscany.spi.implementation.java.JavaMappedService; +import org.apache.tuscany.spi.implementation.java.PojoComponentType; +import org.apache.tuscany.spi.model.OverrideOptions; + +import junit.framework.TestCase; +import org.apache.tuscany.core.idl.java.JavaInterfaceProcessorRegistryImpl; + +/** + * @version $Rev$ $Date$ + */ +public class ConstructorPropertyTestCase extends TestCase { + + ConstructorProcessor processor = + new ConstructorProcessor(new ImplementationProcessorServiceImpl(new JavaInterfaceProcessorRegistryImpl())); + + public void testProperty() throws Exception { + PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>> type = + new PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>>(); + Constructor<Foo> ctor = Foo.class.getConstructor(String.class); + processor.visitConstructor(null, ctor, type, null); + JavaMappedProperty<?> property = type.getProperties().get("myProp"); + //assertTrue(property.isRequired()); + assertEquals(property.getOverride(), OverrideOptions.MAY); + assertEquals("myProp", property.getName()); + } + + public void testTwoPropertiesSameType() throws Exception { + PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>> type = + new PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>>(); + Constructor<Foo> ctor = Foo.class.getConstructor(String.class, String.class); + processor.visitConstructor(null, ctor, type, null); + assertNotNull(type.getProperties().get("myProp1")); + assertNotNull(type.getProperties().get("myProp2")); + } + + public void testDuplicateProperty() throws Exception { + PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>> type = + new PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>>(); + Constructor<BadFoo> ctor = BadFoo.class.getConstructor(String.class, String.class); + try { + processor.visitConstructor(null, ctor, type, null); + fail(); + } catch (DuplicatePropertyException e) { + // expected + } + } + + public void testNoName() throws Exception { + PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>> type = + new PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>>(); + Constructor<BadFoo> ctor = BadFoo.class.getConstructor(String.class); + try { + processor.visitConstructor(null, ctor, type, null); + fail(); + } catch (InvalidPropertyException e) { + // expected + } + } + + public void testNamesOnConstructor() throws Exception { + PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>> type = + new PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>>(); + Constructor<Foo> ctor = Foo.class.getConstructor(Integer.class); + processor.visitConstructor(null, ctor, type, null); + assertNotNull(type.getProperties().get("myProp")); + } + + public void testInvalidNumberOfNames() throws Exception { + PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>> type = + new PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>>(); + Constructor<BadFoo> ctor = BadFoo.class.getConstructor(Integer.class, Integer.class); + try { + processor.visitConstructor(null, ctor, type, null); + fail(); + } catch (InvalidPropertyException e) { + // expected + } + } + + public void testNoMatchingNames() throws Exception { + PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>> type = + new PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>>(); + Constructor<BadFoo> ctor = BadFoo.class.getConstructor(List.class, List.class); + try { + processor.visitConstructor(null, ctor, type, null); + fail(); + } catch (InvalidConstructorException e) { + // expected + } + } + +// public void testMultiplicityRequired() throws Exception { + // TODO multiplicity +// } + + private static class Foo { + + @org.osoa.sca.annotations.Constructor() + public Foo(@Property(name = "myProp", override = "may") String prop) { + + } + + @org.osoa.sca.annotations.Constructor("myProp") + public Foo(@Property Integer prop) { + + } + + @org.osoa.sca.annotations.Constructor() + public Foo(@Property(name = "myProp1") String prop1, @Property(name = "myProp2") String prop2) { + + } + + @org.osoa.sca.annotations.Constructor() + public Foo(@Property List prop) { + + } + } + + private static class BadFoo { + + @org.osoa.sca.annotations.Constructor() + public BadFoo(@Property(name = "myProp") String prop1, @Property(name = "myProp") String prop2) { + + } + + @org.osoa.sca.annotations.Constructor() + public BadFoo(@Property String prop) { + + } + + @org.osoa.sca.annotations.Constructor("myProp") + public BadFoo(@Property Integer prop, @Property Integer prop2) { + + } + + @org.osoa.sca.annotations.Constructor({"myRef", "myRef2"}) + public BadFoo(@Property List ref, @Property(name = "myOtherRef") List ref2) { + + } + + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/processor/ConstructorReferenceTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/processor/ConstructorReferenceTestCase.java new file mode 100644 index 0000000000..687c95e860 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/processor/ConstructorReferenceTestCase.java @@ -0,0 +1,173 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.implementation.processor; + +import java.lang.reflect.Constructor; +import java.util.List; + +import org.osoa.sca.annotations.Reference; + +import org.apache.tuscany.spi.implementation.java.JavaMappedProperty; +import org.apache.tuscany.spi.implementation.java.JavaMappedReference; +import org.apache.tuscany.spi.implementation.java.JavaMappedService; +import org.apache.tuscany.spi.implementation.java.PojoComponentType; + +import junit.framework.TestCase; +import org.apache.tuscany.core.idl.java.JavaInterfaceProcessorRegistryImpl; + +/** + * @version $Rev$ $Date$ + */ +public class ConstructorReferenceTestCase extends TestCase { + + ConstructorProcessor processor; + + public void testReference() throws Exception { + PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>> type = + new PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>>(); + Constructor<Foo> ctor = Foo.class.getConstructor(String.class); + processor.visitConstructor(null, ctor, type, null); + JavaMappedReference reference = type.getReferences().get("myRef"); + assertTrue(reference.isRequired()); + assertEquals("myRef", reference.getName()); + } + + public void testTwoReferencesSameType() throws Exception { + PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>> type = + new PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>>(); + Constructor<Foo> ctor = Foo.class.getConstructor(String.class, String.class); + processor.visitConstructor(null, ctor, type, null); + assertNotNull(type.getReferences().get("myRef1")); + assertNotNull(type.getReferences().get("myRef2")); + } + + public void testDuplicateProperty() throws Exception { + PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>> type = + new PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>>(); + Constructor<BadFoo> ctor = BadFoo.class.getConstructor(String.class, String.class); + try { + processor.visitConstructor(null, ctor, type, null); + fail(); + } catch (DuplicateReferenceException e) { + // expected + } + } + + public void testNoName() throws Exception { + PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>> type = + new PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>>(); + Constructor<BadFoo> ctor = BadFoo.class.getConstructor(String.class); + try { + processor.visitConstructor(null, ctor, type, null); + fail(); + } catch (InvalidReferenceException e) { + // expected + } + } + + public void testNamesOnConstructor() throws Exception { + PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>> type = + new PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>>(); + Constructor<Foo> ctor = Foo.class.getConstructor(Integer.class); + processor.visitConstructor(null, ctor, type, null); + assertNotNull(type.getReferences().get("myRef")); + } + + public void testInvalidNumberOfNames() throws Exception { + PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>> type = + new PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>>(); + Constructor<BadFoo> ctor = BadFoo.class.getConstructor(Integer.class, Integer.class); + try { + processor.visitConstructor(null, ctor, type, null); + fail(); + } catch (InvalidReferenceException e) { + // expected + } + } + + public void testNoMatchingNames() throws Exception { + PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>> type = + new PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>>(); + Constructor<BadFoo> ctor = BadFoo.class.getConstructor(List.class, List.class); + try { + processor.visitConstructor(null, ctor, type, null); + fail(); + } catch (InvalidConstructorException e) { + // expected + } + } + + protected void setUp() throws Exception { + super.setUp(); + processor = + new ConstructorProcessor(new ImplementationProcessorServiceImpl(new JavaInterfaceProcessorRegistryImpl())); + } + +// public void testMultiplicityRequired() throws Exception { + // TODO multiplicity +// } + + private static class Foo { + + @org.osoa.sca.annotations.Constructor() + public Foo(@Reference(name = "myRef", required = true) String prop) { + + } + + @org.osoa.sca.annotations.Constructor() + public Foo(@Reference(name = "myRef1") String prop1, @Reference(name = "myRef2") String prop2) { + + } + + @org.osoa.sca.annotations.Constructor("myRef") + public Foo(@Reference Integer prop) { + + } + + @org.osoa.sca.annotations.Constructor() + public Foo(@Reference List prop) { + + } + } + + private static class BadFoo { + + @org.osoa.sca.annotations.Constructor + public BadFoo(@Reference(name = "myRef") String prop1, @Reference(name = "myRef") String prop2) { + + } + + @org.osoa.sca.annotations.Constructor + public BadFoo(@Reference String prop) { + + } + + @org.osoa.sca.annotations.Constructor("myRef") + public BadFoo(@Reference Integer ref, @Reference Integer ref2) { + + } + + @org.osoa.sca.annotations.Constructor({"myRef", "myRef2"}) + public BadFoo(@Reference List ref, @Reference(name = "myOtherRef") List ref2) { + + } + + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/processor/DestroyProcessorTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/processor/DestroyProcessorTestCase.java new file mode 100644 index 0000000000..6929250298 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/processor/DestroyProcessorTestCase.java @@ -0,0 +1,100 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.implementation.processor; + +import java.lang.reflect.Method; + +import org.osoa.sca.annotations.Destroy; + +import org.apache.tuscany.spi.implementation.java.JavaMappedService; + +import junit.framework.TestCase; +import org.apache.tuscany.spi.implementation.java.PojoComponentType; +import org.apache.tuscany.spi.implementation.java.JavaMappedProperty; + +import org.apache.tuscany.spi.implementation.java.JavaMappedReference; + +/** + * @version $Rev$ $Date$ + */ +public class DestroyProcessorTestCase extends TestCase { + + public void testDestroy() throws Exception { + DestroyProcessor processor = new DestroyProcessor(); + PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>> type = + new PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>>(); + Method method = Foo.class.getMethod("destroy"); + processor.visitMethod(null, method, type, null); + assertNotNull(type.getDestroyMethod()); + } + + public void testBadDestroy() throws Exception { + DestroyProcessor processor = new DestroyProcessor(); + PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>> type = + new PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>>(); + Method method = Bar.class.getMethod("badDestroy", String.class); + try { + processor.visitMethod(null, method, type, null); + fail(); + } catch (IllegalDestructorException e) { + // expected + } + } + + public void testTwoDestroy() throws Exception { + DestroyProcessor processor = new DestroyProcessor(); + PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>> type = + new PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>>(); + Method method = Bar.class.getMethod("destroy"); + Method method2 = Bar.class.getMethod("destroy2"); + processor.visitMethod(null, method, type, null); + try { + processor.visitMethod(null, method2, type, null); + fail(); + } catch (DuplicateDestructorException e) { + // expected + } + } + + + private class Foo { + + @Destroy + public void destroy() { + } + } + + + private class Bar { + + @Destroy + public void destroy() { + } + + @Destroy + public void destroy2() { + } + + @Destroy + public void badDestroy(String foo) { + } + + + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/processor/HeuristicAndPropertyTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/processor/HeuristicAndPropertyTestCase.java new file mode 100644 index 0000000000..93de605e33 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/processor/HeuristicAndPropertyTestCase.java @@ -0,0 +1,70 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.implementation.processor; + +import java.lang.reflect.Constructor; + +import org.osoa.sca.annotations.Property; + +import org.apache.tuscany.spi.implementation.java.ConstructorDefinition; +import org.apache.tuscany.spi.implementation.java.JavaMappedProperty; +import org.apache.tuscany.spi.implementation.java.JavaMappedReference; +import org.apache.tuscany.spi.implementation.java.JavaMappedService; +import org.apache.tuscany.spi.implementation.java.PojoComponentType; + +import junit.framework.TestCase; +import org.apache.tuscany.core.idl.java.JavaInterfaceProcessorRegistryImpl; + +/** + * @version $Rev$ $Date$ + */ +public class HeuristicAndPropertyTestCase extends TestCase { + + private PropertyProcessor propertyProcessor; + private HeuristicPojoProcessor heuristicProcessor; + + /** + * Verifies the property and heuristic processors don't collide + */ + @SuppressWarnings("unchecked") + public void testPropertyProcessorWithHeuristicProcessor() throws Exception { + PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>> type = + new PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>>(); + Constructor ctor = Foo.class.getConstructor(String.class); + type.setConstructorDefinition(new ConstructorDefinition(ctor)); + propertyProcessor.visitConstructor(null, ctor, type, null); + heuristicProcessor.visitEnd(null, Foo.class, type, null); + assertEquals(1, type.getProperties().size()); + assertNotNull(type.getProperties().get("foo")); + } + + protected void setUp() throws Exception { + super.setUp(); + ImplementationProcessorServiceImpl service = + new ImplementationProcessorServiceImpl(new JavaInterfaceProcessorRegistryImpl()); + propertyProcessor = new PropertyProcessor(service); + heuristicProcessor = new HeuristicPojoProcessor(service); + } + + public static class Foo { + public Foo(@Property(name = "foo") String prop) { + } + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/processor/HeuristicConstructorTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/processor/HeuristicConstructorTestCase.java new file mode 100644 index 0000000000..92f6d54366 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/processor/HeuristicConstructorTestCase.java @@ -0,0 +1,330 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.implementation.processor; + +import org.osoa.sca.annotations.Property; +import org.osoa.sca.annotations.Reference; +import org.osoa.sca.annotations.Remotable; + +import org.apache.tuscany.spi.annotation.Autowire; +import org.apache.tuscany.spi.idl.java.JavaServiceContract; +import org.apache.tuscany.spi.implementation.java.JavaMappedProperty; +import org.apache.tuscany.spi.implementation.java.JavaMappedReference; +import org.apache.tuscany.spi.implementation.java.JavaMappedService; +import org.apache.tuscany.spi.implementation.java.PojoComponentType; +import org.apache.tuscany.spi.model.ServiceContract; + +import junit.framework.TestCase; +import org.apache.tuscany.core.idl.java.JavaInterfaceProcessorRegistryImpl; + +/** + * @version $Rev$ $Date$ + */ +public class HeuristicConstructorTestCase extends TestCase { + + private HeuristicPojoProcessor processor = + new HeuristicPojoProcessor(new ImplementationProcessorServiceImpl(new JavaInterfaceProcessorRegistryImpl())); + + /** + * Verifies a single constructor is chosen with a parameter as the type + */ + public void testSingleConstructorWithParam() throws Exception { + PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>> type = + new PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>>(); + JavaMappedProperty<String> prop = new JavaMappedProperty<String>(); + prop.setName("foo"); + prop.setJavaType(String.class); + type.getProperties().put("foo", prop); + processor.visitEnd(null, Foo1.class, type, null); + assertNotNull(type.getConstructorDefinition().getConstructor()); + assertEquals("foo", type.getConstructorDefinition().getInjectionNames().get(0)); + } + + /** + * Verifies a single constructor is chosen with a reference as the type + */ + public void testSingleConstructorWithRef() throws Exception { + PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>> type = + new PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>>(); + JavaMappedReference ref = new JavaMappedReference(); + ref.setName("foo"); + ServiceContract contract = new JavaServiceContract(String.class); + ref.setServiceContract(contract); + type.getReferences().put("foo", ref); + processor.visitEnd(null, Foo1.class, type, null); + assertNotNull(type.getConstructorDefinition().getConstructor()); + assertEquals("foo", type.getConstructorDefinition().getInjectionNames().get(0)); + } + + /** + * Verifies a single constructor is chosen with a property and a reference as the type + */ + public void testSingleConstructorWithPropRef() throws Exception { + PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>> type = + new PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>>(); + + JavaMappedProperty<String> prop = new JavaMappedProperty<String>(); + prop.setName("foo"); + prop.setJavaType(String.class); + type.getProperties().put("foo", prop); + + JavaMappedReference ref = new JavaMappedReference(); + ref.setName("ref"); + ServiceContract contract = new JavaServiceContract(Foo1.class); + ref.setServiceContract(contract); + type.getReferences().put("ref", ref); + processor.visitEnd(null, Foo2.class, type, null); + assertNotNull(type.getConstructorDefinition().getConstructor()); + assertEquals(2, type.getConstructorDefinition().getInjectionNames().size()); + } + + + public void testSingleConstructorResolvableParam() throws Exception { + PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>> type = + new PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>>(); + processor.visitEnd(null, Foo5.class, type, null); + assertEquals(String.class, type.getProperties().get("string").getJavaType()); + } + + public void testSingleConstructorResolvableRef() throws Exception { + PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>> type = + new PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>>(); + processor.visitEnd(null, Foo6.class, type, null); + assertEquals(Ref.class, + type.getReferences().get("heuristicconstructortestcase$ref").getServiceContract().getInterfaceClass()); + } + + public void testSingleConstructorAmbiguousRef() throws Exception { + PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>> type = + new PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>>(); + JavaMappedReference ref = new JavaMappedReference(); + ref.setName("ref"); + ServiceContract contract = new JavaServiceContract(Foo1.class); + ref.setServiceContract(contract); + type.getReferences().put("ref", ref); + JavaMappedReference ref2 = new JavaMappedReference(); + ref2.setName("ref2"); + ref2.setServiceContract(contract); + type.getReferences().put("ref2", ref2); + try { + processor.visitEnd(null, Foo4.class, type, null); + fail(); + } catch (AmbiguousConstructorException e) { + // expected + } + } + + public void testConstructorPropertyAnnotatedParamsOnly() throws Exception { + PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>> type = + new PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>>(); + processor.visitEnd(null, Foo7.class, type, null); + assertNotNull(type.getProperties().get("myProp")); + } + + public void testConstructorReferenceAnnotatedParamsOnly() throws Exception { + PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>> type = + new PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>>(); + processor.visitEnd(null, Foo8.class, type, null); + assertNotNull(type.getReferences().get("myRef")); + } + + public void testConstructorAutowireAnnotatedParamsOnly() throws Exception { + PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>> type = + new PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>>(); + processor.visitEnd(null, Foo9.class, type, null); + assertNotNull(type.getReferences().get("myAutowire")); + } + + @SuppressWarnings("unchecked") + public void testDefaultConstructor() throws Exception { + PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>> type = + new PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>>(); + processor.visitEnd(null, Foo3.class, type, null); + assertNotNull(type.getConstructorDefinition().getConstructor()); + } + + public void testSameTypesButAnnotated() throws Exception { + PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>> type = + new PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>>(); + processor.visitEnd(null, Foo12.class, type, null); + assertEquals(2, type.getProperties().size()); + assertNotNull(type.getProperties().get("prop1")); + assertNotNull(type.getProperties().get("prop2")); + } + + /** + * Verifies processing executes with additional extension annotations + */ + public void testRandomAnnotation() throws Exception { + PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>> type = + new PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>>(); + processor.visitEnd(null, Foo11.class, type, null); + assertEquals(1, type.getProperties().size()); + assertNotNull(type.getProperties().get("prop1")); + } + + public void testAutowire() throws Exception { + PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>> type = + new PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>>(); + processor.visitEnd(null, Foo13.class, type, null); + assertEquals(1, type.getReferences().size()); + assertNotNull(type.getReferences().get(String.class.getName() + "0")); + } + + public void testMultipleAutowire() throws Exception { + PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>> type = + new PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>>(); + processor.visitEnd(null, Foo15.class, type, null); + assertEquals(2, type.getReferences().size()); + assertNotNull(type.getReferences().get(String.class.getName() + "0")); + assertNotNull(type.getReferences().get(String.class.getName() + "1")); + } + + public void testNoAutowireNameInConstructor() throws Exception { + PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>> type = + new PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>>(); + processor.visitEnd(null, Foo16.class, type, null); + assertEquals(2, type.getReferences().size()); + assertNotNull(type.getReferences().get(String.class.getName() + "0")); + assertNotNull(type.getReferences().get("bar")); + assertNotNull(type.getProperties().get("foo")); + } + + public void testPrivateConstructor() throws Exception { + PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>> type = + new PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>>(); + try { + processor.visitEnd(null, Foo14.class, type, null); + fail(); + } catch (NoConstructorException e) { + // expected + } + } + + + public void testMultipleConstructors() throws Exception { + // throw new UnsupportedOperationException("Finish heuristic multiple constructors - Foo10"); + } + + + public static class Foo1 { + public Foo1(String val) { + } + } + + public static class Foo2 { + public Foo2(String val, Foo1 ref) { + } + } + + public static class Foo3 { + } + + public static class Foo4 { + public Foo4(Foo1 ref) { + } + } + + public static class Prop { + + } + + @Remotable + public static interface Ref { + + } + + public static class Foo5 { + public Foo5(String val) { + } + } + + public static class Foo6 { + public Foo6(Ref ref) { + } + } + + public static class Foo7 { + public Foo7(@Property(name = "myProp") String prop) { + } + } + + + public static class Foo8 { + public Foo8(@Reference(name = "myRef") String ref) { + } + } + + public static class Foo9 { + public Foo9(@Autowire(name = "myAutowire") String autowire) { + } + } + + public static class Foo10 { + + public Foo10() { + } + + public Foo10(String prop) { + } + + public Foo10(@Property(name = "prop1") String prop1, @Property(name = "prop2") String prop2) { + + } + } + + public static class Foo11 { + + public Foo11(@Property(name = "prop1") String prop, @Baz String baz) { + } + } + + public static class Foo12 { + + public Foo12(@Property(name = "prop1") String prop, @Property(name = "prop2") String baz) { + } + } + + public @interface Baz { + + } + + public static class Foo13 { + public Foo13(@Autowire String foo) { + } + } + + public static final class Foo14 { + private Foo14() { + } + } + + public static final class Foo15 { + public Foo15(@Autowire String param1, @Autowire String param2) { + } + } + + public static final class Foo16 { + public Foo16(@Autowire String param1, + @Property(name = "foo") String param2, + @Reference(name = "bar") String param3) { + } + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/processor/HeuristicPojoProcessorTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/processor/HeuristicPojoProcessorTestCase.java new file mode 100644 index 0000000000..659cbbd115 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/processor/HeuristicPojoProcessorTestCase.java @@ -0,0 +1,367 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.implementation.processor; + +import java.lang.reflect.Constructor; +import java.util.Collection; +import java.util.List; + +import org.osoa.sca.annotations.Property; +import org.osoa.sca.annotations.Reference; +import org.osoa.sca.annotations.Remotable; +import org.osoa.sca.annotations.Service; + +import org.apache.tuscany.spi.implementation.java.ConstructorDefinition; +import org.apache.tuscany.spi.implementation.java.JavaMappedProperty; +import org.apache.tuscany.spi.implementation.java.JavaMappedReference; +import org.apache.tuscany.spi.implementation.java.JavaMappedService; +import org.apache.tuscany.spi.implementation.java.PojoComponentType; +import org.apache.tuscany.spi.implementation.java.ProcessingException; + +import junit.framework.TestCase; +import org.apache.tuscany.core.idl.java.JavaInterfaceProcessorRegistryImpl; + +/** + * Verfies component type information is properly introspected from an unadorned POJO according to the SCA Java Client + * and Implementation Model Specification + * + * @version $Rev$ $Date$ + */ +public class HeuristicPojoProcessorTestCase extends TestCase { + + private HeuristicPojoProcessor processor = + new HeuristicPojoProcessor(new ImplementationProcessorServiceImpl(new JavaInterfaceProcessorRegistryImpl())); + + /** + * Verifies a single service interface is computed when only one interface is implemented + */ + public void testSingleInterface() throws Exception { + PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>> type = + new PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>>(); + Constructor<SingleInterfaceImpl> ctor = SingleInterfaceImpl.class.getConstructor(); + type.setConstructorDefinition(new ConstructorDefinition<SingleInterfaceImpl>(ctor)); + processor.visitEnd(null, SingleInterfaceImpl.class, type, null); + assertEquals(1, type.getServices().size()); + assertEquals(PropertyInterface.class, + type.getServices().get("HeuristicPojoProcessorTestCase$PropertyInterface") + .getServiceContract().getInterfaceClass()); + assertTrue(type.getProperties().isEmpty()); + assertTrue(type.getReferences().isEmpty()); + } + + /** + * Verifies property and reference setters are computed + */ + public void testPropertyReference() throws Exception { + PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>> type = + new PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>>(); + Constructor<SingleInterfaceWithPropertyReferenceImpl> ctor = + SingleInterfaceWithPropertyReferenceImpl.class.getConstructor(); + type.setConstructorDefinition(new ConstructorDefinition<SingleInterfaceWithPropertyReferenceImpl>(ctor)); + processor.visitEnd(null, SingleInterfaceWithPropertyReferenceImpl.class, type, null); + assertEquals(1, type.getServices().size()); + assertEquals(Interface1.class, + type.getServices().get("HeuristicPojoProcessorTestCase$Interface1") + .getServiceContract().getInterfaceClass()); + assertEquals(1, type.getProperties().size()); + assertEquals(ComplexProperty.class, type.getProperties().get("property").getJavaType()); + assertEquals(1, type.getReferences().size()); + assertEquals(Ref.class, type.getReferences().get("reference").getServiceContract().getInterfaceClass()); + } + + /** + * Verifies that a property setter is not introspected if an analogous operation is in the service interface + */ + public void testPropertySetterInInterface() throws Exception { + PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>> type = + new PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>>(); + Constructor<SingleInterfaceImpl> ctor = SingleInterfaceImpl.class.getConstructor(); + type.setConstructorDefinition(new ConstructorDefinition<SingleInterfaceImpl>(ctor)); + processor.visitEnd(null, SingleInterfaceImpl.class, type, null); + assertEquals(0, type.getProperties().size()); + } + + /** + * Verifies that a reference setter is not introspected if an analogous operation is in the service interface + */ + public void testReferenceSetterInInterface() throws Exception { + PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>> type = + new PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>>(); + Constructor<RefInterfaceImpl> ctor = RefInterfaceImpl.class.getConstructor(); + type.setConstructorDefinition(new ConstructorDefinition<RefInterfaceImpl>(ctor)); + processor.visitEnd(null, RefInterfaceImpl.class, type, null); + assertEquals(0, type.getReferences().size()); + } + + /** + * Verifies collection generic types or array types are introspected as references according to spec rules + */ + public void testReferenceCollectionType() throws Exception { + PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>> type = + new PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>>(); + Constructor<ReferenceCollectionImpl> ctor = ReferenceCollectionImpl.class.getConstructor(); + type.setConstructorDefinition(new ConstructorDefinition<ReferenceCollectionImpl>(ctor)); + processor.visitEnd(null, ReferenceCollectionImpl.class, type, null); + assertEquals(0, type.getProperties().size()); + assertEquals(4, type.getReferences().size()); + } + + /** + * Verifies collection generic types or array types are introspected as properties according to spec rules + */ + public void testPropertyCollectionType() throws Exception { + PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>> type = + new PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>>(); + Constructor<PropertyCollectionImpl> ctor = PropertyCollectionImpl.class.getConstructor(); + type.setConstructorDefinition(new ConstructorDefinition<PropertyCollectionImpl>(ctor)); + processor.visitEnd(null, PropertyCollectionImpl.class, type, null); + assertEquals(0, type.getReferences().size()); + assertEquals(4, type.getProperties().size()); + } + + /** + * Verifies references are calculated when the type marked with is @Remotable + */ + public void testRemotableRef() throws Exception { + PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>> type = + new PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>>(); + Constructor<RemotableRefImpl> ctor = RemotableRefImpl.class.getConstructor(); + type.setConstructorDefinition(new ConstructorDefinition<RemotableRefImpl>(ctor)); + processor.visitEnd(null, RemotableRefImpl.class, type, null); + assertEquals(2, type.getReferences().size()); + assertEquals(0, type.getProperties().size()); + } + + public void testParentInterface() throws ProcessingException, NoSuchMethodException { + PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>> type = + new PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>>(); + Constructor<Child> ctor = Child.class.getConstructor(); + type.setConstructorDefinition(new ConstructorDefinition<Child>(ctor)); + processor.visitEnd(null, Child.class, type, null); + assertTrue(type.getServices().containsKey("HeuristicPojoProcessorTestCase$Interface1")); + } + + /** + * Verifies a service inteface is calculated when only props and refs are given + */ + public void testExcludedPropertyAndReference() throws Exception { + PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>> type = + new PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>>(); + JavaMappedReference ref = new JavaMappedReference(); + ref.setName("reference"); + type.add(ref); + JavaMappedReference ref2 = new JavaMappedReference(); + ref2.setName("reference2"); + type.add(ref2); + JavaMappedProperty<?> prop1 = new JavaMappedProperty(); + prop1.setName("string1"); + type.add(prop1); + JavaMappedProperty<?> prop2 = new JavaMappedProperty(); + prop2.setName("string2"); + type.add(prop2); + processor.visitEnd(null, ServiceImpl.class, type, null); + assertEquals(1, type.getServices().size()); + } + + public void testProtectedRemotableRefField() throws ProcessingException, NoSuchMethodException { + PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>> type = + new PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>>(); + Constructor<ProtectedRemotableRefFieldImpl> ctor = ProtectedRemotableRefFieldImpl.class.getConstructor(); + type.setConstructorDefinition(new ConstructorDefinition<ProtectedRemotableRefFieldImpl>(ctor)); + processor.visitEnd(null, ProtectedRemotableRefFieldImpl.class, type, null); + assertNotNull(type.getReferences().get("otherRef")); + } + + public void testProtectedRemotableRefMethod() throws ProcessingException, NoSuchMethodException { + PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>> type = + new PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>>(); + Constructor<ProtectedRemotableRefMethodImpl> ctor = ProtectedRemotableRefMethodImpl.class.getConstructor(); + type.setConstructorDefinition(new ConstructorDefinition<ProtectedRemotableRefMethodImpl>(ctor)); + processor.visitEnd(null, ProtectedRemotableRefMethodImpl.class, type, null); + assertNotNull(type.getReferences().get("otherRef")); + } + + private interface PropertyInterface { + void setString1(String val); + } + + private interface Interface1 { + } + + private static class Parent implements Interface1 { + + } + + private static class Child extends Parent { + public Child() { + } + + } + + private static class SingleInterfaceImpl implements PropertyInterface { + public SingleInterfaceImpl() { + } + + public void setString1(String val) { + } + + } + + private interface HeuristicServiceInterface { + void fooOperation(String ref); + void setInvalid1(); // No parameter + void setInvalid2(String str, int i); // More than one parameter + String setInvalid3(String str); // return should be void + } + + public static class ServiceImpl implements PropertyInterface, RefInterface, HeuristicServiceInterface { + + @Property + public void setString1(String val) { + } + + @Property + public void setString2(String val) { + } + + @Reference + public void setReference(Ref ref) { + } + + @Reference + public void setReference2(Ref ref) { + } + + public void fooOperation(String ref) { + + } + public void setInvalid1() { + } + + public void setInvalid2(String str, int i) { + } + + public String setInvalid3(String str) { + return null; + } + + } + + @Service + private interface Ref { + } + + private class ComplexProperty { + } + + private interface RefInterface { + void setReference(Ref ref); + } + + private static class RefInterfaceImpl implements RefInterface { + public RefInterfaceImpl() { + } + + public void setReference(Ref ref) { + } + } + + private static class SingleInterfaceWithPropertyReferenceImpl implements Interface1 { + public SingleInterfaceWithPropertyReferenceImpl() { + } + + public void setReference(Ref ref) { + } + + public void setProperty(ComplexProperty prop) { + } + } + + private static class ReferenceCollectionImpl implements Interface1 { + public ReferenceCollectionImpl() { + } + + public void setCollectionReference(Collection<Ref> ref) { + } + + public void setNonGenericCollectionReference(Collection ref) { + } + + public void setListReference(List<Ref> ref) { + } + + public void setArrayReference(Ref[] ref) { + } + } + + private static class PropertyCollectionImpl implements Interface1 { + public PropertyCollectionImpl() { + } + + public void setCollectionProperty(Collection<ComplexProperty> prop) { + } + + public void setCollectionProperty2(Collection<String> prop) { + } + + public void setArrayProperty(ComplexProperty[] prop) { + } + + public void setArrayProperty2(String[] prop) { + } + } + + @Remotable + private interface RemotableRef { + } + + private static class RemotableRefImpl implements Interface1 { + protected RemotableRef otherRef; + + public RemotableRefImpl() { + } + + public void setRef(RemotableRef ref) { + + } + } + + private static class ProtectedRemotableRefFieldImpl implements Interface1 { + protected RemotableRef otherRef; + + public ProtectedRemotableRefFieldImpl() { + } + + public ProtectedRemotableRefFieldImpl(RemotableRef otherRef) { + this.otherRef = otherRef; + } + + } + + private static class ProtectedRemotableRefMethodImpl implements Interface1 { + public ProtectedRemotableRefMethodImpl() { + } + + protected void setOtherRef(RemotableRef otherRef) { + } + + } + + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/processor/HeutisticExtensibleConstructorTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/processor/HeutisticExtensibleConstructorTestCase.java new file mode 100644 index 0000000000..4e6c1063d8 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/processor/HeutisticExtensibleConstructorTestCase.java @@ -0,0 +1,129 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.implementation.processor; + +import java.lang.reflect.Constructor; +import java.util.List; + +import org.apache.tuscany.spi.implementation.java.ConstructorDefinition; +import org.apache.tuscany.spi.implementation.java.JavaMappedProperty; +import org.apache.tuscany.spi.implementation.java.JavaMappedReference; +import org.apache.tuscany.spi.implementation.java.JavaMappedService; +import org.apache.tuscany.spi.implementation.java.PojoComponentType; + +import junit.framework.TestCase; +import org.apache.tuscany.core.idl.java.JavaInterfaceProcessorRegistryImpl; + +/** + * Verifies constructors that have extensible annotation types, i.e. that have parameters marked by annotations which + * are themselves processed by some other implementation processor + * + * @version $Rev$ $Date$ + */ +public class HeutisticExtensibleConstructorTestCase extends TestCase { + + private HeuristicPojoProcessor processor = + new HeuristicPojoProcessor(new ImplementationProcessorServiceImpl(new JavaInterfaceProcessorRegistryImpl())); + + /** + * Verifies heuristic processing can be called priot to an extension annotation processors being called. + */ + public void testBarAnnotationProcessedFirst() throws Exception { + PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>> type = + new PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>>(); + Constructor<Foo> ctor = Foo.class.getConstructor(String.class, String.class); + ConstructorDefinition<Foo> definition = new ConstructorDefinition<Foo>(ctor); + type.setConstructorDefinition(definition); + JavaMappedProperty property = new JavaMappedProperty(); + property.setName("myBar"); + definition.getInjectionNames().add("myBar"); + type.getProperties().put("myBar", property); + processor.visitEnd(null, Foo.class, type, null); + assertEquals(2, type.getProperties().size()); + } + + /** + * Verifies heuristic processing can be called before an extension annotation processors is called. + * <p/> + * For example, given: + * <pre> Foo(@Bar String prop, @org.osoa.sca.annotations.Property(name = "foo") String prop2)</pre> + * <p/> + * Heuristic evaluation of @Property can occur prior to another implementation processor evaluating @Bar + * + * @throws Exception + */ + public void testBarAnnotationProcessedLast() throws Exception { + PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>> type = + new PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>>(); + processor.visitEnd(null, Foo.class, type, null); + + // now simulate process the bar impl + ConstructorDefinition<?> definition = type.getConstructorDefinition(); + List<String> injectionNames = definition.getInjectionNames(); + injectionNames.remove(0); + injectionNames.add(0, "mybar"); + type.getProperties().put("mybar", new JavaMappedProperty<String>()); + + assertEquals(2, type.getProperties().size()); + assertEquals("foo", definition.getInjectionNames().get(1)); + } + + /** + * Verifies heuristic processing can be called before an extension annotation processors is called with the + * extension parameter in a middle position. Specifically, verifies that the heuristic processor updates injection + * names and preserves their ordering. + */ + public void testBarAnnotationProcessedFirstInMiddle() throws Exception { + PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>> type = + new PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>>(); + Constructor<Foo2> ctor = Foo2.class.getConstructor(String.class, String.class, String.class); + ConstructorDefinition<Foo2> definition = new ConstructorDefinition<Foo2>(ctor); + type.setConstructorDefinition(definition); + // insert placeholder for first param, which would be done by a processor + definition.getInjectionNames().add(""); + JavaMappedProperty property = new JavaMappedProperty(); + property.setName("myBar"); + definition.getInjectionNames().add("myBar"); + type.getProperties().put("myBar", property); + processor.visitEnd(null, Foo2.class, type, null); + assertEquals("baz", definition.getInjectionNames().get(0)); + assertEquals(2, type.getProperties().size()); + assertEquals(1, type.getReferences().size()); + } + + public @interface Bar { + + } + + public static class Foo { + public Foo(@Bar String prop, @org.osoa.sca.annotations.Property(name = "foo") String prop2) { + } + } + + public static class Foo2 { + public Foo2(@org.osoa.sca.annotations.Reference(name = "baz") String prop1, + @Bar String prop2, + @org.osoa.sca.annotations.Property(name = "foo") String prop3) { + } + } + + +} + + diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/processor/ImplementationProcessorServiceTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/processor/ImplementationProcessorServiceTestCase.java new file mode 100644 index 0000000000..3fbe5a8350 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/processor/ImplementationProcessorServiceTestCase.java @@ -0,0 +1,73 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.implementation.processor; + +import org.osoa.sca.annotations.Callback; +import org.osoa.sca.annotations.Remotable; +import org.osoa.sca.annotations.Scope; + +import org.apache.tuscany.spi.implementation.java.JavaMappedService; +import org.apache.tuscany.spi.implementation.java.ImplementationProcessorService; +import org.apache.tuscany.spi.model.InteractionScope; +import org.apache.tuscany.spi.model.ServiceContract; + +import junit.framework.TestCase; +import org.apache.tuscany.core.idl.java.JavaInterfaceProcessorRegistryImpl; + +/** + * @version $Rev$ $Date$ + */ +public class ImplementationProcessorServiceTestCase extends TestCase { + + private ImplementationProcessorService implService = + new ImplementationProcessorServiceImpl(new JavaInterfaceProcessorRegistryImpl()); + + public void testCreateConversationalService() throws Exception { + JavaMappedService service = implService.createService(Foo.class); + assertTrue(Foo.class.equals(service.getServiceContract().getInterfaceClass())); + assertTrue(service.isRemotable()); + assertEquals(InteractionScope.CONVERSATIONAL, service.getServiceContract().getInteractionScope()); + ServiceContract serviceContract = service.getServiceContract(); + assertTrue(Bar.class.equals(serviceContract.getCallbackClass())); + assertTrue("ImplementationProcessorServiceTestCase$Bar".equals(serviceContract.getCallbackName())); + } + + public void testCreateDefaultService() throws Exception { + JavaMappedService service = implService.createService(Baz.class); + assertTrue(Baz.class.equals(service.getServiceContract().getInterfaceClass())); + assertTrue(!service.isRemotable()); + assertEquals(InteractionScope.NONCONVERSATIONAL, service.getServiceContract().getInteractionScope()); + } + + + @Callback(Bar.class) + @Remotable + @Scope("CONVERSATIONAL") + public interface Foo { + + } + + public interface Bar { + + } + + public interface Baz { + + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/processor/ImplementationProcessorServiceUniqueTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/processor/ImplementationProcessorServiceUniqueTestCase.java new file mode 100644 index 0000000000..da45ed2d46 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/processor/ImplementationProcessorServiceUniqueTestCase.java @@ -0,0 +1,67 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.implementation.processor; + +import org.apache.tuscany.spi.implementation.java.ImplementationProcessorService; + +import junit.framework.TestCase; +import org.apache.tuscany.core.idl.java.JavaInterfaceProcessorRegistryImpl; + +/** + * @version $Rev$ $Date$ + */ +public class ImplementationProcessorServiceUniqueTestCase extends TestCase { + + private ImplementationProcessorService service = + new ImplementationProcessorServiceImpl(new JavaInterfaceProcessorRegistryImpl()); + + public void testUniquess1() throws Exception { + Class[] classes = new Class[2]; + classes[0] = String.class; + classes[1] = Integer.class; + assertTrue(service.areUnique(classes)); + } + + public void testUniquess2() throws Exception { + Class[] classes = new Class[2]; + classes[0] = String.class; + classes[1] = String.class; + assertFalse(service.areUnique(classes)); + } + + public void testUniquess3() throws Exception { + Class[] classes = new Class[1]; + classes[0] = String.class; + assertTrue(service.areUnique(classes)); + } + + public void testUniquess4() throws Exception { + Class[] classes = new Class[3]; + classes[0] = String.class; + classes[1] = Integer.class; + classes[2] = String.class; + assertFalse(service.areUnique(classes)); + } + + public void testUniquess5() throws Exception { + Class[] classes = new Class[0]; + assertTrue(service.areUnique(classes)); + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/processor/InitProcessorTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/processor/InitProcessorTestCase.java new file mode 100644 index 0000000000..059094f922 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/processor/InitProcessorTestCase.java @@ -0,0 +1,98 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.implementation.processor; + +import java.lang.reflect.Method; + +import org.osoa.sca.annotations.Init; + +import org.apache.tuscany.spi.implementation.java.JavaMappedService; + +import junit.framework.TestCase; +import org.apache.tuscany.spi.implementation.java.JavaMappedProperty; +import org.apache.tuscany.spi.implementation.java.JavaMappedReference; +import org.apache.tuscany.spi.implementation.java.PojoComponentType; + +/** + * @version $Rev$ $Date$ + */ +public class InitProcessorTestCase extends TestCase { + + public void testInit() throws Exception { + InitProcessor processor = new InitProcessor(); + PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>> type = + new PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>>(); + Method method = InitProcessorTestCase.Foo.class.getMethod("init"); + processor.visitMethod(null, method, type, null); + assertNotNull(type.getInitMethod()); + assertEquals(50, type.getInitLevel()); + } + + public void testBadInit() throws Exception { + InitProcessor processor = new InitProcessor(); + PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>> type = + new PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>>(); + Method method = InitProcessorTestCase.Bar.class.getMethod("badInit", String.class); + try { + processor.visitMethod(null, method, type, null); + fail(); + } catch (IllegalInitException e) { + // expected + } + } + + public void testTwoInit() throws Exception { + InitProcessor processor = new InitProcessor(); + PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>> type = + new PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>>(); + Method method = InitProcessorTestCase.Bar.class.getMethod("init"); + Method method2 = InitProcessorTestCase.Bar.class.getMethod("init2"); + processor.visitMethod(null, method, type, null); + try { + processor.visitMethod(null, method2, type, null); + fail(); + } catch (DuplicateInitException e) { + // expected + } + } + + + private class Foo { + @Init(eager = true) + public void init() { + } + } + + + private class Bar { + @Init + public void init() { + } + + @Init + public void init2() { + } + + @Init + public void badInit(String foo) { + } + + + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/processor/MonitorProcessorTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/processor/MonitorProcessorTestCase.java new file mode 100644 index 0000000000..8982fa3991 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/processor/MonitorProcessorTestCase.java @@ -0,0 +1,180 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.implementation.processor; + +import java.lang.reflect.Constructor; +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.util.Map; + +import org.apache.tuscany.spi.implementation.java.ConstructorDefinition; +import org.apache.tuscany.spi.implementation.java.JavaMappedProperty; +import org.apache.tuscany.spi.implementation.java.JavaMappedReference; +import org.apache.tuscany.spi.implementation.java.JavaMappedService; +import org.apache.tuscany.spi.implementation.java.PojoComponentType; +import org.apache.tuscany.spi.implementation.java.IllegalPropertyException; + +import junit.framework.TestCase; +import org.apache.tuscany.api.annotation.Monitor; +import org.apache.tuscany.core.idl.java.JavaInterfaceProcessorRegistryImpl; +import org.apache.tuscany.core.injection.SingletonObjectFactory; +import org.apache.tuscany.host.MonitorFactory; +import org.easymock.EasyMock; + +/** + * @version $Rev$ $Date$ + */ +public class MonitorProcessorTestCase extends TestCase { + + private MonitorProcessor processor; + private MonitorFactory monitorFactory; + + public void testSetter() throws Exception { + PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>> type = + new PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>>(); + Method method = Foo.class.getMethod("setMonitor", Foo.class); + EasyMock.expect(monitorFactory.getMonitor(EasyMock.eq(Foo.class))).andReturn(null); + EasyMock.replay(monitorFactory); + processor.visitMethod(null, method, type, null); + Map<String, JavaMappedProperty<?>> properties = type.getProperties(); + assertTrue(properties.get("monitor").getDefaultValueFactory() instanceof SingletonObjectFactory); + EasyMock.verify(monitorFactory); + } + + + public void testBadSetter() throws Exception { + PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>> type = + new PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>>(); + Method method = BadMonitor.class.getMethod("setMonitor"); + try { + processor.visitMethod(null, method, type, null); + fail(); + } catch (IllegalPropertyException e) { + // expected + } + } + + public void testField() throws Exception { + PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>> type = + new PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>>(); + Field field = Foo.class.getDeclaredField("bar"); + EasyMock.expect(monitorFactory.getMonitor(EasyMock.eq(Foo.class))).andReturn(null); + EasyMock.replay(monitorFactory); + processor.visitField(null, field, type, null); + Map<String, JavaMappedProperty<?>> properties = type.getProperties(); + assertTrue(properties.get("bar").getDefaultValueFactory() instanceof SingletonObjectFactory); + EasyMock.verify(monitorFactory); + } + + public void testConstructor() throws Exception { + PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>> type = + new PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>>(); + Constructor<Bar> ctor = Bar.class.getConstructor(BazMonitor.class); + EasyMock.expect(monitorFactory.getMonitor(EasyMock.eq(BazMonitor.class))).andReturn(null); + EasyMock.replay(monitorFactory); + processor.visitConstructor(null, ctor, type, null); + Map<String, JavaMappedProperty<?>> properties = type.getProperties(); + assertTrue( + properties.get(BazMonitor.class.getName()).getDefaultValueFactory() instanceof SingletonObjectFactory); + EasyMock.verify(monitorFactory); + } + + /** + * Verifies calling the monitor processor to evaluate a constructor can be done after a property parameter is + * processed + */ + public void testConstructorAfterProperty() throws Exception { + PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>> type = + new PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>>(); + Constructor<Bar> ctor = Bar.class.getConstructor(String.class, BazMonitor.class); + EasyMock.expect(monitorFactory.getMonitor(EasyMock.eq(BazMonitor.class))).andReturn(null); + EasyMock.replay(monitorFactory); + ConstructorDefinition<Bar> definition = new ConstructorDefinition<Bar>(ctor); + JavaMappedProperty prop = new JavaMappedProperty(); + definition.getInjectionNames().add("prop"); + type.setConstructorDefinition(definition); + type.getProperties().put("prop", prop); + processor.visitConstructor(null, ctor, type, null); + Map<String, JavaMappedProperty<?>> properties = type.getProperties(); + assertEquals(BazMonitor.class.getName(), definition.getInjectionNames().get(1)); + assertEquals(2, type.getProperties().size()); + String name = BazMonitor.class.getName(); + assertTrue(properties.get(name).getDefaultValueFactory() instanceof SingletonObjectFactory); + EasyMock.verify(monitorFactory); + } + + /** + * Verifies calling the monitor processor to evaluate a constructor can be done before a property parameter is + * processed + */ + public void testConstructorBeforeProperty() throws Exception { + PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>> type = + new PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>>(); + Constructor<Bar> ctor = Bar.class.getConstructor(String.class, BazMonitor.class); + EasyMock.expect(monitorFactory.getMonitor(EasyMock.eq(BazMonitor.class))).andReturn(null); + EasyMock.replay(monitorFactory); + processor.visitConstructor(null, ctor, type, null); + Map<String, JavaMappedProperty<?>> properties = type.getProperties(); + ConstructorDefinition definition = type.getConstructorDefinition(); + assertEquals(2, definition.getInjectionNames().size()); + assertEquals(BazMonitor.class.getName(), definition.getInjectionNames().get(1)); + String name = BazMonitor.class.getName(); + assertTrue(properties.get(name).getDefaultValueFactory() instanceof SingletonObjectFactory); + EasyMock.verify(monitorFactory); + } + + protected void setUp() throws Exception { + super.setUp(); + monitorFactory = EasyMock.createMock(MonitorFactory.class); + JavaInterfaceProcessorRegistryImpl registry = new JavaInterfaceProcessorRegistryImpl(); + ImplementationProcessorServiceImpl processor = new ImplementationProcessorServiceImpl(registry); + this.processor = new MonitorProcessor(monitorFactory, processor); + } + + private class Foo { + + @Monitor + protected Foo bar; + + @Monitor + public void setMonitor(Foo foo) { + } + } + + + private class BadMonitor { + + @Monitor + public void setMonitor() { + } + } + + private interface BazMonitor { + + } + + private static class Bar { + + public Bar(@Monitor BazMonitor monitor) { + } + + public Bar(String prop, @Monitor BazMonitor monitor) { + } + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/processor/PropertyProcessorTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/processor/PropertyProcessorTestCase.java new file mode 100644 index 0000000000..412c9f9d36 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/processor/PropertyProcessorTestCase.java @@ -0,0 +1,156 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.implementation.processor; + +import static org.apache.tuscany.spi.model.OverrideOptions.MUST; +import junit.framework.TestCase; + +import org.apache.tuscany.core.idl.java.JavaInterfaceProcessorRegistryImpl; +import org.apache.tuscany.spi.implementation.java.DuplicatePropertyException; +import org.apache.tuscany.spi.implementation.java.IllegalPropertyException; +import org.apache.tuscany.spi.implementation.java.JavaMappedProperty; +import org.apache.tuscany.spi.implementation.java.JavaMappedReference; +import org.apache.tuscany.spi.implementation.java.JavaMappedService; +import org.apache.tuscany.spi.implementation.java.PojoComponentType; +import org.apache.tuscany.spi.model.OverrideOptions; +import org.osoa.sca.annotations.Property; + +/** + * @version $Rev$ $Date$ + */ +public class PropertyProcessorTestCase extends TestCase { + + PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>> type; + PropertyProcessor processor; + + public void testMethodAnnotation() throws Exception { + processor.visitMethod(null, Foo.class.getMethod("setFoo", String.class), type, null); + assertNotNull(type.getProperties().get("foo")); + } + + public void testMethodRequired() throws Exception { + processor.visitMethod(null, Foo.class.getMethod("setFooRequired", String.class), type, null); + JavaMappedProperty prop = type.getProperties().get("fooRequired"); + assertNotNull(prop); + assertEquals(prop.getOverride(), MUST); + } + + public void testMethodName() throws Exception { + processor.visitMethod(null, Foo.class.getMethod("setBarMethod", String.class), type, null); + assertNotNull(type.getProperties().get("bar")); + } + + public void testFieldAnnotation() throws Exception { + processor.visitField(null, Foo.class.getDeclaredField("baz"), type, null); + assertNotNull(type.getProperties().get("baz")); + } + + public void testFieldRequired() throws Exception { + processor.visitField(null, Foo.class.getDeclaredField("bazRequired"), type, null); + JavaMappedProperty prop = type.getProperties().get("bazRequired"); + assertNotNull(prop); + assertEquals(prop.getOverride(), OverrideOptions.MUST); + } + + public void testFieldName() throws Exception { + processor.visitField(null, Foo.class.getDeclaredField("bazField"), type, null); + assertNotNull(type.getProperties().get("theBaz")); + } + + public void testDuplicateFields() throws Exception { + processor.visitField(null, Bar.class.getDeclaredField("dup"), type, null); + try { + processor.visitField(null, Bar.class.getDeclaredField("baz"), type, null); + fail(); + } catch (DuplicatePropertyException e) { + // expected + } + } + + public void testDuplicateMethods() throws Exception { + processor.visitMethod(null, Bar.class.getMethod("dupMethod", String.class), type, null); + try { + processor.visitMethod(null, Bar.class.getMethod("dupSomeMethod", String.class), type, null); + fail(); + } catch (DuplicatePropertyException e) { + // expected + } + } + + public void testInvalidProperty() throws Exception { + try { + processor.visitMethod(null, Bar.class.getMethod("badMethod"), type, null); + fail(); + } catch (IllegalPropertyException e) { + // expected + } + } + + protected void setUp() throws Exception { + super.setUp(); + type = new PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>>(); + JavaInterfaceProcessorRegistryImpl registry = new JavaInterfaceProcessorRegistryImpl(); + processor = new PropertyProcessor(new ImplementationProcessorServiceImpl(registry)); + } + + private class Foo { + + @Property + protected String baz; + @Property(override = "must") + protected String bazRequired; + @Property(name = "theBaz") + protected String bazField; + + @Property + public void setFoo(String string) { + } + + @Property(override = "must") + public void setFooRequired(String string) { + } + + @Property(name = "bar") + public void setBarMethod(String string) { + } + + } + + private class Bar { + + @Property + protected String dup; + + @Property(name = "dup") + protected String baz; + + @Property + public void dupMethod(String s) { + } + + @Property(name = "dupMethod") + public void dupSomeMethod(String s) { + } + + @Property + public void badMethod() { + } + + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/processor/ReferenceProcessorTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/processor/ReferenceProcessorTestCase.java new file mode 100644 index 0000000000..e60cf58fb5 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/processor/ReferenceProcessorTestCase.java @@ -0,0 +1,173 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.implementation.processor; + +import org.osoa.sca.annotations.Reference; + +import org.apache.tuscany.spi.implementation.java.JavaMappedProperty; +import org.apache.tuscany.spi.implementation.java.JavaMappedReference; +import org.apache.tuscany.spi.implementation.java.JavaMappedService; +import org.apache.tuscany.spi.implementation.java.PojoComponentType; +import org.apache.tuscany.spi.model.ServiceContract; + +import junit.framework.TestCase; +import org.apache.tuscany.core.idl.java.JavaInterfaceProcessorRegistryImpl; + +/** + * @version $Rev$ $Date$ + */ +public class ReferenceProcessorTestCase extends TestCase { + + PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>> type = + new PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>>(); + ReferenceProcessor processor = + new ReferenceProcessor(new JavaInterfaceProcessorRegistryImpl()); + + public void testMethodAnnotation() throws Exception { + processor.visitMethod(null, ReferenceProcessorTestCase.Foo.class.getMethod("setFoo", Ref.class), type, null); + JavaMappedReference reference = type.getReferences().get("foo"); + assertNotNull(reference); + ServiceContract contract = reference.getServiceContract(); + assertEquals(Ref.class, contract.getInterfaceClass()); + assertEquals("ReferenceProcessorTestCase$Ref", contract.getInterfaceName()); + } + + public void testMethodRequired() throws Exception { + processor + .visitMethod(null, ReferenceProcessorTestCase.Foo.class.getMethod("setFooRequired", Ref.class), type, null); + JavaMappedReference prop = type.getReferences().get("fooRequired"); + assertNotNull(prop); + assertTrue(prop.isRequired()); + } + + public void testMethodName() throws Exception { + processor + .visitMethod(null, ReferenceProcessorTestCase.Foo.class.getMethod("setBarMethod", Ref.class), type, null); + assertNotNull(type.getReferences().get("bar")); + } + + public void testFieldAnnotation() throws Exception { + processor.visitField(null, ReferenceProcessorTestCase.Foo.class.getDeclaredField("baz"), type, null); + JavaMappedReference reference = type.getReferences().get("baz"); + assertNotNull(reference); + ServiceContract contract = reference.getServiceContract(); + assertEquals(Ref.class, contract.getInterfaceClass()); + assertEquals("ReferenceProcessorTestCase$Ref", contract.getInterfaceName()); + } + + public void testFieldRequired() throws Exception { + processor.visitField(null, ReferenceProcessorTestCase.Foo.class.getDeclaredField("bazRequired"), type, null); + JavaMappedReference prop = type.getReferences().get("bazRequired"); + assertNotNull(prop); + assertTrue(prop.isRequired()); + } + + public void testFieldName() throws Exception { + processor.visitField(null, ReferenceProcessorTestCase.Foo.class.getDeclaredField("bazField"), type, null); + assertNotNull(type.getReferences().get("theBaz")); + } + + public void testDuplicateFields() throws Exception { + processor.visitField(null, ReferenceProcessorTestCase.Bar.class.getDeclaredField("dup"), type, null); + try { + processor.visitField(null, ReferenceProcessorTestCase.Bar.class.getDeclaredField("baz"), type, null); + fail(); + } catch (DuplicateReferenceException e) { + //expected + } + } + + public void testDuplicateMethods() throws Exception { + processor.visitMethod(null, ReferenceProcessorTestCase.Bar.class.getMethod("dupMethod", Ref.class), type, null); + try { + processor + .visitMethod(null, ReferenceProcessorTestCase.Bar.class.getMethod("dupSomeMethod", Ref.class), type, + null); + fail(); + } catch (DuplicateReferenceException e) { + //expected + } + } + + public void testInvalidProperty() throws Exception { + try { + processor.visitMethod(null, ReferenceProcessorTestCase.Bar.class.getMethod("badMethod"), type, null); + fail(); + } catch (IllegalReferenceException e) { + //expected + } + } + + protected void setUp() throws Exception { + super.setUp(); + type = new PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>>(); + processor = new ReferenceProcessor(new JavaInterfaceProcessorRegistryImpl()); + } + + private interface Ref { + } + + private class Foo { + + @Reference + protected Ref baz; + @Reference(required = true) + protected Ref bazRequired; + @Reference(name = "theBaz") + protected Ref bazField; + + + @Reference + public void setFoo(Ref ref) { + } + + @Reference(required = true) + public void setFooRequired(Ref ref) { + } + + @Reference(name = "bar") + public void setBarMethod(Ref ref) { + } + + } + + + private class Bar { + + @Reference + protected Ref dup; + + @Reference(name = "dup") + protected Ref baz; + + @Reference + public void dupMethod(Ref s) { + } + + @Reference(name = "dupMethod") + public void dupSomeMethod(Ref s) { + } + + @Reference + public void badMethod() { + } + + + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/processor/ScopeProcessorTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/processor/ScopeProcessorTestCase.java new file mode 100644 index 0000000000..09152c9009 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/processor/ScopeProcessorTestCase.java @@ -0,0 +1,116 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.implementation.processor; + +import org.apache.tuscany.spi.component.CompositeComponent; +import org.apache.tuscany.spi.implementation.java.JavaMappedProperty; +import org.apache.tuscany.spi.implementation.java.JavaMappedReference; +import org.apache.tuscany.spi.implementation.java.JavaMappedService; +import org.apache.tuscany.spi.implementation.java.PojoComponentType; +import org.apache.tuscany.spi.implementation.java.ProcessingException; +import org.apache.tuscany.spi.model.Scope; + +import junit.framework.TestCase; +import org.easymock.EasyMock; + +/** + * @version $Rev$ $Date$ + */ +public class ScopeProcessorTestCase extends TestCase { + + CompositeComponent parent; + + public void testModuleScope() throws ProcessingException { + ScopeProcessor processor = new ScopeProcessor(); + PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>> type = + new PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>>(); + + processor.visitClass(parent, Module.class, type, null); + assertEquals(Scope.MODULE, type.getImplementationScope()); + } + + public void testSessionScope() throws ProcessingException { + ScopeProcessor processor = new ScopeProcessor(); + PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>> type = + new PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>>(); + processor.visitClass(parent, Session.class, type, null); + assertEquals(Scope.SESSION, type.getImplementationScope()); + } + + public void testRequestScope() throws ProcessingException { + ScopeProcessor processor = new ScopeProcessor(); + PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>> type = + new PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>>(); + processor.visitClass(parent, Request.class, type, null); + assertEquals(Scope.REQUEST, type.getImplementationScope()); + } + + public void testCompositeScope() throws ProcessingException { + ScopeProcessor processor = new ScopeProcessor(); + PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>> type = + new PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>>(); + processor.visitClass(parent, Composite.class, type, null); + assertEquals(Scope.COMPOSITE, type.getImplementationScope()); + } + + public void testStatelessScope() throws ProcessingException { + ScopeProcessor processor = new ScopeProcessor(); + PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>> type = + new PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>>(); + processor.visitClass(parent, Stateless.class, type, null); + assertEquals(Scope.STATELESS, type.getImplementationScope()); + } + + public void testNoScope() throws ProcessingException { + ScopeProcessor processor = new ScopeProcessor(); + PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>> type = + new PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>>(); + processor.visitClass(parent, None.class, type, null); + assertEquals(Scope.STATELESS, type.getImplementationScope()); + } + + protected void setUp() throws Exception { + super.setUp(); + parent = EasyMock.createNiceMock(CompositeComponent.class); + } + + @org.osoa.sca.annotations.Scope("MODULE") + private class Module { + } + + @org.osoa.sca.annotations.Scope("SESSION") + private class Session { + } + + @org.osoa.sca.annotations.Scope("REQUEST") + private class Request { + } + + @org.osoa.sca.annotations.Scope("COMPOSITE") + private class Composite { + } + + @org.osoa.sca.annotations.Scope("STATELESS") + private class Stateless { + } + + private class None { + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/processor/ServiceCallbackTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/processor/ServiceCallbackTestCase.java new file mode 100644 index 0000000000..e5b5698e23 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/processor/ServiceCallbackTestCase.java @@ -0,0 +1,166 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.implementation.processor; + +import java.lang.reflect.Field; +import java.lang.reflect.Method; + +import org.osoa.sca.annotations.Callback; +import org.osoa.sca.annotations.Service; + +import org.apache.tuscany.spi.implementation.java.JavaMappedProperty; +import org.apache.tuscany.spi.implementation.java.JavaMappedReference; +import org.apache.tuscany.spi.implementation.java.JavaMappedService; +import org.apache.tuscany.spi.implementation.java.PojoComponentType; +import org.apache.tuscany.spi.implementation.java.ProcessingException; + +import junit.framework.TestCase; +import org.apache.tuscany.core.idl.java.JavaInterfaceProcessorRegistryImpl; +import org.apache.tuscany.core.idl.java.IllegalCallbackException; + +/** + * @version $Rev$ $Date$ + */ +public class ServiceCallbackTestCase extends TestCase { + + ServiceProcessor processor = + new ServiceProcessor(new ImplementationProcessorServiceImpl(new JavaInterfaceProcessorRegistryImpl())); + + public void testMethodCallbackInterface() throws Exception { + PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>> type = + new PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>>(); + processor.visitClass(null, FooImpl.class, type, null); + JavaMappedService service = type.getServices().get("ServiceCallbackTestCase$Foo"); + assertNotNull(service); + Method method = FooImpl.class.getMethod("setCallback", FooCallback.class); + processor.visitMethod(null, method, type, null); + assertEquals(method, service.getCallbackMember()); + } + + public void testFieldCallbackInterface() throws Exception { + PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>> type = + new PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>>(); + processor.visitClass(null, FooImpl.class, type, null); + JavaMappedService service = type.getServices().get("ServiceCallbackTestCase$Foo"); + assertNotNull(service); + Field field = FooImpl.class.getDeclaredField("callback"); + processor.visitField(null, field, type, null); + assertEquals(field, service.getCallbackMember()); + } + + public void testMethodDoesNotMatchCallback() throws Exception { + PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>> type = + new PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>>(); + processor.visitClass(null, BadBarImpl.class, type, null); + Method method = BadBarImpl.class.getMethod("setWrongInterfaceCallback", String.class); + try { + processor.visitMethod(null, method, type, null); + fail(); + } catch (IllegalCallbackReferenceException e) { + // expected + } + } + + public void testNoParamCallback() throws Exception { + PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>> type = + new PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>>(); + processor.visitClass(null, BadBarImpl.class, type, null); + Method method = BadBarImpl.class.getMethod("setNoParamCallback"); + try { + processor.visitMethod(null, method, type, null); + fail(); + } catch (IllegalCallbackReferenceException e) { + // expected + } + } + + public void testFieldDoesNotMatchCallback() throws Exception { + PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>> type = + new PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>>(); + processor.visitClass(null, BadBarImpl.class, type, null); + Field field = BadBarImpl.class.getDeclaredField("wrongInterfaceCallback"); + try { + processor.visitField(null, field, type, null); + fail(); + } catch (IllegalCallbackReferenceException e) { + // expected + } + } + + public void testBadCallbackInterfaceAnnotation() throws Exception { + PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>> type = + new PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>>(); + try { + processor.visitClass(null, BadFooImpl.class, type, null); + fail(); + } catch (ProcessingException e) { + // expected + assertTrue(e.getCause() instanceof IllegalCallbackException); + } + } + + @Callback(FooCallback.class) + private interface Foo { + + } + + private interface FooCallback { + + } + + @Service(Foo.class) + private static class FooImpl implements Foo { + + @Callback + protected FooCallback callback; + + @Callback + public void setCallback(FooCallback cb) { + + } + } + + private static class BadBarImpl implements Foo { + @Callback + protected String wrongInterfaceCallback; + + @Callback + public void setWrongInterfaceCallback(String cb) { + + } + + @Callback + public void setNoParamCallback() { + + } + + } + + @Callback + private interface BadFoo { + + } + + @Service(BadFoo.class) + private static class BadFooImpl implements BadFoo { + + } + + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/processor/ServiceProcessorTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/processor/ServiceProcessorTestCase.java new file mode 100644 index 0000000000..f2a22fcb85 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/processor/ServiceProcessorTestCase.java @@ -0,0 +1,137 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.implementation.processor; + +import org.osoa.sca.annotations.Callback; +import org.osoa.sca.annotations.Remotable; +import org.osoa.sca.annotations.Service; + +import org.apache.tuscany.spi.implementation.java.JavaMappedProperty; +import org.apache.tuscany.spi.implementation.java.JavaMappedReference; +import org.apache.tuscany.spi.implementation.java.JavaMappedService; +import org.apache.tuscany.spi.implementation.java.PojoComponentType; +import org.apache.tuscany.spi.model.ServiceContract; + +import junit.framework.TestCase; +import org.apache.tuscany.core.idl.java.JavaInterfaceProcessorRegistryImpl; + +/** + * @version $Rev$ $Date$ + */ +public class ServiceProcessorTestCase extends TestCase { + + private ServiceProcessor processor; + private PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>> type; + + public void testMultipleInterfaces() throws Exception { + processor.visitClass(null, FooMultiple.class, type, null); + assertEquals(2, type.getServices().size()); + JavaMappedService service = type.getServices().get("ServiceProcessorTestCase$Baz"); + ServiceContract contract = service.getServiceContract(); + assertEquals(Baz.class, contract.getInterfaceClass()); + assertEquals(Bar.class, contract.getCallbackClass()); + assertEquals("ServiceProcessorTestCase$Bar", contract.getCallbackName()); + assertNotNull(type.getServices().get("ServiceProcessorTestCase$Bar")); + } + + public void testSingleInterfaces() throws Exception { + processor.visitClass(null, FooSingle.class, type, null); + assertEquals(1, type.getServices().size()); + assertNotNull(type.getServices().get("ServiceProcessorTestCase$Baz")); + } + + public void testMultipleNoService() throws Exception { + processor.visitClass(null, FooMultipleNoService.class, type, null); + assertEquals(0, type.getServices().size()); + } + + public void testRemotableNoService() throws Exception { + processor.visitClass(null, FooRemotableNoService.class, type, null); + assertEquals(1, type.getServices().size()); + JavaMappedService service = type.getServices().get("ServiceProcessorTestCase$BazRemotable"); + ServiceContract contract = service.getServiceContract(); + assertEquals(BazRemotable.class, contract.getInterfaceClass()); + } + + public void testNonInterface() throws Exception { + try { + processor.visitClass(null, BadImpl.class, type, null); + fail(); + } catch (InvalidServiceType e) { + //expected + } + } + + public void testNoInterfaces() throws Exception { + try { + processor.visitClass(null, BadDefinition.class, type, null); + fail(); + } catch (IllegalServiceDefinitionException e) { + //expected + } + } + + protected void setUp() throws Exception { + super.setUp(); + JavaInterfaceProcessorRegistryImpl registry = new JavaInterfaceProcessorRegistryImpl(); + processor = new ServiceProcessor(new ImplementationProcessorServiceImpl(registry)); + type = new PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>>(); + } + + @Callback(Bar.class) + private interface Baz { + } + + private interface Bar { + } + + @Remotable + private interface BazRemotable { + } + + @Service(interfaces = {Baz.class, Bar.class}) + private class FooMultiple implements Baz, Bar { + + } + + @Service(Baz.class) + private class FooSingle implements Baz, Bar { + + } + + private class FooMultipleNoService implements Baz, Bar { + + } + + private class FooRemotableNoService implements BazRemotable, Bar { + + } + + @Service(FooSingle.class) + private class BadImpl extends FooSingle { + + } + + + @Service() + private class BadDefinition extends FooSingle { + + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/system/builder/SystemComponentBuilderTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/system/builder/SystemComponentBuilderTestCase.java new file mode 100644 index 0000000000..97d69f976e --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/system/builder/SystemComponentBuilderTestCase.java @@ -0,0 +1,303 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.implementation.system.builder; + +import java.lang.reflect.Method; +import java.net.URI; + +import org.apache.tuscany.spi.annotation.Autowire; +import org.apache.tuscany.spi.component.AtomicComponent; +import org.apache.tuscany.spi.component.CompositeComponent; +import org.apache.tuscany.spi.deployer.DeploymentContext; +import org.apache.tuscany.spi.idl.java.JavaServiceContract; +import org.apache.tuscany.spi.implementation.java.ConstructorDefinition; +import org.apache.tuscany.spi.implementation.java.JavaMappedProperty; +import org.apache.tuscany.spi.implementation.java.JavaMappedReference; +import org.apache.tuscany.spi.implementation.java.JavaMappedService; +import org.apache.tuscany.spi.implementation.java.PojoComponentType; +import org.apache.tuscany.spi.model.ComponentDefinition; +import org.apache.tuscany.spi.model.PropertyValue; +import org.apache.tuscany.spi.model.ReferenceTarget; +import org.apache.tuscany.spi.model.Scope; +import org.apache.tuscany.spi.model.ServiceContract; +import org.apache.tuscany.spi.wire.OutboundWire; + +import junit.framework.TestCase; +import org.apache.tuscany.core.component.event.CompositeStart; +import org.apache.tuscany.core.component.event.CompositeStop; +import org.apache.tuscany.core.component.scope.ModuleScopeContainer; +import org.apache.tuscany.core.implementation.system.model.SystemImplementation; +import org.apache.tuscany.core.implementation.system.wire.SystemInboundWire; +import org.apache.tuscany.core.injection.SingletonObjectFactory; +import org.easymock.EasyMock; + +/** + * @version $Rev$ $Date$ + */ +public class SystemComponentBuilderTestCase extends TestCase { + + CompositeComponent parent; + DeploymentContext deploymentContext; + SystemComponentBuilder builder = new SystemComponentBuilder(); + ModuleScopeContainer container; + + /** + * Verifies lifecycle callbacks are made + */ + public void testLifecycleBuild() throws Exception { + PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>> type = + new PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>>(); + type.setEagerInit(true); + Method initMethod = FooImpl.class.getMethod("init"); + initMethod.setAccessible(true); + type.setInitMethod(initMethod); + Method destroyMethod = FooImpl.class.getMethod("destroy"); + destroyMethod.setAccessible(true); + type.setDestroyMethod(destroyMethod); + type.setImplementationScope(Scope.MODULE); + ConstructorDefinition<FooImpl> ctorDef = new ConstructorDefinition<FooImpl>(FooImpl.class.getConstructor()); + type.setConstructorDefinition(ctorDef); + SystemImplementation impl = new SystemImplementation(); + impl.setComponentType(type); + impl.setImplementationClass(FooImpl.class); + ComponentDefinition<SystemImplementation> definition = new ComponentDefinition<SystemImplementation>(impl); + AtomicComponent component = builder.build(parent, definition, deploymentContext); + component.start(); + container.onEvent(new CompositeStart(this, null)); + FooImpl foo = (FooImpl) component.getServiceInstance(); + assertTrue(foo.initialized); + container.onEvent(new CompositeStop(this, null)); + assertTrue(foo.destroyed); + } + + /** + * Verifies properties are built properly + */ + public void testPropertyBuild() throws Exception { + PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>> type = + new PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>>(); + type.setEagerInit(true); + Method initMethod = FooImpl.class.getMethod("init"); + initMethod.setAccessible(true); + type.setInitMethod(initMethod); + Method destroyMethod = FooImpl.class.getMethod("destroy"); + destroyMethod.setAccessible(true); + type.setDestroyMethod(destroyMethod); + type.setImplementationScope(Scope.MODULE); + JavaMappedProperty mappedProp = new JavaMappedProperty(); + mappedProp.setName("prop"); + Method propMethod = FooImpl.class.getMethod("setProp", String.class); + propMethod.setAccessible(true); + mappedProp.setMember(propMethod); + type.add(mappedProp); + ConstructorDefinition<FooImpl> ctorDef = new ConstructorDefinition<FooImpl>(FooImpl.class.getConstructor()); + type.setConstructorDefinition(ctorDef); + SystemImplementation impl = new SystemImplementation(); + impl.setComponentType(type); + impl.setImplementationClass(FooImpl.class); + ComponentDefinition<SystemImplementation> definition = new ComponentDefinition<SystemImplementation>(impl); + PropertyValue<String> propVal = new PropertyValue<String>(); + propVal.setName("prop"); + propVal.setValueFactory(new SingletonObjectFactory<String>("value")); + definition.add(propVal); + AtomicComponent component = builder.build(parent, definition, deploymentContext); + component.start(); + FooImpl foo = (FooImpl) component.getServiceInstance(); + assertEquals("value", foo.prop); + container.onEvent(new CompositeStop(this, null)); + } + + /** + * Verifies references are built properly + */ + public void testRefBuild() throws Exception { + PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>> type = + new PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>>(); + type.setImplementationScope(Scope.MODULE); + JavaMappedReference mappedReference = new JavaMappedReference(); + mappedReference.setName("ref"); + Method refMethod = FooImpl.class.getMethod("setRef", Foo.class); + refMethod.setAccessible(true); + mappedReference.setMember(refMethod); + ServiceContract contract = new JavaServiceContract(Foo.class); + mappedReference.setServiceContract(contract); + type.add(mappedReference); + ConstructorDefinition<FooImpl> ctorDef = new ConstructorDefinition<FooImpl>(FooImpl.class.getConstructor()); + type.setConstructorDefinition(ctorDef); + SystemImplementation impl = new SystemImplementation(); + impl.setComponentType(type); + impl.setImplementationClass(FooImpl.class); + ComponentDefinition<SystemImplementation> definition = new ComponentDefinition<SystemImplementation>(impl); + ReferenceTarget target = new ReferenceTarget(); + target.setReferenceName("ref"); + target.addTarget(new URI("foo")); + definition.add(target); + AtomicComponent component = builder.build(parent, definition, deploymentContext); + OutboundWire wire = component.getOutboundWires().get("ref").get(0); + SystemInboundWire inbound = EasyMock.createMock(SystemInboundWire.class); + FooImpl targetFoo = new FooImpl(); + EasyMock.expect(inbound.getTargetService()).andReturn(targetFoo); + EasyMock.replay(inbound); + wire.setTargetWire(inbound); + component.start(); + FooImpl foo = (FooImpl) component.getServiceInstance(); + assertNotNull(foo.ref); + container.onEvent(new CompositeStop(this, null)); + EasyMock.verify(inbound); + } + + /** + * Verifies autowires are built properly + */ + public void testAutowireBuild() throws Exception { + PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>> type = + new PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>>(); + type.setImplementationScope(Scope.MODULE); + JavaMappedReference mappedReference = new JavaMappedReference(); + mappedReference.setName("ref"); + mappedReference.setAutowire(true); + Method refMethod = FooImpl.class.getMethod("setRef", Foo.class); + refMethod.setAccessible(true); + mappedReference.setMember(refMethod); + ServiceContract contract = new JavaServiceContract(Foo.class); + mappedReference.setServiceContract(contract); + type.add(mappedReference); + ConstructorDefinition<FooImpl> ctorDef = new ConstructorDefinition<FooImpl>(FooImpl.class.getConstructor()); + type.setConstructorDefinition(ctorDef); + SystemImplementation impl = new SystemImplementation(); + impl.setComponentType(type); + impl.setImplementationClass(FooImpl.class); + ComponentDefinition<SystemImplementation> definition = new ComponentDefinition<SystemImplementation>(impl); + CompositeComponent parent = EasyMock.createNiceMock(CompositeComponent.class); + FooImpl targetFoo = new FooImpl(); + EasyMock.expect(parent.resolveSystemInstance(EasyMock.eq(Foo.class))).andReturn(targetFoo); + EasyMock.replay(parent); + AtomicComponent component = builder.build(parent, definition, deploymentContext); + component.start(); + FooImpl foo = (FooImpl) component.getServiceInstance(); + assertNotNull(foo.ref); + container.onEvent(new CompositeStop(this, null)); + EasyMock.verify(parent); + } + + /** + * Verifies constructor-based autowiring + */ + public void testAutowireConstructorBuild() throws Exception { + PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>> type = + new PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>>(); + type.setImplementationScope(Scope.MODULE); + ConstructorDefinition<FooImpl2> ctorDef = + new ConstructorDefinition<FooImpl2>(FooImpl2.class.getConstructor(Foo.class)); + ctorDef.getInjectionNames().add("ref"); + type.setConstructorDefinition(ctorDef); + SystemImplementation impl = new SystemImplementation(); + impl.setComponentType(type); + impl.setImplementationClass(FooImpl2.class); + JavaMappedReference mappedReference = new JavaMappedReference(); + mappedReference.setName("ref"); + mappedReference.setAutowire(true); + ServiceContract contract = new JavaServiceContract(Foo.class); + mappedReference.setServiceContract(contract); + type.add(mappedReference); + ComponentDefinition<SystemImplementation> definition = new ComponentDefinition<SystemImplementation>(impl); + CompositeComponent parent = EasyMock.createNiceMock(CompositeComponent.class); + FooImpl targetFoo = new FooImpl(); + EasyMock.expect(parent.resolveSystemInstance(EasyMock.eq(Foo.class))).andReturn(targetFoo); + EasyMock.replay(parent); + AtomicComponent component = builder.build(parent, definition, deploymentContext); + component.start(); + container.onEvent(new CompositeStart(this, null)); + FooImpl2 foo = (FooImpl2) component.getServiceInstance(); + assertNotNull(foo.getRef()); + container.onEvent(new CompositeStop(this, null)); + EasyMock.verify(parent); + } + + protected void setUp() throws Exception { + super.setUp(); + parent = EasyMock.createNiceMock(CompositeComponent.class); + container = new ModuleScopeContainer(); + container.start(); + deploymentContext = EasyMock.createMock(DeploymentContext.class); + EasyMock.expect(deploymentContext.getModuleScope()).andReturn(container).atLeastOnce(); + EasyMock.replay(deploymentContext); + } + + private static interface Foo { + + } + + private static class FooImpl implements Foo { + private boolean initialized; + private boolean destroyed; + private String prop; + private Foo ref; + + public FooImpl() { + } + + public void init() { + if (initialized) { + fail(); + } + initialized = true; + } + + public void destroy() { + if (destroyed) { + fail(); + } + destroyed = true; + } + + public boolean isInitialized() { + return initialized; + } + + public String getProp() { + return prop; + } + + public void setProp(String prop) { + this.prop = prop; + } + + public Foo getRef() { + return ref; + } + + public void setRef(Foo ref) { + this.ref = ref; + } + } + + private static class FooImpl2 implements Foo { + private Foo ref; + + public FooImpl2(@Autowire Foo ref) { + this.ref = ref; + } + + public Foo getRef() { + return ref; + } + + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/system/component/SystemAtomicComponentTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/system/component/SystemAtomicComponentTestCase.java new file mode 100644 index 0000000000..29c37ba47a --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/system/component/SystemAtomicComponentTestCase.java @@ -0,0 +1,103 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.implementation.system.component; + +import junit.framework.TestCase; +import org.apache.tuscany.core.implementation.PojoConfiguration; +import org.apache.tuscany.core.implementation.system.wire.SystemOutboundWire; +import org.apache.tuscany.core.injection.EventInvoker; +import org.apache.tuscany.core.injection.MethodEventInvoker; +import org.apache.tuscany.core.injection.PojoObjectFactory; +import org.apache.tuscany.core.injection.SingletonObjectFactory; +import org.easymock.EasyMock; + +/** + * Verifies a system atomic component can be started and initialized + * + * @version $$Rev$$ $$Date$$ + */ +public class SystemAtomicComponentTestCase extends TestCase { + + private EventInvoker<Object> initInvoker; + + public void testDefaultCreationAndInit() throws Exception { + PojoObjectFactory<Foo> factory = new PojoObjectFactory<Foo>(Foo.class.getConstructor((Class[]) null)); + PojoConfiguration configuration = new PojoConfiguration(); + configuration.addServiceInterface(Foo.class); + configuration.setInstanceFactory(factory); + configuration.setInitInvoker(initInvoker); + SystemAtomicComponentImpl component = new SystemAtomicComponentImpl("foo", configuration); + Foo foo = (Foo) component.createInstance(); + component.init(foo); + assertTrue(foo.initialized); + } + + public void testReferenceAndPropertyConstructor() throws Exception { + PojoObjectFactory<Bar> factory = new PojoObjectFactory<Bar>(Bar.class.getConstructor(String.class, Foo.class)); + PojoConfiguration configuration = new PojoConfiguration(); + configuration.addServiceInterface(Foo.class); + configuration.setInstanceFactory(factory); + configuration.setInitInvoker(initInvoker); + configuration.addConstructorParamName("foo"); + configuration.addConstructorParamName("ref"); + SystemAtomicComponentImpl component = new SystemAtomicComponentImpl("foo", configuration); + component.addPropertyFactory("foo", new SingletonObjectFactory<String>("baz")); + Foo target = new Foo(); + SystemOutboundWire wire = EasyMock.createMock(SystemOutboundWire.class); + EasyMock.expect(wire.getTargetService()).andReturn(target); + EasyMock.expect(wire.getReferenceName()).andReturn("ref").anyTimes(); + EasyMock.replay(wire); + component.addOutboundWire(wire); + Bar bar = (Bar) component.createInstance(); + assertEquals("baz", bar.foo); + assertEquals(target, bar.ref); + EasyMock.verify(wire); + } + + protected void setUp() throws Exception { + super.setUp(); + initInvoker = new MethodEventInvoker<Object>(Foo.class.getMethod("init")); + } + + protected void tearDown() throws Exception { + super.tearDown(); + } + + public static class Foo { + + private boolean initialized; + + public void init() { + initialized = true; + } + } + + public static class Bar { + + private String foo; + private Foo ref; + + public Bar(String foo, Foo ref) { + this.foo = foo; + this.ref = ref; + } + } + + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/system/loader/SystemComponentTypeLoaderTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/system/loader/SystemComponentTypeLoaderTestCase.java new file mode 100644 index 0000000000..e4eec8cae2 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/system/loader/SystemComponentTypeLoaderTestCase.java @@ -0,0 +1,82 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.implementation.system.loader; + +import org.apache.tuscany.spi.component.CompositeComponent; +import org.apache.tuscany.spi.implementation.java.PojoComponentType; +import org.apache.tuscany.spi.implementation.java.ProcessingException; +import org.apache.tuscany.spi.model.Property; +import org.apache.tuscany.spi.model.ReferenceDefinition; +import org.apache.tuscany.spi.model.ServiceDefinition; + +import junit.framework.TestCase; +import org.apache.tuscany.core.idl.java.JavaInterfaceProcessorRegistryImpl; +import org.apache.tuscany.core.implementation.IntrospectionRegistryImpl; +import org.apache.tuscany.core.implementation.processor.ConstructorProcessor; +import org.apache.tuscany.core.implementation.processor.DestroyProcessor; +import org.apache.tuscany.core.implementation.processor.HeuristicPojoProcessor; +import org.apache.tuscany.spi.implementation.java.ImplementationProcessorService; +import org.apache.tuscany.core.implementation.processor.ImplementationProcessorServiceImpl; +import org.apache.tuscany.core.implementation.processor.InitProcessor; +import org.apache.tuscany.core.implementation.processor.PropertyProcessor; +import org.apache.tuscany.core.implementation.processor.ReferenceProcessor; +import org.apache.tuscany.core.implementation.processor.ScopeProcessor; +import org.apache.tuscany.core.implementation.processor.ServiceProcessor; +import org.apache.tuscany.core.implementation.system.model.SystemImplementation; +import org.apache.tuscany.core.mock.component.BasicInterface; +import org.apache.tuscany.core.mock.component.BasicInterfaceImpl; +import org.apache.tuscany.core.monitor.NullMonitorFactory; +import org.easymock.EasyMock; + +/** + * @version $Rev$ $Date$ + */ +public class SystemComponentTypeLoaderTestCase extends TestCase { + private SystemComponentTypeLoader loader; + + public void testIntrospectUnannotatedClass() throws ProcessingException { + CompositeComponent parent = EasyMock.createNiceMock(CompositeComponent.class); + SystemImplementation impl = new SystemImplementation(BasicInterfaceImpl.class); + PojoComponentType<?, ?, ?> componentType = loader.loadByIntrospection(parent, impl, null); + ServiceDefinition service = componentType.getServices().get("BasicInterface"); + assertEquals(BasicInterface.class, service.getServiceContract().getInterfaceClass()); + Property<?> property = componentType.getProperties().get("publicProperty"); + assertEquals(String.class, property.getJavaType()); + ReferenceDefinition referenceDefinition = componentType.getReferences().get("protectedReference"); + assertEquals(BasicInterface.class, referenceDefinition.getServiceContract().getInterfaceClass()); + } + + protected void setUp() throws Exception { + super.setUp(); + JavaInterfaceProcessorRegistryImpl interfaceProcessorRegistry = new JavaInterfaceProcessorRegistryImpl(); + ImplementationProcessorService service = + new ImplementationProcessorServiceImpl(interfaceProcessorRegistry); + IntrospectionRegistryImpl registry = new IntrospectionRegistryImpl(); + registry.setMonitor(new NullMonitorFactory().getMonitor(IntrospectionRegistryImpl.Monitor.class)); + registry.registerProcessor(new ConstructorProcessor(service)); + registry.registerProcessor(new DestroyProcessor()); + registry.registerProcessor(new InitProcessor()); + registry.registerProcessor(new ScopeProcessor()); + registry.registerProcessor(new PropertyProcessor(service)); + registry.registerProcessor(new ReferenceProcessor(interfaceProcessorRegistry)); + registry.registerProcessor(new ServiceProcessor(service)); + registry.registerProcessor(new HeuristicPojoProcessor(service)); + loader = new SystemComponentTypeLoader(registry); + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/system/wire/AtomicComponentWireInvocationTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/system/wire/AtomicComponentWireInvocationTestCase.java new file mode 100644 index 0000000000..017274e455 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/system/wire/AtomicComponentWireInvocationTestCase.java @@ -0,0 +1,66 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.implementation.system.wire; + +import org.apache.tuscany.spi.QualifiedName; +import org.apache.tuscany.spi.component.SystemAtomicComponent; +import org.apache.tuscany.spi.wire.OutboundWire; + +import junit.framework.TestCase; +import org.apache.tuscany.core.component.scope.ModuleScopeContainer; +import org.apache.tuscany.core.implementation.PojoConfiguration; +import org.apache.tuscany.core.implementation.system.component.SystemAtomicComponentImpl; +import org.apache.tuscany.core.injection.PojoObjectFactory; +import org.apache.tuscany.core.mock.component.Source; +import org.apache.tuscany.core.mock.component.SourceImpl; +import org.apache.tuscany.core.mock.component.Target; +import org.apache.tuscany.core.mock.component.TargetImpl; +import org.easymock.EasyMock; + +/** + * Tests wiring from an system atomic context + * + * @version $$Rev$$ $$Date$$ + */ +public class AtomicComponentWireInvocationTestCase extends TestCase { + + public void testWireResolution() throws NoSuchMethodException { + ModuleScopeContainer scope = new ModuleScopeContainer(null); + scope.start(); + Target target = new TargetImpl(); + SystemInboundWire inboundWire = EasyMock.createMock(SystemInboundWire.class); + EasyMock.expect(inboundWire.getTargetService()).andReturn(target); + EasyMock.replay(inboundWire); + + PojoConfiguration configuration = new PojoConfiguration(); + configuration.setScopeContainer(scope); + configuration.addReferenceSite("setTarget", SourceImpl.class.getMethod("setTarget", Target.class)); + configuration.addServiceInterface(Source.class); + configuration.setInstanceFactory(new PojoObjectFactory<SourceImpl>(SourceImpl.class.getConstructor())); + SystemAtomicComponent sourceContext = new SystemAtomicComponentImpl("source", configuration); + QualifiedName qName = new QualifiedName("service"); + OutboundWire outboundWire = new SystemOutboundWireImpl("setTarget", qName, Target.class); + outboundWire.setTargetWire(inboundWire); + sourceContext.addOutboundWire(outboundWire); + sourceContext.start(); + assertSame(((Source) sourceContext.getServiceInstance()).getTarget(), target); + // wires should pass back direct ref + EasyMock.verify(inboundWire); + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/system/wire/SystemInboundtoOutboundTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/system/wire/SystemInboundtoOutboundTestCase.java new file mode 100644 index 0000000000..ed89fb6aae --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/system/wire/SystemInboundtoOutboundTestCase.java @@ -0,0 +1,44 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.implementation.system.wire; + +import junit.framework.TestCase; +import org.apache.tuscany.core.mock.component.Target; +import org.apache.tuscany.core.mock.component.TargetImpl; +import org.easymock.EasyMock; + +/** + * Tests connecting an inbound system wire to an outbound system wire + * + * @version $$Rev$$ $$Date$$ + */ +public class SystemInboundtoOutboundTestCase extends TestCase { + + public void testWire() throws NoSuchMethodException { + Target target = new TargetImpl(); + SystemOutboundWire outboundWire = EasyMock.createMock(SystemOutboundWire.class); + EasyMock.expect(outboundWire.getTargetService()).andReturn(target); + EasyMock.replay(outboundWire); + SystemInboundWire inboundWire = new SystemInboundWireImpl("service", Target.class); + inboundWire.setTargetWire(outboundWire); + assertSame(inboundWire.getTargetService(), target); + EasyMock.verify(outboundWire); + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/system/wire/SystemOutboundAutowireTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/system/wire/SystemOutboundAutowireTestCase.java new file mode 100644 index 0000000000..8c00af6e9e --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/system/wire/SystemOutboundAutowireTestCase.java @@ -0,0 +1,74 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.implementation.system.wire; + +import org.apache.tuscany.spi.component.CompositeComponent; +import org.apache.tuscany.spi.component.TargetNotFoundException; + +import junit.framework.TestCase; +import static org.easymock.EasyMock.createMock; +import static org.easymock.EasyMock.expect; +import static org.easymock.EasyMock.replay; +import static org.easymock.EasyMock.verify; + +/** + * @version $Rev$ $Date$ + */ +public class SystemOutboundAutowireTestCase extends TestCase { + + public void testAutowire() { + CompositeComponent component = createMock(CompositeComponent.class); + expect(component.resolveSystemInstance(Object.class)).andReturn(new Object()); + replay(component); + SystemOutboundAutowire wire = new SystemOutboundAutowire("foo", Object.class, component, false); + assertNotNull(wire.getTargetService()); + verify(component); + } + + + public void testNonExistentAutowire() { + CompositeComponent component = createMock(CompositeComponent.class); + expect(component.resolveSystemInstance(Object.class)).andReturn(null); + replay(component); + SystemOutboundAutowire wire = new SystemOutboundAutowire("foo", Object.class, component, true); + try { + wire.getTargetService(); + fail(); + } catch (TargetNotFoundException e) { + // expected + } + verify(component); + } + + + public void testNonExistentAutowireNotRequired() { + CompositeComponent component = createMock(CompositeComponent.class); + expect(component.resolveSystemInstance(Object.class)).andReturn(null); + replay(component); + SystemOutboundAutowire wire = new SystemOutboundAutowire("foo", Object.class, component, false); + try { + assertNull(wire.getTargetService()); + } catch (TargetNotFoundException e) { + fail(); + } + verify(component); + } + + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/system/wire/SystemOutboundToInboundTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/system/wire/SystemOutboundToInboundTestCase.java new file mode 100644 index 0000000000..8f41a33c12 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/system/wire/SystemOutboundToInboundTestCase.java @@ -0,0 +1,47 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.implementation.system.wire; + +import org.apache.tuscany.spi.QualifiedName; + +import junit.framework.TestCase; +import org.apache.tuscany.core.mock.component.Target; +import org.apache.tuscany.core.mock.component.TargetImpl; +import org.easymock.EasyMock; + +/** + * Tests connecting an outbound system wire to an inbound system wire + * + * @version $$Rev$$ $$Date$$ + */ +public class SystemOutboundToInboundTestCase extends TestCase { + + public void testWire() throws NoSuchMethodException { + Target target = new TargetImpl(); + SystemInboundWire inboundWire = EasyMock.createMock(SystemInboundWire.class); + EasyMock.expect(inboundWire.getTargetService()).andReturn(target); + EasyMock.replay(inboundWire); + QualifiedName qName = new QualifiedName("service"); + SystemOutboundWire outboundWire = new SystemOutboundWireImpl("setTarget", qName, Target.class); + outboundWire.setTargetWire(inboundWire); + assertSame(outboundWire.getTargetService(), target); + EasyMock.verify(inboundWire); + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/system/wire/SystemServiceComponentWireTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/system/wire/SystemServiceComponentWireTestCase.java new file mode 100644 index 0000000000..222b02f6a1 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/implementation/system/wire/SystemServiceComponentWireTestCase.java @@ -0,0 +1,48 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.implementation.system.wire; + +import junit.framework.TestCase; +import org.apache.tuscany.core.implementation.system.component.SystemService; +import org.apache.tuscany.core.implementation.system.component.SystemServiceImpl; +import org.apache.tuscany.core.mock.component.Target; +import org.apache.tuscany.core.mock.component.TargetImpl; +import org.easymock.EasyMock; + +/** + * Verifies that a system context interacts correctly with configured, connected inbound and outbound system wires + * + * @version $$Rev$$ $$Date$$ + */ +public class SystemServiceComponentWireTestCase extends TestCase { + + public void testServiceContext() throws NoSuchMethodException { + Target target = new TargetImpl(); + SystemOutboundWire outboundWire = EasyMock.createMock(SystemOutboundWire.class); + EasyMock.expect(outboundWire.getTargetService()).andReturn(target); + EasyMock.replay(outboundWire); + SystemInboundWire wire = new SystemInboundWireImpl("Target", Target.class); + SystemService serviceContext = new SystemServiceImpl("service", null); + serviceContext.setInboundWire(wire); + serviceContext.setOutboundWire(outboundWire); + wire.setTargetWire(outboundWire); + assertSame(target, serviceContext.getServiceInstance()); + EasyMock.verify(outboundWire); + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/injection/CallbackWireObjectFactoryTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/injection/CallbackWireObjectFactoryTestCase.java new file mode 100644 index 0000000000..8c3aea9dd3 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/injection/CallbackWireObjectFactoryTestCase.java @@ -0,0 +1,50 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.injection; + +import org.apache.tuscany.spi.idl.java.JavaServiceContract; +import org.apache.tuscany.spi.wire.WireService; + +import junit.framework.TestCase; +import static org.easymock.EasyMock.createMock; +import static org.easymock.EasyMock.expectLastCall; +import static org.easymock.EasyMock.replay; +import static org.easymock.EasyMock.verify; + +/** + * @version $Rev$ $Date$ + */ +public class CallbackWireObjectFactoryTestCase extends TestCase { + + public void testCreateInstance() throws Exception { + JavaServiceContract contract = new JavaServiceContract(); + contract.setCallbackClass(Foo.class); + WireService service = createMock(WireService.class); + service.createCallbackProxy(contract, null); + expectLastCall().andReturn(null); + replay(service); + CallbackWireObjectFactory factory = new CallbackWireObjectFactory(contract, service, null); + factory.getInstance(); + verify(service); + } + + private interface Foo { + + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/injection/FieldInjectorTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/injection/FieldInjectorTestCase.java new file mode 100644 index 0000000000..d31347f7e6 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/injection/FieldInjectorTestCase.java @@ -0,0 +1,48 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.injection; + +import java.lang.reflect.Field; + +import junit.framework.TestCase; + +/** + * @version $Rev$ $Date$ + */ +public class FieldInjectorTestCase extends TestCase { + + protected Field protectedField; + + public void testIllegalAccess() throws Exception { + FieldInjector<Foo> injector = new FieldInjector<Foo>(protectedField, new SingletonObjectFactory<String>("foo")); + Foo foo = new Foo(); + injector.inject(foo); + assertEquals("foo", foo.hidden); + } + + + protected void setUp() throws Exception { + super.setUp(); + protectedField = Foo.class.getDeclaredField("hidden"); + } + + private class Foo { + private String hidden; + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/injection/JNDIObjectFactoryTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/injection/JNDIObjectFactoryTestCase.java new file mode 100644 index 0000000000..91214fd02d --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/injection/JNDIObjectFactoryTestCase.java @@ -0,0 +1,61 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.injection; + +import javax.naming.Context; +import javax.naming.NamingException; + +import org.apache.tuscany.spi.ObjectCreationException; + +import junit.framework.TestCase; +import org.easymock.EasyMock; + +/** + * @version $Rev$ $Date$ + */ +public class JNDIObjectFactoryTestCase extends TestCase { + + public void testGetInstance() throws Exception { + Context ctx = EasyMock.createMock(Context.class); + EasyMock.expect(ctx.lookup(EasyMock.eq("foo"))).andReturn(new Foo()); + EasyMock.replay(ctx); + JNDIObjectFactory<Foo> factory = new JNDIObjectFactory<Foo>(ctx, "foo"); + assertTrue(factory.getInstance() instanceof Foo); // must do an instanceof b/c of type erasure + EasyMock.verify(ctx); + } + + public void testGetInstanceError() throws Exception { + Context ctx = EasyMock.createMock(Context.class); + EasyMock.expect(ctx.lookup(EasyMock.eq("foo"))).andThrow(new NamingException()); + EasyMock.replay(ctx); + JNDIObjectFactory<Foo> factory = new JNDIObjectFactory<Foo>(ctx, "foo"); + try { + factory.getInstance(); + fail(); + } catch (ObjectCreationException e) { + //expected + } + EasyMock.verify(ctx); + } + + + private class Foo { + + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/injection/MethodEventInvokerTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/injection/MethodEventInvokerTestCase.java new file mode 100644 index 0000000000..3bb882da2d --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/injection/MethodEventInvokerTestCase.java @@ -0,0 +1,72 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.injection; + +import java.lang.reflect.Method; + +import junit.framework.TestCase; + +/** + * @version $Rev$ $Date$ + */ +public class MethodEventInvokerTestCase extends TestCase { + private Method privateMethod; + private Method exceptionMethod; + + public void testIllegalAccess() throws Exception { + MethodEventInvoker<MethodEventInvokerTestCase.Foo> injector = new MethodEventInvoker<Foo>(privateMethod); + try { + injector.invokeEvent(new Foo()); + fail(); + } catch (AssertionError e) { + // expected + } + } + + public void testException() throws Exception { + MethodEventInvoker<MethodEventInvokerTestCase.Foo> injector = new MethodEventInvoker<Foo>(exceptionMethod); + try { + injector.invokeEvent(new Foo()); + fail(); + } catch (RuntimeException e) { + // expected + } + } + + protected void setUp() throws Exception { + super.setUp(); + privateMethod = MethodEventInvokerTestCase.Foo.class.getDeclaredMethod("hidden"); + exceptionMethod = MethodEventInvokerTestCase.Foo.class.getDeclaredMethod("exception"); + + } + + private class Foo { + + public void foo() { + } + + private void hidden() { + } + + public void exception() { + throw new RuntimeException(); + } + + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/injection/MethodInjectorTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/injection/MethodInjectorTestCase.java new file mode 100644 index 0000000000..b21ba4ccfa --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/injection/MethodInjectorTestCase.java @@ -0,0 +1,79 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.injection; + +import java.lang.reflect.Method; + +import org.apache.tuscany.spi.ObjectCreationException; +import org.apache.tuscany.spi.ObjectFactory; + +import junit.framework.TestCase; + +/** + * @version $Rev$ $Date$ + */ +public class MethodInjectorTestCase extends TestCase { + private Method fooMethod; + private Method privateMethod; + private Method exceptionMethod; + + public void testIllegalArgument() throws Exception { + ObjectFactory<Object> factory = new SingletonObjectFactory<Object>(new Object()); + MethodInjector<Foo> injector = new MethodInjector<Foo>(fooMethod, factory); + try { + injector.inject(new Foo()); + fail(); + } catch (ObjectCreationException e) { + // expected + } + } + + public void testException() throws Exception { + ObjectFactory<Object> factory = new SingletonObjectFactory<Object>("foo"); + MethodInjector<Foo> injector = new MethodInjector<Foo>(exceptionMethod, factory); + try { + injector.inject(new Foo()); + fail(); + } catch (RuntimeException e) { + // expected + } + } + + protected void setUp() throws Exception { + super.setUp(); + fooMethod = Foo.class.getMethod("foo", String.class); + privateMethod = Foo.class.getDeclaredMethod("hidden", String.class); + exceptionMethod = Foo.class.getDeclaredMethod("exception", String.class); + + } + + private class Foo { + + public void foo(String bar) { + } + + private void hidden(String bar) { + } + + public void exception(String bar) { + throw new RuntimeException(); + } + + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/injection/PojoObjectFactoryTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/injection/PojoObjectFactoryTestCase.java new file mode 100644 index 0000000000..7aba6dbab3 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/injection/PojoObjectFactoryTestCase.java @@ -0,0 +1,64 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.injection; + +import java.lang.reflect.Constructor; +import java.util.List; +import java.util.ArrayList; + +import org.apache.tuscany.spi.ObjectFactory; + +import junit.framework.TestCase; + +/** + * @version $Rev$ $Date$ + */ +public class PojoObjectFactoryTestCase extends TestCase { + + private Constructor<Foo> ctor; + + public void testConstructorInjection() throws Exception { + List<ObjectFactory> initializers = new ArrayList<ObjectFactory>(); + initializers.add(new SingletonObjectFactory<String>("foo")); + PojoObjectFactory<Foo> factory = new PojoObjectFactory<Foo>(ctor, initializers); + Foo foo = factory.getInstance(); + assertEquals("foo", foo.foo); + } + + public void testConstructorInitializerInjection() throws Exception { + PojoObjectFactory<Foo> factory = new PojoObjectFactory<Foo>(ctor); + factory.setInitializerFactory(0, new SingletonObjectFactory<String>("foo")); + Foo foo = factory.getInstance(); + assertEquals("foo", foo.foo); + } + + protected void setUp() throws Exception { + super.setUp(); + ctor = Foo.class.getConstructor(String.class); + } + + private static class Foo { + + private String foo; + + public Foo(String foo) { + this.foo = foo; + } + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/injection/SingletonObjectFactoryTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/injection/SingletonObjectFactoryTestCase.java new file mode 100644 index 0000000000..876e68d5b3 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/injection/SingletonObjectFactoryTestCase.java @@ -0,0 +1,33 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.injection; + +import junit.framework.TestCase; + +/** + * @version $Rev$ $Date$ + */ +public class SingletonObjectFactoryTestCase extends TestCase { + + public void testSingleton() throws Exception { + Object o = new Object(); + SingletonObjectFactory<Object> factory = new SingletonObjectFactory<Object>(o); + assertEquals(o, factory.getInstance()); + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/injection/WireObjectFactoryTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/injection/WireObjectFactoryTestCase.java new file mode 100644 index 0000000000..e6e531dba7 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/injection/WireObjectFactoryTestCase.java @@ -0,0 +1,45 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.injection; + +import org.apache.tuscany.spi.wire.RuntimeWire; +import org.apache.tuscany.spi.wire.WireService; + +import junit.framework.TestCase; +import static org.easymock.EasyMock.createMock; +import static org.easymock.EasyMock.expectLastCall; +import static org.easymock.EasyMock.replay; +import static org.easymock.EasyMock.verify; + +/** + * @version $Rev$ $Date$ + */ +public class WireObjectFactoryTestCase extends TestCase { + + public void testCreateInstance() throws Exception { + RuntimeWire wire = createMock(RuntimeWire.class); + WireService service = createMock(WireService.class); + service.createProxy(wire); + expectLastCall().andReturn(null); + replay(service); + WireObjectFactory factory = new WireObjectFactory(wire, service); + factory.getInstance(); + verify(service); + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/integration/implementation/IntrospectionRegistryIntegrationTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/integration/implementation/IntrospectionRegistryIntegrationTestCase.java new file mode 100644 index 0000000000..a9b1353cdd --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/integration/implementation/IntrospectionRegistryIntegrationTestCase.java @@ -0,0 +1,122 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.integration.implementation; + +import org.osoa.sca.annotations.Destroy; +import org.osoa.sca.annotations.Init; +import org.osoa.sca.annotations.Property; +import org.osoa.sca.annotations.Reference; +import org.osoa.sca.annotations.Scope; + +import org.apache.tuscany.spi.implementation.java.JavaMappedProperty; +import org.apache.tuscany.spi.implementation.java.JavaMappedReference; +import org.apache.tuscany.spi.implementation.java.JavaMappedService; +import org.apache.tuscany.spi.implementation.java.PojoComponentType; +import org.apache.tuscany.spi.implementation.java.ImplementationProcessorService; +import static org.apache.tuscany.spi.model.Scope.MODULE; + +import junit.framework.TestCase; +import org.apache.tuscany.core.idl.java.JavaInterfaceProcessorRegistryImpl; +import org.apache.tuscany.core.implementation.IntrospectionRegistryImpl; +import org.apache.tuscany.core.implementation.processor.DestroyProcessor; +import org.apache.tuscany.core.implementation.processor.ImplementationProcessorServiceImpl; +import org.apache.tuscany.core.implementation.processor.InitProcessor; +import org.apache.tuscany.core.implementation.processor.PropertyProcessor; +import org.apache.tuscany.core.implementation.processor.ReferenceProcessor; +import org.apache.tuscany.core.implementation.processor.ScopeProcessor; +import org.apache.tuscany.core.monitor.NullMonitorFactory; + +/** + * Sanity check of the <code>IntegrationRegistry</code> to verify operation with processors + * + * @version $Rev$ $Date$ + */ +public class IntrospectionRegistryIntegrationTestCase extends TestCase { + + private IntrospectionRegistryImpl registry; + + public void testSimpleComponentTypeParsing() throws Exception { + PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>> type = + new PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>>(); + registry.introspect(null, Foo.class, type, null); + assertEquals(Foo.class.getMethod("init"), type.getInitMethod()); + assertEquals(Foo.class.getMethod("destroy"), type.getDestroyMethod()); + assertEquals(MODULE, type.getImplementationScope()); + assertEquals(Foo.class.getMethod("setBar", String.class), type.getProperties().get("bar").getMember()); + assertEquals(Foo.class.getMethod("setTarget", Foo.class), type.getReferences().get("target").getMember()); + } + + protected void setUp() throws Exception { + super.setUp(); + registry = new IntrospectionRegistryImpl(); + registry.setMonitor(new NullMonitorFactory().getMonitor(IntrospectionRegistryImpl.Monitor.class)); + registry.registerProcessor(new DestroyProcessor()); + registry.registerProcessor(new InitProcessor()); + registry.registerProcessor(new ScopeProcessor()); + JavaInterfaceProcessorRegistryImpl interfaceProcessorRegistry = new JavaInterfaceProcessorRegistryImpl(); + ImplementationProcessorService service = new ImplementationProcessorServiceImpl(interfaceProcessorRegistry); + registry.registerProcessor(new PropertyProcessor(service)); + registry.registerProcessor(new ReferenceProcessor(interfaceProcessorRegistry)); + } + + @Scope("MODULE") + private static class Foo { + protected Foo target; + protected String bar; + + private boolean initialized; + private boolean destroyed; + + + @Init + public void init() { + if (initialized) { + fail(); + } + initialized = true; + } + + @Destroy + public void destroy() { + if (destroyed) { + fail(); + } + destroyed = true; + } + + public Foo getTarget() { + return target; + } + + @Reference + public void setTarget(Foo target) { + this.target = target; + } + + public String getBar() { + return bar; + } + + @Property + public void setBar(String bar) { + this.bar = bar; + } + + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/integration/implementation/java/builder/JavaBuilderPropertyTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/integration/implementation/java/builder/JavaBuilderPropertyTestCase.java new file mode 100644 index 0000000000..a173dda98e --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/integration/implementation/java/builder/JavaBuilderPropertyTestCase.java @@ -0,0 +1,100 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.integration.implementation.java.builder; + +import org.apache.tuscany.spi.component.AtomicComponent; +import org.apache.tuscany.spi.component.CompositeComponent; +import org.apache.tuscany.spi.component.ScopeRegistry; +import org.apache.tuscany.spi.deployer.DeploymentContext; +import org.apache.tuscany.spi.implementation.java.ConstructorDefinition; +import org.apache.tuscany.spi.implementation.java.JavaMappedProperty; +import org.apache.tuscany.spi.implementation.java.PojoComponentType; +import org.apache.tuscany.spi.model.ComponentDefinition; +import org.apache.tuscany.spi.model.PropertyValue; +import org.apache.tuscany.spi.model.ReferenceDefinition; +import org.apache.tuscany.spi.model.Scope; +import org.apache.tuscany.spi.model.ServiceDefinition; + +import junit.framework.TestCase; +import org.apache.tuscany.core.component.WorkContextImpl; +import org.apache.tuscany.core.component.scope.ScopeRegistryImpl; +import org.apache.tuscany.core.component.scope.StatelessScopeObjectFactory; +import org.apache.tuscany.core.deployer.RootDeploymentContext; +import org.apache.tuscany.core.implementation.java.JavaComponentBuilder; +import org.apache.tuscany.core.implementation.java.JavaImplementation; +import org.apache.tuscany.core.injection.SingletonObjectFactory; +import org.easymock.EasyMock; + +/** + * Verifies that the system builder handles configured properties correctly + * + * @version $Rev$ $Date$ + */ +public class JavaBuilderPropertyTestCase extends TestCase { + + private DeploymentContext deploymentContext; + private CompositeComponent parent; + private ScopeRegistry registry; + + public void testPropertyHandling() throws Exception { + JavaComponentBuilder builder = new JavaComponentBuilder(); + builder.setScopeRegistry(registry); + PojoComponentType<ServiceDefinition, ReferenceDefinition, JavaMappedProperty<?>> type = + new PojoComponentType<ServiceDefinition, ReferenceDefinition, JavaMappedProperty<?>>(); + JavaMappedProperty<String> property = new JavaMappedProperty<String>(); + property.setName("test"); + property.setDefaultValueFactory(new SingletonObjectFactory<String>("foo")); + property.setMember(JavaBuilderPropertyTestCase.Foo.class.getMethod("setTest", String.class)); + type.add(property); + type.setConstructorDefinition(new ConstructorDefinition<Foo>(Foo.class.getConstructor((Class[]) null))); + type.setImplementationScope(Scope.STATELESS); + JavaImplementation impl = new JavaImplementation(); + impl.setComponentType(type); + impl.setImplementationClass(Foo.class); + ComponentDefinition<JavaImplementation> definition = new ComponentDefinition<JavaImplementation>(impl); + PropertyValue propertyValue = new PropertyValue(property.getName(), property.getDefaultValueFactory()); + definition.getPropertyValues().put(property.getName(), propertyValue); + AtomicComponent component = builder.build(parent, definition, deploymentContext); + JavaBuilderPropertyTestCase.Foo foo = (JavaBuilderPropertyTestCase.Foo) component.createInstance(); + assertEquals("foo", foo.getTest()); + } + + protected void setUp() throws Exception { + super.setUp(); + deploymentContext = new RootDeploymentContext(null, null, null, null); + parent = EasyMock.createNiceMock(CompositeComponent.class); + registry = new ScopeRegistryImpl(new WorkContextImpl()); + new StatelessScopeObjectFactory(registry); + } + + private static class Foo { + private String test; + + public Foo() { + } + + public String getTest() { + return test; + } + + public void setTest(String test) { + this.test = test; + } + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/integration/implementation/system/builder/SystemBuilderPropertyTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/integration/implementation/system/builder/SystemBuilderPropertyTestCase.java new file mode 100644 index 0000000000..a7d580bbcb --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/integration/implementation/system/builder/SystemBuilderPropertyTestCase.java @@ -0,0 +1,88 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.integration.implementation.system.builder; + +import org.apache.tuscany.spi.component.AtomicComponent; +import org.apache.tuscany.spi.component.CompositeComponent; +import org.apache.tuscany.spi.deployer.DeploymentContext; +import org.apache.tuscany.spi.implementation.java.ConstructorDefinition; +import org.apache.tuscany.spi.implementation.java.JavaMappedProperty; +import org.apache.tuscany.spi.implementation.java.PojoComponentType; +import org.apache.tuscany.spi.model.ComponentDefinition; +import org.apache.tuscany.spi.model.ReferenceDefinition; +import org.apache.tuscany.spi.model.ServiceDefinition; + +import junit.framework.TestCase; +import org.apache.tuscany.core.deployer.RootDeploymentContext; +import org.apache.tuscany.core.implementation.system.builder.SystemComponentBuilder; +import org.apache.tuscany.core.implementation.system.model.SystemImplementation; +import org.apache.tuscany.core.injection.SingletonObjectFactory; +import org.easymock.EasyMock; + +/** + * Verifies that the system builder handles configured properties correctly + * + * @version $Rev$ $Date$ + */ +public class SystemBuilderPropertyTestCase extends TestCase { + + DeploymentContext deploymentContext; + CompositeComponent parent; + + @SuppressWarnings("unchecked") + public void testPropertyHandling() throws Exception { + SystemComponentBuilder builder = new SystemComponentBuilder(); + PojoComponentType<ServiceDefinition, ReferenceDefinition, JavaMappedProperty<?>> type = + new PojoComponentType<ServiceDefinition, ReferenceDefinition, JavaMappedProperty<?>>(); + type.setConstructorDefinition(new ConstructorDefinition<Foo>(Foo.class.getConstructor((Class[]) null))); + JavaMappedProperty<String> property = new JavaMappedProperty<String>(); + property.setName("test"); + property.setDefaultValueFactory(new SingletonObjectFactory<String>("foo")); + property.setMember(Foo.class.getMethod("setTest", String.class)); + type.add(property); + SystemImplementation impl = new SystemImplementation(); + impl.setComponentType(type); + impl.setImplementationClass(Foo.class); + ComponentDefinition<SystemImplementation> definition = new ComponentDefinition<SystemImplementation>(impl); + AtomicComponent component = builder.build(parent, definition, deploymentContext); + Foo foo = (Foo) component.createInstance(); + assertEquals("foo", foo.getTest()); + } + + protected void setUp() throws Exception { + super.setUp(); + deploymentContext = new RootDeploymentContext(null, null, null, null); + parent = EasyMock.createNiceMock(CompositeComponent.class); + } + + private static class Foo { + private String test; + + public Foo() { + } + + public String getTest() { + return test; + } + + public void setTest(String test) { + this.test = test; + } + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/integration/implementation/system/builder/SystemBuilderWireTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/integration/implementation/system/builder/SystemBuilderWireTestCase.java new file mode 100644 index 0000000000..761d2bb650 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/integration/implementation/system/builder/SystemBuilderWireTestCase.java @@ -0,0 +1,183 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.integration.implementation.system.builder; + +import org.apache.tuscany.spi.builder.Connector; +import org.apache.tuscany.spi.component.AtomicComponent; +import org.apache.tuscany.spi.component.CompositeComponent; +import org.apache.tuscany.spi.component.Reference; +import org.apache.tuscany.spi.component.ScopeContainer; +import org.apache.tuscany.spi.component.Service; +import org.apache.tuscany.spi.component.WorkContext; +import org.apache.tuscany.spi.deployer.DeploymentContext; +import org.apache.tuscany.spi.model.BoundReferenceDefinition; +import org.apache.tuscany.spi.model.BoundServiceDefinition; +import org.apache.tuscany.spi.model.ComponentDefinition; + +import junit.framework.TestCase; +import org.apache.tuscany.core.builder.ConnectorImpl; +import org.apache.tuscany.core.component.WorkContextImpl; +import org.apache.tuscany.core.component.event.CompositeStart; +import org.apache.tuscany.core.component.event.CompositeStop; +import org.apache.tuscany.core.component.scope.ModuleScopeContainer; +import org.apache.tuscany.core.deployer.RootDeploymentContext; +import org.apache.tuscany.core.implementation.composite.CompositeComponentImpl; +import org.apache.tuscany.core.implementation.system.builder.SystemBindingBuilder; +import org.apache.tuscany.core.implementation.system.builder.SystemComponentBuilder; +import org.apache.tuscany.core.implementation.system.model.SystemBinding; +import org.apache.tuscany.core.implementation.system.model.SystemImplementation; +import org.apache.tuscany.core.mock.component.Source; +import org.apache.tuscany.core.mock.component.Target; +import org.apache.tuscany.core.mock.factories.MockComponentFactory; + +/** + * Validates that system builders and the default connector create properly wired contexts + * + * @version $$Rev$$ $$Date$$ + */ +public class SystemBuilderWireTestCase extends TestCase { + private DeploymentContext deploymentContext; + + /** + * Validates building a wire from an atomic context to an atomic context + */ + public void testAtomicWireBuild() throws Exception { + WorkContext work = new WorkContextImpl(); + ScopeContainer scope = new ModuleScopeContainer(work); + scope.start(); + + Connector connector = new ConnectorImpl(); + SystemComponentBuilder builder = new SystemComponentBuilder(); + + CompositeComponent parent = new CompositeComponentImpl(null, null, connector, null); + + ComponentDefinition<SystemImplementation> targetComponentDefinition = MockComponentFactory.createTarget(); + ComponentDefinition<SystemImplementation> sourceComponentDefinition = + MockComponentFactory.createSourceWithTargetReference(); + + AtomicComponent sourceComponent = builder.build(parent, sourceComponentDefinition, deploymentContext); + AtomicComponent targetComponent = builder.build(parent, targetComponentDefinition, deploymentContext); + + parent.register(sourceComponent); + parent.register(targetComponent); + parent.prepare(); + parent.start(); + scope.onEvent(new CompositeStart(this, parent)); + Source source = (Source) parent.getSystemChild("source").getServiceInstance(); + assertNotNull(source); + Target target = (Target) parent.getSystemChild("target").getServiceInstance(); + assertNotNull(target); + assertSame(target, source.getTarget()); + scope.onEvent(new CompositeStop(this, parent)); + parent.stop(); + scope.stop(); + } + + /** + * Validates building a wire from an atomic context to a reference context + */ + public void testAtomicToReferenceWireBuild() throws Exception { + WorkContext work = new WorkContextImpl(); + ScopeContainer scope = new ModuleScopeContainer(work); + scope.start(); + + Connector connector = new ConnectorImpl(); + SystemComponentBuilder builder = new SystemComponentBuilder(); + SystemBindingBuilder bindingBuilder = new SystemBindingBuilder(); + + CompositeComponent grandParent = new CompositeComponentImpl("grandparent", null, null, null); + CompositeComponent parent = new CompositeComponentImpl("parent", grandParent, null, null); + + // create a context in the grandparent that the reference will be autowired to + ComponentDefinition<SystemImplementation> targetComponentDefinition = MockComponentFactory.createTarget(); + AtomicComponent targetComponentComponent = builder.build(parent, targetComponentDefinition, deploymentContext); + grandParent.register(targetComponentComponent); + + BoundReferenceDefinition<SystemBinding> targetReferenceDefinition = MockComponentFactory.createBoundReference(); + ComponentDefinition<SystemImplementation> sourceComponentDefinition = + MockComponentFactory.createSourceWithTargetReference(); + + AtomicComponent sourceComponent = builder.build(parent, sourceComponentDefinition, deploymentContext); + Reference reference = bindingBuilder.build(parent, targetReferenceDefinition, deploymentContext); + + parent.register(sourceComponent); + parent.register(reference); + connector.connect(reference.getInboundWire(), reference.getOutboundWire(), true); + connector.connect(sourceComponent); + grandParent.register(parent); + grandParent.start(); + scope.onEvent(new CompositeStart(this, parent)); + Source source = (Source) parent.getSystemChild("source").getServiceInstance(); + assertNotNull(source); + Target target = (Target) parent.getSystemChild("target").getServiceInstance(); + assertNotNull(target); + assertSame(target, source.getTarget()); + scope.onEvent(new CompositeStop(this, parent)); + grandParent.stop(); + scope.stop(); + } + + + /** + * Validates building a wire from a service context to an atomic context + */ + public void testServiceToAtomicWireBuild() throws Exception { + WorkContext work = new WorkContextImpl(); + ScopeContainer scope = new ModuleScopeContainer(work); + scope.start(); + + ConnectorImpl connector = new ConnectorImpl(); + SystemComponentBuilder builder = new SystemComponentBuilder(); + SystemBindingBuilder bindingBuilder = new SystemBindingBuilder(); + + CompositeComponent parent = new CompositeComponentImpl(null, null, null, null); + + BoundServiceDefinition<SystemBinding> serviceDefinition = MockComponentFactory.createBoundService(); + ComponentDefinition<SystemImplementation> componentDefinition = MockComponentFactory.createTarget(); + + AtomicComponent sourceComponent = builder.build(parent, componentDefinition, deploymentContext); + parent.register(sourceComponent); + + Service service = bindingBuilder.build(parent, serviceDefinition, deploymentContext); + parent.register(service); + + connector.connect(sourceComponent); + connector.connect(service); + + parent.start(); + scope.onEvent(new CompositeStart(this, parent)); + Target target = (Target) parent.getSystemChild("serviceDefinition").getServiceInstance(); + assertNotNull(target); + Target target2 = (Target) parent.getSystemChild("target").getServiceInstance(); + assertNotNull(target); + assertSame(target, target2); + scope.onEvent(new CompositeStop(this, parent)); + parent.stop(); + scope.stop(); + + } + + protected void setUp() throws Exception { + super.setUp(); + ModuleScopeContainer moduleScope = new ModuleScopeContainer(); + moduleScope.start(); + deploymentContext = new RootDeploymentContext(null, null, moduleScope, null); + + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/loader/ComponentLoaderTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/loader/ComponentLoaderTestCase.java new file mode 100644 index 0000000000..7fbda2baf9 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/loader/ComponentLoaderTestCase.java @@ -0,0 +1,137 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.loader; + +import static org.easymock.EasyMock.createMock; +import static org.easymock.EasyMock.expect; +import static org.easymock.EasyMock.replay; +import static org.osoa.sca.Version.XML_NAMESPACE_1_0; + +import javax.xml.namespace.QName; +import javax.xml.stream.XMLStreamConstants; +import javax.xml.stream.XMLStreamException; +import javax.xml.stream.XMLStreamReader; + +import junit.framework.TestCase; + +import org.apache.tuscany.core.implementation.java.JavaImplementation; +import org.apache.tuscany.spi.component.CompositeComponent; +import org.apache.tuscany.spi.deployer.DeploymentContext; +import org.apache.tuscany.spi.implementation.java.PojoComponentType; +import org.apache.tuscany.spi.loader.LoaderException; +import org.apache.tuscany.spi.loader.LoaderRegistry; +import org.apache.tuscany.spi.loader.PropertyObjectFactory; +import org.apache.tuscany.spi.model.ComponentDefinition; +import org.apache.tuscany.spi.model.Implementation; +import org.apache.tuscany.spi.model.Property; +import org.apache.tuscany.spi.model.ReferenceDefinition; +import org.apache.tuscany.spi.model.ServiceDefinition; +import org.easymock.EasyMock; + +/** + * @version $Rev$ $Date$ + */ +public class ComponentLoaderTestCase extends TestCase { + private static final QName COMPONENT = new QName(XML_NAMESPACE_1_0, "component"); + private static final String NAME = "testComponent"; + private static final Implementation IMPL = new JavaImplementation(); + + private XMLStreamReader mockReader; + private LoaderRegistry mockRegistry; + private PropertyObjectFactory mockPropertyFactory; + private ComponentLoader loader; + + public void testEmptyComponent() throws LoaderException, XMLStreamException { + EasyMock.expect(mockReader.getName()).andReturn(COMPONENT).atLeastOnce(); + EasyMock.expect(mockReader.getAttributeValue((String) EasyMock.isNull(), EasyMock.isA(String.class))) + .andReturn(NAME); + EasyMock.expect(mockReader.getAttributeValue((String) EasyMock.isNull(), EasyMock.eq("initLevel"))) + .andReturn(null); + EasyMock.expect(mockReader.getAttributeValue(EasyMock.isA(String.class), EasyMock.isA(String.class))) + .andReturn(null); + EasyMock.expect(mockReader.nextTag()).andReturn(0); + EasyMock.expect(mockReader.next()).andReturn(XMLStreamConstants.END_ELEMENT); + EasyMock.replay(mockReader); + mockRegistry.loadComponentType(EasyMock.isA(CompositeComponent.class), + EasyMock.isA(Implementation.class), + EasyMock.isA(DeploymentContext.class)); + + EasyMock.expect(mockRegistry.load(EasyMock.isA(CompositeComponent.class), + EasyMock.eq(mockReader), + EasyMock.isA(DeploymentContext.class))).andReturn(IMPL); + EasyMock.replay(mockRegistry); + ComponentDefinition component = loader.load(EasyMock.createNiceMock(CompositeComponent.class), + mockReader, + EasyMock.createNiceMock(DeploymentContext.class)); + assertEquals(NAME, component.getName()); + assertNull(component.getInitLevel()); + } + + public void testInitValue20() throws LoaderException, XMLStreamException { + EasyMock.expect(mockReader.getName()).andReturn(COMPONENT).atLeastOnce(); + EasyMock.expect(mockReader.getAttributeValue((String) EasyMock.isNull(), EasyMock.isA(String.class))) + .andReturn(NAME); + EasyMock.expect(mockReader.getAttributeValue((String) EasyMock.isNull(), EasyMock.eq("initLevel"))) + .andReturn("20"); + EasyMock.expect(mockReader.nextTag()).andReturn(0); + EasyMock.expect(mockReader.next()).andReturn(XMLStreamConstants.END_ELEMENT); + EasyMock.replay(mockReader); + + mockRegistry.loadComponentType(EasyMock.isA(CompositeComponent.class), + EasyMock.isA(Implementation.class), + EasyMock.isA(DeploymentContext.class)); + EasyMock.expect(mockRegistry.load(EasyMock.isA(CompositeComponent.class), + EasyMock.eq(mockReader), + EasyMock.isA(DeploymentContext.class))).andReturn(IMPL); + EasyMock.replay(mockRegistry); + ComponentDefinition component = loader.load(EasyMock.createNiceMock(CompositeComponent.class), + mockReader, + EasyMock.createNiceMock(DeploymentContext.class)); + assertEquals(NAME, component.getName()); + assertEquals(Integer.valueOf(20), component.getInitLevel()); + } + + public void testLoadPropertyWithSource() throws LoaderException, XMLStreamException { + PojoComponentType<?, ?, Property<?>> type = + new PojoComponentType<ServiceDefinition, ReferenceDefinition, Property<?>>(); + Property property = new Property(); + property.setName("name"); + type.add(property); + JavaImplementation impl = new JavaImplementation(); + impl.setComponentType(type); + ComponentDefinition<?> defn = new ComponentDefinition<JavaImplementation>(impl); + XMLStreamReader reader = createMock(XMLStreamReader.class); + expect(reader.getAttributeValue(null, "name")).andReturn("name"); + expect(reader.getAttributeValue(null, "source")).andReturn("$source"); + expect(reader.getAttributeValue(null, "file")).andReturn(null); + expect(reader.next()).andReturn(XMLStreamConstants.END_ELEMENT); + replay(reader); + loader.loadProperty(reader, null, defn); + assertEquals("$source", defn.getPropertyValues().get("name").getSource()); + EasyMock.verify(reader); + } + + protected void setUp() throws Exception { + super.setUp(); + mockReader = EasyMock.createMock(XMLStreamReader.class); + mockRegistry = EasyMock.createMock(LoaderRegistry.class); + mockPropertyFactory = EasyMock.createMock(PropertyObjectFactory.class); + loader = new ComponentLoader(mockRegistry, mockPropertyFactory); + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/loader/IncludeLoaderTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/loader/IncludeLoaderTestCase.java new file mode 100644 index 0000000000..38f1122004 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/loader/IncludeLoaderTestCase.java @@ -0,0 +1,164 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.loader; + +import java.net.URL; +import javax.xml.namespace.QName; +import static javax.xml.stream.XMLStreamConstants.END_ELEMENT; +import javax.xml.stream.XMLStreamException; +import javax.xml.stream.XMLStreamReader; + +import junit.framework.TestCase; +import static org.easymock.EasyMock.createMock; +import static org.easymock.EasyMock.eq; +import static org.easymock.EasyMock.expect; +import static org.easymock.EasyMock.isA; +import static org.easymock.EasyMock.isNull; +import static org.easymock.EasyMock.replay; +import static org.easymock.EasyMock.verify; +import org.osoa.sca.Version; + +import org.apache.tuscany.spi.component.CompositeComponent; +import org.apache.tuscany.spi.deployer.DeploymentContext; +import org.apache.tuscany.spi.loader.LoaderException; +import org.apache.tuscany.spi.loader.LoaderRegistry; +import org.apache.tuscany.spi.loader.MissingIncludeException; +import org.apache.tuscany.spi.model.CompositeComponentType; +import org.apache.tuscany.spi.model.Include; + +/** + * @version $Rev$ $Date$ + */ +public class IncludeLoaderTestCase extends TestCase { + private static final QName INCLUDE = new QName(Version.XML_NAMESPACE_1_0, "include"); + + private LoaderRegistry registry; + private IncludeLoader loader; + private XMLStreamReader reader; + private DeploymentContext context; + private URL base; + private URL includeURL; + private ClassLoader cl; + + public void testNoLocation() throws LoaderException, XMLStreamException { + String name = "foo"; + expect(reader.getName()).andReturn(INCLUDE); + expect(reader.getAttributeValue(null, "name")).andReturn(name); + expect(reader.getAttributeValue(null, "scdlLocation")).andReturn(null); + expect(reader.getAttributeValue(null, "scdlResource")).andReturn(null); + expect(reader.next()).andReturn(END_ELEMENT); + + expect(context.getClassLoader()).andReturn(cl); + replay(registry, reader, context); + + try { + loader.load(null, reader, context); + fail(); + } catch (MissingIncludeException e) { + // OK expected + } + verify(registry, reader, context); + } + + public void testWithAbsoluteScdlLocation() throws LoaderException, XMLStreamException { + String name = "foo"; + expect(reader.getName()).andReturn(INCLUDE); + expect(reader.getAttributeValue(null, "name")).andReturn(name); + expect(reader.getAttributeValue(null, "scdlLocation")).andReturn("http://example.com/include.scdl"); + expect(reader.getAttributeValue(null, "scdlResource")).andReturn(null); + expect(reader.next()).andReturn(END_ELEMENT); + + expect(context.getScdlLocation()).andReturn(base); + expect(context.getClassLoader()).andReturn(cl); + + expect(registry.load((CompositeComponent) isNull(), + eq(includeURL), + eq(CompositeComponentType.class), + isA(DeploymentContext.class))) + .andReturn(null); + replay(registry, reader, context); + + Include include = loader.load(null, reader, context); + assertEquals(name, include.getName()); + assertEquals(includeURL, include.getScdlLocation()); + verify(registry, reader, context); + } + + public void testWithRelativeScdlLocation() throws LoaderException, XMLStreamException { + String name = "foo"; + expect(reader.getName()).andReturn(INCLUDE); + expect(reader.getAttributeValue(null, "name")).andReturn(name); + expect(reader.getAttributeValue(null, "scdlLocation")).andReturn("include.scdl"); + expect(reader.getAttributeValue(null, "scdlResource")).andReturn(null); + expect(reader.next()).andReturn(END_ELEMENT); + + expect(context.getScdlLocation()).andReturn(base); + expect(context.getClassLoader()).andReturn(cl); + + expect(registry.load((CompositeComponent) isNull(), + eq(includeURL), + eq(CompositeComponentType.class), + isA(DeploymentContext.class))) + .andReturn(null); + replay(registry, reader, context); + + Include include = loader.load(null, reader, context); + assertEquals(name, include.getName()); + assertEquals(includeURL, include.getScdlLocation()); + verify(registry, reader, context); + } + + public void testWithScdlResource() throws LoaderException, XMLStreamException { + String name = "foo"; + String resource = "org/apache/tuscany/core/loader/test-include.scdl"; + includeURL = cl.getResource(resource); + assertNotNull(includeURL); + + expect(reader.getName()).andReturn(INCLUDE); + expect(reader.getAttributeValue(null, "name")).andReturn(name); + expect(reader.getAttributeValue(null, "scdlLocation")).andReturn(null); + expect(reader.getAttributeValue(null, "scdlResource")).andReturn(resource); + expect(reader.next()).andReturn(END_ELEMENT); + + expect(context.getClassLoader()).andReturn(cl); + + expect(registry.load((CompositeComponent) isNull(), + eq(includeURL), + eq(CompositeComponentType.class), + isA(DeploymentContext.class))) + .andReturn(null); + replay(registry, reader, context); + + Include include = loader.load(null, reader, context); + assertEquals(name, include.getName()); + assertEquals(includeURL, include.getScdlLocation()); + verify(registry, reader, context); + } + + protected void setUp() throws Exception { + super.setUp(); + registry = createMock(LoaderRegistry.class); + reader = createMock(XMLStreamReader.class); + context = createMock(DeploymentContext.class); + cl = getClass().getClassLoader(); + base = new URL("http://example.com/test.scdl"); + includeURL = new URL("http://example.com/include.scdl"); + loader = new IncludeLoader(registry); + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/loader/JNDIPropertyFactoryTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/loader/JNDIPropertyFactoryTestCase.java new file mode 100644 index 0000000000..fb5bfd32d3 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/loader/JNDIPropertyFactoryTestCase.java @@ -0,0 +1,81 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.loader; + +import java.lang.reflect.Type; +import java.util.Hashtable; +import javax.naming.Context; +import javax.naming.NamingException; +import javax.naming.spi.InitialContextFactory; + +import org.w3c.dom.Document; +import org.w3c.dom.Element; + +import org.apache.tuscany.spi.model.PropertyValue; + +import junit.framework.TestCase; +import org.apache.tuscany.core.injection.JNDIObjectFactory; +import org.easymock.EasyMock; + +/** + * @version $Rev$ $Date$ + */ +public class JNDIPropertyFactoryTestCase extends TestCase { + + public void testCreate() throws Exception { + String old = System.getProperty(Context.INITIAL_CONTEXT_FACTORY); + try { + System.setProperty(Context.INITIAL_CONTEXT_FACTORY, MockInitialContextFactory.class.getName()); + JNDIPropertyFactory factory = new JNDIPropertyFactory(); + Element element = EasyMock.createMock(Element.class); + EasyMock.expect(element.getTextContent()).andReturn("foo"); + EasyMock.replay(element); + Document doc = EasyMock.createMock(Document.class); + EasyMock.expect(doc.getDocumentElement()).andReturn(element); + EasyMock.replay(doc); + PropertyValue<?> value = new MockPropertyValue<Type>(); + value.setValue(doc); + JNDIObjectFactory<?> jndiFactory = (JNDIObjectFactory<?>) factory.createObjectFactory(null, value); + assertEquals("bar", jndiFactory.getInstance()); + } finally { + System.clearProperty(Context.INITIAL_CONTEXT_FACTORY); + if (old != null) { + System.setProperty(Context.INITIAL_CONTEXT_FACTORY, old); + } + } + + } + + private class MockPropertyValue<T> extends PropertyValue<T> { + + } + + public static class MockInitialContextFactory implements InitialContextFactory { + public MockInitialContextFactory() { + } + + public Context getInitialContext(Hashtable<?, ?> environment) throws NamingException { + Context context = EasyMock.createMock(Context.class); + EasyMock.expect(context.lookup("foo")).andReturn("bar"); + EasyMock.replay(context); + return context; + } + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/loader/PropertyParsingTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/loader/PropertyParsingTestCase.java new file mode 100644 index 0000000000..080bc25039 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/loader/PropertyParsingTestCase.java @@ -0,0 +1,76 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.loader; + +import java.io.StringReader; +import javax.xml.stream.XMLInputFactory; +import javax.xml.stream.XMLStreamReader; +import javax.xml.stream.XMLStreamException; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.DocumentBuilder; + +import junit.framework.TestCase; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.NodeList; + +/** + * @version $Rev$ $Date$ + */ +public class PropertyParsingTestCase extends TestCase { + private XMLInputFactory xmlFactory; + private DocumentBuilder docBuilder; + private Element root; + + public void testComplexProperty() throws XMLStreamException { + String xml = "<property xmlns:foo='http://foo.com'>" + + "<foo:a>aValue</foo:a>" + + "<foo:b>InterestingURI</foo:b>" + + "</property>"; + + XMLStreamReader reader = getReader(xml); + StAXUtil.loadPropertyValue(reader, root); + NodeList childNodes = root.getChildNodes(); + assertEquals(2, childNodes.getLength()); + + Element e = (Element) childNodes.item(0); + assertEquals("http://foo.com", e.getNamespaceURI()); + assertEquals("a", e.getLocalName()); + assertEquals("aValue", e.getTextContent()); + e = (Element) childNodes.item(1); + assertEquals("http://foo.com", e.getNamespaceURI()); + assertEquals("b", e.getLocalName()); + assertEquals("InterestingURI", e.getTextContent()); + } + + public XMLStreamReader getReader(String xml) throws XMLStreamException { + XMLStreamReader reader = xmlFactory.createXMLStreamReader(new StringReader(xml)); + reader.next(); + return reader; + } + + protected void setUp() throws Exception { + super.setUp(); + xmlFactory = XMLInputFactory.newInstance(); + DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); + docBuilder = docFactory.newDocumentBuilder(); + Document doc = docBuilder.newDocument(); + root = doc.createElement("value"); + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/loader/ServiceLoaderTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/loader/ServiceLoaderTestCase.java new file mode 100644 index 0000000000..bcf153290a --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/loader/ServiceLoaderTestCase.java @@ -0,0 +1,103 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.loader; + +import javax.xml.namespace.QName; +import static javax.xml.stream.XMLStreamConstants.END_ELEMENT; +import static javax.xml.stream.XMLStreamConstants.START_ELEMENT; +import javax.xml.stream.XMLStreamException; +import javax.xml.stream.XMLStreamReader; + +import static org.osoa.sca.Version.XML_NAMESPACE_1_0; + +import org.apache.tuscany.spi.deployer.DeploymentContext; +import org.apache.tuscany.spi.loader.LoaderException; +import org.apache.tuscany.spi.loader.LoaderRegistry; +import org.apache.tuscany.spi.model.ServiceContract; +import org.apache.tuscany.spi.model.ServiceDefinition; + +import junit.framework.TestCase; +import org.apache.tuscany.core.deployer.RootDeploymentContext; +import org.easymock.EasyMock; +import static org.easymock.EasyMock.expect; +import static org.easymock.EasyMock.replay; + +/** + * Verifies loading of a service definition from an XML-based assembly + * + * @version $Rev$ $Date$ + */ +public class ServiceLoaderTestCase extends TestCase { + private static final QName SERVICE = new QName(XML_NAMESPACE_1_0, "service"); + private static final QName REFERENCE = new QName(XML_NAMESPACE_1_0, "reference"); + private static final QName INTERFACE_JAVA = new QName(XML_NAMESPACE_1_0, "interface.java"); + + private ServiceLoader loader; + private DeploymentContext deploymentContext; + private XMLStreamReader mockReader; + private LoaderRegistry mockRegistry; + + public void testWithNoInterface() throws LoaderException, XMLStreamException { + String name = "serviceDefinition"; +// String target = "target"; + expect(mockReader.getName()).andReturn(SERVICE).anyTimes(); + expect(mockReader.getAttributeValue(null, "name")).andReturn(name); + expect(mockReader.next()).andReturn(END_ELEMENT); + expect(mockReader.getName()).andReturn(SERVICE).anyTimes(); + replay(mockReader); + ServiceDefinition serviceDefinition = loader.load(null, mockReader, null); + assertNotNull(serviceDefinition); + assertEquals(name, serviceDefinition.getName()); + } + + public void testWithInterface() throws LoaderException, XMLStreamException { + String name = "serviceDefinition"; + String target = "target"; + ServiceContract sc = new ServiceContract() { + }; + expect(mockReader.getName()).andReturn(SERVICE).anyTimes(); + expect(mockReader.getAttributeValue(null, "name")).andReturn(name); + expect(mockReader.next()).andReturn(START_ELEMENT); + expect(mockReader.getName()).andReturn(INTERFACE_JAVA); + expect(mockRegistry.load(null, mockReader, deploymentContext)).andReturn(sc); + expect(mockReader.next()).andReturn(START_ELEMENT); + expect(mockReader.getName()).andReturn(REFERENCE); + expect(mockReader.getElementText()).andReturn(target); + expect(mockReader.next()).andReturn(END_ELEMENT); + expect(mockReader.getName()).andReturn(REFERENCE); + expect(mockReader.next()).andReturn(END_ELEMENT); + expect(mockReader.getName()).andReturn(SERVICE); + + replay(mockReader); + replay(mockRegistry); + + ServiceDefinition serviceDefinition = loader.load(null, mockReader, deploymentContext); + assertNotNull(serviceDefinition); + assertEquals(name, serviceDefinition.getName()); + assertSame(sc, serviceDefinition.getServiceContract()); + } + + protected void setUp() throws Exception { + super.setUp(); + mockReader = EasyMock.createStrictMock(XMLStreamReader.class); + mockRegistry = EasyMock.createMock(LoaderRegistry.class); + loader = new ServiceLoader(mockRegistry); + deploymentContext = new RootDeploymentContext(null, null, null, null); + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/loader/StAXLoaderRegistryImplTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/loader/StAXLoaderRegistryImplTestCase.java new file mode 100644 index 0000000000..0d7c47774e --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/loader/StAXLoaderRegistryImplTestCase.java @@ -0,0 +1,112 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.loader; + +import javax.xml.namespace.QName; +import javax.xml.stream.XMLStreamException; +import javax.xml.stream.XMLStreamReader; + +import org.apache.tuscany.spi.component.CompositeComponent; +import org.apache.tuscany.spi.deployer.DeploymentContext; +import org.apache.tuscany.spi.loader.LoaderException; +import org.apache.tuscany.spi.loader.StAXElementLoader; +import org.apache.tuscany.spi.loader.UnrecognizedElementException; +import org.apache.tuscany.spi.model.ModelObject; + +import junit.framework.TestCase; +import org.apache.tuscany.core.deployer.RootDeploymentContext; +import org.easymock.classextension.EasyMock; + +/** + * Verifies the default loader registry + * + * @version $Rev$ $Date$ + */ +public class StAXLoaderRegistryImplTestCase extends TestCase { + private LoaderRegistryImpl registry; + private QName name; + private LoaderRegistryImpl.Monitor mockMonitor; + private StAXElementLoader<ModelObject> mockLoader; + private XMLStreamReader mockReader; + private DeploymentContext deploymentContext; + private ModelObject modelObject; + + public void testLoaderRegistration() { + mockMonitor.registeringLoader(EasyMock.eq(name)); + EasyMock.replay(mockMonitor); + registry.registerLoader(name, mockLoader); + EasyMock.verify(mockMonitor); + } + + public void testLoaderUnregistration() { + mockMonitor.unregisteringLoader(EasyMock.eq(name)); + EasyMock.replay(mockMonitor); + registry.unregisterLoader(name, (StAXElementLoader<ModelObject>) mockLoader); + EasyMock.verify(mockMonitor); + } + + public void testSuccessfulDispatch() throws LoaderException, XMLStreamException { + EasyMock.expect(mockReader.getName()).andReturn(name); + EasyMock.replay(mockReader); + mockMonitor.registeringLoader(EasyMock.eq(name)); + mockMonitor.elementLoad(EasyMock.eq(name)); + EasyMock.replay(mockMonitor); + EasyMock.expect(mockLoader.load(EasyMock.isA(CompositeComponent.class), + EasyMock.eq(mockReader), + EasyMock.eq(deploymentContext))).andReturn(modelObject); + EasyMock.replay(mockLoader); + registry.registerLoader(name, (StAXElementLoader<ModelObject>) mockLoader); + CompositeComponent parent = EasyMock.createNiceMock(CompositeComponent.class); + assertSame(modelObject, registry.load(parent, mockReader, deploymentContext)); + EasyMock.verify(mockLoader); + EasyMock.verify(mockMonitor); + EasyMock.verify(mockReader); + + } + + public void testUnsuccessfulDispatch() throws LoaderException, XMLStreamException { + EasyMock.expect(mockReader.getName()).andReturn(name); + EasyMock.replay(mockReader); + mockMonitor.elementLoad(EasyMock.eq(name)); + EasyMock.replay(mockMonitor); + try { + registry.load(null, mockReader, deploymentContext); + fail(); + } catch (UnrecognizedElementException e) { + assertSame(name, e.getElement()); + } + EasyMock.verify(mockReader); + EasyMock.verify(mockMonitor); + } + + @SuppressWarnings("unchecked") + protected void setUp() throws Exception { + super.setUp(); + name = new QName("http://mock", "test"); + deploymentContext = new RootDeploymentContext(null, null, null, null); + registry = new LoaderRegistryImpl(); + mockMonitor = EasyMock.createMock(LoaderRegistryImpl.Monitor.class); + registry.setMonitor(mockMonitor); + + mockLoader = EasyMock.createMock(StAXElementLoader.class); + mockReader = EasyMock.createMock(XMLStreamReader.class); + modelObject = new ModelObject() { + }; + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/loader/StringParserPropertyFactoryTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/loader/StringParserPropertyFactoryTestCase.java new file mode 100644 index 0000000000..4445dfad2c --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/loader/StringParserPropertyFactoryTestCase.java @@ -0,0 +1,128 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.loader; + +import org.w3c.dom.Document; +import org.w3c.dom.Element; + +import org.apache.tuscany.spi.ObjectFactory; +import org.apache.tuscany.spi.model.Property; +import org.apache.tuscany.spi.model.PropertyValue; + +import junit.framework.TestCase; +import org.easymock.EasyMock; + +/** + * @version $Rev$ $Date$ + */ +public class StringParserPropertyFactoryTestCase extends TestCase { + + private <T> PropertyValue<T> mock(String value) { + Document document = EasyMock.createMock(Document.class); + Element element = EasyMock.createMock(Element.class); + EasyMock.expect(document.getDocumentElement()).andReturn(element); + EasyMock.expect(element.getTextContent()).andReturn(value); + EasyMock.replay(document, element); + return new PropertyValue<T>(null, document); + } + + public void testInteger() throws Exception { + + StringParserPropertyFactory factory = new StringParserPropertyFactory(); + Property<Integer> property = new Property<Integer>(); + property.setJavaType(Integer.class); + PropertyValue<Integer> propertyValue = mock("1"); + ObjectFactory<Integer> oFactory = factory.createObjectFactory(property, propertyValue); + assertEquals(1, oFactory.getInstance().intValue()); + } + + public void testPrimitiveInt() throws Exception { + StringParserPropertyFactory factory = new StringParserPropertyFactory(); + Property<Integer> property = new Property<Integer>(); + property.setJavaType(Integer.TYPE); + PropertyValue<Integer> propertyValue = mock("1"); + ObjectFactory<Integer> oFactory = factory.createObjectFactory(property, propertyValue); + assertEquals(1, oFactory.getInstance().intValue()); + } + + public void testString() throws Exception { + StringParserPropertyFactory factory = new StringParserPropertyFactory(); + Property<String> property = new Property<String>(); + property.setJavaType(String.class); + PropertyValue<String> propertyValue = mock("1"); + ObjectFactory<String> oFactory = factory.createObjectFactory(property, propertyValue); + assertEquals("1", oFactory.getInstance()); + } + + public void testByteArray() throws Exception { + StringParserPropertyFactory factory = new StringParserPropertyFactory(); + Property<byte[]> property = new Property<byte[]>(); + property.setJavaType(byte[].class); + PropertyValue<byte[]> propertyValue = mock("1"); + ObjectFactory<byte[]> oFactory = factory.createObjectFactory(property, propertyValue); + byte[] result = oFactory.getInstance(); + byte[] expected = "1".getBytes(); + for (int i = 0; i < result.length; i++) { + byte b = result[i]; + if (b != expected[i]) { + fail(); + } + } + } + + public void testBoolean() throws Exception { + StringParserPropertyFactory factory = new StringParserPropertyFactory(); + Property<Boolean> property = new Property<Boolean>(); + property.setJavaType(Boolean.class); + PropertyValue<Boolean> propertyValue = mock("true"); + ObjectFactory<Boolean> oFactory = factory.createObjectFactory(property, propertyValue); + assertTrue(oFactory.getInstance()); + } + + public void testPrimitiveBoolean() throws Exception { + StringParserPropertyFactory factory = new StringParserPropertyFactory(); + Property<Boolean> property = new Property<Boolean>(); + property.setJavaType(Boolean.TYPE); + PropertyValue<Boolean> propertyValue = mock("true"); + ObjectFactory<Boolean> oFactory = factory.createObjectFactory(property, propertyValue); + assertTrue(oFactory.getInstance()); + } + + public void testStringConstructor() throws Exception { + StringParserPropertyFactory factory = new StringParserPropertyFactory(); + Property<Foo> property = new Property<Foo>(); + property.setJavaType(Foo.class); + PropertyValue<Foo> propertyValue = mock("test"); + ObjectFactory<Foo> oFactory = factory.createObjectFactory(property, propertyValue); + assertEquals("test", oFactory.getInstance().getFoo()); + } + + private static class Foo { + private String foo; + + public Foo(String foo) { + this.foo = foo; + } + + public String getFoo() { + return foo; + } + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/mock/component/BadContextPojo.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/mock/component/BadContextPojo.java new file mode 100644 index 0000000000..214378b2c9 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/mock/component/BadContextPojo.java @@ -0,0 +1,28 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.mock.component; + +import org.osoa.sca.annotations.Context; + +public class BadContextPojo { + + @Context + String moduleContext; + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/mock/component/BadNamePojo.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/mock/component/BadNamePojo.java new file mode 100644 index 0000000000..77ec37f9e4 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/mock/component/BadNamePojo.java @@ -0,0 +1,26 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.mock.component; + +import org.osoa.sca.annotations.ComponentName; + +public class BadNamePojo { + @ComponentName + private int name; +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/mock/component/BasicInterface.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/mock/component/BasicInterface.java new file mode 100644 index 0000000000..b7921c248f --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/mock/component/BasicInterface.java @@ -0,0 +1,30 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.mock.component; + +/** + * @version $Rev$ $Date$ + */ +public interface BasicInterface { + String returnsProperty(); + + BasicInterface returnsReference(); + + int returnsInt(); +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/mock/component/BasicInterfaceImpl.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/mock/component/BasicInterfaceImpl.java new file mode 100644 index 0000000000..c2ca45ec17 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/mock/component/BasicInterfaceImpl.java @@ -0,0 +1,61 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.mock.component; + +import org.osoa.sca.annotations.Property; +import org.osoa.sca.annotations.Reference; + +/** + * @version $Rev$ $Date$ + */ +public class BasicInterfaceImpl implements BasicInterface { + + @Property + public String publicProperty; + @Reference + public BasicInterface publicReference; + @Property + protected String protectedProperty; + @Reference + protected BasicInterface protectedReference; + private String privateProperty; + private BasicInterface privateReference; + + @Property + public void setPrivateProperty(String privateProperty) { + this.privateProperty = privateProperty; + } + + @Reference + public void setPrivateReference(BasicInterface privateReference) { + this.privateReference = privateReference; + } + + public String returnsProperty() { + return privateProperty; + } + + public BasicInterface returnsReference() { + return privateReference; + } + + public int returnsInt() { + return 0; + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/mock/component/ModuleScopeComponent.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/mock/component/ModuleScopeComponent.java new file mode 100644 index 0000000000..5b63caf286 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/mock/component/ModuleScopeComponent.java @@ -0,0 +1,31 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.mock.component; + +import org.osoa.sca.annotations.Scope; + +/** + * @version $Rev$ $Date$ + */ +@Scope("MODULE") +public interface ModuleScopeComponent { + + //public boolean isInit(); +} + diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/mock/component/ModuleScopeComponentImpl.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/mock/component/ModuleScopeComponentImpl.java new file mode 100644 index 0000000000..5febc32ce6 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/mock/component/ModuleScopeComponentImpl.java @@ -0,0 +1,40 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.mock.component; + +import org.osoa.sca.annotations.Scope; + + +/** + * @version $Rev$ $Date$ + */ +@Scope("MODULE") +public class ModuleScopeComponentImpl implements + ModuleScopeComponent { + + private String foo; + + public void setFoo(String foo) { + this.foo = foo; + } + + public String getFoo() { + return foo; + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/mock/component/ModuleScopeDestroyOnlyComponent.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/mock/component/ModuleScopeDestroyOnlyComponent.java new file mode 100644 index 0000000000..886f3586f8 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/mock/component/ModuleScopeDestroyOnlyComponent.java @@ -0,0 +1,36 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.mock.component; + +import org.osoa.sca.annotations.Destroy; + +public class ModuleScopeDestroyOnlyComponent extends ModuleScopeComponentImpl { + + boolean destroyed; + + public boolean isDestroyed() { + return destroyed; + } + + @Destroy + public void destroy() { + destroyed = true; + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/mock/component/ModuleScopeEagerInitComponent.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/mock/component/ModuleScopeEagerInitComponent.java new file mode 100644 index 0000000000..a4cf75e8cb --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/mock/component/ModuleScopeEagerInitComponent.java @@ -0,0 +1,40 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.mock.component; + +import org.osoa.sca.annotations.Init; + +public class ModuleScopeEagerInitComponent extends ModuleScopeComponentImpl { + + boolean initialized; + // this value tests to ensure introspection can find the init() method even + // if a field is named the same. Ultimately, this should be in the + // introspection tests + private boolean init; + + public boolean isInitialized() { + return initialized; + } + + @Init(eager = true) + public void init() { + initialized = true; + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/mock/component/ModuleScopeEagerInitDestroyComponent.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/mock/component/ModuleScopeEagerInitDestroyComponent.java new file mode 100644 index 0000000000..4cb219958d --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/mock/component/ModuleScopeEagerInitDestroyComponent.java @@ -0,0 +1,35 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.mock.component; + +import org.osoa.sca.annotations.Destroy; + +public class ModuleScopeEagerInitDestroyComponent extends ModuleScopeEagerInitComponent { + + boolean destroyed; + + public boolean isDestroyed() { + return destroyed; + } + + @Destroy + public void destroy() { + destroyed = true; + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/mock/component/ModuleScopeInitDestroyComponent.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/mock/component/ModuleScopeInitDestroyComponent.java new file mode 100644 index 0000000000..323ebc636f --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/mock/component/ModuleScopeInitDestroyComponent.java @@ -0,0 +1,39 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.mock.component; + +import org.osoa.sca.annotations.Destroy; + +public class ModuleScopeInitDestroyComponent extends ModuleScopeInitOnlyComponent { + + boolean destroyed; + + public boolean isDestroyed() { + return destroyed; + } + + @Destroy + public void destroy() { + if (destroyed) { + throw new AssertionError("Destroy called more than once"); + } + destroyed = true; + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/mock/component/ModuleScopeInitOnlyComponent.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/mock/component/ModuleScopeInitOnlyComponent.java new file mode 100644 index 0000000000..723ee18fac --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/mock/component/ModuleScopeInitOnlyComponent.java @@ -0,0 +1,42 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.mock.component; + +import org.osoa.sca.annotations.Init; + +public class ModuleScopeInitOnlyComponent extends ModuleScopeComponentImpl { + + private boolean initialized; + // this value tests to ensure introspection can find the init() method even + // if a field is named the same. Ultimately, this should be in the introspection tests + private boolean init; + + public boolean isInitialized() { + return initialized; + } + + @Init + public void init() { + if (initialized) { + throw new AssertionError("Init called more than once"); + } + initialized = true; + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/mock/component/OrderException.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/mock/component/OrderException.java new file mode 100644 index 0000000000..af257c226d --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/mock/component/OrderException.java @@ -0,0 +1,40 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.mock.component; + +public class OrderException extends Exception { + + public OrderException() { + super(); + } + + public OrderException(String message) { + super(message); + } + + public OrderException(String message, Throwable cause) { + super(message, cause); + } + + public OrderException(Throwable cause) { + super(cause); + } + +} + diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/mock/component/OrderedDependentPojo.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/mock/component/OrderedDependentPojo.java new file mode 100644 index 0000000000..2033f0eca5 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/mock/component/OrderedDependentPojo.java @@ -0,0 +1,29 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.mock.component; + +/** + * @version $$Rev$$ $$Date$$ + */ +public interface OrderedDependentPojo extends OrderedInitPojo { + + OrderedInitPojo getPojo(); + + void setPojo(OrderedInitPojo pojo); +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/mock/component/OrderedDependentPojoImpl.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/mock/component/OrderedDependentPojoImpl.java new file mode 100644 index 0000000000..439c3d143c --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/mock/component/OrderedDependentPojoImpl.java @@ -0,0 +1,36 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.mock.component; + +/** + * @version $$Rev$$ $$Date$$ + */ +public class OrderedDependentPojoImpl extends OrderedInitPojoImpl implements OrderedDependentPojo { + + private OrderedInitPojo pojo; + + public OrderedInitPojo getPojo() { + return pojo; + } + + public void setPojo(OrderedInitPojo pojo) { + this.pojo = pojo; + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/mock/component/OrderedEagerInitPojo.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/mock/component/OrderedEagerInitPojo.java new file mode 100644 index 0000000000..815d9d6b12 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/mock/component/OrderedEagerInitPojo.java @@ -0,0 +1,58 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.mock.component; + +import org.osoa.sca.annotations.Destroy; +import org.osoa.sca.annotations.Init; +import org.osoa.sca.annotations.Scope; + +@Scope("MODULE") +public class OrderedEagerInitPojo { + + private static final Object LOCK = new Object(); + private static int numberInstantied; + private int initOrder; + + @Init(eager = true) + public void init() { + synchronized (LOCK) { + ++numberInstantied; + initOrder = numberInstantied; + } + } + + @Destroy + public void destroy() throws OrderException { + synchronized (LOCK) { + if (initOrder != numberInstantied) { + throw new OrderException("Instance shutdown done out of order"); + } + --numberInstantied; + } + } + + public int getNumberInstantiated() { + return numberInstantied; + } + + public int getInitOrder() { + return initOrder; + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/mock/component/OrderedInitPojo.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/mock/component/OrderedInitPojo.java new file mode 100644 index 0000000000..0b891cfa42 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/mock/component/OrderedInitPojo.java @@ -0,0 +1,28 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.mock.component; + +/** + * @version $$Rev$$ $$Date$$ + */ +public interface OrderedInitPojo { + int getNumberInstantiated(); + + int getInitOrder(); +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/mock/component/OrderedInitPojoImpl.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/mock/component/OrderedInitPojoImpl.java new file mode 100644 index 0000000000..53338f5613 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/mock/component/OrderedInitPojoImpl.java @@ -0,0 +1,58 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.mock.component; + +import org.osoa.sca.annotations.Destroy; +import org.osoa.sca.annotations.Init; +import org.osoa.sca.annotations.Scope; + +@Scope("MODULE") +public class OrderedInitPojoImpl implements OrderedInitPojo { + + private static final Object LOCK = new Object(); + private static int numberInstantied; + private int initOrder; + + @Init + public void init() { + synchronized (LOCK) { + ++numberInstantied; + initOrder = numberInstantied; + } + } + + @Destroy + public void destroy() throws OrderException { + synchronized (LOCK) { + if (initOrder != numberInstantied) { + throw new OrderException("Instance shutdown done out of order"); + } + --numberInstantied; + } + } + + public int getNumberInstantiated() { + return numberInstantied; + } + + public int getInitOrder() { + return initOrder; + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/mock/component/RequestScopeComponent.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/mock/component/RequestScopeComponent.java new file mode 100644 index 0000000000..8c7dc107ee --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/mock/component/RequestScopeComponent.java @@ -0,0 +1,30 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.mock.component; + +import org.osoa.sca.annotations.Scope; + +/** + * @version $Rev$ $Date$ + */ +@Scope("REQUEST") +public interface RequestScopeComponent { + +} + diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/mock/component/RequestScopeDestroyOnlyComponent.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/mock/component/RequestScopeDestroyOnlyComponent.java new file mode 100644 index 0000000000..5224ceda5f --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/mock/component/RequestScopeDestroyOnlyComponent.java @@ -0,0 +1,38 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.mock.component; + +import org.osoa.sca.annotations.Destroy; +import org.osoa.sca.annotations.Scope; + +@Scope("REQUEST") +public class RequestScopeDestroyOnlyComponent extends SessionScopeComponentImpl { + + boolean destroyed; + + public boolean isDestroyed() { + return destroyed; + } + + @Destroy + public void destroy() { + destroyed = true; + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/mock/component/RequestScopeInitDestroyComponent.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/mock/component/RequestScopeInitDestroyComponent.java new file mode 100644 index 0000000000..38b188a4b5 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/mock/component/RequestScopeInitDestroyComponent.java @@ -0,0 +1,38 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.mock.component; + +import org.osoa.sca.annotations.Destroy; +import org.osoa.sca.annotations.Scope; + +@Scope("REQUEST") +public class RequestScopeInitDestroyComponent extends SessionScopeInitOnlyComponent { + + boolean destroyed; + + public boolean isDestroyed() { + return destroyed; + } + + @Destroy + public void destroy() { + destroyed = true; + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/mock/component/RequestScopeInitOnlyComponent.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/mock/component/RequestScopeInitOnlyComponent.java new file mode 100644 index 0000000000..707f8ab50f --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/mock/component/RequestScopeInitOnlyComponent.java @@ -0,0 +1,39 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.mock.component; + +import org.osoa.sca.annotations.Init; +import org.osoa.sca.annotations.Scope; + +@Scope("REQUEST") +public class RequestScopeInitOnlyComponent extends SessionScopeComponentImpl { + + private boolean initialized; + + public boolean isInitialized() { + return initialized; + } + + @Init + public void init() { + initialized = true; + } + + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/mock/component/SessionScopeComponent.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/mock/component/SessionScopeComponent.java new file mode 100644 index 0000000000..827ba804f2 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/mock/component/SessionScopeComponent.java @@ -0,0 +1,30 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.mock.component; + +import org.osoa.sca.annotations.Scope; + +/** + * @version $Rev$ $Date$ + */ +@Scope("SESSION") +public interface SessionScopeComponent { + +} + diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/mock/component/SessionScopeComponentImpl.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/mock/component/SessionScopeComponentImpl.java new file mode 100644 index 0000000000..e547bf6113 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/mock/component/SessionScopeComponentImpl.java @@ -0,0 +1,30 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.mock.component; + +import org.osoa.sca.annotations.Scope; + +/** + * @version $Rev$ $Date$ + */ +@Scope("SESSION") +public class SessionScopeComponentImpl implements + SessionScopeComponent { + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/mock/component/SessionScopeInitDestroyComponent.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/mock/component/SessionScopeInitDestroyComponent.java new file mode 100644 index 0000000000..c11bd1bd49 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/mock/component/SessionScopeInitDestroyComponent.java @@ -0,0 +1,36 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.mock.component; + +import org.osoa.sca.annotations.Destroy; + +public class SessionScopeInitDestroyComponent extends SessionScopeInitOnlyComponent { + + private boolean destroyed; + + public boolean isDestroyed() { + return destroyed; + } + + @Destroy + public void destroy() { + destroyed = true; + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/mock/component/SessionScopeInitOnlyComponent.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/mock/component/SessionScopeInitOnlyComponent.java new file mode 100644 index 0000000000..095cc916ec --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/mock/component/SessionScopeInitOnlyComponent.java @@ -0,0 +1,37 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.mock.component; + +import org.osoa.sca.annotations.Init; + +public class SessionScopeInitOnlyComponent extends SessionScopeComponentImpl { + + private boolean initialized; + + public boolean isInitialized() { + return initialized; + } + + @Init + public void init() { + initialized = true; + } + + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/mock/component/SimpleTarget.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/mock/component/SimpleTarget.java new file mode 100644 index 0000000000..c78ba00a7a --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/mock/component/SimpleTarget.java @@ -0,0 +1,30 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.mock.component; + +public interface SimpleTarget { + + String hello(String message) throws Exception; + + String goodbye(String message) throws Exception; + + String echo(String message) throws Exception; + +} + diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/mock/component/SimpleTargetImpl.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/mock/component/SimpleTargetImpl.java new file mode 100644 index 0000000000..634a07a401 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/mock/component/SimpleTargetImpl.java @@ -0,0 +1,41 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.mock.component; + +public class SimpleTargetImpl implements SimpleTarget { + + public SimpleTargetImpl() { + super(); + } + + public String hello(String message) throws Exception { + return message; + } + + public String goodbye(String message) throws Exception { + return message; + } + + public String echo(String message) throws Exception { + return message; + } + + +} + diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/mock/component/Source.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/mock/component/Source.java new file mode 100644 index 0000000000..f7969f748b --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/mock/component/Source.java @@ -0,0 +1,37 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.mock.component; + +import java.util.List; + +/** + * Implementations are used in wiring tests + * + * @version $Rev$ $Date$ + */ +public interface Source { + + Target getTarget(); + + List<Target> getTargets(); + + List<Target> getTargetsThroughField(); + +} + diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/mock/component/SourceImpl.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/mock/component/SourceImpl.java new file mode 100644 index 0000000000..187e33b2bd --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/mock/component/SourceImpl.java @@ -0,0 +1,63 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.mock.component; + +import java.util.List; + +/** + * Mock system component implementation used in wiring tests + * + * @version $Rev$ $Date$ + */ +public class SourceImpl implements Source { + + private Target target; + private List<Target> targets; + private List<Target> targetsThroughField; + private Target[] targetsArray; + + public void setTarget(Target target) { + this.target = target; + } + + public Target getTarget() { + return target; + } + + public List<Target> getTargets() { + return targets; + } + + public void setTargets(List<Target> targets) { + this.targets = targets; + } + + public List<Target> getTargetsThroughField() { + return targetsThroughField; + } + + public Target[] getArrayOfTargets() { + return targetsArray; + } + + public void setArrayOfTargets(Target[] targets) { + targetsArray = targets; + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/mock/component/StatelessComponent.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/mock/component/StatelessComponent.java new file mode 100644 index 0000000000..c16ac942a3 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/mock/component/StatelessComponent.java @@ -0,0 +1,30 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.mock.component; + +import org.osoa.sca.annotations.Scope; + +/** + * @version $Rev$ $Date$ + */ +@Scope("STATELESS") +public interface StatelessComponent { + +} + diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/mock/component/StatelessComponentImpl.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/mock/component/StatelessComponentImpl.java new file mode 100644 index 0000000000..64a23c12c8 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/mock/component/StatelessComponentImpl.java @@ -0,0 +1,27 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.mock.component; + +/** + * @version $Rev$ $Date$ + */ +public class StatelessComponentImpl implements + StatelessComponent { + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/mock/component/Target.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/mock/component/Target.java new file mode 100644 index 0000000000..778c14665d --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/mock/component/Target.java @@ -0,0 +1,32 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.mock.component; + +/** + * Implementations are used in wiring tests + * + * @version $Rev$ $Date$ + */ +public interface Target { + + String getString(); + + void setString(String val); +} + diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/mock/component/TargetImpl.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/mock/component/TargetImpl.java new file mode 100644 index 0000000000..037dd3a37c --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/mock/component/TargetImpl.java @@ -0,0 +1,38 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.mock.component; + +/** + * Mock system component implementation used in wiring tests + * + * @version $Rev$ $Date$ + */ +public class TargetImpl implements Target { + + private String theString; + + public String getString() { + return theString; + } + + public void setString(String val) { + theString = val; + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/mock/factories/MockComponentFactory.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/mock/factories/MockComponentFactory.java new file mode 100644 index 0000000000..e6f1611d40 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/mock/factories/MockComponentFactory.java @@ -0,0 +1,180 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.mock.factories; + +import java.net.URI; +import java.net.URISyntaxException; + +import org.apache.tuscany.spi.idl.java.JavaServiceContract; +import org.apache.tuscany.spi.implementation.java.ConstructorDefinition; +import org.apache.tuscany.spi.implementation.java.JavaMappedProperty; +import org.apache.tuscany.spi.implementation.java.JavaMappedReference; +import org.apache.tuscany.spi.implementation.java.JavaMappedService; +import org.apache.tuscany.spi.implementation.java.PojoComponentType; +import org.apache.tuscany.spi.model.BoundReferenceDefinition; +import org.apache.tuscany.spi.model.BoundServiceDefinition; +import org.apache.tuscany.spi.model.ComponentDefinition; +import org.apache.tuscany.spi.model.ReferenceTarget; +import org.apache.tuscany.spi.model.Scope; +import org.apache.tuscany.spi.model.ServiceContract; + +import org.apache.tuscany.core.implementation.system.model.SystemBinding; +import org.apache.tuscany.core.implementation.system.model.SystemImplementation; +import org.apache.tuscany.core.mock.component.SourceImpl; +import org.apache.tuscany.core.mock.component.Target; +import org.apache.tuscany.core.mock.component.TargetImpl; + +/** + * @version $$Rev$$ $$Date$$ + */ +public final class MockComponentFactory { + + private MockComponentFactory() { + } + + /** + * Creates a component named "source" with a reference to target/Target + */ + public static ComponentDefinition<SystemImplementation> createSourceWithTargetReference() + throws NoSuchMethodException { + SystemImplementation impl = new SystemImplementation(); + PojoComponentType componentType = new PojoComponentType(); + componentType.setImplementationScope(Scope.MODULE); + componentType + .setConstructorDefinition( + new ConstructorDefinition<SourceImpl>(SourceImpl.class.getConstructor((Class[]) null))); + JavaMappedReference reference; + try { + reference = new JavaMappedReference(); + reference.setName("target"); + reference.setMember(SourceImpl.class.getMethod("setTarget", Target.class)); + JavaServiceContract contract = new JavaServiceContract(); + contract.setInterfaceClass(Target.class); + reference.setServiceContract(contract); + componentType.add(reference); + } catch (NoSuchMethodException e) { + throw new AssertionError(e); + } + impl.setComponentType(componentType); + impl.setImplementationClass(SourceImpl.class); + ComponentDefinition<SystemImplementation> sourceComponentDefinition = + new ComponentDefinition<SystemImplementation>(impl); + sourceComponentDefinition.setName("source"); + + ReferenceTarget referenceTarget = new ReferenceTarget(); + referenceTarget.setReferenceName("target"); + try { + referenceTarget.addTarget(new URI("target/Target")); + } catch (URISyntaxException e) { + throw new AssertionError(e); + } + sourceComponentDefinition.add(referenceTarget); + return sourceComponentDefinition; + } + + /** + * Creates a component named "source" with an autowire reference to {@link Target} + */ + public static ComponentDefinition<SystemImplementation> createSourceWithTargetAutowire() { + SystemImplementation impl = new SystemImplementation(); + PojoComponentType componentType = new PojoComponentType(); + componentType.setImplementationScope(Scope.MODULE); + JavaMappedReference reference; + try { + reference = new JavaMappedReference(); + reference.setName("target"); + reference.setMember(SourceImpl.class.getMethod("setTarget", Target.class)); + reference.setAutowire(true); + ServiceContract<?> contract = new JavaServiceContract(); + contract.setInterfaceClass(Target.class); + reference.setServiceContract(contract); + componentType.add(reference); + } catch (NoSuchMethodException e) { + throw new AssertionError(e); + } + impl.setComponentType(componentType); + impl.setImplementationClass(SourceImpl.class); + ComponentDefinition<SystemImplementation> sourceComponentDefinition = + new ComponentDefinition<SystemImplementation>(impl); + sourceComponentDefinition.setName("source"); + + ReferenceTarget referenceTarget = new ReferenceTarget(); + referenceTarget.setReferenceName("target"); + sourceComponentDefinition.add(referenceTarget); + return sourceComponentDefinition; + } + + /** + * Creates a component named "target" with a service named "Target" + */ + public static ComponentDefinition<SystemImplementation> createTarget() throws NoSuchMethodException { + SystemImplementation impl = new SystemImplementation(); + PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>> componentType = + new PojoComponentType<JavaMappedService, JavaMappedReference, JavaMappedProperty<?>>(); + componentType.setImplementationScope(Scope.MODULE); + componentType + .setConstructorDefinition( + new ConstructorDefinition<TargetImpl>(TargetImpl.class.getConstructor((Class[]) null))); + JavaMappedService targetServiceDefinition = new JavaMappedService(); + targetServiceDefinition.setName("Target"); + ServiceContract<?> contract = new JavaServiceContract(); + contract.setInterfaceClass(Target.class); + targetServiceDefinition.setServiceContract(contract); + componentType.add(targetServiceDefinition); + impl.setComponentType(componentType); + impl.setImplementationClass(TargetImpl.class); + ComponentDefinition<SystemImplementation> targetComponentDefinition = + new ComponentDefinition<SystemImplementation>(impl); + targetComponentDefinition.setName("target"); + return targetComponentDefinition; + } + + + public static BoundReferenceDefinition<SystemBinding> createBoundReference() { + SystemBinding binding = new SystemBinding(); + BoundReferenceDefinition<SystemBinding> referenceDefinition = new BoundReferenceDefinition<SystemBinding>(); + referenceDefinition.setBinding(binding); + referenceDefinition.setName("target"); + ServiceContract<?> contract = new JavaServiceContract(); + contract.setInterfaceClass(Target.class); + referenceDefinition.setServiceContract(contract); + return referenceDefinition; + } + + /** + * Creates a bound service with the name "service" that is configured to be wired to a target named "target/Target" + */ + public static BoundServiceDefinition<SystemBinding> createBoundService() { + SystemBinding binding = new SystemBinding(); + BoundServiceDefinition<SystemBinding> serviceDefinition = new BoundServiceDefinition<SystemBinding>(); + serviceDefinition.setBinding(binding); + serviceDefinition.setName("serviceDefinition"); + ServiceContract<?> contract = new JavaServiceContract(); + contract.setInterfaceClass(Target.class); + serviceDefinition.setServiceContract(contract); + try { + serviceDefinition.setTarget(new URI("target/Target")); + } catch (URISyntaxException e) { + throw new AssertionError(e); + } + return serviceDefinition; + } + + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/mock/factories/MockFactory.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/mock/factories/MockFactory.java new file mode 100644 index 0000000000..c06633c4f7 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/mock/factories/MockFactory.java @@ -0,0 +1,184 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.mock.factories; + +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.osoa.sca.annotations.Destroy; +import org.osoa.sca.annotations.Init; + +import org.apache.tuscany.spi.QualifiedName; +import org.apache.tuscany.spi.component.AtomicComponent; +import org.apache.tuscany.spi.component.ScopeContainer; +import org.apache.tuscany.spi.component.SystemAtomicComponent; +import org.apache.tuscany.spi.idl.InvalidServiceContractException; +import org.apache.tuscany.spi.idl.java.JavaInterfaceProcessorRegistry; +import org.apache.tuscany.spi.idl.java.JavaServiceContract; +import org.apache.tuscany.spi.model.Operation; +import org.apache.tuscany.spi.model.ServiceContract; +import org.apache.tuscany.spi.wire.InboundInvocationChain; +import org.apache.tuscany.spi.wire.InboundWire; + +import org.apache.tuscany.core.idl.java.JavaInterfaceProcessorRegistryImpl; +import org.apache.tuscany.core.implementation.PojoConfiguration; +import org.apache.tuscany.core.implementation.system.component.SystemAtomicComponentImpl; +import org.apache.tuscany.core.implementation.system.wire.SystemInboundWireImpl; +import org.apache.tuscany.core.implementation.system.wire.SystemOutboundWire; +import org.apache.tuscany.core.implementation.system.wire.SystemOutboundWireImpl; +import org.apache.tuscany.core.injection.MethodEventInvoker; +import org.apache.tuscany.core.injection.PojoObjectFactory; +import org.apache.tuscany.core.wire.InboundInvocationChainImpl; +import org.apache.tuscany.core.wire.InboundWireImpl; +import org.apache.tuscany.core.wire.InvokerInterceptor; + +/** + * @version $$Rev$$ $$Date$$ + */ +public final class MockFactory { + + private MockFactory() { + } + + public static Map<String, AtomicComponent> createWiredComponents(String source, + Class<?> sourceClass, + ScopeContainer sourceScopeContainer, + String target, + Class<?> targetClass, + ScopeContainer targetScopeContainer) + throws NoSuchMethodException { + List<Class<?>> sourceClasses = new ArrayList<Class<?>>(); + sourceClasses.add(sourceClass); + return createWiredComponents(source, sourceClasses, sourceClass, sourceScopeContainer, target, targetClass, + targetScopeContainer); + } + + /** + * Creates source and target {@link AtomicComponent}s whose instances are wired together. The wiring algorithm + * searches for the first method on the source with a single parameter type matching an interface implemented by the + * target. + * + * @throws NoSuchMethodException + */ + @SuppressWarnings("unchecked") + public static Map<String, AtomicComponent> createWiredComponents(String source, + List<Class<?>> sourceInterfaces, + Class<?> sourceClass, + ScopeContainer sourceScopeContainer, + String target, + Class<?> targetClass, + ScopeContainer targetScopeContainer) + throws NoSuchMethodException { + + Map<String, AtomicComponent> contexts = new HashMap<String, AtomicComponent>(); + SystemAtomicComponent targetComponent = createAtomicComponent(target, targetScopeContainer, targetClass); + PojoConfiguration sourceConfig = new PojoConfiguration(); + sourceConfig.getServiceInterfaces().addAll(sourceInterfaces); + sourceConfig.setScopeContainer(sourceScopeContainer); + sourceConfig.setInstanceFactory(new PojoObjectFactory(sourceClass.getConstructor())); + + //create target wire + Method[] sourceMethods = sourceClass.getMethods(); + Class[] interfaces = targetClass.getInterfaces(); + Method setter = null; + for (Class interfaze : interfaces) { + for (Method method : sourceMethods) { + if (method.getParameterTypes().length == 1) { + if (interfaze.isAssignableFrom(method.getParameterTypes()[0])) { + setter = method; + } + } + Init init; + if ((init = method.getAnnotation(Init.class)) != null) { + sourceConfig.setInitLevel(init.eager() ? 50 : 0); + sourceConfig.setInitInvoker(new MethodEventInvoker<Object>(method)); + + } else if (method.getAnnotation(Destroy.class) != null) { + sourceConfig.setDestroyInvoker(new MethodEventInvoker<Object>(method)); + } + } + + } + if (setter == null) { + throw new IllegalArgumentException("No setter found on source for target"); + } + + sourceConfig.addReferenceSite(setter.getName(), setter); + SystemAtomicComponent sourceCtx = new SystemAtomicComponentImpl(source, sourceConfig); + QualifiedName targetName = new QualifiedName(target); + SystemOutboundWire wire = new SystemOutboundWireImpl(setter.getName(), targetName, targetClass); + InboundWire inboundWire = new SystemInboundWireImpl(targetName.getPortName(), targetClass, targetComponent); + wire.setTargetWire(inboundWire); + + sourceCtx.addOutboundWire(wire); + contexts.put(source, sourceCtx); + contexts.put(target, targetComponent); + return contexts; + } + + @SuppressWarnings("unchecked") + public static SystemAtomicComponent createAtomicComponent(String name, ScopeContainer container, Class<?> clazz) + throws NoSuchMethodException { + PojoConfiguration configuration = new PojoConfiguration(); + configuration.setScopeContainer(container); + configuration.addServiceInterface(clazz); + configuration.setInstanceFactory(new PojoObjectFactory(clazz.getConstructor())); + Method[] methods = clazz.getMethods(); + for (Method method : methods) { + Init init; + if ((init = method.getAnnotation(Init.class)) != null) { + configuration.setInitLevel(init.eager() ? 50 : 0); + configuration.setInitInvoker(new MethodEventInvoker<Object>(method)); + + } else if (method.getAnnotation(Destroy.class) != null) { + configuration.setDestroyInvoker(new MethodEventInvoker<Object>(method)); + } + } + return new SystemAtomicComponentImpl(name, configuration); + } + + public static <T> InboundWire createTargetWireFactory(String serviceName, Class<T> interfaze) + throws InvalidServiceContractException { + InboundWire wire = new InboundWireImpl(); + wire.setServiceName(serviceName); + JavaServiceContract contract = new JavaServiceContract(interfaze); + wire.setServiceContract(contract); + wire.addInvocationChains(createInboundChains(interfaze)); + return wire; + } + + public static Map<Operation<?>, InboundInvocationChain> createInboundChains(Class<?> interfaze) + throws InvalidServiceContractException { + JavaInterfaceProcessorRegistry registry = new JavaInterfaceProcessorRegistryImpl(); + Map<Operation<?>, InboundInvocationChain> invocations = new HashMap<Operation<?>, InboundInvocationChain>(); + ServiceContract<?> contract = registry.introspect(interfaze); + + for (Operation<?> operation : contract.getOperations().values()) { + InboundInvocationChain chain = new InboundInvocationChainImpl(operation); + // add tail interceptor + chain.addInterceptor(new InvokerInterceptor()); + invocations.put(operation, chain); + } + return invocations; + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/mock/wire/MockStaticInvoker.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/mock/wire/MockStaticInvoker.java new file mode 100644 index 0000000000..85afda9b08 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/mock/wire/MockStaticInvoker.java @@ -0,0 +1,97 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.mock.wire; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; + +import org.apache.tuscany.spi.wire.Interceptor; +import org.apache.tuscany.spi.wire.InvocationRuntimeException; +import org.apache.tuscany.spi.wire.Message; +import org.apache.tuscany.spi.wire.TargetInvoker; + +/** + * Caches component instances that do not need to be resolved for every wire, e.g. an wire originating from a lesser + * scope intended for a target with a wider scope + * + * @version $Rev$ $Date$ + */ +public class MockStaticInvoker implements TargetInvoker { + + private Object instance; + private Method operation; + private boolean cacheable; + + + public MockStaticInvoker(Method operation, Object instance) { + this.operation = operation; + this.instance = instance; + } + + public boolean isCacheable() { + return cacheable; + } + + public void setCacheable(boolean cacheable) { + this.cacheable = cacheable; + } + + public boolean isOptimizable() { + return isCacheable(); + } + + public Object invokeTarget(final Object payload) throws InvocationTargetException { + try { + if (payload != null && !payload.getClass().isArray()) { + return operation.invoke(instance, payload); + } else { + return operation.invoke(instance, (Object[]) payload); + } + } catch (IllegalAccessException e) { + throw new InvocationRuntimeException(e); + } + } + + public Message invoke(Message msg) throws InvocationRuntimeException { + try { + Object resp = invokeTarget(msg.getBody()); + msg.setBody(resp); + } catch (InvocationTargetException e) { + msg.setBodyWithFault(e.getCause()); + } catch (Throwable e) { + msg.setBodyWithFault(e); + } + return msg; + } + + public void setNext(Interceptor next) { + throw new IllegalStateException("This interceptor must be the last interceptor in an interceptor chain"); + } + + public Object clone() throws CloneNotSupportedException { + try { + MockStaticInvoker invoker = (MockStaticInvoker) super.clone(); + invoker.instance = this.instance; + invoker.operation = this.operation; + return invoker; + } catch (CloneNotSupportedException e) { + return null; // will not happen + } + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/mock/wire/MockSyncInterceptor.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/mock/wire/MockSyncInterceptor.java new file mode 100644 index 0000000000..1fe2c027ab --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/mock/wire/MockSyncInterceptor.java @@ -0,0 +1,55 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.mock.wire; + +import org.apache.tuscany.spi.wire.Interceptor; +import org.apache.tuscany.spi.wire.Message; + +public class MockSyncInterceptor implements Interceptor { + + private int count; + + private Interceptor next; + + public MockSyncInterceptor() { + } + + public Message invoke(Message msg) { + ++count; + return next.invoke(msg); + } + + public int getCount() { + return count; + } + + public void setNext(Interceptor next) { + this.next = next; + } + + public Interceptor getNext() { + return next; + } + + public boolean isOptimizable() { + return false; + } + +} + diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/monitor/JavaLoggingTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/monitor/JavaLoggingTestCase.java new file mode 100644 index 0000000000..ee452d34fa --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/monitor/JavaLoggingTestCase.java @@ -0,0 +1,165 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.monitor; + +import java.util.ArrayList; +import java.util.List; +import java.util.Properties; +import java.util.logging.Handler; +import java.util.logging.Level; +import java.util.logging.LogRecord; +import java.util.logging.Logger; + +import org.apache.tuscany.api.annotation.LogLevel; +import org.apache.tuscany.host.MonitorFactory; + +import junit.framework.TestCase; + +/** + * Test case for the JavaLoggingMonitorFactory. + * + * @version $Rev$ $Date$ + */ +public class JavaLoggingTestCase extends TestCase { + private static final Logger LOGGER = Logger.getLogger(Monitor.class.getName()); + private static final MockHandler HANDLER = new MockHandler(); + + private MonitorFactory factory; + + /** + * Smoke test to ensure the LOGGER is working. + */ + public void testLogger() { + LOGGER.info("test"); + assertEquals(1, HANDLER.logs.size()); + } + + /** + * Test that no record is logged. + */ + public void testUnloggedEvent() { + Monitor mon = factory.getMonitor(Monitor.class); + mon.eventNotToLog(); + assertEquals(0, HANDLER.logs.size()); + } + + /** + * Test the correct record is written for an event with no arguments. + */ + public void testEventWithNoArgs() { + Monitor mon = factory.getMonitor(Monitor.class); + mon.eventWithNoArgs(); + assertEquals(1, HANDLER.logs.size()); + LogRecord record = HANDLER.logs.get(0); + assertEquals(Level.INFO, record.getLevel()); + assertEquals(LOGGER.getName(), record.getLoggerName()); + assertEquals(Monitor.class.getName() + "#eventWithNoArgs", record.getMessage()); + } + + /** + * Test the correct record is written for an event defined by annotation. + */ + public void testEventWithAnnotation() { + Monitor mon = factory.getMonitor(Monitor.class); + mon.eventWithAnnotation(); + assertEquals(1, HANDLER.logs.size()); + LogRecord record = HANDLER.logs.get(0); + assertEquals(Level.INFO, record.getLevel()); + assertEquals(LOGGER.getName(), record.getLoggerName()); + assertEquals(Monitor.class.getName() + "#eventWithAnnotation", record.getMessage()); + } + + /** + * Test a Throwable is logged when passed to an event. + */ + public void testEventWithThrowable() { + Exception e = new Exception(); + Monitor mon = factory.getMonitor(Monitor.class); + mon.eventWithThrowable(e); + assertEquals(1, HANDLER.logs.size()); + LogRecord record = HANDLER.logs.get(0); + assertEquals(Level.WARNING, record.getLevel()); + assertEquals(LOGGER.getName(), record.getLoggerName()); + assertEquals(Monitor.class.getName() + "#eventWithThrowable", record.getMessage()); + assertSame(e, record.getThrown()); + } + + /** + * Test the argument is logged. + */ + public void testEventWithOneArg() { + Monitor mon = factory.getMonitor(Monitor.class); + mon.eventWithOneArg("ARG"); + assertEquals(1, HANDLER.logs.size()); + LogRecord record = HANDLER.logs.get(0); + assertEquals(Monitor.class.getName() + "#eventWithOneArg", record.getMessage()); + } + + protected void setUp() throws Exception { + super.setUp(); + LOGGER.setUseParentHandlers(false); + LOGGER.addHandler(HANDLER); + HANDLER.flush(); + + String sourceClass = Monitor.class.getName(); + Properties levels = new Properties(); + levels.setProperty(sourceClass + "#eventWithNoArgs", "INFO"); + levels.setProperty(sourceClass + "#eventWithOneArg", "INFO"); + levels.setProperty(sourceClass + "#eventWithThrowable", "WARNING"); + factory = new JavaLoggingMonitorFactory(levels, Level.FINE, "TestMessages"); + } + + protected void tearDown() throws Exception { + LOGGER.removeHandler(HANDLER); + HANDLER.flush(); + super.tearDown(); + } + + /** + * Mock log HANDLER to capture records. + */ + public static class MockHandler extends Handler { + List<LogRecord> logs = new ArrayList<LogRecord>(); + + public void publish(LogRecord record) { + logs.add(record); + } + + public void flush() { + logs.clear(); + } + + public void close() throws SecurityException { + } + } + + @SuppressWarnings({"JavaDoc"}) + public static interface Monitor { + void eventNotToLog(); + + void eventWithNoArgs(); + + void eventWithOneArg(String msg); + + void eventWithThrowable(Exception e); + + @LogLevel("INFO") + void eventWithAnnotation(); + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/property/PropertyHelperTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/property/PropertyHelperTestCase.java new file mode 100644 index 0000000000..4f2e2fbf42 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/property/PropertyHelperTestCase.java @@ -0,0 +1,107 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.tuscany.core.property; + +import java.net.URL; +import javax.xml.namespace.NamespaceContext; + +import org.w3c.dom.Document; +import org.w3c.dom.Node; + +import org.apache.tuscany.spi.deployer.DeploymentContext; + +import junit.framework.TestCase; +import org.apache.tuscany.core.databinding.xml.String2Node; +import org.easymock.EasyMock; + +/** + * + */ +public class PropertyHelperTestCase extends TestCase { + private static final String IPO_XML = + "<?xml version=\"1.0\"?>" + "<ipo:purchaseOrder" + + " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"" + + " xmlns:ipo=\"http://www.example.com/IPO\"" + + " xsi:schemaLocation=\"http://www.example.com/IPO ipo.xsd\"" + + " orderDate=\"1999-12-01\">" + + " <shipTo exportCode=\"1\" xsi:type=\"ipo:UKAddress\">" + + " <name>Helen Zoe</name>" + + " <street>47 Eden Street</street>" + + " <city>Cambridge</city>" + + " <postcode>CB1 1JR</postcode>" + + " </shipTo>" + + " <billTo xsi:type=\"ipo:USAddress\">" + + " <name>Robert Smith</name>" + + " <street>8 Oak Avenue</street>" + + " <city>Old Town</city>" + + " <state>PA</state>" + + " <zip>95819</zip>" + + " </billTo>" + + " <items>" + + " <item partNum=\"833-AA\">" + + " <productName>Lapis necklace</productName>" + + " <quantity>1</quantity>" + + " <USPrice>99.95</USPrice>" + + " <ipo:comment>Want this for the holidays</ipo:comment>" + + " <shipDate>1999-12-05</shipDate>" + + " </item>" + + " </items>" + + "</ipo:purchaseOrder>"; + + /** + * @see junit.framework.TestCase#setUp() + */ + protected void setUp() throws Exception { + super.setUp(); + } + + public void testXPath() throws Exception { + String2Node t = new String2Node(); + Node node = t.transform(IPO_XML, null); + + Document doc = PropertyHelper.evaluate(null, node, "/ipo:purchaseOrder/billTo"); + assertNotNull(doc); + + NamespaceContext context = EasyMock.createMock(NamespaceContext.class); + EasyMock.expect(context.getNamespaceURI("ipo")).andReturn("http://www.example.com/IPO").anyTimes(); + EasyMock.replay(context); + doc = PropertyHelper.evaluate(context, node, "/ipo:purchaseOrder/items"); + assertNotNull(doc); + doc = PropertyHelper.evaluate(context, node, "/ipo:purchaseOrder/billTo"); + assertNotNull(doc); + doc = PropertyHelper.evaluate(context, node, "/"); + assertNotNull(doc); + doc = PropertyHelper.evaluate(context, node, "/ipo:purchaseOrder/billTo1"); + assertNull(doc); + } + + public void testFile() throws Exception { + URL url = getClass().getResource("ipo.xml"); + Document doc = PropertyHelper.loadFromFile(url.toExternalForm(), null); + assertNotNull(doc); + + DeploymentContext context = EasyMock.createMock(DeploymentContext.class); + EasyMock.expect(context.getClassLoader()).andReturn(getClass().getClassLoader()); + EasyMock.replay(context); + doc = PropertyHelper.loadFromFile("org/apache/tuscany/core/property/ipo.xml", context); + assertNotNull(doc); + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/property/SimplePropertyObjectFactoryTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/property/SimplePropertyObjectFactoryTestCase.java new file mode 100644 index 0000000000..9ef1faccfe --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/property/SimplePropertyObjectFactoryTestCase.java @@ -0,0 +1,107 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.property; + +import org.w3c.dom.Document; +import org.w3c.dom.Element; + +import org.apache.tuscany.spi.ObjectFactory; +import org.apache.tuscany.spi.model.Property; +import org.apache.tuscany.spi.model.PropertyValue; + +import junit.framework.TestCase; +import org.easymock.EasyMock; + +/** + * @version $Rev$ $Date$ + */ +public class SimplePropertyObjectFactoryTestCase extends TestCase { + + private <T> PropertyValue<T> mock(String value) { + Document document = EasyMock.createMock(Document.class); + Element element = EasyMock.createMock(Element.class); + EasyMock.expect(document.getDocumentElement()).andReturn(element); + EasyMock.expect(element.getTextContent()).andReturn(value); + EasyMock.replay(document, element); + return new PropertyValue<T>(null, document); + } + + public void testInteger() throws Exception { + + PropertyObjectFactoryImpl factory = new PropertyObjectFactoryImpl(); + Property<Integer> property = new Property<Integer>(); + property.setJavaType(Integer.class); + PropertyValue<Integer> propertyValue = mock("1"); + ObjectFactory<Integer> oFactory = factory.createObjectFactory(property, propertyValue); + assertEquals(1, oFactory.getInstance().intValue()); + } + + public void testPrimitiveInt() throws Exception { + PropertyObjectFactoryImpl factory = new PropertyObjectFactoryImpl(); + Property<Integer> property = new Property<Integer>(); + property.setJavaType(Integer.TYPE); + PropertyValue<Integer> propertyValue = mock("1"); + ObjectFactory<Integer> oFactory = factory.createObjectFactory(property, propertyValue); + assertEquals(1, oFactory.getInstance().intValue()); + } + + public void testString() throws Exception { + PropertyObjectFactoryImpl factory = new PropertyObjectFactoryImpl(); + Property<String> property = new Property<String>(); + property.setJavaType(String.class); + PropertyValue<String> propertyValue = mock("1"); + ObjectFactory<String> oFactory = factory.createObjectFactory(property, propertyValue); + assertEquals("1", oFactory.getInstance()); + } + + public void testByteArray() throws Exception { + PropertyObjectFactoryImpl factory = new PropertyObjectFactoryImpl(); + Property<byte[]> property = new Property<byte[]>(); + property.setJavaType(byte[].class); + PropertyValue<byte[]> propertyValue = mock("TWFu"); // BASE64 for "Man" + ObjectFactory<byte[]> oFactory = factory.createObjectFactory(property, propertyValue); + byte[] result = oFactory.getInstance(); + byte[] expected = "Man".getBytes(); + for (int i = 0; i < result.length; i++) { + byte b = result[i]; + if (b != expected[i]) { + fail(); + } + } + } + + public void testBoolean() throws Exception { + PropertyObjectFactoryImpl factory = new PropertyObjectFactoryImpl(); + Property<Boolean> property = new Property<Boolean>(); + property.setJavaType(Boolean.class); + PropertyValue<Boolean> propertyValue = mock("true"); + ObjectFactory<Boolean> oFactory = factory.createObjectFactory(property, propertyValue); + assertTrue(oFactory.getInstance()); + } + + public void testPrimitiveBoolean() throws Exception { + PropertyObjectFactoryImpl factory = new PropertyObjectFactoryImpl(); + Property<Boolean> property = new Property<Boolean>(); + property.setJavaType(Boolean.TYPE); + PropertyValue<Boolean> propertyValue = mock("true"); + ObjectFactory<Boolean> oFactory = factory.createObjectFactory(property, propertyValue); + assertTrue(oFactory.getInstance()); + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/services/artifact/LocalMavenRepositoryTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/services/artifact/LocalMavenRepositoryTestCase.java new file mode 100644 index 0000000000..0efecb9302 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/services/artifact/LocalMavenRepositoryTestCase.java @@ -0,0 +1,82 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.services.artifact; + +import java.io.File; +import java.io.UnsupportedEncodingException; +import java.net.MalformedURLException; +import java.net.URL; + +import junit.framework.TestCase; + +import org.apache.tuscany.spi.services.artifact.Artifact; + +/** + * This testcase assumes that there is a maven repo in the default location. + * + * @version $Rev$ $Date$ + */ +public class LocalMavenRepositoryTestCase extends TestCase { + private static final String VERSION = "3.8.1"; + private LocalMavenRepository repo; + private Artifact artifact; + private String path; + + public void testPathWithNoClassifier() { + assertEquals(path, repo.getPath(artifact)); + } + + public void testPathWithClassifier() { + artifact.setClassifier("x86"); + path = "junit/junit/" + VERSION + "/junit-" + VERSION + "-x86.jar"; + assertEquals(path, repo.getPath(artifact)); + } + + public void testArtifactFoundInRepo() throws MalformedURLException, UnsupportedEncodingException { + String home = System.getProperty("user.home"); + File file = new File(home + "/.m2/repository", path); + repo.resolve(artifact); + assertEquals(file.toURI().toURL(), artifact.getUrl()); + } + + public void testArtifactNotFoundInRepo() throws MalformedURLException { + artifact.setClassifier("x86"); + repo.resolve(artifact); + assertNull(artifact.getUrl()); + } + + public void testNonNullURLIsUnmodified() throws MalformedURLException { + URL url = new URL("http://www.apache.org"); + artifact.setUrl(url); + repo.resolve(artifact); + assertSame(url, artifact.getUrl()); + } + + protected void setUp() throws Exception { + super.setUp(); + repo = new LocalMavenRepository(".m2/repository"); + + artifact = new Artifact(); + artifact.setGroup("junit"); + artifact.setName("junit"); + artifact.setVersion(VERSION); + artifact.setType("jar"); + path = "junit/junit/" + VERSION + "/junit-" + VERSION + ".jar"; + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/services/work/jsr237/Jsr237WorkSchedulerTest.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/services/work/jsr237/Jsr237WorkSchedulerTest.java new file mode 100644 index 0000000000..1a5cb4ebe1 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/services/work/jsr237/Jsr237WorkSchedulerTest.java @@ -0,0 +1,81 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.services.work.jsr237; + +import org.apache.tuscany.spi.services.work.NotificationListener; +import org.apache.tuscany.spi.services.work.WorkScheduler; + +import commonj.work.WorkManager; +import junit.framework.TestCase; +import org.apache.tuscany.core.services.work.jsr237.workmanager.ThreadPoolWorkManager; + +public class Jsr237WorkSchedulerTest extends TestCase { + + /* + * Test method for 'org.apache.tuscany.core.services.work.jsr237.Jsr237WorkScheduler.scheduleWork(T) <T>' + */ + public void testScheduleWorkT() { + + + WorkManager workManager = new ThreadPoolWorkManager(1); + WorkScheduler workScheduler = new Jsr237WorkScheduler(workManager); + + workScheduler.scheduleWork(new MyRunnable(), new MyNotificationListener()); + + } + + /* + * Test method for 'org.apache.tuscany.core.services.work.jsr237.Jsr237WorkScheduler.scheduleWork(T, + * NotificationListener<T>) <T>' + */ + public void testScheduleWorkTNotificationListenerOfT() { + + } + + private class MyRunnable implements Runnable { + public void run() { + System.err.println("Test executed"); + } + } + + private class MyNotificationListener implements NotificationListener<MyRunnable> { + + public void workAccepted(MyRunnable work) { + System.err.println("Work accepted"); + } + + public void workCompleted(MyRunnable work) { + System.err.println("Work completed"); + } + + public void workStarted(MyRunnable work) { + System.err.println("Work started"); + } + + public void workRejected(MyRunnable work) { + System.err.println("Work rejected"); + } + + public void workFailed(MyRunnable work, Throwable error) { + System.err.println("Work failed"); + } + + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/services/work/jsr237/Jsr237WorkSchedulerTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/services/work/jsr237/Jsr237WorkSchedulerTestCase.java new file mode 100644 index 0000000000..3966f65683 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/services/work/jsr237/Jsr237WorkSchedulerTestCase.java @@ -0,0 +1,100 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.services.work.jsr237; + +import org.apache.tuscany.spi.services.work.NotificationListener; +import org.apache.tuscany.spi.services.work.WorkSchedulerException; + +import commonj.work.Work; +import commonj.work.WorkItem; +import commonj.work.WorkListener; +import commonj.work.WorkManager; +import commonj.work.WorkRejectedException; +import junit.framework.TestCase; +import static org.easymock.EasyMock.createMock; +import static org.easymock.EasyMock.expectLastCall; +import static org.easymock.EasyMock.isA; +import static org.easymock.EasyMock.replay; +import static org.easymock.EasyMock.verify; + +/** + * @version $Rev$ $Date$ + */ +public class Jsr237WorkSchedulerTestCase extends TestCase { + + public void testSchedule() throws Exception { + WorkItem item = createMock(WorkItem.class); + WorkManager mgr = createMock(WorkManager.class); + mgr.schedule(isA(Work.class)); + expectLastCall().andReturn(item); + replay(mgr); + Jsr237WorkScheduler scheduler = new Jsr237WorkScheduler(mgr); + Work work = createMock(Work.class); + scheduler.scheduleWork(work); + verify(mgr); + } + + @SuppressWarnings("unchecked") + public void testListener() throws Exception { + WorkItem item = createMock(WorkItem.class); + WorkManager mgr = createMock(WorkManager.class); + mgr.schedule(isA(Work.class), isA(WorkListener.class)); + expectLastCall().andReturn(item); + replay(mgr); + Jsr237WorkScheduler scheduler = new Jsr237WorkScheduler(mgr); + Work work = createMock(Work.class); + NotificationListener<Runnable> listener = createMock(NotificationListener.class); + scheduler.scheduleWork(work, listener); + verify(mgr); + } + + @SuppressWarnings("unchecked") + public void testWorkRejectedListener() throws Exception { + WorkManager mgr = createMock(WorkManager.class); + mgr.schedule(isA(Work.class), isA(WorkListener.class)); + expectLastCall().andThrow(new WorkRejectedException()); + replay(mgr); + Jsr237WorkScheduler scheduler = new Jsr237WorkScheduler(mgr); + Work work = createMock(Work.class); + NotificationListener<Runnable> listener = createMock(NotificationListener.class); + listener.workRejected(isA(Runnable.class)); + expectLastCall(); + replay(listener); + scheduler.scheduleWork(work, listener); + verify(mgr); + } + + @SuppressWarnings("unchecked") + public void testWorkRejectedNoListener() throws Exception { + WorkManager mgr = createMock(WorkManager.class); + mgr.schedule(isA(Work.class)); + expectLastCall().andThrow(new WorkRejectedException()); + replay(mgr); + Jsr237WorkScheduler scheduler = new Jsr237WorkScheduler(mgr); + Work work = createMock(Work.class); + try { + scheduler.scheduleWork(work); + fail(); + } catch (WorkSchedulerException e) { + // expected + } + verify(mgr); + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/services/work/jsr237/workmanager/ThreadPoolWorkManagerTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/services/work/jsr237/workmanager/ThreadPoolWorkManagerTestCase.java new file mode 100644 index 0000000000..33ecd66fdc --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/services/work/jsr237/workmanager/ThreadPoolWorkManagerTestCase.java @@ -0,0 +1,132 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.services.work.jsr237.workmanager; + +import java.util.concurrent.CountDownLatch; + +import commonj.work.Work; +import commonj.work.WorkEvent; +import commonj.work.WorkListener; +import junit.framework.TestCase; +import static org.easymock.EasyMock.createMock; +import static org.easymock.EasyMock.createStrictMock; +import static org.easymock.EasyMock.expectLastCall; +import static org.easymock.EasyMock.isA; +import static org.easymock.EasyMock.replay; +import static org.easymock.EasyMock.verify; +import org.easymock.IAnswer; + +/** + * @version $Rev$ $Date$ + */ +public class ThreadPoolWorkManagerTestCase extends TestCase { + + public void testSchedule() throws Exception { + final CountDownLatch latch = new CountDownLatch(1); + Work work = createMock(Work.class); + work.run(); + expectLastCall().andStubAnswer(new IAnswer<Object>() { + public Object answer() throws Throwable { + latch.countDown(); + return null; + } + }); + replay(work); + ThreadPoolWorkManager mgr = new ThreadPoolWorkManager(1); + mgr.schedule(work); + latch.await(); + verify(work); + } + + public void testListener() throws Exception { + final CountDownLatch latch = new CountDownLatch(1); + WorkListener listener = createStrictMock(WorkListener.class); + listener.workAccepted(isA(WorkEvent.class)); + listener.workStarted(isA(WorkEvent.class)); + listener.workCompleted(isA(WorkEvent.class)); + expectLastCall(); + replay(listener); + Work work = createMock(Work.class); + work.run(); + expectLastCall().andStubAnswer(new IAnswer<Object>() { + public Object answer() throws Throwable { + latch.countDown(); + return null; + } + }); + replay(work); + ThreadPoolWorkManager mgr = new ThreadPoolWorkManager(1); + mgr.schedule(work, listener); + latch.await(); + verify(work); + } + + public void testDelayListener() throws Exception { + final CountDownLatch latch = new CountDownLatch(1); + final CountDownLatch latch2 = new CountDownLatch(1); + WorkListener listener = createStrictMock(WorkListener.class); + listener.workAccepted(isA(WorkEvent.class)); + listener.workStarted(isA(WorkEvent.class)); + listener.workCompleted(isA(WorkEvent.class)); + expectLastCall().andStubAnswer(new IAnswer<Object>() { + public Object answer() throws Throwable { + latch2.countDown(); + return null; + } + }); + replay(listener); + Work work = createMock(Work.class); + work.run(); + expectLastCall().andStubAnswer(new IAnswer<Object>() { + public Object answer() throws Throwable { + latch.await(); + return null; + } + }); + replay(work); + ThreadPoolWorkManager mgr = new ThreadPoolWorkManager(1); + mgr.schedule(work, listener); + latch.countDown(); + verify(work); + } + + public void testErrorListener() throws Exception { + final CountDownLatch latch = new CountDownLatch(1); + WorkListener listener = createStrictMock(WorkListener.class); + listener.workAccepted(isA(WorkEvent.class)); + listener.workStarted(isA(WorkEvent.class)); + listener.workCompleted(isA(WorkEvent.class)); + replay(listener); + Work work = createMock(Work.class); + work.run(); + expectLastCall().andStubAnswer(new IAnswer<Object>() { + public Object answer() throws Throwable { + latch.countDown(); + throw new RuntimeException(); + } + }); + replay(work); + ThreadPoolWorkManager mgr = new ThreadPoolWorkManager(1); + mgr.schedule(work, listener); + latch.await(); + verify(work); + } + +} + diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/util/Bean1.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/util/Bean1.java new file mode 100644 index 0000000000..79fad549aa --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/util/Bean1.java @@ -0,0 +1,45 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.util; + + +public class Bean1 extends SuperBean { + + public static final int ALL_BEAN1_FIELDS = 6 + ALL_SUPER_FIELDS; + public static final int ALL_BEAN1_PUBLIC_PROTECTED_FIELDS = 5 + ALL_SUPER_PUBLIC_PROTECTED_FIELDS; + public static final int ALL_BEAN1_METHODS = 4 + ALL_SUPER_METHODS - 1; + public String field3; + protected String field2; + private String field1; + + public void setMethod1(String param) { + } + + public void setMethod1(int param) { + } + + public void override(String param) throws Exception { + } + + + public void noOverride(String param) throws Exception { + } + + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/util/Bean2.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/util/Bean2.java new file mode 100644 index 0000000000..7f7f03da9e --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/util/Bean2.java @@ -0,0 +1,47 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.util; + +import java.util.List; + +import junit.framework.AssertionFailedError; + +public class Bean2 { + + private List methodList; + private List fieldList; + + public List getMethodList() { + return methodList; + } + + public void setMethodList(List list) { + methodList = list; + } + + public List getfieldList() { + return fieldList; + } + + public void setfieldList(List list) { + throw new AssertionFailedError("setter inadvertantly called"); + } + + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/util/JavaIntrospectionHelperTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/util/JavaIntrospectionHelperTestCase.java new file mode 100644 index 0000000000..797b147b54 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/util/JavaIntrospectionHelperTestCase.java @@ -0,0 +1,180 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.util; + +import java.lang.reflect.Constructor; +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import junit.framework.TestCase; +import org.apache.tuscany.core.mock.component.Target; + +public class JavaIntrospectionHelperTestCase extends TestCase { + + private List testNoGenericsList; + private List<String> testList; + private Map<String, Bean1> testMap; + private Target[] testArray; + private String[] testStringArray; + + public JavaIntrospectionHelperTestCase() { + super(); + } + + public JavaIntrospectionHelperTestCase(String arg0) { + super(arg0); + } + + public void testBean1AllPublicProtectedFields() throws Exception { + Set<Field> beanFields = JavaIntrospectionHelper.getAllPublicAndProtectedFields(Bean1.class); + assertEquals(4, beanFields.size()); //Bean1.ALL_BEAN1_PUBLIC_PROTECTED_FIELDS + } + + public void testGetSuperAllMethods() throws Exception { + Set<Method> superBeanMethods = JavaIntrospectionHelper.getAllUniquePublicProtectedMethods(SuperBean.class); + assertEquals(SuperBean.ALL_SUPER_METHODS, superBeanMethods.size()); + } + + public void testGetBean1AllMethods() throws Exception { + Set<Method> beanMethods = JavaIntrospectionHelper.getAllUniquePublicProtectedMethods(Bean1.class); + assertEquals(Bean1.ALL_BEAN1_METHODS, beanMethods.size()); + } + + public void testOverrideMethod() throws Exception { + Set<Method> beanFields = JavaIntrospectionHelper.getAllUniquePublicProtectedMethods(Bean1.class); + boolean invoked = false; + for (Method method : beanFields) { + if (method.getName().equals("override")) { + method.invoke(new Bean1(), "foo"); + invoked = true; + } + } + if (!invoked) { + throw new Exception("Override never invoked"); + } + } + + public void testNoOverrideMethod() throws Exception { + Set<Method> beanFields = JavaIntrospectionHelper.getAllUniquePublicProtectedMethods(Bean1.class); + boolean found = false; + for (Method method : beanFields) { + if (method.getName().equals("noOverride") && method.getParameterTypes().length == 0) { + found = true; + } + } + if (!found) { + throw new Exception("No override not found"); + } + } + + public void testDefaultConstructor() throws Exception { + Constructor ctr = JavaIntrospectionHelper.getDefaultConstructor(Bean2.class); + assertEquals(ctr, Bean2.class.getConstructor()); + assertTrue(Bean2.class == ctr.newInstance((Object[]) null).getClass()); + } + + + public void testGetAllInterfaces() { + Set<Class> interfaces = JavaIntrospectionHelper.getAllInterfaces(Z.class); + assertEquals(2, interfaces.size()); + assertTrue(interfaces.contains(W.class)); + assertTrue(interfaces.contains(W2.class)); + } + + + public void testGetAllInterfacesObject() { + Set<Class> interfaces = JavaIntrospectionHelper.getAllInterfaces(Object.class); + assertEquals(0, interfaces.size()); + } + + public void testGetAllInterfacesNoInterfaces() { + Set<Class> interfaces = JavaIntrospectionHelper.getAllInterfaces(NoInterface.class); + assertEquals(0, interfaces.size()); + } + + /** + * Tests generics introspection capabilities + */ + public void testGenerics() throws Exception { + + List classes = JavaIntrospectionHelper.getGenerics(getClass().getDeclaredField("testList").getGenericType()); + assertEquals(1, classes.size()); + assertEquals(String.class, classes.get(0)); + + classes = + JavaIntrospectionHelper.getGenerics(getClass().getDeclaredField("testNoGenericsList").getGenericType()); + assertEquals(0, classes.size()); + + classes = JavaIntrospectionHelper.getGenerics(getClass().getDeclaredField("testMap").getGenericType()); + assertEquals(2, classes.size()); + assertEquals(String.class, classes.get(0)); + assertEquals(Bean1.class, classes.get(1)); + + classes = JavaIntrospectionHelper + .getGenerics(getClass().getDeclaredMethod("fooMethod", Map.class).getGenericParameterTypes()[0]); + assertEquals(2, classes.size()); + assertEquals(String.class, classes.get(0)); + assertEquals(Bean1.class, classes.get(1)); + + classes = JavaIntrospectionHelper + .getGenerics(getClass().getDeclaredMethod("fooMethod", List.class).getGenericParameterTypes()[0]); + assertEquals(1, classes.size()); + assertEquals(String.class, classes.get(0)); + + } + + private void fooMethod(List<String> foo) { + + } + + private void fooMethod(Map<String, Bean1> foo) { + + } + + public void setTestArray(Target[] array) { + } + + private interface W { + + } + + private interface W2 { + + } + + private class X implements W { + + } + + private class Y extends X implements W, W2 { + + } + + private class Z extends Y { + + } + + private class NoInterface { + + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/util/SuperBean.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/util/SuperBean.java new file mode 100644 index 0000000000..83aef7fb5e --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/util/SuperBean.java @@ -0,0 +1,48 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.util; + +/** + * @version $Rev$ $Date$ + */ +public class SuperBean { + + public static final int ALL_SUPER_FIELDS = 6; + public static final int ALL_SUPER_PUBLIC_PROTECTED_FIELDS = 5; + public static final int ALL_SUPER_METHODS = 4; + public String superField2; + + protected String superField3; + + private String superField1; + + public void setSuperMethod1(String param) { + } + + public void setSuperMethod1(int param) { + } + + public void override(String param) throws Exception { + throw new Exception("Override not handled"); + } + + public void noOverride() throws Exception { + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/wire/BasicReferenceInvocationHandlerTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/wire/BasicReferenceInvocationHandlerTestCase.java new file mode 100644 index 0000000000..fe7469c998 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/wire/BasicReferenceInvocationHandlerTestCase.java @@ -0,0 +1,70 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.wire; + +import java.lang.reflect.Method; + +import org.apache.tuscany.spi.idl.java.JavaInterfaceProcessorRegistry; +import org.apache.tuscany.spi.model.Operation; +import org.apache.tuscany.spi.model.ServiceContract; +import org.apache.tuscany.spi.wire.OutboundInvocationChain; +import org.apache.tuscany.spi.wire.OutboundWire; + +import junit.framework.TestCase; +import org.apache.tuscany.core.component.WorkContextImpl; +import org.apache.tuscany.core.idl.java.JavaInterfaceProcessorRegistryImpl; +import org.apache.tuscany.core.mock.component.SimpleTarget; +import org.apache.tuscany.core.mock.component.SimpleTargetImpl; +import org.apache.tuscany.core.mock.wire.MockStaticInvoker; +import org.apache.tuscany.core.mock.wire.MockSyncInterceptor; +import org.apache.tuscany.core.wire.jdk.JDKOutboundInvocationHandler; + +/** + * @version $$Rev$$ $$Date$$ + */ +public class BasicReferenceInvocationHandlerTestCase extends TestCase { + + private Method echo; + + public void testInterceptorInvoke() throws Throwable { + JavaInterfaceProcessorRegistry registry = new JavaInterfaceProcessorRegistryImpl(); + ServiceContract<?> contract = registry.introspect(SimpleTarget.class); + Operation<?> operation = contract.getOperations().get("echo"); + MockStaticInvoker invoker = new MockStaticInvoker(echo, new SimpleTargetImpl()); + OutboundInvocationChain chain = new OutboundInvocationChainImpl(operation); + MockSyncInterceptor interceptor = new MockSyncInterceptor(); + chain.addInterceptor(interceptor); + chain.setTargetInterceptor(new InvokerInterceptor()); + chain.setTargetInvoker(invoker); + chain.prepare(); + //chains.put(echo, chain); + OutboundWire wire = new OutboundWireImpl(); + wire.addInvocationChain(operation, chain); + wire.setServiceContract(contract); + JDKOutboundInvocationHandler handler = new JDKOutboundInvocationHandler(wire, new WorkContextImpl()); + assertEquals("foo", handler.invoke(null, echo, new String[]{"foo"})); + assertEquals(1, interceptor.getCount()); + } + + public void setUp() throws Exception { + super.setUp(); + echo = SimpleTarget.class.getMethod("echo", String.class); + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/wire/InboundInvocationErrorTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/wire/InboundInvocationErrorTestCase.java new file mode 100644 index 0000000000..79abec4904 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/wire/InboundInvocationErrorTestCase.java @@ -0,0 +1,150 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.wire; + +import java.lang.reflect.Method; +import java.lang.reflect.Proxy; +import java.util.HashMap; +import java.util.Map; + +import org.apache.tuscany.spi.component.WorkContext; +import org.apache.tuscany.spi.idl.InvalidServiceContractException; +import org.apache.tuscany.spi.idl.java.JavaInterfaceProcessorRegistry; +import org.apache.tuscany.spi.model.Operation; +import org.apache.tuscany.spi.model.ServiceContract; +import org.apache.tuscany.spi.wire.InboundInvocationChain; + +import junit.framework.TestCase; + +import org.apache.tuscany.core.idl.java.JavaInterfaceProcessorRegistryImpl; +import org.apache.tuscany.core.mock.wire.MockStaticInvoker; +import org.apache.tuscany.core.mock.wire.MockSyncInterceptor; +import org.apache.tuscany.core.wire.jdk.JDKInboundInvocationHandler; +import org.easymock.classextension.EasyMock; + +/** + * Tests handling of exceptions thrown during an inbound wire invocation + * + * @version $Rev$ $Date$ + */ +public class InboundInvocationErrorTestCase extends TestCase { + + private Method checkedMethod; + private Method runtimeMethod; + private Operation checkedOperation; + private Operation runtimeOperation; + + public InboundInvocationErrorTestCase() { + super(); + } + + public InboundInvocationErrorTestCase(String arg0) { + super(arg0); + } + + public void setUp() throws Exception { + super.setUp(); + checkedMethod = + TestBean.class.getDeclaredMethod("checkedException", (Class[]) null); + runtimeMethod = + TestBean.class.getDeclaredMethod("runtimeException", (Class[]) null); + assertNotNull(checkedMethod); + assertNotNull(runtimeMethod); + JavaInterfaceProcessorRegistry registry = new JavaInterfaceProcessorRegistryImpl(); + ServiceContract<?> contract; + try { + contract = registry.introspect(TestBean.class); + } catch (InvalidServiceContractException e) { + throw new AssertionError(); + } + + checkedOperation = contract.getOperations().get("checkedException"); + runtimeOperation = contract.getOperations().get("runtimeException"); + } + + public void testCheckedException() throws Exception { + Map<Method, InboundInvocationChain> chains = new HashMap<Method, InboundInvocationChain>(); + chains.put(checkedMethod, createChain(checkedMethod, checkedOperation)); + WorkContext workContext = EasyMock.createNiceMock(WorkContext.class); + EasyMock.replay(workContext); + JDKInboundInvocationHandler handler = new JDKInboundInvocationHandler(chains, workContext); + try { + InboundInvocationErrorTestCase.TestBean proxy = (InboundInvocationErrorTestCase.TestBean) Proxy + .newProxyInstance(Thread.currentThread().getContextClassLoader(), + new Class[]{InboundInvocationErrorTestCase.TestBean.class}, handler); + proxy.checkedException(); + } catch (InboundInvocationErrorTestCase.TestException e) { + return; + } + fail(InboundInvocationErrorTestCase.TestException.class.getName() + " should have been thrown"); + } + + public void testRuntimeException() throws Exception { + Map<Method, InboundInvocationChain> chains = new HashMap<Method, InboundInvocationChain>(); + chains.put(runtimeMethod, createChain(runtimeMethod, runtimeOperation)); + WorkContext workContext = EasyMock.createNiceMock(WorkContext.class); + EasyMock.replay(workContext); + JDKInboundInvocationHandler handler = new JDKInboundInvocationHandler(chains, workContext); + try { + InboundInvocationErrorTestCase.TestBean proxy = (InboundInvocationErrorTestCase.TestBean) Proxy + .newProxyInstance(Thread.currentThread().getContextClassLoader(), + new Class[]{InboundInvocationErrorTestCase.TestBean.class}, handler); + proxy.runtimeException(); + } catch (InboundInvocationErrorTestCase.TestRuntimeException e) { + return; + } + fail(InboundInvocationErrorTestCase.TestException.class.getName() + " should have been thrown"); + } + + private InboundInvocationChain createChain(Method m, Operation operation) { + MockStaticInvoker invoker = new MockStaticInvoker(m, new InboundInvocationErrorTestCase.TestBeanImpl()); + InboundInvocationChain chain = new InboundInvocationChainImpl(operation); + chain.addInterceptor(new MockSyncInterceptor()); + chain.setTargetInvoker(invoker); + chain.addInterceptor(new InvokerInterceptor()); + chain.prepare(); + return chain; + } + + public interface TestBean { + + void checkedException() throws InboundInvocationErrorTestCase.TestException; + + void runtimeException() throws InboundInvocationErrorTestCase.TestRuntimeException; + + } + + public class TestBeanImpl implements InboundInvocationErrorTestCase.TestBean { + + public void checkedException() throws InboundInvocationErrorTestCase.TestException { + throw new InboundInvocationErrorTestCase.TestException(); + } + + public void runtimeException() throws InboundInvocationErrorTestCase.TestRuntimeException { + throw new InboundInvocationErrorTestCase.TestRuntimeException(); + } + } + + public class TestException extends Exception { + } + + public class TestRuntimeException extends RuntimeException { + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/wire/InvocationChainImplTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/wire/InvocationChainImplTestCase.java new file mode 100644 index 0000000000..294e98997f --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/wire/InvocationChainImplTestCase.java @@ -0,0 +1,94 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.wire; + +import java.lang.reflect.Type; + +import org.apache.tuscany.spi.model.Operation; +import org.apache.tuscany.spi.wire.Interceptor; +import org.apache.tuscany.spi.wire.Message; + +import junit.framework.TestCase; + +/** + * @version $Rev$ $Date$ + */ +public class InvocationChainImplTestCase extends TestCase { + + public void testInsertAtPos() throws Exception { + MockChain chain = new MockChain(new Operation<Type>("foo", null, null, null)); + Interceptor inter3 = new MockInterceptor(); + Interceptor inter2 = new MockInterceptor(); + Interceptor inter1 = new MockInterceptor(); + chain.addInterceptor(inter3); + chain.addInterceptor(0, inter1); + chain.addInterceptor(1, inter2); + Interceptor head = chain.getHeadInterceptor(); + assertEquals(inter1, head); + assertEquals(inter2, head.getNext()); + assertEquals(inter3, head.getNext().getNext()); + } + + public void testInsertAtEnd() throws Exception { + MockChain chain = new MockChain(new Operation<Type>("foo", null, null, null)); + Interceptor inter2 = new MockInterceptor(); + Interceptor inter1 = new MockInterceptor(); + chain.addInterceptor(0, inter1); + chain.addInterceptor(1, inter2); + Interceptor head = chain.getHeadInterceptor(); + assertEquals(inter1, head); + assertEquals(inter2, head.getNext()); + assertEquals(inter2, chain.getTailInterceptor()); + + } + + private class MockChain extends InvocationChainImpl { + + public MockChain(Operation operation) { + super(operation); + } + + public void prepare() { + + } + } + + private class MockInterceptor implements Interceptor { + + private Interceptor next; + + public Message invoke(Message msg) { + return null; + } + + public void setNext(Interceptor next) { + this.next = next; + } + + public Interceptor getNext() { + return next; + } + + public boolean isOptimizable() { + return false; + } + } + + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/wire/InvocationConfigurationErrorTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/wire/InvocationConfigurationErrorTestCase.java new file mode 100644 index 0000000000..aca68a0f25 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/wire/InvocationConfigurationErrorTestCase.java @@ -0,0 +1,95 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.wire; + +import java.lang.reflect.Method; + +import org.apache.tuscany.spi.idl.java.JavaInterfaceProcessorRegistry; +import org.apache.tuscany.spi.model.Operation; +import org.apache.tuscany.spi.model.ServiceContract; +import org.apache.tuscany.spi.wire.InboundInvocationChain; +import org.apache.tuscany.spi.wire.Message; +import org.apache.tuscany.spi.wire.MessageImpl; +import org.apache.tuscany.spi.wire.OutboundInvocationChain; + +import junit.framework.TestCase; +import org.apache.tuscany.core.idl.java.JavaInterfaceProcessorRegistryImpl; +import org.apache.tuscany.core.mock.component.SimpleTarget; +import org.apache.tuscany.core.mock.component.SimpleTargetImpl; +import org.apache.tuscany.core.mock.wire.MockStaticInvoker; +import org.apache.tuscany.core.mock.wire.MockSyncInterceptor; + +/** + * Tests error propagation through an innvocation + * + * @version $Rev$ $Date$ + */ +public class InvocationConfigurationErrorTestCase extends TestCase { + + private ServiceContract<?> contract; + private Method hello; + + public InvocationConfigurationErrorTestCase() { + super(); + } + + public InvocationConfigurationErrorTestCase(String arg0) { + super(arg0); + } + + public void setUp() throws Exception { + super.setUp(); + JavaInterfaceProcessorRegistry registry = new JavaInterfaceProcessorRegistryImpl(); + contract = registry.introspect(SimpleTarget.class); + hello = SimpleTarget.class.getMethod("hello", String.class); + } + + /** + * Tests basic wiring of a source to a target, including handlers and interceptors + */ + public void testInvokeWithInterceptors() throws Exception { + Operation operation = contract.getOperations().get("hello"); + OutboundInvocationChain source = new OutboundInvocationChainImpl(operation); + MockSyncInterceptor sourceInterceptor = new MockSyncInterceptor(); + source.addInterceptor(sourceInterceptor); + + InboundInvocationChain target = new InboundInvocationChainImpl(operation); + MockSyncInterceptor targetInterceptor = new MockSyncInterceptor(); + target.addInterceptor(targetInterceptor); + target.addInterceptor(new InvokerInterceptor()); + + // connect the source to the target + source.setTargetInterceptor(target.getHeadInterceptor()); + source.prepare(); + target.prepare(); + MockStaticInvoker invoker = new MockStaticInvoker(hello, new SimpleTargetImpl()); + source.setTargetInvoker(invoker); + + Message msg = new MessageImpl(); + msg.setTargetInvoker(invoker); + Message response = source.getHeadInterceptor().invoke(msg); + assertTrue(response.isFault()); + assertTrue(response.getBody() instanceof IllegalArgumentException); + assertEquals(1, sourceInterceptor.getCount()); + assertEquals(1, targetInterceptor.getCount()); + + } + +} + diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/wire/InvocationConfigurationTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/wire/InvocationConfigurationTestCase.java new file mode 100644 index 0000000000..62df732a9e --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/wire/InvocationConfigurationTestCase.java @@ -0,0 +1,95 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.wire; + +import java.lang.reflect.Method; + +import org.apache.tuscany.spi.idl.InvalidServiceContractException; +import org.apache.tuscany.spi.idl.java.JavaInterfaceProcessorRegistry; +import org.apache.tuscany.spi.model.Operation; +import org.apache.tuscany.spi.model.ServiceContract; +import org.apache.tuscany.spi.wire.InboundInvocationChain; +import org.apache.tuscany.spi.wire.Message; +import org.apache.tuscany.spi.wire.MessageImpl; +import org.apache.tuscany.spi.wire.OutboundInvocationChain; + +import junit.framework.TestCase; +import org.apache.tuscany.core.idl.java.JavaInterfaceProcessorRegistryImpl; +import org.apache.tuscany.core.mock.component.SimpleTarget; +import org.apache.tuscany.core.mock.component.SimpleTargetImpl; +import org.apache.tuscany.core.mock.wire.MockStaticInvoker; +import org.apache.tuscany.core.mock.wire.MockSyncInterceptor; + +public class InvocationConfigurationTestCase extends TestCase { + + private Method hello; + private Operation operation; + + + public InvocationConfigurationTestCase() { + super(); + } + + public InvocationConfigurationTestCase(String arg0) { + super(arg0); + } + + public void setUp() throws Exception { + super.setUp(); + JavaInterfaceProcessorRegistry registry = new JavaInterfaceProcessorRegistryImpl(); + ServiceContract<?> contract; + try { + contract = registry.introspect(SimpleTarget.class); + } catch (InvalidServiceContractException e) { + throw new AssertionError(); + } + + operation = contract.getOperations().get("echo"); + hello = SimpleTarget.class.getMethod("hello", String.class); + } + + /** + * Tests basic wiring of a source to a target, including handlers and interceptors + */ + public void testInvokeWithInterceptors() throws Exception { + OutboundInvocationChain source = new OutboundInvocationChainImpl(operation); + MockSyncInterceptor sourceInterceptor = new MockSyncInterceptor(); + source.addInterceptor(sourceInterceptor); + + InboundInvocationChain target = new InboundInvocationChainImpl(operation); + MockSyncInterceptor targetInterceptor = new MockSyncInterceptor(); + target.addInterceptor(targetInterceptor); + target.addInterceptor(new InvokerInterceptor()); + + // connect the source to the target + source.setTargetInterceptor(target.getHeadInterceptor()); + source.prepare(); + target.prepare(); + MockStaticInvoker invoker = new MockStaticInvoker(hello, new SimpleTargetImpl()); + source.setTargetInvoker(invoker); + + Message msg = new MessageImpl(); + msg.setBody("foo"); + msg.setTargetInvoker(invoker); + Message response = source.getHeadInterceptor().invoke(msg); + assertEquals("foo", response.getBody()); + assertEquals(1, sourceInterceptor.getCount()); + assertEquals(1, targetInterceptor.getCount()); + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/wire/MediationTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/wire/MediationTestCase.java new file mode 100644 index 0000000000..a81e955a20 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/wire/MediationTestCase.java @@ -0,0 +1,50 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.wire; + +import java.lang.reflect.Method; + +import junit.framework.Assert; +import junit.framework.TestCase; +import org.apache.tuscany.core.mock.component.SimpleTargetImpl; + +/** + * Tests invoking on a different interface from the one actually implemented by the target + * + * @version $Rev$ $Date$ + */ +public class MediationTestCase extends TestCase { + + private Method hello; + + public void setUp() throws Exception { + hello = Hello.class.getMethod("hello", String.class); + } + + public void testMediation() throws Exception { + StaticPojoTargetInvoker invoker = new StaticPojoTargetInvoker(hello, new SimpleTargetImpl()); + Assert.assertEquals("foo", invoker.invokeTarget("foo")); + } + + public interface Hello { + + String hello(String message) throws Exception; + + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/wire/NonBlockingBridgingInterceptorTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/wire/NonBlockingBridgingInterceptorTestCase.java new file mode 100644 index 0000000000..a8b1eaf36f --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/wire/NonBlockingBridgingInterceptorTestCase.java @@ -0,0 +1,63 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.wire; + +import org.apache.tuscany.spi.component.WorkContext; +import org.apache.tuscany.spi.services.work.WorkScheduler; +import org.apache.tuscany.spi.wire.Interceptor; +import org.apache.tuscany.spi.wire.Message; +import org.apache.tuscany.spi.wire.MessageImpl; + +import junit.framework.TestCase; +import org.easymock.EasyMock; +import static org.easymock.EasyMock.createMock; +import static org.easymock.EasyMock.expectLastCall; +import static org.easymock.EasyMock.getCurrentArguments; +import static org.easymock.EasyMock.isA; +import static org.easymock.EasyMock.replay; +import static org.easymock.EasyMock.verify; +import org.easymock.IAnswer; + +/** + * @version $Rev$ $Date$ + */ +public class NonBlockingBridgingInterceptorTestCase extends TestCase { + + public void testInvoke() throws Exception { + WorkScheduler scheduler = createMock(WorkScheduler.class); + scheduler.scheduleWork(isA(Runnable.class)); + expectLastCall().andStubAnswer(new IAnswer<Object>() { + public Object answer() throws Throwable { + Runnable runnable = (Runnable) getCurrentArguments()[0]; + runnable.run(); + return null; + } + }); + replay(scheduler); + WorkContext context = createMock(WorkContext.class); + Message msg = new MessageImpl(); + Interceptor next = EasyMock.createMock(Interceptor.class); + EasyMock.expect(next.invoke(EasyMock.eq(msg))).andReturn(msg); + EasyMock.replay(next); + Interceptor interceptor = new NonBlockingBridgingInterceptor(scheduler, context, next); + interceptor.invoke(msg); + verify(next); + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/wire/OutboundInvocationErrorTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/wire/OutboundInvocationErrorTestCase.java new file mode 100644 index 0000000000..6313f14220 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/wire/OutboundInvocationErrorTestCase.java @@ -0,0 +1,135 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.wire; + +import java.lang.reflect.Method; +import java.lang.reflect.Proxy; + +import org.apache.tuscany.spi.idl.java.JavaInterfaceProcessorRegistry; +import org.apache.tuscany.spi.model.Operation; +import org.apache.tuscany.spi.model.ServiceContract; +import org.apache.tuscany.spi.wire.OutboundInvocationChain; +import org.apache.tuscany.spi.wire.OutboundWire; + +import junit.framework.TestCase; + +import org.apache.tuscany.core.component.WorkContextImpl; +import org.apache.tuscany.core.idl.java.JavaInterfaceProcessorRegistryImpl; +import org.apache.tuscany.core.mock.wire.MockStaticInvoker; +import org.apache.tuscany.core.mock.wire.MockSyncInterceptor; +import org.apache.tuscany.core.wire.jdk.JDKOutboundInvocationHandler; + +/** + * Tests handling of exceptions thrown during an outbound wire invocation + * + * @version $Rev$ $Date$ + */ +public class OutboundInvocationErrorTestCase extends TestCase { + + private Method checkedMethod; + private Method runtimeMethod; + private JavaInterfaceProcessorRegistry registry = new JavaInterfaceProcessorRegistryImpl(); + + public OutboundInvocationErrorTestCase() { + super(); + } + + public OutboundInvocationErrorTestCase(String arg0) { + super(arg0); + } + + public void setUp() throws Exception { + super.setUp(); + checkedMethod = TestBean.class.getDeclaredMethod("checkedException", (Class[]) null); + runtimeMethod = TestBean.class.getDeclaredMethod("runtimeException", (Class[]) null); + assertNotNull(checkedMethod); + assertNotNull(runtimeMethod); + } + + public void testCheckedException() throws Exception { + OutboundWire wire = new OutboundWireImpl(); + ServiceContract<?> contract = registry.introspect(TestBean.class); + wire.setServiceContract(contract); + Operation operation = contract.getOperations().get("checkedException"); + wire.addInvocationChain(operation, createChain(checkedMethod, operation)); + JDKOutboundInvocationHandler handler = new JDKOutboundInvocationHandler(wire, new WorkContextImpl()); + try { + TestBean proxy = (TestBean) Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), + new Class[]{TestBean.class}, handler); + proxy.checkedException(); + } catch (TestException e) { + return; + } + fail(TestException.class.getName() + " should have been thrown"); + } + + public void testRuntimeException() throws Exception { + OutboundWire wire = new OutboundWireImpl(); + ServiceContract<?> contract = registry.introspect(TestBean.class); + wire.setServiceContract(contract); + Operation operation = contract.getOperations().get("runtimeException"); + OutboundInvocationChain chain = createChain(runtimeMethod, operation); + wire.addInvocationChain(operation, chain); + JDKOutboundInvocationHandler handler = new JDKOutboundInvocationHandler(wire, new WorkContextImpl()); + try { + TestBean proxy = (TestBean) Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), + new Class[]{TestBean.class}, handler); + proxy.runtimeException(); + } catch (TestRuntimeException e) { + return; + } + fail(TestException.class.getName() + " should have been thrown"); + } + + private OutboundInvocationChain createChain(Method m, Operation operation) { + MockStaticInvoker invoker = new MockStaticInvoker(m, new TestBeanImpl()); + OutboundInvocationChain chain = new OutboundInvocationChainImpl(operation); + chain.addInterceptor(new MockSyncInterceptor()); + chain.setTargetInvoker(invoker); + chain.setTargetInterceptor(new InvokerInterceptor()); + chain.prepare(); + return chain; + } + + public interface TestBean { + + void checkedException() throws TestException; + + void runtimeException() throws TestRuntimeException; + + } + + public class TestBeanImpl implements TestBean { + + public void checkedException() throws TestException { + throw new TestException(); + } + + public void runtimeException() throws TestRuntimeException { + throw new TestRuntimeException(); + } + } + + public class TestException extends Exception { + } + + public class TestRuntimeException extends RuntimeException { + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/wire/OutboundInvocationHandlerTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/wire/OutboundInvocationHandlerTestCase.java new file mode 100644 index 0000000000..11e2a78d56 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/wire/OutboundInvocationHandlerTestCase.java @@ -0,0 +1,133 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.wire; + +import java.lang.reflect.Method; + +import org.apache.tuscany.spi.idl.java.JavaIDLUtils; +import org.apache.tuscany.spi.idl.java.JavaInterfaceProcessorRegistry; +import org.apache.tuscany.spi.model.Operation; +import org.apache.tuscany.spi.model.ServiceContract; +import org.apache.tuscany.spi.wire.InboundInvocationChain; +import org.apache.tuscany.spi.wire.OutboundInvocationChain; +import org.apache.tuscany.spi.wire.OutboundWire; + +import junit.framework.TestCase; +import org.apache.tuscany.core.component.WorkContextImpl; +import org.apache.tuscany.core.idl.java.JavaInterfaceProcessorRegistryImpl; +import org.apache.tuscany.core.mock.component.SimpleTarget; +import org.apache.tuscany.core.mock.component.SimpleTargetImpl; +import org.apache.tuscany.core.mock.wire.MockStaticInvoker; +import org.apache.tuscany.core.mock.wire.MockSyncInterceptor; +import org.apache.tuscany.core.wire.jdk.JDKOutboundInvocationHandler; + +public class OutboundInvocationHandlerTestCase extends TestCase { + + private Method hello; + private ServiceContract<?> contract; + + public OutboundInvocationHandlerTestCase() { + super(); + } + + public OutboundInvocationHandlerTestCase(String arg0) { + super(arg0); + } + + public void setUp() throws Exception { + super.setUp(); + JavaInterfaceProcessorRegistry registry = new JavaInterfaceProcessorRegistryImpl(); + contract = registry.introspect(SimpleTarget.class); + hello = SimpleTarget.class.getMethod("hello", String.class); + } + + public void testBasicInvoke() throws Throwable { + OutboundWire wire = new OutboundWireImpl(); + Operation operation = contract.getOperations().get("hello"); + wire.addInvocationChain(operation, createChain(operation)); + wire.setServiceContract(contract); + JDKOutboundInvocationHandler handler = new JDKOutboundInvocationHandler(wire, new WorkContextImpl()); + assertEquals("foo", handler.invoke(hello, new Object[]{"foo"})); + } + + public void testErrorInvoke() throws Throwable { + OutboundWire wire = new OutboundWireImpl(); + Operation operation = contract.getOperations().get("hello"); + wire.addInvocationChain(operation, createChain(operation)); + wire.setServiceContract(contract); + JDKOutboundInvocationHandler handler = new JDKOutboundInvocationHandler(wire, new WorkContextImpl()); + try { + handler.invoke(hello, new Object[]{}); + fail("Expected " + IllegalArgumentException.class.getName()); + } catch (IllegalArgumentException e) { + // should throw + } + } + + public void testDirectErrorInvoke() throws Throwable { + Operation operation = contract.getOperations().get("hello"); + OutboundInvocationChain source = new OutboundInvocationChainImpl(operation); + MockStaticInvoker invoker = new MockStaticInvoker(hello, new SimpleTargetImpl()); + source.setTargetInvoker(invoker); + + OutboundWire wire = new OutboundWireImpl(); + wire.setServiceContract(contract); + wire.addInvocationChain(operation, source); + JDKOutboundInvocationHandler handler = new JDKOutboundInvocationHandler(wire, new WorkContextImpl()); + try { + assertEquals("foo", handler.invoke(hello, new Object[]{})); + fail("Expected " + IllegalArgumentException.class.getName()); + } catch (IllegalArgumentException e) { + // should throw + } + } + + public void testDirectInvoke() throws Throwable { + Operation operation = contract.getOperations().get("hello"); + OutboundInvocationChain source = new OutboundInvocationChainImpl(operation); + MockStaticInvoker invoker = new MockStaticInvoker(hello, new SimpleTargetImpl()); + source.setTargetInvoker(invoker); + + OutboundWire wire = new OutboundWireImpl(); + wire.setServiceContract(contract); + wire.addInvocationChain(operation, source); + JDKOutboundInvocationHandler handler = new JDKOutboundInvocationHandler(wire, new WorkContextImpl()); + assertEquals("foo", handler.invoke(hello, new Object[]{"foo"})); + } + + private OutboundInvocationChain createChain(Operation operation) { + OutboundInvocationChain source = new OutboundInvocationChainImpl(operation); + MockSyncInterceptor sourceInterceptor = new MockSyncInterceptor(); + source.addInterceptor(sourceInterceptor); + + InboundInvocationChain target = new InboundInvocationChainImpl(operation); + MockSyncInterceptor targetInterceptor = new MockSyncInterceptor(); + target.addInterceptor(targetInterceptor); + target.addInterceptor(new InvokerInterceptor()); + + // connect the source to the target + source.setTargetInterceptor(targetInterceptor); + source.prepare(); + target.prepare(); + Method method = JavaIDLUtils.findMethod(operation, SimpleTarget.class.getMethods()); + MockStaticInvoker invoker = new MockStaticInvoker(method, new SimpleTargetImpl()); + source.setTargetInvoker(invoker); + return source; + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/wire/StaticPojoInvokerTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/wire/StaticPojoInvokerTestCase.java new file mode 100644 index 0000000000..e9e07dfa0a --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/wire/StaticPojoInvokerTestCase.java @@ -0,0 +1,157 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.wire; + +import static java.lang.Integer.TYPE; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; + +import junit.framework.Assert; +import junit.framework.TestCase; + +public class StaticPojoInvokerTestCase extends TestCase { + + private Method echoMethod; + private Method arrayMethod; + private Method nullParamMethod; + private Method primitiveMethod; + private Method checkedMethod; + private Method runtimeMethod; + + public StaticPojoInvokerTestCase() { + + } + + public StaticPojoInvokerTestCase(String arg0) { + super(arg0); + } + + public void setUp() throws Exception { + echoMethod = TestBean.class.getDeclaredMethod("echo", String.class); + arrayMethod = TestBean.class.getDeclaredMethod("arrayEcho", String[].class); + nullParamMethod = TestBean.class.getDeclaredMethod("nullParam", (Class[]) null); + primitiveMethod = TestBean.class.getDeclaredMethod("primitiveEcho", TYPE); + checkedMethod = TestBean.class.getDeclaredMethod("checkedException", (Class[]) null); + runtimeMethod = TestBean.class.getDeclaredMethod("runtimeException", (Class[]) null); + Assert.assertNotNull(echoMethod); + Assert.assertNotNull(checkedMethod); + Assert.assertNotNull(runtimeMethod); + } + + public void testObjectInvoke() throws Throwable { + TestBean bean = new TestBean(); + StaticPojoTargetInvoker invoker = new StaticPojoTargetInvoker(echoMethod, bean); + Object ret = invoker.invokeTarget("foo"); + Assert.assertEquals("foo", ret); + } + + public void testArrayInvoke() throws Throwable { + TestBean bean = new TestBean(); + StaticPojoTargetInvoker invoker = new StaticPojoTargetInvoker(arrayMethod, bean); + String[] args = new String[]{"foo", "bar"}; + Object ret = invoker.invokeTarget(new Object[]{args}); + String[] retA = (String[]) ret; + Assert.assertNotNull(retA); + Assert.assertEquals(2, retA.length); + Assert.assertEquals("foo", retA[0]); + Assert.assertEquals("bar", retA[1]); + } + + public void testNullInvoke() throws Throwable { + TestBean bean = new TestBean(); + StaticPojoTargetInvoker invoker = new StaticPojoTargetInvoker(nullParamMethod, bean); + Object ret = invoker.invokeTarget(null); + String retS = (String) ret; + Assert.assertEquals("foo", retS); + } + + public void testPrimitiveInvoke() throws Throwable { + TestBean bean = new TestBean(); + StaticPojoTargetInvoker invoker = new StaticPojoTargetInvoker(primitiveMethod, bean); + Object ret = invoker.invokeTarget(new Integer[]{1}); + Integer retI = (Integer) ret; + Assert.assertEquals(1, retI.intValue()); + } + + public void testInvokeCheckedException() throws Throwable { + TestBean bean = new TestBean(); + StaticPojoTargetInvoker invoker = new StaticPojoTargetInvoker(checkedMethod, bean); + try { + invoker.invokeTarget(null); + } catch (InvocationTargetException e) { + if (e.getCause() != null && TestException.class.equals(e.getCause().getClass())) { + return; + } + } catch (Throwable e) { + //ok + } + fail(TestException.class.getName() + " should have been thrown"); + } + + public void testInvokeRuntimeException() throws Throwable { + TestBean bean = new TestBean(); + StaticPojoTargetInvoker invoker = new StaticPojoTargetInvoker(runtimeMethod, bean); + try { + invoker.invokeTarget(null); + } catch (InvocationTargetException e) { + if (e.getCause() != null && e.getCause() instanceof TestRuntimeException) { + return; + } + } + fail(TestException.class.getName() + " should have been thrown"); + } + + private class TestBean { + + public String echo(String msg) throws Exception { + Assert.assertEquals("foo", msg); + return msg; + } + + public String[] arrayEcho(String[] msg) throws Exception { + Assert.assertNotNull(msg); + Assert.assertEquals(2, msg.length); + Assert.assertEquals("foo", msg[0]); + Assert.assertEquals("bar", msg[1]); + return msg; + } + + public String nullParam() throws Exception { + return "foo"; + } + + public int primitiveEcho(int i) throws Exception { + return i; + } + + public void checkedException() throws TestException { + throw new TestException(); + } + + public void runtimeException() throws TestRuntimeException { + throw new TestRuntimeException(); + } + } + + public class TestException extends Exception { + } + + public class TestRuntimeException extends RuntimeException { + } +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/wire/SynchronousBridgingInterceptorTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/wire/SynchronousBridgingInterceptorTestCase.java new file mode 100644 index 0000000000..f1631fc555 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/wire/SynchronousBridgingInterceptorTestCase.java @@ -0,0 +1,44 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.wire; + +import org.apache.tuscany.spi.wire.Interceptor; +import org.apache.tuscany.spi.wire.Message; +import org.apache.tuscany.spi.wire.MessageImpl; + +import org.easymock.EasyMock; +import static org.easymock.EasyMock.verify; +import junit.framework.TestCase; + +/** + * @version $Rev$ $Date$ + */ +public class SynchronousBridgingInterceptorTestCase extends TestCase { + + public void testInvoke() throws Exception { + Message msg = new MessageImpl(); + Interceptor next = EasyMock.createMock(Interceptor.class); + EasyMock.expect(next.invoke(EasyMock.eq(msg))).andReturn(msg); + EasyMock.replay(next); + Interceptor interceptor = new SynchronousBridgingInterceptor(next); + interceptor.invoke(msg); + verify(next); + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/wire/WireOptimizationTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/wire/WireOptimizationTestCase.java new file mode 100644 index 0000000000..97e27d947e --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/wire/WireOptimizationTestCase.java @@ -0,0 +1,139 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.wire; + +import java.lang.reflect.Method; +import java.lang.reflect.Type; + +import org.apache.tuscany.spi.model.Operation; +import org.apache.tuscany.spi.wire.InboundInvocationChain; +import org.apache.tuscany.spi.wire.InboundWire; +import org.apache.tuscany.spi.wire.Interceptor; +import org.apache.tuscany.spi.wire.Message; +import org.apache.tuscany.spi.wire.OutboundInvocationChain; +import org.apache.tuscany.spi.wire.OutboundWire; +import org.apache.tuscany.spi.wire.TargetInvoker; + +import junit.framework.TestCase; + +/** + * Verifies wire optimization analysis + * + * @version $$Rev$$ $$Date$$ + */ +public class WireOptimizationTestCase extends TestCase { + + private Operation operation; + private Method m; + + public void foo() { + } + + public void testSourceWireInterceptorOptimization() throws Exception { + OutboundWire wire = new OutboundWireImpl(); + OutboundInvocationChain chain = new OutboundInvocationChainImpl(operation); + chain.addInterceptor(new OptimizableInterceptor()); + wire.addInvocationChain(operation, chain); + assertTrue(wire.isOptimizable()); + } + + public void testSourceWireNonInterceptorOptimization() throws Exception { + OutboundWire wire = new OutboundWireImpl(); + OutboundInvocationChain chain = new OutboundInvocationChainImpl(operation); + chain.addInterceptor(new NonOptimizableInterceptor()); + wire.addInvocationChain(operation, chain); + assertFalse(wire.isOptimizable()); + } + + public void testTargetWireInterceptorOptimization() throws Exception { + InboundWire wire = new InboundWireImpl(); + InboundInvocationChain chain = new InboundInvocationChainImpl(operation); + chain.addInterceptor(new OptimizableInterceptor()); + wire.addInvocationChain(operation, chain); + assertTrue(wire.isOptimizable()); + } + + public void testTargetWireNonInterceptorOptimization() throws Exception { + InboundWire wire = new InboundWireImpl(); + InboundInvocationChain chain = new InboundInvocationChainImpl(operation); + chain.addInterceptor(new NonOptimizableInterceptor()); + wire.addInvocationChain(operation, chain); + assertFalse(wire.isOptimizable()); + } + + public void testTargetWireNonTargetInvokerOptimization() throws Exception { + InboundWire wire = new InboundWireImpl(); + InboundInvocationChain chain = new InboundInvocationChainImpl(operation); + TargetInvoker invoker = new StaticPojoTargetInvoker(m, new Object()); + invoker.setCacheable(false); + chain.setTargetInvoker(invoker); + wire.addInvocationChain(operation, chain); + assertFalse(wire.isOptimizable()); + } + + protected void tearDown() throws Exception { + super.tearDown(); + } + + protected void setUp() throws Exception { + super.setUp(); + m = getClass().getMethod("foo", (Class[]) null); + operation = new Operation<Type>("foo", null, null, null, false, null); + + } + + private class OptimizableInterceptor implements Interceptor { + + public Message invoke(Message msg) { + return null; + } + + public void setNext(Interceptor next) { + + } + + public Interceptor getNext() { + return null; + } + + public boolean isOptimizable() { + return true; + } + } + + private class NonOptimizableInterceptor implements Interceptor { + + public Message invoke(Message msg) { + return null; + } + + public void setNext(Interceptor next) { + + } + + public Interceptor getNext() { + return null; + } + + public boolean isOptimizable() { + return false; + } + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/wire/jdk/JDKInboundInvocationHandlerTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/wire/jdk/JDKInboundInvocationHandlerTestCase.java new file mode 100644 index 0000000000..d34ecd61f0 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/wire/jdk/JDKInboundInvocationHandlerTestCase.java @@ -0,0 +1,138 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.wire.jdk; + +import java.lang.reflect.Method; +import java.lang.reflect.Proxy; +import java.util.HashMap; +import java.util.Map; + +import org.apache.tuscany.spi.component.WorkContext; +import org.apache.tuscany.spi.idl.InvalidServiceContractException; +import org.apache.tuscany.spi.idl.java.JavaInterfaceProcessorRegistry; +import org.apache.tuscany.spi.model.Operation; +import org.apache.tuscany.spi.model.ServiceContract; +import org.apache.tuscany.spi.wire.InboundInvocationChain; + +import junit.framework.TestCase; + +import org.apache.tuscany.core.idl.java.JavaInterfaceProcessorRegistryImpl; +import org.apache.tuscany.core.mock.component.SimpleTarget; +import org.apache.tuscany.core.mock.component.SimpleTargetImpl; +import org.apache.tuscany.core.mock.wire.MockStaticInvoker; +import org.apache.tuscany.core.mock.wire.MockSyncInterceptor; +import org.apache.tuscany.core.wire.InboundInvocationChainImpl; +import org.apache.tuscany.core.wire.InvokerInterceptor; +import org.easymock.classextension.EasyMock; + +/** + * Verifies invocations on inbound wires + * + * @version $$Rev$$ $$Date$$ + */ +public class JDKInboundInvocationHandlerTestCase extends TestCase { + + private Method echo; + private Operation operation; + + public void testInterceptorInvoke() throws Throwable { + Map<Method, InboundInvocationChain> chains = new HashMap<Method, InboundInvocationChain>(); + MockStaticInvoker invoker = new MockStaticInvoker(echo, new SimpleTargetImpl()); + InboundInvocationChain chain = new InboundInvocationChainImpl(operation); + MockSyncInterceptor interceptor = new MockSyncInterceptor(); + chain.addInterceptor(interceptor); + chain.addInterceptor(new InvokerInterceptor()); + chain.setTargetInvoker(invoker); + chain.prepare(); + chains.put(echo, chain); + WorkContext workContext = EasyMock.createNiceMock(WorkContext.class); + EasyMock.replay(workContext); + JDKInboundInvocationHandler handler = new JDKInboundInvocationHandler(chains, workContext); + assertEquals("foo", handler.invoke(echo, new String[]{"foo"})); + assertEquals(1, interceptor.getCount()); + } + + + public void testDirectErrorInvoke() throws Throwable { + InboundInvocationChain source = new InboundInvocationChainImpl(operation); + MockStaticInvoker invoker = new MockStaticInvoker(echo, new SimpleTargetImpl()); + source.setTargetInvoker(invoker); + + Map<Method, InboundInvocationChain> chains = new HashMap<Method, InboundInvocationChain>(); + chains.put(echo, source); + WorkContext workContext = EasyMock.createNiceMock(WorkContext.class); + EasyMock.replay(workContext); + JDKInboundInvocationHandler handler = new JDKInboundInvocationHandler(chains, workContext); + try { + assertEquals("foo", handler.invoke(echo, new Object[]{})); + fail("Expected " + IllegalArgumentException.class.getName()); + } catch (IllegalArgumentException e) { + // should throw + } + } + + public void testDirectInvoke() throws Throwable { + InboundInvocationChain source = new InboundInvocationChainImpl(operation); + MockStaticInvoker invoker = new MockStaticInvoker(echo, new SimpleTargetImpl()); + source.setTargetInvoker(invoker); + + Map<Method, InboundInvocationChain> chains = new HashMap<Method, InboundInvocationChain>(); + chains.put(echo, source); + WorkContext workContext = EasyMock.createNiceMock(WorkContext.class); + EasyMock.replay(workContext); + JDKInboundInvocationHandler handler = new JDKInboundInvocationHandler(chains, workContext); + assertEquals("foo", handler.invoke(echo, new Object[]{"foo"})); + } + + public void testToString() { + WorkContext workContext = EasyMock.createNiceMock(WorkContext.class); + EasyMock.replay(workContext); + JDKInboundInvocationHandler handler = + new JDKInboundInvocationHandler(new HashMap<Method, InboundInvocationChain>(), workContext); + Foo foo = (Foo) Proxy.newProxyInstance(getClass().getClassLoader(), new Class[]{Foo.class}, handler); + assertNotNull(foo.toString()); + } + + public void testHashCode() { + WorkContext workContext = EasyMock.createNiceMock(WorkContext.class); + EasyMock.replay(workContext); + JDKInboundInvocationHandler handler = + new JDKInboundInvocationHandler(new HashMap<Method, InboundInvocationChain>(), workContext); + Foo foo = (Foo) Proxy.newProxyInstance(getClass().getClassLoader(), new Class[]{Foo.class}, handler); + assertNotNull(foo.hashCode()); + } + + public void setUp() throws Exception { + super.setUp(); + JavaInterfaceProcessorRegistry registry = new JavaInterfaceProcessorRegistryImpl(); + ServiceContract<?> contract; + try { + contract = registry.introspect(SimpleTarget.class); + } catch (InvalidServiceContractException e) { + throw new AssertionError(); + } + operation = contract.getOperations().get("echo"); + echo = SimpleTarget.class.getMethod("echo", String.class); + } + + private interface Foo { + + } + +} diff --git a/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/wire/jdk/JDKOutboundInvocationHandlerTestCase.java b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/wire/jdk/JDKOutboundInvocationHandlerTestCase.java new file mode 100644 index 0000000000..74338c4d38 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-M2/sca/kernel/core/src/test/java/org/apache/tuscany/core/wire/jdk/JDKOutboundInvocationHandlerTestCase.java @@ -0,0 +1,54 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.core.wire.jdk; + +import java.lang.reflect.Proxy; + +import org.apache.tuscany.spi.idl.java.JavaServiceContract; + +import junit.framework.TestCase; + +import org.apache.tuscany.core.component.WorkContextImpl; +import org.apache.tuscany.core.wire.OutboundWireImpl; + +/** + * @version $Rev$ $Date$ + */ +public class JDKOutboundInvocationHandlerTestCase extends TestCase { + + public void testToString() { + OutboundWireImpl wire = new OutboundWireImpl(); + wire.setServiceContract(new JavaServiceContract(Foo.class)); + JDKOutboundInvocationHandler handler = new JDKOutboundInvocationHandler(wire, new WorkContextImpl()); + Foo foo = (Foo) Proxy.newProxyInstance(getClass().getClassLoader(), new Class[]{Foo.class}, handler); + assertNotNull(foo.toString()); + } + + public void testHashCode() { + OutboundWireImpl wire = new OutboundWireImpl(); + wire.setServiceContract(new JavaServiceContract(Foo.class)); + JDKOutboundInvocationHandler handler = new JDKOutboundInvocationHandler(wire, new WorkContextImpl()); + Foo foo = (Foo) Proxy.newProxyInstance(getClass().getClassLoader(), new Class[]{Foo.class}, handler); + assertNotNull(foo.hashCode()); + } + + private interface Foo { + + } +} |