Skip to main content
summaryrefslogtreecommitdiffstats
blob: 87ae0dd6f59e36f865b3c15e8aab4321c0086e21 (plain) (blame)
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
/*******************************************************************************
 * Copyright (c) 2005, 2016 IBM Corporation and others.
 * 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:
 *     IBM Corporation - initial API and implementation
 *******************************************************************************/
package org.eclipse.ua.tests.util;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.nio.charset.StandardCharsets;

import org.osgi.framework.Bundle;

/*
 * Utility methods for working with files.
 */
public class FileUtil {

	/**
	 * Gets the contents of the file with the given relative path in the given bundle,
	 * as a String (file must be encoded as UTF-8).
	 */
	public static String getContents(Bundle bundle, String relativePath) throws IOException {
		URL url = bundle.getEntry(relativePath);
		if (url != null) {
			return readString(url.openStream());
		}
		return null;
	}

	/**
	 * Gets the contents of the file with the given absolute path as a String (file must
	 * be encoded as UTF-8).
	 */
	public static String getContents(String absolutePath) throws IOException {
		try (FileInputStream fis = new FileInputStream(absolutePath)) {
			return readString(fis);
		}
	}

	/**
	 * Generates a filename with path to the result file that will be generated
	 * for the intro xml referred to by the string.
	 */
	public static String getResultFile(String in) {
		return in.substring(0, in.lastIndexOf('.')) + "_expected.txt";
	}

	/**
	 * Reads the contents of the input stream as UTF-8 and constructs and returns
	 * as a String.
	 */
	public static String readString(InputStream in) throws IOException {
		try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
			byte[] buffer = new byte[4096];
			int num;
			while ((num = in.read(buffer)) > 0) {
				out.write(buffer, 0, num);
			}
			String result = new String(out.toByteArray(), StandardCharsets.UTF_8);
			if (result.length() > 0) {
				// filter windows-specific newline
				result = result.replaceAll("\r", "");
			}
			// ignore whitespace at start or end
			return result.trim();
		}
	}
}

Back to the top