JvmArgumentHelper.java
1/*******************************************************************************
2 * Copyright (c) 2009 Mountainminds GmbH & Co. KG and others
3 * All rights reserved. This program and the accompanying materials
4 * are made available under the terms of the Eclipse Public License v1.0
5 * which accompanies this distribution, and is available at
6 * http://www.eclipse.org/legal/epl-v10.html
7 *
8 * Contributors:
9 * Brock Janiczak - initial API and implementation
10 *
11 * $Id: $
12 *******************************************************************************/
13package org.jacoco.ant;
14
15import java.io.File;
16import java.io.FileOutputStream;
17import java.io.IOException;
18import java.io.InputStream;
19import java.io.OutputStream;
20
21import org.apache.tools.ant.BuildException;
22import org.apache.tools.ant.util.FileUtils;
23import org.jacoco.agent.AgentJar;
24import org.jacoco.core.runtime.AgentOptions;
25
26/**
27 * Helper class to generate the JVM argument required to start a new JVM with a
28 * code coverage agent
29 *
30 * @author Brock Janiczak
31 * @version $Revision: $
32 */
33class JvmArgumentHelper {
34 private final File agentJar;
35
36 JvmArgumentHelper() {
37 final InputStream inputStream = AgentJar.getResourceAsStream();
38 try {
39 agentJar = extractAgentJar(inputStream);
40 } finally {
41 FileUtils.close(inputStream);
42 }
43 }
44
45 /**
46 * Extract the JaCoCo agent jar from the classpath and put it into a
47 * temporary location.
48 *
49 * @param inputJarStream
50 * Open stream pointing to the JaCoCo jar
51 * @return Local physical location of the JaCoCo agent jar. This file will
52 * be removed once the task has been executed
53 */
54 private File extractAgentJar(final InputStream inputJarStream) {
55
56 if (inputJarStream == null) {
57 throw new BuildException("Unable to locate Agent Jar");
58 }
59
60 OutputStream outputJarStream = null;
61 try {
62 final File agentJar = File.createTempFile("jacocoagent", ".jar");
63 agentJar.deleteOnExit();
64
65 outputJarStream = new FileOutputStream(agentJar);
66
67 final byte[] buffer = new byte[8192];
68
69 int bytesRead;
70 while ((bytesRead = inputJarStream.read(buffer)) != -1) {
71 outputJarStream.write(buffer, 0, bytesRead);
72 }
73
74 return agentJar;
75 } catch (final IOException e) {
76 throw new BuildException("Unable to unpack Agent Jar", e);
77 } finally {
78 FileUtils.close(outputJarStream);
79 }
80 }
81
82 /**
83 * Generate required JVM argument string based on current configuration and
84 * agent jar location
85 *
86 * @return Argument to pass to create new VM with coverage enabled
87 */
88 String createJavaAgentParam(final AgentOptions agentOptions) {
89 final StringBuilder param = new StringBuilder();
90 param.append("-javaagent:");
91 param.append(agentJar.getAbsolutePath());
92 param.append("=");
93 param.append(agentOptions.toString());
94
95 return param.toString();
96 }
97}