diff options
Diffstat (limited to 'sca-java-2.x/tags/2.0.1/modules/domain-node/src/main/java/org/apache/tuscany/sca/impl')
8 files changed, 1477 insertions, 0 deletions
diff --git a/sca-java-2.x/tags/2.0.1/modules/domain-node/src/main/java/org/apache/tuscany/sca/impl/ContributionHelper.java b/sca-java-2.x/tags/2.0.1/modules/domain-node/src/main/java/org/apache/tuscany/sca/impl/ContributionHelper.java new file mode 100644 index 0000000000..9125fd47c8 --- /dev/null +++ b/sca-java-2.x/tags/2.0.1/modules/domain-node/src/main/java/org/apache/tuscany/sca/impl/ContributionHelper.java @@ -0,0 +1,80 @@ +/*
+ * 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.impl;
+
+import java.net.URLClassLoader;
+
+import org.apache.tuscany.sca.common.xml.dom.DOMHelper;
+import org.apache.tuscany.sca.contribution.Contribution;
+import org.apache.tuscany.sca.contribution.java.impl.ClassLoaderModelResolver;
+import org.apache.tuscany.sca.contribution.resolver.ClassReference;
+import org.apache.tuscany.sca.contribution.resolver.ExtensibleModelResolver;
+import org.apache.tuscany.sca.contribution.resolver.ModelResolver;
+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.core.invocation.ProxyFactoryExtensionPoint;
+import org.apache.tuscany.sca.databinding.jaxb.JAXBContextHelper;
+import org.apache.tuscany.sca.interfacedef.java.JavaInterfaceFactory;
+
+import sun.misc.ClassLoaderUtil;
+
+public class ContributionHelper {
+
+ public static void close(Contribution contribution, ExtensionPointRegistry extensionPointRegistry) {
+ ClassLoader contributionClassloader = contribution.getClassLoader();
+
+ if (contributionClassloader == null && contribution.getModelResolver() instanceof ExtensibleModelResolver) {
+ ModelResolver o = ((ExtensibleModelResolver)contribution.getModelResolver()).getModelResolverInstance(ClassReference.class);
+ if (o instanceof ClassLoader) {
+ contributionClassloader = (ClassLoader)o;
+ contribution.setClassLoader(contributionClassloader);
+ }
+ }
+
+ UtilityExtensionPoint utilityExtensionPoint = extensionPointRegistry.getExtensionPoint(UtilityExtensionPoint.class);
+ FactoryExtensionPoint factoryExtensionPoint = extensionPointRegistry.getExtensionPoint(FactoryExtensionPoint.class);
+
+ JAXBContextHelper jaxbContextHelper = utilityExtensionPoint.getUtility(JAXBContextHelper.class);
+ jaxbContextHelper.removeJAXBContextForContribution(contributionClassloader);
+
+ JavaInterfaceFactory javaInterfaceFactory = factoryExtensionPoint.getFactory(JavaInterfaceFactory.class);
+ javaInterfaceFactory.removeInterfacesForContribution(contributionClassloader);
+
+ ProxyFactoryExtensionPoint proxyFactoryExtensionPoint = extensionPointRegistry.getExtensionPoint(ProxyFactoryExtensionPoint.class);
+ ProxyFactory interfaceProxyFactory = proxyFactoryExtensionPoint.getInterfaceProxyFactory();
+ interfaceProxyFactory.removeProxiesForContribution(contributionClassloader);
+
+ DOMHelper.getInstance(extensionPointRegistry).stop();
+ java.beans.Introspector.flushCaches();
+
+ if (contributionClassloader instanceof URLClassLoader) {
+ ClassLoaderUtil.releaseLoader((URLClassLoader)contributionClassloader);
+ }
+
+ if (contributionClassloader instanceof ClassLoaderModelResolver) {
+ ClassLoaderModelResolver clmr = (ClassLoaderModelResolver) contributionClassloader;
+ clmr.clear();
+ }
+
+ contribution.setClassLoader(null);
+ }
+
+}
diff --git a/sca-java-2.x/tags/2.0.1/modules/domain-node/src/main/java/org/apache/tuscany/sca/impl/DependencyUtils.java b/sca-java-2.x/tags/2.0.1/modules/domain-node/src/main/java/org/apache/tuscany/sca/impl/DependencyUtils.java new file mode 100644 index 0000000000..08c426da42 --- /dev/null +++ b/sca-java-2.x/tags/2.0.1/modules/domain-node/src/main/java/org/apache/tuscany/sca/impl/DependencyUtils.java @@ -0,0 +1,76 @@ +/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.tuscany.sca.impl;
+
+import java.io.BufferedOutputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.StringReader;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipInputStream;
+
+import javax.xml.stream.XMLStreamException;
+
+import org.apache.tuscany.sca.TuscanyRuntime;
+import org.apache.tuscany.sca.contribution.Contribution;
+import org.apache.tuscany.sca.contribution.ContributionMetadata;
+import org.apache.tuscany.sca.contribution.processor.ContributionReadException;
+import org.apache.tuscany.sca.deployment.Deployer;
+import org.apache.tuscany.sca.monitor.Monitor;
+import org.apache.tuscany.sca.monitor.ValidationException;
+
+public class DependencyUtils {
+
+ public static List<String> getDependencies(String contributionURI, Map<String, ZipInputStream> possibles) throws ValidationException, IOException, ContributionReadException, XMLStreamException {
+ Deployer deployer = TuscanyRuntime.newInstance().getDeployer();
+
+ Map<String, ContributionMetadata> contributionMetaDatas = new HashMap<String, ContributionMetadata>();
+ for (String curi : possibles.keySet()) {
+ ZipInputStream zis = possibles.get(curi);
+ ZipEntry entry;
+ while ((entry = zis.getNextEntry()) != null) {
+ if (Contribution.SCA_CONTRIBUTION_META.equals(entry.getName())) {
+
+ byte[] buffer = new byte[2048];
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ BufferedOutputStream bos = new BufferedOutputStream(baos, buffer.length);
+
+ int size;
+ while ((size = zis.read(buffer, 0, buffer.length)) != -1) {
+ bos.write(buffer, 0, size);
+ }
+ bos.close();
+
+ contributionMetaDatas.put(curi, (ContributionMetadata)deployer.loadXMLDocument(new StringReader(baos.toString())));
+ }
+ }
+ zis.close(); // close it so no one tries to reuse the already read stream
+ }
+ Monitor monitor = deployer.createMonitor();
+ try {
+ return deployer.getDependencies(contributionMetaDatas, contributionURI, monitor);
+ } finally {
+ monitor.analyzeProblems();
+ }
+ }
+}
diff --git a/sca-java-2.x/tags/2.0.1/modules/domain-node/src/main/java/org/apache/tuscany/sca/impl/DeployedComposite.java b/sca-java-2.x/tags/2.0.1/modules/domain-node/src/main/java/org/apache/tuscany/sca/impl/DeployedComposite.java new file mode 100644 index 0000000000..fb40980d04 --- /dev/null +++ b/sca-java-2.x/tags/2.0.1/modules/domain-node/src/main/java/org/apache/tuscany/sca/impl/DeployedComposite.java @@ -0,0 +1,185 @@ +/* + * 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.impl; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.xml.namespace.QName; + +import org.apache.tuscany.sca.assembly.Component; +import org.apache.tuscany.sca.assembly.Composite; +import org.apache.tuscany.sca.assembly.builder.CompositeBuilderException; +import org.apache.tuscany.sca.assembly.impl.CompositeImpl; +import org.apache.tuscany.sca.context.CompositeContext; +import org.apache.tuscany.sca.contribution.Contribution; +import org.apache.tuscany.sca.contribution.processor.ContributionResolveException; +import org.apache.tuscany.sca.contribution.resolver.ClassReference; +import org.apache.tuscany.sca.contribution.resolver.ExtensibleModelResolver; +import org.apache.tuscany.sca.contribution.resolver.ModelResolver; +import org.apache.tuscany.sca.core.ExtensionPointRegistry; +import org.apache.tuscany.sca.deployment.Deployer; +import org.apache.tuscany.sca.monitor.Monitor; +import org.apache.tuscany.sca.monitor.ValidationException; +import org.apache.tuscany.sca.runtime.ActivationException; +import org.apache.tuscany.sca.runtime.CompositeActivator; +import org.apache.tuscany.sca.runtime.DomainRegistry; + +public class DeployedComposite { + + private Composite composite; + private Contribution contribution; + private List<Contribution> dependedOnContributions; + private Composite builtComposite; + + private CompositeActivator compositeActivator; + private CompositeContext compositeContext; + private Deployer deployer; + private DomainRegistry domainRegistry; + private ExtensionPointRegistry extensionPointRegistry; + private List<String> usedContributionURIs; + private boolean endpointsIncludeDomainName; + + public DeployedComposite(Composite composite, + Contribution contribution, + List<Contribution> dependedOnContributions, + Deployer deployer, + CompositeActivator compositeActivator, + DomainRegistry domainRegistry, + ExtensionPointRegistry extensionPointRegistry, + boolean endpointsIncludeDomainName) throws ValidationException, ActivationException { + this.composite = composite; + this.contribution = contribution; + this.dependedOnContributions = dependedOnContributions; + this.deployer = deployer; + this.compositeActivator = compositeActivator; + this.domainRegistry = domainRegistry; + this.extensionPointRegistry = extensionPointRegistry; + this.endpointsIncludeDomainName = endpointsIncludeDomainName; + + try { + build(); + } catch (ContributionResolveException e) { + throw new ActivationException(e); + } catch (CompositeBuilderException e) { + throw new ActivationException(e); + } + } + + protected void build() throws ValidationException, ActivationException, ContributionResolveException, CompositeBuilderException { + + List<Contribution> contributions = new ArrayList<Contribution>(); + contributions.add(contribution); + contributions.get(0).getDeployables().clear(); + contributions.get(0).getDeployables().add(composite); + + contributions.addAll(dependedOnContributions); + + Map<QName, List<String>> bs = new HashMap<QName, List<String>>(); + if (endpointsIncludeDomainName) { + bs.put(new QName("default"), Arrays.asList(new String[]{domainRegistry.getDomainName()})); + } + + Monitor monitor = deployer.createMonitor(); + builtComposite = deployer.build(contributions, contributions, bs, monitor); + monitor.analyzeProblems(); + + // TODO: Ideally deployer.build would set the name and uri to what this needs + builtComposite.setName(composite.getName()); + builtComposite.setURI(composite.getURI()); + builtComposite.setContributionURI(composite.getContributionURI()); + + // attempt to ensure the contribution classloader is set + // TODO: ideally the runtime would do this itself + if (contribution.getClassLoader() == null && contribution.getModelResolver() instanceof ExtensibleModelResolver) { + ModelResolver o = ((ExtensibleModelResolver)contribution.getModelResolver()).getModelResolverInstance(ClassReference.class); + if (o instanceof ClassLoader) { + contribution.setClassLoader((ClassLoader)o); + } + } + + compositeContext = new CompositeContext(extensionPointRegistry, + domainRegistry, + builtComposite, + null, // nothing appears to use the domain name in CompositeContext + null, // don't need node uri + deployer.getSystemDefinitions()); + usedContributionURIs = new ArrayList<String>(); + usedContributionURIs.add(contribution.getURI()); + for (Contribution dc : dependedOnContributions) { + usedContributionURIs.add(dc.getURI()); + } + } + + public void start() throws ActivationException { + try { + compositeActivator.activate(compositeContext, builtComposite); + compositeActivator.start(compositeContext, builtComposite); + domainRegistry.addRunningComposite(contribution.getURI(), builtComposite); + } catch (ActivationException ex){ + stop(); + throw ex; + } catch (Exception ex){ + stop(); + throw new ActivationException(ex); + } + } + + public void stop() throws ActivationException { + domainRegistry.removeRunningComposite(contribution.getURI(), builtComposite.getURI()); + compositeActivator.stop(compositeContext, builtComposite); + compositeActivator.deactivate(builtComposite); + } + + public String getURI() { + return composite.getURI(); + } + + public List<String> getContributionURIs() { + return usedContributionURIs; + } + + public boolean uses(String contributionURI, String compositeURI) { + // TODO: builtComposite or composite? + return compositeUses(builtComposite, contributionURI, compositeURI); + } + + protected boolean compositeUses(Composite c, String contributionURI, String compositeURI) { + if (contributionURI.equals(c.getContributionURI()) && compositeURI.equals(c.getURI())) { + return true; + } + for (Composite include : ((CompositeImpl)c).getFusedIncludes()) { + if (compositeUses(include, contributionURI, compositeURI)) { + return true; + } + } + for (Component comp : c.getComponents()) { + if (comp.getImplementation() instanceof Composite) { + if (compositeUses((Composite)comp.getImplementation(), contributionURI, compositeURI)) { + return true; + } + } + } + return false; + } +} diff --git a/sca-java-2.x/tags/2.0.1/modules/domain-node/src/main/java/org/apache/tuscany/sca/impl/NodeImpl.java b/sca-java-2.x/tags/2.0.1/modules/domain-node/src/main/java/org/apache/tuscany/sca/impl/NodeImpl.java new file mode 100644 index 0000000000..52a6c7ede5 --- /dev/null +++ b/sca-java-2.x/tags/2.0.1/modules/domain-node/src/main/java/org/apache/tuscany/sca/impl/NodeImpl.java @@ -0,0 +1,656 @@ +/* + * 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.impl; + +import java.io.Reader; +import java.io.StringReader; +import java.net.URLClassLoader; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.Iterator; +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.Node; +import org.apache.tuscany.sca.TuscanyRuntime; +import org.apache.tuscany.sca.assembly.Composite; +import org.apache.tuscany.sca.assembly.xml.Utils; +import org.apache.tuscany.sca.common.java.io.IOHelper; +import org.apache.tuscany.sca.common.xml.dom.DOMHelper; +import org.apache.tuscany.sca.contribution.Contribution; +import org.apache.tuscany.sca.contribution.ContributionMetadata; +import org.apache.tuscany.sca.contribution.Import; +import org.apache.tuscany.sca.contribution.java.JavaImport; +import org.apache.tuscany.sca.contribution.namespace.NamespaceImport; +import org.apache.tuscany.sca.contribution.processor.ContributionReadException; +import org.apache.tuscany.sca.contribution.resolver.ClassReference; +import org.apache.tuscany.sca.contribution.resolver.ExtensibleModelResolver; +import org.apache.tuscany.sca.contribution.resolver.ModelResolver; +import org.apache.tuscany.sca.core.ExtensionPointRegistry; +import org.apache.tuscany.sca.core.UtilityExtensionPoint; +import org.apache.tuscany.sca.deployment.Deployer; +import org.apache.tuscany.sca.monitor.Monitor; +import org.apache.tuscany.sca.monitor.ValidationException; +import org.apache.tuscany.sca.runtime.ActivationException; +import org.apache.tuscany.sca.runtime.ActiveNodes; +import org.apache.tuscany.sca.runtime.CompositeActivator; +import org.apache.tuscany.sca.runtime.ContributionDescription; +import org.apache.tuscany.sca.runtime.ContributionListener; +import org.apache.tuscany.sca.runtime.DomainRegistry; +import org.apache.tuscany.sca.runtime.RuntimeProperties; +import org.oasisopen.sca.NoSuchServiceException; + +import sun.misc.ClassLoaderUtil; + +public class NodeImpl implements Node { + private static final Logger logger = Logger.getLogger(NodeImpl.class.getName()); + + private Deployer deployer; + private CompositeActivator compositeActivator; + private DomainRegistry domainRegistry; + private ExtensionPointRegistry extensionPointRegistry; + private UtilityExtensionPoint utilityExtensionPoint; + private TuscanyRuntime tuscanyRuntime; + + private Map<String, Contribution> loadedContributions = new ConcurrentHashMap<String, Contribution>(); + + private Map<String, DeployedComposite> startedComposites = new HashMap<String, DeployedComposite>(); + private Map<String, DeployedComposite> stoppedComposites = new HashMap<String, DeployedComposite>(); + + private boolean endpointsIncludeDomainName; + private boolean quietLogging; + + private boolean releaseOnUnload; + + private ContributionListener contributionListener; + + public NodeImpl(Deployer deployer, + CompositeActivator compositeActivator, + DomainRegistry domainRegistry, + ExtensionPointRegistry extensionPointRegistry, + TuscanyRuntime tuscanyRuntime) { + this.deployer = deployer; + this.compositeActivator = compositeActivator; + this.domainRegistry = domainRegistry; + this.extensionPointRegistry = extensionPointRegistry; + this.tuscanyRuntime = tuscanyRuntime; + + utilityExtensionPoint = extensionPointRegistry.getExtensionPoint(UtilityExtensionPoint.class); + + utilityExtensionPoint.getUtility(ActiveNodes.class).getActiveNodes().add(this); + + contributionListener = new ContributionListener() { + public void contributionInstalled(String uri) { + // Do nothing + } + public void contributionUpdated(String uri) { + unloadContribution(uri); + } + public void contributionRemoved(String uri) { + unloadContribution(uri); + } + private void unloadContribution(String curi) { + Contribution c = loadedContributions.remove(curi); + if (c != null) { + ClassLoader cl = c.getClassLoader(); + ContributionHelper.close(c, NodeImpl.this.extensionPointRegistry); + if (releaseOnUnload) { + if (cl instanceof URLClassLoader) { + ClassLoaderUtil.releaseLoader((URLClassLoader)cl); + } + } + } + } + }; + + this.domainRegistry.addContributionListener(contributionListener); + + endpointsIncludeDomainName = !TuscanyRuntime.DEFAUL_DOMAIN_NAME.equals(domainRegistry.getDomainName()); + + UtilityExtensionPoint utilities = extensionPointRegistry.getExtensionPoint(UtilityExtensionPoint.class); + this.releaseOnUnload = Boolean.parseBoolean(utilities.getUtility(RuntimeProperties.class).getProperties().getProperty(RuntimeProperties.RELEASE_ON_UNLOAD, "true")); + + this.quietLogging = Boolean.parseBoolean(utilities.getUtility(RuntimeProperties.class).getProperties().getProperty(RuntimeProperties.QUIET_LOGGING)); + if (logger.isLoggable(quietLogging? Level.FINE : Level.INFO)) logger.log(quietLogging? Level.FINE : Level.INFO, "domain: " + domainRegistry.getDomainName() + (!domainRegistry.getDomainName().equals(domainRegistry.getDomainURI()) ? "" : (" domainURI: " + domainRegistry.getDomainURI()))); + } + + // TODO: install shouldn't throw ValidationException as it shouldn't do any validation, its + // only here from the loadContribution in mergeContributionMetaData so change that approach + + public String installContribution(String contributionURL) throws ContributionReadException, ValidationException { + return installContribution(null, contributionURL, null, null); + } + + public String installContribution(String uri, String contributionURL) throws ContributionReadException, ValidationException { if (logger.isLoggable(Level.FINE)) logger.log(Level.FINE, "updateUsingComposites", contributionURL); + return installContribution(uri, contributionURL, null, null); + } + + public boolean updateContribution(String uri, String contributionURL, String metaDataURL, List<String> dependentContributionURIs) throws ContributionReadException, ValidationException, ActivationException { + if (logger.isLoggable(Level.FINE)) { + logger.log(Level.FINE, "updateContribution" + Arrays.asList(new Object[]{uri, contributionURL, metaDataURL, dependentContributionURIs})); + } + ContributionDescription ic = domainRegistry.getInstalledContribution(uri); + if (ic == null) { + installContribution(uri, contributionURL, metaDataURL, dependentContributionURIs); + return true; + } + + // do this if only updating if the contribution has been modified: + // if url equal and a file and last modified not changed + // if metadata url equal and a file and laqst modified not changed + // if (dependent contributions uris not changed) + // return false + + uninstallContribution(uri); + + installContribution(uri, contributionURL, metaDataURL, dependentContributionURIs); + + // merge in additional deployables + if (ic.getAdditionalDeployables().size() > 0) { + ContributionDescription newIC = getInstalledContribution(uri); + newIC.getAdditionalDeployables().putAll(ic.getAdditionalDeployables()); + domainRegistry.updateInstalledContribution(newIC); + } + + // stop/start all started composites using the contribution + for (DeployedComposite dc : new ArrayList<DeployedComposite>(startedComposites.values())) { + if (dc.getContributionURIs().contains(uri)) { + String dcContributionURI = dc.getContributionURIs().get(0); + String dcCompositeURI = dc.getURI(); + stopComposite(dcContributionURI, dcCompositeURI); + String key = dcContributionURI + "/" + dcCompositeURI; + stoppedComposites.remove(key); + startComposite(dcContributionURI, dcCompositeURI); + } + } + + // remove all stopped composites using the contribution + for (DeployedComposite dc : new ArrayList<DeployedComposite>(stoppedComposites.values())) { + if (dc.getContributionURIs().contains(uri)) { + stoppedComposites.remove(uri + "/" + dc.getURI()); + } + } + + if (logger.isLoggable(quietLogging? Level.FINE : Level.INFO)) logger.log(quietLogging? Level.FINE : Level.INFO, "updateContribution: " + uri); + return true; + } + + public String installContribution(String uri, String contributionURL, String metaDataURL, List<String> dependentContributionURIs) throws ContributionReadException, ValidationException { + if (logger.isLoggable(Level.FINE)) { + logger.log(Level.FINE, "installContribution" + Arrays.asList(new Object[]{uri, contributionURL, metaDataURL, dependentContributionURIs})); + } + ContributionDescription cd = new ContributionDescription(uri, IOHelper.getLocationAsURL(contributionURL).toString()); + + if (dependentContributionURIs != null) { + cd.getDependentContributionURIs().addAll(dependentContributionURIs); + } + + if (metaDataURL != null) { + mergeContributionMetaData(metaDataURL, loadContribution(cd)); + } + + peekIntoContribution(cd); + + domainRegistry.installContribution(cd); + + if (logger.isLoggable(quietLogging? Level.FINE : Level.INFO)) logger.log(quietLogging? Level.FINE : Level.INFO, "installContribution: " + cd.getURI()); + return cd.getURI(); + } + + public void installContribution(Contribution contribution, List<String> dependentContributionURIs) { + if (logger.isLoggable(Level.FINE)) { + logger.log(Level.FINE, "installContribution" + Arrays.asList(new Object[]{contribution, dependentContributionURIs})); + } + ContributionDescription cd = new ContributionDescription(contribution.getURI(), contribution.getLocation()); + if (dependentContributionURIs != null) { + cd.getDependentContributionURIs().addAll(dependentContributionURIs); + } + cd.configureMetaData(contribution); + domainRegistry.installContribution(cd); + loadedContributions.put(cd.getURI(), contribution); + if (logger.isLoggable(quietLogging? Level.FINE : Level.INFO)) logger.log(quietLogging? Level.FINE : Level.INFO, "installContribution: " + cd.getURI()); + } + + public void uninstallContribution(String contributionURI) { + + // note that the contribution listener that this class registers will free up the contribution's resources + + domainRegistry.uninstallContribution(contributionURI); + + // remove any stopped composite that used the contribution + Iterator<String> i = stoppedComposites.keySet().iterator(); + while (i.hasNext()) { + DeployedComposite dc = stoppedComposites.get(i.next()); + if (dc.getContributionURIs().contains(contributionURI)) { + i.remove(); + } + } + + if (loadedContributions.size() < 1) { + DOMHelper.getInstance(extensionPointRegistry).stop(); + java.beans.Introspector.flushCaches(); + } + + if (logger.isLoggable(quietLogging? Level.FINE : Level.INFO)) logger.log(quietLogging? Level.FINE : Level.INFO, "uninstallContribution: " + contributionURI); + } + + protected void mergeContributionMetaData(String metaDataURL, Contribution contribution) throws ValidationException { + ContributionMetadata metaData; + Monitor monitor = deployer.createMonitor(); + try { + metaData = deployer.loadXMLDocument(IOHelper.getLocationAsURL(metaDataURL), monitor); + } catch (Exception e) { + throw new ValidationException(e); + } + monitor.analyzeProblems(); + contribution.mergeMetaData(metaData); + } + + /** + * Peek into the contribution to find its attributes. + * ASM12032 and ASM12033 say no error checking should be done during install and that should happen later, but + * we need to know about deployables and exports so peek into the contribution to try to get those, + * and just ignore any errors they might happen while doing that. + */ + protected void peekIntoContribution(ContributionDescription cd) { + Contribution contribution = null; + try { + contribution = loadContribution(cd); + } catch (Exception e) { + // ignore it + } + + if (contribution != null) { + cd.configureMetaData(contribution); + } + } + + public List<String> getInstalledContributionURIs() { + return new ArrayList<String>(domainRegistry.getInstalledContributionURIs()); + } + + public Contribution getContribution(String contributionURI) throws ContributionReadException, ValidationException { + return loadContribution(getInstalledContribution(contributionURI)); + } + + public List<String> getDeployableCompositeURIs(String contributionURI) { + ContributionDescription cd = domainRegistry.getInstalledContribution(contributionURI); + List<String> deployables = new ArrayList<String>(cd.getDeployables()); + deployables.addAll(cd.getAdditionalDeployables().keySet()); + return deployables; + } + + public String addDeploymentComposite(String contributionURI, Reader compositeXML) throws ContributionReadException, XMLStreamException, ValidationException { + ContributionDescription cd = getInstalledContribution(contributionURI); + + // load it to check its valid composite XML + Composite composite = deployer.loadXMLDocument(compositeXML); + + return addDeploymentComposite(cd, composite); + } + + public String addDeploymentComposite(String contributionURI, Composite composite) { + ContributionDescription cd = getInstalledContribution(contributionURI); + return addDeploymentComposite(cd, composite); + } + + protected String addDeploymentComposite(ContributionDescription cd, Composite composite) { + if (logger.isLoggable(Level.FINE)) { + logger.log(Level.FINE, "addDeploymentComposite" + Arrays.asList(new Object[]{cd, composite})); + } + if (composite.getURI() == null || composite.getURI().length() < 1) { + composite.setURI(composite.getName().getLocalPart() + ".composite"); + } + composite.setContributionURI(cd.getURI()); + cd.getAdditionalDeployables().put(composite.getURI(), Utils.modelToXML(composite, false, extensionPointRegistry)); + domainRegistry.updateInstalledContribution(cd); + if (logger.isLoggable(quietLogging? Level.FINE : Level.INFO)) logger.log(quietLogging? Level.FINE : Level.INFO, "addDeploymentComposite: " + composite.getURI()); + return composite.getURI(); + } + + public void validateContribution(String contributionURI) throws ContributionReadException, ValidationException { + ContributionDescription cd = getInstalledContribution(contributionURI); + Contribution contribution = loadContribution(cd); + + Monitor monitor = deployer.createMonitor(); + try { + ArrayList<Contribution> cs = new ArrayList<Contribution>(); + cs.add(contribution); + cs.addAll(calculateDependentContributions(cd)); + deployer.resolve(cs, null, monitor); + } catch (Exception e) { + loadedContributions.remove(cd.getURI()); + throw new RuntimeException(e); + } + try { + monitor.analyzeProblems(); + } catch (ValidationException e) { + loadedContributions.remove(cd.getURI()); + throw e; + } + if (contribution.getClassLoader() == null && contribution.getModelResolver() instanceof ExtensibleModelResolver) { + ModelResolver o = ((ExtensibleModelResolver)contribution.getModelResolver()).getModelResolverInstance(ClassReference.class); + if (o instanceof ClassLoader) { + contribution.setClassLoader((ClassLoader)o); + } + } + } + + public Map<String, List<String>> getStartedCompositeURIs() { + return Collections.unmodifiableMap(domainRegistry.getRunningCompositeURIs()); + } + + public void startComposite(String contributionURI, String compositeURI) throws ActivationException, ValidationException, ContributionReadException { + String key = contributionURI+"/"+compositeURI; + if (startedComposites.containsKey(key)) { + throw new IllegalStateException("composite already started: " + compositeURI); + } + DeployedComposite dc = stoppedComposites.remove(key); + try { + if (dc != null) { + dc.start(); + startedComposites.put(key, dc); + } else { + ContributionDescription cd = getInstalledContribution(contributionURI); + Contribution contribution = loadContribution(cd); + Composite composite = contribution.getArtifactModel(compositeURI); + List<Contribution> dependentContributions = calculateDependentContributions(cd); + dc = new DeployedComposite(composite, contribution, dependentContributions, deployer, compositeActivator, domainRegistry, extensionPointRegistry, endpointsIncludeDomainName); + dc.start(); + startedComposites.put(key, dc); + } + }catch(ActivationException e){ + if(dc != null){ + try { + // try to stop the composite. This should have already happened + // in the activator if the composite failed to start but we're + // being sure + dc.stop(); + } catch (Exception ex) { + // do nothing as we are going to throw the + // original exception + } + stoppedComposites.put(key, dc); + } + throw e; + } + if (logger.isLoggable(quietLogging? Level.FINE : Level.INFO)) logger.log(quietLogging? Level.FINE : Level.INFO, "startComposite: " + key); + } + + @Override + public void startComposite(String contributionURI, String compositeURI, String nodeName) throws ActivationException { + String response = domainRegistry.remoteCommand(nodeName, new RemoteCommand(domainRegistry.getDomainName(), "start", contributionURI, compositeURI)); + if (!"Started.".equals(response)) { + throw new ActivationException(response); + } + if (logger.isLoggable(quietLogging? Level.FINE : Level.INFO)) logger.log(quietLogging? Level.FINE : Level.INFO, "startComposite: " + contributionURI + " " + compositeURI + " " + nodeName); + } + + public void stopComposite(String contributionURI, String compositeURI) throws ActivationException { + String key = contributionURI+"/"+compositeURI; + DeployedComposite dc = startedComposites.remove(key); + if (dc != null) { + dc.stop(); + stoppedComposites.put(key, dc); + } else { + String member = domainRegistry.getRunningNodeName(contributionURI, compositeURI); + if (member == null) { + throw new IllegalStateException("composite not started: " + compositeURI); + } + RemoteCommand command = new RemoteCommand(domainRegistry.getDomainName(), "stop", contributionURI, compositeURI); + String response = domainRegistry.remoteCommand(member, command); + if (!"Stopped.".equals(response)) { + throw new ActivationException(response); + } + } + if (logger.isLoggable(quietLogging? Level.FINE : Level.INFO)) logger.log(quietLogging? Level.FINE : Level.INFO, "stopComposite: " + key); + } + + public void stopCompositeAndUninstallUnused(String contributionURI, String compositeURI) throws ActivationException { + String key = contributionURI+"/"+compositeURI; + DeployedComposite dc = startedComposites.remove(key); + if (dc != null) { + dc.stop(); + } else { + // check in the stopped list in case it stopped on failure during start + dc = stoppedComposites.get(key); + } + + if (dc != null) { + loop: for (String curi : dc.getContributionURIs()) { + for (DeployedComposite started : startedComposites.values()) { + if (started.getContributionURIs().contains(curi)) { + continue loop; + } + } + uninstallContribution(curi); + } + } + if (logger.isLoggable(quietLogging? Level.FINE : Level.INFO)) logger.log(quietLogging? Level.FINE : Level.INFO, "stopCompositeAndUninstallUnused: " + key); + } + + public String getDomainURI() { + return domainRegistry.getDomainURI(); + } + + public String getDomainName() { + return domainRegistry.getDomainName(); + } + + public Composite getDomainComposite() { + return domainRegistry.getDomainComposite(); + } + + public <T> T getService(Class<T> interfaze, String serviceURI) throws NoSuchServiceException { + return ServiceHelper.getService(interfaze, serviceURI, domainRegistry, extensionPointRegistry, deployer); + } + + public ContributionDescription getInstalledContribution(String contributionURI) { + ContributionDescription cd = domainRegistry.getInstalledContribution(contributionURI); + if (cd == null) { + throw new IllegalArgumentException("Contribution not installed: " + contributionURI); + } + return cd; + } + + protected Contribution loadContribution(ContributionDescription cd) throws ContributionReadException, ValidationException { + Contribution contribution = loadedContributions.get(cd.getURI()); + if (contribution == null) { + Monitor monitor = deployer.createMonitor(); + contribution = deployer.loadContribution(IOHelper.createURI(cd.getURI()), IOHelper.getLocationAsURL(cd.getURL()), monitor); + + // TODO: should the monitor be checked? If it is then the peek in to get the metadata doesn't work if there's a problem + // monitor.analyzeProblems(); + if (cd.getAdditionalDeployables().size() > 0) { + for (String uri : cd.getAdditionalDeployables().keySet()) { + String compositeXML = cd.getAdditionalDeployables().get(uri); + Composite composite; + try { + composite = deployer.loadXMLDocument(new StringReader(compositeXML)); + } catch (XMLStreamException e) { + throw new ContributionReadException(e); + } + composite.setURI(composite.getName().getLocalPart() + ".composite"); + contribution.addComposite(composite); + } + } + loadedContributions.put(cd.getURI(), contribution); + } + return contribution; + } + + protected List<Contribution> calculateDependentContributions(ContributionDescription cd) throws ContributionReadException, ValidationException { + Map<String, Contribution> dependentContributions = new HashMap<String, Contribution>(); + if (cd.getDependentContributionURIs() != null && cd.getDependentContributionURIs().size() > 0) { + // if the install specified dependent uris use just those contributions + for (String uri : cd.getDependentContributionURIs()) { + if (!!!dependentContributions.containsKey(uri)) { + ContributionDescription dependee = domainRegistry.getInstalledContribution(uri); + if (dependee != null) { + dependentContributions.put(uri, loadContribution(dependee)); + } + } + } + } else { + for (Import imprt : loadContribution(cd).getImports()) { + for (ContributionDescription exportingIC : findExportingContributions(imprt)) { + if (!!!dependentContributions.containsKey(exportingIC.getURI()) && !!!cd.getURI().equals(exportingIC.getURI())) { + dependentContributions.put(exportingIC.getURI(), loadContribution(exportingIC)); + } + } + } + } + // TODO: there is also the location attribute on the import which should be taken into account + return new ArrayList<Contribution>(dependentContributions.values()); + } + + private List<ContributionDescription> findExportingContributions(Import imprt) { + List<ContributionDescription> ics = new ArrayList<ContributionDescription>(); + // TODO: Handle Imports in a more extensible way + for (String curi : domainRegistry.getInstalledContributionURIs()) { + ContributionDescription cd = domainRegistry.getInstalledContribution(curi); + if (imprt instanceof JavaImport) { + for (String s : cd.getJavaExports()) { + if (s.startsWith(((JavaImport)imprt).getPackage())) { + ics.add(cd); + } + } + } else if (imprt instanceof NamespaceImport) { + if (cd.getNamespaceExports().contains(((NamespaceImport)imprt).getNamespace())) { + ics.add(cd); + } + } + } + return ics; + } + + @Override + public Object getQNameDefinition(String contributionURI, QName definition, QName symbolSpace) { + // TODO Auto-generated method stub + return null; + } + + @Override + public List<String> startDeployables(String contributionURI) throws ActivationException, ValidationException, ContributionReadException { + List<String> dcURIs = getDeployableCompositeURIs(contributionURI); + for (String dcURI : dcURIs) { + startComposite(contributionURI, dcURI); + } + return dcURIs; + } + + // TODO: these are used by the shell, should they be on the Node interface? + public DomainRegistry getEndpointRegistry() { + return domainRegistry; + } + public ExtensionPointRegistry getExtensionPointRegistry() { + return extensionPointRegistry; + } + + public void stop() { + for (DeployedComposite dc : startedComposites.values()) { + try { + dc.stop(); + } catch (ActivationException e) { + } + } + startedComposites.clear(); + stoppedComposites.clear(); + extensionPointRegistry.getExtensionPoint(UtilityExtensionPoint.class).getUtility(ActiveNodes.class).getActiveNodes().remove(this); + domainRegistry.removeContributionListener(contributionListener); + if (tuscanyRuntime != null) { + tuscanyRuntime.stop(); + } + } + + @Override + public List<String> getNodeNames() { + return domainRegistry.getNodeNames(); + } + + @Override + public String getLocalNodeName() { + return domainRegistry.getLocalNodeName(); + } + + @Override + public String getRunningNodeName(String contributionURI, String compositeURI) { + return domainRegistry.getRunningNodeName(contributionURI, compositeURI); + } + + public List<String> updateUsingComposites(String contributionURI, String compositeURI) throws ActivationException, ContributionReadException, ValidationException { + List<String> updated = new ArrayList<String>(); + for (DeployedComposite dc : new ArrayList<DeployedComposite>(startedComposites.values())) { + if (dc.uses(contributionURI, compositeURI)) { + String dcContributionURI = dc.getContributionURIs().get(0); + String dcCompositeURI = dc.getURI(); + stopComposite(dcContributionURI, dcCompositeURI); + String key = dcContributionURI + "/" + dcCompositeURI; + stoppedComposites.remove(key); + updated.add(key); + startComposite(dcContributionURI, dcCompositeURI); + } + } + if (logger.isLoggable(quietLogging? Level.FINE : Level.INFO)) logger.log(quietLogging? Level.FINE : Level.INFO, "updateUsingComposites", updated); + return updated; + } + + public void uninstallContribution(String contributionURI, boolean b) throws ActivationException { + uninstallContribution(contributionURI); + if (!b) { + return; + } + + // stop all started composites using the contribution + for (DeployedComposite dc : new ArrayList<DeployedComposite>(startedComposites.values())) { + if (dc.getContributionURIs().contains(contributionURI)) { + String dcContributionURI = dc.getContributionURIs().get(0); + String dcCompositeURI = dc.getURI(); + stopComposite(dcContributionURI, dcCompositeURI); + String key = dcContributionURI + "/" + dcCompositeURI; + stoppedComposites.remove(key); + } + } + + // remove all stopped composites using the contribution + for (DeployedComposite dc : new ArrayList<DeployedComposite>(stoppedComposites.values())) { + if (dc.getContributionURIs().contains(contributionURI)) { + stoppedComposites.remove(contributionURI + "/" + dc.getURI()); + } + } + } + + public boolean getEndpointsIncludeDomainName() { + return endpointsIncludeDomainName; + } + + public void setEndpointsIncludeDomainName(boolean b) { + endpointsIncludeDomainName = b; + } + +} diff --git a/sca-java-2.x/tags/2.0.1/modules/domain-node/src/main/java/org/apache/tuscany/sca/impl/RemoteCommand.java b/sca-java-2.x/tags/2.0.1/modules/domain-node/src/main/java/org/apache/tuscany/sca/impl/RemoteCommand.java new file mode 100644 index 0000000000..5e150dba02 --- /dev/null +++ b/sca-java-2.x/tags/2.0.1/modules/domain-node/src/main/java/org/apache/tuscany/sca/impl/RemoteCommand.java @@ -0,0 +1,83 @@ +/*
+ * 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.impl;
+
+import java.io.Serializable;
+import java.util.concurrent.Callable;
+
+import org.apache.tuscany.sca.Node;
+import org.apache.tuscany.sca.core.ExtensionPointRegistry;
+import org.apache.tuscany.sca.core.ExtensionPointRegistryLocator;
+import org.apache.tuscany.sca.core.UtilityExtensionPoint;
+import org.apache.tuscany.sca.runtime.ActiveNodes;
+
+public class RemoteCommand implements Callable<String>, Serializable {
+ private static final long serialVersionUID = 1L;
+
+ // all fields MUST be Serializable
+ private String domainName;
+ private String command;
+ private String contributionURI;
+ private String compositeURI;
+
+ public RemoteCommand(String domainName, String command, String contributionURI, String compositeURI) {
+ this.domainName = domainName;
+ this.command = command;
+ this.contributionURI = contributionURI;
+ this.compositeURI = compositeURI;
+ }
+
+ public String call() throws Exception {
+ String response;
+ try {
+ Node node = getNode();
+
+ if ("start".equals(command)) {
+ node.startComposite(contributionURI, compositeURI);
+ response = "Started.";
+ } else if ("stop".equals(command)) {
+ node.stopComposite(contributionURI, compositeURI);
+ response = "Stopped.";
+ } else {
+ response = "Unknown command: " + command;
+ }
+ } catch (Exception e) {
+ response = "REMOTE EXCEPTION: " + e.getClass() + ":" + e.getMessage();
+ }
+ return response;
+ }
+
+ private Node getNode() {
+ // TODO Several places in Tuscany need to do this type of thing, for example, processing
+ // async responses, so we need to design a "proper" way to do it
+
+ for (ExtensionPointRegistry xpr : ExtensionPointRegistryLocator.getExtensionPointRegistries()) {
+ ActiveNodes activeNodes = xpr.getExtensionPoint(UtilityExtensionPoint.class).getUtility(ActiveNodes.class);
+ for (Object o : activeNodes.getActiveNodes()) {
+ Node node = (Node)o;
+ if (node.getDomainName().equals(domainName)) {
+ return node;
+ }
+ }
+ }
+ throw new IllegalStateException("No remote Node found for domain: " + domainName);
+ }
+
+}
diff --git a/sca-java-2.x/tags/2.0.1/modules/domain-node/src/main/java/org/apache/tuscany/sca/impl/ServiceHelper.java b/sca-java-2.x/tags/2.0.1/modules/domain-node/src/main/java/org/apache/tuscany/sca/impl/ServiceHelper.java new file mode 100644 index 0000000000..3ada1bbbb1 --- /dev/null +++ b/sca-java-2.x/tags/2.0.1/modules/domain-node/src/main/java/org/apache/tuscany/sca/impl/ServiceHelper.java @@ -0,0 +1,211 @@ +/*
+ * 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.impl;
+
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.net.URLClassLoader;
+import java.util.List;
+
+import org.apache.tuscany.sca.assembly.AssemblyFactory;
+import org.apache.tuscany.sca.assembly.Component;
+import org.apache.tuscany.sca.assembly.ComponentReference;
+import org.apache.tuscany.sca.assembly.ComponentService;
+import org.apache.tuscany.sca.assembly.Endpoint;
+import org.apache.tuscany.sca.assembly.EndpointReference;
+import org.apache.tuscany.sca.assembly.Multiplicity;
+import org.apache.tuscany.sca.assembly.Service;
+import org.apache.tuscany.sca.context.CompositeContext;
+import org.apache.tuscany.sca.core.ExtensionPointRegistry;
+import org.apache.tuscany.sca.core.FactoryExtensionPoint;
+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.deployment.Deployer;
+import org.apache.tuscany.sca.interfacedef.Interface;
+import org.apache.tuscany.sca.interfacedef.InterfaceContract;
+import org.apache.tuscany.sca.interfacedef.InvalidInterfaceException;
+import org.apache.tuscany.sca.interfacedef.java.JavaInterface;
+import org.apache.tuscany.sca.interfacedef.java.JavaInterfaceFactory;
+import org.apache.tuscany.sca.runtime.ContributionDescription;
+import org.apache.tuscany.sca.runtime.DomainRegistry;
+import org.apache.tuscany.sca.runtime.RuntimeComponent;
+import org.apache.tuscany.sca.runtime.RuntimeComponentReference;
+import org.apache.tuscany.sca.runtime.RuntimeEndpointReference;
+import org.oasisopen.sca.NoSuchServiceException;
+import org.oasisopen.sca.ServiceRuntimeException;
+import org.oasisopen.sca.annotation.Remotable;
+
+/**
+ * TODO: Merge this into sca-client RemoteServiceInvocationHandler
+ *
+ * All the code for creating a service proxy in this helper class as it feels like
+ * it doesn't all belong in the node but i can't see where to refactor it to yet.
+ * (perhaps its just the remote proxy bit that needs to go somewhere else?)
+ */
+public class ServiceHelper {
+
+ public static <T> T getService(Class<T> interfaze, String serviceURI, DomainRegistry domainRegistry, ExtensionPointRegistry extensionPointRegistry, Deployer deployer) throws NoSuchServiceException {
+
+ List<Endpoint> endpoints = domainRegistry.findEndpoint(serviceURI);
+ if (endpoints.size() < 1) {
+ throw new NoSuchServiceException(serviceURI);
+ }
+
+ String serviceName = null;
+ if (serviceURI.contains("/")) {
+ int i = serviceURI.indexOf("/");
+ if (i < serviceURI.length() - 1) {
+ serviceName = serviceURI.substring(i + 1);
+ }
+ }
+
+ Endpoint ep = endpoints.get(0);
+ if (((RuntimeComponent)ep.getComponent()).getComponentContext() != null) {
+ return ((RuntimeComponent)ep.getComponent()).getServiceReference(interfaze, serviceName).getService();
+ } else {
+ return getRemoteProxy(interfaze, ep, domainRegistry, extensionPointRegistry, deployer);
+ }
+ }
+
+ private static <T> T getRemoteProxy(Class<T> serviceInterface, Endpoint endpoint, DomainRegistry domainRegistry, ExtensionPointRegistry extensionPointRegistry, Deployer deployer) throws NoSuchServiceException {
+ FactoryExtensionPoint factories = extensionPointRegistry.getExtensionPoint(FactoryExtensionPoint.class);
+ AssemblyFactory assemblyFactory = factories.getFactory(AssemblyFactory.class);
+ JavaInterfaceFactory javaInterfaceFactory = factories.getFactory(JavaInterfaceFactory.class);
+ ProxyFactory proxyFactory =
+ new ExtensibleProxyFactory(extensionPointRegistry.getExtensionPoint(ProxyFactoryExtensionPoint.class));
+
+ CompositeContext compositeContext =
+ new CompositeContext(extensionPointRegistry, domainRegistry, null, null, null,
+ deployer.getSystemDefinitions());
+
+ if (serviceInterface == null) {
+ try {
+ serviceInterface = (Class<T>)findInterface(endpoint, domainRegistry);
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ RuntimeEndpointReference epr;
+ try {
+ epr =
+ createEndpointReference(javaInterfaceFactory,
+ compositeContext,
+ assemblyFactory,
+ endpoint,
+ serviceInterface);
+ } catch (Exception e) {
+ throw new ServiceRuntimeException(e);
+ }
+
+ return proxyFactory.createProxy(serviceInterface, epr);
+ }
+
+ private static RuntimeEndpointReference createEndpointReference(JavaInterfaceFactory javaInterfaceFactory,
+ CompositeContext compositeContext,
+ AssemblyFactory assemblyFactory,
+ Endpoint endpoint,
+ Class<?> businessInterface)
+ throws CloneNotSupportedException, InvalidInterfaceException {
+ Component component = endpoint.getComponent();
+ ComponentService service = endpoint.getService();
+ ComponentReference componentReference = assemblyFactory.createComponentReference();
+ componentReference.setName("sca.client." + service.getName());
+
+ componentReference.setCallback(service.getCallback());
+ componentReference.getTargets().add(service);
+ componentReference.getPolicySets().addAll(service.getPolicySets());
+ componentReference.getRequiredIntents().addAll(service.getRequiredIntents());
+ componentReference.getBindings().add(endpoint.getBinding());
+
+ InterfaceContract interfaceContract = service.getInterfaceContract();
+ Service componentTypeService = service.getService();
+ if (componentTypeService != null && componentTypeService.getInterfaceContract() != null) {
+ interfaceContract = componentTypeService.getInterfaceContract();
+ }
+ interfaceContract = getInterfaceContract(javaInterfaceFactory, interfaceContract, businessInterface);
+ componentReference.setInterfaceContract(interfaceContract);
+ componentReference.setMultiplicity(Multiplicity.ONE_ONE);
+ // component.getReferences().add(componentReference);
+
+ // create endpoint reference
+ EndpointReference endpointReference = assemblyFactory.createEndpointReference();
+ endpointReference.setComponent(component);
+ endpointReference.setReference(componentReference);
+ endpointReference.setBinding(endpoint.getBinding());
+ endpointReference.setUnresolved(false);
+ endpointReference.setStatus(EndpointReference.Status.WIRED_TARGET_FOUND_AND_MATCHED);
+
+ endpointReference.setTargetEndpoint(endpoint);
+
+ componentReference.getEndpointReferences().add(endpointReference);
+ ((RuntimeComponentReference)componentReference).setComponent((RuntimeComponent)component);
+ ((RuntimeEndpointReference)endpointReference).bind(compositeContext);
+
+ return (RuntimeEndpointReference)endpointReference;
+ }
+
+ private static InterfaceContract getInterfaceContract(JavaInterfaceFactory javaInterfaceFactory,
+ InterfaceContract interfaceContract,
+ Class<?> businessInterface) throws CloneNotSupportedException,
+ InvalidInterfaceException {
+ if (businessInterface == null) {
+ return interfaceContract;
+ }
+ boolean compatible = false;
+ if (interfaceContract != null && interfaceContract.getInterface() != null) {
+ Interface interfaze = interfaceContract.getInterface();
+ if (interfaze instanceof JavaInterface) {
+ Class<?> cls = ((JavaInterface)interfaze).getJavaClass();
+ if (cls != null && businessInterface.isAssignableFrom(cls)) {
+ compatible = true;
+ }
+ }
+ }
+
+ if (!compatible) {
+ // The interface is not assignable from the interface contract
+ interfaceContract = javaInterfaceFactory.createJavaInterfaceContract();
+ JavaInterface callInterface = javaInterfaceFactory.createJavaInterface(businessInterface);
+ callInterface.setRemotable(true);
+ interfaceContract.setInterface(callInterface);
+ if (callInterface.getCallbackClass() != null) {
+ interfaceContract.setCallbackInterface(javaInterfaceFactory.createJavaInterface(callInterface
+ .getCallbackClass()));
+ }
+ }
+
+ return interfaceContract;
+ }
+
+ private static Class<?> findInterface(Endpoint endpoint, DomainRegistry domainRegistry) throws MalformedURLException, ClassNotFoundException {
+ Interface iface = endpoint.getService().getInterfaceContract().getInterface();
+ if (iface instanceof JavaInterface) {
+ String curi = domainRegistry.getContainingCompositesContributionURI(endpoint.getComponent().getName());
+ if (curi != null) {
+ ContributionDescription ic = domainRegistry.getInstalledContribution(curi);
+ ClassLoader cl = new URLClassLoader(new URL[]{new URL(ic.getURL())}, Remotable.class.getClassLoader());
+ return cl.loadClass(((JavaInterface)iface).getName());
+ }
+ }
+ return null;
+ }
+}
diff --git a/sca-java-2.x/tags/2.0.1/modules/domain-node/src/main/java/org/apache/tuscany/sca/impl/hotupdate/HotUpdater.java b/sca-java-2.x/tags/2.0.1/modules/domain-node/src/main/java/org/apache/tuscany/sca/impl/hotupdate/HotUpdater.java new file mode 100644 index 0000000000..7369ab385b --- /dev/null +++ b/sca-java-2.x/tags/2.0.1/modules/domain-node/src/main/java/org/apache/tuscany/sca/impl/hotupdate/HotUpdater.java @@ -0,0 +1,111 @@ +/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.tuscany.sca.impl.hotupdate;
+
+import java.io.File;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.Executors;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.TimeUnit;
+
+import org.apache.tuscany.sca.Node;
+import org.apache.tuscany.sca.impl.NodeImpl;
+
+/**
+ * Code to do dynamic updates to a running Node.
+ * Very experimental presently, mainly just to see what type of things are required
+ */
+public class HotUpdater {
+
+ private final Node node;
+ private final File domainDir;
+
+ // key is contribution URI (which for exploded contributions is the directory name)
+ private final Map<String, LastModifiedTracker> contributions = new HashMap<String, LastModifiedTracker>();
+
+ private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
+
+ public HotUpdater(Node node, File domainDir){
+ this.node = node;
+ this.domainDir = domainDir;
+
+ final Runnable checker = new Runnable() {
+ public void run() {
+ check();
+ }
+ };
+
+ scheduler.scheduleAtFixedRate(checker, 10, 10, TimeUnit.SECONDS);
+ }
+
+ private void check() {
+ Set<String> found = new HashSet<String>();
+ for (File f : domainDir.listFiles()) {
+ if (f.isDirectory() && !f.getName().startsWith(".")) {
+ found.add(f.getName());
+ LastModifiedTracker scanner = contributions.get(f.getName());
+ if (scanner == null) {
+ //newContribution(f);
+ contributions.put(f.getName(), new LastModifiedTracker(f));
+ } else {
+ if (scanner.checkModified()) {
+ updatedContribution(f);
+ }
+ }
+ }
+ }
+
+ HashSet<String> removed = new HashSet<String>(contributions.keySet());
+ removed.removeAll(found);
+ for (String curi : removed) {
+ removedContribution(curi);
+ }
+
+ }
+
+ private void removedContribution(String curi) {
+ try {
+ ((NodeImpl)node).uninstallContribution(curi, true);
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ contributions.remove(curi);
+ }
+
+ private void updatedContribution(File f) {
+ try {
+ ((NodeImpl)node).updateContribution(f.getName(), f.toURI().toURL().toString(), null, null);
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ }
+
+ private void newContribution(File f) {
+ try {
+ node.installContribution(f.getName(), f.toURI().toURL().toString(), null, null);
+ node.startDeployables(f.getName());
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ }
+}
diff --git a/sca-java-2.x/tags/2.0.1/modules/domain-node/src/main/java/org/apache/tuscany/sca/impl/hotupdate/LastModifiedTracker.java b/sca-java-2.x/tags/2.0.1/modules/domain-node/src/main/java/org/apache/tuscany/sca/impl/hotupdate/LastModifiedTracker.java new file mode 100644 index 0000000000..a129f4d0fe --- /dev/null +++ b/sca-java-2.x/tags/2.0.1/modules/domain-node/src/main/java/org/apache/tuscany/sca/impl/hotupdate/LastModifiedTracker.java @@ -0,0 +1,75 @@ +/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.tuscany.sca.impl.hotupdate;
+
+import java.io.File;
+
+/**
+ * Keeps track of if a file or directory has been modified since a previous check
+ */
+public class LastModifiedTracker {
+
+ private File targetFile;
+ private Long lastModified;
+
+ public LastModifiedTracker(File targetFile) {
+ this.targetFile = targetFile;
+ checkModified();
+ }
+
+ public void reset() {
+ lastModified = null;
+ }
+
+ public boolean checkModified() {
+
+ long newLastModified = getNewLastModified(targetFile);
+
+ if (lastModified == null) {
+ lastModified = newLastModified;
+ return false;
+ }
+
+ if (newLastModified > lastModified) {
+ lastModified = newLastModified;
+ return true;
+ }
+
+ return false;
+ }
+
+ protected long getNewLastModified(File f) {
+
+ if (!f.exists()) return 0;
+
+ if (f.isFile()) return f.lastModified();
+
+ long newLastModified = f.lastModified();
+
+ for (File fx : f.listFiles()) {
+ long fxLastModified = getNewLastModified(fx);
+ if (fxLastModified > newLastModified){
+ newLastModified = fxLastModified;
+ }
+ }
+
+ return newLastModified;
+ }
+}
|