From 132aa8a77685ec92bc90c03f987650d275a7b639 Mon Sep 17 00:00:00 2001 From: lresende Date: Mon, 30 Sep 2013 06:59:11 +0000 Subject: 2.0.1 RC1 release tag git-svn-id: http://svn.us.apache.org/repos/asf/tuscany@1527464 13f79535-47bb-0310-9956-ffa450edef68 --- .../tuscany/sca/node/impl/NodeFactoryImpl.java | 504 +++++++++++++++++++++ .../org/apache/tuscany/sca/node/impl/NodeImpl.java | 443 ++++++++++++++++++ .../org/apache/tuscany/sca/node/impl/NodeUtil.java | 43 ++ 3 files changed, 990 insertions(+) create mode 100644 sca-java-2.x/tags/2.0.1-RC1/modules/node-impl/src/main/java/org/apache/tuscany/sca/node/impl/NodeFactoryImpl.java create mode 100644 sca-java-2.x/tags/2.0.1-RC1/modules/node-impl/src/main/java/org/apache/tuscany/sca/node/impl/NodeImpl.java create mode 100644 sca-java-2.x/tags/2.0.1-RC1/modules/node-impl/src/main/java/org/apache/tuscany/sca/node/impl/NodeUtil.java (limited to 'sca-java-2.x/tags/2.0.1-RC1/modules/node-impl/src/main/java/org/apache/tuscany/sca/node/impl') diff --git a/sca-java-2.x/tags/2.0.1-RC1/modules/node-impl/src/main/java/org/apache/tuscany/sca/node/impl/NodeFactoryImpl.java b/sca-java-2.x/tags/2.0.1-RC1/modules/node-impl/src/main/java/org/apache/tuscany/sca/node/impl/NodeFactoryImpl.java new file mode 100644 index 0000000000..a97f40e943 --- /dev/null +++ b/sca-java-2.x/tags/2.0.1-RC1/modules/node-impl/src/main/java/org/apache/tuscany/sca/node/impl/NodeFactoryImpl.java @@ -0,0 +1,504 @@ +/* + * 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.node.impl; + +import static java.lang.System.currentTimeMillis; +import static org.apache.tuscany.sca.common.java.io.IOHelper.createURI; +import static org.apache.tuscany.sca.common.java.io.IOHelper.openStream; + +import java.io.File; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.Reader; +import java.io.StringReader; +import java.net.URI; +import java.net.URL; +import java.security.AccessController; +import java.security.PrivilegedAction; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.logging.Level; +import java.util.logging.Logger; + +import javax.xml.namespace.QName; +import javax.xml.stream.XMLStreamException; + +import org.apache.tuscany.sca.assembly.AssemblyFactory; +import org.apache.tuscany.sca.assembly.Composite; +import org.apache.tuscany.sca.common.java.io.IOHelper; +import org.apache.tuscany.sca.contribution.Artifact; +import org.apache.tuscany.sca.contribution.Contribution; +import org.apache.tuscany.sca.contribution.processor.ContributionReadException; +import org.apache.tuscany.sca.contribution.processor.ProcessorContext; +import org.apache.tuscany.sca.contribution.processor.ValidationSchemaExtensionPoint; +import org.apache.tuscany.sca.core.DefaultExtensionPointRegistry; +import org.apache.tuscany.sca.core.ExtensionPointRegistry; +import org.apache.tuscany.sca.core.FactoryExtensionPoint; +import org.apache.tuscany.sca.core.ModuleActivatorExtensionPoint; +import org.apache.tuscany.sca.core.UtilityExtensionPoint; +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.deployment.Deployer; +import org.apache.tuscany.sca.extensibility.ServiceDiscovery; +import org.apache.tuscany.sca.monitor.Monitor; +import org.apache.tuscany.sca.monitor.MonitorFactory; +import org.apache.tuscany.sca.monitor.Problem; +import org.apache.tuscany.sca.monitor.Problem.Severity; +import org.apache.tuscany.sca.node.Node; +import org.apache.tuscany.sca.node.NodeFactory; +import org.apache.tuscany.sca.node.configuration.BindingConfiguration; +import org.apache.tuscany.sca.node.configuration.ContributionConfiguration; +import org.apache.tuscany.sca.node.configuration.DefaultNodeConfigurationFactory; +import org.apache.tuscany.sca.node.configuration.DeploymentComposite; +import org.apache.tuscany.sca.node.configuration.NodeConfiguration; +import org.apache.tuscany.sca.node.configuration.NodeConfigurationFactory; +import org.apache.tuscany.sca.node.extensibility.NodeExtension; +import org.apache.tuscany.sca.runtime.DomainRegistryFactory; +import org.apache.tuscany.sca.runtime.ExtensibleDomainRegistryFactory; +import org.apache.tuscany.sca.runtime.RuntimeProperties; +import org.apache.tuscany.sca.work.WorkScheduler; +import org.oasisopen.sca.ServiceRuntimeException; + +/** + * This class provides a node factory that can create multiple nodes that share the same + * extension point registry + */ +public class NodeFactoryImpl extends NodeFactory { + protected static final Logger logger = Logger.getLogger(NodeImpl.class.getName()); + + protected boolean inited; + protected Map nodes = new ConcurrentHashMap(); + + protected Deployer deployer; + protected ExtensionPointRegistry registry; + protected ProxyFactory proxyFactory; + protected MonitorFactory monitorFactory; + + /** + * Automatically destroy the factory when last node is stopped. Subclasses + * can set this flag. + */ + protected boolean autoDestroy = true; + + boolean quietLogging; + + @Override + public Node createNode(NodeConfiguration configuration) { + if (configuration.getURI() == null) { + // Make sure a unique node URI is created for the same node factory + configuration.setURI(generateNodeURI()); + } + return new NodeImpl(this, configuration); + } + + protected Node removeNode(NodeConfiguration configuration) { + Node node = nodes.remove(getNodeKey(configuration)); + if (autoDestroy && nodes.isEmpty()) { + destroy(); + } + return node; + } + + @SuppressWarnings("unchecked") + @Override + public Node createNode(List contributions) { + NodeConfigurationFactory nodeConfigurationFactory = new DefaultNodeConfigurationFactory(); + return new NodeImpl(this, nodeConfigurationFactory.createNodeConfiguration(), new ArrayList((List)contributions)); + } + + protected void addNode(NodeConfiguration configuration, Node node) { + nodes.put(getNodeKey(configuration), node); + } + + @Override + public NodeConfiguration loadConfiguration(InputStream xml, URL base) { + try { + init(); + InputStreamReader reader = new InputStreamReader(xml, "UTF-8"); + ProcessorContext context = deployer.createProcessorContext(); + NodeConfiguration config = deployer.loadXMLDocument(reader, context.getMonitor()); + if (base != null && config != null) { + // Resolve the contribution location against the node.xml + for (ContributionConfiguration c : config.getContributions()) { + String location = c.getLocation(); + if (location != null) { + URL url = new URL(base, location); + url = IOHelper.normalize(url); + c.setLocation(url.toString()); + } + } + } + return config; + } catch (Throwable e) { + throw new ServiceRuntimeException(e); + } + } + + public Map getNodes() { + return nodes; + } + + public List getNodesInDomain(String domainName) { + List domainNodes = new ArrayList(); + if (nodes != null) { + for (Node n : nodes.values()) { + if (domainName.equals(((NodeImpl)n).getConfiguration().getDomainURI())) { + domainNodes.add(n); + } + } + } + return domainNodes; + } + + protected Object getNodeKey(NodeConfiguration configuration) { + return new NodeKey(configuration); + } + + public synchronized void destroy() { + if (inited) { + for (Node node : nodes.values()) { + node.stop(); + } + nodes.clear(); + deployer.stop(); + registry.stop(); + super.destroy(); + inited = false; + } + } + + /** + * Analyze problems reported by the artifact processors and builders. + * + * @throws Exception + */ + private void analyzeProblems(Monitor monitor) throws Throwable { + try { + for (Problem problem : monitor.getProblems()) { + if ((problem.getSeverity() == Severity.ERROR)) { + if (problem.getCause() != null) { + throw problem.getCause(); + } else { + throw new ServiceRuntimeException(problem.toString()); + } + } + } + } finally { + // FIXME: Clear problems so that the monitor is clean again + monitor.reset(); + } + } + + private boolean attachDeploymentComposite(Contribution contribution, Reader xml, String location, boolean attached, ProcessorContext context) + throws XMLStreamException, ContributionReadException { + + // Read the composite model + Composite composite = deployer.loadXMLDocument(xml, context.getMonitor()); + + // Replace the deployable composites with the deployment composites + // Clear the deployable composites if it's the first deployment composite + deployer.attachDeploymentComposite(contribution, composite, attached); + if (!attached) { + attached = true; + } + return attached; + } + + public ExtensionPointRegistry getExtensionPointRegistry() { + if (registry == null) { + // Create extension point registry + registry = createExtensionPointRegistry(); + registry.start(); + } + return registry; + } + + public synchronized void init() { + if (inited) { + return; + } + long start = currentTimeMillis(); + + getExtensionPointRegistry(); + + UtilityExtensionPoint utilities = registry.getExtensionPoint(UtilityExtensionPoint.class); + monitorFactory = utilities.getUtility(MonitorFactory.class); + + utilities.getUtility(RuntimeProperties.class).setProperties(properties); + quietLogging = Boolean.parseBoolean(properties.getProperty(RuntimeProperties.QUIET_LOGGING)); + + // Use the runtime-enabled assembly factory + FactoryExtensionPoint modelFactories = registry.getExtensionPoint(FactoryExtensionPoint.class); + AssemblyFactory assemblyFactory = new RuntimeAssemblyFactory(registry); + modelFactories.addFactory(assemblyFactory); + + // Load the Deployer + deployer = utilities.getUtility(Deployer.class); + + // Enable schema validation only of the logger level is FINE or higher + deployer.setSchemaValidationEnabled(isSchemaValidationEnabled()); + + // Initialize the Tuscany module activators + // The module activators will be started + registry.getExtensionPoint(ModuleActivatorExtensionPoint.class); + + // Initialize runtime + + // Get proxy factory + proxyFactory = ExtensibleProxyFactory.getInstance(registry); + + utilities.getUtility(WorkScheduler.class); + + inited = true; + + if (logger.isLoggable(Level.FINE)) { + long end = currentTimeMillis(); + logger.fine("The tuscany runtime started in " + (end - start) + " ms."); + } + } + + public void start() { + init(); + DomainRegistryFactory domainRegistryFactory = ExtensibleDomainRegistryFactory.getInstance(registry); + domainRegistryFactory.getEndpointRegistry(properties.getProperty("reguri"), properties.getProperty("defaultDomainName")); + } + + protected ExtensionPointRegistry createExtensionPointRegistry() { + return new DefaultExtensionPointRegistry(); + } + + protected boolean isSchemaValidationEnabled() { + String enabled = getSystemProperty(ValidationSchemaExtensionPoint.class.getName() + ".enabled"); + if (enabled == null) { + enabled = "true"; + } + boolean debug = logger.isLoggable(Level.FINE); + return "true".equals(enabled) || debug; + } + + protected Composite configureNode(NodeConfiguration configuration, List contributions, ProcessorContext context) + throws Throwable { + if (contributions == null) { + // Load contributions + contributions = loadContributions(configuration, context); + } + + Monitor monitor = context.getMonitor(); + Map> bindingBaseURIs = new HashMap>(); + for (BindingConfiguration config : configuration.getBindings()) { + bindingBaseURIs.put(config.getBindingType(), config.getBaseURIs()); + } + List allContributions = getAllContributions(configuration.getDomainURI()); + + Composite domainComposite = deployer.build(contributions, allContributions, bindingBaseURIs, monitor); + analyzeProblems(monitor); + + // postBuildEndpointReferenceMatching(domainComposite); + + return domainComposite; + } + + private List getAllContributions(String domainName) { + List contributions = new ArrayList(); + for (NodeFactory f : getNodeFactories()) { + for (Node node : ((NodeFactoryImpl)f).getNodesInDomain(domainName)) { + contributions.addAll(((NodeImpl)node).getContributions()); + } + } + return contributions; + } + + protected List loadContributions(NodeConfiguration configuration, ProcessorContext context) throws Throwable { + List contributions = new ArrayList(); + + // Load the specified contributions + for (ContributionConfiguration contrib : configuration.getContributions()) { + URI contributionURI = createURI(contrib.getURI()); + + URI uri = createURI(contrib.getLocation()); + if (uri != null && uri.getScheme() == null) { + uri = new File(contrib.getLocation()).toURI(); + } + URL contributionURL = null; + if (uri != null) { + contributionURL = uri.toURL(); + } + + // Load the contribution + logger.log(quietLogging? Level.FINE : Level.INFO, "Loading contribution: " + contributionURL); + Contribution contribution = deployer.loadContribution(contributionURI, contributionURL, context.getMonitor()); + contributions.add(contribution); + + boolean attached = false; + for (DeploymentComposite dc : contrib.getDeploymentComposites()) { + if (dc.getContent() != null) { + Reader xml = new StringReader(dc.getContent()); + attached = attachDeploymentComposite(contribution, xml, null, attached, context); + } else if (dc.getLocation() != null) { + URI dcURI = createURI(dc.getLocation()); + if (!dcURI.isAbsolute()) { + Composite composite = null; + // The location is pointing to an artifact within the contribution + for (Artifact a : contribution.getArtifacts()) { + if (dcURI.toString().equals(a.getURI())) { + composite = (Composite)a.getModel(); + if (!attached) { + contribution.getDeployables().clear(); + attached = true; + } + contribution.getDeployables().add(composite); + break; + } + } + if (composite == null) { + // Not found + throw new ServiceRuntimeException("Deployment composite " + dcURI + + " cannot be found within contribution " + + contribution.getLocation()); + } + } else { + URL url = dcURI.toURL(); + InputStream is = openStream(url); + Reader xml = new InputStreamReader(is, "UTF-8"); + attached = attachDeploymentComposite(contribution, xml, url.toString(), attached, context); + } + } + } + analyzeProblems(context.getMonitor()); + } + return contributions; + } + + protected static String getSystemProperty(final String name) { + return AccessController.doPrivileged(new PrivilegedAction() { + public String run() { + return System.getProperty(name); + } + }); + } + + protected static class NodeKey { + private String domainURI; + private String nodeURI; + + public NodeKey(NodeConfiguration configuration) { + this.domainURI = configuration.getDomainURI(); + this.nodeURI = configuration.getURI(); + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((domainURI == null) ? 0 : domainURI.hashCode()); + result = prime * result + ((nodeURI == null) ? 0 : nodeURI.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + NodeKey other = (NodeKey)obj; + if (domainURI == null) { + if (other.domainURI != null) + return false; + } else if (!domainURI.equals(other.domainURI)) + return false; + if (nodeURI == null) { + if (other.nodeURI != null) + return false; + } else if (!nodeURI.equals(other.nodeURI)) + return false; + return true; + } + + public String toString() { + StringBuffer buf = new StringBuffer(); + if (domainURI != null) { + buf.append("{").append(domainURI).append("}"); + } + if (nodeURI != null) { + buf.append(nodeURI); + } + return buf.toString(); + } + } + + @Override + public void configure(Map> attributes) { + ServiceDiscovery discovery = getExtensionPointRegistry().getServiceDiscovery(); + for (Map.Entry> e : attributes.entrySet()) { + discovery.setAttribute(e.getKey(), e.getValue()); + } + for (Object o : properties.keySet()) { + String p = (String) o; + if (p.indexOf('.') > -1) { + String serviceType = p.substring(0, p.lastIndexOf('.')); + String attribute = p.substring(p.lastIndexOf('.')+1); + discovery.setAttribute(serviceType, attribute, properties.getProperty(p)); + } + } + quietLogging = Boolean.parseBoolean(properties.getProperty(RuntimeProperties.QUIET_LOGGING)); + super.configure(attributes); + } + + /** + * Added to allow the node access to the deployer in order to get + * to the systemContribution and hence set up the CompositeContext so that + * the runtime epr matching algorithm can get at the binding types + * @return + */ + public Deployer getDeployer() { + return deployer; + } + + @Override + public void setAutoDestroy(boolean b) { + autoDestroy = b; + } + + /** + * Create and load a node + * @param configuration + * @return The node + */ + public NodeExtension loadNode(NodeConfiguration configuration) { + Node node = createNode(configuration); + + try { + NodeImpl nodeImpl = ((NodeImpl) node); + nodeImpl.load(); + return nodeImpl; + } catch (Throwable e) { + throw new ServiceRuntimeException(e); + } + } + + +} diff --git a/sca-java-2.x/tags/2.0.1-RC1/modules/node-impl/src/main/java/org/apache/tuscany/sca/node/impl/NodeImpl.java b/sca-java-2.x/tags/2.0.1-RC1/modules/node-impl/src/main/java/org/apache/tuscany/sca/node/impl/NodeImpl.java new file mode 100644 index 0000000000..453b4fb486 --- /dev/null +++ b/sca-java-2.x/tags/2.0.1-RC1/modules/node-impl/src/main/java/org/apache/tuscany/sca/node/impl/NodeImpl.java @@ -0,0 +1,443 @@ +/* + * 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.node.impl; + +import java.io.ByteArrayOutputStream; +import java.util.ArrayList; +import java.util.List; +import java.util.logging.Level; +import java.util.logging.Logger; + +import javax.xml.stream.XMLOutputFactory; +import javax.xml.stream.XMLStreamWriter; + +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.Endpoint; +import org.apache.tuscany.sca.assembly.Service; +import org.apache.tuscany.sca.context.CompositeContext; +import org.apache.tuscany.sca.context.ThreadMessageContext; +import org.apache.tuscany.sca.contribution.Contribution; +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.UtilityExtensionPoint; +import org.apache.tuscany.sca.core.invocation.ProxyFactory; +import org.apache.tuscany.sca.interfacedef.Interface; +import org.apache.tuscany.sca.interfacedef.java.JavaInterface; +import org.apache.tuscany.sca.monitor.Monitor; +import org.apache.tuscany.sca.node.Node; +import org.apache.tuscany.sca.node.configuration.NodeConfiguration; +import org.apache.tuscany.sca.node.extensibility.NodeActivator; +import org.apache.tuscany.sca.node.extensibility.NodeActivatorExtensionPoint; +import org.apache.tuscany.sca.node.extensibility.NodeExtension; +import org.apache.tuscany.sca.runtime.ActivationException; +import org.apache.tuscany.sca.runtime.CompositeActivator; +import org.apache.tuscany.sca.runtime.DomainRegistry; +import org.apache.tuscany.sca.runtime.DomainRegistryFactory; +import org.apache.tuscany.sca.runtime.ExtensibleDomainRegistryFactory; +import org.apache.tuscany.sca.runtime.RuntimeComponent; +import org.apache.tuscany.sca.runtime.RuntimeComponentService; +import org.oasisopen.sca.ServiceReference; +import org.oasisopen.sca.ServiceRuntimeException; +import org.oasisopen.sca.ServiceUnavailableException; + +/** + * An SCA Node that is managed by the NodeManager + */ +public class NodeImpl implements Node, NodeExtension { + private static final Logger logger = Logger.getLogger(NodeImpl.class.getName()); + private ProxyFactory proxyFactory; + private CompositeActivator compositeActivator; + private CompositeContext compositeContext; + private Composite domainComposite; + private NodeConfiguration configuration; + private NodeFactoryImpl nodeFactory; + private List contributions; + private NodeActivatorExtensionPoint nodeActivators; + // private NodeManager mbean; + + /** + * Create a node from the configuration + * @param manager + * @param configuration + */ + public NodeImpl(NodeFactoryImpl nodeFactory, NodeConfiguration configuration) { + super(); + this.configuration = configuration; + this.nodeFactory = nodeFactory; + this.nodeActivators = nodeFactory.getExtensionPointRegistry().getExtensionPoint(NodeActivatorExtensionPoint.class); + } + + /** + * Create a node from the configuration and loaded contributions + * @param manager + * @param configuration + * @param contributions + */ + public NodeImpl(NodeFactoryImpl manager, NodeConfiguration configuration, List contributions) { + super(); + this.configuration = configuration; + this.nodeFactory = manager; + this.nodeActivators = nodeFactory.getExtensionPointRegistry().getExtensionPoint(NodeActivatorExtensionPoint.class); + this.contributions = new ArrayList(contributions); + } + + public String getURI() { + return getConfiguration().getURI(); + } + + public String getDomainURI() { + return getConfiguration().getDomainURI(); + } + + public Node start() { + logger.log(nodeFactory.quietLogging? Level.FINE : Level.INFO, "Starting node: " + configuration.getURI() + " domain: " + configuration.getDomainURI()); + + try { + load(); + + this.proxyFactory = nodeFactory.proxyFactory; + + // Set up the node context + UtilityExtensionPoint utilities = nodeFactory.registry.getExtensionPoint(UtilityExtensionPoint.class); + this.compositeActivator = utilities.getUtility(CompositeActivator.class); + + DomainRegistryFactory domainRegistryFactory = + ExtensibleDomainRegistryFactory.getInstance(nodeFactory.registry); + DomainRegistry domainRegistry = + domainRegistryFactory.getEndpointRegistry(configuration.getDomainRegistryURI(), + configuration.getDomainURI()); + + this.compositeContext = + new CompositeContext(nodeFactory.registry, domainRegistry, domainComposite, + configuration.getDomainURI(), configuration.getURI(), nodeFactory + .getDeployer().getSystemDefinitions()); + // Pass down the context attributes + compositeContext.getAttributes().putAll(configuration.getAttributes()); + + // Add endpoint descriptions from the node configuration if the domain registry is local + if (!domainRegistry.isDistributed()) { + for (Endpoint e : configuration.getEndpointDescriptions()) { + domainRegistry.addEndpoint(e); + } + } + // Activate the composite + compositeActivator.activate(compositeContext, domainComposite); + + // Start the composite + compositeActivator.start(compositeContext, domainComposite); + + // FIXME: [rfeng] We should turn the management capability into a system utility. + // In certain environment such as Google App Engine, the JMX API is not allowed + try { + /* + MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer(); + mbean = new NodeManager(this); + mBeanServer.registerMBean(mbean, mbean.getName()); + */ + /* + LocateRegistry.createRegistry(9999); + JMXServiceURL url = + new JMXServiceURL("service:jmx:rmi:///jndi/rmi://localhost:9999/server"); + JMXConnectorServer connectorServer = JMXConnectorServerFactory.newJMXConnectorServer(url, null, mBeanServer); + connectorServer.start(); + */ + } catch (Throwable e) { + // Ignore the error for now + // mbean = null; + logger.log(Level.SEVERE, e.getMessage(), e); + } + + for(NodeActivator activator : nodeActivators.getNodeActivators()) { + activator.nodeStarted(this); + } + return this; + + } catch (Throwable e) { + throw new IllegalStateException(e); + } + + } + + public void load() throws Throwable { + nodeFactory.init(); + + nodeFactory.addNode(configuration, this); + + Monitor monitor = nodeFactory.monitorFactory.createMonitor(); + ProcessorContext context = new ProcessorContext(monitor); + + // Set up the thead context monitor + Monitor tcm = nodeFactory.monitorFactory.setContextMonitor(monitor); + try { + // Use the lack of the contributions collection as an indicator for when the node + // is being started for the first time. If it is the first time do all the work + // to read the contributions and create the domain composite + if (contributions == null) { + contributions = nodeFactory.loadContributions(configuration, context); + } + + if (domainComposite == null) { + domainComposite = nodeFactory.configureNode(configuration, contributions, context); + } + + + } finally { + // Reset the thread context monitor + nodeFactory.monitorFactory.setContextMonitor(tcm); + } + } + + public void stop() { + logger.log(nodeFactory.quietLogging? Level.FINE : Level.INFO, "Stopping node: " + configuration.getURI()); + + try { + if (compositeActivator == null) { + return; + } + + /* + if (mbean != null) { + try { + MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer(); + mBeanServer.unregisterMBean(mbean.getName()); + } catch (Throwable e) { + logger.log(Level.SEVERE, e.getMessage(), e); + } finally { + mbean = null; + } + } + */ + + if( domainComposite != null ) { + + // Stop the composite + compositeActivator.stop(compositeContext, domainComposite); + + // Deactivate the composite + compositeActivator.deactivate(domainComposite); + + } // end if + + // Remove the external endpoint descriptions from node.xml + DomainRegistry domainRegistry = compositeContext.getEndpointRegistry(); + if (!domainRegistry.isDistributed()) { + for (Endpoint e : configuration.getEndpointDescriptions()) { + domainRegistry.removeEndpoint(e); + } + } + + nodeFactory.removeNode(configuration); +/* + this.compositeActivator = null; + this.proxyFactory = null; + this.domainComposite = null; + this.compositeContext = null; +*/ + + for(NodeActivator activator : nodeActivators.getNodeActivators()) { + activator.nodeStopped(this); + } + + ThreadMessageContext.removeMessageContext(); + + } catch (ActivationException e) { + throw new IllegalStateException(e); + } + + } + + @SuppressWarnings("unchecked") + public > R cast(B target) throws IllegalArgumentException { + return (R)proxyFactory.cast(target); + } + + 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(); + } + + public ServiceReference getServiceReference(Class businessInterface, String name) { + + // Extract the component name + String componentName = null; + String serviceName = null; + if (name != null) { + 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 + Component component = null; + + for (Component compositeComponent : domainComposite.getComponents()) { + if (componentName == null) { + for (ComponentService service : compositeComponent.getServices()) { + Interface intf = service.getInterfaceContract().getInterface(); + if (intf instanceof JavaInterface) { + JavaInterface ji = (JavaInterface)intf; + if (ji.getJavaClass() == businessInterface) { + return ((RuntimeComponent)compositeComponent).getComponentContext() + .createSelfReference(businessInterface, service); + } + } + } + } + if (compositeComponent.getName().equals(componentName)) { + component = compositeComponent; + break; + } + } + + if (component == null) { + throw new ServiceUnavailableException("The service " + name + " has not been contributed to the domain"); + } + + return ((RuntimeComponent)component).getServiceReference(businessInterface, serviceName); + } + + public NodeConfiguration getConfiguration() { + return configuration; + } + + public ExtensionPointRegistry getExtensionPointRegistry() { + return nodeFactory.getExtensionPointRegistry(); + } + + /** + * Get the service endpoints in this Node + * TODO: needs review, works for the very simple testcase but i expect there are + * other endpoints to be included + */ + public List getServiceEndpoints() { + List endpoints = new ArrayList(); + if (compositeActivator != null) { + if (domainComposite != null) { + for (Component component : domainComposite.getComponents()) { + for (Service service : component.getServices()) { + // MJE 28/05/2009 - changed to RuntimeComponentService from RuntimeComponentServiceImpl + // - no need to access the Impl directly here + if (service instanceof RuntimeComponentService) { + endpoints.addAll(((RuntimeComponentService)service).getEndpoints()); + } + } + } + } + } + return endpoints; + } + + public Composite getDomainComposite() { + return domainComposite; + } + + public String dumpDomainComposite() { + + StAXArtifactProcessorExtensionPoint xmlProcessors = + getExtensionPointRegistry().getExtensionPoint(StAXArtifactProcessorExtensionPoint.class); + StAXArtifactProcessor compositeProcessor = + xmlProcessors.getProcessor(Composite.class); + + return writeComposite(getDomainComposite(), compositeProcessor); + } + + private String writeComposite(Composite composite, StAXArtifactProcessor compositeProcessor){ + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + XMLOutputFactory outputFactory = + nodeFactory.getExtensionPointRegistry().getExtensionPoint(FactoryExtensionPoint.class) + .getFactory(XMLOutputFactory.class); + + try { + XMLStreamWriter xmlStreamWriter = outputFactory.createXMLStreamWriter(bos); + compositeProcessor.write(composite, xmlStreamWriter, new ProcessorContext(nodeFactory.registry)); + xmlStreamWriter.flush(); + } catch(Exception ex) { + return ex.toString(); + } + + + String result = bos.toString(); + + // write out and nested composites + for (Component component : composite.getComponents()) { + if (component.getImplementation() instanceof Composite) { + result += "\n\n" + + writeComposite((Composite)component.getImplementation(), + compositeProcessor); + } + } + + return result; + } + + public List getContributions() { + return contributions; + } + + @Override + public String getEndpointAddress(String serviceBindingName) { + if (serviceBindingName == null) { + throw new IllegalArgumentException("Service binding name cannot be null"); + } + + // Calculate the names for compoment/service/binding + String[] parts = serviceBindingName.split("/"); + String componentName = parts[0]; + String serviceName = parts.length >= 2 ? parts[1] : null; + String bindingName = parts.length >= 3 ? parts[2] : serviceName; + + if (domainComposite != null) { + for (Component component : domainComposite.getComponents()) { + if (!component.getName().equals(componentName)) { + continue; + } + for (Service service : component.getServices()) { + if (serviceName != null && !service.getName().equals(serviceName)) { + continue; + } + if (service instanceof RuntimeComponentService) { + for (Endpoint ep : ((RuntimeComponentService)service).getEndpoints()) { + if (bindingName == null || bindingName.equals(ep.getBinding().getName())) { + return ep.getDeployedURI(); + } + } + } + } + } + } + return null; + } + +} diff --git a/sca-java-2.x/tags/2.0.1-RC1/modules/node-impl/src/main/java/org/apache/tuscany/sca/node/impl/NodeUtil.java b/sca-java-2.x/tags/2.0.1-RC1/modules/node-impl/src/main/java/org/apache/tuscany/sca/node/impl/NodeUtil.java new file mode 100644 index 0000000000..4da41442f5 --- /dev/null +++ b/sca-java-2.x/tags/2.0.1-RC1/modules/node-impl/src/main/java/org/apache/tuscany/sca/node/impl/NodeUtil.java @@ -0,0 +1,43 @@ +/* + * 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.node.impl; + +import org.apache.tuscany.sca.contribution.Contribution; +import org.apache.tuscany.sca.contribution.ContributionFactory; + +/** + * NodeUtil + * + * @version $Rev$ $Date$ + */ +public class NodeUtil { + + private NodeUtil() { + } + + static Contribution contribution(ContributionFactory contributionFactory, org.apache.tuscany.sca.node.Contribution c) { + Contribution contribution = contributionFactory.createContribution(); + contribution.setURI(c.getURI()); + contribution.setLocation(c.getLocation()); + contribution.setUnresolved(true); + return contribution; + } + +} -- cgit v1.2.3