StringUtils { public static String stripControlCharacters(String rawValue) { if (rawValue == null) { return null; } String value = replaceEntities(rawValue); boolean hasControlChars = false; for (int i = value.length() - 1; i >= 0; i--) { if (Character.isISOControl(value.charAt(i))) { hasControlChars = true; break; } } if (!hasControlChars) { return value; } StringBuilder buf = new StringBuilder(value.length()); int i = 0; for (; i < value.length(); i++) { if (!Character.isISOControl(value.charAt(i))) { break; } } boolean suppressingControlChars = false; for (; i < value.length(); i++) { if (Character.isISOControl(value.charAt(i))) { suppressingControlChars = true; continue; } else { if (suppressingControlChars) { suppressingControlChars = false; buf.append(' '); } buf.append(value.charAt(i)); } } return buf.toString(); }  static byte[] getUtf8Bytes(String input); static String stripControlCharacters(String rawValue);  }
@Test public void testStripCRLF() { String lineSep = System.getProperty("line.separator"); String testStringWithLineSep = "foo" + lineSep + "bar"; String testString = "abc\n\rdef"; String anotherString = "abc\"def&hij<klm>"; assertTrue(testString.indexOf('\n') > 0); assertTrue(testString.indexOf('\r') > 0); String processedString = StringUtils.stripControlCharacters(testString); String processedTest2 = StringUtils.stripControlCharacters(testStringWithLineSep); String processedAnotherString = StringUtils.stripControlCharacters(anotherString); assertTrue(processedString.indexOf('\n') == -1); assertTrue(processedString.indexOf('\r') == -1); assertTrue(processedTest2.indexOf(lineSep) == -1); assertTrue(processedAnotherString.indexOf('"') == -1); assertTrue(processedAnotherString.indexOf('<') == -1); assertTrue(processedAnotherString.indexOf('>') == -1); }