diff options
Diffstat (limited to 'tags/java/sca/2.0-M4-RC1/modules/core/src/main/java/org/apache/tuscany/sca/core/context/impl')
4 files changed, 1249 insertions, 0 deletions
diff --git a/tags/java/sca/2.0-M4-RC1/modules/core/src/main/java/org/apache/tuscany/sca/core/context/impl/CallbackServiceReferenceImpl.java b/tags/java/sca/2.0-M4-RC1/modules/core/src/main/java/org/apache/tuscany/sca/core/context/impl/CallbackServiceReferenceImpl.java new file mode 100644 index 0000000000..5218a7fd01 --- /dev/null +++ b/tags/java/sca/2.0-M4-RC1/modules/core/src/main/java/org/apache/tuscany/sca/core/context/impl/CallbackServiceReferenceImpl.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.sca.core.context.impl; + + +import java.util.List; + +import org.apache.tuscany.sca.assembly.Binding; +import org.apache.tuscany.sca.assembly.Endpoint; +import org.apache.tuscany.sca.assembly.EndpointReference; +import org.apache.tuscany.sca.context.ThreadMessageContext; +import org.apache.tuscany.sca.core.assembly.impl.RuntimeWireImpl; +import org.apache.tuscany.sca.core.invocation.ProxyFactory; +import org.apache.tuscany.sca.invocation.Message; +import org.apache.tuscany.sca.runtime.RuntimeComponentReference; +import org.apache.tuscany.sca.runtime.RuntimeWire; + +public class CallbackServiceReferenceImpl<B> extends ServiceReferenceImpl<B> { + private RuntimeWire wire; + private List<RuntimeWire> wires; + private Endpoint resolvedEndpoint; + + /* + * Public constructor for Externalizable serialization/deserialization + */ + public CallbackServiceReferenceImpl() { + super(); + } + + public CallbackServiceReferenceImpl(Class<B> interfaze, List<RuntimeWire> wires, ProxyFactory proxyFactory) { + super(interfaze, null, proxyFactory); + this.wires = wires; + init(); + } + + public void init() { + Message msgContext = ThreadMessageContext.getMessageContext(); + wire = selectCallbackWire(msgContext); + if (wire == null) { + //FIXME: need better exception + throw new RuntimeException("No callback binding found for " + msgContext.getTo().toString()); + } + resolvedEndpoint = msgContext.getFrom().getCallbackEndpoint(); + } + + @Override + protected Object createProxy() throws Exception { + return proxyFactory.createCallbackProxy(this); + } + + public RuntimeWire getCallbackWire() { + if (resolvedEndpoint == null) { + return null; + } else { + return cloneAndBind(wire); + } + } + + public Endpoint getResolvedEndpoint() { + return resolvedEndpoint; + } + + private RuntimeWire selectCallbackWire(Message msgContext) { + // look for callback binding with same name as service binding + Endpoint to = msgContext.getTo(); + if (to == null) { + //FIXME: need better exception + throw new RuntimeException("Destination for forward call is not available"); + } + for (RuntimeWire wire : wires) { + if (wire.getEndpointReference().getBinding().getName().equals(to.getBinding().getName())) { + return wire; + } + } + + // if no match, look for callback binding with same type as service binding + for (RuntimeWire wire : wires) { + if (wire.getEndpointReference().getBinding().getClass() == to.getBinding().getClass()) { + return wire; + } + } + + // no suitable callback wire was found + return null; + } + + private RuntimeWire cloneAndBind(RuntimeWire wire) { + RuntimeWire boundWire = null; + if (resolvedEndpoint != null) { + boundWire = ((RuntimeWireImpl)wire).lookupCache(resolvedEndpoint); + if (boundWire != null) { + return boundWire; + } + try { + // TODO - EPR - is this correct? + + // Fluff up a new response wire based on the callback endpoint + RuntimeComponentReference ref = + bind((RuntimeComponentReference)wire.getEndpointReference().getReference(), + resolvedEndpoint); + + boundWire = ref.getRuntimeWires().get(0); + + Binding binding = wire.getEndpointReference().getBinding(); + + ((RuntimeWireImpl)wire).addToCache(resolvedEndpoint, boundWire); + } catch (CloneNotSupportedException e) { + // will not happen + } + } + return boundWire; + } + + private RuntimeComponentReference bind(RuntimeComponentReference reference, + Endpoint callbackEndpoint) throws CloneNotSupportedException { + + // clone the callback reference ready to configure it for this callback endpoint + RuntimeComponentReference ref = (RuntimeComponentReference)reference.clone(); + ref.getTargets().clear(); + ref.getBindings().clear(); + ref.getEndpointReferences().clear(); + + // no access to the assembly factory so clone an existing epr + EndpointReference callbackEndpointReference = (EndpointReference)reference.getEndpointReferences().get(0).clone(); + + callbackEndpointReference.setReference(ref); + callbackEndpointReference.setTargetEndpoint(callbackEndpoint); + callbackEndpointReference.setUnresolved(true); + + // TODO - should really use incoming callback info but awaiting + // decision from OASIS on what will happen with callbacks + // The callback endpoint will be resolved with the registry + // when the wire chains are created + ref.getEndpointReferences().add(callbackEndpointReference); + + return ref; + } +} diff --git a/tags/java/sca/2.0-M4-RC1/modules/core/src/main/java/org/apache/tuscany/sca/core/context/impl/ComponentContextImpl.java b/tags/java/sca/2.0-M4-RC1/modules/core/src/main/java/org/apache/tuscany/sca/core/context/impl/ComponentContextImpl.java new file mode 100644 index 0000000000..4e71181747 --- /dev/null +++ b/tags/java/sca/2.0-M4-RC1/modules/core/src/main/java/org/apache/tuscany/sca/core/context/impl/ComponentContextImpl.java @@ -0,0 +1,496 @@ +/* + * 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.sca.core.context.impl; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; + +import org.apache.tuscany.sca.assembly.AssemblyFactory; +import org.apache.tuscany.sca.assembly.Binding; +import org.apache.tuscany.sca.assembly.Component; +import org.apache.tuscany.sca.assembly.ComponentProperty; +import org.apache.tuscany.sca.assembly.ComponentReference; +import org.apache.tuscany.sca.assembly.ComponentService; +import org.apache.tuscany.sca.assembly.Endpoint; +import org.apache.tuscany.sca.assembly.EndpointReference; +import org.apache.tuscany.sca.assembly.Multiplicity; +import org.apache.tuscany.sca.assembly.OptimizableBinding; +import org.apache.tuscany.sca.assembly.Reference; +import org.apache.tuscany.sca.assembly.Service; +import org.apache.tuscany.sca.context.CompositeContext; +import org.apache.tuscany.sca.context.ContextFactoryExtensionPoint; +import org.apache.tuscany.sca.context.PropertyValueFactory; +import org.apache.tuscany.sca.context.RequestContextFactory; +import org.apache.tuscany.sca.core.ExtensionPointRegistry; +import org.apache.tuscany.sca.core.FactoryExtensionPoint; +import org.apache.tuscany.sca.core.UtilityExtensionPoint; +import org.apache.tuscany.sca.core.invocation.ExtensibleProxyFactory; +import org.apache.tuscany.sca.core.invocation.ProxyFactory; +import org.apache.tuscany.sca.core.invocation.ProxyFactoryExtensionPoint; +import org.apache.tuscany.sca.interfacedef.Interface; +import org.apache.tuscany.sca.interfacedef.InterfaceContract; +import org.apache.tuscany.sca.interfacedef.InvalidInterfaceException; +import org.apache.tuscany.sca.interfacedef.java.JavaInterface; +import org.apache.tuscany.sca.interfacedef.java.JavaInterfaceFactory; +import org.apache.tuscany.sca.monitor.Monitor; +import org.apache.tuscany.sca.monitor.MonitorFactory; +import org.apache.tuscany.sca.runtime.CompositeActivator; +import org.apache.tuscany.sca.runtime.EndpointReferenceBinder; +import org.apache.tuscany.sca.runtime.RuntimeComponent; +import org.apache.tuscany.sca.runtime.RuntimeComponentContext; +import org.apache.tuscany.sca.runtime.RuntimeComponentReference; +import org.apache.tuscany.sca.runtime.RuntimeComponentService; +import org.oasisopen.sca.RequestContext; +import org.oasisopen.sca.SCARuntimeException; +import org.oasisopen.sca.ServiceReference; +import org.oasisopen.sca.ServiceRuntimeException; + +/** + * Implementation of ComponentContext that delegates to a ComponentContextProvider. + * + * @version $Rev$ $Date$ + */ +public class ComponentContextImpl implements RuntimeComponentContext { + private final RuntimeComponent component; + + private final CompositeContext compositeContext; + private final CompositeActivator compositeActivator; + private final RequestContextFactory requestContextFactory; + private final ProxyFactory proxyFactory; + private final AssemblyFactory assemblyFactory; + private final JavaInterfaceFactory javaInterfaceFactory; + private final PropertyValueFactory propertyFactory; + private final EndpointReferenceBinder eprBinder; + private final Monitor monitor; + + public ComponentContextImpl(ExtensionPointRegistry registry, CompositeContext compositeContext, RuntimeComponent component) { + this.component = component; + FactoryExtensionPoint factories = registry.getExtensionPoint(FactoryExtensionPoint.class); + this.assemblyFactory = factories.getFactory(AssemblyFactory.class); + this.javaInterfaceFactory = factories.getFactory(JavaInterfaceFactory.class); + + UtilityExtensionPoint utilities = registry.getExtensionPoint(UtilityExtensionPoint.class); + this.compositeContext = compositeContext; + + this.compositeActivator = utilities.getUtility(CompositeActivator.class); + + this.requestContextFactory = + registry.getExtensionPoint(ContextFactoryExtensionPoint.class).getFactory(RequestContextFactory.class); + this.proxyFactory = new ExtensibleProxyFactory(registry.getExtensionPoint(ProxyFactoryExtensionPoint.class)); + this.propertyFactory = factories.getFactory(PropertyValueFactory.class); + + this.eprBinder = utilities.getUtility(EndpointReferenceBinder.class); + + MonitorFactory monitorFactory = utilities.getUtility(MonitorFactory.class); + this.monitor = monitorFactory.createMonitor(); + } + + public String getURI() { + return component.getURI(); + } + + public <B, R extends ServiceReference<B>> R cast(B target) throws IllegalArgumentException { + return (R)proxyFactory.cast(target); + } + + public <B> B getService(Class<B> businessInterface, String referenceName) { + ServiceReference<B> serviceRef = getServiceReference(businessInterface, referenceName); + return serviceRef.getService(); + } + + public <B> ServiceReference<B> getServiceReference(Class<B> businessInterface, String referenceName) { + try { + for (ComponentReference ref : component.getReferences()) { + if (referenceName.equals(ref.getName())) { + /* ******************** Contribution for issue TUSCANY-2281 ******************** */ + Multiplicity multiplicity = ref.getMultiplicity(); + if (multiplicity == Multiplicity.ZERO_N || multiplicity == Multiplicity.ONE_N) { + throw new IllegalArgumentException("Reference " + referenceName + + " has multiplicity " + + multiplicity); + } + /* ******************** Contribution for issue TUSCANY-2281 ******************** */ + + return getServiceReference(businessInterface, (RuntimeComponentReference)ref, null); + } + } + throw new ServiceRuntimeException("Reference not found: " + referenceName); + } catch (ServiceRuntimeException e) { + throw e; + } catch (Exception e) { + if (e instanceof RuntimeException) { + throw (RuntimeException)e; + } + throw new ServiceRuntimeException(e.getMessage(), e); + } + } + + /** + * Gets the value for the specified property with the specified type. + * + * @param type The type of the property value we are getting + * @param propertyName The name of the property we are getting + * @param B The class of the property value we are getting + * + * @throws ServiceRuntimeException If a Property for the specified propertyName + * is not found + * + * @see #setPropertyValueFactory(PropertyValueFactory) + */ + public <B> B getProperty(Class<B> type, String propertyName) { + for (ComponentProperty p : component.getProperties()) { + if (propertyName.equals(p.getName())) { + return propertyFactory.createPropertyValue(p, type); + } + } + throw new ServiceRuntimeException("Property not found: " + propertyName); + } + + /** + * @param component + */ + public static ComponentService getSingleService(Component component) { + ComponentService targetService; + List<ComponentService> services = component.getServices(); + List<ComponentService> regularServices = new ArrayList<ComponentService>(); + for (ComponentService service : services) { + if (service.isForCallback()) { + continue; + } + String name = service.getName(); + if (!name.startsWith("$") || name.startsWith("$dynamic$")) { + regularServices.add(service); + } + } + if (regularServices.size() == 0) { + throw new ServiceRuntimeException("No service is declared on component " + component.getURI()); + } + if (regularServices.size() != 1) { + throw new ServiceRuntimeException("More than one service is declared on component " + component.getURI() + + ". Service name is required to get the service."); + } + targetService = regularServices.get(0); + return targetService; + } + + + public <B> ServiceReference<B> createSelfReference(Class<B> businessInterface) { + ComponentService service = getSingleService(component); + try { + return createSelfReference(businessInterface, service); + } catch (Exception e) { + throw new ServiceRuntimeException(e.getMessage(), e); + } + } + + public <B> ServiceReference<B> createSelfReference(Class<B> businessInterface, String serviceName) { + try { + for (ComponentService service : component.getServices()) { + if (serviceName.equals(service.getName())) { + return createSelfReference(businessInterface, service); + } + } + throw new ServiceRuntimeException("Service not found: " + serviceName); + } catch (ServiceRuntimeException e) { + throw e; + } catch (Exception e) { + throw new ServiceRuntimeException(e.getMessage(), e); + } + } + + /** + * @param <B> + * @param businessInterface + * @param service + * @return + */ + public <B> ServiceReference<B> createSelfReference(Class<B> businessInterface, ComponentService service) { + try { + RuntimeComponentReference ref = + (RuntimeComponentReference)createSelfReference(component, service, businessInterface); + ref.setComponent(component); + return getServiceReference(businessInterface, ref, null); + } catch (Exception e) { + throw new ServiceRuntimeException(e); + } + } + + public RequestContext getRequestContext() { + if (requestContextFactory != null) { + return requestContextFactory.createRequestContext(component); + } else { + return new RequestContextImpl(component); + } + } + + /** + * @param businessInterface + * @param reference + * @return + * @throws CloneNotSupportedException + * @throws InvalidInterfaceException + */ + public <B> ServiceReference<B> getServiceReference(Class<B> businessInterface, + RuntimeComponentReference reference, + EndpointReference endpointReference) { + try { + RuntimeComponentReference ref = (RuntimeComponentReference)reference; + InterfaceContract interfaceContract = reference.getInterfaceContract(); + Reference componentTypeReference = reference.getReference(); + if (componentTypeReference != null && componentTypeReference.getInterfaceContract() != null) { + interfaceContract = componentTypeReference.getInterfaceContract(); + } + InterfaceContract refInterfaceContract = getInterfaceContract(interfaceContract, businessInterface); + if (refInterfaceContract != interfaceContract) { + ref = (RuntimeComponentReference)reference.clone(); + if (interfaceContract != null) { + ref.setInterfaceContract(interfaceContract); + } else { + ref.setInterfaceContract(refInterfaceContract); + } + } + ref.setComponent(component); + return new ServiceReferenceImpl<B>(businessInterface, component, ref, endpointReference, proxyFactory, + component.getComponentContext().getCompositeContext()); + } catch (Exception e) { + throw new ServiceRuntimeException(e); + } + } + + /** + * Bind a component reference to a component service + * @param <B> + * @param businessInterface + * @param reference + * @param service + * @return + * @throws CloneNotSupportedException + * @throws InvalidInterfaceException + */ + public <B> ServiceReference<B> getServiceReference(Class<B> businessInterface, + RuntimeComponentReference reference, + RuntimeComponent component, + RuntimeComponentService service) { + try { + RuntimeComponentReference ref = (RuntimeComponentReference)reference.clone(); + InterfaceContract interfaceContract = reference.getInterfaceContract(); + Reference componentTypeReference = reference.getReference(); + if (componentTypeReference != null && componentTypeReference.getInterfaceContract() != null) { + interfaceContract = componentTypeReference.getInterfaceContract(); + } + InterfaceContract refInterfaceContract = getInterfaceContract(interfaceContract, businessInterface); + if (refInterfaceContract != interfaceContract) { + ref = (RuntimeComponentReference)reference.clone(); + ref.setInterfaceContract(interfaceContract); + } + ref.getTargets().add(service); + ref.getBindings().clear(); + for (Binding binding : service.getBindings()) { + if (binding instanceof OptimizableBinding) { + OptimizableBinding optimizableBinding = (OptimizableBinding)((OptimizableBinding)binding).clone(); + optimizableBinding.setTargetBinding(binding); + optimizableBinding.setTargetComponent(component); + optimizableBinding.setTargetComponentService(service); + ref.getBindings().add(optimizableBinding); + } else { + ref.getBindings().add(binding); + } + } + return new ServiceReferenceImpl<B>(businessInterface, component, ref, null, proxyFactory, compositeContext); + } catch (Exception e) { + throw new ServiceRuntimeException(e); + } + } + + public <B> ServiceReference<B> getCallableReference(Class<B> businessInterface, + RuntimeComponent component, + RuntimeComponentService service) { + try { + if (businessInterface == null) { + InterfaceContract contract = service.getInterfaceContract(); + businessInterface = (Class<B>)((JavaInterface)contract.getInterface()).getJavaClass(); + } + RuntimeComponentReference ref = + (RuntimeComponentReference)createSelfReference(component, service, businessInterface); + ref.setComponent(component); + return new ServiceReferenceImpl<B>(businessInterface, component, ref, null, proxyFactory, + compositeContext); + } catch (Exception e) { + throw new ServiceRuntimeException(e); + } + } + + /** + * Create a self-reference for a component service + * @param component + * @param service + * @throws CloneNotSupportedException + * @throws InvalidInterfaceException + */ + private ComponentReference createSelfReference(Component component, + ComponentService service, + Class<?> businessInterface) throws CloneNotSupportedException, + InvalidInterfaceException { + ComponentReference componentReference = assemblyFactory.createComponentReference(); + componentReference.setName("$self$." + service.getName()); + + for (Binding binding : service.getBindings()) { + if (binding instanceof OptimizableBinding) { + OptimizableBinding optimizableBinding = (OptimizableBinding)((OptimizableBinding)binding).clone(); + optimizableBinding.setTargetBinding(binding); + optimizableBinding.setTargetComponent(component); + optimizableBinding.setTargetComponentService(service); + componentReference.getBindings().add(optimizableBinding); + } else { + componentReference.getBindings().add(binding); + } + } + + componentReference.setCallback(service.getCallback()); + componentReference.getTargets().add(service); + componentReference.getPolicySets().addAll(service.getPolicySets()); + componentReference.getRequiredIntents().addAll(service.getRequiredIntents()); + + InterfaceContract interfaceContract = service.getInterfaceContract(); + Service componentTypeService = service.getService(); + if (componentTypeService != null && componentTypeService.getInterfaceContract() != null) { + interfaceContract = componentTypeService.getInterfaceContract(); + } + interfaceContract = getInterfaceContract(interfaceContract, businessInterface); + componentReference.setInterfaceContract(interfaceContract); + componentReference.setMultiplicity(Multiplicity.ONE_ONE); + // component.getReferences().add(componentReference); + + // create endpoint reference + EndpointReference endpointReference = assemblyFactory + .createEndpointReference(); + endpointReference.setComponent(component); + endpointReference.setReference(componentReference); + endpointReference.setUnresolved(false); + endpointReference.setStatus(EndpointReference.WIRED_TARGET_FOUND_READY_FOR_MATCHING); + + // create endpoint. + Endpoint endpoint = assemblyFactory.createEndpoint(); + endpoint.setComponent(component); + endpoint.setService(service); + endpoint.setUnresolved(true); + endpointReference.setTargetEndpoint(endpoint); + + componentReference.getEndpointReferences().add(endpointReference); + + // do binding matching + boolean ok = eprBinder.bind(compositeContext.getEndpointRegistry(), endpointReference); + + if (!ok) { + throw new SCARuntimeException("Unable to bind " + endpointReference); + } + + return componentReference; + } + + /** + * @param interfaceContract + * @param businessInterface + * @return + * @throws CloneNotSupportedException + * @throws InvalidInterfaceException + */ + private InterfaceContract getInterfaceContract(InterfaceContract interfaceContract, Class<?> businessInterface) + throws CloneNotSupportedException, InvalidInterfaceException { + boolean compatible = false; + if (interfaceContract != null && interfaceContract.getInterface() != null) { + Interface interfaze = interfaceContract.getInterface(); + if (interfaze instanceof JavaInterface) { + Class<?> cls = ((JavaInterface)interfaze).getJavaClass(); + if (businessInterface.isAssignableFrom(cls)) { + compatible = true; + } + } + } + + if (!compatible) { + // The interface is not assignable from the interface contract + interfaceContract = javaInterfaceFactory.createJavaInterfaceContract(); + JavaInterface callInterface = javaInterfaceFactory.createJavaInterface(businessInterface); + interfaceContract.setInterface(callInterface); + if (callInterface.getCallbackClass() != null) { + interfaceContract.setCallbackInterface(javaInterfaceFactory.createJavaInterface(callInterface + .getCallbackClass())); + } + } + + return interfaceContract; + } + + /** + * @see org.apache.tuscany.sca.runtime.RuntimeComponentContext#start(org.apache.tuscany.sca.runtime.RuntimeComponentReference) + */ + public void start(RuntimeComponentReference reference) { + compositeActivator.start(compositeContext, component, reference); + } + + + /* ******************** Contribution for issue TUSCANY-2281 ******************** */ + + /** + * @see ComponentContext#getServices(Class<B>, String) + */ + public <B> Collection<B> getServices(Class<B> businessInterface, String referenceName) { + ArrayList<B> services = new ArrayList<B>(); + Collection<ServiceReference<B>> serviceRefs = getServiceReferences(businessInterface, referenceName); + for (ServiceReference<B> serviceRef : serviceRefs) { + services.add(serviceRef.getService()); + } + return services; + } + + /** + * @see ComponentContext#getServiceReferences(Class<B>, String) + */ + public <B> Collection<ServiceReference<B>> getServiceReferences(Class<B> businessInterface, String referenceName) { + try { + for (ComponentReference ref : component.getReferences()) { + if (referenceName.equals(ref.getName())) { + ArrayList<ServiceReference<B>> serviceRefs = new ArrayList<ServiceReference<B>>(); + for (EndpointReference endpointReference : ref.getEndpointReferences()) { + serviceRefs + .add(getServiceReference(businessInterface, (RuntimeComponentReference)ref, endpointReference)); + } + return serviceRefs; + } + } + throw new ServiceRuntimeException("Reference not found: " + referenceName); + } catch (ServiceRuntimeException e) { + throw e; + } catch (Exception e) { + throw new ServiceRuntimeException(e.getMessage(), e); + } + } + /* ******************** Contribution for issue TUSCANY-2281 ******************** */ + + public CompositeContext getCompositeContext() { + return compositeContext; + } + + public ExtensionPointRegistry getExtensionPointRegistry() { + return getCompositeContext().getExtensionPointRegistry(); + } + +} diff --git a/tags/java/sca/2.0-M4-RC1/modules/core/src/main/java/org/apache/tuscany/sca/core/context/impl/RequestContextImpl.java b/tags/java/sca/2.0-M4-RC1/modules/core/src/main/java/org/apache/tuscany/sca/core/context/impl/RequestContextImpl.java new file mode 100644 index 0000000000..e8a1254dc9 --- /dev/null +++ b/tags/java/sca/2.0-M4-RC1/modules/core/src/main/java/org/apache/tuscany/sca/core/context/impl/RequestContextImpl.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.sca.core.context.impl; + +import java.util.List; + +import javax.security.auth.Subject; + +import org.apache.tuscany.sca.assembly.Endpoint; +import org.apache.tuscany.sca.context.ThreadMessageContext; +import org.apache.tuscany.sca.core.ExtensionPointRegistry; +import org.apache.tuscany.sca.core.invocation.ExtensibleProxyFactory; +import org.apache.tuscany.sca.core.invocation.ProxyFactory; +import org.apache.tuscany.sca.core.invocation.ProxyFactoryExtensionPoint; +import org.apache.tuscany.sca.interfacedef.java.JavaInterface; +import org.apache.tuscany.sca.invocation.Message; +import org.apache.tuscany.sca.runtime.RuntimeComponent; +import org.apache.tuscany.sca.runtime.RuntimeComponentReference; +import org.apache.tuscany.sca.runtime.RuntimeComponentService; +import org.apache.tuscany.sca.runtime.RuntimeWire; +import org.oasisopen.sca.RequestContext; +import org.oasisopen.sca.ServiceReference; + +/** + * @version $Rev$ $Date$ + */ +public class RequestContextImpl implements RequestContext { + + private ProxyFactoryExtensionPoint proxyFactoryExtensionPoint; + + public RequestContextImpl(RuntimeComponent component) { + ExtensionPointRegistry registry = component.getComponentContext().getExtensionPointRegistry(); + proxyFactoryExtensionPoint = registry.getExtensionPoint(ProxyFactoryExtensionPoint.class); + } + + public Subject getSecuritySubject() { + Subject subject = null; + + for (Object header : ThreadMessageContext.getMessageContext().getHeaders()){ + if (header instanceof Subject){ + subject = (Subject)header; + break; + } + } + return subject; + } + + public String getServiceName() { + return ThreadMessageContext.getMessageContext().getTo().getService().getName(); + } + + public <B> ServiceReference<B> getServiceReference() { + Message msgContext = ThreadMessageContext.getMessageContext(); + // FIXME: [rfeng] Is this the service reference matching the caller side? + Endpoint to = msgContext.getTo(); + RuntimeComponentService service = (RuntimeComponentService) to.getService(); + RuntimeComponent component = (RuntimeComponent) to.getComponent(); + + ServiceReference<B> callableReference = component.getComponentContext().getCallableReference(null, component, service); + + //TODO - EPR - not required for OASIS + //ReferenceParameters parameters = msgContext.getFrom().getReferenceParameters(); + //((CallableReferenceExt<B>) callableReference).attachCallbackID(parameters.getCallbackID()); + //((CallableReferenceExt<B>) callableReference).attachConversation(parameters.getConversationID()); + + return callableReference; + } + + public <CB> CB getCallback() { + ServiceReference<CB> cb = getCallbackReference(); + if (cb == null) { + return null; + } + return cb.getService(); + } + + @SuppressWarnings("unchecked") + public <CB> ServiceReference<CB> getCallbackReference() { + Message msgContext = ThreadMessageContext.getMessageContext(); + Endpoint to = msgContext.getTo(); + RuntimeComponentService service = (RuntimeComponentService) to.getService(); + RuntimeComponentReference callbackReference = (RuntimeComponentReference)service.getCallbackReference(); + if (callbackReference == null) { + return null; + } + JavaInterface javaInterface = (JavaInterface) callbackReference.getInterfaceContract().getInterface(); + Class<CB> javaClass = (Class<CB>)javaInterface.getJavaClass(); + List<RuntimeWire> wires = callbackReference.getRuntimeWires(); + ProxyFactory proxyFactory = new ExtensibleProxyFactory(proxyFactoryExtensionPoint); + ServiceReferenceImpl ref = new CallbackServiceReferenceImpl(javaClass, wires, proxyFactory); + if (ref != null) { + //ref.resolveTarget(); + // TODO - EPR - not required for OASIS + //ReferenceParameters parameters = msgContext.getFrom().getReferenceParameters(); + //ref.attachCallbackID(parameters.getCallbackID()); + //if (ref.getConversation() != null) { + // ref.attachConversationID(parameters.getConversationID()); + //} + } + return ref; + } +} diff --git a/tags/java/sca/2.0-M4-RC1/modules/core/src/main/java/org/apache/tuscany/sca/core/context/impl/ServiceReferenceImpl.java b/tags/java/sca/2.0-M4-RC1/modules/core/src/main/java/org/apache/tuscany/sca/core/context/impl/ServiceReferenceImpl.java new file mode 100644 index 0000000000..23126b5123 --- /dev/null +++ b/tags/java/sca/2.0-M4-RC1/modules/core/src/main/java/org/apache/tuscany/sca/core/context/impl/ServiceReferenceImpl.java @@ -0,0 +1,481 @@ +/* + * 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.sca.core.context.impl; + +import java.io.IOException; +import java.io.ObjectInput; +import java.io.ObjectOutput; +import java.io.Reader; +import java.io.StringReader; +import java.io.StringWriter; +import java.security.AccessController; +import java.security.PrivilegedAction; +import java.util.UUID; + +import javax.xml.stream.XMLInputFactory; +import javax.xml.stream.XMLOutputFactory; +import javax.xml.stream.XMLStreamException; +import javax.xml.stream.XMLStreamReader; +import javax.xml.stream.XMLStreamWriter; + +import org.apache.tuscany.sca.assembly.AssemblyFactory; +import org.apache.tuscany.sca.assembly.Binding; +import org.apache.tuscany.sca.assembly.ComponentService; +import org.apache.tuscany.sca.assembly.CompositeService; +import org.apache.tuscany.sca.assembly.EndpointReference; +import org.apache.tuscany.sca.assembly.Service; +import org.apache.tuscany.sca.assembly.builder.BindingBuilder; +import org.apache.tuscany.sca.assembly.builder.BuilderContext; +import org.apache.tuscany.sca.assembly.builder.BuilderExtensionPoint; +import org.apache.tuscany.sca.context.CompositeContext; +import org.apache.tuscany.sca.contribution.processor.ContributionReadException; +import org.apache.tuscany.sca.contribution.processor.ContributionWriteException; +import org.apache.tuscany.sca.contribution.processor.ProcessorContext; +import org.apache.tuscany.sca.contribution.processor.StAXArtifactProcessor; +import org.apache.tuscany.sca.contribution.processor.StAXArtifactProcessorExtensionPoint; +import org.apache.tuscany.sca.core.ExtensionPointRegistry; +import org.apache.tuscany.sca.core.FactoryExtensionPoint; +import org.apache.tuscany.sca.core.assembly.RuntimeAssemblyFactory; +import org.apache.tuscany.sca.core.assembly.impl.ReferenceParametersImpl; +import org.apache.tuscany.sca.core.context.ServiceReferenceExt; +import org.apache.tuscany.sca.core.factory.ObjectCreationException; +import org.apache.tuscany.sca.core.invocation.ExtensibleProxyFactory; +import org.apache.tuscany.sca.core.invocation.ProxyFactory; +import org.apache.tuscany.sca.core.invocation.ProxyFactoryExtensionPoint; +import org.apache.tuscany.sca.interfacedef.Interface; +import org.apache.tuscany.sca.interfacedef.java.JavaInterface; +import org.apache.tuscany.sca.interfacedef.java.JavaInterfaceFactory; +import org.apache.tuscany.sca.runtime.ReferenceParameters; +import org.apache.tuscany.sca.runtime.RuntimeComponent; +import org.apache.tuscany.sca.runtime.RuntimeComponentReference; +import org.apache.tuscany.sca.runtime.RuntimeWire; +import org.oasisopen.sca.ServiceRuntimeException; + +/** + * Default implementation of a ServiceReference. + * + * @version $Rev$ $Date$ + * @param <B> the type of the business interface + */ +public class ServiceReferenceImpl<B> implements ServiceReferenceExt<B> { + private static final long serialVersionUID = 6763709434194361540L; + + protected transient ProxyFactory proxyFactory; + protected transient Class<B> businessInterface; + protected transient Object proxy; + + protected Object callbackID; // The callbackID should be serializable + + protected transient RuntimeComponent component; + protected transient RuntimeComponentReference reference; + protected transient EndpointReference endpointReference; + + protected String scdl; + + private transient XMLStreamReader xmlReader; + + protected transient CompositeContext compositeContext; + private ExtensionPointRegistry registry; + private FactoryExtensionPoint modelFactories; + protected RuntimeAssemblyFactory assemblyFactory; + private StAXArtifactProcessorExtensionPoint staxProcessors; + private StAXArtifactProcessor<EndpointReference> staxProcessor; + private XMLInputFactory xmlInputFactory; + private XMLOutputFactory xmlOutputFactory; + private BuilderExtensionPoint builders; + + /* + * Public constructor for Externalizable serialization/deserialization + */ + public ServiceReferenceImpl() { + super(); + } + + /* + * Public constructor for use by XMLStreamReader2CallableReference + */ + // TODO - EPR - Is this required + public ServiceReferenceImpl(XMLStreamReader xmlReader) throws Exception { + this.xmlReader = xmlReader; + resolve(); + } + + protected ServiceReferenceImpl(Class<B> businessInterface, + RuntimeComponent component, + RuntimeComponentReference reference, + EndpointReference endpointReference, + ProxyFactory proxyFactory, + CompositeContext compositeContext) { + this.proxyFactory = proxyFactory; + this.businessInterface = businessInterface; + this.component = component; + this.reference = reference; + this.endpointReference = endpointReference; + this.compositeContext = compositeContext; + + getExtensions(); + + // FIXME: The SCA Specification is not clear how we should handle multiplicity + // for CallableReference + if (this.endpointReference == null) { + + // TODO - EPR - If no endpoint reference specified assume the first one + // This will happen when a self reference is created in which case the + // the reference should only have one endpointReference so use that + if (this.reference.getEndpointReferences().size() == 0){ + throw new ServiceRuntimeException("The reference " + reference.getName() + " in component " + + component.getName() + " has no endpoint references"); + } + + if (this.reference.getEndpointReferences().size() > 1){ + throw new ServiceRuntimeException("The reference " + reference.getName() + " in component " + + component.getName() + " has more than one endpoint reference"); + } + + this.endpointReference = this.reference.getEndpointReferences().get(0); + } + + // FIXME: Should we normalize the componentName/serviceName URI into an absolute SCA URI in the SCA binding? + // sca:component1/component11/component112/service1? + initCallbackID(); + } + + private void getExtensions() { + this.registry = compositeContext.getExtensionPointRegistry(); + this.modelFactories = registry.getExtensionPoint(FactoryExtensionPoint.class); + this.assemblyFactory = (RuntimeAssemblyFactory)modelFactories.getFactory(AssemblyFactory.class); + this.xmlInputFactory = modelFactories.getFactory(XMLInputFactory.class); + this.xmlOutputFactory = modelFactories.getFactory(XMLOutputFactory.class); + this.staxProcessors = registry.getExtensionPoint(StAXArtifactProcessorExtensionPoint.class); + this.staxProcessor = staxProcessors.getProcessor(EndpointReference.class); + this.builders = registry.getExtensionPoint(BuilderExtensionPoint.class); + } + + public ServiceReferenceImpl(Class<B> businessInterface, RuntimeWire wire, ProxyFactory proxyFactory) { + this.proxyFactory = proxyFactory; + this.businessInterface = businessInterface; + //ExtensionPointRegistry registry = ((RuntimeWireImpl)wire).getExtensionPoints(); + //this.modelFactories = registry.getExtensionPoint(FactoryExtensionPoint.class); + //this.assemblyFactory = (RuntimeAssemblyFactory)modelFactories.getFactory(AssemblyFactory.class); + bind(wire); + } + + public RuntimeWire getRuntimeWire() { + try { + resolve(); + if (endpointReference != null){ + return reference.getRuntimeWire(endpointReference); + } else { + return null; + } + } catch (Exception e) { + throw new ServiceRuntimeException(e); + } + } + + public EndpointReference getEndpointReference() { + return endpointReference; + } + + protected void bind(RuntimeWire wire) { + if (wire != null) { + this.component = (RuntimeComponent)wire.getEndpointReference().getComponent(); + this.reference = (RuntimeComponentReference)wire.getEndpointReference().getReference(); + this.endpointReference = wire.getEndpointReference(); + this.compositeContext = component.getComponentContext().getCompositeContext(); + initCallbackID(); + } + } + + protected void initCallbackID() { + if (reference.getInterfaceContract() != null) { + if (reference.getInterfaceContract().getCallbackInterface() != null) { + this.callbackID = createCallbackID(); + } + } + } + + public B getProxy() throws ObjectCreationException { + try { + if (proxy == null) { + proxy = createProxy(); + } + return businessInterface.cast(proxy); + } catch (Exception e) { + throw new ObjectCreationException(e); + } + } + + public void setProxy(Object proxy) { + this.proxy = proxy; + } + + protected Object createProxy() throws Exception { + return proxyFactory.createProxy(this); + } + + public B getService() { + try { + resolve(); + return getProxy(); + } catch (Exception e) { + throw new ServiceRuntimeException(e); + } + } + + public Class<B> getBusinessInterface() { + try { + resolve(); + return businessInterface; + } catch (Exception e) { + throw new ServiceRuntimeException(e); + } + } + + public boolean isConversational() { + try { + resolve(); + return reference == null ? false : reference.getInterfaceContract().getInterface().isConversational(); + } catch (Exception e) { + throw new ServiceRuntimeException(e); + } + } + + public Object getCallbackID() { + try { + resolve(); + return callbackID; + } catch (Exception e) { + throw new ServiceRuntimeException(e); + } + } + + /** + * Follow a service promotion chain down to the inner most (non composite) + * component service. + * + * @param topCompositeService + * @return + */ + private ComponentService getPromotedComponentService(CompositeService compositeService) { + ComponentService componentService = compositeService.getPromotedService(); + if (componentService != null) { + Service service = componentService.getService(); + if (componentService.getName() != null && service instanceof CompositeService) { + + // Continue to follow the service promotion chain + return getPromotedComponentService((CompositeService)service); + + } else { + + // Found a non-composite service + return componentService; + } + } else { + + // No promoted service + return null; + } + } + + // ============ WRITE AND READ THE REFERENCE TO EXTERNAL XML ======================== + + /** + * write the reference to a stream + * + * @see java.io.Externalizable#writeExternal(java.io.ObjectOutput) + */ + public void writeExternal(ObjectOutput out) throws IOException { + try { + String xml = null; + if (scdl == null){ + xml = toXMLString(); + } else { + xml = scdl; + } + + if (xml == null) { + out.writeBoolean(false); + } else { + out.writeBoolean(true); + out.writeUTF(xml); + } + } catch (Exception e) { + // e.printStackTrace(); + throw new IOException(e.toString()); + } + } + + /** + * write the endpoint reference into an xml string + */ + public String toXMLString() throws IOException, XMLStreamException, ContributionWriteException{ + StringWriter writer = new StringWriter(); + XMLStreamWriter streamWriter = xmlOutputFactory.createXMLStreamWriter(writer); + staxProcessor.write(endpointReference, streamWriter, new ProcessorContext(registry)); + return writer.toString(); + } + + /** + * Read the reference from a stream + * + * @see java.io.Externalizable#readExternal(java.io.ObjectInput) + */ + public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { + final boolean hasSCDL = in.readBoolean(); + if (hasSCDL) { + this.scdl = in.readUTF(); + } else { + this.scdl = null; + } + } + + /** + * Read xml string into the endpoint reference + */ + public void fromXMLString() throws IOException, XMLStreamException, ContributionReadException { + + XMLStreamReader streamReader = xmlReader; + + if (scdl != null ){ + Reader reader = new StringReader(scdl); + + if (xmlInputFactory == null){ + // this is a reference being read from a external stream + // so set up enough of the reference in order to resolved the + // xml being read + this.compositeContext = CompositeContext.getCurrentCompositeContext(); + getExtensions(); + } + + streamReader = xmlInputFactory.createXMLStreamReader(reader); + } + + endpointReference = staxProcessor.read(streamReader, new ProcessorContext(registry)); + + // ok to GC + xmlReader = null; + scdl = null; + } + + /** + * @throws IOException + */ + private synchronized void resolve() throws Exception { + if ((scdl != null || xmlReader != null) && component == null && reference == null) { + fromXMLString(); + + this.component = (RuntimeComponent)endpointReference.getComponent(); + compositeContext.bindComponent(this.component); + + this.reference = (RuntimeComponentReference)endpointReference.getReference(); + this.reference.setComponent(this.component); + + ReferenceParameters parameters = null; + for (Object ext : reference.getExtensions()) { + if (ext instanceof ReferenceParameters) { + parameters = (ReferenceParameters)ext; + break; + } + } + + if (parameters != null) { + this.callbackID = parameters.getCallbackID(); + } + + Interface i = reference.getInterfaceContract().getInterface(); + if (i instanceof JavaInterface) { + JavaInterface javaInterface = (JavaInterface)i; + if (javaInterface.isUnresolved()) { + // Allow privileged access to get ClassLoader. Requires RuntimePermission in + // security policy. + ClassLoader classLoader = AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() { + public ClassLoader run() { + return Thread.currentThread().getContextClassLoader(); + } + }); + + javaInterface.setJavaClass(classLoader.loadClass(javaInterface.getName())); + JavaInterfaceFactory javaInterfaceFactory = getJavaInterfaceFactory(compositeContext); + + javaInterfaceFactory.createJavaInterface(javaInterface, javaInterface.getJavaClass()); + //FIXME: If the interface needs XSDs to be loaded (e.g., for static SDO), + // this needs to be done here. We usually search for XSDs in the current + // contribution at resolve time. Is it possible to locate the current + // contribution at runtime? + } + this.businessInterface = (Class<B>)javaInterface.getJavaClass(); + } + + Binding binding = endpointReference.getBinding(); + if (binding != null) { + BindingBuilder bindingBuilder = builders.getBindingBuilder(binding.getType()); + if (bindingBuilder != null) { + BuilderContext context = new BuilderContext(registry); + bindingBuilder.build(component, reference, endpointReference.getBinding(), context); + } + } + + this.proxyFactory = getProxyFactory(this.compositeContext); + } else if (compositeContext == null) { + this.compositeContext = CompositeContext.getCurrentCompositeContext(); + if (this.compositeContext != null) { + this.proxyFactory = getProxyFactory(this.compositeContext); + } + } + } + + private JavaInterfaceFactory getJavaInterfaceFactory(CompositeContext compositeContext) { + ExtensionPointRegistry extensionPointRegistry = compositeContext.getExtensionPointRegistry(); + FactoryExtensionPoint factories = extensionPointRegistry.getExtensionPoint(FactoryExtensionPoint.class); + JavaInterfaceFactory javaInterfaceFactory = factories.getFactory(JavaInterfaceFactory.class); + return javaInterfaceFactory; + } + + private ProxyFactory getProxyFactory(CompositeContext compositeContext) { + ExtensionPointRegistry extensionPointRegistry = compositeContext.getExtensionPointRegistry(); + ProxyFactoryExtensionPoint proxyFactories = extensionPointRegistry.getExtensionPoint(ProxyFactoryExtensionPoint.class); + return new ExtensibleProxyFactory(proxyFactories); + } + + // ================================================================================== + + /** + * Create a callback id + * + * @return the callback id + */ + private String createCallbackID() { + return UUID.randomUUID().toString(); + } + + public void attachCallbackID(Object callbackID) { + this.callbackID = callbackID; + } + + protected ReferenceParameters getReferenceParameters() { + ReferenceParameters parameters = new ReferenceParametersImpl(); + parameters.setCallbackID(callbackID); + return parameters; + } + + public XMLStreamReader getXMLReader() { + return xmlReader; + } +} |