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.charset.StandardCharsets;
047import java.nio.file.Files;
048import java.nio.file.Path;
049import java.nio.file.Paths;
050import java.nio.file.StandardCopyOption;
051import java.nio.file.StandardOpenOption;
052import java.util.ArrayList;
053import java.util.List;
054import java.util.regex.Pattern;
055
056import org.hl7.fhir.utilities.filesystem.CSFile;
057import org.hl7.fhir.utilities.filesystem.ManagedFileAccess;
058
059/**
060 * Set of static helper functions to read lines from files, create files from lists of lines,
061 * read files into a single string and create files from a single string.
062 * @author Ewout
063 *
064 */
065public class TextFile {
066
067        public static List<String> readAllLines(String path) throws IOException
068        {
069          final File file = ManagedFileAccess.csfile(path);
070    return Files.readAllLines(file.toPath(), StandardCharsets.UTF_8);
071        }
072        
073        public static void writeAllLines(String path, List<String> lines) throws IOException
074        {
075          final File file = ManagedFileAccess.csfile(path);
076    Files.write(file.toPath(), lines, StandardCharsets.UTF_8);
077        }
078        
079  public static void stringToStream(final String content, final OutputStream stream) throws IOException {
080    stream.write(content.getBytes(StandardCharsets.UTF_8));
081  }
082  
083  public static byte[] stringToBytes(final String content) throws IOException {
084    return content.getBytes(StandardCharsets.UTF_8);
085  }
086  
087  public static void stringToFile(final String content, final String path) throws IOException  {
088    final File file = ManagedFileAccess.csfile(path);
089    stringToFile(content, file);
090  }
091
092
093  public static void stringToFile(final String content, final File file) throws IOException {
094    try (final OutputStream output = Files.newOutputStream(file.toPath())) {
095      output.write(content.getBytes(StandardCharsets.UTF_8));
096    }
097  }  
098  
099  public static void stringToFileWithBOM(final String content, final File file) throws IOException  {
100    try (final OutputStream output = Files.newOutputStream(file.toPath())) {
101      output.write(new byte[]{(byte)239, (byte)187, (byte)191});
102      output.write(content.getBytes(StandardCharsets.UTF_8));
103    }
104  }
105  
106  public static void stringToFileWithBOM(final String content, final String path) throws IOException  {
107    final File file = ManagedFileAccess.csfile(path);
108    stringToFileWithBOM(content, file);
109  }
110  
111
112  public static String fileToString(final File f) throws FileNotFoundException, IOException {
113    // Files.readString(Path) will fail on invalid UTF-8 byte sequences, so we use Files.readAllBytes() instead.
114    // This would happen when reading an XSLX file, for example.
115    return new String(Files.readAllBytes(f.toPath()), StandardCharsets.UTF_8);
116  }
117  
118  public static String fileToString(final String src) throws FileNotFoundException, IOException  {
119    final CSFile f = ManagedFileAccess.csfile(src);
120    if (!f.exists()) {
121      throw new IOException("File "+src+" not found");
122    }
123    return fileToString(f);
124  }
125
126  public static String streamToString(final InputStream input) throws IOException  {
127    return new String(input.readAllBytes(), StandardCharsets.UTF_8).replace("\uFEFF", "");
128  }
129
130  public static byte[] streamToBytes(final InputStream input) throws IOException  {
131    if (input == null) {
132      return null;
133    }
134    final byte[] read = input.readAllBytes();
135    input.close();
136    return read;
137  }
138
139  public static byte[] streamToBytesNoClose(final InputStream input) throws IOException  {
140    if (input == null) {
141      return null;
142    }
143    return input.readAllBytes();
144  }
145
146  public static void bytesToFile(final byte[] bytes, final String path) throws IOException {
147    try (final OutputStream sw = ManagedFileAccess.outStream(ManagedFileAccess.csfile(path))) {
148      sw.write(bytes);
149    }
150  }
151  
152  public static void bytesToFile(final byte[] bytes, final File f) throws IOException {
153    try (final OutputStream sw = ManagedFileAccess.outStream(f)) {
154      sw.write(bytes);
155    }
156  }
157  
158  public static void appendBytesToFile(final byte[] bytes, final String path) throws IOException {
159    byte[] linebreak = new byte[] {13, 10};
160    Files.write(Paths.get(path), linebreak, StandardOpenOption.APPEND);
161    Files.write(Paths.get(path), bytes, StandardOpenOption.APPEND);
162  }
163
164  public static byte[] fileToBytes(final String srcFile) throws FileNotFoundException, IOException {
165    final File f = ManagedFileAccess.csfile(srcFile);
166    return Files.readAllBytes(f.toPath());
167  }
168
169  /**
170   * 
171   * fileToBytes insists in case correctness to ensure that stuff works across linux and windows, but it's not always appropriate to check case (e.g. validator parameters)
172   * 
173   * @param srcFile
174   * @return
175   * @throws FileNotFoundException
176   * @throws IOException
177   */
178  public static byte[] fileToBytesNCS(final String srcFile) throws FileNotFoundException, IOException {
179    return Files.readAllBytes(Path.of(srcFile));
180  }
181
182  public static byte[] fileToBytes(final File file) throws FileNotFoundException, IOException {
183    return Files.readAllBytes(file.toPath());
184  }
185
186  public static String bytesToString(final byte[] bs) throws IOException {
187    return new String(bs, StandardCharsets.UTF_8);
188  }
189
190  public static String bytesToString(final byte[] bs, final boolean removeBOM) throws IOException {
191    final String read = new String(bs, StandardCharsets.UTF_8);
192    if (removeBOM)
193      return read.replace("\uFEFF", "");
194    else
195      return read;
196  }
197
198  public static void streamToFile(final InputStream stream, final String filename) throws IOException {
199    Files.copy(stream, Path.of(filename), StandardCopyOption.REPLACE_EXISTING);
200    stream.close();
201  }
202
203  public static void streamToFileNoClose(final InputStream stream, final String filename) throws IOException {
204    Files.copy(stream, Path.of(filename), StandardCopyOption.REPLACE_EXISTING);
205  }
206
207  public static String[] fileToLines(String file) throws FileNotFoundException, IOException {
208    Pattern LINE_SEP_PATTERN = Pattern.compile("\\R");
209    return LINE_SEP_PATTERN.split(fileToString(file));
210  }
211}