1 package tim.prune.save.xml;
4 import java.io.FileOutputStream;
5 import java.io.IOException;
6 import java.io.OutputStreamWriter;
7 import java.nio.charset.Charset;
10 * Collection of utility functions for handling XML
12 public abstract class XmlUtils
14 /** Start of Cdata sequence */
15 private static final String CDATA_START = "<![CDATA[";
16 /** End of Cdata sequence */
17 private static final String CDATA_END = "]]>";
18 /** Cached copy of system encoding string */
19 private static String _systemEncoding = null;
22 * Fix the CDATA blocks in the given String to give valid xml
23 * @param inString String to modify
24 * @return fixed String
26 public static String fixCdata(String inString)
28 if (inString == null) return "";
29 if (inString.indexOf('<') < 0 && inString.indexOf('>') < 0) {
32 String result = inString;
33 // Remove cdata block at start if present
34 if (result.startsWith(CDATA_START)) {
35 result = result.substring(CDATA_START.length());
37 // Remove all instances of end block
38 result = result.replaceAll(CDATA_END, "");
39 // Now check whether cdata block is required
40 if (result.indexOf('<') < 0 && result.indexOf('>') < 0) {
43 return CDATA_START + result + CDATA_END;
48 * @return true if system uses UTF-8 by default
50 public static boolean isSystemUtf8()
52 String systemEncoding = getSystemEncoding();
53 return (systemEncoding != null && systemEncoding.toUpperCase().equals("UTF-8"));
57 * @return name of the system's character encoding
59 public static String getSystemEncoding()
61 if (_systemEncoding == null) {
62 _systemEncoding = determineSystemEncoding();
64 return _systemEncoding;
68 * Use a temporary file to obtain the name of the default system encoding
69 * @return name of default system encoding, or null if write failed
71 private static String determineSystemEncoding()
74 String encoding = null;
77 tempFile = File.createTempFile("gpsprune", null);
78 OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(tempFile));
79 encoding = getEncoding(writer);
82 catch (IOException e) {} // value stays null
84 if (tempFile != null && tempFile.exists()) {
85 if (!tempFile.delete()) {
86 System.err.println("Cannot delete temp file: " + tempFile.getAbsolutePath());
89 // If writing failed (eg permissions) then just ask system for default
90 if (encoding == null) encoding = Charset.defaultCharset().name();
96 * Get the default system encoding using a writer
97 * @param inWriter writer object
98 * @return string defining encoding
100 public static String getEncoding(OutputStreamWriter inWriter)
102 String encoding = inWriter.getEncoding();
104 encoding = Charset.forName(encoding).name();
106 catch (Exception e) {} // ignore failure to find encoding