From f520619c5ef71428448b6487c05ab364e21b5b7a Mon Sep 17 00:00:00 2001 From: rfeng Date: Fri, 16 Jan 2009 00:52:30 +0000 Subject: Bring up the equinox-based junit plugin for maven git-svn-id: http://svn.us.apache.org/repos/asf/tuscany@734877 13f79535-47bb-0310-9956-ffa450edef68 --- .../sca/node/equinox/launcher/EquinoxHost.java | 43 ++- .../node/equinox/launcher/NodeLauncherUtil.java | 77 ++++- java/sca/samples/calculator-osgi/pom.xml | 15 + .../test/java/calculator/CalculatorTestCase.java | 55 ++++ .../sca/equinox/junit/plugin/OSGiJUnitMojo.java | 361 +++++++++++++++++++++ .../tools/sca/osgi/junit/plugin/OSGiJUnitMojo.java | 320 ------------------ .../sca/tools/inspector/AssemblyInspector.java | 8 +- .../sca/tools/inspector/RegistryInspector.java | 4 +- .../sca/tools/inspector/RuntimeInspector.java | 5 +- 9 files changed, 535 insertions(+), 353 deletions(-) create mode 100644 java/sca/samples/calculator-osgi/src/test/java/calculator/CalculatorTestCase.java create mode 100644 java/sca/tools/maven/maven-osgi-junit/src/main/java/org/apache/tuscany/sca/equinox/junit/plugin/OSGiJUnitMojo.java delete mode 100644 java/sca/tools/maven/maven-osgi-junit/src/main/java/org/apache/tuscany/tools/sca/osgi/junit/plugin/OSGiJUnitMojo.java diff --git a/java/sca/modules/node-launcher-equinox/src/main/java/org/apache/tuscany/sca/node/equinox/launcher/EquinoxHost.java b/java/sca/modules/node-launcher-equinox/src/main/java/org/apache/tuscany/sca/node/equinox/launcher/EquinoxHost.java index 74dedca4a8..d9e42711ff 100644 --- a/java/sca/modules/node-launcher-equinox/src/main/java/org/apache/tuscany/sca/node/equinox/launcher/EquinoxHost.java +++ b/java/sca/modules/node-launcher-equinox/src/main/java/org/apache/tuscany/sca/node/equinox/launcher/EquinoxHost.java @@ -30,7 +30,10 @@ import static org.apache.tuscany.sca.node.equinox.launcher.NodeLauncherUtil.thir import static org.apache.tuscany.sca.node.equinox.launcher.NodeLauncherUtil.thisBundleLocation; import java.io.File; +import java.io.FileNotFoundException; import java.io.InputStream; +import java.net.MalformedURLException; +import java.net.URISyntaxException; import java.net.URL; import java.util.ArrayList; import java.util.HashMap; @@ -55,12 +58,14 @@ public class EquinoxHost { private BundleContext bundleContext; private Bundle launcherBundle; private boolean startedEclipse; + private Set dependencies; private List bundleFiles = new ArrayList(); private List bundleNames = new ArrayList(); private List jarFiles = new ArrayList(); private Map allBundles = new HashMap(); private List installedBundles = new ArrayList(); + /* private final static String systemPackages = "org.osgi.framework; version=1.3.0," + "org.osgi.service.packageadmin; version=1.2.0, " @@ -113,6 +118,15 @@ public class EquinoxHost { + "org.omg.PortableInterceptor, " + "org.omg.stub.java.rmi, " + "javax.rmi.CORBA"; + */ + public EquinoxHost() { + super(); + } + + public EquinoxHost(Set dependencies) { + super(); + this.dependencies = dependencies; + } /** * Start the Equinox host. @@ -167,17 +181,7 @@ public class EquinoxHost { // Determine the runtime classpath entries Set urls; - if (!startedEclipse) { - - // Use classpath entries from a distribution if there is one and the modules - // directories available in a dev environment for example - urls = runtimeClasspathEntries(true, false, true); - } else { - - // Use classpath entries from a distribution if there is one and the classpath - // entries on the current application's classloader - urls = runtimeClasspathEntries(true, true, false); - } + urls = findDependencies(); // Sort out which are bundles (and not already installed) and which are just // regular JARs @@ -325,6 +329,23 @@ public class EquinoxHost { } } + private Set findDependencies() throws FileNotFoundException, URISyntaxException, MalformedURLException { + if (dependencies == null) { + if (!startedEclipse) { + + // Use classpath entries from a distribution if there is one and the modules + // directories available in a dev environment for example + dependencies = runtimeClasspathEntries(true, false, true); + } else { + + // Use classpath entries from a distribution if there is one and the classpath + // entries on the current application's classloader + dependencies = runtimeClasspathEntries(true, true, false); + } + } + return dependencies; + } + /** * Stop the Equinox host. */ diff --git a/java/sca/modules/node-launcher-equinox/src/main/java/org/apache/tuscany/sca/node/equinox/launcher/NodeLauncherUtil.java b/java/sca/modules/node-launcher-equinox/src/main/java/org/apache/tuscany/sca/node/equinox/launcher/NodeLauncherUtil.java index db53eb7852..d52d3ccf86 100644 --- a/java/sca/modules/node-launcher-equinox/src/main/java/org/apache/tuscany/sca/node/equinox/launcher/NodeLauncherUtil.java +++ b/java/sca/modules/node-launcher-equinox/src/main/java/org/apache/tuscany/sca/node/equinox/launcher/NodeLauncherUtil.java @@ -261,22 +261,67 @@ final class NodeLauncherUtil { */ private static void addPackages(String jarFile, Set packages) throws IOException { String version = ";version=" + jarVersion(jarFile); - ZipInputStream is = new ZipInputStream(new FileInputStream(file(new URL(jarFile)))); - ZipEntry entry; - while ((entry = is.getNextEntry()) != null) { - String entryName = entry.getName(); - if (!entry.isDirectory() && entryName != null - && entryName.length() > 0 - && !entryName.startsWith(".") - && entryName.endsWith(".class") // Exclude resources from Export-Package - && entryName.lastIndexOf("/") > 0) { - String pkg = entryName.substring(0, entryName.lastIndexOf("/")).replace('/', '.') + version; + File file = file(new URL(jarFile)); + if (file.isDirectory()) { + List classFiles = listClassFiles(file); + for (String cls : classFiles) { + int index = cls.lastIndexOf('/'); + String pkg = cls.substring(0, index); + pkg = pkg.replace('/', '.') + version; packages.add(pkg); } + } else if (file.isFile()) { + ZipInputStream is = new ZipInputStream(new FileInputStream(file)); + ZipEntry entry; + while ((entry = is.getNextEntry()) != null) { + String entryName = entry.getName(); + if (!entry.isDirectory() && entryName != null + && entryName.length() > 0 + && !entryName.startsWith(".") + && entryName.endsWith(".class") // Exclude resources from Export-Package + && entryName.lastIndexOf("/") > 0) { + String pkg = entryName.substring(0, entryName.lastIndexOf("/")).replace('/', '.') + version; + packages.add(pkg); + } + } + is.close(); + } + } + + private static List listClassFiles(File directory) { + List artifacts = new ArrayList(); + traverse(artifacts, directory, directory); + return artifacts; + } + + /** + * Recursively traverse a root directory + * + * @param fileList + * @param file + * @param root + * @throws IOException + */ + private static void traverse(List fileList, File file, File root) { + if (file.isFile() && file.getName().endsWith(".class")) { + fileList.add(root.toURI().relativize(file.toURI()).toString()); + } else if (file.isDirectory()) { + String uri = root.toURI().relativize(file.toURI()).toString(); + if (uri.endsWith("/")) { + uri = uri.substring(0, uri.length() - 1); + } + fileList.add(uri); + + File[] files = file.listFiles(); + for (File f: files) { + if (!f.getName().startsWith(".")) { + traverse(fileList, f, root); + } + } } - is.close(); } + /** * Generate a manifest from a list of third-party JAR files. * @@ -362,7 +407,11 @@ final class NodeLauncherUtil { if (url == null) { throw new FileNotFoundException(resource); } - URI uri = url.toURI(); + String str = url.toString(); + if (str.contains(" ")) { + str = str.replace(" ", "%20"); + } + URI uri = URI.create(str); String scheme = uri.getScheme(); if (scheme.equals("jar")) { @@ -506,7 +555,9 @@ final class NodeLauncherUtil { } else { JarFile jar = new JarFile(file, false); Manifest manifest = jar.getManifest(); - bundleName = manifest.getMainAttributes().getValue(BUNDLE_SYMBOLICNAME); + if (manifest != null) { + bundleName = manifest.getMainAttributes().getValue(BUNDLE_SYMBOLICNAME); + } jar.close(); } if (bundleName == null) { diff --git a/java/sca/samples/calculator-osgi/pom.xml b/java/sca/samples/calculator-osgi/pom.xml index 4947a07438..c8e6a4666e 100644 --- a/java/sca/samples/calculator-osgi/pom.xml +++ b/java/sca/samples/calculator-osgi/pom.xml @@ -115,6 +115,21 @@ + + + org.apache.tuscany.sca + tuscany-maven-osgi-junit + + + osgi-test + test + + test + + + + + diff --git a/java/sca/samples/calculator-osgi/src/test/java/calculator/CalculatorTestCase.java b/java/sca/samples/calculator-osgi/src/test/java/calculator/CalculatorTestCase.java new file mode 100644 index 0000000000..9d9b0a9ffb --- /dev/null +++ b/java/sca/samples/calculator-osgi/src/test/java/calculator/CalculatorTestCase.java @@ -0,0 +1,55 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package calculator; + +import org.apache.tuscany.sca.node.Contribution; +import org.apache.tuscany.sca.node.ContributionLocationHelper; +import org.apache.tuscany.sca.node.Node; +import org.apache.tuscany.sca.node.NodeFactory; +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; + +/** + * This shows how to test the Calculator composition. + */ +public class CalculatorTestCase { + + private static Node node; + + @BeforeClass + public static void setUpBeforeClass() throws Exception { + String location = ContributionLocationHelper.getContributionLocation(CalculatorClient.class); + node = NodeFactory.newInstance().createNode("Calculator.composite", new Contribution("test", location)); + System.out.println("SCA Node API ClassLoader: " + node.getClass().getClassLoader()); + node.start(); + } + + @AfterClass + public static void tearDownAfterClass() throws Exception { + if (node != null) { + node.stop(); + node.destroy(); + } + } + + @Test + public void testDummy() throws Exception { + } +} diff --git a/java/sca/tools/maven/maven-osgi-junit/src/main/java/org/apache/tuscany/sca/equinox/junit/plugin/OSGiJUnitMojo.java b/java/sca/tools/maven/maven-osgi-junit/src/main/java/org/apache/tuscany/sca/equinox/junit/plugin/OSGiJUnitMojo.java new file mode 100644 index 0000000000..386120d3f8 --- /dev/null +++ b/java/sca/tools/maven/maven-osgi-junit/src/main/java/org/apache/tuscany/sca/equinox/junit/plugin/OSGiJUnitMojo.java @@ -0,0 +1,361 @@ +/* + * 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.equinox.junit.plugin; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.lang.reflect.Method; +import java.net.MalformedURLException; +import java.net.URL; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.jar.JarOutputStream; +import java.util.jar.Manifest; +import java.util.zip.ZipEntry; + +import junit.framework.Assert; + +import org.apache.maven.artifact.Artifact; +import org.apache.maven.artifact.resolver.ArtifactNotFoundException; +import org.apache.maven.artifact.resolver.ArtifactResolutionException; +import org.apache.maven.artifact.versioning.InvalidVersionSpecificationException; +import org.apache.maven.artifact.versioning.VersionRange; +import org.apache.maven.plugin.AbstractMojo; +import org.apache.maven.plugin.MojoExecutionException; +import org.apache.maven.plugin.logging.Log; +import org.apache.maven.project.MavenProject; +import org.apache.tuscany.sca.node.equinox.launcher.EquinoxHost; +import org.osgi.framework.Bundle; +import org.osgi.framework.BundleContext; + +/** + * @version $Rev$ $Date$ + * @goal test + * @phase test + * @requiresDependencyResolution test + * @description Run the unit test with OSGi + */ +public class OSGiJUnitMojo extends AbstractMojo { + /** + * The project to create a build for. + * + * @parameter expression="${project}" + * @required + * @readonly + */ + private MavenProject project; + + /** + * The basedir of the project. + * + * @parameter expression="${basedir}" + * @required @readonly + */ + protected File basedir; + + /** + * Used to look up Artifacts in the remote repository. + * + * @parameter expression="${component.org.apache.maven.artifact.factory.ArtifactFactory}" + * @required + * @readonly + */ + protected org.apache.maven.artifact.factory.ArtifactFactory factory; + + /** + * Used to look up Artifacts in the remote repository. + * + * @parameter expression="${component.org.apache.maven.artifact.resolver.ArtifactResolver}" + * @required + * @readonly + */ + protected org.apache.maven.artifact.resolver.ArtifactResolver resolver; + + /** + * Location of the local repository. + * + * @parameter expression="${localRepository}" + * @readonly + * @required + */ + protected org.apache.maven.artifact.repository.ArtifactRepository local; + + /** + * List of Remote Repositories used by the resolver + * + * @parameter expression="${project.remoteArtifactRepositories}" + * @readonly + * @required + */ + protected java.util.List remoteRepos; + + protected Artifact getArtifact(String groupId, String artifactId) throws MojoExecutionException { + Artifact artifact; + VersionRange vr; + try { + vr = VersionRange.createFromVersionSpec(project.getVersion()); + } catch (InvalidVersionSpecificationException e1) { + vr = VersionRange.createFromVersion(project.getVersion()); + } + artifact = factory.createDependencyArtifact(groupId, artifactId, vr, "jar", null, Artifact.SCOPE_TEST); + + try { + resolver.resolve(artifact, remoteRepos, local); + } catch (ArtifactResolutionException e) { + throw new MojoExecutionException("Unable to resolve artifact.", e); + } catch (ArtifactNotFoundException e) { + throw new MojoExecutionException("Unable to find artifact.", e); + } + + return artifact; + } + + /** + * Returns a string representation of the given bundle. + * + * @param b + * @param verbose + * @return + */ + static String string(Bundle bundle, boolean verbose) { + StringBuffer sb = new StringBuffer(); + sb.append(bundle.getBundleId()).append(" ").append(bundle.getSymbolicName()); + int s = bundle.getState(); + if ((s & Bundle.UNINSTALLED) != 0) { + sb.append(" UNINSTALLED"); + } + if ((s & Bundle.INSTALLED) != 0) { + sb.append(" INSTALLED"); + } + if ((s & Bundle.RESOLVED) != 0) { + sb.append(" RESOLVED"); + } + if ((s & Bundle.STARTING) != 0) { + sb.append(" STARTING"); + } + if ((s & Bundle.STOPPING) != 0) { + sb.append(" STOPPING"); + } + if ((s & Bundle.ACTIVE) != 0) { + sb.append(" ACTIVE"); + } + + if (verbose) { + sb.append(" ").append(bundle.getLocation()); + sb.append(" ").append(bundle.getHeaders()); + } + return sb.toString(); + } + + private void generateJar(File root, File jar, Manifest mf) throws IOException { + getLog().info("Generating " + jar.toString()); + FileOutputStream fos = new FileOutputStream(jar); + JarOutputStream jos = mf != null ? new JarOutputStream(fos, mf) : new JarOutputStream(fos); + addDir(jos, root, root); + jos.close(); + } + + private void addDir(JarOutputStream jos, File root, File dir) throws IOException, FileNotFoundException { + for (File file : dir.listFiles()) { + if (file.isDirectory()) { + addDir(jos, root, file); + } else if (file.isFile()) { + // getLog().info(file.toString()); + String uri = root.toURI().relativize(file.toURI()).toString(); + ZipEntry entry = new ZipEntry(uri); + jos.putNextEntry(entry); + byte[] buf = new byte[4096]; + FileInputStream in = new FileInputStream(file); + for (;;) { + int len = in.read(buf); + if (len > 0) { + jos.write(buf, 0, len); + } else { + break; + } + } + in.close(); + jos.closeEntry(); + } + } + } + + public void execute() throws MojoExecutionException { + if (project.getPackaging().equals("pom")) { + return; + } + + Log log = getLog(); + Set jarFiles = new HashSet(); + for (Object o : project.getArtifacts()) { + Artifact a = (Artifact)o; + try { + if (log.isDebugEnabled()) { + log.debug("Adding: " + a); + } + jarFiles.add(a.getFile().toURI().toURL()); + } catch (MalformedURLException e) { + getLog().error(e); + } + } + + /* + * Add org.apache.tuscany.sca:tuscany-extensibility-osgi module + */ + String aid = "tuscany-extensibility-equinox"; + Artifact ext = getArtifact("org.apache.tuscany.sca", aid); + try { + URL url = ext.getFile().toURI().toURL(); + if (log.isDebugEnabled()) { + log.debug("Adding: " + ext); + } + jarFiles.add(url); + } catch (MalformedURLException e) { + getLog().error(e); + } + + File mainJar = new File(project.getBuild().getDirectory(), project.getArtifactId()+"-osgi.jar"); + File testJar = new File(project.getBuild().getDirectory(), project.getArtifactId()+"-test-osgi.jar"); + try { + generateJar(new File(project.getBuild().getOutputDirectory()), mainJar, null); + generateJar(new File(project.getBuild().getTestOutputDirectory()), testJar, null); + jarFiles.add(mainJar.toURI().toURL()); + jarFiles.add(testJar.toURI().toURL()); + } catch (IOException e) { + getLog().error(e); + } + + if (log.isDebugEnabled()) { + for (URL url : jarFiles) { + getLog().debug(url.toString()); + } + } + + try { + EquinoxHost host = new EquinoxHost(jarFiles); + BundleContext context = host.start(); + + if (getLog().isDebugEnabled()) { + for (Bundle b : context.getBundles()) { + getLog().debug(string(b, false)); + } + } + Bundle testBundle = null; + String libraryBundleName = "org.apache.tuscany.sca.node.launcher.equinox.libraries"; + for(Bundle bundle: context.getBundles()) { + if(libraryBundleName.equals(bundle.getSymbolicName())) { + testBundle = bundle; + break; + } + } + + try { + runAllTestsFromDirs(testBundle, project.getBuild().getTestOutputDirectory()); + } finally { + host.stop(); + } + } catch (Throwable e) { + throw new MojoExecutionException(e.getMessage(), e); + } + } + + public void getTestCases(File dir, String prefix, HashSet testCaseSet) { + File[] files = dir.listFiles(); + for (File file : files) { + if (file.isDirectory()) { + String newPrefix = prefix == null ? file.getName() : prefix + "." + file.getName(); + getTestCases(file, newPrefix, testCaseSet); + } else if (file.getName().endsWith("TestCase.class")) { + String name = file.getName(); + name = name.substring(0, name.length() - 6); // remove .class + name = (prefix == null) ? name : prefix + "." + name; + + testCaseSet.add(name); + } + } + } + + public void runAllTestsFromDirs(Bundle testBundle, String testDir) throws Exception { + + int failures = 0; + HashSet testCaseSet = new HashSet(); + getTestCases(new File(testDir), null, testCaseSet); + for (String className : testCaseSet) { + Class testClass = testBundle.loadClass(className); + failures += runTestCase(testBundle, testClass); + } + + Assert.assertEquals(0, failures); + + } + + /** + * Use java reflection to call JUNIT as the JUNIT might be in the bundles + * @param testBundle + * @param testClass + * @return + * @throws Exception + */ + public int runTestCase(Bundle testBundle, Class testClass) throws Exception { + + if (testClass.getName().endsWith("TestCase")) { + getLog().info("Running: " + testClass.getName()); + Class coreClass = testBundle.loadClass("org.junit.runner.JUnitCore"); + Object core = coreClass.newInstance(); + Class reqClass = testBundle.loadClass("org.junit.runner.Request"); + Method aClass = reqClass.getMethod("aClass", Class.class); + Object req = aClass.invoke(null, testClass); + Method run = coreClass.getMethod("run", reqClass); + Object result = run.invoke(core, req); + Object runs = result.getClass().getMethod("getRunCount").invoke(result); + Object ignores = result.getClass().getMethod("getIgnoreCount").invoke(result); + List failureList = (List)result.getClass().getMethod("getFailures").invoke(result); + + int failures = 0, errors = 0; + Class errorClass = testBundle.loadClass("junit.framework.AssertionFailedError"); + for (Object f : failureList) { + Object ex = f.getClass().getMethod("getException").invoke(f); + if (errorClass.isInstance(ex)) { + failures++; + } else { + errors++; + } + getLog().error((Throwable)ex); + } + + getLog().info("Test Runs: " + runs + + ", Failures: " + + failures + + ", Errors: " + + errors + + ", Ignores: " + + ignores); + + return failureList.size(); + + } + return 0; + + } + +} diff --git a/java/sca/tools/maven/maven-osgi-junit/src/main/java/org/apache/tuscany/tools/sca/osgi/junit/plugin/OSGiJUnitMojo.java b/java/sca/tools/maven/maven-osgi-junit/src/main/java/org/apache/tuscany/tools/sca/osgi/junit/plugin/OSGiJUnitMojo.java deleted file mode 100644 index c967220768..0000000000 --- a/java/sca/tools/maven/maven-osgi-junit/src/main/java/org/apache/tuscany/tools/sca/osgi/junit/plugin/OSGiJUnitMojo.java +++ /dev/null @@ -1,320 +0,0 @@ -/* - * 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.tools.sca.osgi.junit.plugin; - -import java.io.File; -import java.lang.reflect.Method; -import java.net.MalformedURLException; -import java.net.URL; -import java.net.URLClassLoader; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; - -import junit.framework.Assert; - -import org.apache.maven.artifact.Artifact; -import org.apache.maven.artifact.resolver.ArtifactNotFoundException; -import org.apache.maven.artifact.resolver.ArtifactResolutionException; -import org.apache.maven.artifact.versioning.InvalidVersionSpecificationException; -import org.apache.maven.artifact.versioning.VersionRange; -import org.apache.maven.plugin.AbstractMojo; -import org.apache.maven.plugin.MojoExecutionException; -import org.apache.maven.plugin.logging.Log; -import org.apache.maven.project.MavenProject; -import org.apache.tuscany.sca.node.equinox.launcher.EquinoxHost; -import org.osgi.framework.Bundle; -import org.osgi.framework.BundleContext; - -/** - * @version $Rev$ $Date$ - * @goal test - * @phase integration-test - * @requiresDependencyResolution test - * @description Run the unit test with OSGi - */ -public class OSGiJUnitMojo extends AbstractMojo { - /** - * The project to create a build for. - * - * @parameter expression="${project}" - * @required - * @readonly - */ - private MavenProject project; - - /** - * The basedir of the project. - * - * @parameter expression="${basedir}" - * @required @readonly - */ - protected File basedir; - - /** - * Used to look up Artifacts in the remote repository. - * - * @parameter expression="${component.org.apache.maven.artifact.factory.ArtifactFactory}" - * @required - * @readonly - */ - protected org.apache.maven.artifact.factory.ArtifactFactory factory; - - /** - * Used to look up Artifacts in the remote repository. - * - * @parameter expression="${component.org.apache.maven.artifact.resolver.ArtifactResolver}" - * @required - * @readonly - */ - protected org.apache.maven.artifact.resolver.ArtifactResolver resolver; - - /** - * Location of the local repository. - * - * @parameter expression="${localRepository}" - * @readonly - * @required - */ - protected org.apache.maven.artifact.repository.ArtifactRepository local; - - /** - * List of Remote Repositories used by the resolver - * - * @parameter expression="${project.remoteArtifactRepositories}" - * @readonly - * @required - */ - protected java.util.List remoteRepos; - - /** - * @parameter - */ - protected String osgiRuntime; - - protected Artifact getArtifact(String groupId, String artifactId) throws MojoExecutionException { - Artifact artifact; - VersionRange vr; - try { - vr = VersionRange.createFromVersionSpec(project.getVersion()); - } catch (InvalidVersionSpecificationException e1) { - vr = VersionRange.createFromVersion(project.getVersion()); - } - artifact = factory.createDependencyArtifact(groupId, artifactId, vr, "jar", null, Artifact.SCOPE_TEST); - - try { - resolver.resolve(artifact, remoteRepos, local); - } catch (ArtifactResolutionException e) { - throw new MojoExecutionException("Unable to resolve artifact.", e); - } catch (ArtifactNotFoundException e) { - throw new MojoExecutionException("Unable to find artifact.", e); - } - - return artifact; - } - - /** - * Returns a string representation of the given bundle. - * - * @param b - * @param verbose - * @return - */ - static String string(Bundle bundle, boolean verbose) { - StringBuffer sb = new StringBuffer(); - sb.append(bundle.getBundleId()).append(" ").append(bundle.getSymbolicName()); - int s = bundle.getState(); - if ((s & Bundle.UNINSTALLED) != 0) { - sb.append(" UNINSTALLED"); - } - if ((s & Bundle.INSTALLED) != 0) { - sb.append(" INSTALLED"); - } - if ((s & Bundle.RESOLVED) != 0) { - sb.append(" RESOLVED"); - } - if ((s & Bundle.STARTING) != 0) { - sb.append(" STARTING"); - } - if ((s & Bundle.STOPPING) != 0) { - sb.append(" STOPPING"); - } - if ((s & Bundle.ACTIVE) != 0) { - sb.append(" ACTIVE"); - } - - if (verbose) { - sb.append(" ").append(bundle.getLocation()); - sb.append(" ").append(bundle.getHeaders()); - } - return sb.toString(); - } - - - public void execute() throws MojoExecutionException { - if (project.getPackaging().equals("pom")) { - return; - } - - Log log = getLog(); - List jarFiles = new ArrayList(); - for (Object o : project.getArtifacts()) { - Artifact a = (Artifact)o; - try { - if (log.isDebugEnabled()) { - log.debug("Adding: " + a); - } - jarFiles.add(a.getFile().toURI().toURL()); - } catch (MalformedURLException e) { - getLog().error(e); - } - } - - /* - * Add org.apache.tuscany.sca:tuscany-extensibility-osgi module - */ - String aid = "equinox".equals(osgiRuntime) ? "tuscany-extensibility-equinox" : "tuscany-extensibility-osgi"; - Artifact ext = getArtifact("org.apache.tuscany.sca", aid); - try { - URL url = ext.getFile().toURI().toURL(); - if (!jarFiles.contains(url)) { - if (log.isDebugEnabled()) { - log.debug("Adding: " + ext); - } - jarFiles.add(url); - } - } catch (MalformedURLException e) { - getLog().error(e); - } - - // String home = new File(basedir, "target/tuscany").toString(); - // System.setProperty("TUSCANY_HOME", home); - // getLog().info(home); - try { - EquinoxHost host = new EquinoxHost(); - BundleContext context = host.start(); - - for (Bundle b : context.getBundles()) { - if (getLog().isDebugEnabled()) { - getLog().debug(string(b, false)); - } - } - - ClassLoader tccl = Thread.currentThread().getContextClassLoader(); - URL[] urls = - new URL[] {new File(project.getBuild().getOutputDirectory()).toURI().toURL(), - new File(project.getBuild().getTestOutputDirectory()).toURI().toURL()}; - - URLClassLoader cl = new URLClassLoader(urls, tccl); - Thread.currentThread().setContextClassLoader(cl); - try { - runAllTestsFromDirs(cl, project.getBuild().getTestOutputDirectory()); - } finally { - Thread.currentThread().setContextClassLoader(tccl); - } - host.stop(); - } catch (Throwable e) { - throw new MojoExecutionException(e.getMessage(), e); - } - // finally { - // System.clearProperty("TUSCANY_HOME"); - // } - - } - - public void getTestCases(File dir, String prefix, HashSet testCaseSet) { - File[] files = dir.listFiles(); - for (File file : files) { - if (file.isDirectory()) { - String newPrefix = prefix == null ? file.getName() : prefix + "." + file.getName(); - getTestCases(file, newPrefix, testCaseSet); - } else if (file.getName().endsWith("TestCase.class")) { - String name = file.getName(); - name = name.substring(0, name.length() - 6); // remove .class - name = (prefix == null) ? name : prefix + "." + name; - - testCaseSet.add(name); - } - } - } - - public void runAllTestsFromDirs(ClassLoader testClassLoader, String testDir) throws Exception { - - int failures = 0; - HashSet testCaseSet = new HashSet(); - getTestCases(new File(testDir), null, testCaseSet); - for (String className : testCaseSet) { - Class testClass = testClassLoader.loadClass(className); - failures += runTestCase(testClassLoader, testClass); - } - - Assert.assertEquals(0, failures); - - } - - /** - * Use java reflection to call JUNIT as the JUNIT might be in the bundles - * @param testClassLoader - * @param testClass - * @return - * @throws Exception - */ - public int runTestCase(ClassLoader testClassLoader, Class testClass) throws Exception { - - if (testClass.getName().endsWith("TestCase")) { - getLog().info("Running: " + testClass.getName()); - Class coreClass = Class.forName("org.junit.runner.JUnitCore", true, testClassLoader); - Object core = coreClass.newInstance(); - Class reqClass = Class.forName("org.junit.runner.Request", true, testClassLoader); - Method aClass = reqClass.getMethod("aClass", Class.class); - Object req = aClass.invoke(null, testClass); - Method run = coreClass.getMethod("run", reqClass); - Object result = run.invoke(core, req); - Object runs = result.getClass().getMethod("getRunCount").invoke(result); - Object ignores = result.getClass().getMethod("getIgnoreCount").invoke(result); - List failureList = (List)result.getClass().getMethod("getFailures").invoke(result); - - int failures = 0, errors = 0; - Class errorClass = Class.forName("junit.framework.AssertionFailedError", true, testClassLoader); - for (Object f : failureList) { - Object ex = f.getClass().getMethod("getException").invoke(f); - if (errorClass.isInstance(ex)) { - failures++; - } else { - errors++; - } - getLog().error((Throwable)ex); - } - - getLog().info("Test Runs: " + runs - + ", Failures: " - + failures - + ", Errors: " - + errors - + ", Ignores: " - + ignores); - - return failureList.size(); - - } - return 0; - - } - -} diff --git a/java/sca/tools/runtime-inspector/src/main/java/org/apache/tuscany/sca/tools/inspector/AssemblyInspector.java b/java/sca/tools/runtime-inspector/src/main/java/org/apache/tuscany/sca/tools/inspector/AssemblyInspector.java index ff32d1b48f..ce91155b53 100644 --- a/java/sca/tools/runtime-inspector/src/main/java/org/apache/tuscany/sca/tools/inspector/AssemblyInspector.java +++ b/java/sca/tools/runtime-inspector/src/main/java/org/apache/tuscany/sca/tools/inspector/AssemblyInspector.java @@ -22,11 +22,11 @@ import javax.xml.stream.XMLOutputFactory; import javax.xml.stream.XMLStreamWriter; import org.apache.tuscany.sca.assembly.Composite; -import org.apache.tuscany.sca.contribution.ModelFactoryExtensionPoint; 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.node.SCANode; +import org.apache.tuscany.sca.core.FactoryExtensionPoint; +import org.apache.tuscany.sca.node.Node; import org.apache.tuscany.sca.node.impl.NodeImpl; @@ -36,7 +36,7 @@ import org.apache.tuscany.sca.node.impl.NodeImpl; public class AssemblyInspector { - public String assemblyAsString(SCANode node) { + public String assemblyAsString(Node node) { StringBuffer assemblyString = new StringBuffer(); // get at the node internals @@ -44,7 +44,7 @@ public class AssemblyInspector { ExtensionPointRegistry registry = ((NodeImpl)node).getExtensionPointRegistry(); // Get the output factory - ModelFactoryExtensionPoint modelFactories = registry.getExtensionPoint(ModelFactoryExtensionPoint.class); + FactoryExtensionPoint modelFactories = registry.getExtensionPoint(FactoryExtensionPoint.class); XMLOutputFactory outputFactory = modelFactories.getFactory(XMLOutputFactory.class); StAXArtifactProcessorExtensionPoint staxProcessors = registry.getExtensionPoint(StAXArtifactProcessorExtensionPoint.class); StAXArtifactProcessor compositeProcessor = (StAXArtifactProcessor)staxProcessors.getProcessor(Composite.class); diff --git a/java/sca/tools/runtime-inspector/src/main/java/org/apache/tuscany/sca/tools/inspector/RegistryInspector.java b/java/sca/tools/runtime-inspector/src/main/java/org/apache/tuscany/sca/tools/inspector/RegistryInspector.java index 283d5e3df9..10eb0716e9 100644 --- a/java/sca/tools/runtime-inspector/src/main/java/org/apache/tuscany/sca/tools/inspector/RegistryInspector.java +++ b/java/sca/tools/runtime-inspector/src/main/java/org/apache/tuscany/sca/tools/inspector/RegistryInspector.java @@ -23,7 +23,7 @@ import java.util.Map; import java.util.Set; import org.apache.tuscany.sca.core.DefaultExtensionPointRegistry; -import org.apache.tuscany.sca.node.SCANode; +import org.apache.tuscany.sca.node.Node; import org.apache.tuscany.sca.node.impl.NodeImpl; @@ -32,7 +32,7 @@ import org.apache.tuscany.sca.node.impl.NodeImpl; */ public class RegistryInspector { - public String registryAsString(SCANode node) { + public String registryAsString(Node node) { StringBuffer extensionPointRegistryString = new StringBuffer("Extension Point Registry \n"); // Get the interesting extension points out of the registry and print them out diff --git a/java/sca/tools/runtime-inspector/src/main/java/org/apache/tuscany/sca/tools/inspector/RuntimeInspector.java b/java/sca/tools/runtime-inspector/src/main/java/org/apache/tuscany/sca/tools/inspector/RuntimeInspector.java index 26080b2e12..883f042172 100644 --- a/java/sca/tools/runtime-inspector/src/main/java/org/apache/tuscany/sca/tools/inspector/RuntimeInspector.java +++ b/java/sca/tools/runtime-inspector/src/main/java/org/apache/tuscany/sca/tools/inspector/RuntimeInspector.java @@ -35,9 +35,8 @@ import java.util.List; import java.util.Set; import org.apache.tuscany.sca.assembly.Composite; -import org.apache.tuscany.sca.node.SCANode; +import org.apache.tuscany.sca.node.Node; import org.apache.tuscany.sca.node.impl.NodeImpl; -import org.w3c.dom.Node; /** @@ -56,7 +55,7 @@ public class RuntimeInspector { } } - public String runtimeAsString(SCANode node) { + public String runtimeAsString(Node node) { StringBuffer assemblyString = new StringBuffer(); this.out = new PrintWriter(new OutputStreamWriter(System.out), true); -- cgit v1.2.3