summaryrefslogtreecommitdiffstats
path: root/tags/java/sca/1.5.1/tools/maven/maven-osgi-junit/src/main/java/org/apache/tuscany/tools/sca/osgi/junit/plugin/OSGiJUnitMojo.java
blob: a2251a6a2aa7e11978a3f2bb60b6c8efeebf064e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
/*
 * 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.osgi.launcher.FelixOSGiHost;
import org.apache.tuscany.sca.node.osgi.launcher.LauncherBundleActivator;
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;
    }

    public void execute() throws MojoExecutionException {
        if (project.getPackaging().equals("pom")) {
            return;
        }

        Log log = getLog();
        List<URL> jarFiles = new ArrayList<URL>();
        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 {
            FelixOSGiHost host = new FelixOSGiHost();
            host.setActivator(new LauncherBundleActivator(jarFiles));
            BundleContext context = host.start();

            for (Bundle b : context.getBundles()) {
                if (getLog().isDebugEnabled()) {
                    getLog().debug(LauncherBundleActivator.toString(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<String> 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<String> testCaseSet = new HashSet<String>();
        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;

    }

}