From f59cbbb5adcd012e180e139aa03665ff840f4fb4 Mon Sep 17 00:00:00 2001 From: Arndt Brenschede Date: Sat, 2 Nov 2019 18:27:32 +0100 Subject: [PATCH] StringUtils escape xml/json --- .../main/java/btools/util/StringUtils.java | 37 ++++++++++++++++++- .../java/btools/util/StringUtilsTest.java | 29 +++++++++++++++ 2 files changed, 64 insertions(+), 2 deletions(-) create mode 100644 brouter-util/src/test/java/btools/util/StringUtilsTest.java diff --git a/brouter-util/src/main/java/btools/util/StringUtils.java b/brouter-util/src/main/java/btools/util/StringUtils.java index f2f299b..3e8c7f8 100644 --- a/brouter-util/src/main/java/btools/util/StringUtils.java +++ b/brouter-util/src/main/java/btools/util/StringUtils.java @@ -5,12 +5,18 @@ package btools.util; */ public class StringUtils { + private static char[] xmlChr = new char[] { '&', '<', '>', '\'', '"', '\t', '\n', '\r' }; + private static String[] xmlEsc = new String[]{ "&", "<", ">", "'", """, " ", " ", " " }; + + private static char[] jsnChr = new char[] { '\'', '"', '\\', '/' }; + private static String[] jsnEsc = new String[]{ "\\'", "\\\"", "\\\\", "\\/" }; + /** * Escape a literal to put into a json document */ public static String escapeJson( String s ) { - return s; + return escape( s, jsnChr, jsnEsc ); } /** @@ -18,7 +24,34 @@ public class StringUtils */ public static String escapeXml10( String s ) { - return s; + return escape( s, xmlChr, xmlEsc ); } + private static String escape( String s, char[] chr, String[] esc ) + { + StringBuilder sb = null; + for( int i=0; i5 ?", "or 1<>2 ?", "\"hi\" 'there'" }; + private static String[] xml = new String[] { "hallo", "is 1<2 ?", "or 4>5 ?", "or 1<>2 ?", ""hi" 'there'" }; + private static String[] jsn = new String[] { "hallo", "is 1<2 ?", "or 4>5 ?", "or 1<>2 ?", "\\\"hi\\\" \\'there\\'" }; + + @Test + public void xmlEncodingTest() + { + for( int i=0; i