001package org.hl7.fhir.utilities;
002
003/*
004  Copyright (c) 2011+, HL7, Inc.
005  All rights reserved.
006  
007  Redistribution and use in source and binary forms, with or without modification, 
008  are permitted provided that the following conditions are met:
009    
010   * Redistributions of source code must retain the above copyright notice, this 
011     list of conditions and the following disclaimer.
012   * Redistributions in binary form must reproduce the above copyright notice, 
013     this list of conditions and the following disclaimer in the documentation 
014     and/or other materials provided with the distribution.
015   * Neither the name of HL7 nor the names of its contributors may be used to 
016     endorse or promote products derived from this software without specific 
017     prior written permission.
018  
019  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 
020  ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 
021  WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 
022  IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, 
023  INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT 
024  NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR 
025  PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, 
026  WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 
027  ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 
028  POSSIBILITY OF SUCH DAMAGE.
029  
030 */
031
032
033
034import java.io.BufferedReader;
035import java.io.ByteArrayInputStream;
036import java.io.ByteArrayOutputStream;
037import java.io.File;
038import java.io.FileInputStream;
039import java.io.FileNotFoundException;
040import java.io.FileOutputStream;
041import java.io.IOException;
042import java.io.InputStream;
043import java.io.InputStreamReader;
044import java.io.OutputStream;
045import java.io.OutputStreamWriter;
046import java.nio.file.Files;
047import java.nio.file.Paths;
048import java.nio.file.StandardOpenOption;
049import java.util.ArrayList;
050import java.util.List;
051
052/**
053 * Set of static helper functions to read lines from files, create files from lists of lines,
054 * read files into a single string and create files from a single string.
055 * @author Ewout
056 *
057 */
058public class TextFile {
059
060        public static List<String> readAllLines(String path) throws IOException
061        {
062                List<String> result = new ArrayList<String>();
063                
064                File file = new CSFile(path);
065                BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file),"UTF-8"));
066                
067                while( reader.ready() )
068                        result.add(reader.readLine());
069                
070                reader.close();
071                return result;
072        }
073        
074        public static void writeAllLines(String path, List<String> lines) throws IOException
075        {
076                File file = new CSFile(path);
077                FileOutputStream s = new FileOutputStream(file);
078                OutputStreamWriter sw = new OutputStreamWriter(s, "UTF-8");
079                for( String line : lines )
080                        sw.write(line + "\r\n");
081                
082                sw.flush();
083                s.close();
084        }
085        
086        
087  public static void stringToFile(String content, File file) throws IOException {
088    OutputStreamWriter sw = new OutputStreamWriter(new FileOutputStream(file), "UTF-8");
089    sw.write('\ufeff');  // Unicode BOM, translates to UTF-8 with the configured outputstreamwriter
090    sw.write(content);
091    sw.flush();
092    sw.close();
093  }
094  
095  public static void stringToStream(String content, OutputStream stream, boolean bom) throws IOException {
096    OutputStreamWriter sw = new OutputStreamWriter(stream, "UTF-8");
097    if (bom) {
098      sw.write('\ufeff');  // Unicode BOM, translates to UTF-8 with the configured outputstreamwriter
099    }
100    sw.write(content);
101    sw.flush();
102    sw.close();
103  }
104  
105  public static byte[] stringToBytes(String content, boolean bom) throws IOException {
106    ByteArrayOutputStream bs = new ByteArrayOutputStream();
107    OutputStreamWriter sw = new OutputStreamWriter(bs, "UTF-8");
108    if (bom)
109      sw.write('\ufeff');  // Unicode BOM, translates to UTF-8 with the configured outputstreamwriter
110    sw.write(content);
111    sw.flush();
112    sw.close();
113    return bs.toByteArray(); 
114  }
115  
116  public static void stringToFile(String content, String path) throws IOException  {
117    File file = new CSFile(path);
118    stringToFile(content, file);
119  }
120
121  public static void stringToFile(String content, File file, boolean bom) throws IOException  {
122    OutputStreamWriter sw = new OutputStreamWriter(new FileOutputStream(file), "UTF-8");
123    if (bom)
124      sw.write('\ufeff');  // Unicode BOM, translates to UTF-8 with the configured outputstreamwriter
125    sw.write(content);
126    sw.flush();
127    sw.close();
128  }
129  
130  public static void stringToFile(String content, String path, boolean bom) throws IOException  {
131    File file = new CSFile(path);
132    stringToFile(content, file, bom);
133  }
134
135  public static void stringToFileNoPrefix(String content, String path) throws IOException  {
136    File file = new CSFile(path);
137    OutputStreamWriter sw = new OutputStreamWriter(new FileOutputStream(file), "UTF-8");
138    sw.write(content);
139    sw.flush();
140    sw.close();
141  }
142
143  public static String fileToString(File f) throws FileNotFoundException, IOException {
144    return streamToString(new FileInputStream(f));
145  }
146  
147  public static String fileToString(String src) throws FileNotFoundException, IOException  {
148    return streamToString(new FileInputStream(new CSFile(src)));
149        }
150
151  public static String streamToString(InputStream input) throws IOException  {
152    InputStreamReader sr = new InputStreamReader(input, "UTF-8");    
153    StringBuilder b = new StringBuilder();
154    //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
155    int i = -1;
156    while((i = sr.read()) > -1) {
157      char c = (char) i;
158      b.append(c);
159    }
160    sr.close();
161    
162    return  b.toString().replace("\uFEFF", ""); 
163  }
164
165  public static byte[] streamToBytes(InputStream input) throws IOException  {
166    if (input== null) {
167      return null;
168    }
169    ByteArrayOutputStream r = new ByteArrayOutputStream(2048);
170    byte[] read = new byte[512]; 
171    for (int i; -1 != (i = input.read(read)); r.write(read, 0, i));
172    input.close();
173    return r.toByteArray();
174  }
175
176  public static byte[] streamToBytesNoClose(InputStream input) throws IOException  {
177    if (input== null) {
178      return null;
179    }
180    ByteArrayOutputStream r = new ByteArrayOutputStream(2048);
181    byte[] read = new byte[512]; 
182    for (int i; -1 != (i = input.read(read)); r.write(read, 0, i));
183    return r.toByteArray();
184  }
185
186  public static void bytesToFile(byte[] bytes, String path) throws IOException {
187    File file = new CSFile(path);
188    OutputStream sw = new FileOutputStream(file);
189    sw.write(bytes);
190    sw.flush();
191    sw.close(); 
192  }
193  
194  public static void bytesToFile(byte[] bytes, File f) throws IOException {
195    OutputStream sw = new FileOutputStream(f);
196    sw.write(bytes);
197    sw.flush();
198    sw.close(); 
199  }
200  
201  public static void appendBytesToFile(byte[] bytes, String path) throws IOException {
202    byte[] linebreak = new byte[] {13, 10};
203    Files.write(Paths.get(path), linebreak, StandardOpenOption.APPEND);
204    Files.write(Paths.get(path), bytes, StandardOpenOption.APPEND);
205  }
206
207  public static byte[] fileToBytes(String srcFile) throws FileNotFoundException, IOException {
208    return streamToBytes(new FileInputStream(new CSFile(srcFile)));
209  }
210
211  /**
212   * 
213   * fileToBytes insists in case correctness to ensure that stuff works across linux and windows, but it's not always appropriate to ceheck case (e.g. validator parameters)
214   * 
215   * @param srcFile
216   * @return
217   * @throws FileNotFoundException
218   * @throws IOException
219   */
220  public static byte[] fileToBytesNCS(String srcFile) throws FileNotFoundException, IOException {
221    return streamToBytes(new FileInputStream(new File(srcFile)));
222  }
223
224  public static byte[] fileToBytes(File file) throws FileNotFoundException, IOException {
225    return streamToBytes(new FileInputStream(file));
226  }
227
228  public static String bytesToString(byte[] bs) throws IOException {
229    return streamToString(new ByteArrayInputStream(bs));
230  }
231
232  public static String bytesToString(byte[] bs, boolean removeBOM) throws IOException {
233    if (removeBOM)
234      return streamToString(new ByteArrayInputStream(bs)).replace("\uFEFF", "");
235    else
236      return streamToString(new ByteArrayInputStream(bs));
237  }
238
239  public static void streamToFile(InputStream stream, String filename) throws IOException {
240    byte[] cnt = streamToBytes(stream);
241    bytesToFile(cnt, filename);
242  }
243
244  public static void streamToFileNoClose(InputStream stream, String filename) throws IOException {
245    byte[] cnt = streamToBytesNoClose(stream);
246    bytesToFile(cnt, filename);
247  }
248}