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.nio.file.Files;
065import java.nio.file.Paths;
066import java.nio.file.StandardOpenOption;
067import java.util.ArrayList;
068import java.util.List;
069
070/**
071 * Set of static helper functions to read lines from files, create files from lists of lines,
072 * read files into a single string and create files from a single string.
073 * @author Ewout
074 *
075 */
076public class TextFile {
077
078        public static List<String> readAllLines(String path) throws IOException
079        {
080                List<String> result = new ArrayList<String>();
081                
082                File file = new CSFile(path);
083                BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file),"UTF-8"));
084                
085                while( reader.ready() )
086                        result.add(reader.readLine());
087                
088                reader.close();
089                return result;
090        }
091        
092        public static void writeAllLines(String path, List<String> lines) throws IOException
093        {
094                File file = new CSFile(path);
095                FileOutputStream s = new FileOutputStream(file);
096                OutputStreamWriter sw = new OutputStreamWriter(s, "UTF-8");
097                for( String line : lines )
098                        sw.write(line + "\r\n");
099                
100                sw.flush();
101                s.close();
102        }
103        
104        
105  public static void stringToFile(String content, File file) throws IOException {
106    OutputStreamWriter sw = new OutputStreamWriter(new FileOutputStream(file), "UTF-8");
107    sw.write('\ufeff');  // Unicode BOM, translates to UTF-8 with the configured outputstreamwriter
108    sw.write(content);
109    sw.flush();
110    sw.close();
111  }
112  
113  public static void stringToStream(String content, OutputStream stream, boolean bom) throws IOException {
114    OutputStreamWriter sw = new OutputStreamWriter(stream, "UTF-8");
115    if (bom) {
116      sw.write('\ufeff');  // Unicode BOM, translates to UTF-8 with the configured outputstreamwriter
117    }
118    sw.write(content);
119    sw.flush();
120    sw.close();
121  }
122  
123  public static byte[] stringToBytes(String content, boolean bom) throws IOException {
124    ByteArrayOutputStream bs = new ByteArrayOutputStream();
125    OutputStreamWriter sw = new OutputStreamWriter(bs, "UTF-8");
126    if (bom)
127      sw.write('\ufeff');  // Unicode BOM, translates to UTF-8 with the configured outputstreamwriter
128    sw.write(content);
129    sw.flush();
130    sw.close();
131    return bs.toByteArray(); 
132  }
133  
134  public static void stringToFile(String content, String path) throws IOException  {
135    File file = new CSFile(path);
136    stringToFile(content, file);
137  }
138
139  public static void stringToFile(String content, File file, boolean bom) throws IOException  {
140    OutputStreamWriter sw = new OutputStreamWriter(new FileOutputStream(file), "UTF-8");
141    if (bom)
142      sw.write('\ufeff');  // Unicode BOM, translates to UTF-8 with the configured outputstreamwriter
143    sw.write(content);
144    sw.flush();
145    sw.close();
146  }
147  
148  public static void stringToFile(String content, String path, boolean bom) throws IOException  {
149    File file = new CSFile(path);
150    stringToFile(content, file, bom);
151  }
152
153  public static void stringToFileNoPrefix(String content, String path) throws IOException  {
154    File file = new CSFile(path);
155    OutputStreamWriter sw = new OutputStreamWriter(new FileOutputStream(file), "UTF-8");
156    sw.write(content);
157    sw.flush();
158    sw.close();
159  }
160
161  public static String fileToString(File f) throws FileNotFoundException, IOException {
162    return streamToString(new FileInputStream(f));
163  }
164  
165  public static String fileToString(String src) throws FileNotFoundException, IOException  {
166    return streamToString(new FileInputStream(new CSFile(src)));
167        }
168
169  public static String streamToString(InputStream input) throws IOException  {
170    InputStreamReader sr = new InputStreamReader(input, "UTF-8");    
171    StringBuilder b = new StringBuilder();
172    //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
173    int i = -1;
174    while((i = sr.read()) > -1) {
175      char c = (char) i;
176      b.append(c);
177    }
178    sr.close();
179    
180    return  b.toString().replace("\uFEFF", ""); 
181  }
182
183  public static byte[] streamToBytes(InputStream input) throws IOException  {
184    if (input== null) {
185      return null;
186    }
187    // Define a size if you have an idea of it.
188    ByteArrayOutputStream r = new ByteArrayOutputStream(2048);
189    byte[] read = new byte[512]; // Your buffer size.
190    for (int i; -1 != (i = input.read(read)); r.write(read, 0, i));
191    input.close();
192    return r.toByteArray();
193  }
194
195  public static void bytesToFile(byte[] bytes, String path) throws IOException {
196    File file = new CSFile(path);
197    OutputStream sw = new FileOutputStream(file);
198    sw.write(bytes);
199    sw.flush();
200    sw.close(); 
201  }
202  
203  public static void bytesToFile(byte[] bytes, File f) throws IOException {
204    OutputStream sw = new FileOutputStream(f);
205    sw.write(bytes);
206    sw.flush();
207    sw.close(); 
208  }
209  
210  public static void appendBytesToFile(byte[] bytes, String path) throws IOException {
211    byte[] linebreak = new byte[] {13, 10};
212    Files.write(Paths.get(path), linebreak, StandardOpenOption.APPEND);
213    Files.write(Paths.get(path), bytes, StandardOpenOption.APPEND);
214  }
215
216  public static byte[] fileToBytes(String srcFile) throws FileNotFoundException, IOException {
217    return streamToBytes(new FileInputStream(new CSFile(srcFile)));
218  }
219
220  /**
221   * 
222   * 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)
223   * 
224   * @param srcFile
225   * @return
226   * @throws FileNotFoundException
227   * @throws IOException
228   */
229  public static byte[] fileToBytesNCS(String srcFile) throws FileNotFoundException, IOException {
230    return streamToBytes(new FileInputStream(new File(srcFile)));
231  }
232
233  public static byte[] fileToBytes(File file) throws FileNotFoundException, IOException {
234    return streamToBytes(new FileInputStream(file));
235  }
236
237  public static String bytesToString(byte[] bs) throws IOException {
238    return streamToString(new ByteArrayInputStream(bs));
239  }
240
241  public static String bytesToString(byte[] bs, boolean removeBOM) throws IOException {
242    if (removeBOM)
243      return streamToString(new ByteArrayInputStream(bs)).replace("\uFEFF", "");
244    else
245      return streamToString(new ByteArrayInputStream(bs));
246  }
247
248
249}