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