### Question:
Reformatter { static String fixup(String s) { StringBuilder out = new StringBuilder(); JavaScanner scanner = new JavaScanner(s); s = scanner.string(); int len = s.length(); for (int start = 0, previous = 0, braces = 0, parens = 0, end = 0; start < len; previous = start, start = end) { end = scanner.tokenEnd(start); switch (s.charAt(start)) { case '(': parens++; break; case ')': parens--; break; case '{': braces++; break; case '}': braces--; break; case ' ': if (s.charAt(previous) != '(' && "\n.,;)".indexOf(s.charAt(end)) < 0) { out.append(' '); } continue; case '\n': if (end < len && s.charAt(end) != '\n') { if (out.length() == 0) { start++; } break; } if (parens == 0 && braces < 2 && s.charAt(previous) != '\n' && out.length() > 0) { out.append('\n'); } continue; default: break; } out.append(s, start, end); } return out.toString(); }    }### Answer:
@Test public void testSimple() { String input = "\n" + "package com.latin.declension; \n" + "\n" + "\n" + "public class Idem { \n" + " \n" + " Eadem idem ; \n" + "\n" + " Eundem eandem ( Idem eiusdem ) {\n" + "\n" + " eiusdem ( eiusdem ) ; \n" + "\n" + " eidem_eidem_eidem( ) ;\n" + "\n" + " }\n" + "\n" + "\n" + " Eodem ( Eadem eodem ) { }\n"; String output = "package com.latin.declension;\n" + "\n" + "public class Idem {\n" + "\n" + " Eadem idem;\n" + "\n" + " Eundem eandem (Idem eiusdem) {\n" + " eiusdem (eiusdem);\n" + " eidem_eidem_eidem();\n" + " }\n" + "\n" + " Eodem (Eadem eodem) { }\n"; assertEquals(output, Reformatter.fixup(input)); }
@Test public void testSpecialSpaces() { String input = "\n" + "package com.example.whatever;\n" + "\n" + "public class SomeClass {\n" + " static final String STRING = \" hello world \\n\"; \n" + " static final String STRING_WITH_QUOTES = \" \\\"quote me now \\\" \" ;\n" + " static final int INT = 23 ;\n" + " static final char QUOTE = '\"' ;\n" + " static final char QUOTE2 = '\\\"' ;\n" + "}\n"; String output = "package com.example.whatever;\n" + "\n" + "public class SomeClass {\n" + " static final String STRING = \" hello world \\n\";\n" + " static final String STRING_WITH_QUOTES = \" \\\"quote me now \\\" \";\n" + " static final int INT = 23;\n" + " static final char QUOTE = '\"';\n" + " static final char QUOTE2 = '\\\"';\n" + "}\n"; assertEquals(output, Reformatter.fixup(input)); }
@Test public void noTrailingNewline() { String input = "package com.example.whatever;\n\npublic class SomeClass {}"; String output = input + "\n"; assertEquals(output, Reformatter.fixup(input)); }