aboutsummaryrefslogtreecommitdiffstats
path: root/org.jacoco.report/src/org/jacoco/report/InputStreamSourceFileLocator.java
blob: deab8fbd9dda718b74fcc8e782ebffcdd6515032 (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
/*******************************************************************************
 * Copyright (c) 2009, 2017 Mountainminds GmbH & Co. KG and Contributors
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *    Marc R. Hoffmann - initial API and implementation
 *    
 *******************************************************************************/
package org.jacoco.report;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;

/**
 * Abstract base class for {@link ISourceFileLocator} locator implementations
 * based on {@link InputStream}s. It handles the encoding and tab width.
 */
public abstract class InputStreamSourceFileLocator implements
		ISourceFileLocator {

	private final String encoding;
	private final int tabWidth;

	/**
	 * Creates a new locator with the given specification.
	 * 
	 * @param encoding
	 *            encoding of the source files, <code>null</code> for platform
	 *            default encoding
	 * @param tabWidth
	 *            tab width in source files as number of blanks
	 * 
	 */
	protected InputStreamSourceFileLocator(final String encoding,
			final int tabWidth) {
		this.encoding = encoding;
		this.tabWidth = tabWidth;
	}

	public Reader getSourceFile(final String packageName, final String fileName)
			throws IOException {
		final InputStream in;
		if (packageName.length() > 0) {
			in = getSourceStream(packageName + "/" + fileName);
		} else {
			in = getSourceStream(fileName);
		}

		if (in == null) {
			return null;
		}

		if (encoding == null) {
			return new InputStreamReader(in);
		} else {
			return new InputStreamReader(in, encoding);
		}
	}

	public int getTabWidth() {
		return tabWidth;
	}

	/**
	 * Tries to locate the given source file and opens its binary content.
	 * 
	 * @param path
	 *            local path to the resource
	 * @return stream if the file could be located, <code>null</code> otherwise
	 * @throws IOException
	 *             in case of problems while opening the stream
	 */
	protected abstract InputStream getSourceStream(String path)
			throws IOException;

}