1 /******************************************************************************* 2 * Copyright (c) 2009, 2015 Mountainminds GmbH & Co. KG and Contributors 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 *******************************************************************************/ 12 package org.jacoco.agent.rt.internal.output; 13 14 import java.io.File; 15 import java.io.FileOutputStream; 16 import java.io.IOException; 17 import java.io.OutputStream; 18 19 import org.jacoco.core.data.ExecutionDataWriter; 20 import org.jacoco.core.runtime.AgentOptions; 21 import org.jacoco.core.runtime.RuntimeData; 22 23 /** 24 * Local only agent output that will write coverage data to the filesystem. This 25 * controller uses the following agent options: 26 * <ul> 27 * <li>destfile</li> 28 * <li>append</li> 29 * </ul> 30 */ 31 public class FileOutput implements IAgentOutput { 32 33 private RuntimeData data; 34 35 private File destFile; 36 37 private boolean append; 38 39 public final void startup(final AgentOptions options, final RuntimeData data) 40 throws IOException { 41 this.data = data; 42 this.destFile = new File(options.getDestfile()).getAbsoluteFile(); 43 this.append = options.getAppend(); 44 final File folder = destFile.getParentFile(); 45 if (folder != null) { 46 folder.mkdirs(); 47 } 48 // Make sure we can write to the file: 49 openFile().close(); 50 } 51 52 public void writeExecutionData(final boolean reset) throws IOException { 53 final OutputStream output = openFile(); 54 try { 55 final ExecutionDataWriter writer = new ExecutionDataWriter(output); 56 data.collect(writer, writer, reset); 57 } finally { 58 output.close(); 59 } 60 } 61 62 public void shutdown() throws IOException { 63 // Nothing to do 64 } 65 66 private OutputStream openFile() throws IOException { 67 final FileOutputStream file = new FileOutputStream(destFile, append); 68 // Avoid concurrent writes from different agents running in parallel: 69 file.getChannel().lock(); 70 return file; 71 } 72 73 } 74