FormattingFiler implements Filer { @Override public JavaFileObject createSourceFile(CharSequence name, Element... originatingElements) throws IOException { return new FormattingJavaFileObject( delegate.createSourceFile(name, originatingElements), formatter, messager); } FormattingFiler(Filer delegate);  FormattingFiler(Filer delegate, @Nullable Messager messager); @Override JavaFileObject createSourceFile(CharSequence name, Element... originatingElements); @Override JavaFileObject createClassFile(CharSequence name, Element... originatingElements); @Override FileObject createResource(
      JavaFileManager.Location location,
      CharSequence pkg,
      CharSequence relativeName,
      Element... originatingElements); @Override FileObject getResource(
      JavaFileManager.Location location, CharSequence pkg, CharSequence relativeName);  }
@Test public void invalidSyntaxDoesNotThrowError() throws IOException { List<String> logMessages = new ArrayList<>(); Messager messager = new Messager() { @Override public void printMessage(javax.tools.Diagnostic.Kind kind, CharSequence msg) { logMessages.add(kind.toString() + ";" + msg); } @Override public void printMessage(javax.tools.Diagnostic.Kind kind, CharSequence msg, Element e) {} @Override public void printMessage( javax.tools.Diagnostic.Kind kind, CharSequence msg, Element e, AnnotationMirror a) {} @Override public void printMessage( javax.tools.Diagnostic.Kind kind, CharSequence msg, Element e, AnnotationMirror a, AnnotationValue v) {} }; String file = Joiner.on('\n').join("package foo;", "public class Bar {"); FormattingFiler formattingFiler = new FormattingFiler(new FakeFiler(), messager); Writer writer = formattingFiler.createSourceFile("foo.Bar").openWriter(); writer.write(file); writer.close(); assertThat(logMessages).containsExactly("NOTE;Error formatting foo.Bar"); }
@Test public void formatsFile() throws IOException { FormattingFiler formattingFiler = new FormattingFiler(new FakeFiler()); JavaFileObject sourceFile = formattingFiler.createSourceFile("foo.Bar"); try (Writer writer = sourceFile.openWriter()) { writer.write("package foo;class Bar{private String baz;\n\n\n\n}"); } assertThat(sourceFile.getCharContent(false).toString()) .isEqualTo( Joiner.on('\n') .join( "package foo;", "", "class Bar {", " private String baz;", "}", "")); }