From 3a569a2f00bf172cddfd567149774ee808a2a242 Mon Sep 17 00:00:00 2001 From: nash Date: Wed, 30 Mar 2011 19:50:51 +0000 Subject: Create branch for 1.6.2 git-svn-id: http://svn.us.apache.org/repos/asf/tuscany@1087059 13f79535-47bb-0310-9956-ffa450edef68 --- .../host/embedded/impl/ComponentManagerImpl.java | 120 +++++++ .../sca/host/embedded/impl/DefaultSCADomain.java | 360 +++++++++++++++++++ .../sca/host/embedded/impl/EmbeddedSCADomain.java | 235 +++++++++++++ .../host/embedded/impl/HotUpdatableSCADomain.java | 389 +++++++++++++++++++++ .../sca/host/embedded/impl/ReallySmallRuntime.java | 387 ++++++++++++++++++++ .../embedded/impl/ReallySmallRuntimeBuilder.java | 275 +++++++++++++++ 6 files changed, 1766 insertions(+) create mode 100644 sca-java-1.x/branches/sca-java-1.6.2/modules/host-embedded/src/main/java/org/apache/tuscany/sca/host/embedded/impl/ComponentManagerImpl.java create mode 100644 sca-java-1.x/branches/sca-java-1.6.2/modules/host-embedded/src/main/java/org/apache/tuscany/sca/host/embedded/impl/DefaultSCADomain.java create mode 100644 sca-java-1.x/branches/sca-java-1.6.2/modules/host-embedded/src/main/java/org/apache/tuscany/sca/host/embedded/impl/EmbeddedSCADomain.java create mode 100644 sca-java-1.x/branches/sca-java-1.6.2/modules/host-embedded/src/main/java/org/apache/tuscany/sca/host/embedded/impl/HotUpdatableSCADomain.java create mode 100644 sca-java-1.x/branches/sca-java-1.6.2/modules/host-embedded/src/main/java/org/apache/tuscany/sca/host/embedded/impl/ReallySmallRuntime.java create mode 100644 sca-java-1.x/branches/sca-java-1.6.2/modules/host-embedded/src/main/java/org/apache/tuscany/sca/host/embedded/impl/ReallySmallRuntimeBuilder.java (limited to 'sca-java-1.x/branches/sca-java-1.6.2/modules/host-embedded/src/main/java/org/apache/tuscany/sca/host/embedded/impl') diff --git a/sca-java-1.x/branches/sca-java-1.6.2/modules/host-embedded/src/main/java/org/apache/tuscany/sca/host/embedded/impl/ComponentManagerImpl.java b/sca-java-1.x/branches/sca-java-1.6.2/modules/host-embedded/src/main/java/org/apache/tuscany/sca/host/embedded/impl/ComponentManagerImpl.java new file mode 100644 index 0000000000..187f32f405 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-1.6.2/modules/host-embedded/src/main/java/org/apache/tuscany/sca/host/embedded/impl/ComponentManagerImpl.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.sca.host.embedded.impl; + +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.concurrent.CopyOnWriteArrayList; + +import org.apache.tuscany.sca.assembly.Component; +import org.apache.tuscany.sca.assembly.Composite; +import org.apache.tuscany.sca.core.assembly.ActivationException; +import org.apache.tuscany.sca.core.assembly.RuntimeComponentImpl; +import org.apache.tuscany.sca.host.embedded.management.ComponentListener; +import org.apache.tuscany.sca.host.embedded.management.ComponentManager; + +/** + * Implementation of the ComponentManager. + * + * @version $Rev$ $Date$ + */ +public class ComponentManagerImpl implements ComponentManager { + + protected List listeners = new CopyOnWriteArrayList(); + protected EmbeddedSCADomain domain; + + public ComponentManagerImpl(EmbeddedSCADomain domain) { + this.domain = domain; + } + + public void addComponentListener(ComponentListener listener) { + this.listeners.add(listener); + } + + public void removeComponentListener(ComponentListener listener) { + this.listeners.remove(listener); + } + + public Set getComponentNames() { + Set names = new HashSet(); + for (Composite composite: domain.getDomainComposite().getIncludes()) { + for (Component component: composite.getComponents()) { + names.add(component.getName()); + } + } + return names; + } + + public Component getComponent(String componentName) { + for (Composite composite: domain.getDomainComposite().getIncludes()) { + for (Component component: composite.getComponents()) { + if (component.getName().equals(componentName)) { + return component; + } + } + } + return null; + } + + public void startComponent(String componentName) throws ActivationException { + Component component = getComponent(componentName); + if (component == null) { + throw new IllegalArgumentException("no component: " + componentName); + } + domain.getCompositeActivator().start(component); + notifyComponentStarted(componentName); + } + + public void stopComponent(String componentName) throws ActivationException { + Component component = getComponent(componentName); + if (component == null) { + throw new IllegalArgumentException("no component: " + componentName); + } + domain.getCompositeActivator().stop(component); + notifyComponentStopped(componentName); + } + + public void notifyComponentStarted(String componentName) { + for (ComponentListener listener : listeners) { + try { + listener.componentStarted(componentName); + } catch (Exception e) { + e.printStackTrace(); // TODO: log + } + } + } + + public void notifyComponentStopped(String componentName) { + for (ComponentListener listener : listeners) { + try { + listener.componentStopped(componentName); + } catch (Exception e) { + e.printStackTrace(); // TODO: log + } + } + } + + public boolean isComponentStarted(String componentName) { + RuntimeComponentImpl runtimeComponent = (RuntimeComponentImpl)getComponent(componentName); + return runtimeComponent.isStarted(); + } + +} diff --git a/sca-java-1.x/branches/sca-java-1.6.2/modules/host-embedded/src/main/java/org/apache/tuscany/sca/host/embedded/impl/DefaultSCADomain.java b/sca-java-1.x/branches/sca-java-1.6.2/modules/host-embedded/src/main/java/org/apache/tuscany/sca/host/embedded/impl/DefaultSCADomain.java new file mode 100644 index 0000000000..9b02ee9fa2 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-1.6.2/modules/host-embedded/src/main/java/org/apache/tuscany/sca/host/embedded/impl/DefaultSCADomain.java @@ -0,0 +1,360 @@ +/* + * 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.host.embedded.impl; + +import java.net.URI; +import java.net.URL; +import java.net.URLConnection; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.CopyOnWriteArrayList; + +import javax.xml.XMLConstants; +import javax.xml.stream.XMLInputFactory; +import javax.xml.stream.XMLStreamReader; + +import org.apache.tuscany.sca.assembly.Component; +import org.apache.tuscany.sca.assembly.Composite; +import org.apache.tuscany.sca.assembly.xml.Constants; +import org.apache.tuscany.sca.core.assembly.ActivationException; +import org.apache.tuscany.sca.core.assembly.CompositeActivator; +import org.apache.tuscany.sca.core.assembly.RuntimeComponentImpl; +import org.apache.tuscany.sca.host.embedded.SCADomain; +import org.apache.tuscany.sca.host.embedded.management.ComponentListener; +import org.apache.tuscany.sca.host.embedded.management.ComponentManager; +import org.apache.tuscany.sca.host.http.ServletHostExtensionPoint; +import org.apache.tuscany.sca.node.SCAClient; +import org.apache.tuscany.sca.node.SCAContribution; +import org.apache.tuscany.sca.node.SCANode; +import org.apache.tuscany.sca.node.SCANodeFactory; +import org.apache.tuscany.sca.node.impl.NodeImpl; +import org.apache.tuscany.sca.node.impl.RuntimeBootStrapper; +import org.osoa.sca.CallableReference; +import org.osoa.sca.ServiceReference; + +/** + * A default SCA domain facade implementation. + * + * @version $Rev$ $Date$ + */ +public class DefaultSCADomain extends SCADomain { + + private String uri; + private String[] composites; + // private Composite domainComposite; + // private List contributions; + private Map components; + private ComponentManager componentManager; + // private ClassLoader runtimeClassLoader; + private ClassLoader applicationClassLoader; + private String domainURI; + private List contributionURLs; + + private CompositeActivator compositeActivator; + private SCANode node; + private SCAClient client; + + /** + * Constructs a new domain facade. + * + * @param domainURI + * @param contributionLocation + * @param composites + */ + public DefaultSCADomain(ClassLoader runtimeClassLoader, + ClassLoader applicationClassLoader, + String domainURI, + String contributionLocation, + String... composites) { + this.uri = domainURI; + this.composites = composites; + // this.runtimeClassLoader = runtimeClassLoader; + this.applicationClassLoader = applicationClassLoader; + this.domainURI = domainURI; + this.contributionURLs = new ArrayList(); + if (contributionLocation != null && !"/".equals(contributionLocation)) { + this.contributionURLs.add(contributionLocation); + } + this.composites = composites; + + init(); + + this.componentManager = new DefaultSCADomainComponentManager(this); + + } + + /** + * A hack to create an aggregated composite + * @param classLoader + * @param composites + * @return + */ + private String createDeploymentComposite(ClassLoader classLoader, String composites[]) { + try { + StringBuffer xml = + new StringBuffer("\n"); + XMLInputFactory factory = XMLInputFactory.newInstance(); + for (int i = 0; i < composites.length; i++) { + URL url = classLoader.getResource(composites[i]); + if (url == null) { + continue; + } + String location = NodeImpl.getContributionURL(url, composites[i]).toString(); + if (!contributionURLs.contains(location)) { + contributionURLs.add(location); + } + URLConnection connection = url.openConnection(); + connection.setUseCaches(false); + XMLStreamReader reader = factory.createXMLStreamReader(connection.getInputStream()); + reader.nextTag(); + + assert Constants.COMPOSITE_QNAME.equals(reader.getName()); + String ns = reader.getAttributeValue(null, "targetNamespace"); + if (ns == null) { + ns = XMLConstants.NULL_NS_URI; + } + String name = reader.getAttributeValue(null, "name"); + reader.close(); + if (XMLConstants.NULL_NS_URI.equals(ns)) { + xml.append("\n"); + } else { + xml.append("\n"); + } + } + xml.append(""); + // System.out.println(xml.toString()); + return xml.toString(); + } catch (Exception e) { + throw new IllegalArgumentException(e); + } + } + + public void init() { + SCANodeFactory factory = SCANodeFactory.newInstance(); + + List contributions = new ArrayList(); + + if (composites != null && composites.length > 1) { + // Create an aggregated composite that includes all the composites as Node API only takes one composite + String content = createDeploymentComposite(applicationClassLoader, composites); + // Create SCA contributions + for (String location : contributionURLs) { + contributions.add(new SCAContribution(location, location)); + } + node = + factory.createSCANode("http://tuscany.apache.org/xmlns/sca/1.0/aggregated", content, contributions + .toArray(new SCAContribution[contributions.size()])); + } else { + for (String location : contributionURLs) { + contributions.add(new SCAContribution(location, location)); + } + String composite = (composites != null && composites.length >= 1) ? composites[0] : null; + if (!contributions.isEmpty()) { + node = + factory.createSCANode(composite, contributions.toArray(new SCAContribution[contributions.size()])); + } else { + node = factory.createSCANodeFromClassLoader(composite, applicationClassLoader); + } + } + client = (SCAClient)node; + compositeActivator = ((NodeImpl)node).getCompositeActivator(); + components = new HashMap(); + + setDefaultPort(); + + node.start(); + + getComponents(compositeActivator.getDomainComposite()); + } + + private void setDefaultPort() { + URI uri = URI.create(domainURI); + if (uri.getPort() > -1) { + RuntimeBootStrapper rt = ((NodeImpl)node).getRuntime(); + ServletHostExtensionPoint sh = rt.getExtensionPointRegistry().getExtensionPoint(ServletHostExtensionPoint.class); + if (sh != null && sh.getServletHosts() != null && !sh.getServletHosts().isEmpty()) { + sh.getServletHosts().get(0).setDefaultPort(uri.getPort()); + } + } + } + + private void getComponents(Composite composite) { + for (Component c : composite.getComponents()) { + components.put(c.getName(), c); + } + for (Composite cp : composite.getIncludes()) { + getComponents(cp); + } + } + + @Override + public void close() { + super.close(); + node.stop(); + node = null; + client = null; + components.clear(); + compositeActivator = null; + applicationClassLoader = null; + componentManager = null; + } + + @Override + @SuppressWarnings("unchecked") + public > R cast(B target) throws IllegalArgumentException { + return (R)client.cast(target); + } + + @Override + public B getService(Class businessInterface, String serviceName) { + return client.getService(businessInterface, serviceName); + } + + @Override + public ServiceReference getServiceReference(Class businessInterface, String name) { + return client.getServiceReference(businessInterface, name); + } + + @Override + public String getURI() { + return uri; + } + + @Override + public ComponentManager getComponentManager() { + return componentManager; + } + + public Set getComponentNames() { + return components.keySet(); + /* + Set componentNames = new HashSet(); + for (Contribution contribution : contributions) { + for (Artifact artifact : contribution.getArtifacts()) { + if (artifact.getModel() instanceof Composite) { + for (Component component : ((Composite)artifact.getModel()).getComponents()) { + componentNames.add(component.getName()); + } + } + } + } + return componentNames; + */ + } + + public Component getComponent(String componentName) { + return components.get(componentName); + /* + for (Contribution contribution : contributions) { + for (Artifact artifact : contribution.getArtifacts()) { + if (artifact.getModel() instanceof Composite) { + for (Component component : ((Composite)artifact.getModel()).getComponents()) { + if (component.getName().equals(componentName)) { + return component; + } + } + } + } + } + return null; + */ + } + + public void startComponent(String componentName) throws ActivationException { + Component component = getComponent(componentName); + if (component == null) { + throw new IllegalArgumentException("no component: " + componentName); + } + compositeActivator.start(component); + } + + public void stopComponent(String componentName) throws ActivationException { + Component component = getComponent(componentName); + if (component == null) { + throw new IllegalArgumentException("no component: " + componentName); + } + compositeActivator.stop(component); + } +} + +class DefaultSCADomainComponentManager implements ComponentManager { + + protected DefaultSCADomain scaDomain; + protected List listeners = new CopyOnWriteArrayList(); + + public DefaultSCADomainComponentManager(DefaultSCADomain scaDomain) { + this.scaDomain = scaDomain; + } + + public void addComponentListener(ComponentListener listener) { + this.listeners.add(listener); + } + + public void removeComponentListener(ComponentListener listener) { + this.listeners.remove(listener); + } + + public Set getComponentNames() { + return scaDomain.getComponentNames(); + } + + public Component getComponent(String componentName) { + return scaDomain.getComponent(componentName); + } + + public void startComponent(String componentName) throws ActivationException { + scaDomain.startComponent(componentName); + } + + public void stopComponent(String componentName) throws ActivationException { + scaDomain.stopComponent(componentName); + } + + public void notifyComponentStarted(String componentName) { + for (ComponentListener listener : listeners) { + try { + listener.componentStarted(componentName); + } catch (Exception e) { + e.printStackTrace(); // TODO: log + } + } + } + + public void notifyComponentStopped(String componentName) { + for (ComponentListener listener : listeners) { + try { + listener.componentStopped(componentName); + } catch (Exception e) { + e.printStackTrace(); // TODO: log + } + } + } + + public boolean isComponentStarted(String componentName) { + RuntimeComponentImpl runtimeComponent = (RuntimeComponentImpl)getComponent(componentName); + return runtimeComponent.isStarted(); + } + +} diff --git a/sca-java-1.x/branches/sca-java-1.6.2/modules/host-embedded/src/main/java/org/apache/tuscany/sca/host/embedded/impl/EmbeddedSCADomain.java b/sca-java-1.x/branches/sca-java-1.6.2/modules/host-embedded/src/main/java/org/apache/tuscany/sca/host/embedded/impl/EmbeddedSCADomain.java new file mode 100644 index 0000000000..519e76d0ae --- /dev/null +++ b/sca-java-1.x/branches/sca-java-1.6.2/modules/host-embedded/src/main/java/org/apache/tuscany/sca/host/embedded/impl/EmbeddedSCADomain.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.sca.host.embedded.impl; + +import javax.xml.namespace.QName; + +import org.apache.tuscany.sca.assembly.AssemblyFactory; +import org.apache.tuscany.sca.assembly.Component; +import org.apache.tuscany.sca.assembly.ComponentService; +import org.apache.tuscany.sca.assembly.Composite; +import org.apache.tuscany.sca.assembly.CompositeService; +import org.apache.tuscany.sca.assembly.SCABinding; +import org.apache.tuscany.sca.assembly.SCABindingFactory; +import org.apache.tuscany.sca.assembly.builder.CompositeBuilder; +import org.apache.tuscany.sca.assembly.builder.CompositeBuilderException; +import org.apache.tuscany.sca.assembly.xml.Constants; +import org.apache.tuscany.sca.contribution.ModelFactoryExtensionPoint; +import org.apache.tuscany.sca.contribution.service.ContributionService; +import org.apache.tuscany.sca.core.assembly.ActivationException; +import org.apache.tuscany.sca.core.assembly.CompositeActivator; +import org.apache.tuscany.sca.core.context.ServiceReferenceImpl; +import org.apache.tuscany.sca.host.embedded.SCADomain; +import org.apache.tuscany.sca.host.embedded.management.ComponentManager; +import org.apache.tuscany.sca.interfacedef.InterfaceContract; +import org.apache.tuscany.sca.interfacedef.java.JavaInterfaceFactory; +import org.apache.tuscany.sca.node.impl.RuntimeBootStrapper; +import org.apache.tuscany.sca.runtime.RuntimeComponent; +import org.apache.tuscany.sca.runtime.RuntimeComponentContext; +import org.apache.tuscany.sca.runtime.RuntimeComponentReference; +import org.osoa.sca.CallableReference; +import org.osoa.sca.ServiceReference; +import org.osoa.sca.ServiceRuntimeException; + +/** + * An SCA domain facade implementation. + * + * @version $Rev$ $Date$ + */ +public class EmbeddedSCADomain extends SCADomain { + + private String uri; + private Composite domainComposite; + private RuntimeBootStrapper runtime; + private ComponentManagerImpl componentManager = new ComponentManagerImpl(this); + + /** + * Constructs a new domain facade. + * + * @param runtimeClassLoader + * @param domainURI + */ + public EmbeddedSCADomain(ClassLoader runtimeClassLoader, + String domainURI) { + this.uri = domainURI; + + // Create a runtime + runtime = new RuntimeBootStrapper(runtimeClassLoader); + } + + public void start() throws ActivationException { + + // Start the runtime + runtime.start(); + + // Create an in-memory domain level composite + AssemblyFactory assemblyFactory = runtime.getAssemblyFactory(); + domainComposite = assemblyFactory.createComposite(); + domainComposite.setName(new QName(Constants.SCA10_NS, "domain")); + domainComposite.setURI(uri); + + getCompositeActivator().setDomainComposite(domainComposite); + + } + + public void stop() throws ActivationException { + + // Stop the runtime + runtime.stop(); + + // Cleanup + domainComposite = null; + } + + public void buildComposite(Composite composite) throws CompositeBuilderException { + runtime.buildComposite(composite); + } + + public ContributionService getContributionService() { + return runtime.getContributionService(); + } + + public CompositeBuilder getCompositeBuilder() { + return runtime.getCompositeBuilder(); + } + + public CompositeActivator getCompositeActivator() { + return runtime.getCompositeActivator(); + } + + public Composite getDomainComposite() { + return domainComposite; + } + + @Override + public ComponentManager getComponentManager() { + return componentManager; + } + + @Override + public void close() { + super.close(); + } + + @Override + public > R cast(B target) throws IllegalArgumentException { + return (R)runtime.getProxyFactory().cast(target); + } + + @Override + public B getService(Class businessInterface, String serviceName) { + ServiceReference serviceReference = getServiceReference(businessInterface, serviceName); + if (serviceReference == null) { + throw new ServiceRuntimeException("Service not found: " + serviceName); + } + return serviceReference.getService(); + } + + private ServiceReference createServiceReference(Class businessInterface, String targetURI) { + try { + AssemblyFactory assemblyFactory = runtime.getAssemblyFactory(); + Composite composite = assemblyFactory.createComposite(); + composite.setName(new QName(Constants.SCA10_TUSCANY_NS, "default")); + RuntimeComponent component = (RuntimeComponent)assemblyFactory.createComponent(); + component.setName("default"); + component.setURI("default"); + runtime.getCompositeActivator().configureComponentContext(component); + composite.getComponents().add(component); + RuntimeComponentReference reference = (RuntimeComponentReference)assemblyFactory.createComponentReference(); + reference.setName("default"); + ModelFactoryExtensionPoint factories = + runtime.getExtensionPointRegistry().getExtensionPoint(ModelFactoryExtensionPoint.class); + JavaInterfaceFactory javaInterfaceFactory = factories.getFactory(JavaInterfaceFactory.class); + InterfaceContract interfaceContract = javaInterfaceFactory.createJavaInterfaceContract(); + interfaceContract.setInterface(javaInterfaceFactory.createJavaInterface(businessInterface)); + reference.setInterfaceContract(interfaceContract); + component.getReferences().add(reference); + reference.setComponent(component); + SCABindingFactory scaBindingFactory = factories.getFactory(SCABindingFactory.class); + SCABinding binding = scaBindingFactory.createSCABinding(); + binding.setURI(targetURI); + reference.getBindings().add(binding); + return new ServiceReferenceImpl(businessInterface, component, reference, binding, runtime + .getProxyFactory(), runtime.getCompositeActivator()); + } catch (Exception e) { + throw new ServiceRuntimeException(e); + } + } + @Override + public ServiceReference getServiceReference(Class businessInterface, String name) { + + // Extract the component name + String componentName; + String serviceName; + int i = name.indexOf('/'); + if (i != -1) { + componentName = name.substring(0, i); + serviceName = name.substring(i + 1); + + } else { + componentName = name; + serviceName = null; + } + + // Lookup the component in the domain + Component component = componentManager.getComponent(componentName); + if (component == null) { + // The component is not local in the partition, try to create a remote service ref + return createServiceReference(businessInterface, name); + } + RuntimeComponentContext componentContext = null; + + // If the component is a composite, then we need to find the + // non-composite component that provides the requested service + if (component.getImplementation() instanceof Composite) { + for (ComponentService componentService : component.getServices()) { + if (serviceName == null || serviceName.equals(componentService.getName())) { + CompositeService compositeService = (CompositeService)componentService.getService(); + if (compositeService != null) { + if (serviceName != null) { + serviceName = "$promoted$" + component.getName() + "$slash$" + serviceName; + } + componentContext = + ((RuntimeComponent)compositeService.getPromotedComponent()).getComponentContext(); + return componentContext.createSelfReference(businessInterface, compositeService + .getPromotedService()); + } + break; + } + } + // No matching service is found + throw new ServiceRuntimeException("Composite service not found: " + name); + } else { + componentContext = ((RuntimeComponent)component).getComponentContext(); + if (serviceName != null) { + return componentContext.createSelfReference(businessInterface, serviceName); + } else { + return componentContext.createSelfReference(businessInterface); + } + } + + } + + @Override + public String getURI() { + return uri; + } + +} diff --git a/sca-java-1.x/branches/sca-java-1.6.2/modules/host-embedded/src/main/java/org/apache/tuscany/sca/host/embedded/impl/HotUpdatableSCADomain.java b/sca-java-1.x/branches/sca-java-1.6.2/modules/host-embedded/src/main/java/org/apache/tuscany/sca/host/embedded/impl/HotUpdatableSCADomain.java new file mode 100644 index 0000000000..d59f1544e5 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-1.6.2/modules/host-embedded/src/main/java/org/apache/tuscany/sca/host/embedded/impl/HotUpdatableSCADomain.java @@ -0,0 +1,389 @@ +/* + * 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.host.embedded.impl; + +import java.io.File; +import java.io.FilenameFilter; +import java.io.IOException; +import java.io.InputStream; +import java.net.MalformedURLException; +import java.net.URISyntaxException; +import java.net.URL; +import java.net.URLClassLoader; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.logging.Logger; + +import org.apache.tuscany.sca.assembly.Composite; +import org.apache.tuscany.sca.assembly.builder.CompositeBuilderException; +import org.apache.tuscany.sca.contribution.Contribution; +import org.apache.tuscany.sca.contribution.service.ContributionService; +import org.apache.tuscany.sca.contribution.service.util.FileHelper; +import org.apache.tuscany.sca.core.assembly.ActivationException; +import org.apache.tuscany.sca.host.embedded.SCADomain; +import org.apache.tuscany.sca.host.embedded.management.ComponentManager; +import org.osoa.sca.CallableReference; +import org.osoa.sca.ServiceReference; +import org.osoa.sca.ServiceRuntimeException; + +/** + * An SCADomain that starts a Tuscany runtime supporting multiple + * SCA contribution jars. All contribution jars found in a repository + * directory will be contributed to the SCA domain. Any changes to the + * contributions in that repository will be automatically detected and + * the SCADomain updated accordingly. + * + * TODO: find how to properly add/remove contributions and start/activate the SCADomain + * TODO: support contributions that are folders as well as jar's + * TODO: needs to restart the entire SCADomain when a contribution changes + * as the domain classpath includes all the contribution jar's, would + * be nice to find a way to avoid this + * TODO: hot update requires copying contribution jars to a temp location + * to avoid the classpath lock preventing updating the contribution + * jars, would be nice to find a way to avoid that + * + * @version $Rev$ $Date$ + */ +public class HotUpdatableSCADomain extends SCADomain { + private static final Logger logger = Logger.getLogger(HotUpdatableSCADomain.class.getName()); + protected String domainURI; + protected File contributionRepository; + + protected EmbeddedSCADomain scaDomain; + + protected boolean hotUpdateActive; + protected Thread hotUpdateThread; + protected int hotUpdateInterval; // milliseconds, 0 = hotupdate disabled + + protected HashMap existingContributions; // value is last modified time + protected ClassLoader originalCCL; + + protected static final String REPOSITORY_FOLDER = "sca-contributions"; + + public HotUpdatableSCADomain(String domainURI, File contributionRepository, int hotupdateInterval) { + this.domainURI = domainURI; + this.contributionRepository = contributionRepository; + this.hotUpdateInterval = hotupdateInterval; + this.originalCCL = Thread.currentThread().getContextClassLoader(); + start(); + } + + protected void start() { + try { + initEmbeddedSCADomain(); + activateHotUpdate(); + for (URL url : existingContributions.keySet()) { + File f = new File(url.toURI()); + logger.info("added contribution: " + f.getName()); + } + } catch (ActivationException e) { + throw new ServiceRuntimeException(e); + } catch (URISyntaxException e) { + throw new ServiceRuntimeException(e); + } + } + + @Override + public void close() { + try { + hotUpdateActive = false; + scaDomain.stop(); + } catch (ActivationException e) { + throw new ServiceRuntimeException(e); + } + Thread.currentThread().setContextClassLoader(originalCCL); + super.close(); + } + + + protected SCADomain initEmbeddedSCADomain() throws ActivationException { + + URL[] contributionJars = getContributionJarURLs(contributionRepository); + + this.existingContributions = getLastModified(contributionJars); + + if (hotUpdateInterval > 0) { + contributionJars = copyContributionsToTemp(contributionJars); + } + + // Using the CCL as the parent exposes Tuscany to the contributions, want to do this? + URLClassLoader cl = new URLClassLoader(contributionJars, originalCCL); + Thread.currentThread().setContextClassLoader(cl); + + scaDomain = new EmbeddedSCADomain(cl, domainURI); + + scaDomain.start(); + + initContributions(scaDomain, cl, contributionJars); + + return scaDomain; + } + + protected URL[] getContributionJarURLs(File repositoryDir) { + + String[] jars = repositoryDir.list(new FilenameFilter() { + public boolean accept(File dir, String name) { + return name.endsWith(".jar"); + }}); + + List contributionJars = new ArrayList(); + if (jars != null) { + for (String jar : jars) { + try { + contributionJars.add(new File(repositoryDir, jar).toURL()); + } catch (MalformedURLException e) { + throw new RuntimeException(e); + } + } + } + + return contributionJars.toArray(new URL[contributionJars.size()]); + } + + /** + * TODO: No idea what the 'correct' way to add/contribute and activate/start things to an scaDomain is + * but this seems to work. Doesn't seem to start s or s which are outside of + * a so something is missing/wrong. Also this doesn't seem to be picking up composites + * located in META-INF/deployables or specified in the sca-deployables.xml. Maybe the EmbeddedSCADomain + * and ContributionService APIs should make all this easier? + */ + protected void initContributions(EmbeddedSCADomain scaDomain, ClassLoader cl, URL[] contributionJars) { + Contribution contribution = null; + ContributionService contributionService = scaDomain.getContributionService(); + for (URL jar : contributionJars) { + InputStream is = null; + try { + is = jar.openStream(); + contribution = contributionService.contribute(jar.toString(), jar, is); + } catch (Exception e) { + System.err.println("exception adding contribution: " + jar); + e.printStackTrace(); + } + if (is != null) { + try { + is.close(); + } catch (IOException e) { + // ignore + } + } + } + + if (contribution != null ) { + try { + + for (Composite composite : contribution.getDeployables()) { + scaDomain.getDomainComposite().getIncludes().add(composite); + scaDomain.getCompositeBuilder().build(composite); + scaDomain.getCompositeActivator().activate(composite); + } + + for (Composite composite : contribution.getDeployables()) { + scaDomain.getCompositeActivator().start(composite); + } + + } catch (ActivationException e) { + throw new RuntimeException(e); + } catch (CompositeBuilderException e) { + throw new RuntimeException(e); + } + } + + } + + /** + * Copies Files to a temp location returning the URLs of the new temp files. + * For hot update to work need to be able to delete/update the contribution jar's + * but as they're in the classpath the URLClassLoader has an open lock on the jar's + * so you can't update them. This solution copies each contribution to a temp + * location for use on the classpath, nicer would be a ClassLoder impl that doesn't + * lock the jar's. + */ + protected URL[] copyContributionsToTemp(URL[] contributionJars) { + try { + + URL[] newURLs = new URL[contributionJars.length]; + File tempDir = new File(System.getProperty("java.io.tmpdir")); + for (int i=0; i getLastModified(URL[] contrabutions) { + try { + + HashMap contributionLastUpdates = new HashMap(); + for (URL url: contrabutions) { + File f = new File(url.toURI()); + contributionLastUpdates.put(url, new Long(f.lastModified())); + } + return contributionLastUpdates; + + } catch (URISyntaxException e) { + throw new RuntimeException(e); + } + } + + protected void activateHotUpdate() { + if (hotUpdateInterval == 0) { + return; // hotUpdateInterval of 0 disables hotupdate + } + + Runnable runable = new Runnable() { + public void run() { + logger.info("Tuscany contribution hotupdate running"); + while (hotUpdateActive) { + try { + Thread.sleep(hotUpdateInterval); + } catch (InterruptedException e) { + } + if (hotUpdateActive) { + checkForUpdates(); + } + } + logger.info("Tuscany contribution hotupdate stopped"); + } + }; + hotUpdateThread = new Thread(runable, "TuscanyHotUpdate"); + hotUpdateActive = true; + hotUpdateThread.start(); + } + + + /** + * Checks if any of the contributions have been updated and if so restarts the SCADomain + * TODO: Ideally just the altered contribution would be restarted but thats not possible + * as the ClassLoader used by the SCADomain includes the old contribution so need + * to restart the entire domain to use a new ClassLoader. Should there be separate + * ClassLoader per contribution? But then have all the issues with sharing classes + * across contributions. + */ + protected void checkForUpdates() { + URL[] currentContributions = getContributionJarURLs(contributionRepository); + + if (areContributionsAltered(currentContributions)) { + try { + scaDomain.stop(); + } catch (Exception e) { + e.printStackTrace(); + } + try { + initEmbeddedSCADomain(); + } catch (Exception e) { + e.printStackTrace(); + } + } + } + + protected boolean areContributionsAltered(URL[] currentContrabutions) { + try { + + List addedContributions = getAddedContributions(currentContrabutions); + List removedContributions = getRemovedContributions(currentContrabutions); + List updatedContributions = getUpdatedContributions(currentContrabutions); + + return (addedContributions.size() > 0 || removedContributions.size() > 0 || updatedContributions.size() > 0); + + } catch (URISyntaxException e) { + throw new RuntimeException(e); + } + } + + protected List getUpdatedContributions(URL[] currentContrabutions) throws URISyntaxException { + List urls = new ArrayList(); + for (URL url : currentContrabutions) { + if (existingContributions.containsKey(url)) { + File curentFile = new File(url.toURI()); + if (curentFile.lastModified() != existingContributions.get(url)) { + urls.add(url); + logger.info("updated contribution: " + curentFile.getName()); + } + } + } + return urls; + } + + protected List getRemovedContributions(URL[] currentContrabutions) throws URISyntaxException { + List currentUrls = Arrays.asList(currentContrabutions); + List urls = new ArrayList(); + for (URL url : existingContributions.keySet()) { + if (!currentUrls.contains(url)) { + urls.add(url); + } + } + for (URL url : urls) { + logger.info("removed contributions: " + new File(url.toURI()).getName()); + } + return urls; + } + + protected List getAddedContributions(URL[] currentContrabutions) throws URISyntaxException { + List urls = new ArrayList(); + for (URL url : currentContrabutions) { + if (!existingContributions.containsKey(url)) { + urls.add(url); + logger.info("added contribution: " + new File(url.toURI()).getName()); + } + } + return urls; + } + + @Override + public > R cast(B target) throws IllegalArgumentException { + throw new UnsupportedOperationException("not implemented"); + } + + @Override + public B getService(Class businessInterface, String serviceName) { + return scaDomain.getService(businessInterface, serviceName); + } + + @Override + public ServiceReference getServiceReference(Class businessInterface, String referenceName) { + return scaDomain.getServiceReference(businessInterface, referenceName); + } + + @Override + public String getURI() { + return domainURI; + } + + @Override + public ComponentManager getComponentManager(){ + return scaDomain.getComponentManager(); + } + +} diff --git a/sca-java-1.x/branches/sca-java-1.6.2/modules/host-embedded/src/main/java/org/apache/tuscany/sca/host/embedded/impl/ReallySmallRuntime.java b/sca-java-1.x/branches/sca-java-1.6.2/modules/host-embedded/src/main/java/org/apache/tuscany/sca/host/embedded/impl/ReallySmallRuntime.java new file mode 100644 index 0000000000..34a54e21ad --- /dev/null +++ b/sca-java-1.x/branches/sca-java-1.6.2/modules/host-embedded/src/main/java/org/apache/tuscany/sca/host/embedded/impl/ReallySmallRuntime.java @@ -0,0 +1,387 @@ +/* + * 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.host.embedded.impl; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.logging.Level; +import java.util.logging.Logger; + +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.transform.TransformerFactory; + +import org.apache.tuscany.sca.assembly.AssemblyFactory; +import org.apache.tuscany.sca.assembly.Composite; +import org.apache.tuscany.sca.assembly.EndpointFactory; +import org.apache.tuscany.sca.assembly.SCABindingFactory; +import org.apache.tuscany.sca.assembly.builder.CompositeBuilder; +import org.apache.tuscany.sca.assembly.builder.CompositeBuilderException; +import org.apache.tuscany.sca.contribution.ContributionFactory; +import org.apache.tuscany.sca.contribution.ModelFactoryExtensionPoint; +import org.apache.tuscany.sca.contribution.processor.URLArtifactProcessor; +import org.apache.tuscany.sca.contribution.processor.URLArtifactProcessorExtensionPoint; +import org.apache.tuscany.sca.contribution.resolver.DefaultModelResolver; +import org.apache.tuscany.sca.contribution.resolver.ModelResolver; +import org.apache.tuscany.sca.contribution.service.ContributionService; +import org.apache.tuscany.sca.core.DefaultExtensionPointRegistry; +import org.apache.tuscany.sca.core.ExtensionPointRegistry; +import org.apache.tuscany.sca.core.ModuleActivator; +import org.apache.tuscany.sca.core.UtilityExtensionPoint; +import org.apache.tuscany.sca.core.assembly.ActivationException; +import org.apache.tuscany.sca.core.assembly.CompositeActivator; +import org.apache.tuscany.sca.core.assembly.RuntimeAssemblyFactory; +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.core.scope.ScopeRegistry; +import org.apache.tuscany.sca.definitions.SCADefinitions; +import org.apache.tuscany.sca.definitions.impl.SCADefinitionsImpl; +import org.apache.tuscany.sca.definitions.util.SCADefinitionsUtil; +import org.apache.tuscany.sca.extensibility.ServiceDeclaration; +import org.apache.tuscany.sca.extensibility.ServiceDiscovery; +import org.apache.tuscany.sca.interfacedef.InterfaceContractMapper; +import org.apache.tuscany.sca.invocation.MessageFactory; +import org.apache.tuscany.sca.monitor.Monitor; +import org.apache.tuscany.sca.monitor.MonitorFactory; +import org.apache.tuscany.sca.monitor.impl.DefaultMonitorFactoryImpl; +import org.apache.tuscany.sca.policy.DefaultIntentAttachPointTypeFactory; +import org.apache.tuscany.sca.policy.DefaultPolicyFactory; +import org.apache.tuscany.sca.policy.Intent; +import org.apache.tuscany.sca.policy.IntentAttachPointType; +import org.apache.tuscany.sca.policy.IntentAttachPointTypeFactory; +import org.apache.tuscany.sca.policy.PolicyFactory; +import org.apache.tuscany.sca.policy.PolicySet; +import org.apache.tuscany.sca.provider.SCADefinitionsProvider; +import org.apache.tuscany.sca.provider.SCADefinitionsProviderExtensionPoint; +import org.apache.tuscany.sca.work.WorkScheduler; + +/** + * + * @version $Rev$ $Date$ + */ +public class ReallySmallRuntime { + private static final Logger logger = Logger.getLogger(ReallySmallRuntime.class.getName()); + private List modules; + private ExtensionPointRegistry registry; + + private ClassLoader classLoader; + private AssemblyFactory assemblyFactory; + private ContributionService contributionService; + private CompositeActivator compositeActivator; + private CompositeBuilder compositeBuilder; + // private DomainBuilder domainBuilder; + private WorkScheduler workScheduler; + private ScopeRegistry scopeRegistry; + private ProxyFactory proxyFactory; + private List policyDefinitions; + private ModelResolver policyDefinitionsResolver; + private Monitor monitor; + + public ReallySmallRuntime(ClassLoader classLoader) { + this.classLoader = classLoader; + + // Create our extension point registry + registry = new DefaultExtensionPointRegistry(); + } + + public void start() throws ActivationException { + long start = System.currentTimeMillis(); + + + UtilityExtensionPoint utilities = registry.getExtensionPoint(UtilityExtensionPoint.class); + + // Get work scheduler + workScheduler = utilities.getUtility(WorkScheduler.class); + + // Create an interface contract mapper + InterfaceContractMapper mapper = utilities.getUtility(InterfaceContractMapper.class); + + // Get factory extension point + ModelFactoryExtensionPoint factories = registry.getExtensionPoint(ModelFactoryExtensionPoint.class); + + // Get Message factory + MessageFactory messageFactory = factories.getFactory(MessageFactory.class); + + // Get proxy factory + ProxyFactoryExtensionPoint proxyFactories = registry.getExtensionPoint(ProxyFactoryExtensionPoint.class); + proxyFactory = new ExtensibleProxyFactory(proxyFactories); + + // Create model factories + assemblyFactory = new RuntimeAssemblyFactory(); + factories.addFactory(assemblyFactory); + PolicyFactory policyFactory = new DefaultPolicyFactory(); + factories.addFactory(policyFactory); + + // Load the runtime modules + modules = loadModules(registry); + + // Start the runtime modules + startModules(registry, modules); + + SCABindingFactory scaBindingFactory = factories.getFactory(SCABindingFactory.class); + IntentAttachPointTypeFactory intentAttachPointTypeFactory = new DefaultIntentAttachPointTypeFactory(); + factories.addFactory(intentAttachPointTypeFactory); + ContributionFactory contributionFactory = factories.getFactory(ContributionFactory.class); + + // Create a monitor + MonitorFactory monitorFactory = utilities.getUtility(MonitorFactory.class); + + if (monitorFactory != null){ + monitor = monitorFactory.createMonitor(); + } else { + monitorFactory = new DefaultMonitorFactoryImpl(); + monitor = monitorFactory.createMonitor(); + utilities.addUtility(monitorFactory); + //logger.fine("No MonitorFactory is found on the classpath."); + } + + // Create a contribution service + policyDefinitions = new ArrayList(); + policyDefinitionsResolver = new DefaultModelResolver(); + contributionService = ReallySmallRuntimeBuilder.createContributionService(classLoader, + registry, + contributionFactory, + assemblyFactory, + policyFactory, + mapper, + policyDefinitions, + policyDefinitionsResolver, + monitor); + + // Create the ScopeRegistry + scopeRegistry = ReallySmallRuntimeBuilder.createScopeRegistry(registry); + + // Create a composite activator + compositeActivator = ReallySmallRuntimeBuilder.createCompositeActivator(registry, + assemblyFactory, + messageFactory, + scaBindingFactory, + mapper, + proxyFactory, + scopeRegistry, + workScheduler); + + // Load the definitions.xml + loadSCADefinitions(); + + if (logger.isLoggable(Level.FINE)) { + long end = System.currentTimeMillis(); + logger.fine("The tuscany runtime is started in " + (end - start) + " ms."); + } + } + + public void stop() throws ActivationException { + long start = System.currentTimeMillis(); + + // Stop the runtime modules + stopModules(registry, modules); + + // Stop and destroy the work manager + workScheduler.destroy(); + + // Cleanup + modules = null; + registry = null; + assemblyFactory = null; + contributionService = null; + compositeActivator = null; + workScheduler = null; + scopeRegistry = null; + + if (logger.isLoggable(Level.FINE)) { + long end = System.currentTimeMillis(); + logger.fine("The tuscany runtime is stopped in " + (end - start) + " ms."); + } + } + + public void buildComposite(Composite composite) throws CompositeBuilderException { + //Get factory extension point + ModelFactoryExtensionPoint factories = registry.getExtensionPoint(ModelFactoryExtensionPoint.class); + SCABindingFactory scaBindingFactory = factories.getFactory(SCABindingFactory.class); + IntentAttachPointTypeFactory intentAttachPointTypeFactory = factories.getFactory(IntentAttachPointTypeFactory.class); + EndpointFactory endpointFactory = factories.getFactory(EndpointFactory.class); + UtilityExtensionPoint utilities = registry.getExtensionPoint(UtilityExtensionPoint.class); + InterfaceContractMapper mapper = utilities.getUtility(InterfaceContractMapper.class); + DocumentBuilderFactory documentBuilderFactory = factories.getFactory(DocumentBuilderFactory.class); + TransformerFactory transformerFactory = factories.getFactory(TransformerFactory.class); + + //Create a composite builder + SCADefinitions aggregatedDefinitions = new SCADefinitionsImpl(); + for ( SCADefinitions definition : ((List)policyDefinitions) ) { + SCADefinitionsUtil.aggregateSCADefinitions(definition, aggregatedDefinitions); + } + compositeBuilder = ReallySmallRuntimeBuilder.createCompositeBuilder(monitor, + assemblyFactory, + scaBindingFactory, + endpointFactory, + intentAttachPointTypeFactory, + documentBuilderFactory, + transformerFactory, + mapper, + aggregatedDefinitions); + compositeBuilder.build(composite); + + } + + public ContributionService getContributionService() { + return contributionService; + } + + public CompositeActivator getCompositeActivator() { + return compositeActivator; + } + + public CompositeBuilder getCompositeBuilder() { + return compositeBuilder; + } + + public AssemblyFactory getAssemblyFactory() { + return assemblyFactory; + } + + private void loadSCADefinitions() throws ActivationException { + try { + URLArtifactProcessorExtensionPoint documentProcessors = registry.getExtensionPoint(URLArtifactProcessorExtensionPoint.class); + URLArtifactProcessor definitionsProcessor = documentProcessors.getProcessor(SCADefinitions.class); + SCADefinitionsProviderExtensionPoint scaDefnProviders = registry.getExtensionPoint(SCADefinitionsProviderExtensionPoint.class); + + SCADefinitions systemSCADefinitions = new SCADefinitionsImpl(); + SCADefinitions aSCADefn = null; + for ( SCADefinitionsProvider aProvider : scaDefnProviders.getSCADefinitionsProviders() ) { + aSCADefn = aProvider.getSCADefinition(); + SCADefinitionsUtil.aggregateSCADefinitions(aSCADefn, systemSCADefinitions); + } + + policyDefinitions.add(systemSCADefinitions); + + //we cannot expect that providers will add the intents and policysets into the resolver + //so we do this here explicitly + for ( Intent intent : systemSCADefinitions.getPolicyIntents() ) { + policyDefinitionsResolver.addModel(intent); + } + + for ( PolicySet policySet : systemSCADefinitions.getPolicySets() ) { + policyDefinitionsResolver.addModel(policySet); + } + + for ( IntentAttachPointType attachPoinType : systemSCADefinitions.getBindingTypes() ) { + policyDefinitionsResolver.addModel(attachPoinType); + } + + for ( IntentAttachPointType attachPoinType : systemSCADefinitions.getImplementationTypes() ) { + policyDefinitionsResolver.addModel(attachPoinType); + } + + //now that all system sca definitions have been read, lets resolve them right away + definitionsProcessor.resolve(systemSCADefinitions, + policyDefinitionsResolver); + } catch ( Exception e ) { + throw new ActivationException(e); + } + } + + @SuppressWarnings("unchecked") + private List loadModules(ExtensionPointRegistry registry) throws ActivationException { + + // Load and instantiate the modules found on the classpath (or any registered ClassLoaders) + modules = new ArrayList(); + try { + Set moduleActivators = + ServiceDiscovery.getInstance().getServiceDeclarations(ModuleActivator.class); + Set moduleClasses = new HashSet(); + for (ServiceDeclaration moduleDeclarator : moduleActivators) { + if (moduleClasses.contains(moduleDeclarator.getClassName())) { + continue; + } + moduleClasses.add(moduleDeclarator.getClassName()); + Class moduleClass = moduleDeclarator.loadClass(); + ModuleActivator module = (ModuleActivator)moduleClass.newInstance(); + modules.add(module); + } + } catch (IOException e) { + throw new ActivationException(e); + } catch (ClassNotFoundException e) { + throw new ActivationException(e); + } catch (InstantiationException e) { + throw new ActivationException(e); + } catch (IllegalAccessException e) { + throw new ActivationException(e); + } + + return modules; + } + + private void startModules(ExtensionPointRegistry registry, List modules) + throws ActivationException { + boolean debug = logger.isLoggable(Level.FINE); + // Start all the extension modules + for (ModuleActivator module : modules) { + long start = 0L; + if (debug) { + logger.fine(module.getClass().getName() + " is starting."); + start = System.currentTimeMillis(); + } + try { + module.start(registry); + if (debug) { + long end = System.currentTimeMillis(); + logger.fine(module.getClass().getName() + " is started in " + (end - start) + " ms."); + } + } catch (Throwable e) { + logger.log(Level.WARNING, "Exception starting module " + module.getClass().getName() + " :" + e.getMessage()); + logger.log(Level.FINE, "Exception starting module " + module.getClass().getName(), e); + } + } + } + + private void stopModules(final ExtensionPointRegistry registry, List modules) { + boolean debug = logger.isLoggable(Level.FINE); + for (ModuleActivator module : modules) { + long start = 0L; + if (debug) { + logger.fine(module.getClass().getName() + " is stopping."); + start = System.currentTimeMillis(); + } + module.stop(registry); + if (debug) { + long end = System.currentTimeMillis(); + logger.fine(module.getClass().getName() + " is stopped in " + (end - start) + " ms."); + } + } + } + + /** + * @return the proxyFactory + */ + public ProxyFactory getProxyFactory() { + return proxyFactory; + } + + /** + * @return the registry + */ + public ExtensionPointRegistry getExtensionPointRegistry() { + return registry; + } + +} diff --git a/sca-java-1.x/branches/sca-java-1.6.2/modules/host-embedded/src/main/java/org/apache/tuscany/sca/host/embedded/impl/ReallySmallRuntimeBuilder.java b/sca-java-1.x/branches/sca-java-1.6.2/modules/host-embedded/src/main/java/org/apache/tuscany/sca/host/embedded/impl/ReallySmallRuntimeBuilder.java new file mode 100644 index 0000000000..0f5aedfd75 --- /dev/null +++ b/sca-java-1.x/branches/sca-java-1.6.2/modules/host-embedded/src/main/java/org/apache/tuscany/sca/host/embedded/impl/ReallySmallRuntimeBuilder.java @@ -0,0 +1,275 @@ +/* + * 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.host.embedded.impl; + +import java.io.IOException; +import java.security.AccessController; +import java.security.PrivilegedAction; +import java.util.List; + +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.stream.XMLInputFactory; +import javax.xml.stream.XMLOutputFactory; +import javax.xml.transform.TransformerFactory; + +import org.apache.tuscany.sca.assembly.AssemblyFactory; +import org.apache.tuscany.sca.assembly.Composite; +import org.apache.tuscany.sca.assembly.EndpointFactory; +import org.apache.tuscany.sca.assembly.SCABindingFactory; +import org.apache.tuscany.sca.assembly.builder.CompositeBuilder; +import org.apache.tuscany.sca.assembly.builder.impl.CompositeBuilderImpl; +import org.apache.tuscany.sca.assembly.xml.CompositeDocumentProcessor; +import org.apache.tuscany.sca.context.ContextFactoryExtensionPoint; +import org.apache.tuscany.sca.context.RequestContextFactory; +import org.apache.tuscany.sca.contribution.ContributionFactory; +import org.apache.tuscany.sca.contribution.ModelFactoryExtensionPoint; +import org.apache.tuscany.sca.contribution.processor.DefaultValidatingXMLInputFactory; +import org.apache.tuscany.sca.contribution.processor.DefaultValidationSchemaExtensionPoint; +import org.apache.tuscany.sca.contribution.processor.ExtensiblePackageProcessor; +import org.apache.tuscany.sca.contribution.processor.ExtensibleStAXArtifactProcessor; +import org.apache.tuscany.sca.contribution.processor.ExtensibleURLArtifactProcessor; +import org.apache.tuscany.sca.contribution.processor.PackageProcessor; +import org.apache.tuscany.sca.contribution.processor.PackageProcessorExtensionPoint; +import org.apache.tuscany.sca.contribution.processor.StAXArtifactProcessorExtensionPoint; +import org.apache.tuscany.sca.contribution.processor.URLArtifactProcessorExtensionPoint; +import org.apache.tuscany.sca.contribution.processor.ValidationSchemaExtensionPoint; +import org.apache.tuscany.sca.contribution.resolver.ModelResolver; +import org.apache.tuscany.sca.contribution.resolver.ModelResolverExtensionPoint; +import org.apache.tuscany.sca.contribution.service.ContributionListenerExtensionPoint; +import org.apache.tuscany.sca.contribution.service.ContributionRepository; +import org.apache.tuscany.sca.contribution.service.ContributionService; +import org.apache.tuscany.sca.contribution.service.ExtensibleContributionListener; +import org.apache.tuscany.sca.contribution.service.TypeDescriber; +import org.apache.tuscany.sca.contribution.service.impl.ContributionRepositoryImpl; +import org.apache.tuscany.sca.contribution.service.impl.ContributionServiceImpl; +import org.apache.tuscany.sca.contribution.service.impl.PackageTypeDescriberImpl; +import org.apache.tuscany.sca.core.ExtensionPointRegistry; +import org.apache.tuscany.sca.core.UtilityExtensionPoint; +import org.apache.tuscany.sca.core.assembly.ActivationException; +import org.apache.tuscany.sca.core.assembly.CompositeActivator; +import org.apache.tuscany.sca.core.assembly.CompositeActivatorImpl; +import org.apache.tuscany.sca.core.conversation.ConversationManager; +import org.apache.tuscany.sca.core.invocation.ExtensibleWireProcessor; +import org.apache.tuscany.sca.core.invocation.ProxyFactory; +import org.apache.tuscany.sca.core.scope.CompositeScopeContainerFactory; +import org.apache.tuscany.sca.core.scope.ConversationalScopeContainerFactory; +import org.apache.tuscany.sca.core.scope.RequestScopeContainerFactory; +import org.apache.tuscany.sca.core.scope.ScopeContainerFactory; +import org.apache.tuscany.sca.core.scope.ScopeRegistry; +import org.apache.tuscany.sca.core.scope.ScopeRegistryImpl; +import org.apache.tuscany.sca.core.scope.StatelessScopeContainerFactory; +import org.apache.tuscany.sca.definitions.SCADefinitions; +import org.apache.tuscany.sca.endpointresolver.EndpointResolverFactoryExtensionPoint; +import org.apache.tuscany.sca.interfacedef.InterfaceContractMapper; +import org.apache.tuscany.sca.interfacedef.java.JavaInterfaceFactory; +import org.apache.tuscany.sca.invocation.MessageFactory; +import org.apache.tuscany.sca.monitor.Monitor; +import org.apache.tuscany.sca.policy.IntentAttachPointTypeFactory; +import org.apache.tuscany.sca.policy.PolicyFactory; +import org.apache.tuscany.sca.provider.ProviderFactoryExtensionPoint; +import org.apache.tuscany.sca.runtime.RuntimeWireProcessor; +import org.apache.tuscany.sca.runtime.RuntimeWireProcessorExtensionPoint; +import org.apache.tuscany.sca.work.WorkScheduler; + +/** + * + * @version $Rev$ $Date$ + */ +public class ReallySmallRuntimeBuilder { + + // private static final Logger logger = Logger.getLogger(ReallySmallRuntimeBuilder.class.getName()); + + public static CompositeActivator createCompositeActivator(ExtensionPointRegistry registry, + AssemblyFactory assemblyFactory, + MessageFactory messageFactory, + SCABindingFactory scaBindingFactory, + InterfaceContractMapper mapper, + ProxyFactory proxyFactory, + ScopeRegistry scopeRegistry, + WorkScheduler workScheduler) { + + // Create a wire post processor extension point + RuntimeWireProcessorExtensionPoint wireProcessors = + registry.getExtensionPoint(RuntimeWireProcessorExtensionPoint.class); + RuntimeWireProcessor wireProcessor = new ExtensibleWireProcessor(wireProcessors); + + // Retrieve the processors extension point + StAXArtifactProcessorExtensionPoint processors = + registry.getExtensionPoint(StAXArtifactProcessorExtensionPoint.class); + + // Create a provider factory extension point + ProviderFactoryExtensionPoint providerFactories = + registry.getExtensionPoint(ProviderFactoryExtensionPoint.class); + + // Create a endpoint resolver factory extension point + EndpointResolverFactoryExtensionPoint endpointResolverFactories = + registry.getExtensionPoint(EndpointResolverFactoryExtensionPoint.class); + + JavaInterfaceFactory javaInterfaceFactory = + registry.getExtensionPoint(ModelFactoryExtensionPoint.class).getFactory(JavaInterfaceFactory.class); + RequestContextFactory requestContextFactory = + registry.getExtensionPoint(ContextFactoryExtensionPoint.class).getFactory(RequestContextFactory.class); + + UtilityExtensionPoint utilities = registry.getExtensionPoint(UtilityExtensionPoint.class); + ConversationManager conversationManager = utilities.getUtility(ConversationManager.class); + + // Create the composite activator + CompositeActivator compositeActivator = + new CompositeActivatorImpl(assemblyFactory, messageFactory, javaInterfaceFactory, scaBindingFactory, + mapper, scopeRegistry, workScheduler, wireProcessor, requestContextFactory, + proxyFactory, providerFactories, endpointResolverFactories, processors, conversationManager); + + return compositeActivator; + } + + public static CompositeBuilder createCompositeBuilder(Monitor monitor, + AssemblyFactory assemblyFactory, + SCABindingFactory scaBindingFactory, + EndpointFactory endpointFactory, + IntentAttachPointTypeFactory intentAttachPointTypeFactory, + DocumentBuilderFactory documentBuilderFactory, + TransformerFactory transformerFactory, + InterfaceContractMapper interfaceContractMapper, + SCADefinitions policyDefinitions) { + + + return new CompositeBuilderImpl(assemblyFactory, + endpointFactory, + scaBindingFactory, + intentAttachPointTypeFactory, + documentBuilderFactory, + transformerFactory, + interfaceContractMapper, + policyDefinitions, + monitor); + } + + + /** + * Create the contribution service used by this domain. + * + * @throws ActivationException + */ + public static ContributionService createContributionService(ClassLoader classLoader, + ExtensionPointRegistry registry, + ContributionFactory contributionFactory, + AssemblyFactory assemblyFactory, + PolicyFactory policyFactory, + InterfaceContractMapper mapper, + List policyDefinitions, + ModelResolver policyDefinitionResolver, + Monitor monitor) + throws ActivationException { + + // Get the model factory extension point + ModelFactoryExtensionPoint modelFactories = registry.getExtensionPoint(ModelFactoryExtensionPoint.class); + + // Create a new XML input factory + // Allow privileged access to factory. Requires RuntimePermission in security policy file. + XMLInputFactory inputFactory = AccessController.doPrivileged(new PrivilegedAction() { + public XMLInputFactory run() { + return XMLInputFactory.newInstance(); + } + }); + modelFactories.addFactory(inputFactory); + + // Create a validation XML schema extension point + ValidationSchemaExtensionPoint schemas = registry.getExtensionPoint(ValidationSchemaExtensionPoint.class); + + // Create a validating XML input factory + XMLInputFactory validatingInputFactory = new DefaultValidatingXMLInputFactory(inputFactory, schemas, monitor); + modelFactories.addFactory(validatingInputFactory); + + // Create StAX artifact processor extension point + StAXArtifactProcessorExtensionPoint staxProcessors = + registry.getExtensionPoint(StAXArtifactProcessorExtensionPoint.class); + + // Create and register StAX processors for SCA assembly XML + // Allow privileged access to factory. Requires RuntimePermission in security policy file. + XMLOutputFactory outputFactory = AccessController.doPrivileged(new PrivilegedAction() { + public XMLOutputFactory run() { + return XMLOutputFactory.newInstance(); + } + }); + ExtensibleStAXArtifactProcessor staxProcessor = + new ExtensibleStAXArtifactProcessor(staxProcessors, inputFactory, outputFactory, monitor); + + // Create URL artifact processor extension point + URLArtifactProcessorExtensionPoint documentProcessors = + registry.getExtensionPoint(URLArtifactProcessorExtensionPoint.class); + + // Create and register document processors for SCA assembly XML + documentProcessors.getProcessor(Composite.class); + DocumentBuilderFactory documentBuilderFactory = AccessController.doPrivileged(new PrivilegedAction() { + public DocumentBuilderFactory run() { + return DocumentBuilderFactory.newInstance(); + } + }); + documentProcessors.addArtifactProcessor(new CompositeDocumentProcessor(staxProcessor, validatingInputFactory, documentBuilderFactory, policyDefinitions, monitor)); + + // Create Model Resolver extension point + ModelResolverExtensionPoint modelResolvers = registry.getExtensionPoint(ModelResolverExtensionPoint.class); + + // Create contribution package processor extension point + TypeDescriber describer = new PackageTypeDescriberImpl(); + PackageProcessor packageProcessor = + new ExtensiblePackageProcessor(registry.getExtensionPoint(PackageProcessorExtensionPoint.class), describer, monitor); + + // Create contribution listener + ExtensibleContributionListener contributionListener = + new ExtensibleContributionListener(registry.getExtensionPoint(ContributionListenerExtensionPoint.class)); + + // Create a contribution repository + ContributionRepository repository; + try { + repository = new ContributionRepositoryImpl("target", inputFactory, monitor); + } catch (IOException e) { + throw new ActivationException(e); + } + + ExtensibleURLArtifactProcessor documentProcessor = new ExtensibleURLArtifactProcessor(documentProcessors, monitor); + + // Create the contribution service + ContributionService contributionService = + new ContributionServiceImpl(repository, packageProcessor, documentProcessor, staxProcessor, + contributionListener, policyDefinitionResolver, modelResolvers, modelFactories, + assemblyFactory, contributionFactory, inputFactory, policyDefinitions, registry, monitor); + return contributionService; + } + + public static ScopeRegistry createScopeRegistry(ExtensionPointRegistry registry) { + ScopeRegistry scopeRegistry = new ScopeRegistryImpl(); + ScopeContainerFactory[] factories = + new ScopeContainerFactory[] {new CompositeScopeContainerFactory(), new StatelessScopeContainerFactory(), + new RequestScopeContainerFactory(), + new ConversationalScopeContainerFactory(null), + // new HttpSessionScopeContainer(monitor) + }; + for (ScopeContainerFactory f : factories) { + scopeRegistry.register(f); + } + + //FIXME Pass the scope container differently as it's not an extension point + registry.addExtensionPoint(scopeRegistry); + + return scopeRegistry; + } + +} -- cgit v1.2.3