001package org.hl7.fhir.convertors.misc;
002
003import java.io.File;
004import java.io.FileInputStream;
005import java.io.FileNotFoundException;
006import java.io.IOException;
007import java.io.InputStream;
008import java.io.InputStreamReader;
009
010import org.hl7.fhir.utilities.FileUtilities;
011import org.hl7.fhir.utilities.Utilities;
012import org.hl7.fhir.utilities.filesystem.ManagedFileAccess;
013
014@SuppressWarnings("checkstyle:systemout")
015public class BOMRemover {
016
017  public static void main(String[] args) throws FileNotFoundException, IOException {
018    new BOMRemover().execute(ManagedFileAccess.file(args[0]));
019
020  }
021
022  private void execute(File f) throws FileNotFoundException, IOException {
023    if (f.isDirectory()) {
024      for (File file : f.listFiles()) {
025        execute(file);
026      }
027    } else if (f.getName().endsWith(".java")) {
028      String src = fileToString(f);
029      String s = Utilities.stripBOM(src);
030      if (!s.equals(src)) {
031        System.out.println("Remove BOM from "+f.getAbsolutePath());
032        FileUtilities.stringToFile(s, f);
033      }
034    }
035  }
036
037
038  public static String fileToString(File f) throws FileNotFoundException, IOException {
039    return streamToString(new FileInputStream(f));
040  }
041  
042  public static String streamToString(InputStream input) throws IOException  {
043    InputStreamReader sr = new InputStreamReader(input, "UTF-8");    
044    StringBuilder b = new StringBuilder();
045    //while (sr.ready()) { Commented out by Claude Nanjo (1/14/2014) - sr.ready() always returns false - please remove if change does not impact other areas of codebase
046    int i = -1;
047    while((i = sr.read()) > -1) {
048      char c = (char) i;
049      b.append(c);
050    }
051    sr.close();
052    
053    return  b.toString(); 
054  }
055
056}