actualMap;
67 | builder.addDataModel(actualMap = withCapture());
68 |
69 | assertEquals(expectedTemplateLocation, templateLocation);
70 | assertEquals(expectedOutputLocation, outputLocation);
71 | assertArrayEquals(expectedMap.entrySet().toArray(), actualMap.entrySet().toArray());
72 | }};
73 | }
74 |
75 | @Test
76 | public void testParsingException(@Mocked OutputGenerator.OutputGeneratorBuilder builder, @Mocked Gson gson) {
77 | Path path = dataDir.toPath().resolve("mydir/success-test.txt.json");
78 | new Expectations() {{
79 | gson.fromJson((JsonReader) any, (Type) any); result = new RuntimeException("test exception");
80 | }};
81 | JsonPropertiesProvider toTest = JsonPropertiesProvider.create(dataDir, templateDir, outputDir);
82 |
83 | assertThatExceptionOfType(RuntimeException.class).isThrownBy(() -> {
84 | toTest.providePropertiesFromFile(path, builder);
85 | }).withMessage("Could not parse json data file: src/test/data/generating-file-visitor/data/mydir/success-test.txt.json");
86 | }
87 |
88 | @Test
89 | public void testMissingTemplateName(@Mocked OutputGenerator.OutputGeneratorBuilder builder) {
90 | Path path = dataDir.toPath().resolve("mydir/missing-template-name.txt.json");
91 | JsonPropertiesProvider toTest = JsonPropertiesProvider.create(dataDir, templateDir, outputDir);
92 |
93 | assertThatExceptionOfType(RuntimeException.class).isThrownBy(() -> {
94 | toTest.providePropertiesFromFile(path, builder);
95 | }).withMessage("Require json data property not found: templateName");
96 | }
97 |
98 | @Test
99 | public void testBadPath(@Mocked OutputGenerator.OutputGeneratorBuilder builder) {
100 | Path path = testDir.toPath().resolve("badPath/success-test.txt.json");
101 | JsonPropertiesProvider toTest = JsonPropertiesProvider.create(dataDir, templateDir, outputDir);
102 | assertThatExceptionOfType(IllegalStateException.class).isThrownBy(() -> {
103 | toTest.providePropertiesFromFile(path, builder);
104 | }).withMessage("visitFile() given file not in sourceDirectory: src/test/data/generating-file-visitor/badPath/success-test.txt.json");
105 | }
106 | }
107 |
--------------------------------------------------------------------------------
/src/main/java/com/oath/maven/plugin/freemarker/OutputGenerator.java:
--------------------------------------------------------------------------------
1 | // Copyright 2018, Oath Inc.
2 | // Licensed under the terms of the Apache 2.0 license. See the LICENSE file in the project root for terms.
3 |
4 | package com.oath.maven.plugin.freemarker;
5 |
6 | import freemarker.template.Configuration;
7 | import freemarker.template.Template;
8 |
9 | import java.io.File;
10 | import java.io.FileWriter;
11 | import java.nio.file.Path;
12 | import java.util.HashMap;
13 | import java.util.Map;
14 |
15 | /**
16 | * Knows how to generate an output file given five things:
17 | *
18 | * - The latest update time of the pom file(s) for the project
19 | * - The location of the generator file
20 | * - The location of the template file
21 | * - The location of the output file
22 | * - A data model used to fill out the template.
23 | *
24 | *Given these five pieces of information, the generator will generate a new output file, but only if any existing
25 | * generated file is not newer than the inputs (pom, generator, and template).
26 | */
27 | class OutputGenerator {
28 | public final long pomModifiedTimestamp;
29 | public final Path generatorLocation;
30 | public final Path templateLocation;
31 | public final Path outputLocation;
32 | public final Map dataModel;
33 | private OutputGenerator(
34 | long pomModifiedTimestamp,
35 | Path generatorLocation,
36 | Path templateLocation,
37 | Path outputLocation,
38 | Map dataModel) {
39 | this.pomModifiedTimestamp = pomModifiedTimestamp;
40 | this.generatorLocation = generatorLocation;
41 | this.templateLocation = templateLocation;
42 | this.outputLocation = outputLocation;
43 | this.dataModel = dataModel;
44 | }
45 |
46 | /**
47 | * Uses a fluent builder to make the code more legible in place.
48 | * Also allows the output generator to be built from multiple locations in source by passing the builder.
49 | * @return A new fluent builder for the OutputGenerator class.
50 | */
51 | public static OutputGeneratorBuilder builder() {
52 | return new OutputGeneratorBuilder();
53 | }
54 |
55 | public static class OutputGeneratorBuilder {
56 | private long pomModifiedTimestamp = Long.MAX_VALUE;
57 | private Path generatorLocation = null;
58 | private Path templateLocation = null;
59 | private Path outputLocation = null;
60 | private Map dataModel = null;
61 |
62 | public OutputGeneratorBuilder addPomLastModifiedTimestamp(long pomModifiedTimestamp) {
63 | this.pomModifiedTimestamp = pomModifiedTimestamp;
64 | return this;
65 | }
66 |
67 | public OutputGeneratorBuilder addGeneratorLocation(Path generatorLocation) {
68 | this.generatorLocation = generatorLocation;
69 | return this;
70 | }
71 |
72 | public OutputGeneratorBuilder addTemplateLocation(Path templateLocation) {
73 | this.templateLocation = templateLocation;
74 | return this;
75 | }
76 |
77 | public OutputGeneratorBuilder addOutputLocation(Path outputLocation) {
78 | this.outputLocation = outputLocation;
79 | return this;
80 | }
81 |
82 | public OutputGeneratorBuilder addDataModel(Map dataModel) {
83 | this.dataModel = dataModel;
84 | return this;
85 | }
86 |
87 | public OutputGeneratorBuilder addToDataModel(String key, Object val) {
88 | if (this.dataModel == null) {
89 | this.dataModel = new HashMap<>(4);
90 | }
91 | this.dataModel.put(key,val);
92 | return this;
93 | }
94 |
95 | /**
96 | * @throws IllegalStateException if any of the parts of the OutputGenerator were not set.
97 | * @return A new output generator (which is immutable).
98 | */
99 | public OutputGenerator create() {
100 | if (pomModifiedTimestamp == Long.MAX_VALUE) throw new IllegalStateException("Must set the pomModifiedTimestamp");
101 | if (generatorLocation == null) throw new IllegalStateException("Must set a non-null generatorLocation");
102 | if (templateLocation == null) throw new IllegalStateException("Must set a non-null templateLocation");
103 | if (outputLocation == null) throw new IllegalStateException("Must set a non-null outputLocation");
104 | if (dataModel == null) throw new IllegalStateException("Must set a non-null dataModel");
105 | return new OutputGenerator(pomModifiedTimestamp, generatorLocation, templateLocation, outputLocation, dataModel);
106 | }
107 | }
108 |
109 | /**
110 | * Generates an output by applying the model to the template.
111 | * Checks the ages of the inputs against an existing output file to early exit if there is no update.
112 | * @param config Used to load the template from the template name.
113 | */
114 | public void generate(Configuration config) {
115 | //Use "createFile" for testing purposes only
116 | File outputFile = FactoryUtil.createFile(outputLocation.toFile().toString());
117 | File templateFile = templateLocation.toFile();
118 | File generatorFile = generatorLocation.toFile();
119 | if (outputFile.exists()) {
120 | //early exit only if the output file is newer than all files that contribute to its generation
121 | if (outputFile.lastModified() > generatorFile.lastModified()
122 | && outputFile.lastModified() > templateFile.lastModified()
123 | && outputFile.lastModified() > pomModifiedTimestamp) {
124 | return;
125 | }
126 | } else {
127 | File parentDir = outputFile.getParentFile();
128 | if (parentDir.isFile()) {
129 | throw new RuntimeException("Parent directory of output file is a file: " + parentDir.getAbsoluteFile());
130 | }
131 | parentDir.mkdirs();
132 | if (!parentDir.isDirectory()) {
133 | throw new RuntimeException("Could not create directory: " + parentDir.getAbsoluteFile());
134 | }
135 | }
136 |
137 | Template template;
138 | try {
139 | template = config.getTemplate(templateFile.getName());
140 | } catch (Throwable t) {
141 | throw new RuntimeException("Could not read template: " + templateFile.getName(), t);
142 | }
143 |
144 | try (FileWriter writer = new FileWriter(outputFile)) {
145 | template.process(dataModel, writer);
146 | } catch (Throwable t) {
147 | throw new RuntimeException("Could not process template associated with data file: " + generatorLocation, t);
148 | }
149 | }
150 | }
151 |
--------------------------------------------------------------------------------
/pom.xml:
--------------------------------------------------------------------------------
1 |
3 | 4.0.0
4 |
5 | com.oath.freemarker
6 | freemarker-maven-plugin
7 | 1.0.${build}
8 | maven-plugin
9 |
10 | Freemarker Maven Plugin
11 | http://corp.yahoo.com
12 |
13 |
14 | UTF-8
15 | 1.8
16 | 1.8
17 | 3.5.2
18 | 3.5.2
19 | 3.5
20 | 8.1.0
21 | 2.3.23
22 | 2.8.2
23 | 1.32
24 | 6.8
25 | 3.8.0
26 | 100
27 | pre-site
28 |
29 |
30 |
31 |
32 | org.apache.maven
33 | maven-core
34 | ${maven-core.version}
35 | provided
36 |
37 |
38 | com.google.guava
39 | guava
40 |
41 |
42 | org.codehaus.plexus
43 | plexus-utils
44 |
45 |
46 |
47 |
48 | org.apache.maven
49 | maven-plugin-api
50 | ${maven-plugin-api.version}
51 | provided
52 |
53 |
54 | org.apache.maven.plugin-tools
55 | maven-plugin-annotations
56 | ${maven-plugin-annotations.version}
57 | provided
58 |
59 |
60 | org.apache.maven
61 | maven-artifact
62 |
63 |
64 |
65 |
66 | org.eclipse.sisu
67 | org.eclipse.sisu.plexus
68 | 0.3.3
69 |
70 |
71 | org.codehaus.plexus
72 | plexus-utils
73 |
74 |
75 |
76 |
77 | org.jmockit
78 | jmockit
79 | ${jmockit.version}
80 | test
81 |
82 |
83 | com.google.code.gson
84 | gson
85 | ${gson.version}
86 |
87 |
88 | org.freemarker
89 | freemarker
90 | ${freemarker.version}
91 |
92 |
93 | org.testng
94 | testng
95 | ${org.testng.version}
96 | test
97 |
98 |
99 | org.assertj
100 | assertj-core
101 | ${assertj-core.version}
102 | test
103 |
104 |
105 |
106 |
107 |
108 |
109 | org.apache.maven.plugins
110 | maven-compiler-plugin
111 | 3.7.0
112 |
113 | 1.8
114 | 1.8
115 |
116 |
117 |
118 | org.apache.maven.plugins
119 | maven-source-plugin
120 | 3.0.1
121 |
122 |
123 | attach-sources
124 |
125 | jar
126 |
127 |
128 |
129 |
130 |
131 | org.apache.maven.plugins
132 | maven-plugin-plugin
133 | 3.5
134 |
135 | freemarker
136 |
137 |
138 |
139 | default-descriptor
140 |
141 | descriptor
142 |
143 | process-classes
144 |
145 |
146 |
147 |
148 | org.openclover
149 | clover-maven-plugin
150 | 4.2.0
151 |
152 |
153 | clover
154 | ${clover-phase}
155 |
156 | instrument-test
157 | clover
158 | check
159 |
160 |
161 | ${clover-target-percentage}
162 | true
163 | true
164 | ${target_jdk_version}
165 |
166 |
167 |
168 |
169 |
170 |
171 |
172 |
--------------------------------------------------------------------------------
/Code-of-Conduct.md:
--------------------------------------------------------------------------------
1 | # Oath Open Source Code of Conduct
2 |
3 | ## Summary
4 | This Code of Conduct is our way to encourage good behavior and discourage bad behavior in our open source community. We invite participation from many people to bring different perspectives to support this project. We pledge to do our part to foster a welcoming and professional environment free of harassment. We expect participants to communicate professionally and thoughtfully during their involvement with this project.
5 |
6 | Participants may lose their good standing by engaging in misconduct. For example: insulting, threatening, or conveying unwelcome sexual content. We ask participants who observe conduct issues to report the incident directly to the project's Response Team at opensource-conduct@oath.com. Oath will assign a respondent to address the issue. We may remove harassers from this project.
7 |
8 | This code does not replace the terms of service or acceptable use policies of the websites used to support this project. We acknowledge that participants may be subject to additional conduct terms based on their employment which may govern their online expressions.
9 |
10 | ## Details
11 | This Code of Conduct makes our expectations of participants in this community explicit.
12 | * We forbid harassment and abusive speech within this community.
13 | * We request participants to report misconduct to the project’s Response Team.
14 | * We urge participants to refrain from using discussion forums to play out a fight.
15 |
16 | ### Expected Behaviors
17 | We expect participants in this community to conduct themselves professionally. Since our primary mode of communication is text on an online forum (e.g. issues, pull requests, comments, emails, or chats) devoid of vocal tone, gestures, or other context that is often vital to understanding, it is important that participants are attentive to their interaction style.
18 |
19 | * **Assume positive intent.** We ask community members to assume positive intent on the part of other people’s communications. We may disagree on details, but we expect all suggestions to be supportive of the community goals.
20 | * **Respect participants.** We expect participants will occasionally disagree. Even if we reject an idea, we welcome everyone’s participation. Open Source projects are learning experiences. Ask, explore, challenge, and then respectfully assert if you agree or disagree. If your idea is rejected, be more persuasive not bitter.
21 | * **Welcoming to new members.** New members bring new perspectives. Some may raise questions that have been addressed before. Kindly point them to existing discussions. Everyone is new to every project once.
22 | * **Be kind to beginners.** Beginners use open source projects to get experience. They might not be talented coders yet, and projects should not accept poor quality code. But we were all beginners once, and we need to engage kindly.
23 | * **Consider your impact on others.** Your work will be used by others, and you depend on the work of others. We expect community members to be considerate and establish a balance their self-interest with communal interest.
24 | * **Use words carefully.** We may not understand intent when you say something ironic. Poe’s Law suggests that without an emoticon people will misinterpret sarcasm. We ask community members to communicate plainly.
25 | * **Leave with class.** When you wish to resign from participating in this project for any reason, you are free to fork the code and create a competitive project. Open Source explicitly allows this. Your exit should not be dramatic or bitter.
26 |
27 | ### Unacceptable Behaviors
28 | Participants remain in good standing when they do not engage in misconduct or harassment. To elaborate:
29 | * **Don't be a bigot.** Calling out project members by their identity or background in a negative or insulting manner. This includes, but is not limited to, slurs or insinuations related to protected or suspect classes e.g. race, color, citizenship, national origin, political belief, religion, sexual orientation, gender identity and expression, age, size, culture, ethnicity, genetic features, language, profession, national minority statue, mental or physical ability.
30 | * **Don't insult.** Insulting remarks about a person’s lifestyle practices.
31 | * **Don't dox.** Revealing private information about other participants without explicit permission.
32 | * **Don't intimidate.** Threats of violence or intimidation of any project member.
33 | * **Don't creep.** Unwanted sexual attention or content unsuited for the subject of this project.
34 | * **Don't disrupt.** Sustained disruptions in a discussion.
35 | * **Let us help.** Refusal to assist the Response Team to resolve an issue in the community.
36 |
37 | We do not list all forms of harassment, nor imply some forms of harassment are not worthy of action. Any participant who *feels* harassed or *observes* harassment, should report the incident. Victim of harassment should not address grievances in the public forum, as this often intensifies the problem. Report it, and let us address it off-line.
38 |
39 | ### Reporting Issues
40 | If you experience or witness misconduct, or have any other concerns about the conduct of members of this project, please report it by contacting our Response Team at opensource-conduct@oath.com who will handle your report with discretion. Your report should include:
41 | * Your preferred contact information. We cannot process anonymous reports.
42 | * Names (real or usernames) of those involved in the incident.
43 | * Your account of what occurred, and if the incident is ongoing. Please provide links to or transcripts of the publicly available records (e.g. a mailing list archive or a public IRC logger), so that we can review it.
44 | * Any additional information that may be helpful to achieve resolution.
45 |
46 | After filing a report, a representative will contact you directly to review the incident and ask additional questions. If a member of the Oath Response Team is named in an incident report, that member will be recused from handling your incident. If the complaint originates from a member of the Response Team, it will be addressed by a different member of the Response Team. We will consider reports to be confidential for the purpose of protecting victims of abuse.
47 |
48 | ### Scope
49 | Oath will assign a Response Team member with admin rights on the project and legal rights on the project copyright. The Response Team is empowered to restrict some privileges to the project as needed. Since this project is governed by an open source license, any participant may fork the code under the terms of the project license. The Response Team’s goal is to preserve the project if possible, and will restrict or remove participation from those who disrupt the project.
50 |
51 | This code does not replace the terms of service or acceptable use policies that are provided by the websites used to support this community. Nor does this code apply to communications or actions that take place outside of the context of this community. Many participants in this project are also subject to codes of conduct based on their employment. This code is a social-contract that informs participants of our social expectations. It is not a terms of service or legal contract.
52 |
53 | ## License and Acknowledgment.
54 | This text is shared under the [CC-BY-4.0 license](https://creativecommons.org/licenses/by/4.0/). This code is based on a study conducted by the [TODO Group](https://todogroup.org/) of many codes used in the open source community. If you have feedback about this code, contact our Response Team at the address listed above.
55 |
--------------------------------------------------------------------------------
/src/test/java/com/oath/maven/plugin/freemarker/GeneratingFileVisitorTest.java:
--------------------------------------------------------------------------------
1 | // Copyright 2018, Oath Inc.
2 | // Licensed under the terms of the Apache 2.0 license. See the LICENSE file in the project root for terms.
3 |
4 | package com.oath.maven.plugin.freemarker;
5 |
6 | import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
7 |
8 | import java.io.File;
9 | import java.io.IOException;
10 | import java.lang.reflect.Type;
11 | import java.nio.charset.StandardCharsets;
12 | import java.nio.file.FileVisitResult;
13 | import java.nio.file.Files;
14 | import java.nio.file.Path;
15 | import java.nio.file.attribute.BasicFileAttributes;
16 | import java.util.*;
17 |
18 | import org.apache.maven.execution.MavenSession;
19 | import org.apache.maven.project.MavenProject;
20 | import org.junit.Assert;
21 | import org.testng.annotations.BeforeClass;
22 | import org.testng.annotations.BeforeMethod;
23 | import org.testng.annotations.Test;
24 |
25 | import com.google.gson.Gson;
26 | import com.google.gson.stream.JsonReader;
27 |
28 | import freemarker.cache.FileTemplateLoader;
29 | import freemarker.template.Configuration;
30 | import mockit.Expectations;
31 | import mockit.Mocked;
32 |
33 | public class GeneratingFileVisitorTest extends Assert {
34 |
35 | private static File testDir = new File("src/test/data/generating-file-visitor");
36 | private static File dataDir = new File(testDir, "data");
37 | private static File templateDir = new File(testDir, "template");
38 | private static File outputDir = new File("target/test-output/generating-file-visitor");
39 | private static Map builders = new HashMap<>();
40 | private Configuration config;
41 | private Properties pomProperties = new Properties();
42 |
43 | @BeforeClass
44 | public static void beforeClass() throws IOException {
45 | builders.put(".json", JsonPropertiesProvider.create(dataDir,templateDir,outputDir));
46 | // Clean output dir before each run.
47 | File outputDir = new File("target/test-output/generating-file-visitor");
48 | if (outputDir.exists()) {
49 | // Recursively delete output from previous run.
50 | Files.walk(outputDir.toPath())
51 | .sorted(Comparator.reverseOrder())
52 | .map(Path::toFile)
53 | .forEach(File::delete);
54 | }
55 | }
56 |
57 | @BeforeMethod
58 | public void before() throws IOException {
59 | if (!testDir.isDirectory()) {
60 | throw new RuntimeException("Can't find required test data directory. "
61 | + "If running test outside of maven, make sure working directory is the project directory. "
62 | + "Looking for: " + testDir);
63 | }
64 |
65 | config = new Configuration(Configuration.VERSION_2_3_23);
66 | config.setDefaultEncoding("UTF-8");
67 | config.setTemplateLoader(new FileTemplateLoader(templateDir));
68 | pomProperties.put("pomVar", "pom value");
69 | }
70 |
71 | @Test
72 | public void functionalHappyPathTestNoDataModel(
73 | @Mocked MavenSession session,
74 | @Mocked MavenProject project,
75 | @Mocked File mockFile,
76 | @Mocked BasicFileAttributes attrs) throws IOException {
77 | List projects = new ArrayList<>();
78 | projects.add(project);
79 | new Expectations(session, project, mockFile) {{
80 | session.getCurrentProject(); result = project;
81 | session.getAllProjects(); result = projects;
82 | project.getProperties(); result = pomProperties;
83 | attrs.isRegularFile(); result = true;
84 | project.getFile(); result = mockFile;
85 | mockFile.lastModified(); result = 10;
86 | }};
87 |
88 | File file = new File(dataDir, "mydir/success-test-2.txt.json");
89 | GeneratingFileVisitor gfv = GeneratingFileVisitor.create(config, session, builders);
90 | assertEquals(FileVisitResult.CONTINUE, gfv.visitFile(file.toPath(), attrs));
91 |
92 | File outputFile = new File(outputDir, "mydir/success-test-2.txt");
93 | assertTrue(outputFile.isFile());
94 | List lines = Files.readAllLines(outputFile.toPath(), StandardCharsets.UTF_8);
95 | assertEquals(1, lines.size());
96 | assertEquals("This is a test freemarker template. Test pom data: 'pom value'.", lines.get(0));
97 | }
98 |
99 | @Test
100 | public void functionalHappyPathTest(
101 | @Mocked MavenSession session,
102 | @Mocked MavenProject project,
103 | @Mocked File mockFile,
104 | @Mocked BasicFileAttributes attrs) throws IOException {
105 | List projects = new ArrayList<>();
106 | projects.add(project);
107 | new Expectations(session, project, mockFile) {{
108 | session.getCurrentProject(); result = project;
109 | session.getAllProjects(); result = projects;
110 | project.getProperties(); result = pomProperties;
111 | attrs.isRegularFile(); result = true;
112 | project.getFile(); result = mockFile;
113 | mockFile.lastModified(); result = 10;
114 | }};
115 |
116 | File file = new File(dataDir, "mydir/success-test.txt.json");
117 | GeneratingFileVisitor gfv = GeneratingFileVisitor.create(config, session, builders);
118 | assertEquals(FileVisitResult.CONTINUE, gfv.visitFile(file.toPath(), attrs));
119 |
120 | File outputFile = new File(outputDir, "mydir/success-test.txt");
121 | assertTrue(outputFile.isFile());
122 | List lines = Files.readAllLines(outputFile.toPath(), StandardCharsets.UTF_8);
123 | assertEquals(1, lines.size());
124 | assertEquals("This is a test freemarker template. Test json data: 'test value'. Test pom data: 'pom value'.", lines.get(0));
125 | }
126 |
127 | @Test
128 | public void visitFile_badExtensionTest(
129 | @Mocked MavenSession session,
130 | @Mocked MavenProject project,
131 | @Mocked File mockFile,
132 | @Mocked BasicFileAttributes attrs) throws IOException {
133 | List projects = new ArrayList<>();
134 | projects.add(project);
135 | new Expectations(session, project, mockFile) {{
136 | attrs.isRegularFile(); result = true;
137 | session.getAllProjects(); result = projects;
138 | project.getFile(); result = mockFile;
139 | mockFile.lastModified(); result = 10;
140 | }};
141 | // Test file without .json suffix.
142 | File file = new File(dataDir, "mydir/bad-extension-test.txt");
143 | GeneratingFileVisitor gfv = GeneratingFileVisitor.create(config, session, builders);
144 | assertThatExceptionOfType(RuntimeException.class).isThrownBy(() -> {
145 | gfv.visitFile(file.toPath(), attrs);
146 | }).withMessage("Unknown file extension: " + file.toPath());
147 | }
148 |
149 | @Test
150 | public void visitFile_notRegularFileTest(@Mocked MavenSession session,
151 | @Mocked MavenProject project,
152 | @Mocked BasicFileAttributes attrs,
153 | @Mocked File mockFile
154 | ) {
155 | List projects = new ArrayList<>();
156 | projects.add(project);
157 | new Expectations(session, project, mockFile) {{
158 | attrs.isRegularFile(); result = false;
159 | session.getAllProjects(); result = projects;
160 | project.getFile(); result = mockFile;
161 | mockFile.lastModified(); result = 10;
162 | }};
163 | // FYI: if you change above result to true, test will fail trying to read the 'mydir' directory
164 | // as a json file.
165 | File dir = new File(dataDir, "mydir");
166 | GeneratingFileVisitor gfv = GeneratingFileVisitor.create(config, session, builders);
167 | assertEquals(FileVisitResult.CONTINUE, gfv.visitFile(dir.toPath(), attrs));
168 | }
169 | }
170 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 |
2 | # ARCHIVED
3 |
4 | # freemarker-maven-plugin
5 | > A flexible plugin to generate source files from FreeMarker templates and JSON data.
6 |
7 | ## Table of contents
8 |
9 | - [Background](#background)
10 | - [Install](#install)
11 | - [Usage](#usage)
12 | - [FreeMarker Template Files](#freemarker-template-files)
13 | - [JSON Generator Files](#json-generator-files)
14 | - [Using POM Properties During Generation](#using-pom-properties-during-generation)
15 | - [FreeMarker Configuration](#freemarker-configuration)
16 | - [Incremental Builds](#incremental-builds)
17 | - [Code Coverage](#code-coverage)
18 | - [Contributing](#contributing)
19 | - [License](#license)
20 |
21 | ## Background
22 | This plugin allows you to generate files from [FreeMarker](https://freemarker.apache.org/) template files and JSON data. It was created to fill a hole in the FreeMarker ecosystem: there aren't any flexible, open source code generation plugins for Maven. This plugin generates source files from FreeMarker templates with a flexible process that includes the ability to:
23 |
24 | - Generate multiple source files from a single template,
25 | - Generate source files during multiple steps in the build process such as testing, and
26 | - Specify distinct locations for the templates and data models for different stages of the build.
27 |
28 | ## Install
29 | ### pom.xml
30 |
31 | Add the following snippet within the `` tag of your pom.xml:
32 |
33 | ```xml
34 |
35 | com.oath
36 | freemarker-maven-plugin
37 | ${freemarker-maven-plugin.version}
38 |
39 |
40 | 2.3.23
41 |
42 |
43 |
46 |
47 | freemarker
48 |
49 | generate-sources
50 |
51 |
52 | generate
53 |
54 |
55 |
56 | src/main/freemarker
57 |
58 | src/main/freemarker/template
59 |
60 | src/main/freemarker/generator
61 |
62 | target/generated-sources/freemarker
63 |
64 |
65 |
66 |
67 | ```
68 |
69 | ## Usage
70 |
71 | ### FreeMarker Template Files
72 | FreeMarker template files must reside in the `templateDirectory`. For the default configuration,
73 | this is: `src/main/freemarker/template`.
74 |
75 | By convention, file names for FreeMarker template files use the .ftl extension. For details on the FreeMarker
76 | template syntax, see: [Getting Started](https://freemarker.apache.org/docs/dgui_quickstart.html) and
77 | [Template Language Reference](https://freemarker.apache.org/docs/ref.html).
78 |
79 | ### JSON Generator Files
80 | The JSON generator files must reside in the `generatorDirectory`. For the default
81 | configuration, this is: `src/main/freemarker/generator`.
82 |
83 | For each JSON generator file, freemarker-maven-plugin will generate a file under the outputDirectory.
84 | The name of the generated file will be based on the name of the JSON data file. For example,
85 | the following JSON file:
86 | ```
87 | /data/my/package/MyClass.java.json
88 | ```
89 | will result in the following file being generated:
90 | ```
91 | /my/package/MyClass.java
92 | ```
93 |
94 | This plugin parses the JSON generator file's `dataModel` field into a `Map` instance (hereafter, referred
95 | to as the data model). If the dataModel field is empty, an empty map will be created.
96 |
97 | Here are some additional details you need to know.
98 |
99 | - This plugin *requires* one top-level field in the JSON data file: `templateName`. This field is used to locate the template file under `/template` that is used to generate the file. This plugin provides the data model to FreeMarker as the data model to process the template identified by `templateName`.
100 | - The parser allows for comments.
101 | - This plugin currently assumes that the JSON data file encoded using UTF-8.
102 |
103 | Here is an example JSON data file:
104 | ```json
105 | {
106 | // An end-of-line comment.
107 | # Another end-of-line comment
108 | "templateName": "my-template.ftl", #Required
109 | "dataModel": { #Optional
110 | /* A multi-line
111 | comment */
112 | "myString": "a string",
113 | "myNumber": 1,
114 | "myListOfStrings": ["s1", "s2"],
115 | "myListOfNumbers": [1, 2],
116 | "myMap": {
117 | "key1": "value1",
118 | "key2": 2
119 | }
120 | }
121 | }
122 | ```
123 |
124 | ### Using POM Properties During Generation
125 | After parsing the JSON file, the plugin will add
126 | a `pomProperties` entry into the data model, which is a map itself, that contains the properties defined in the pom. Thus, your template can reference the pom property `my_property` using `${pomProperties.my_property}`. If you have a period or dash in the property name, use `${pomProperties["my.property"]}`.
127 |
128 |
129 |
130 | ### FreeMarker Configuration
131 |
132 | Typically, users of this plugin do not need to mess with the FreeMarker configuration. This plugin explicitly sets two FreeMarker configurations:
133 |
134 | 1. the default encoding is set to UTF-8
135 | 2. the template loader is set to be a FileTemplateLoader that reads from `templateDirectory`.
136 |
137 | If you need to override these configs or set your own, you can put them in a
138 | `/freemarker.properties` file. If that file exists, this plugin will read it into a java Properties instance and pass it to freemarker.core.Configurable.setSettings() to establish the FreeMarker configuration. See this [javadoc](https://freemarker.apache.org/docs/api/freemarker/template/Configuration.html#setSetting-java.lang.String-java.lang.String-) for configuration details.
139 |
140 |
141 | ### Incremental Builds
142 | This plugin supports incremental builds; it only generates sources if the generator file, template file, or pom file have timestamps newer than any existing output file. To force a rebuild if these conditions are not met (for example, if you pass in a model parameter on the command line), first run `mvn clean`.
143 |
144 | ## Code Coverage
145 |
146 | By default, the code coverage report is not generated. It is generated by screwdriver jobs. You can generate code coverage on your dev machine with the following maven command:
147 | ```bash
148 | mvn clean initialize -Dclover-phase=initialize
149 | ```
150 | Bring up the coverage report by pointing your browser to target/site/clover/dashboard.html under the root directory of the local repository.
151 |
152 |
153 | ## Contributing
154 | See [Contributing.md](Contributing.md)
155 |
156 | ## License
157 | Licenced under the Apache 2.0 license. See: [LICENSE](LICENSE)
158 |
159 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 |
2 | Apache License
3 | Version 2.0, January 2004
4 | http://www.apache.org/licenses/
5 |
6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7 |
8 | 1. Definitions.
9 |
10 | "License" shall mean the terms and conditions for use, reproduction,
11 | and distribution as defined by Sections 1 through 9 of this document.
12 |
13 | "Licensor" shall mean the copyright owner or entity authorized by
14 | the copyright owner that is granting the License.
15 |
16 | "Legal Entity" shall mean the union of the acting entity and all
17 | other entities that control, are controlled by, or are under common
18 | control with that entity. For the purposes of this definition,
19 | "control" means (i) the power, direct or indirect, to cause the
20 | direction or management of such entity, whether by contract or
21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
22 | outstanding shares, or (iii) beneficial ownership of such entity.
23 |
24 | "You" (or "Your") shall mean an individual or Legal Entity
25 | exercising permissions granted by this License.
26 |
27 | "Source" form shall mean the preferred form for making modifications,
28 | including but not limited to software source code, documentation
29 | source, and configuration files.
30 |
31 | "Object" form shall mean any form resulting from mechanical
32 | transformation or translation of a Source form, including but
33 | not limited to compiled object code, generated documentation,
34 | and conversions to other media types.
35 |
36 | "Work" shall mean the work of authorship, whether in Source or
37 | Object form, made available under the License, as indicated by a
38 | copyright notice that is included in or attached to the work
39 | (an example is provided in the Appendix below).
40 |
41 | "Derivative Works" shall mean any work, whether in Source or Object
42 | form, that is based on (or derived from) the Work and for which the
43 | editorial revisions, annotations, elaborations, or other modifications
44 | represent, as a whole, an original work of authorship. For the purposes
45 | of this License, Derivative Works shall not include works that remain
46 | separable from, or merely link (or bind by name) to the interfaces of,
47 | the Work and Derivative Works thereof.
48 |
49 | "Contribution" shall mean any work of authorship, including
50 | the original version of the Work and any modifications or additions
51 | to that Work or Derivative Works thereof, that is intentionally
52 | submitted to Licensor for inclusion in the Work by the copyright owner
53 | or by an individual or Legal Entity authorized to submit on behalf of
54 | the copyright owner. For the purposes of this definition, "submitted"
55 | means any form of electronic, verbal, or written communication sent
56 | to the Licensor or its representatives, including but not limited to
57 | communication on electronic mailing lists, source code control systems,
58 | and issue tracking systems that are managed by, or on behalf of, the
59 | Licensor for the purpose of discussing and improving the Work, but
60 | excluding communication that is conspicuously marked or otherwise
61 | designated in writing by the copyright owner as "Not a Contribution."
62 |
63 | "Contributor" shall mean Licensor and any individual or Legal Entity
64 | on behalf of whom a Contribution has been received by Licensor and
65 | subsequently incorporated within the Work.
66 |
67 | 2. Grant of Copyright License. Subject to the terms and conditions of
68 | this License, each Contributor hereby grants to You a perpetual,
69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70 | copyright license to reproduce, prepare Derivative Works of,
71 | publicly display, publicly perform, sublicense, and distribute the
72 | Work and such Derivative Works in Source or Object form.
73 |
74 | 3. Grant of Patent License. Subject to the terms and conditions of
75 | this License, each Contributor hereby grants to You a perpetual,
76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77 | (except as stated in this section) patent license to make, have made,
78 | use, offer to sell, sell, import, and otherwise transfer the Work,
79 | where such license applies only to those patent claims licensable
80 | by such Contributor that are necessarily infringed by their
81 | Contribution(s) alone or by combination of their Contribution(s)
82 | with the Work to which such Contribution(s) was submitted. If You
83 | institute patent litigation against any entity (including a
84 | cross-claim or counterclaim in a lawsuit) alleging that the Work
85 | or a Contribution incorporated within the Work constitutes direct
86 | or contributory patent infringement, then any patent licenses
87 | granted to You under this License for that Work shall terminate
88 | as of the date such litigation is filed.
89 |
90 | 4. Redistribution. You may reproduce and distribute copies of the
91 | Work or Derivative Works thereof in any medium, with or without
92 | modifications, and in Source or Object form, provided that You
93 | meet the following conditions:
94 |
95 | (a) You must give any other recipients of the Work or
96 | Derivative Works a copy of this License; and
97 |
98 | (b) You must cause any modified files to carry prominent notices
99 | stating that You changed the files; and
100 |
101 | (c) You must retain, in the Source form of any Derivative Works
102 | that You distribute, all copyright, patent, trademark, and
103 | attribution notices from the Source form of the Work,
104 | excluding those notices that do not pertain to any part of
105 | the Derivative Works; and
106 |
107 | (d) If the Work includes a "NOTICE" text file as part of its
108 | distribution, then any Derivative Works that You distribute must
109 | include a readable copy of the attribution notices contained
110 | within such NOTICE file, excluding those notices that do not
111 | pertain to any part of the Derivative Works, in at least one
112 | of the following places: within a NOTICE text file distributed
113 | as part of the Derivative Works; within the Source form or
114 | documentation, if provided along with the Derivative Works; or,
115 | within a display generated by the Derivative Works, if and
116 | wherever such third-party notices normally appear. The contents
117 | of the NOTICE file are for informational purposes only and
118 | do not modify the License. You may add Your own attribution
119 | notices within Derivative Works that You distribute, alongside
120 | or as an addendum to the NOTICE text from the Work, provided
121 | that such additional attribution notices cannot be construed
122 | as modifying the License.
123 |
124 | You may add Your own copyright statement to Your modifications and
125 | may provide additional or different license terms and conditions
126 | for use, reproduction, or distribution of Your modifications, or
127 | for any such Derivative Works as a whole, provided Your use,
128 | reproduction, and distribution of the Work otherwise complies with
129 | the conditions stated in this License.
130 |
131 | 5. Submission of Contributions. Unless You explicitly state otherwise,
132 | any Contribution intentionally submitted for inclusion in the Work
133 | by You to the Licensor shall be under the terms and conditions of
134 | this License, without any additional terms or conditions.
135 | Notwithstanding the above, nothing herein shall supersede or modify
136 | the terms of any separate license agreement you may have executed
137 | with Licensor regarding such Contributions.
138 |
139 | 6. Trademarks. This License does not grant permission to use the trade
140 | names, trademarks, service marks, or product names of the Licensor,
141 | except as required for reasonable and customary use in describing the
142 | origin of the Work and reproducing the content of the NOTICE file.
143 |
144 | 7. Disclaimer of Warranty. Unless required by applicable law or
145 | agreed to in writing, Licensor provides the Work (and each
146 | Contributor provides its Contributions) on an "AS IS" BASIS,
147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148 | implied, including, without limitation, any warranties or conditions
149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150 | PARTICULAR PURPOSE. You are solely responsible for determining the
151 | appropriateness of using or redistributing the Work and assume any
152 | risks associated with Your exercise of permissions under this License.
153 |
154 | 8. Limitation of Liability. In no event and under no legal theory,
155 | whether in tort (including negligence), contract, or otherwise,
156 | unless required by applicable law (such as deliberate and grossly
157 | negligent acts) or agreed to in writing, shall any Contributor be
158 | liable to You for damages, including any direct, indirect, special,
159 | incidental, or consequential damages of any character arising as a
160 | result of this License or out of the use or inability to use the
161 | Work (including but not limited to damages for loss of goodwill,
162 | work stoppage, computer failure or malfunction, or any and all
163 | other commercial damages or losses), even if such Contributor
164 | has been advised of the possibility of such damages.
165 |
166 | 9. Accepting Warranty or Additional Liability. While redistributing
167 | the Work or Derivative Works thereof, You may choose to offer,
168 | and charge a fee for, acceptance of support, warranty, indemnity,
169 | or other liability obligations and/or rights consistent with this
170 | License. However, in accepting such obligations, You may act only
171 | on Your own behalf and on Your sole responsibility, not on behalf
172 | of any other Contributor, and only if You agree to indemnify,
173 | defend, and hold each Contributor harmless for any liability
174 | incurred by, or claims asserted against, such Contributor by reason
175 | of your accepting any such warranty or additional liability.
176 |
177 | END OF TERMS AND CONDITIONS
--------------------------------------------------------------------------------
/src/test/java/com/oath/maven/plugin/freemarker/OutputGeneratorTest.java:
--------------------------------------------------------------------------------
1 | // Copyright 2018, Oath Inc.
2 | // Licensed under the terms of the Apache 2.0 license. See the LICENSE file in the project root for terms.
3 |
4 | package com.oath.maven.plugin.freemarker;
5 |
6 | import com.google.gson.Gson;
7 | import com.google.gson.stream.JsonReader;
8 | import freemarker.cache.FileTemplateLoader;
9 | import freemarker.template.Configuration;
10 | import mockit.Expectations;
11 | import mockit.Mocked;
12 | import org.apache.maven.execution.MavenSession;
13 | import org.apache.maven.project.MavenProject;
14 | import org.assertj.core.api.Assertions;
15 | import org.testng.annotations.BeforeClass;
16 | import org.testng.annotations.Test;
17 | import org.testng.annotations.BeforeMethod;
18 |
19 | import java.io.File;
20 | import java.io.IOException;
21 | import java.lang.reflect.Type;
22 | import java.nio.charset.StandardCharsets;
23 | import java.nio.file.FileVisitResult;
24 | import java.nio.file.Files;
25 | import java.nio.file.Path;
26 | import java.nio.file.attribute.BasicFileAttributes;
27 | import java.util.*;
28 |
29 | import static junit.framework.Assert.assertEquals;
30 | import static org.assertj.core.api.AssertionsForClassTypes.assertThatExceptionOfType;
31 | import static org.junit.Assert.assertArrayEquals;
32 | import static org.junit.Assert.assertTrue;
33 |
34 | public class OutputGeneratorTest {
35 |
36 | private File testDir = new File("src/test/data/generating-file-visitor");
37 | private File dataDir = new File(testDir, "data");
38 | private File templateDir = new File(testDir, "template");
39 | private File outputDir = new File("target/test-output/generating-file-visitor");
40 | private Configuration config;
41 | private Map dataModel = new HashMap();
42 |
43 | @BeforeMethod
44 | public void setupDataModel() {
45 | dataModel.clear();
46 | dataModel.put("testVar", "test value");
47 | dataModel.put("pomProperties", new HashMap());
48 | ((Map)dataModel.get("pomProperties")).put("pomVar", "pom value");
49 | }
50 |
51 | @BeforeClass
52 | public static void cleanFields() throws IOException {
53 | // Clean output dir before each run.
54 | File outputDir = new File("target/test-output/generating-file-visitor");
55 | if (outputDir.exists()) {
56 | // Recursively delete output from previous run.
57 | Files.walk(outputDir.toPath())
58 | .sorted(Comparator.reverseOrder())
59 | .map(Path::toFile)
60 | .forEach(File::delete);
61 | }
62 | }
63 |
64 | @BeforeMethod
65 | public void before() throws IOException {
66 | if (!testDir.isDirectory()) {
67 | throw new RuntimeException("Can't find required test data directory. "
68 | + "If running test outside of maven, make sure working directory is the project directory. "
69 | + "Looking for: " + testDir);
70 | }
71 |
72 | config = new Configuration(Configuration.VERSION_2_3_23);
73 | config.setDefaultEncoding("UTF-8");
74 | config.setTemplateLoader(new FileTemplateLoader(templateDir));
75 | }
76 |
77 | @Test
78 | public void createTest() {
79 | OutputGenerator.OutputGeneratorBuilder builder = OutputGenerator.builder();
80 | assertThatExceptionOfType(IllegalStateException.class).isThrownBy(() -> {
81 | builder.create();
82 | }).withMessage("Must set the pomModifiedTimestamp");
83 |
84 | builder.addPomLastModifiedTimestamp(0);
85 | assertThatExceptionOfType(IllegalStateException.class).isThrownBy(() -> {
86 | builder.create();
87 | }).withMessage("Must set a non-null generatorLocation");
88 |
89 | File file = new File(dataDir, "mydir/success-test.txt.json");
90 | builder.addGeneratorLocation(file.toPath());
91 | assertThatExceptionOfType(IllegalStateException.class).isThrownBy(() -> {
92 | builder.create();
93 | }).withMessage("Must set a non-null templateLocation");
94 |
95 | File templateFile = new File(templateDir, "test.ftl");
96 | builder.addTemplateLocation(templateFile.toPath());
97 | assertThatExceptionOfType(IllegalStateException.class).isThrownBy(() -> {
98 | builder.create();
99 | }).withMessage("Must set a non-null outputLocation");
100 |
101 | File outputFile = new File(outputDir, "mydir/success-test.txt");
102 | builder.addOutputLocation(outputFile.toPath());
103 |
104 | assertThatExceptionOfType(IllegalStateException.class).isThrownBy(() -> {
105 | builder.create();
106 | }).withMessage("Must set a non-null dataModel");
107 |
108 | builder.addDataModel(dataModel);
109 | OutputGenerator generator = builder.create();
110 |
111 | assertEquals(0, generator.pomModifiedTimestamp);
112 | assertEquals(file.toPath(), generator.generatorLocation);
113 | assertEquals(templateFile.toPath(), generator.templateLocation);
114 | assertEquals(outputFile.toPath(), generator.outputLocation);
115 | assertEquals(dataModel.size(), generator.dataModel.size());
116 | assertArrayEquals(dataModel.entrySet().toArray(), generator.dataModel.entrySet().toArray());
117 | }
118 |
119 | @Test
120 | public void generate_SuccessTest()
121 | throws IOException {
122 | OutputGenerator.OutputGeneratorBuilder builder = OutputGenerator.builder();
123 | builder.addPomLastModifiedTimestamp(0);
124 | File file = new File(dataDir, "mydir/success-test.txt.json");
125 | builder.addGeneratorLocation(file.toPath());
126 | File outputFile = new File(outputDir, "mydir/success-test.txt");
127 | builder.addOutputLocation(outputFile.toPath());
128 | File templateFile = new File(templateDir, "test.ftl");
129 | builder.addTemplateLocation(templateFile.toPath());
130 | builder.addDataModel(dataModel);
131 | OutputGenerator generator = builder.create();
132 | generator.generate(config);
133 |
134 | assertTrue(outputFile.isFile());
135 | List lines = Files.readAllLines(outputFile.toPath(), StandardCharsets.UTF_8);
136 | assertEquals(1, lines.size());
137 | assertEquals("This is a test freemarker template. Test json data: 'test value'. Test pom data: 'pom value'.", lines.get(0));
138 |
139 | // Process same file again, should not regenerate file.
140 | long lastMod = outputFile.lastModified();
141 | generator.generate(config);
142 | assertEquals(lastMod, outputFile.lastModified());
143 |
144 | // Set mod time to before json file.
145 | lastMod = file.lastModified() - 1000; // File system may only keep 1 second precision.
146 | outputFile.setLastModified(lastMod);
147 | generator.generate(config);
148 | assertTrue(lastMod < outputFile.lastModified());
149 |
150 | // Set mod time to before template file.
151 | lastMod = templateFile.lastModified() - 1000; // File system may only keep 1 second precision.
152 | outputFile.setLastModified(lastMod);
153 | generator.generate(config);
154 | assertTrue(lastMod < outputFile.lastModified());
155 | }
156 |
157 | @Test
158 | public void generate_badTemplateNameTest(){
159 | OutputGenerator.OutputGeneratorBuilder builder = OutputGenerator.builder();
160 | builder.addPomLastModifiedTimestamp(0);
161 | File file = new File(dataDir, "mydir/bad-template-name.txt.json");
162 | builder.addGeneratorLocation(file.toPath());
163 | File outputFile = new File(outputDir, "mydir/bad-template-name.txt");
164 | builder.addOutputLocation(outputFile.toPath());
165 | File templateFile = new File(templateDir, "missing.ftl"); //this doesn't exist
166 | builder.addTemplateLocation(templateFile.toPath());
167 | builder.addDataModel(dataModel);
168 | OutputGenerator generator = builder.create();
169 | Assertions.assertThatExceptionOfType(RuntimeException.class).isThrownBy(() -> {
170 | generator.generate(config);
171 | }).withMessage("Could not read template: missing.ftl");
172 | }
173 |
174 | @Test
175 | public void generate_missingVarTest() {
176 | OutputGenerator.OutputGeneratorBuilder builder = OutputGenerator.builder();
177 | builder.addPomLastModifiedTimestamp(0);
178 | File file = new File(dataDir, "mydir/missing-var-test.txt.json");
179 | builder.addGeneratorLocation(file.toPath());
180 | File outputFile = new File(outputDir, "mydir/missing-var-test.txt");
181 | builder.addOutputLocation(outputFile.toPath());
182 | File templateFile = new File(templateDir, "test.ftl"); //this is missing a
183 | builder.addTemplateLocation(templateFile.toPath());
184 | dataModel.remove("testVar");
185 | builder.addDataModel(dataModel);
186 | OutputGenerator generator = builder.create();
187 | Assertions.assertThatExceptionOfType(RuntimeException.class).isThrownBy(() -> {
188 | generator.generate(config);
189 | }).withMessage("Could not process template associated with data file: src/test/data/generating-file-visitor/data/mydir/missing-var-test.txt.json");
190 | }
191 |
192 | @Test
193 | public void generate_badParentTest() throws IOException {
194 | OutputGenerator.OutputGeneratorBuilder builder = OutputGenerator.builder();
195 | builder.addPomLastModifiedTimestamp(0);
196 | File file = new File(dataDir, "badParent/bad-parent-test.txt.json");
197 | builder.addGeneratorLocation(file.toPath());
198 | File outputFile = new File(outputDir, "badParent/bad-parent-test.txt");
199 | builder.addOutputLocation(outputFile.toPath());
200 | File templateFile = new File(templateDir, "test.ftl"); //this is missing a
201 | builder.addTemplateLocation(templateFile.toPath());
202 | builder.addDataModel(dataModel);
203 | OutputGenerator generator = builder.create();
204 | outputDir.mkdirs();
205 | outputFile.getParentFile().createNewFile();
206 |
207 | Assertions.assertThatExceptionOfType(RuntimeException.class).isThrownBy(() -> {
208 | generator.generate(config);
209 | }).withMessage("Parent directory of output file is a file: " + outputFile.getParentFile().getAbsolutePath());
210 | }
211 |
212 | @Test
213 | public void generate_cantCreateOutputFileParentDirTest(
214 | @Mocked FactoryUtil factoryUtil,
215 | @Mocked File mockOutputFile) throws IOException {
216 |
217 | File parentDir = new File("target/test-output/generating-file-visitor/mydir");
218 | new Expectations(mockOutputFile, parentDir) {{
219 | FactoryUtil.createFile(anyString); result = mockOutputFile;
220 | mockOutputFile.exists(); result = false;
221 | mockOutputFile.getParentFile(); result = parentDir;
222 | parentDir.isDirectory(); result = false;
223 | }};
224 |
225 | OutputGenerator.OutputGeneratorBuilder builder = OutputGenerator.builder();
226 | builder.addPomLastModifiedTimestamp(0);
227 | File file = new File(dataDir, "mydir/missing-var-test.txt.json");
228 | builder.addGeneratorLocation(file.toPath());
229 | File outputFile = new File(outputDir, "mydir/missing-var-test.txt");
230 | builder.addOutputLocation(outputFile.toPath());
231 | File templateFile = new File(templateDir, "test.ftl"); //this is missing a
232 | builder.addTemplateLocation(templateFile.toPath());
233 | builder.addDataModel(dataModel);
234 | OutputGenerator generator = builder.create();
235 | Assertions.assertThatExceptionOfType(RuntimeException.class).isThrownBy(() -> {
236 | generator.generate(config);
237 | }).withMessage("Could not create directory: " + parentDir.getAbsoluteFile().toString());
238 | }
239 | }
240 |
--------------------------------------------------------------------------------
/src/test/java/com/oath/maven/plugin/freemarker/FreeMarkerMojoTest.java:
--------------------------------------------------------------------------------
1 | // Copyright 2018, Oath Inc.
2 | // Licensed under the terms of the Apache 2.0 license. See the LICENSE file in the project root for terms.
3 |
4 | package com.oath.maven.plugin.freemarker;
5 |
6 | import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
7 |
8 | import java.io.File;
9 | import java.io.IOException;
10 | import java.nio.file.FileVisitor;
11 | import java.nio.file.Files;
12 | import java.nio.file.Path;
13 | import java.util.Comparator;
14 | import java.util.Map;
15 | import java.util.Properties;
16 |
17 | import org.apache.maven.execution.MavenSession;
18 | import org.apache.maven.plugin.MojoExecution;
19 | import org.apache.maven.plugin.MojoExecutionException;
20 | import org.apache.maven.plugin.MojoFailureException;
21 | import org.apache.maven.project.MavenProject;
22 | import org.junit.Assert;
23 | import org.testng.annotations.BeforeClass;
24 | import org.testng.annotations.Test;
25 |
26 | import freemarker.cache.FileTemplateLoader;
27 | import freemarker.cache.TemplateLoader;
28 | import freemarker.template.Configuration;
29 | import mockit.Deencapsulation;
30 | import mockit.Expectations;
31 | import mockit.Mocked;
32 | import mockit.Verifications;
33 |
34 | public class FreeMarkerMojoTest extends Assert {
35 |
36 | public static final File testOutputDir = new File("target/test-output/freemarker-mojo");
37 |
38 | @BeforeClass
39 | public static void beforeClass() throws IOException {
40 | // Clean output dir before each run.
41 | if (testOutputDir.exists()) {
42 | // Recursively delete output from previous run.
43 | Files.walk(testOutputDir.toPath())
44 | .sorted(Comparator.reverseOrder())
45 | .map(Path::toFile)
46 | .forEach(File::delete);
47 | }
48 | }
49 |
50 | @Test
51 | public void executeTest(
52 | @Mocked MavenSession session,
53 | @Mocked MavenProject project,
54 | @Mocked MojoExecution mojoExecution,
55 | @Mocked GeneratingFileVisitor generatingFileVisitor,
56 | @Mocked Files files
57 | ) throws MojoExecutionException, MojoFailureException, IOException {
58 |
59 | new Expectations(mojoExecution, generatingFileVisitor) {{
60 | mojoExecution.getLifecyclePhase(); result = "generate-sources";
61 | session.getCurrentProject(); result = project;
62 | }};
63 |
64 | FreeMarkerMojo mojo = new FreeMarkerMojo();
65 |
66 | // Validate freeMarkerVersion is required.
67 | assertThatExceptionOfType(MojoExecutionException.class).isThrownBy(() -> {
68 | mojo.execute();
69 | }).withMessage("freeMarkerVersion is required");
70 |
71 | Deencapsulation.setField(mojo, "freeMarkerVersion", "");
72 | assertThatExceptionOfType(MojoExecutionException.class).isThrownBy(() -> {
73 | mojo.execute();
74 | }).withMessage("freeMarkerVersion is required");
75 |
76 | File testCaseOutputDir = new File(testOutputDir, "executeTest");
77 | Deencapsulation.setField(mojo, "freeMarkerVersion", "2.3.23");
78 | Deencapsulation.setField(mojo, "sourceDirectory", testCaseOutputDir);
79 | Deencapsulation.setField(mojo, "templateDirectory", new File(testCaseOutputDir, "template"));
80 | Deencapsulation.setField(mojo, "generatorDirectory", new File(testCaseOutputDir, "data"));
81 | Deencapsulation.setField(mojo, "outputDirectory", new File(testCaseOutputDir, "generated-files"));
82 | Deencapsulation.setField(mojo, "mojo", mojoExecution);
83 | Deencapsulation.setField(mojo, "session", session);
84 |
85 | // Validate source directory.
86 | assertThatExceptionOfType(MojoExecutionException.class).isThrownBy(() -> {
87 | mojo.execute();
88 | }).withMessage("Required directory does not exist: target/test-output/freemarker-mojo/executeTest/data");
89 |
90 | new File(testCaseOutputDir, "data").mkdirs();
91 | assertThatExceptionOfType(MojoExecutionException.class).isThrownBy(() -> {
92 | mojo.execute();
93 | }).withMessage("Required directory does not exist: target/test-output/freemarker-mojo/executeTest/template");
94 | new File(testCaseOutputDir, "template").mkdirs();
95 |
96 | // Validate minimum configuration.
97 | mojo.execute();
98 |
99 | new Verifications() {{
100 | project.addCompileSourceRoot("target/test-output/freemarker-mojo/executeTest/generated-files"); times = 1;
101 |
102 | Configuration config;
103 | MavenSession capturedSession;
104 | Map builders;
105 |
106 | GeneratingFileVisitor.create(
107 | config = withCapture(),
108 | capturedSession = withCapture(),
109 | builders = withCapture()); times = 1;
110 |
111 | assertEquals("UTF-8", config.getDefaultEncoding());
112 | assertEquals(session, capturedSession);
113 | TemplateLoader loader = config.getTemplateLoader();
114 | assertTrue(loader instanceof FileTemplateLoader);
115 |
116 | Path path;
117 | FileVisitor fileVisitor;
118 |
119 | Files.walkFileTree(path = withCapture(), fileVisitor = withCapture()); times = 1;
120 |
121 | assertEquals(new File(testCaseOutputDir, "data").toPath(), path);
122 | assertTrue(fileVisitor instanceof GeneratingFileVisitor);
123 | }};
124 | }
125 |
126 | @Test
127 | public void execute_generateTestSourceTest(
128 | @Mocked MavenSession session,
129 | @Mocked MavenProject project,
130 | @Mocked MojoExecution mojoExecution,
131 | @Mocked GeneratingFileVisitor generatingFileVisitor,
132 | @Mocked Files files
133 | ) throws MojoExecutionException, MojoFailureException, IOException {
134 |
135 | new Expectations(mojoExecution, generatingFileVisitor) {{
136 | mojoExecution.getLifecyclePhase(); result = "generate-test-sources";
137 | session.getCurrentProject(); result = project;
138 | }};
139 |
140 | FreeMarkerMojo mojo = new FreeMarkerMojo();
141 |
142 | File testCaseOutputDir = new File(testOutputDir, "generateTestSourceTest");
143 | Deencapsulation.setField(mojo, "freeMarkerVersion", "2.3.23");
144 | Deencapsulation.setField(mojo, "sourceDirectory", testCaseOutputDir);
145 | Deencapsulation.setField(mojo, "templateDirectory", new File(testCaseOutputDir, "template"));
146 | Deencapsulation.setField(mojo, "generatorDirectory", new File(testCaseOutputDir, "data"));
147 | Deencapsulation.setField(mojo, "outputDirectory", new File(testCaseOutputDir, "generated-files"));
148 | Deencapsulation.setField(mojo, "mojo", mojoExecution);
149 | Deencapsulation.setField(mojo, "session", session);
150 |
151 | new File(testCaseOutputDir, "data").mkdirs();
152 | new File(testCaseOutputDir, "template").mkdirs();
153 |
154 | mojo.execute();
155 |
156 | new Verifications() {{
157 | project.addTestCompileSourceRoot("target/test-output/freemarker-mojo/generateTestSourceTest/generated-files"); times = 1;
158 | }};
159 | }
160 |
161 | @SuppressWarnings({"rawtypes", "unchecked"})
162 | @Test
163 | public void execute_walkFileTreeExceptionTest(
164 | @Mocked MavenSession session,
165 | @Mocked MavenProject project,
166 | @Mocked MojoExecution mojoExecution,
167 | @Mocked GeneratingFileVisitor generatingFileVisitor,
168 | @Mocked Files files
169 | ) throws MojoExecutionException, MojoFailureException, IOException {
170 |
171 | new Expectations(mojoExecution, generatingFileVisitor) {{
172 | mojoExecution.getLifecyclePhase(); result = "generate-test-sources";
173 | session.getCurrentProject(); result = project;
174 | Files.walkFileTree((Path) any,(FileVisitor) any); result = new RuntimeException("test exception");
175 | }};
176 |
177 | FreeMarkerMojo mojo = new FreeMarkerMojo();
178 |
179 | File testCaseOutputDir = new File(testOutputDir, "generateTestSourceTest");
180 | Deencapsulation.setField(mojo, "freeMarkerVersion", "2.3.23");
181 | Deencapsulation.setField(mojo, "sourceDirectory", testCaseOutputDir);
182 | Deencapsulation.setField(mojo, "templateDirectory", new File(testCaseOutputDir, "template"));
183 | Deencapsulation.setField(mojo, "generatorDirectory", new File(testCaseOutputDir, "data"));
184 | Deencapsulation.setField(mojo, "outputDirectory", new File(testCaseOutputDir, "generated-files"));
185 | Deencapsulation.setField(mojo, "mojo", mojoExecution);
186 | Deencapsulation.setField(mojo, "session", session);
187 |
188 | new File(testCaseOutputDir, "data").mkdirs();
189 | new File(testCaseOutputDir, "template").mkdirs();
190 |
191 | assertThatExceptionOfType(MojoExecutionException.class).isThrownBy(() -> {
192 | mojo.execute();
193 | }).withMessage("Failed to process files in generator dir: target/test-output/freemarker-mojo/generateTestSourceTest/data");
194 | }
195 |
196 | @Test
197 | public void execute_setTemplateLoaderExceptionTest(
198 | @Mocked MavenSession session,
199 | @Mocked MavenProject project,
200 | @Mocked MojoExecution mojoExecution,
201 | @Mocked FactoryUtil factoryUtil,
202 | @Mocked Configuration config) {
203 |
204 | new Expectations(config, FactoryUtil.class) {{
205 | FactoryUtil.createConfiguration("2.3.23"); result = config;
206 | config.setTemplateLoader((TemplateLoader) any); result = new RuntimeException("test exception");
207 | }};
208 |
209 | FreeMarkerMojo mojo = new FreeMarkerMojo();
210 |
211 | File testCaseOutputDir = new File(testOutputDir, "setTemplateLoaderException");
212 |
213 | Deencapsulation.setField(mojo, "freeMarkerVersion", "2.3.23");
214 | Deencapsulation.setField(mojo, "sourceDirectory", testCaseOutputDir);
215 | Deencapsulation.setField(mojo, "templateDirectory", new File(testCaseOutputDir, "template"));
216 | Deencapsulation.setField(mojo, "generatorDirectory", new File(testCaseOutputDir, "data"));
217 | Deencapsulation.setField(mojo, "outputDirectory", new File(testCaseOutputDir, "generated-files"));
218 | Deencapsulation.setField(mojo, "mojo", mojoExecution);
219 | Deencapsulation.setField(mojo, "session", session);
220 |
221 | new File(testCaseOutputDir, "data").mkdirs();
222 | new File(testCaseOutputDir, "template").mkdirs();
223 |
224 | assertThatExceptionOfType(MojoExecutionException.class).isThrownBy(() -> {
225 | mojo.execute();
226 | }).withMessage("Could not establish file template loader for directory: target/test-output/freemarker-mojo/setTemplateLoaderException/template");
227 | }
228 |
229 | @Test
230 | public void execute_loadFreemarkerPropertiesTest(
231 | @Mocked MavenSession session,
232 | @Mocked MavenProject project,
233 | @Mocked MojoExecution mojoExecution,
234 | @Mocked Configuration config) throws Exception {
235 |
236 | FreeMarkerMojo mojo = new FreeMarkerMojo();
237 |
238 | File sourceDirectory = new File("src/test/data/freemarker-mojo");
239 | File testCaseOutputDir = new File(testOutputDir, "loadFreemarkerProperties");
240 |
241 | Deencapsulation.setField(mojo, "freeMarkerVersion", "2.3.23");
242 | Deencapsulation.setField(mojo, "sourceDirectory", sourceDirectory);
243 | Deencapsulation.setField(mojo, "templateDirectory", new File( sourceDirectory, "template"));
244 | Deencapsulation.setField(mojo, "generatorDirectory", new File( sourceDirectory, "data"));
245 | Deencapsulation.setField(mojo, "outputDirectory", new File(testCaseOutputDir, "generated-files"));
246 | Deencapsulation.setField(mojo, "mojo", mojoExecution);
247 | Deencapsulation.setField(mojo, "session", session);
248 |
249 | mojo.execute();
250 |
251 | new Verifications() {{
252 | Properties properties;
253 |
254 | config.setSettings(properties = withCapture()); times = 1;
255 |
256 | assertEquals("T,F", properties.getProperty("boolean_format"));
257 | }};
258 | }
259 |
260 | @Test
261 | public void execute_loadFreemarkerPropertiesExceptionTest(
262 | @Mocked MavenSession session,
263 | @Mocked MavenProject project,
264 | @Mocked MojoExecution mojoExecution,
265 | @Mocked FactoryUtil factoryUtil,
266 | @Mocked Configuration config) throws Exception {
267 |
268 | new Expectations(FactoryUtil.class) {{
269 | FactoryUtil.createFileInputStream((File) any); result = new RuntimeException("test exception");
270 | }};
271 |
272 | FreeMarkerMojo mojo = new FreeMarkerMojo();
273 |
274 | File sourceDirectory = new File("src/test/data/freemarker-mojo");
275 | File testCaseOutputDir = new File(testOutputDir, "loadFreemarkerPropertiesExceptionTest");
276 |
277 | Deencapsulation.setField(mojo, "freeMarkerVersion", "2.3.23");
278 | Deencapsulation.setField(mojo, "sourceDirectory", sourceDirectory);
279 | Deencapsulation.setField(mojo, "templateDirectory", new File( sourceDirectory, "template"));
280 | Deencapsulation.setField(mojo, "generatorDirectory", new File( sourceDirectory, "data"));
281 | Deencapsulation.setField(mojo, "outputDirectory", new File(testCaseOutputDir, "generated-files"));
282 | Deencapsulation.setField(mojo, "mojo", mojoExecution);
283 | Deencapsulation.setField(mojo, "session", session);
284 |
285 | System.out.println("==== before mojo execute");
286 | try {
287 | assertThatExceptionOfType(MojoExecutionException.class).isThrownBy(() -> {
288 | mojo.execute();
289 | }).withMessage("Failed to load src/test/data/freemarker-mojo/freemarker.properties");
290 | } catch ( Throwable t) {
291 | t.printStackTrace();
292 | }
293 | }
294 |
295 | @Test
296 | public void execute_setSettingsExceptionTest(
297 | @Mocked MavenSession session,
298 | @Mocked MavenProject project,
299 | @Mocked MojoExecution mojoExecution,
300 | @Mocked Configuration config) throws Exception {
301 |
302 | new Expectations() {{
303 | config.setSettings((Properties) any); result = new RuntimeException("test exception");
304 | }};
305 |
306 | FreeMarkerMojo mojo = new FreeMarkerMojo();
307 |
308 | File sourceDirectory = new File("src/test/data/freemarker-mojo");
309 | File testCaseOutputDir = new File(testOutputDir, "loadFreemarkerProperties");
310 |
311 | Deencapsulation.setField(mojo, "freeMarkerVersion", "2.3.23");
312 | Deencapsulation.setField(mojo, "sourceDirectory", sourceDirectory);
313 | Deencapsulation.setField(mojo, "templateDirectory", new File( sourceDirectory, "template"));
314 | Deencapsulation.setField(mojo, "generatorDirectory", new File( sourceDirectory, "data"));
315 | Deencapsulation.setField(mojo, "outputDirectory", new File(testCaseOutputDir, "generated-files"));
316 | Deencapsulation.setField(mojo, "mojo", mojoExecution);
317 | Deencapsulation.setField(mojo, "session", session);
318 |
319 | assertThatExceptionOfType(MojoExecutionException.class).isThrownBy(() -> {
320 | mojo.execute();
321 | }).withMessage("Invalid setting(s) in src/test/data/freemarker-mojo/freemarker.properties");
322 | }
323 |
324 | }
325 |
--------------------------------------------------------------------------------