WebUtils { public static String replaceLeadingSpaces(final String string) { if (StringUtils.isEmpty(string)) { return string; } final StringBuilder sb = new StringBuilder(); final String[] lines = NL_REGEXP.split(string); for (final String line : lines) { if (!StringUtils.isWhitespace(line)) { String result = org.springframework.util.StringUtils.trimLeadingWhitespace(line); int removedSpacesCount = line.length() - result.length(); for (int i = 0; i < removedSpacesCount; i++) { result = NBSP + result; } sb.append(result); } else { sb.append(line); } if (lines.length > 1) { sb.append(NL); } } return sb.toString(); } private  WebUtils(); static String nl2br(final String string); static String replaceLeadingSpaces(final String string); static String extractBaseURLFromRequest(final HttpServletRequest request); static final String APPLICATION_OCTET_STREAM; static final String CONTENT_TYPE_TEXT_PLAIN; static final String CONTENT_DISPOSITION_HEADER; static final String NL; static final String NBSP; static final Pattern NL_REGEXP; }
@Test public void testReplaceLeadingSpaces() throws Exception { try { WebUtils.replaceLeadingSpaces(null); } catch (NullPointerException npe) { } assertEquals("", WebUtils.replaceLeadingSpaces("")); assertEquals("&nbsp;c", WebUtils.replaceLeadingSpaces(" c")); assertEquals("&nbsp;&nbsp;class {", WebUtils.replaceLeadingSpaces(" class {")); }
@Test public void testReplaceLeadingSpacesMultiline() throws Exception { String line = " one " + NL + " two " + NL + " " + NL + " three four" + NL; String expected = "&nbsp;one " + NL + "&nbsp;&nbsp;two " + NL + " " + NL + "&nbsp;three four" + NL; assertEquals(expected, WebUtils.replaceLeadingSpaces(line)); line = NL + " one " + NL + " two "; expected = NL + "&nbsp;one " + NL + "&nbsp;&nbsp;two " + NL; assertEquals(expected, WebUtils.replaceLeadingSpaces(line)); }