1/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package vogar.target;
18
19import java.lang.reflect.Method;
20import java.util.concurrent.atomic.AtomicReference;
21import vogar.ClassAnalyzer;
22import vogar.Result;
23import vogar.monitor.TargetMonitor;
24
25/**
26 * Runs a Java class with a main method. This includes jtreg tests.
27 */
28public final class MainRunner implements Runner {
29
30    private TargetMonitor monitor;
31    private Class<?> mainClass;
32    private Method main;
33
34    public void init(TargetMonitor monitor, String actionName, String qualification,
35            Class<?> mainClass, AtomicReference<String> skipPastReference,
36            TestEnvironment testEnvironment, int timeoutSeconds, boolean profile) {
37        this.monitor = monitor;
38        this.mainClass = mainClass;
39        try {
40            this.main = mainClass.getMethod("main", String[].class);
41        } catch (NoSuchMethodException e) {
42            // Don't create a MainRunner without first checking supports().
43            throw new IllegalArgumentException(e);
44        }
45    }
46
47    public boolean run(String actionName, Profiler profiler, String[] args) {
48        monitor.outcomeStarted(this, mainClass.getName(), actionName);
49        try {
50            if (profiler != null) {
51                profiler.start();
52            }
53            main.invoke(null, new Object[] { args });
54            monitor.outcomeFinished(Result.SUCCESS);
55        } catch (Throwable ex) {
56            ex.printStackTrace();
57            monitor.outcomeFinished(Result.EXEC_FAILED);
58        } finally {
59            if (profiler != null) {
60                profiler.stop();
61            }
62        }
63        return true;
64    }
65
66    public boolean supports(Class<?> klass) {
67        // public static void main(String[] args)
68        return new ClassAnalyzer(klass).hasMethod(true, void.class, "main", String[].class);
69    }
70}
71