String cleanupSource(String source) { if (source.isEmpty()) { return source.concat("\n"); } int lastChIdx = source.length() - 1; if (source.charAt(lastChIdx) != '\n') { // Append a newline at the end source = source.concat("\n"); } else { // Remove all newlines at the end but one while (lastChIdx >= 1) { Character ch1 = source.charAt(lastChIdx); if (ch1 == '\n' || Character.isWhitespace(ch1)) { source = source.substring(0, lastChIdx--); } else { break; } } source = source.concat("\n"); } return source; }