Skip to content

Commit d757050

Browse files
knightdnapedja4
authored andcommitted
BAEL-1200 JavaPoet (eugenp#4500)
* Initial commit * Implement JavaPoet examples
1 parent 4109abe commit d757050

7 files changed

Lines changed: 362 additions & 0 deletions

File tree

‎libraries/.gitignore‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
*.class
2+
3+
# Folders #
4+
/gensrc
5+
/target
6+
7+
# Packaged files #
8+
*.jar

‎libraries/pom.xml‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -722,6 +722,17 @@
722722
<scope>test</scope>
723723
</dependency>
724724

725+
<dependency>
726+
<groupId>com.squareup</groupId>
727+
<artifactId>javapoet</artifactId>
728+
<version>${javapoet.version}</version>
729+
</dependency>
730+
<dependency>
731+
<groupId>org.hamcrest</groupId>
732+
<artifactId>hamcrest-all</artifactId>
733+
<version>${hamcrest-all.version}</version>
734+
<scope>test</scope>
735+
</dependency>
725736

726737
</dependencies>
727738

@@ -939,6 +950,8 @@
939950
<xchart-version>3.5.2</xchart-version>
940951
<commons-net.version>3.6</commons-net.version>
941952
<mockftpserver.version>2.7.1</mockftpserver.version>
953+
<javapoet.version>1.10.0</javapoet.version>
954+
<hamcrest-all.version>1.3</hamcrest-all.version>
942955
</properties>
943956

944957
</project>
Lines changed: 183 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,183 @@
1+
package com.baeldung.javapoet;
2+
3+
import com.squareup.javapoet.ClassName;
4+
import com.squareup.javapoet.CodeBlock;
5+
import com.squareup.javapoet.FieldSpec;
6+
import com.squareup.javapoet.JavaFile;
7+
import com.squareup.javapoet.MethodSpec;
8+
import com.squareup.javapoet.ParameterSpec;
9+
import com.squareup.javapoet.ParameterizedTypeName;
10+
import com.squareup.javapoet.TypeName;
11+
import com.squareup.javapoet.TypeSpec;
12+
13+
import javax.lang.model.element.Modifier;
14+
import java.io.File;
15+
import java.io.IOException;
16+
import java.nio.file.Path;
17+
import java.nio.file.Paths;
18+
import java.util.ArrayList;
19+
import java.util.Collections;
20+
import java.util.Comparator;
21+
import java.util.List;
22+
import java.util.stream.IntStream;
23+
24+
public class PersonGenerator {
25+
26+
private static final String FOUR_WHITESPACES = " ";
27+
private static final String PERSON_PACKAGE_NAME = "com.baeldung.javapoet.test.person";
28+
29+
private File outputFile;
30+
31+
public PersonGenerator() {
32+
outputFile = new File(getOutputPath().toUri());
33+
}
34+
35+
public static String getPersonPackageName() {
36+
return PERSON_PACKAGE_NAME;
37+
}
38+
39+
public Path getOutputPath() {
40+
return Paths.get(new File(".").getAbsolutePath() + "/gensrc");
41+
}
42+
43+
public FieldSpec getDefaultNameField() {
44+
return FieldSpec
45+
.builder(String.class, "DEFAULT_NAME")
46+
.addModifiers(Modifier.PUBLIC, Modifier.STATIC, Modifier.FINAL)
47+
.initializer("$S", "Alice")
48+
.build();
49+
}
50+
51+
public MethodSpec getSortByLengthMethod() {
52+
return MethodSpec
53+
.methodBuilder("sortByLength")
54+
.addModifiers(Modifier.PUBLIC, Modifier.STATIC)
55+
.addParameter(ParameterSpec
56+
.builder(ParameterizedTypeName.get(ClassName.get(List.class), TypeName.get(String.class)), "strings")
57+
.build())
58+
.addStatement("$T.sort($N, $L)", Collections.class, "strings", getComparatorAnonymousClass())
59+
.build();
60+
}
61+
62+
public MethodSpec getPrintNameMultipleTimesMethod() {
63+
return MethodSpec
64+
.methodBuilder("printNameMultipleTimes")
65+
.addModifiers(Modifier.PUBLIC)
66+
.addCode(getPrintNameMultipleTimesLambdaImpl())
67+
.build();
68+
}
69+
70+
public CodeBlock getPrintNameMultipleTimesImpl() {
71+
return CodeBlock
72+
.builder()
73+
.beginControlFlow("for (int i = $L; i < $L; i++)")
74+
.addStatement("System.out.println(name)")
75+
.endControlFlow()
76+
.build();
77+
}
78+
79+
public CodeBlock getPrintNameMultipleTimesLambdaImpl() {
80+
return CodeBlock
81+
.builder()
82+
.addStatement("$T<$T> names = new $T<>()", List.class, String.class, ArrayList.class)
83+
.addStatement("$T.range($L, $L).forEach(i -> names.add(name))", IntStream.class, 0, 10)
84+
.addStatement("names.forEach(System.out::println)")
85+
.build();
86+
}
87+
88+
public TypeSpec getGenderEnum() {
89+
return TypeSpec
90+
.enumBuilder("Gender")
91+
.addModifiers(Modifier.PUBLIC)
92+
.addEnumConstant("MALE")
93+
.addEnumConstant("FEMALE")
94+
.addEnumConstant("UNSPECIFIED")
95+
.build();
96+
}
97+
98+
public TypeSpec getPersonInterface() {
99+
return TypeSpec
100+
.interfaceBuilder("Person")
101+
.addModifiers(Modifier.PUBLIC)
102+
.addField(getDefaultNameField())
103+
.addMethod(MethodSpec
104+
.methodBuilder("getName")
105+
.addModifiers(Modifier.PUBLIC, Modifier.ABSTRACT)
106+
.returns(String.class)
107+
.build())
108+
.addMethod(MethodSpec
109+
.methodBuilder("getDefaultName")
110+
.addModifiers(Modifier.PUBLIC, Modifier.DEFAULT)
111+
.returns(String.class)
112+
.addCode(CodeBlock
113+
.builder()
114+
.addStatement("return DEFAULT_NAME")
115+
.build())
116+
.build())
117+
.build();
118+
}
119+
120+
public TypeSpec getStudentClass() {
121+
return TypeSpec
122+
.classBuilder("Student")
123+
.addSuperinterface(ClassName.get(PERSON_PACKAGE_NAME, "Person"))
124+
.addModifiers(Modifier.PUBLIC)
125+
.addField(FieldSpec
126+
.builder(String.class, "name")
127+
.addModifiers(Modifier.PRIVATE)
128+
.build())
129+
.addMethod(MethodSpec
130+
.methodBuilder("getName")
131+
.addAnnotation(Override.class)
132+
.addModifiers(Modifier.PUBLIC)
133+
.returns(String.class)
134+
.addStatement("return this.name")
135+
.build())
136+
.addMethod(MethodSpec
137+
.methodBuilder("setName")
138+
.addParameter(String.class, "name")
139+
.addModifiers(Modifier.PUBLIC)
140+
.addStatement("this.name = name")
141+
.build())
142+
.addMethod(getPrintNameMultipleTimesMethod())
143+
.addMethod(getSortByLengthMethod())
144+
.build();
145+
}
146+
147+
public TypeSpec getComparatorAnonymousClass() {
148+
return TypeSpec
149+
.anonymousClassBuilder("")
150+
.addSuperinterface(ParameterizedTypeName.get(Comparator.class, String.class))
151+
.addMethod(MethodSpec
152+
.methodBuilder("compare")
153+
.addModifiers(Modifier.PUBLIC)
154+
.addAnnotation(Override.class)
155+
.addParameter(String.class, "a")
156+
.addParameter(String.class, "b")
157+
.returns(int.class)
158+
.addStatement("return a.length() - b.length()")
159+
.build())
160+
.build();
161+
}
162+
163+
public void generateGenderEnum() throws IOException {
164+
writeToOutputFile(getPersonPackageName(), getGenderEnum());
165+
}
166+
167+
public void generatePersonInterface() throws IOException {
168+
writeToOutputFile(getPersonPackageName(), getPersonInterface());
169+
}
170+
171+
public void generateStudentClass() throws IOException {
172+
writeToOutputFile(getPersonPackageName(), getStudentClass());
173+
}
174+
175+
private void writeToOutputFile(String packageName, TypeSpec typeSpec) throws IOException {
176+
JavaFile javaFile = JavaFile
177+
.builder(packageName, typeSpec)
178+
.indent(FOUR_WHITESPACES)
179+
.build();
180+
javaFile.writeTo(outputFile);
181+
}
182+
183+
}
Lines changed: 99 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,99 @@
1+
package com.baeldung.javapoet.test;
2+
3+
import com.baeldung.javapoet.PersonGenerator;
4+
import org.apache.commons.io.FileUtils;
5+
import org.junit.After;
6+
import org.junit.Before;
7+
import org.junit.Test;
8+
import org.junit.runner.RunWith;
9+
import org.junit.runners.JUnit4;
10+
11+
import java.io.File;
12+
import java.io.IOException;
13+
import java.nio.charset.StandardCharsets;
14+
import java.nio.file.Files;
15+
import java.nio.file.Path;
16+
import java.nio.file.Paths;
17+
18+
import static org.hamcrest.Matchers.equalTo;
19+
import static org.hamcrest.Matchers.is;
20+
import static org.junit.Assert.assertThat;
21+
22+
@RunWith(JUnit4.class)
23+
public class PersonGeneratorUnitTest {
24+
25+
private PersonGenerator generator;
26+
private Path generatedFolderPath;
27+
private Path expectedFolderPath;
28+
29+
@Before
30+
public void setUp() {
31+
String packagePath = this
32+
.getClass()
33+
.getPackage()
34+
.getName()
35+
.replace(".", "/") + "/person";
36+
generator = new PersonGenerator();
37+
generatedFolderPath = generator
38+
.getOutputPath()
39+
.resolve(packagePath);
40+
expectedFolderPath = Paths.get(new File(".").getAbsolutePath() + "/src/test/java/" + packagePath);
41+
}
42+
43+
@After
44+
public void tearDown() throws Exception {
45+
FileUtils.deleteDirectory(new File(generator
46+
.getOutputPath()
47+
.toUri()));
48+
}
49+
50+
@Test
51+
public void whenGenerateGenderEnum_thenGenerateGenderEnumAndWriteToFile() throws IOException {
52+
generator.generateGenderEnum();
53+
String fileName = "Gender.java";
54+
assertThatFileIsGeneratedAsExpected(fileName);
55+
deleteGeneratedFile(fileName);
56+
}
57+
58+
@Test
59+
public void whenGeneratePersonInterface_thenGeneratePersonInterfaceAndWriteToFile() throws IOException {
60+
generator.generatePersonInterface();
61+
String fileName = "Person.java";
62+
assertThatFileIsGeneratedAsExpected(fileName);
63+
deleteGeneratedFile(fileName);
64+
}
65+
66+
@Test
67+
public void whenGenerateStudentClass_thenGenerateStudentClassAndWriteToFile() throws IOException {
68+
generator.generateStudentClass();
69+
String fileName = "Student.java";
70+
assertThatFileIsGeneratedAsExpected(fileName);
71+
deleteGeneratedFile(fileName);
72+
}
73+
74+
private void assertThatFileIsGeneratedAsExpected(String fileName) throws IOException {
75+
String generatedFileContent = extractFileContent(generatedFolderPath.resolve(fileName));
76+
String expectedFileContent = extractFileContent(expectedFolderPath.resolve(fileName));
77+
78+
assertThat("Generated file is identical to the file with the expected content", generatedFileContent, is(equalTo(expectedFileContent)));
79+
80+
}
81+
82+
private void deleteGeneratedFile(String fileName) throws IOException {
83+
Path generatedFilePath = generatedFolderPath.resolve(fileName);
84+
Files.delete(generatedFilePath);
85+
}
86+
87+
private String extractFileContent(Path filePath) throws IOException {
88+
byte[] fileContentAsBytes = Files.readAllBytes(filePath);
89+
String fileContentAsString = new String(fileContentAsBytes, StandardCharsets.UTF_8);
90+
91+
if (!fileContentAsString.contains("\r\n")) {
92+
// file is not in DOS format
93+
// convert it first, so that the content comparison will be relevant
94+
return fileContentAsString.replaceAll("\n", "\r\n");
95+
}
96+
return fileContentAsString;
97+
}
98+
99+
}
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
package com.baeldung.javapoet.test.person;
2+
3+
public enum Gender {
4+
MALE,
5+
6+
FEMALE,
7+
8+
UNSPECIFIED
9+
}
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
package com.baeldung.javapoet.test.person;
2+
3+
import java.lang.String;
4+
5+
public interface Person {
6+
String DEFAULT_NAME = "Alice";
7+
8+
String getName();
9+
10+
default String getDefaultName() {
11+
return DEFAULT_NAME;
12+
}
13+
}
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
package com.baeldung.javapoet.test.person;
2+
3+
import java.lang.Override;
4+
import java.lang.String;
5+
import java.util.ArrayList;
6+
import java.util.Collections;
7+
import java.util.Comparator;
8+
import java.util.List;
9+
import java.util.stream.IntStream;
10+
11+
public class Student implements Person {
12+
private String name;
13+
14+
@Override
15+
public String getName() {
16+
return this.name;
17+
}
18+
19+
public void setName(String name) {
20+
this.name = name;
21+
}
22+
23+
public void printNameMultipleTimes() {
24+
List<String> names = new ArrayList<>();
25+
IntStream.range(0, 10).forEach(i -> names.add(name));
26+
names.forEach(System.out::println);
27+
}
28+
29+
public static void sortByLength(List<String> strings) {
30+
Collections.sort(strings, new Comparator<String>() {
31+
@Override
32+
public int compare(String a, String b) {
33+
return a.length() - b.length();
34+
}
35+
});
36+
}
37+
}

0 commit comments

Comments
 (0)