StringUtils escape xml/json
This commit is contained in:
parent
3170f031cc
commit
f59cbbb5ad
2 changed files with 64 additions and 2 deletions
|
@ -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; i<s.length(); i++ )
|
||||
{
|
||||
char c = s.charAt( i );
|
||||
int j = 0;
|
||||
while( j<chr.length )
|
||||
{
|
||||
if (c == chr[j])
|
||||
{
|
||||
if ( sb == null )
|
||||
{
|
||||
sb = new StringBuilder( s.substring( 0, i ) );
|
||||
}
|
||||
sb.append( esc[j] );
|
||||
break;
|
||||
}
|
||||
j++;
|
||||
}
|
||||
if ( sb != null && j==chr.length )
|
||||
{
|
||||
sb.append( c );
|
||||
}
|
||||
}
|
||||
return sb == null ? s : sb.toString();
|
||||
}
|
||||
}
|
||||
|
|
29
brouter-util/src/test/java/btools/util/StringUtilsTest.java
Normal file
29
brouter-util/src/test/java/btools/util/StringUtilsTest.java
Normal file
|
@ -0,0 +1,29 @@
|
|||
package btools.util;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
public class StringUtilsTest
|
||||
{
|
||||
private static String[] raw = new String[] { "hallo", "is 1<2 ?", "or 4>5 ?", "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<raw.length; i++ )
|
||||
{
|
||||
Assert.assertEquals( "xml encoding mismatch for raw: " + raw[i], xml[i], StringUtils.escapeXml10( raw[i] ) );
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void jsonEncodingTest()
|
||||
{
|
||||
for( int i=0; i<raw.length; i++ )
|
||||
{
|
||||
Assert.assertEquals( "json encoding mismatch for raw: " + raw[i], jsn[i], StringUtils.escapeJson( raw[i] ) );
|
||||
}
|
||||
}
|
||||
}
|
Loading…
Reference in a new issue