package eu.dnetlib.contract.utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.net.URL;

/**
 * File utilities.
 * @author mhorst
 *
 */
public class FileUtils {

	public static final String CLASSPATH_PREFIX = "classpath:";
	
	/**
	 * Returns file content for given path.
	 * Path might be absolute, relative file path or classpath.
	 * @param filePath
	 * @return
	 */
	public static String getFileContent(String filePath) throws Exception {
		if (filePath==null)
			return null;
		File file = null;
//			added support for reading file content by web application
		
		if (filePath.startsWith(CLASSPATH_PREFIX)) {
			filePath = filePath.substring(CLASSPATH_PREFIX.length());
		}
		URL fileURL = FileUtils.class.getResource("/"+filePath);
		if (fileURL!=null) {
			file = new File(fileURL.getPath());
		} else
			file = new File(filePath);
		
		BufferedReader reader = new BufferedReader(new FileReader(file));
		StringBuffer strBuff = new StringBuffer();
		String line;
		while ((line = reader.readLine())!=null) {
			strBuff.append(line);
		}
		return strBuff.toString();
	}
}
