/**
 * Copyright 2008-2010 DRIVER PROJECT (Bielefeld University)
 * Original author: Marek Imialek <marek.imialek at uni-bielefeld.de>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package eu.dnetlib.miscutils.file;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;

import org.apache.velocity.exception.ResourceNotFoundException;
import org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader;

/**
 * The Class FileHandler offers methods for handling files.
 * @author <a href="mailto:marek.imialek at uni-bielefeld.de">Marek Imialek</a>
 */
public class FileHandler {

	/**
	 * Method reads content of file indicated by class path and return it as string.
	 * 
	 * @param sourceFilePath the source file path
	 * @return file content
	 * @throws ResourceNotFoundException the resource not found exception
	 * @throws IOException Signals that an I/O exception has occurred.
	 */
	public static String readFile(String sourceFilePath) throws ResourceNotFoundException, IOException{

		ClasspathResourceLoader loader = new ClasspathResourceLoader();
		String sourceContent = read(loader.getResourceStream(sourceFilePath));
		return sourceContent;
	}

	/**
	 * Method store input stream content in buffer
	 * 
	 * @param in file input stream
	 * @return content of input stream as string
	 * @throws IOException Signals that an I/O exception has occurred.
	 */
	public static String read(InputStream in) throws IOException {
		StringBuffer out = new StringBuffer();
		byte[] b = new byte[4096];
		for (int n; (n = in.read(b)) != -1;) {
			out.append(new String(b, 0, n));
		}
		return out.toString();
	}
	
	/**
	 * Deletes all files and sub-directories under specified directory.
	 * 
	 * @param dir directory to be removed
	 * 
	 * @return true if deletion succesfull
	 */
    public static boolean deleteDirectory(File dir) {
    	
        if (dir.isDirectory()) {
        	
            String[] children = dir.list();
            
            for (int i=0; i<children.length; i++) {
                boolean success = deleteDirectory(new File(dir, children[i]));
                if (!success) {
                    return false;
                }
            }
        }
    
        return dir.delete();
    }
}
