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 com.google.caliper.runner.CaliperMain;
20import com.google.common.collect.ImmutableList;
21import java.io.PrintWriter;
22import vogar.Result;
23import vogar.monitor.TargetMonitor;
24
25/**
26 * Runs a <a href="http://code.google.com/p/caliper/">Caliper</a> benchmark.
27 */
28public final class CaliperTargetRunner implements TargetRunner {
29
30    private final TargetMonitor monitor;
31    private final Class<?> testClass;
32    private final String[] args;
33
34    public CaliperTargetRunner(TargetMonitor monitor, Class<?> testClass, String[] args) {
35        this.monitor = monitor;
36        this.testClass = testClass;
37        this.args = args;
38    }
39
40    public boolean run() {
41        monitor.outcomeStarted(testClass.getName());
42        ImmutableList.Builder<String> builder = ImmutableList.<String>builder()
43            .add(testClass.getName())
44            .add(args);
45
46        // Make sure that the results are output to the correct location so that vogar will
47        // copy them back to the ./vogar-results/ directory.
48        builder.add("-Cresults.file.options.dir=" + System.getProperty("java.io.tmpdir"));
49
50        // TODO(paulduffin): Remove once caliper supports suitable defaults for Android.
51        // Temporary change to force caliper to use a heap of 256M for each of it's workers when
52        // running on Android.
53        if (System.getProperty("java.specification.name").equals("Dalvik Core Library")) {
54            builder.add("-Cvm.args=-Xmx256M -Xms256M");
55        }
56
57        ImmutableList<String> argList = builder.build();
58        String[] arguments = argList.toArray(new String[argList.size()]);
59        Result result = Result.EXEC_FAILED;
60        try {
61            PrintWriter stdout = new PrintWriter(System.out);
62            PrintWriter stderr = new PrintWriter(System.err);
63            CaliperMain.exitlessMain(arguments, stdout, stderr);
64            result = Result.SUCCESS;
65        } catch (Exception ex) {
66            ex.printStackTrace();
67        }
68        monitor.outcomeFinished(result);
69        return true;
70    }
71}
72