modifiers,
String initialValue) throws IOException {
indent();
emitModifiers(modifiers);
emitCompressedType(type);
out.write(" ");
out.write(name);
if (initialValue != null) {
out.write(" =");
if (!initialValue.startsWith("\n")) {
out.write(" ");
}
String[] lines = initialValue.split("\n", -1);
out.write(lines[0]);
for (int i = 1; i < lines.length; i++) {
out.write("\n");
hangingIndent();
out.write(lines[i]);
}
}
out.write(";\n");
return this;
}
/**
* Emit a method declaration.
*
* A {@code null} return type may be used to indicate a constructor, but
* {@link #beginConstructor(Set, String...)} should be preferred. This behavior may be removed in
* a future release.
*
* @param returnType the method's return type, or null for constructors
* @param name the method name, or the fully qualified class name for constructors.
* @param modifiers the set of modifiers to be applied to the method
* @param parameters alternating parameter types and names.
*/
public JavaWriter beginMethod(String returnType, String name, Set modifiers,
String... parameters) throws IOException {
return beginMethod(returnType, name, modifiers, Arrays.asList(parameters), null);
}
/**
* Emit a method declaration.
*
* A {@code null} return type may be used to indicate a constructor, but
* {@link #beginConstructor(Set, List, List)} should be preferred. This behavior may be removed in
* a future release.
*
* @param returnType the method's return type, or null for constructors.
* @param name the method name, or the fully qualified class name for constructors.
* @param modifiers the set of modifiers to be applied to the method
* @param parameters alternating parameter types and names.
* @param throwsTypes the classes to throw, or null for no throws clause.
*/
public JavaWriter beginMethod(String returnType, String name, Set modifiers,
List parameters, List throwsTypes) throws IOException {
indent();
emitModifiers(modifiers);
if (returnType != null) {
emitCompressedType(returnType);
out.write(" ");
out.write(name);
} else {
emitCompressedType(name);
}
out.write("(");
if (parameters != null) {
for (int p = 0; p < parameters.size();) {
if (p != 0) {
out.write(", ");
}
emitCompressedType(parameters.get(p++));
out.write(" ");
emitCompressedType(parameters.get(p++));
}
}
out.write(")");
if (throwsTypes != null && throwsTypes.size() > 0) {
out.write("\n");
indent();
out.write(" throws ");
for (int i = 0; i < throwsTypes.size(); i++) {
if (i != 0) {
out.write(", ");
}
emitCompressedType(throwsTypes.get(i));
}
}
if (modifiers.contains(ABSTRACT) || Scope.INTERFACE_DECLARATION.equals(scopes.peek())) {
out.write(";\n");
scopes.push(Scope.ABSTRACT_METHOD);
} else {
out.write(" {\n");
scopes.push(returnType == null ? Scope.CONSTRUCTOR : Scope.NON_ABSTRACT_METHOD);
}
return this;
}
public JavaWriter beginConstructor(Set modifiers, String... parameters)
throws IOException {
beginMethod(null, rawType(types.peekFirst()), modifiers, parameters);
return this;
}
public JavaWriter beginConstructor(Set modifiers,
List parameters, List throwsTypes)
throws IOException {
beginMethod(null, rawType(types.peekFirst()), modifiers, parameters, throwsTypes);
return this;
}
/** Emits some Javadoc comments with line separated by {@code \n}. */
public JavaWriter emitJavadoc(String javadoc, Object... params) throws IOException {
String formatted = String.format(javadoc, params);
indent();
out.write("/**\n");
for (String line : formatted.split("\n")) {
indent();
out.write(" *");
if (!line.isEmpty()) {
out.write(" ");
out.write(line);
}
out.write("\n");
}
indent();
out.write(" */\n");
return this;
}
/** Emits a single line comment. */
public JavaWriter emitSingleLineComment(String comment, Object... args) throws IOException {
indent();
out.write("// ");
out.write(String.format(comment, args));
out.write("\n");
return this;
}
public JavaWriter emitEmptyLine() throws IOException {
out.write("\n");
return this;
}
public JavaWriter emitEnumValue(String name) throws IOException {
indent();
out.write(name);
out.write(",\n");
return this;
}
/**
* A simple switch to emit the proper enum depending if its last causing it to be terminated
* by a semi-colon ({@code ;}).
*/
public JavaWriter emitEnumValue(String name, boolean isLast) throws IOException {
return isLast ? emitLastEnumValue(name) : emitEnumValue(name);
}
private JavaWriter emitLastEnumValue(String name) throws IOException {
indent();
out.write(name);
out.write(";\n");
return this;
}
/** Emit a list of enum values followed by a semi-colon ({@code ;}). */
public JavaWriter emitEnumValues(Iterable names) throws IOException {
Iterator iterator = names.iterator();
while (iterator.hasNext()) {
String name = iterator.next();
if (iterator.hasNext()) {
emitEnumValue(name);
} else {
emitLastEnumValue(name);
}
}
return this;
}
/** Equivalent to {@code annotation(annotation, emptyMap())}. */
public JavaWriter emitAnnotation(String annotation) throws IOException {
return emitAnnotation(annotation, Collections.emptyMap());
}
/** Equivalent to {@code annotation(annotationType.getName(), emptyMap())}. */
public JavaWriter emitAnnotation(Class extends Annotation> annotationType) throws IOException {
return emitAnnotation(type(annotationType), Collections.emptyMap());
}
/**
* Annotates the next element with {@code annotationType} and a {@code value}.
*
* @param value an object used as the default (value) parameter of the annotation. The value will
* be encoded using Object.toString(); use {@link #stringLiteral} for String values. Object
* arrays are written one element per line.
*/
public JavaWriter emitAnnotation(Class extends Annotation> annotationType, Object value)
throws IOException {
return emitAnnotation(type(annotationType), value);
}
/**
* Annotates the next element with {@code annotation} and a {@code value}.
*
* @param value an object used as the default (value) parameter of the annotation. The value will
* be encoded using Object.toString(); use {@link #stringLiteral} for String values. Object
* arrays are written one element per line.
*/
public JavaWriter emitAnnotation(String annotation, Object value) throws IOException {
indent();
out.write("@");
emitCompressedType(annotation);
out.write("(");
emitAnnotationValue(value);
out.write(")");
out.write("\n");
return this;
}
/** Equivalent to {@code annotation(annotationType.getName(), attributes)}. */
public JavaWriter emitAnnotation(Class extends Annotation> annotationType,
Map attributes) throws IOException {
return emitAnnotation(type(annotationType), attributes);
}
/**
* Annotates the next element with {@code annotation} and {@code attributes}.
*
* @param attributes a map from annotation attribute names to their values. Values are encoded
* using Object.toString(); use {@link #stringLiteral} for String values. Object arrays are
* written one element per line.
*/
public JavaWriter emitAnnotation(String annotation, Map attributes)
throws IOException {
indent();
out.write("@");
emitCompressedType(annotation);
switch (attributes.size()) {
case 0:
break;
case 1:
Entry onlyEntry = attributes.entrySet().iterator().next();
out.write("(");
if (!"value".equals(onlyEntry.getKey())) {
out.write(onlyEntry.getKey());
out.write(" = ");
}
emitAnnotationValue(onlyEntry.getValue());
out.write(")");
break;
default:
boolean split = attributes.size() > MAX_SINGLE_LINE_ATTRIBUTES
|| containsArray(attributes.values());
out.write("(");
scopes.push(Scope.ANNOTATION_ATTRIBUTE);
String separator = split ? "\n" : "";
for (Map.Entry entry : attributes.entrySet()) {
out.write(separator);
separator = split ? ",\n" : ", ";
if (split) {
indent();
}
out.write(entry.getKey());
out.write(" = ");
Object value = entry.getValue();
emitAnnotationValue(value);
}
popScope(Scope.ANNOTATION_ATTRIBUTE);
if (split) {
out.write("\n");
indent();
}
out.write(")");
break;
}
out.write("\n");
return this;
}
private boolean containsArray(Collection> values) {
for (Object value : values) {
if (value instanceof Object[]) {
return true;
}
}
return false;
}
/**
* Writes a single annotation value. If the value is an array, each element in the array will be
* written to its own line.
*/
private JavaWriter emitAnnotationValue(Object value) throws IOException {
if (value instanceof Object[]) {
out.write("{");
boolean firstValue = true;
scopes.push(Scope.ANNOTATION_ARRAY_VALUE);
for (Object o : ((Object[]) value)) {
if (firstValue) {
firstValue = false;
out.write("\n");
} else {
out.write(",\n");
}
indent();
out.write(o.toString());
}
popScope(Scope.ANNOTATION_ARRAY_VALUE);
out.write("\n");
indent();
out.write("}");
} else {
out.write(value.toString());
}
return this;
}
/**
* @param pattern a code pattern like "int i = %s". Newlines will be further indented. Should not
* contain trailing semicolon.
*/
public JavaWriter emitStatement(String pattern, Object... args) throws IOException {
checkInMethod();
String[] lines = String.format(pattern, args).split("\n", -1);
indent();
out.write(lines[0]);
for (int i = 1; i < lines.length; i++) {
out.write("\n");
hangingIndent();
out.write(lines[i]);
}
out.write(";\n");
return this;
}
/**
* @param controlFlow the control flow construct and its code, such as "if (foo == 5)". Shouldn't
* contain braces or newline characters.
*/
// NOTE: This method is for binary compatibility with previous versions.
public JavaWriter beginControlFlow(String controlFlow) throws IOException {
return beginControlFlow(controlFlow, new Object[0]);
}
/**
* @param controlFlow the control flow construct and its code, such as "if (foo == 5)". Shouldn't
* contain braces or newline characters.
*/
public JavaWriter beginControlFlow(String controlFlow, Object... args) throws IOException {
checkInMethod();
indent();
out.write(String.format(controlFlow, args));
out.write(" {\n");
scopes.push(Scope.CONTROL_FLOW);
return this;
}
/**
* @param controlFlow the control flow construct and its code, such as "else if (foo == 10)".
* Shouldn't contain braces or newline characters.
*/
// NOTE: This method is for binary compatibility with previous versions.
public JavaWriter nextControlFlow(String controlFlow) throws IOException {
return nextControlFlow(controlFlow, new Object[0]);
}
/**
* @param controlFlow the control flow construct and its code, such as "else if (foo == 10)".
* Shouldn't contain braces or newline characters.
*/
public JavaWriter nextControlFlow(String controlFlow, Object... args) throws IOException {
popScope(Scope.CONTROL_FLOW);
indent();
scopes.push(Scope.CONTROL_FLOW);
out.write("} ");
out.write(String.format(controlFlow, args));
out.write(" {\n");
return this;
}
public JavaWriter endControlFlow() throws IOException {
return endControlFlow(null);
}
/**
* @param controlFlow the optional control flow construct and its code, such as
* "while(foo == 20)". Only used for "do/while" control flows.
*/
// NOTE: This method is for binary compatibility with previous versions.
public JavaWriter endControlFlow(String controlFlow) throws IOException {
return endControlFlow(controlFlow, new Object[0]);
}
/**
* @param controlFlow the optional control flow construct and its code, such as
* "while(foo == 20)". Only used for "do/while" control flows.
*/
public JavaWriter endControlFlow(String controlFlow, Object... args) throws IOException {
popScope(Scope.CONTROL_FLOW);
indent();
if (controlFlow != null) {
out.write("} ");
out.write(String.format(controlFlow, args));
out.write(";\n");
} else {
out.write("}\n");
}
return this;
}
/** Completes the current method declaration. */
public JavaWriter endMethod() throws IOException {
Scope popped = scopes.pop();
// support calling a constructor a "method" to support the legacy code
if (popped == Scope.NON_ABSTRACT_METHOD || popped == Scope.CONSTRUCTOR) {
indent();
out.write("}\n");
} else if (popped != Scope.ABSTRACT_METHOD) {
throw new IllegalStateException();
}
return this;
}
/** Completes the current constructor declaration. */
public JavaWriter endConstructor() throws IOException {
popScope(Scope.CONSTRUCTOR);
indent();
out.write("}\n");
return this;
}
/**
* Returns the string literal representing {@code data}, including wrapping quotes.
*
* @deprecated use {@link StringLiteral} and its {@link StringLiteral#literal()} method instead.
*/
@Deprecated
public static String stringLiteral(String data) {
return StringLiteral.forValue(data).literal();
}
/** Build a string representation of a type and optionally its generic type arguments. */
public static String type(Class> raw, String... parameters) {
if (parameters.length == 0) {
return raw.getCanonicalName();
}
if (raw.getTypeParameters().length != parameters.length) {
throw new IllegalArgumentException();
}
StringBuilder result = new StringBuilder();
result.append(raw.getCanonicalName());
result.append("<");
result.append(parameters[0]);
for (int i = 1; i < parameters.length; i++) {
result.append(", ");
result.append(parameters[i]);
}
result.append(">");
return result.toString();
}
/** Build a string representation of the raw type for a (optionally generic) type. */
public static String rawType(String type) {
int lessThanIndex = type.indexOf('<');
if (lessThanIndex != -1) {
return type.substring(0, lessThanIndex);
}
return type;
}
@Override public void close() throws IOException {
out.close();
}
/** Emits the modifiers to the writer. */
private void emitModifiers(Set modifiers) throws IOException {
if (modifiers.isEmpty()) {
return;
}
// Use an EnumSet to ensure the proper ordering
if (!(modifiers instanceof EnumSet)) {
modifiers = EnumSet.copyOf(modifiers);
}
for (Modifier modifier : modifiers) {
out.append(modifier.toString()).append(' ');
}
}
private void indent() throws IOException {
for (int i = 0, count = scopes.size(); i < count; i++) {
out.write(indent);
}
}
private void hangingIndent() throws IOException {
for (int i = 0, count = scopes.size() + 2; i < count; i++) {
out.write(indent);
}
}
private static final EnumSet METHOD_SCOPES = EnumSet.of(
Scope.NON_ABSTRACT_METHOD, Scope.CONSTRUCTOR, Scope.CONTROL_FLOW, Scope.INITIALIZER);
private void checkInMethod() {
if (!METHOD_SCOPES.contains(scopes.peekFirst())) {
throw new IllegalArgumentException();
}
}
private void popScope(Scope... expected) {
if (!EnumSet.copyOf(Arrays.asList(expected)).contains(scopes.pop())) {
throw new IllegalStateException();
}
}
private enum Scope {
TYPE_DECLARATION,
INTERFACE_DECLARATION,
ABSTRACT_METHOD,
NON_ABSTRACT_METHOD,
CONSTRUCTOR,
CONTROL_FLOW,
ANNOTATION_ATTRIBUTE,
ANNOTATION_ARRAY_VALUE,
INITIALIZER
}
}
javawriter-2.5.1/src/main/java/com/squareup/javawriter/StringLiteral.java 0000664 0000000 0000000 00000004106 12551715567 0026577 0 ustar 00root root 0000000 0000000 // Copyright 2014 Square, Inc.
package com.squareup.javawriter;
import java.util.Formatter;
/**
* Represents a string literal as found in Java source code.
*/
public final class StringLiteral {
/** Returns a new {@link StringLiteral} instance for the intended value of the literal. */
public static StringLiteral forValue(String value) {
return new StringLiteral(value, stringLiteral(value));
}
/** Returns the string literal representing {@code data}, including wrapping quotes. */
private static String stringLiteral(String value) {
StringBuilder result = new StringBuilder();
result.append('"');
for (int i = 0; i < value.length(); i++) {
char c = value.charAt(i);
switch (c) {
case '"':
result.append("\\\"");
break;
case '\\':
result.append("\\\\");
break;
case '\b':
result.append("\\b");
break;
case '\t':
result.append("\\t");
break;
case '\n':
result.append("\\n");
break;
case '\f':
result.append("\\f");
break;
case '\r':
result.append("\\r");
break;
default:
if (Character.isISOControl(c)) {
new Formatter(result).format("\\u%04x", (int) c);
} else {
result.append(c);
}
}
}
result.append('"');
return result.toString();
}
private final String value;
private final String literal;
private StringLiteral(String value, String literal) {
this.value = value;
this.literal = literal;
}
public String value() {
return value;
}
public String literal() {
return literal;
}
@Override
public String toString() {
return literal;
}
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
} else if (obj instanceof StringLiteral) {
return this.value.equals(((StringLiteral) obj).value);
} else {
return false;
}
}
@Override
public int hashCode() {
return value.hashCode();
}
}
javawriter-2.5.1/src/test/ 0000775 0000000 0000000 00000000000 12551715567 0015461 5 ustar 00root root 0000000 0000000 javawriter-2.5.1/src/test/java/ 0000775 0000000 0000000 00000000000 12551715567 0016402 5 ustar 00root root 0000000 0000000 javawriter-2.5.1/src/test/java/com/ 0000775 0000000 0000000 00000000000 12551715567 0017160 5 ustar 00root root 0000000 0000000 javawriter-2.5.1/src/test/java/com/example/ 0000775 0000000 0000000 00000000000 12551715567 0020613 5 ustar 00root root 0000000 0000000 javawriter-2.5.1/src/test/java/com/example/Binding.java 0000664 0000000 0000000 00000000121 12551715567 0023022 0 ustar 00root root 0000000 0000000 // Copyright 2013 Square, Inc.
package com.example;
public class Binding {
}
javawriter-2.5.1/src/test/java/com/squareup/ 0000775 0000000 0000000 00000000000 12551715567 0021025 5 ustar 00root root 0000000 0000000 javawriter-2.5.1/src/test/java/com/squareup/javawriter/ 0000775 0000000 0000000 00000000000 12551715567 0023203 5 ustar 00root root 0000000 0000000 javawriter-2.5.1/src/test/java/com/squareup/javawriter/JavaWriterTest.java 0000664 0000000 0000000 00000101555 12551715567 0026773 0 ustar 00root root 0000000 0000000 // Copyright 2013 Square, Inc.
package com.squareup.javawriter;
import com.example.Binding;
import java.io.IOException;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.EnumSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.lang.model.element.Modifier;
import org.junit.Test;
import static javax.lang.model.element.Modifier.ABSTRACT;
import static javax.lang.model.element.Modifier.FINAL;
import static javax.lang.model.element.Modifier.PRIVATE;
import static javax.lang.model.element.Modifier.PUBLIC;
import static javax.lang.model.element.Modifier.STATIC;
import static org.fest.assertions.api.Assertions.assertThat;
import static org.fest.assertions.api.Assertions.failBecauseExceptionWasNotThrown;
public final class JavaWriterTest {
private final StringWriter stringWriter = new StringWriter();
private final JavaWriter javaWriter = new JavaWriter(stringWriter);
@Test public void typeDeclaration() throws IOException {
javaWriter.emitPackage("com.squareup");
javaWriter.beginType("com.squareup.Foo", "class", EnumSet.of(PUBLIC, FINAL));
javaWriter.endType();
assertCode(""
+ "package com.squareup;\n"
+ "\n"
+ "public final class Foo {\n"
+ "}\n");
}
@Test public void enumDeclaration() throws IOException {
javaWriter.emitPackage("com.squareup");
javaWriter.beginType("com.squareup.Foo", "enum", EnumSet.of(PUBLIC));
javaWriter.emitEnumValue("BAR");
javaWriter.emitEnumValue("BAZ");
javaWriter.endType();
assertCode(""
+ "package com.squareup;\n"
+ "\n"
+ "public enum Foo {\n"
+ " BAR,\n"
+ " BAZ,\n"
+ "}\n");
}
@Test public void enumDeclarationWithMethod() throws IOException{
javaWriter.emitPackage("com.squareup");
javaWriter.beginType("com.squareup.Foo", "enum", EnumSet.of(PUBLIC));
javaWriter.emitEnumValues(Arrays.asList("BAR", "BAZ"));
javaWriter.beginMethod("void", "foo", EnumSet.of(PUBLIC));
javaWriter.endMethod();
javaWriter.endType();
assertCode(""
+ "package com.squareup;\n"
+ "\n"
+ "public enum Foo {\n"
+ " BAR,\n"
+ " BAZ;\n"
+ " public void foo() {\n"
+ " }\n"
+ "}\n");
}
@Test public void enumDeclarationWithAnnotationAndMethod() throws IOException{
javaWriter.emitPackage("com.squareup");
javaWriter.beginType("com.squareup.Foo", "enum", EnumSet.of(PUBLIC));
List list = Arrays.asList("BAR", "BAZ");
int index = 0;
for (Iterator i = list.iterator(); i.hasNext(); ) {
javaWriter.emitAnnotation("ProtoEnum", index);
javaWriter.emitEnumValue(i.next(), !i.hasNext());
index++;
}
javaWriter.beginMethod("void", "foo", EnumSet.of(PUBLIC));
javaWriter.endMethod();
javaWriter.endType();
assertCode(""
+ "package com.squareup;\n"
+ "\n"
+ "public enum Foo {\n"
+ " @ProtoEnum(0)\n"
+ " BAR,\n"
+ " @ProtoEnum(1)\n"
+ " BAZ;\n"
+ " public void foo() {\n"
+ " }\n"
+ "}\n");
}
@Test public void fieldDeclaration() throws IOException {
javaWriter.emitPackage("com.squareup");
javaWriter.beginType("com.squareup.Foo", "class");
javaWriter.emitField("java.lang.String", "string", EnumSet.of(PRIVATE, STATIC));
javaWriter.endType();
assertCode(""
+ "package com.squareup;\n"
+ "\n"
+ "class Foo {\n"
+ " private static String string;\n"
+ "}\n");
}
@Test public void fieldDeclarationWithInitialValue() throws IOException {
javaWriter.emitPackage("com.squareup");
javaWriter.beginType("com.squareup.Foo", "class");
javaWriter.emitField("java.lang.String", "string", EnumSet.noneOf(Modifier.class),
"\"bar\" + \"baz\"");
javaWriter.endType();
assertCode(""
+ "package com.squareup;\n"
+ "\n"
+ "class Foo {\n"
+ " String string = \"bar\" + \"baz\";\n"
+ "}\n");
}
@Test public void fieldDeclarationWithWrappingInitialValue() throws IOException {
javaWriter.emitPackage("com.squareup");
javaWriter.beginType("com.squareup.Foo", "class");
javaWriter.emitField("java.lang.String", "string", EnumSet.noneOf(Modifier.class),
"\"bar\"\n+ \"baz\"\n+ \"biz\"");
javaWriter.endType();
assertCode(""
+ "package com.squareup;\n"
+ "\n"
+ "class Foo {\n"
+ " String string = \"bar\"\n"
+ " + \"baz\"\n"
+ " + \"biz\";\n"
+ "}\n");
}
// If the initializer begins with a newline, don't emit a space after the '='.
@Test public void fieldDeclarationWithNewlineInitialValue() throws IOException {
javaWriter.emitPackage("com.squareup");
javaWriter.beginType("com.squareup.Foo", "class");
javaWriter.emitField("java.lang.String", "string", EnumSet.noneOf(Modifier.class),
"\n\"bar\"\n+ \"baz\"\n+ \"biz\"");
javaWriter.endType();
assertCode(""
+ "package com.squareup;\n"
+ "\n"
+ "class Foo {\n"
+ " String string =\n"
+ " \"bar\"\n"
+ " + \"baz\"\n"
+ " + \"biz\";\n"
+ "}\n");
}
@Test public void abstractMethodDeclaration() throws IOException {
javaWriter.emitPackage("com.squareup");
javaWriter.beginType("com.squareup.Foo", "class");
javaWriter.beginMethod("java.lang.String", "foo", EnumSet.of(ABSTRACT, PUBLIC),
"java.lang.Object", "object", "java.lang.String", "s");
javaWriter.endMethod();
javaWriter.endType();
assertCode(""
+ "package com.squareup;\n"
+ "\n"
+ "class Foo {\n"
+ " public abstract String foo(Object object, String s);\n"
+ "}\n");
}
@Test public void abstractMethodDeclarationWithThrows() throws IOException {
javaWriter.emitPackage("com.squareup");
javaWriter.beginType("com.squareup.Foo", "class");
javaWriter.beginMethod("java.lang.String", "foo", EnumSet.of(ABSTRACT, PUBLIC),
Arrays.asList("java.lang.Object", "object", "java.lang.String", "s"),
Arrays.asList("java.io.IOException"));
javaWriter.endMethod();
javaWriter.endType();
assertCode(""
+ "package com.squareup;\n"
+ "\n"
+ "class Foo {\n"
+ " public abstract String foo(Object object, String s)\n"
+ " throws java.io.IOException;\n"
+ "}\n");
}
@Test public void nonAbstractMethodDeclaration() throws IOException {
javaWriter.emitPackage("com.squareup");
javaWriter.beginType("com.squareup.Foo", "class");
javaWriter.beginMethod("int", "foo", EnumSet.noneOf(Modifier.class), "java.lang.String", "s");
javaWriter.endMethod();
javaWriter.endType();
assertCode(""
+ "package com.squareup;\n"
+ "\n"
+ "class Foo {\n"
+ " int foo(String s) {\n"
+ " }\n"
+ "}\n");
}
@Test public void nonAbstractMethodDeclarationWithThrows() throws IOException {
javaWriter.emitPackage("com.squareup");
javaWriter.beginType("com.squareup.Foo", "class");
javaWriter.beginMethod("int", "foo", EnumSet.noneOf(Modifier.class),
Arrays.asList("java.lang.String", "s"), Arrays.asList("java.io.IOException"));
javaWriter.endMethod();
javaWriter.endType();
assertCode(""
+ "package com.squareup;\n"
+ "\n"
+ "class Foo {\n"
+ " int foo(String s)\n"
+ " throws java.io.IOException {\n"
+ " }\n"
+ "}\n");
}
@Test public void interfaceMethodDeclaration() throws IOException {
javaWriter.emitPackage("com.squareup");
javaWriter.beginType("com.squareup.Foo", "interface");
javaWriter.beginMethod("java.lang.String", "foo", EnumSet.noneOf(Modifier.class),
"java.lang.Object", "object", "java.lang.String", "s");
javaWriter.endMethod();
javaWriter.endType();
assertCode(""
+ "package com.squareup;\n"
+ "\n"
+ "interface Foo {\n"
+ " String foo(Object object, String s);\n"
+ "}\n");
}
@Test public void interfaceMethodDeclarationWithThrows() throws IOException {
javaWriter.emitPackage("com.squareup");
javaWriter.beginType("com.squareup.Foo", "interface");
javaWriter.beginMethod("java.lang.String", "foo", EnumSet.noneOf(Modifier.class),
Arrays.asList("java.lang.Object", "object", "java.lang.String", "s"),
Arrays.asList("java.io.IOException"));
javaWriter.endMethod();
javaWriter.endType();
assertCode(""
+ "package com.squareup;\n"
+ "\n"
+ "interface Foo {\n"
+ " String foo(Object object, String s)\n"
+ " throws java.io.IOException;\n"
+ "}\n");
}
@Test public void constructorDeclaration() throws IOException {
javaWriter.emitPackage("com.squareup");
javaWriter.beginType("com.squareup.Foo", "class");
javaWriter.beginConstructor(EnumSet.of(PUBLIC), "java.lang.String", "s");
javaWriter.endConstructor();
javaWriter.endType();
assertCode(""
+ "package com.squareup;\n"
+ "\n"
+ "class Foo {\n"
+ " public Foo(String s) {\n"
+ " }\n"
+ "}\n");
}
@Test public void simpleConstructor() throws IOException {
javaWriter.emitPackage("com.squareup");
javaWriter.beginType("com.squareup.Foo", "class");
javaWriter.beginConstructor(EnumSet.of(PUBLIC), "java.lang.String", "s");
javaWriter.emitStatement("if (%s == null) throw new NullPointerException()", "s");
javaWriter.endConstructor();
javaWriter.endType();
assertCode(""
+ "package com.squareup;\n"
+ "\n"
+ "class Foo {\n"
+ " public Foo(String s) {\n"
+ " if (s == null) throw new NullPointerException();\n"
+ " }\n"
+ "}\n");
}
@Test public void genericsConstructor() throws IOException {
javaWriter.emitPackage("com.squareup");
javaWriter.beginType("com.squareup.Foo", "class");
javaWriter.emitField("T", "fooType", EnumSet.of(PRIVATE));
javaWriter.beginConstructor(EnumSet.of(PUBLIC), "T", "s");
javaWriter.emitStatement("if (%s == null) throw new NullPointerException()", "s");
javaWriter.endConstructor();
javaWriter.beginMethod("T", "getFooType", EnumSet.of(PUBLIC));
javaWriter.emitStatement("return fooType");
javaWriter.endMethod();
javaWriter.endType();
assertCode(""
+ "package com.squareup;\n"
+ "\n"
+ "class Foo {\n"
+ " private T fooType;\n"
+ " public Foo(T s) {\n"
+ " if (s == null) throw new NullPointerException();\n"
+ " }\n"
+ " public T getFooType() {\n"
+ " return fooType;\n"
+ " }\n"
+ "}\n");
}
@Test public void constructorDeclarationInNestedTypes() throws IOException {
javaWriter.emitPackage("com.squareup");
javaWriter.beginType("com.squareup.Foo", "class");
javaWriter.beginConstructor(EnumSet.of(PUBLIC), "java.lang.String", "s");
javaWriter.endConstructor();
javaWriter.beginType("com.squareup.Bar", "class");
javaWriter.beginConstructor(EnumSet.noneOf(Modifier.class));
javaWriter.endConstructor();
javaWriter.endType();
javaWriter.endType();
assertCode(""
+ "package com.squareup;\n"
+ "\n"
+ "class Foo {\n"
+ " public Foo(String s) {\n"
+ " }\n"
+ " class Bar {\n"
+ " Bar() {\n"
+ " }\n"
+ " }\n"
+ "}\n");
}
@Test public void constructorDeclarationWithThrows() throws IOException {
javaWriter.emitPackage("com.squareup");
javaWriter.beginType("com.squareup.Foo", "class");
javaWriter.beginConstructor(EnumSet.of(PUBLIC),
Arrays.asList("java.lang.String", "s"), Arrays.asList("java.io.IOException"));
javaWriter.endConstructor();
javaWriter.endType();
assertCode(""
+ "package com.squareup;\n"
+ "\n"
+ "class Foo {\n"
+ " public Foo(String s)\n"
+ " throws java.io.IOException {\n"
+ " }\n"
+ "}\n");
}
@Test public void statement() throws IOException {
javaWriter.emitPackage("com.squareup");
javaWriter.beginType("com.squareup.Foo", "class");
javaWriter.beginMethod("int", "foo", EnumSet.noneOf(Modifier.class), "java.lang.String", "s");
javaWriter.emitStatement("int j = s.length() + %s", 13);
javaWriter.endMethod();
javaWriter.endType();
assertCode(""
+ "package com.squareup;\n"
+ "\n"
+ "class Foo {\n"
+ " int foo(String s) {\n"
+ " int j = s.length() + 13;\n"
+ " }\n"
+ "}\n");
}
@Test public void statementPrecededByComment() throws IOException {
javaWriter.emitPackage("com.squareup");
javaWriter.beginType("com.squareup.Foo", "class");
javaWriter.beginMethod("int", "foo", EnumSet.noneOf(Modifier.class), "java.lang.String", "s");
javaWriter.emitSingleLineComment("foo");
javaWriter.emitStatement("int j = s.length() + %s", 13);
javaWriter.endMethod();
javaWriter.endType();
assertCode(""
+ "package com.squareup;\n"
+ "\n"
+ "class Foo {\n"
+ " int foo(String s) {\n"
+ " // foo\n"
+ " int j = s.length() + 13;\n"
+ " }\n"
+ "}\n");
}
@Test public void multiLineStatement() throws IOException {
javaWriter.emitPackage("com.squareup");
javaWriter.beginType("com.squareup.Triangle", "class");
javaWriter.beginMethod("double", "pythagorean", EnumSet.noneOf(Modifier.class),
"int", "a", "int", "b");
javaWriter.emitStatement("int cSquared = a * a\n+ b * b");
javaWriter.emitStatement("return Math.sqrt(cSquared)");
javaWriter.endMethod();
javaWriter.endType();
assertCode(""
+ "package com.squareup;\n"
+ "\n"
+ "class Triangle {\n"
+ " double pythagorean(int a, int b) {\n"
+ " int cSquared = a * a\n"
+ " + b * b;\n"
+ " return Math.sqrt(cSquared);\n"
+ " }\n"
+ "}\n");
}
@Test public void addImport() throws IOException {
javaWriter.emitPackage("com.squareup");
javaWriter.emitImports("java.util.ArrayList");
javaWriter.beginType("com.squareup.Foo", "class", EnumSet.of(PUBLIC, FINAL));
javaWriter.emitField("java.util.ArrayList", "list", EnumSet.noneOf(Modifier.class),
"new java.util.ArrayList()");
javaWriter.endType();
assertCode(""
+ "package com.squareup;\n"
+ "\n"
+ "import java.util.ArrayList;\n"
+ "public final class Foo {\n"
+ " ArrayList list = new java.util.ArrayList();\n"
+ "}\n");
}
@Test public void addImportAsClass() throws IOException {
javaWriter.emitPackage("com.squareup");
javaWriter.emitImports(ArrayList.class);
javaWriter.beginType("com.squareup.Foo", "class", EnumSet.of(PUBLIC, FINAL));
javaWriter.emitField("java.util.ArrayList", "list", EnumSet.noneOf(Modifier.class),
"new java.util.ArrayList()");
javaWriter.endType();
assertCode(""
+ "package com.squareup;\n"
+ "\n"
+ "import java.util.ArrayList;\n"
+ "public final class Foo {\n"
+ " ArrayList list = new java.util.ArrayList();\n"
+ "}\n");
}
@Test public void addStaticImport() throws IOException {
javaWriter.emitPackage("com.squareup");
javaWriter.emitStaticImports("java.lang.System.getProperty");
javaWriter.beginType("com.squareup.Foo", "class", EnumSet.of(PUBLIC, FINAL));
javaWriter.emitField("String", "bar", EnumSet.noneOf(Modifier.class), "getProperty(\"bar\")");
javaWriter.endType();
assertCode(""
+ "package com.squareup;\n"
+ "\n"
+ "import static java.lang.System.getProperty;\n"
+ "public final class Foo {\n"
+ " String bar = getProperty(\"bar\");\n"
+ "}\n");
}
@Test
public void addNestedClassImportAsClass() throws IOException {
javaWriter.emitPackage("com.squareup");
javaWriter.emitImports(NestedClass.class);
javaWriter.beginType("com.squareup.Foo", "class", EnumSet.of(PUBLIC, FINAL));
javaWriter.emitField("com.squareup.javawriter.JavaWriterTest.NestedClass", "nestedClass",
EnumSet.noneOf(Modifier.class), "new NestedClass()");
javaWriter.endType();
assertCode(""
+ "package com.squareup;\n"
+ "\n"
+ "import com.squareup.javawriter.JavaWriterTest.NestedClass;\n"
+ "public final class Foo {\n"
+ " NestedClass nestedClass = new NestedClass();\n"
+ "}\n");
}
public static class NestedClass {}
@Test public void addStaticWildcardImport() throws IOException {
javaWriter.emitPackage("com.squareup");
javaWriter.emitStaticImports("java.lang.System.*");
javaWriter.beginType("com.squareup.Foo", "class", EnumSet.of(PUBLIC, FINAL));
javaWriter.emitField("String", "bar", EnumSet.noneOf(Modifier.class), "getProperty(\"bar\")");
javaWriter.endType();
assertCode(""
+ "package com.squareup;\n"
+ "\n"
+ "import static java.lang.System.*;\n"
+ "public final class Foo {\n"
+ " String bar = getProperty(\"bar\");\n"
+ "}\n");
}
@Test public void emptyImports() throws IOException {
javaWriter.emitPackage("com.squareup");
javaWriter.emitImports(Collections.emptyList());
javaWriter.beginType("com.squareup.Foo", "class", EnumSet.of(PUBLIC, FINAL));
javaWriter.endType();
assertCode(""
+ "package com.squareup;\n"
+ "\n"
+ "public final class Foo {\n"
+ "}\n");
}
@Test public void emptyStaticImports() throws IOException {
javaWriter.emitPackage("com.squareup");
javaWriter.emitStaticImports(Collections.emptyList());
javaWriter.beginType("com.squareup.Foo", "class", EnumSet.of(PUBLIC, FINAL));
javaWriter.endType();
assertCode(""
+ "package com.squareup;\n"
+ "\n"
+ "public final class Foo {\n"
+ "}\n");
}
@Test public void addImportFromSubpackage() throws IOException {
javaWriter.emitPackage("com.squareup");
javaWriter.beginType("com.squareup.Foo", "class", EnumSet.of(PUBLIC, FINAL));
javaWriter.emitField("com.squareup.bar.Baz", "baz");
javaWriter.endType();
assertCode(""
+ "package com.squareup;\n"
+ "\n"
+ "public final class Foo {\n"
+ " com.squareup.bar.Baz baz;\n"
+ "}\n");
}
@Test public void ifControlFlow() throws IOException {
javaWriter.emitPackage("com.squareup");
javaWriter.beginType("com.squareup.Foo", "class");
javaWriter.beginMethod("int", "foo", EnumSet.noneOf(Modifier.class), "java.lang.String", "s");
javaWriter.beginControlFlow("if (s.isEmpty())");
javaWriter.emitStatement("int j = s.length() + %s", 13);
javaWriter.endControlFlow();
javaWriter.endMethod();
javaWriter.endType();
assertCode(""
+ "package com.squareup;\n"
+ "\n"
+ "class Foo {\n"
+ " int foo(String s) {\n"
+ " if (s.isEmpty()) {\n"
+ " int j = s.length() + 13;\n"
+ " }\n"
+ " }\n"
+ "}\n");
}
@Test public void doWhileControlFlow() throws IOException {
javaWriter.emitPackage("com.squareup");
javaWriter.beginType("com.squareup.Foo", "class");
javaWriter.beginMethod("int", "foo", EnumSet.noneOf(Modifier.class), "java.lang.String", "s");
javaWriter.beginControlFlow("do");
javaWriter.emitStatement("int j = s.length() + %s", 13);
javaWriter.endControlFlow("while (s.isEmpty())");
javaWriter.endMethod();
javaWriter.endType();
assertCode(""
+ "package com.squareup;\n"
+ "\n"
+ "class Foo {\n"
+ " int foo(String s) {\n"
+ " do {\n"
+ " int j = s.length() + 13;\n"
+ " } while (s.isEmpty());\n"
+ " }\n"
+ "}\n");
}
@Test public void tryCatchFinallyControlFlow() throws IOException {
javaWriter.emitPackage("com.squareup");
javaWriter.beginType("com.squareup.Foo", "class");
javaWriter.beginMethod("int", "foo", EnumSet.noneOf(Modifier.class), "java.lang.String", "s");
javaWriter.beginControlFlow("try");
javaWriter.emitStatement("int j = s.length() + %s", 13);
javaWriter.nextControlFlow("catch (RuntimeException e)");
javaWriter.emitStatement("e.printStackTrace()");
javaWriter.nextControlFlow("finally");
javaWriter.emitStatement("int k = %s", 13);
javaWriter.endControlFlow();
javaWriter.endMethod();
javaWriter.endType();
assertCode(""
+ "package com.squareup;\n"
+ "\n"
+ "class Foo {\n"
+ " int foo(String s) {\n"
+ " try {\n"
+ " int j = s.length() + 13;\n"
+ " } catch (RuntimeException e) {\n"
+ " e.printStackTrace();\n"
+ " } finally {\n"
+ " int k = 13;\n"
+ " }\n"
+ " }\n"
+ "}\n");
}
@Test public void annotatedType() throws IOException {
javaWriter.emitPackage("com.squareup");
javaWriter.emitImports("javax.inject.Singleton");
javaWriter.emitAnnotation("javax.inject.Singleton");
javaWriter.emitAnnotation(SuppressWarnings.class,
StringLiteral.forValue("unchecked"));
javaWriter.beginType("com.squareup.Foo", "class");
javaWriter.endType();
assertCode(""
+ "package com.squareup;\n"
+ "\n"
+ "import javax.inject.Singleton;\n"
+ "@Singleton\n"
+ "@SuppressWarnings(\"unchecked\")\n"
+ "class Foo {\n"
+ "}\n");
}
@Test public void annotatedMember() throws IOException {
javaWriter.emitPackage("com.squareup");
javaWriter.beginType("com.squareup.Foo", "class");
javaWriter.emitAnnotation(Deprecated.class);
javaWriter.emitField("java.lang.String", "s");
javaWriter.endType();
assertCode(""
+ "package com.squareup;\n"
+ "\n"
+ "class Foo {\n"
+ " @Deprecated\n"
+ " String s;\n"
+ "}\n");
}
@Test public void annotatedWithSingleAttribute() throws IOException {
Map attributes = new LinkedHashMap();
attributes.put("overrides", true);
javaWriter.emitPackage("com.squareup");
javaWriter.emitAnnotation("Module", attributes);
javaWriter.beginType("com.squareup.FooModule", "class", EnumSet.noneOf(Modifier.class));
javaWriter.endType();
assertCode(""
+ "package com.squareup;\n"
+ "\n"
+ "@Module(overrides = true)\n"
+ "class FooModule {\n"
+ "}\n");
}
@Test public void annotatedWithSingleValueAttribute() throws IOException {
Map attributes = new LinkedHashMap();
attributes.put("value", StringLiteral.forValue("blah.Generator"));
javaWriter.emitPackage("com.squareup");
javaWriter.emitAnnotation("Generated", attributes);
javaWriter.beginType("com.squareup.FooModule", "class", EnumSet.noneOf(Modifier.class));
javaWriter.endType();
assertCode(""
+ "package com.squareup;\n"
+ "\n"
+ "@Generated(\"blah.Generator\")\n"
+ "class FooModule {\n"
+ "}\n");
}
@Test public void annotatedWithTwoNonArrayAttributes() throws IOException {
Map attributes = new LinkedHashMap();
attributes.put("overrides", true);
attributes.put("foo", "bar");
javaWriter.emitPackage("com.squareup");
javaWriter.emitAnnotation("Module", attributes);
javaWriter.beginType("com.squareup.FooModule", "class", EnumSet.noneOf(Modifier.class));
javaWriter.endType();
assertCode(""
+ "package com.squareup;\n"
+ "\n"
+ "@Module(overrides = true, foo = bar)\n"
+ "class FooModule {\n"
+ "}\n");
}
@Test public void annotatedWithThreeNonArrayAttributes() throws IOException {
Map attributes = new LinkedHashMap();
attributes.put("overrides", true);
attributes.put("foo", "bar");
attributes.put("bar", "baz");
javaWriter.emitPackage("com.squareup");
javaWriter.emitAnnotation("Module", attributes);
javaWriter.beginType("com.squareup.FooModule", "class", EnumSet.noneOf(Modifier.class));
javaWriter.endType();
assertCode(""
+ "package com.squareup;\n"
+ "\n"
+ "@Module(overrides = true, foo = bar, bar = baz)\n"
+ "class FooModule {\n"
+ "}\n");
}
@Test public void annotatedWithAttributes() throws IOException {
Map attributes = new LinkedHashMap();
attributes.put("overrides", true);
attributes.put("entryPoints", new Object[] { "entryPointA", "entryPointB", "entryPointC" });
attributes.put("staticInjections", "com.squareup.Quux");
javaWriter.emitPackage("com.squareup");
javaWriter.emitAnnotation("Module", attributes);
javaWriter.beginType("com.squareup.FooModule", "class");
javaWriter.endType();
assertCode(""
+ "package com.squareup;\n"
+ "\n"
+ "@Module(\n"
+ " overrides = true,\n"
+ " entryPoints = {\n"
+ " entryPointA,\n"
+ " entryPointB,\n"
+ " entryPointC\n"
+ " },\n"
+ " staticInjections = com.squareup.Quux\n"
+ ")\n"
+ "class FooModule {\n"
+ "}\n");
}
@Test public void parameterizedType() throws IOException {
javaWriter.emitPackage("com.squareup");
javaWriter.emitImports("java.util.Map", "java.util.Date");
javaWriter.beginType("com.squareup.Foo", "class");
javaWriter.emitField("java.util.Map", "map",
EnumSet.noneOf(Modifier.class));
javaWriter.endType();
assertCode(""
+ "package com.squareup;\n"
+ "\n"
+ "import java.util.Date;\n"
+ "import java.util.Map;\n"
+ "class Foo {\n"
+ " Map map;\n"
+ "}\n");
}
@Test public void eolComment() throws IOException {
javaWriter.emitSingleLineComment("foo");
assertCode("// foo\n");
}
@Test public void javadoc() throws IOException {
javaWriter.emitJavadoc("foo");
assertCode(""
+ "/**\n"
+ " * foo\n"
+ " */\n");
}
@Test public void multilineJavadoc() throws IOException {
javaWriter.emitJavadoc("0123456789 0123456789 0123456789 0123456789 0123456789 0123456789\n"
+ "0123456789 0123456789 0123456789 0123456789");
assertCode(""
+ "/**\n"
+ " * 0123456789 0123456789 0123456789 0123456789 0123456789 0123456789\n"
+ " * 0123456789 0123456789 0123456789 0123456789\n"
+ " */\n");
}
@Test public void multilineJavadocDoesNotEmitTrailingSpaceForEmptyLines() throws IOException {
javaWriter.emitJavadoc("Foo\n\nBar");
assertCode(""
+ "/**\n"
+ " * Foo\n"
+ " *\n"
+ " * Bar\n"
+ " */\n"
);
}
@Test public void testType() {
assertThat(JavaWriter.type(String.class)).as("simple type").isEqualTo("java.lang.String");
assertThat(JavaWriter.type(Set.class)).as("raw type").isEqualTo("java.util.Set");
assertThat(JavaWriter.type(Set.class, "?")).as("wildcard type").isEqualTo("java.util.Set>");
assertThat(JavaWriter.type(Map.class, JavaWriter.type(String.class), "?"))
.as("mixed type and wildcard generic type parameters")
.isEqualTo("java.util.Map");
try {
JavaWriter.type(String.class, "foo");
failBecauseExceptionWasNotThrown(IllegalArgumentException.class);
} catch (Throwable e) {
assertThat(e).as("parameterized non-generic").isInstanceOf(IllegalArgumentException.class);
}
try {
JavaWriter.type(Map.class, "foo");
failBecauseExceptionWasNotThrown(IllegalArgumentException.class);
} catch (Throwable e) {
assertThat(e).as("too few type arguments").isInstanceOf(IllegalArgumentException.class);
}
try {
JavaWriter.type(Set.class, "foo", "bar");
failBecauseExceptionWasNotThrown(IllegalArgumentException.class);
} catch (Throwable e) {
assertThat(e).as("too many type arguments").isInstanceOf(IllegalArgumentException.class);
}
}
@Test public void testRawType() {
assertThat(JavaWriter.rawType(JavaWriter.type(Set.class)))
.as("raw type").isEqualTo("java.util.Set");
assertThat(JavaWriter.rawType(JavaWriter.type(Set.class, "?")))
.as("wildcard type").isEqualTo("java.util.Set");
assertThat(JavaWriter.rawType(JavaWriter.type(Set.class, "String")))
.as("parameterized type").isEqualTo("java.util.Set");
assertThat(JavaWriter.rawType(JavaWriter.type(Map.class, "String", "Integer")))
.as("parameterized type").isEqualTo("java.util.Map");
assertThat(JavaWriter.rawType("java.util.Set>"))
.as("nested parameterized type").isEqualTo("java.util.Set");
}
@Test public void compressType() throws IOException {
javaWriter.emitPackage("com.blah");
javaWriter.emitImports(Set.class.getCanonicalName(), Binding.class.getCanonicalName());
String actual =
javaWriter.compressType("java.util.Set>");
assertThat(actual).isEqualTo("Set>");
}
@Test public void compressDeeperType() throws IOException {
javaWriter.emitPackage("com.blah");
javaWriter.emitImports(Binding.class.getCanonicalName());
String actual = javaWriter.compressType("com.example.Binding");
assertThat(actual).isEqualTo("Binding");
}
@Test public void compressNestedType() throws IOException {
javaWriter.emitPackage("com.blah");
String actual = javaWriter.compressType("com.blah.Enclosing.Nested");
assertThat(actual).isEqualTo("Enclosing.Nested");
}
@Test public void compressWildcardType() throws IOException {
javaWriter.emitPackage("com.blah");
javaWriter.emitImports(Binding.class.getCanonicalName());
String actual = javaWriter.compressType("com.example.Binding extends com.blah.Foo.Blah>");
assertThat(actual).isEqualTo("Binding extends Foo.Blah>");
}
@Test public void compressSimpleNameCollisionInSamePackage() throws IOException {
javaWriter.emitPackage("denominator");
javaWriter.emitImports("javax.inject.Provider", "dagger.internal.Binding");
String actual = javaWriter.compressType("dagger.internal.Binding");
assertThat(actual).isEqualTo("Binding");
}
@Test public void compressJavaLangClass() throws IOException {
javaWriter.emitPackage("com.blah");
String actual = javaWriter.compressType("java.lang.Class");
assertThat(actual).isEqualTo("Class");
}
@Test public void compressJavaLangSubPackageClass() throws IOException {
javaWriter.emitPackage("com.blah");
String actual = javaWriter.compressType("java.lang.annotation.Annotation");
assertThat(actual).isEqualTo("java.lang.annotation.Annotation");
}
@Test public void compressVarargsType() throws IOException {
javaWriter.emitPackage("com.blah");
javaWriter.emitImports("java.util.File");
String actual = javaWriter.compressType("java.util.File...");
assertThat(actual).isEqualTo("File...");
}
@Test public void compressArrayType() throws IOException {
javaWriter.emitPackage("com.blah");
javaWriter.emitImports("java.util.File");
String actual1 = javaWriter.compressType("java.util.File[]");
assertThat(actual1).isEqualTo("File[]");
String actual2 = javaWriter.compressType("java.util.File[][][]");
assertThat(actual2).isEqualTo("File[][][]");
}
@Test public void configurableIndent() throws IOException {
javaWriter.setIndent(" ");
javaWriter.emitPackage("com.squareup");
javaWriter.beginType("com.squareup.Foo", "class");
javaWriter.emitField("String", "bar");
javaWriter.endType();
assertCode(""
+ "package com.squareup;\n"
+ "\n"
+ "class Foo {\n"
+ " String bar;\n"
+ "}\n");
}
@Test public void outOfOrderModifierSet() throws IOException {
Set modifiers = new LinkedHashSet(Arrays.asList(FINAL, PUBLIC));
javaWriter.emitPackage("com.squareup");
javaWriter.beginType("com.squareup.Foo", "class", modifiers);
javaWriter.endType();
assertCode(""
+ "package com.squareup;\n"
+ "\n"
+ "public final class Foo {\n"
+ "}\n");
}
@Test public void emptyNonEnumModifierSet() throws IOException {
javaWriter.emitPackage("com.squareup");
javaWriter.beginType("com.squareup.Foo", "class", new LinkedHashSet());
javaWriter.endType();
assertCode(""
+ "package com.squareup;\n"
+ "\n"
+ "class Foo {\n"
+ "}\n");
}
private void assertCode(String expected) {
assertThat(stringWriter.toString()).isEqualTo(expected);
}
}
javawriter-2.5.1/src/test/java/com/squareup/javawriter/StringLiteralTest.java 0000664 0000000 0000000 00000003302 12551715567 0027467 0 ustar 00root root 0000000 0000000 // Copyright 2014 Square, Inc.
package com.squareup.javawriter;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import static org.fest.assertions.api.Assertions.assertThat;
@RunWith(JUnit4.class)
public final class StringLiteralTest {
@Test public void stringLiteral() {
assertThat(StringLiteral.forValue("").toString()).isEqualTo("\"\"");
assertThat(StringLiteral.forValue("JavaWriter").toString()).isEqualTo("\"JavaWriter\"");
assertThat(StringLiteral.forValue("\\").toString()).isEqualTo("\"\\\\\"");
assertThat(StringLiteral.forValue("\"").toString()).isEqualTo("\"\\\"\"");
assertThat(StringLiteral.forValue("\b").toString()).isEqualTo("\"\\b\"");
assertThat(StringLiteral.forValue("\t").toString()).isEqualTo("\"\\t\"");
assertThat(StringLiteral.forValue("\n").toString()).isEqualTo("\"\\n\"");
assertThat(StringLiteral.forValue("\f").toString()).isEqualTo("\"\\f\"");
assertThat(StringLiteral.forValue("\r").toString()).isEqualTo("\"\\r\"");
// Control characters
for (char i = 0x1; i <= 0x1f; i++) {
checkCharEscape(i);
}
for (char i = 0x7f; i <= 0x9f; i++) {
checkCharEscape(i);
}
}
private void checkCharEscape(char codePoint) {
String test = "" + codePoint;
String expected;
switch (codePoint) {
case 8: expected = "\"\\b\""; break;
case 9: expected = "\"\\t\""; break;
case 10: expected = "\"\\n\""; break;
case 12: expected = "\"\\f\""; break;
case 13: expected = "\"\\r\""; break;
default: expected = "\"\\u" + String.format("%04x", (int) codePoint) + "\"";
}
assertThat(StringLiteral.forValue(test).toString()).isEqualTo(expected);
}
}