001package org.hl7.fhir.utilities.xml; 002 003import java.io.BufferedReader; 004import java.io.FileInputStream; 005import java.io.FileOutputStream; 006import java.io.IOException; 007import java.io.InputStream; 008import java.io.InputStreamReader; 009import java.io.OutputStream; 010import java.nio.charset.StandardCharsets; 011 012import org.hl7.fhir.utilities.filesystem.ManagedFileAccess; 013 014public class XmlEscaper { 015 016 private InputStream source; 017 private OutputStream target; 018 019 020 protected XmlEscaper(InputStream source, OutputStream target) { 021 super(); 022 this.source = source; 023 this.target = target; 024 } 025 026 public static void convert(InputStream source, OutputStream target) throws IOException { 027 XmlEscaper self = new XmlEscaper(source, target); 028 self.process(); 029 } 030 031 public static void convert(String source, String target) throws IOException { 032 FileOutputStream fs = ManagedFileAccess.outStream(target); 033 try { 034 convertAndClose(ManagedFileAccess.inStream(source), fs); 035 } finally { 036 fs.close(); 037 } 038 } 039 040 public static void convertAndClose(InputStream source, OutputStream target) throws IOException { 041 XmlEscaper self = new XmlEscaper(source, target); 042 self.process(); 043 source.close(); 044 target.close(); 045 } 046 047 public InputStream getSource() { 048 return source; 049 } 050 public void setSource(InputStream source) { 051 this.source = source; 052 } 053 public OutputStream getTarget() { 054 return target; 055 } 056 public void setTarget(OutputStream target) { 057 this.target = target; 058 } 059 060 public void process() throws IOException { 061 BufferedReader buffer = new BufferedReader(new InputStreamReader(source)); 062 int i = 0; 063 while ((i = buffer.read()) != -1) { 064 char c = (char) i; 065 if (c == '<') 066 write("<"); 067 else if (c == '>') 068 write(">"); 069 else if (c == '&') 070 write("&"); 071 else if (c == '"') 072 write("""); 073 else 074 target.write((byte) i); 075 } 076 } 077 078 private void write(String s) throws IOException { 079 target.write(s.getBytes(StandardCharsets.UTF_8)); 080 } 081 082} 083