Compare commits

..

50 Commits

Author SHA1 Message Date
Markus Kreth 5f2f60b038 [maven-release-plugin] prepare for next development iteration 3 years ago
Markus Kreth 6b7bd09106 [maven-release-plugin] prepare release PropertyToJavaGenerator-2.0.2 3 years ago
Markus Kreth aab2f7b24f Annotation accepts format parameter 3 years ago
Markus Kreth 959b7e924c added some comments to generation templates. 3 years ago
Markus Kreth 4c2b2a5580 Merge branch 'master' of https://github.com/markuskreth/PropertyToJavaGenerator 3 years ago
Markus Kreth 204740ca8b different Format Templates 3 years ago
Markus Kreth 67f4b40989 [maven-release-plugin] prepare for next development iteration 3 years ago
Markus Kreth 776f8b9cf6 [maven-release-plugin] prepare release PropertyToJavaGenerator-2.0.1 3 years ago
Markus Kreth 871d4b6edd release rollback 3 years ago
Markus Kreth 8db7e5cb59 change scm to gitea full capable repository 3 years ago
Markus Kreth 9147db8ee7 [maven-release-plugin] prepare release PropertyToJavaGenerator-2.0.1 3 years ago
Markus Kreth 2f2791d8fe [maven-release-plugin] rollback the release of PropertyToJavaGenerator-2.0.1 3 years ago
Markus Kreth 73c43df3a8 [maven-release-plugin] prepare release PropertyToJavaGenerator-2.0.1 3 years ago
Markus Kreth d386e9d31b fixed distribution repository id. 3 years ago
Markus Kreth a5f8a5f681 using gitea https url 3 years ago
Markus Kreth 68890f1e76 switch scm from github to gitea 3 years ago
Markus Kreth 378972d41d Next development Version 2.0.1-SNAPSHOT 3 years ago
Markus Kreth 34ed824fa2 [maven-release-plugin] prepare release PropertyToJavaGenerator-2.0.0 3 years ago
Markus Kreth 2121643075 [maven-release-plugin] rollback the release of PropertyToJavaGenerator-2.0.0 3 years ago
Markus Kreth b13a64b108 Merge remote-tracking branch 'origin/master' 3 years ago
Markus Kreth 467b39c2e0 [maven-release-plugin] rollback the release of PropertyToJavaGenerator-2.0.0 3 years ago
Markus Kreth 4415368954 [maven-release-plugin] prepare release PropertyToJavaGenerator-1.0.0 3 years ago
Markus Kreth 35dcb32124 [maven-release-plugin] prepare release PropertyToJavaGenerator-2.0.0 3 years ago
Markus Kreth fdfe368bfc [maven-release-plugin] rollback the release of PropertyToJavaGenerator-2.0.0 3 years ago
Markus Kreth 4b864a9546 [maven-release-plugin] prepare release PropertyToJavaGenerator-2.0.0 3 years ago
Markus Kreth b1d16ebef0 setup github scm server id 3 years ago
Markus Kreth 4e796859c0 fixed pom.xml and added scm and distribution management. 3 years ago
Markus Kreth 1d447b2045 Annotation Processor for the generator 3 years ago
Markus Kreth 11f18a9abf
Merge pull request #9 from markuskreth/dependabot/maven/org.apache.logging.log4j-log4j-core-2.17.1 4 years ago
Markus Kreth 82d0ed20ae
Merge pull request #8 from markuskreth/dependabot/maven/org.apache.logging.log4j-log4j-api-2.17.1 4 years ago
dependabot[bot] 64aa57a06a
Bump log4j-core from 2.17.0 to 2.17.1 4 years ago
dependabot[bot] f85bc0cdc7
Bump log4j-api from 2.17.0 to 2.17.1 4 years ago
Markus Kreth fd412f977f
Merge pull request #7 from markuskreth/dependabot/maven/org.apache.logging.log4j-log4j-core-2.17.0 4 years ago
Markus Kreth 01489253f9
Merge pull request #6 from markuskreth/dependabot/maven/org.apache.logging.log4j-log4j-api-2.17.0 4 years ago
dependabot[bot] 90376f7bc5
Bump log4j-core from 2.15.0 to 2.17.0 4 years ago
dependabot[bot] 3bc752100f
Bump log4j-api from 2.15.0 to 2.17.0 4 years ago
Markus Kreth 363caca736
Merge pull request #2 from markuskreth/dependabot/maven/org.apache.logging.log4j-log4j-api-2.15.0 4 years ago
Markus Kreth 8a2a7edf91
Merge pull request #3 from markuskreth/dependabot/maven/org.apache.logging.log4j-log4j-core-2.15.0 4 years ago
dependabot[bot] aeef7c396e
Bump log4j-core from 2.13.3 to 2.15.0 4 years ago
dependabot[bot] 8a3c68be9b
Bump log4j-api from 2.13.3 to 2.15.0 4 years ago
Markus Kreth 25205b5301
Create maven.yml 5 years ago
Markus Kreth a6fe8ace9b
Merge pull request #1 from markuskreth/dependabot/maven/org.apache.logging.log4j-2.13.3 6 years ago
dependabot[bot] a6f0d2d78f
Bump org.apache.logging.log4j from 2.11.0 to 2.13.3 6 years ago
Markus Kreth 9f90973ee3 set development version 7 years ago
Markus Kreth 35bdaf7dc5 fixed test dependencies. 7 years ago
Markus Kreth e4cc48ec17 Sorting properties by name 7 years ago
Markus Kreth f41a50093a corrected merge error 7 years ago
Jenkins c7545499e2 Revert "Merge branch 'master' of github.com:markuskreth/PropertyToJavaGenerator" 7 years ago
Markus Kreth aab67f43fc [artifactory-release] Next development version 7 years ago
Markus Kreth 58cb637d9e [artifactory-release] Next development version 7 years ago
  1. 37
      .classpath
  2. 24
      .github/workflows/maven.yml
  3. 6
      .gitignore
  4. 23
      .project
  5. 1
      META-INF/services/javax.annotation.processing.Processor
  6. 96
      pom.xml
  7. 81
      src/main/java/de/kreth/property2java/Configuration.java
  8. 196
      src/main/java/de/kreth/property2java/Generator.java
  9. 8
      src/main/java/de/kreth/property2java/GeneratorException.java
  10. 123
      src/main/java/de/kreth/property2java/cli/ArgumentConfiguration.java
  11. 42
      src/main/java/de/kreth/property2java/config/FreemarkerConfig.java
  12. 24
      src/main/java/de/kreth/property2java/config/FreemarkerConfigImpl.java
  13. 27
      src/main/java/de/kreth/property2java/processor/Format.java
  14. 42
      src/main/java/de/kreth/property2java/processor/GenerateProperty2Java.java
  15. 46
      src/main/java/de/kreth/property2java/processor/GenerateResourceBundleProperty2Java.java
  16. 21
      src/main/java/de/kreth/property2java/processor/GenerateResourceBundleProperty2Javas.java
  17. 116
      src/main/java/de/kreth/property2java/processor/ProcessorConfiguration.java
  18. 91
      src/main/java/de/kreth/property2java/processor/Property2JavaGenerator.java
  19. 1
      src/main/resources/META-INF/services/javax.annotation.processing.Processor
  20. 2
      src/main/resources/template/enum_template.tpl
  21. 62
      src/main/resources/template/enum_template_with_initializer.tpl
  22. 48
      src/main/resources/template/enum_template_with_inner_properties.tpl
  23. 50
      src/main/resources/template/enum_template_with_inner_propertyresourcebundle.tpl
  24. 1
      src/test/java/de/kreth/property2java/ConfigurationTest.java
  25. 308
      src/test/java/de/kreth/property2java/GeneratorTests.java
  26. 55
      src/test/java/de/kreth/property2java/cli/ArgumentConfigurationTest.java
  27. 46
      src/test/java/de/kreth/property2java/processor/Property2JavaGeneratorTest.java

@ -1,37 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="src" output="target/classes" path="src/main/java">
<attributes>
<attribute name="optional" value="true"/>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry excluding="**" kind="src" output="target/classes" path="src/main/resources">
<attributes>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="src" output="target/test-classes" path="src/test/java">
<attributes>
<attribute name="test" value="true"/>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry excluding="**" kind="src" output="target/test-classes" path="src/test/resources">
<attributes>
<attribute name="test" value="true"/>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry exported="true" kind="con" path="org.eclipse.m2e.MAVEN2_CLASSPATH_CONTAINER">
<attributes>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-11">
<attributes>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="output" path="target/classes"/>
</classpath>

@ -0,0 +1,24 @@
# This workflow will build a Java project with Maven
# For more information see: https://help.github.com/actions/language-and-framework-guides/building-and-testing-java-with-maven
name: PropertyToJavaGenerator Library and console programm
on:
push:
branches: [ master ]
pull_request:
branches: [ master ]
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Set up JDK 1.8
uses: actions/setup-java@v1
with:
java-version: 11
- name: Build with Maven
run: mvn -B package --file pom.xml

6
.gitignore vendored

@ -1,3 +1,5 @@
.classpath
\.settings/ .project
.factorypath
.settings
target target

@ -1,23 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>PropertyToJavaGenerator</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.m2e.core.maven2Builder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.jdt.core.javanature</nature>
<nature>org.eclipse.m2e.core.maven2Nature</nature>
</natures>
</projectDescription>

@ -0,0 +1 @@
de.kreth.property2java.processor.Property2JavaGenerator

@ -1,33 +1,25 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<groupId>de.kreth.property2java</groupId> <groupId>de.kreth.property2java</groupId>
<artifactId>PropertyToJavaGenerator</artifactId> <artifactId>PropertyToJavaGenerator</artifactId>
<version>0.0.2</version> <version>2.0.3-SNAPSHOT</version>
<properties> <properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>11</java.version> <java.version>11</java.version>
<org.junit.jupiter>5.3.0-M1</org.junit.jupiter> <org.junit.jupiter>5.3.0-M1</org.junit.jupiter>
<org.slf4j>1.7.21</org.slf4j> <org.slf4j>1.7.36</org.slf4j>
<org.apache.logging.log4j>2.11.0</org.apache.logging.log4j> <org.apache.logging.log4j>2.17.2</org.apache.logging.log4j>
<timestamp>${maven.build.timestamp}</timestamp> <timestamp>${maven.build.timestamp}</timestamp>
<maven.build.timestamp.format>yyyy-MM-dd HH:mm:ss</maven.build.timestamp.format> <maven.build.timestamp.format>yyyy-MM-dd HH:mm:ss</maven.build.timestamp.format>
<project.scm.id>github</project.scm.id>
<sonar.login>3f3a1fa86ea83226b564895f3a8503f67e855440</sonar.login>
<sonar.jacoco.reportPaths>target/surefire-reports</sonar.jacoco.reportPaths>
<sonar.java.coveragePlugin>jacoco</sonar.java.coveragePlugin>
<sonar.core.codeCoveragePlugin>jacoco</sonar.core.codeCoveragePlugin>
<sonar.dynamicAnalysis>reuseReports</sonar.dynamicAnalysis>
<sonar.jacoco.reportPath>${project.basedir}/target/jacoco.exec</sonar.jacoco.reportPath>
<sonar.exclusions>**/src/main/webapp/VAADIN/**/*</sonar.exclusions>
</properties> </properties>
<dependencies> <dependencies>
<dependency> <dependency>
<groupId>org.apache.commons</groupId> <groupId>org.apache.commons</groupId>
@ -49,8 +41,8 @@
<artifactId>freemarker</artifactId> <artifactId>freemarker</artifactId>
<version>2.3.28</version> <version>2.3.28</version>
</dependency> </dependency>
<!-- LOGGING --> <!-- LOGGING -->
<dependency> <dependency>
<groupId>org.slf4j</groupId> <groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId> <artifactId>slf4j-api</artifactId>
@ -74,35 +66,37 @@
<version>${org.apache.logging.log4j}</version> <version>${org.apache.logging.log4j}</version>
<scope>runtime</scope> <scope>runtime</scope>
</dependency> </dependency>
<!-- TESTING --> <!-- TESTING -->
<dependency> <dependency>
<groupId>org.junit.jupiter</groupId> <groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId> <artifactId>junit-jupiter-api</artifactId>
<version>5.3.2</version> <version>5.3.2</version>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.junit.jupiter</groupId> <groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId> <artifactId>junit-jupiter-engine</artifactId>
<version>5.3.2</version> <version>5.3.2</version>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.junit.jupiter</groupId> <groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-params</artifactId> <artifactId>junit-jupiter-params</artifactId>
<version>5.3.2</version> <version>5.3.2</version>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.junit.platform</groupId> <groupId>org.junit.platform</groupId>
<artifactId>junit-platform-launcher</artifactId> <artifactId>junit-platform-launcher</artifactId>
<version>1.5.0-M1</version> <version>1.5.0-M1</version>
<scope>test</scope>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.junit.platform</groupId> <groupId>org.junit.platform</groupId>
<artifactId>junit-platform-runner</artifactId> <artifactId>junit-platform-runner</artifactId>
<version>1.5.0-M1</version> <version>1.5.0-M1</version>
<scope>test</scope>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.mockito</groupId> <groupId>org.mockito</groupId>
@ -120,9 +114,22 @@
<groupId>org.hamcrest</groupId> <groupId>org.hamcrest</groupId>
<artifactId>hamcrest-library</artifactId> <artifactId>hamcrest-library</artifactId>
<version>2.1-rc4</version> <version>2.1-rc4</version>
<scope>test</scope>
</dependency> </dependency>
</dependencies> </dependencies>
<distributionManagement>
<snapshotRepository>
<id>kreth.snapshots</id>
<url>https://nexus.kreth-development.de/repository/maven-snapshots/</url>
</snapshotRepository>
<repository>
<id>kreth.releases</id>
<url>https://nexus.kreth-development.de/repository/maven-releases/</url>
</repository>
</distributionManagement>
<build> <build>
<plugins> <plugins>
<plugin> <plugin>
@ -131,35 +138,14 @@
<version>3.8.0</version> <version>3.8.0</version>
<configuration> <configuration>
<release>${java.version}</release> <release>${java.version}</release>
<compilerArgs>-proc:none</compilerArgs>
</configuration> </configuration>
</plugin> </plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.0.0-M3</version>
</plugin>
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<version>0.8.2</version>
<executions>
<execution>
<id>default-jacoco-prepare-agent</id>
<goals>
<goal>prepare-agent</goal>
</goals>
</execution>
<execution>
<id>default-jacoco-report</id>
<phase>prepare-package</phase>
<goals>
<goal>report</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins> </plugins>
</build> </build>
<scm>
</project> <developerConnection>scm:git:https://gitea.kreth-development.de/markus/PropertyToJavaGenerator_migration.git</developerConnection>
<connection>scm:git:https://gitea.kreth-development.de/markus/PropertyToJavaGenerator_migration.git</connection>
<tag>HEAD</tag>
</scm>
</project>

@ -5,48 +5,61 @@ import java.io.FileWriter;
import java.io.IOException; import java.io.IOException;
import java.io.Reader; import java.io.Reader;
import java.io.Writer; import java.io.Writer;
import java.nio.charset.Charset;
import java.nio.file.Path; import java.nio.file.Path;
import java.util.Map; import java.util.Map;
import org.apache.commons.text.WordUtils; import org.apache.commons.text.WordUtils;
import de.kreth.property2java.config.FreemarkerConfigImpl;
import de.kreth.property2java.config.Regex; import de.kreth.property2java.config.Regex;
import freemarker.template.Template; import de.kreth.property2java.processor.Format;
public interface Configuration { public interface Configuration {
/** /**
* Package for generated Java Classes eg. "de.kreth.property2java". If null - no package line is generated. * Package for generated Java Classes eg. "de.kreth.property2java". If null - no
* @return * package line is generated.
*/ *
String getPackage(); * @return
*/
/** String getPackage();
* Filename to InputReader Entries
* @return default Format getFormat() {
*/ return Format.WithUnaryOperatorParameter;
Map<String, Reader> getInput(); }
/** /**
* Path of java source folder. * Filename to InputReader Entries
* @return *
*/ * @return
Path getRootPath(); */
Map<String, Reader> getInput();
default Writer outWriter(String fileName) throws IOException {
return new FileWriter(new File(getRootPath().toFile(), mapFilenameToClassName(fileName) + ".java")); /**
} * Path of java source folder.
*
default String mapFilenameToClassName(String fileName) { * @return
*/
String path = Regex.PATTERN.matcher(fileName).replaceAll(".").replaceAll("\\.", "_").replaceAll(" ", "_"); Path getRootPath();
path = WordUtils.capitalize(path, '_');
return path; default Writer outWriter(String fileName) throws IOException {
} return new FileWriter(new File(getRootPath().toFile(), mapFilenameToClassName(fileName) + ".java"),
outputCharset());
default Template getTemplate() throws IOException { }
return FreemarkerConfigImpl.INSTANCE.getTemplate();
} default Charset outputCharset() {
return Charset.defaultCharset();
}
default String mapFilenameToClassName(String fileName) {
String path = Regex.PATTERN.matcher(fileName)
.replaceAll(".")
.replaceAll("\\.", "_")
.replaceAll(" ", "_")
.replaceAll("/", "_");
path = WordUtils.capitalize(path, '_');
return path;
}
} }

@ -1,10 +1,13 @@
package de.kreth.property2java; package de.kreth.property2java;
import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.io.Reader; import java.io.Reader;
import java.io.Writer; import java.io.Writer;
import java.net.URL;
import java.text.DateFormat; import java.text.DateFormat;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections;
import java.util.Date; import java.util.Date;
import java.util.Enumeration; import java.util.Enumeration;
import java.util.HashMap; import java.util.HashMap;
@ -13,108 +16,149 @@ import java.util.Map;
import java.util.Properties; import java.util.Properties;
import de.kreth.property2java.cli.ArgumentConfiguration; import de.kreth.property2java.cli.ArgumentConfiguration;
import de.kreth.property2java.config.FreemarkerConfig;
import freemarker.template.Template; import freemarker.template.Template;
import freemarker.template.TemplateException; import freemarker.template.TemplateException;
public class Generator { public class Generator {
private static final DateFormat dateTimeInstance = DateFormat.getDateTimeInstance(); private static final DateFormat dateTimeInstance = DateFormat.getDateTimeInstance();
private final Configuration config; private final Configuration config;
private final Template template; private final Template template;
public Generator(Configuration config) { public Generator(Configuration config) {
this.config = config; this.config = config;
try { try {
template = config.getTemplate(); template = FreemarkerConfig.INSTANCE.getTemplate(config.getFormat());
} } catch (IOException e) {
catch (IOException e) { throw new IllegalStateException("Unable to load freemarker template", e);
throw new IllegalStateException("Unable to load freemarker template", e);
}
} }
}
public void start() throws IOException, GeneratorException { public void start() throws IOException, GeneratorException {
for (Map.Entry<String, Reader> entry : config.getInput().entrySet()) { for (Map.Entry<String, Reader> entry : config.getInput().entrySet()) {
String fileName = entry.getKey(); String fileName = entry.getKey();
try (Writer out = config.outWriter(fileName)) { try (Writer out = config.outWriter(fileName)) {
Properties properties = new Properties(); Properties properties = new Properties();
properties.load(entry.getValue()); properties.load(entry.getValue());
try { try {
generate(properties, out, fileName, config); generate(properties, out, fileName, config);
} } catch (TemplateException e) {
catch (TemplateException e) { throw new GeneratorException("Error configuring Engine", e);
throw new GeneratorException("Error configuring Engine", e);
}
}
} }
}
} }
}
void generate(Properties properties, Writer out, String fileName, Configuration config) void generate(Properties properties, Writer out, String fileName, Configuration config)
throws IOException, TemplateException { throws IOException, TemplateException {
Map<String, Object> root = new HashMap<>(); Map<String, Object> root = new HashMap<>();
root.put("generator_name", getClass().getName()); root.put("generator_name", getClass().getName());
root.put("generation_date", dateTimeInstance.format(new Date())); root.put("generation_date", dateTimeInstance.format(new Date()));
root.put("package", config.getPackage()); root.put("package", config.getPackage());
root.put("fileName", fileName); root.put("fileName", fileName);
root.put("classname", config.mapFilenameToClassName(fileName)); root.put("bundle_base_name", fileName.substring(0, min(fileName.length(), fileName.lastIndexOf('.'))));
root.put("classname", config.mapFilenameToClassName(fileName));
List<Entry> entries = new ArrayList<>(); List<Entry> entries = new ArrayList<>();
root.put("entries", entries); root.put("entries", entries);
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
Enumeration<String> propertyNames = (Enumeration<String>) properties.propertyNames(); List<String> propertyNames = Collections.list((Enumeration<String>) properties.propertyNames());
Collections.sort(propertyNames);
while (propertyNames.hasMoreElements()) { for (String propertyKeyString : propertyNames) {
final String propertyKeyString = propertyNames.nextElement(); final String propertyValue = properties.getProperty(propertyKeyString);
final String propertyValue = properties.getProperty(propertyKeyString);
entries.add(new Entry(propertyKeyString.toUpperCase().replaceAll("[\\.-]", "_"), propertyKeyString, entries.add(new Entry(propertyKeyString.toUpperCase().replaceAll("[\\.-]", "_"), propertyKeyString,
propertyValue)); propertyValue));
}
template.process(root, out);
} }
template.process(root, out);
}
public static void main(String[] args) throws IOException, GeneratorException { int min(int a, int b) {
Generator generator = new Generator(ArgumentConfiguration.parse(args)); int result = Math.min(a, b);
generator.start(); if (result < 0) {
result = Math.max(a, b);
}
return result;
}
public static void main(String[] args) throws IOException, GeneratorException {
Generator generator = new Generator(ArgumentConfiguration.parse(args));
generator.start();
}
public static void generateFor(Class<?> locationClass, List<URL> rescources, String relativeTargetDir)
throws IOException, GeneratorException {
ArgumentConfiguration.Builder config = new ArgumentConfiguration.Builder();
rescources
.stream()
.map(URL::getFile)
.map(File::new)
.map(File::getAbsolutePath)
.forEach(config::addPropFile);
config.setPackageName(locationClass.getPackageName())
.setTarget(relativeTargetDir);
Generator g = new Generator(config.build());
g.start();
}
/**
* Represents an Property Entry for the generated java class.
*
* @author markus
*
*/
public class Entry {
public final String constant;
public final String key;
public final String value;
/**
* Creates Property Entry data for the generated java class.
*
* @param constant name for the created constant.
* @param key property key
* @param value property value
*/
public Entry(String constant, String key, String value) {
super();
this.constant = constant;
this.key = key;
this.value = value;
} }
public class Entry { public String getConstant() {
return constant;
public final String constant; }
public final String key;
public final String value;
public Entry(String constant, String key, String value) {
super();
this.constant = constant;
this.key = key;
this.value = value;
}
public String getConstant() { public String getKey() {
return constant; return key;
} }
public String getKey() { public String getValue() {
return key; return value;
} }
public String getValue() { @Override
return value; public String toString() {
} return "Entry [constant=" + constant + ", key=" + key + ", value=" + value + "]";
}
@Override }
public String toString() {
return "Entry [constant=" + constant + ", key=" + key + ", value=" + value + "]";
}
}
} }

@ -8,4 +8,12 @@ public class GeneratorException extends Exception {
super(message, cause); super(message, cause);
} }
public GeneratorException(String message) {
super(message);
}
public GeneratorException(Throwable cause) {
super(cause);
}
} }

@ -16,82 +16,81 @@ import de.kreth.property2java.Configuration;
public class ArgumentConfiguration implements Configuration { public class ArgumentConfiguration implements Configuration {
private final String packageName; private final String packageName;
private final Map<String, Reader> files; private final Map<String, Reader> files;
private final Path rootPath; private final Path rootPath;
private ArgumentConfiguration(Builder builder) throws IOException { private ArgumentConfiguration(Builder builder) throws IOException {
this.packageName = builder.packageName; this.packageName = builder.packageName;
rootPath = new File(builder.target).toPath(); rootPath = new File(builder.target).toPath();
files = new HashMap<>(); files = new HashMap<>();
for (String filePath : builder.propFiles) { for (String filePath : builder.propFiles) {
File f = new File(filePath); File f = new File(filePath);
files.put(f.getName(), new FileReader(f)); files.put(f.getName(), new FileReader(f));
}
}
@Override
public String getPackage() {
return packageName;
} }
@Override }
public Map<String, Reader> getInput() {
return files; @Override
public String getPackage() {
return packageName;
}
@Override
public Map<String, Reader> getInput() {
return files;
}
@Override
public Path getRootPath() {
return rootPath;
}
@Override
public Writer outWriter(String fileName) throws IOException {
File dir;
if (packageName != null && packageName.isBlank() == false) {
dir = new File(rootPath.toFile(), packageName.replace('.', File.separatorChar));
} else {
dir = rootPath.toFile();
} }
return new FileWriter(new File(dir, mapFilenameToClassName(fileName) + ".java"), false);
}
@Override public static Configuration parse(String[] args) throws IOException {
public Path getRootPath() { CliConfig cliConfig = new CliConfig();
return rootPath;
}
@Override Builder builder = new Builder();
public Writer outWriter(String fileName) throws IOException { cliConfig.fill(builder, args);
File dir; return builder.build();
if (packageName != null && packageName.isBlank() == false) { }
dir = new File(rootPath.toFile(), packageName.replace('.', File.separatorChar));
}
else {
dir = rootPath.toFile();
}
return new FileWriter(new File(dir, mapFilenameToClassName(fileName) + ".java"), false);
}
public static Configuration parse(String[] args) throws IOException { public static class Builder {
CliConfig cliConfig = new CliConfig(); String target;
Builder builder = new Builder(); List<String> propFiles = new ArrayList<>();
cliConfig.fill(builder, args);
return builder.build();
}
static class Builder { String packageName;
String target;
List<String> propFiles = new ArrayList<>(); public Builder setTarget(String target) {
this.target = target;
String packageName; return this;
}
public Builder setTarget(String target) {
this.target = target;
return this;
}
public Builder addPropFile(String propFile) { public Builder addPropFile(String propFile) {
this.propFiles.add(propFile); this.propFiles.add(propFile);
return this; return this;
} }
public Builder setPackageName(String packageName) { public Builder setPackageName(String packageName) {
this.packageName = packageName; this.packageName = packageName;
return this; return this;
} }
public Configuration build() throws IOException { public Configuration build() throws IOException {
return new ArgumentConfiguration(this); return new ArgumentConfiguration(this);
}
} }
}
} }

@ -1,5 +1,37 @@
package de.kreth.property2java.config; package de.kreth.property2java.config;
public interface FreemarkerConfig { import java.io.IOException;
} import de.kreth.property2java.processor.Format;
import freemarker.template.Configuration;
import freemarker.template.Template;
public enum FreemarkerConfig {
INSTANCE;
private final Configuration cfg;
public Template getTemplate(Format format) throws IOException {
switch (format) {
case WithInitializer:
return cfg.getTemplate("enum_template_with_initializer.tpl");
case WithInnerPropertyLoader:
return cfg.getTemplate("enum_template_with_inner_properties.tpl");
case WithInnerPropertyResourceBundle:
return cfg.getTemplate("enum_template_with_inner_propertyresourcebundle.tpl");
case WithUnaryOperatorParameter:
return cfg.getTemplate("enum_template.tpl");
default:
throw new IllegalArgumentException("Format " + format + " is not supported.");
}
}
private FreemarkerConfig() {
cfg = new Configuration(Configuration.VERSION_2_3_28);
cfg.setClassForTemplateLoading(this.getClass(), "/template/");
cfg.setDefaultEncoding("UTF-8");
}
}

@ -1,24 +0,0 @@
package de.kreth.property2java.config;
import java.io.IOException;
import freemarker.template.Configuration;
import freemarker.template.Template;
public enum FreemarkerConfigImpl implements FreemarkerConfig {
INSTANCE;
private final Configuration cfg;
public Template getTemplate() throws IOException {
return cfg.getTemplate("enum_template.tpl");
}
private FreemarkerConfigImpl() {
cfg = new Configuration(Configuration.VERSION_2_3_28);
cfg.setClassForTemplateLoading(this.getClass(), "/template/");
cfg.setDefaultEncoding("UTF-8");
}
}

@ -0,0 +1,27 @@
package de.kreth.property2java.processor;
import java.util.PropertyResourceBundle;
public enum Format {
/**
* Offers a getString(UnaryOperator<String> resourceFunction) method to access
* the String value
*/
WithUnaryOperatorParameter,
/**
* Generates {@link PropertyResourceBundle} to offer a getText() method without
* parameters.
*/
WithInnerPropertyResourceBundle,
/**
* Offers a generated {@link PropertyResourceBundle} to offer a getText() method
* without parameters.
*/
WithInnerPropertyLoader,
/**
* Offers a static init(UnaryOperator<String> resourceFunction) method to offer
* a getText() method. The init method must be called before any getText() call.
*/
WithInitializer
}

@ -0,0 +1,42 @@
package de.kreth.property2java.processor;
import static java.lang.annotation.ElementType.TYPE;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(TYPE)
@Retention(RetentionPolicy.SOURCE)
/**
* Für die konfigurierten Resourcen wird jeweils eine Java Klasse erzeugt. Es
* muss nur die Abhängigkeit eingebunden werden und die Annotation in einer
* Klasse verwendet werden, in deren Package die neuen Klassen generiert werden.
*
* Für die Ausgabe der Prozessornachrichten muss folgendes im maven compiler
* konfiguriert werden:
*
* <pre>
&lt;build&gt;
&lt;plugins&gt;
&lt;plugin&gt;
&lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt;
&lt;artifactId&gt;maven-compiler-plugin&lt;/artifactId&gt;
&lt;version&gt;3.8.0&lt;/version&gt;
&lt;configuration&gt;
&lt;release&gt;${java.version}&lt;/release&gt;
<b>&lt;showWarnings&gt;true&lt;/showWarnings&gt;</b>
&lt;/configuration&gt;
&lt;/plugin&gt;
&lt;/plugins&gt;
&lt;/build&gt;
* </pre>
*
* @author Markus
*
*/
public @interface GenerateProperty2Java {
String[] resources();
Format format() default Format.WithUnaryOperatorParameter;
}

@ -0,0 +1,46 @@
package de.kreth.property2java.processor;
import static java.lang.annotation.ElementType.TYPE;
import java.lang.annotation.Repeatable;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(TYPE)
@Retention(RetentionPolicy.SOURCE)
@Repeatable(value = GenerateResourceBundleProperty2Javas.class)
/**
* Für die konfigurierten Resourcen wird jeweils eine Java Klasse erzeugt. Es
* muss nur die Abhängigkeit eingebunden werden und die Annotation in einer
* Klasse verwendet werden, in deren Package die neuen Klassen generiert werden.
* Wenn mehrere Resourcen verarbeitet werden sollen, kann diese Annotation
* mehrfach parallel angegeben werden.
*
* Für die Ausgabe der Prozessornachrichten muss folgendes im maven compiler
* konfiguriert werden:
*
* <pre>
&lt;build&gt;
&lt;plugins&gt;
&lt;plugin&gt;
&lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt;
&lt;artifactId&gt;maven-compiler-plugin&lt;/artifactId&gt;
&lt;version&gt;3.8.0&lt;/version&gt;
&lt;configuration&gt;
&lt;release&gt;${java.version}&lt;/release&gt;
<b>&lt;showWarnings&gt;true&lt;/showWarnings&gt;</b>
&lt;/configuration&gt;
&lt;/plugin&gt;
&lt;/plugins&gt;
&lt;/build&gt;
* </pre>
*
* @author Markus
*
*/
public @interface GenerateResourceBundleProperty2Java {
String resource();
Format format();
}

@ -0,0 +1,21 @@
package de.kreth.property2java.processor;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Diese Annotation sollte nicht verwendet werden. Sie sammelt nur
* {@link GenerateResourceBundleProperty2Java} wenn diese mehrfach verwendet
* wird.
*
* @author Markus
*
*/
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface GenerateResourceBundleProperty2Javas {
GenerateResourceBundleProperty2Java[] value();
}

@ -0,0 +1,116 @@
package de.kreth.property2java.processor;
import java.io.IOException;
import java.io.Reader;
import java.io.Writer;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import javax.annotation.processing.Filer;
import javax.lang.model.element.Element;
import javax.lang.model.element.PackageElement;
import javax.lang.model.element.TypeElement;
import javax.tools.FileObject;
import javax.tools.StandardLocation;
import de.kreth.property2java.Configuration;
import de.kreth.property2java.Generator;
import de.kreth.property2java.GeneratorException;
public class ProcessorConfiguration implements Configuration {
private final Filer filer;
private final Element element;
private final Map<String, Reader> input;
private final Format format;
ProcessorConfiguration(Builder builder) throws IOException {
this.filer = builder.filer;
this.element = builder.element;
this.format = Objects.requireNonNullElse(builder.format, Format.WithUnaryOperatorParameter);
this.input = new HashMap<>();
for (String resource : builder.resourcenames) {
FileObject ressource = filer.getResource(StandardLocation.CLASS_PATH, "", resource);
input.put(resource, ressource.openReader(false));
}
}
@Override
public String getPackage() {
String packageName = "";
if (element instanceof TypeElement) {
TypeElement typeElement = (TypeElement) element;
PackageElement packageElement = (PackageElement) typeElement.getEnclosingElement();
packageName = packageElement.getQualifiedName().toString();
}
return packageName;
}
@Override
public Format getFormat() {
return format;
}
@Override
public Map<String, Reader> getInput() {
return input;
}
@Override
public Path getRootPath() {
throw new UnsupportedOperationException(
"For Annotation Processor this is not supported as outWriter is overwritten.");
}
@Override
public Writer outWriter(String fileName) throws IOException {
String packageName = getPackage();
if (packageName != null && !packageName.isBlank()) {
fileName = packageName + "." + mapFilenameToClassName(fileName);
}
return filer.createSourceFile(fileName, element).openWriter();
}
static Builder builder(Filer filer, Element element) {
return new Builder(filer, element);
}
static class Builder {
private final Filer filer;
private final Element element;
private final List<String> resourcenames;
private Format format = Format.WithUnaryOperatorParameter;
private Builder(Filer filer, Element element) {
this.filer = filer;
this.element = element;
this.resourcenames = new ArrayList<>();
}
public Builder withFormat(Format format) {
this.format = format;
return this;
}
public Builder addAll(String[] resourceNames) {
this.resourcenames.addAll(Arrays.asList(resourceNames));
return this;
}
public Builder addAll(List<String> resourceNames) {
this.resourcenames.addAll(resourceNames);
return this;
}
public void startGeneration() throws IOException, GeneratorException {
Generator g = new Generator(new ProcessorConfiguration(this));
g.start();
}
}
}

@ -0,0 +1,91 @@
package de.kreth.property2java.processor;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import javax.annotation.processing.AbstractProcessor;
import javax.annotation.processing.RoundEnvironment;
import javax.annotation.processing.SupportedAnnotationTypes;
import javax.annotation.processing.SupportedSourceVersion;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.Element;
import javax.lang.model.element.TypeElement;
import javax.tools.Diagnostic.Kind;
import de.kreth.property2java.GeneratorException;
@SupportedAnnotationTypes({ "de.kreth.property2java.processor.GenerateProperty2Java",
"de.kreth.property2java.processor.GenerateResourceBundleProperty2Javas",
"de.kreth.property2java.processor.GenerateResourceBundleProperty2Java" })
@SupportedSourceVersion(SourceVersion.RELEASE_8)
public class Property2JavaGenerator extends AbstractProcessor {
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
if (!roundEnv.processingOver()) {
processGenerateProperty2Java(roundEnv);
processGenerateResourceBundleProperty2Javas(roundEnv);
} else {
processingEnv.getMessager().printMessage(Kind.NOTE,
"finished working on annotation " + annotations);
}
return true;
}
private void processGenerateProperty2Java(RoundEnvironment roundEnv) {
processingEnv.getMessager().printMessage(Kind.NOTE,
"Processing annotation " + GenerateProperty2Java.class);
Set<? extends Element> elementsAnnotatedWith = roundEnv
.getElementsAnnotatedWith(GenerateProperty2Java.class);
for (Element element : elementsAnnotatedWith) {
GenerateProperty2Java generateAnnotation = element.getAnnotation(GenerateProperty2Java.class);
String[] resources = generateAnnotation.resources();
Format format = generateAnnotation.format();
generateElementProperties(element, Arrays.asList(resources), format);
}
}
private void processGenerateResourceBundleProperty2Javas(RoundEnvironment roundEnv) {
processingEnv.getMessager().printMessage(Kind.NOTE,
"Processing annotation " + GenerateResourceBundleProperty2Javas.class);
Set<? extends Element> elementsAnnotatedWith = roundEnv
.getElementsAnnotatedWith(GenerateResourceBundleProperty2Javas.class);
for (Element element : elementsAnnotatedWith) {
GenerateResourceBundleProperty2Java[] value = element
.getAnnotation(GenerateResourceBundleProperty2Javas.class).value();
for (GenerateResourceBundleProperty2Java generateResourceBundleProperty2Java : value) {
List<String> resources = Arrays.asList(generateResourceBundleProperty2Java.resource());
generateElementProperties(element, resources, generateResourceBundleProperty2Java.format());
}
}
}
private void generateElementProperties(Element element, List<String> resources, Format format) {
processingEnv.getMessager().printMessage(Kind.NOTE,
"Generating Java for " + Arrays.asList(resources));
try {
ProcessorConfiguration
.builder(processingEnv.getFiler(), element)
.addAll(resources)
.withFormat(format)
.startGeneration();
} catch (IOException | GeneratorException e) {
StringWriter out = new StringWriter();
e.printStackTrace(new PrintWriter(out));
out.flush();
processingEnv.getMessager().printMessage(Kind.ERROR, "Exception " + e + "\n" + out.toString(),
element);
}
}
}

@ -0,0 +1 @@
de.kreth.property2java.processor.Property2JavaGenerator

@ -8,6 +8,8 @@ import javax.annotation.processing.Generated;
/** /**
* Property keys from ${fileName} * Property keys from ${fileName}
* {@link #getValue()} gives the key for the entry, with {@link #getString(UnaryOperator<String>)}
* the value is given directly.
*/ */
@Generated(date = "${generation_date}", value = "${generator_name}") @Generated(date = "${generation_date}", value = "${generator_name}")
public enum ${classname} { public enum ${classname} {

@ -0,0 +1,62 @@
<#if package??>package ${package};
</#if>import java.util.Properties;
import java.util.ResourceBundle;
import java.util.function.UnaryOperator;
import javax.annotation.processing.Generated;
/**
* Property keys from ${fileName}
* {@link #getValue()} gives the key for the entry, with {@link #getText()} the value for the key is given directly.
* This enum needs to be initialized before any use by {@link #init(UnaryOperator)}.
*/
@Generated(date = "${generation_date}", value = "${generator_name}")
public enum ${classname} {
<#list entries as e>
/**
* ${e.key} = "${e.value}"
*/
${e.constant} ("${e.key}")<#sep>,
</#sep>
</#list>;
private static UnaryOperator<String> function;
private final String value;
private ${classname} (String value) {
this.value = value;
}
public static void init(UnaryOperator<String> resourceFunction) {
function = resourceFunction;
}
/**
* Represented Key in property File.
* @return key
*/
public String getValue() {
return value;
}
/**
* Resolves the value for this key.
* {@link #init(UnaryOperator<String>)} must be called before.
*/
public String getText() {
return function.apply(value);
}
/**
* Resolves the value for this key from the parameter function.
* <p>
* e.g. <code>${classname}.getString(resBundle::getString)</code>
* @param resourceFunction {@link Properties#getProperty(String)} or {@link ResourceBundle#getString(String)}
* @return
*/
public String getString(UnaryOperator<String> resourceFunction) {
return resourceFunction.apply(value);
}
}

@ -0,0 +1,48 @@
<#if package??>package ${package};
</#if>import java.util.Properties;
import java.util.PropertyResourceBundle;
import java.util.ResourceBundle;
import java.util.function.UnaryOperator;
import javax.annotation.processing.Generated;
/**
* Property keys from ${fileName}
*/
@Generated(date = "${generation_date}", value = "${generator_name}")
public enum ${classname} {
<#list entries as e>
/**
* ${e.key} = "${e.value}"
*/
${e.constant} ("${e.key}")<#sep>,
</#sep>
</#list>;
private final String value;
private ${classname} (String value) {
this.value = value;
}
/**
* Represented Key in property File.
* @return key
*/
public String getValue() {
return value;
}
private static ResourceBundle bundle = PropertyResourceBundle.getBundle("${bundle_base_name}");
/**
* The Text for this Key from PropertyResourceBundle
* @return human readable text
*/
public String getText() {
return bundle.getString(value);
}
}

@ -0,0 +1,50 @@
<#if package??>package ${package};
</#if>import java.util.Properties;
import java.util.PropertyResourceBundle;
import java.util.ResourceBundle;
import java.util.function.UnaryOperator;
import javax.annotation.processing.Generated;
/**
* Property keys from ${fileName}
* {@link #getValue()} gives the key for the entry, with {@link #getText()} the value for the key is given directly.
* Initializationis generated also.
*/
@Generated(date = "${generation_date}", value = "${generator_name}")
public enum ${classname} {
<#list entries as e>
/**
* ${e.key} = "${e.value}"
*/
${e.constant} ("${e.key}")<#sep>,
</#sep>
</#list>;
private final String value;
private ${classname} (String value) {
this.value = value;
}
/**
* Represented Key in property File.
* @return key
*/
public String getValue() {
return value;
}
private static ResourceBundle bundle = PropertyResourceBundle.getBundle("${bundle_base_name}");
/**
* The Text for this Key from PropertyResourceBundle
* @return human readable text
*/
public String getText() {
return bundle.getString(value);
}
}

@ -29,6 +29,7 @@ class ConfigurationTest {
when(config.outWriter(anyString())).thenCallRealMethod(); when(config.outWriter(anyString())).thenCallRealMethod();
when(config.getRootPath()).thenReturn(new File(".").toPath()); when(config.getRootPath()).thenReturn(new File(".").toPath());
when(config.mapFilenameToClassName(anyString())).thenCallRealMethod(); when(config.mapFilenameToClassName(anyString())).thenCallRealMethod();
when(config.outputCharset()).thenCallRealMethod();
Writer outWriter = config.outWriter("application.properties"); Writer outWriter = config.outWriter("application.properties");
assertTrue(outWriter instanceof FileWriter); assertTrue(outWriter instanceof FileWriter);

@ -3,11 +3,8 @@ package de.kreth.property2java;
import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never; import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verify;
@ -30,170 +27,151 @@ import org.hamcrest.Matchers;
import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import freemarker.template.Template;
import freemarker.template.TemplateException;
class GeneratorTests { class GeneratorTests {
private String path = "application.properties"; private String path = "application.properties";
private Configuration config; private Configuration config;
private Generator generator; private Generator generator;
@BeforeEach @BeforeEach
void setUp() throws Exception { void setUp() throws Exception {
Map<String, Reader> input = new HashMap<>(); Map<String, Reader> input = new HashMap<>();
input.put(path, testProperties()); input.put(path, testProperties());
config = mock(Configuration.class); config = mock(Configuration.class);
when(config.getInput()).thenReturn(input); when(config.getInput()).thenReturn(input);
when(config.mapFilenameToClassName(anyString())).thenCallRealMethod(); when(config.mapFilenameToClassName(anyString())).thenCallRealMethod();
when(config.getTemplate()).thenCallRealMethod(); when(config.outputCharset()).thenCallRealMethod();
generator = new Generator(config); generator = new Generator(config);
} }
@Test @Test
void testClassDefinition() throws IOException, GeneratorException { void testClassDefinition() throws IOException, GeneratorException {
when(config.getPackage()).thenReturn("de.kreth.property2java"); when(config.getPackage()).thenReturn("de.kreth.property2java");
when(config.mapFilenameToClassName(anyString())).thenCallRealMethod(); when(config.mapFilenameToClassName(anyString())).thenCallRealMethod();
StringWriter out = new StringWriter(); StringWriter out = new StringWriter();
when(config.outWriter(anyString())).thenReturn(out); when(config.outWriter(anyString())).thenReturn(out);
generator.start(); generator.start();
String sourceCode = out.toString().trim(); String sourceCode = out.toString().trim();
StringTokenizer sourceTokenizer = new StringTokenizer(sourceCode, "\n"); StringTokenizer sourceTokenizer = new StringTokenizer(sourceCode, "\n");
String linePackage = null; String linePackage = null;
String lineClass = null; String lineClass = null;
int countOpenBaces = 0; int countOpenBaces = 0;
int countCloseBaces = 0; int countCloseBaces = 0;
while (sourceTokenizer.hasMoreTokens()) { while (sourceTokenizer.hasMoreTokens()) {
String line = sourceTokenizer.nextToken(); String line = sourceTokenizer.nextToken();
if (line.trim().startsWith("package")) { if (line.trim().startsWith("package")) {
linePackage = line; linePackage = line;
} } else if (line.trim().startsWith("public enum")) {
else if (line.trim().startsWith("public enum")) { lineClass = line;
lineClass = line; }
} if (line.contains("{")) {
if (line.contains("{")) { countOpenBaces++;
countOpenBaces++; }
} if (line.contains("}")) {
if (line.contains("}")) { countCloseBaces++;
countCloseBaces++; }
}
}
assertEquals(countCloseBaces, countOpenBaces,
"Count of Braces doesn't match. Open = " + countOpenBaces + ", Close = " + countCloseBaces);
assertNotNull(linePackage);
assertNotNull(lineClass);
assertThat(linePackage,
Matchers.stringContainsInOrder(Arrays.asList("package", "de.kreth.property2java", ";")));
assertThat(lineClass,
Matchers.stringContainsInOrder(Arrays.asList("public", "enum", "Application_Properties")));
} }
@Test() assertEquals(countCloseBaces, countOpenBaces,
void testTemplateException() throws IOException, GeneratorException, TemplateException { "Count of Braces doesn't match. Open = " + countOpenBaces + ", Close = " + countCloseBaces);
Writer out = mock(Writer.class); assertNotNull(linePackage);
when(config.outWriter(anyString())).thenReturn(out); assertNotNull(lineClass);
Template template = mock(Template.class); assertThat(linePackage,
when(config.getTemplate()).thenReturn(template); Matchers.stringContainsInOrder(Arrays.asList("package", "de.kreth.property2java", ";")));
doThrow(TemplateException.class).when(template).process(any(), any());
assertThat(lineClass,
generator = new Generator(config); Matchers.stringContainsInOrder(Arrays.asList("public", "enum", "Application_Properties")));
assertThrows(GeneratorException.class, () -> generator.start()); }
} @Test
void testOneInputGeneratesOneOutput() throws IOException, GeneratorException {
@Test
void testOneInputGeneratesOneOutput() throws IOException, GeneratorException { Writer out = mock(Writer.class);
Writer nonOut = mock(Writer.class);
Writer out = mock(Writer.class); when(config.outWriter(anyString())).thenReturn(out, nonOut);
Writer nonOut = mock(Writer.class); generator.start();
when(config.outWriter(anyString())).thenReturn(out, nonOut); verify(out).close();
generator.start(); verify(nonOut, never()).close();
verify(out).close(); verify(nonOut, never()).flush();
verify(nonOut, never()).close(); }
verify(nonOut, never()).flush();
} @Test
void testKeys() throws IOException, GeneratorException {
@Test
void testKeys() throws IOException, GeneratorException { StringWriter out = new StringWriter();
when(config.outWriter(anyString())).thenReturn(out);
StringWriter out = new StringWriter(); generator.start();
when(config.outWriter(anyString())).thenReturn(out);
generator.start(); List<String> lines = out.toString().lines().filter(line -> line.contains(" (\""))
.collect(Collectors.toList());
List<String> lines = out.toString().lines().filter(line -> line.contains(" (\""))
.collect(Collectors.toList()); assertEquals(21, lines.size());
assertLineMatch(lines, "label", "label");
assertEquals(21, lines.size()); assertLineMatch(lines, "label_addarticle", "label.addarticle");
assertLineMatch(lines, "label", "label"); assertLineMatch(lines, "label_user_register", "label.user.register");
assertLineMatch(lines, "label_addarticle", "label.addarticle"); assertLineMatch(lines, "message_article_priceerror", "message.article.priceerror");
assertLineMatch(lines, "label_user_register", "label.user.register"); assertLineMatch(lines, "message_invoiceitem_startbeforeend",
assertLineMatch(lines, "message_article_priceerror", "message.article.priceerror"); "message.invoiceitem.startbeforeend");
assertLineMatch(lines, "message_invoiceitem_startbeforeend", assertLineMatch(lines, "message_invoiceitem_allfieldsmustbeset",
"message.invoiceitem.startbeforeend"); "message.invoiceitem.allfieldsmustbeset");
assertLineMatch(lines, "message_invoiceitem_allfieldsmustbeset", }
"message.invoiceitem.allfieldsmustbeset");
} private void assertLineMatch(List<String> lines, String key, String expected) {
Optional<String> found = lines.stream().filter(line -> keyMatches(line, key))
private void assertLineMatch(List<String> lines, String key, String expected) { .findFirst();
Optional<String> found = lines.stream().filter(line -> keyMatches(line, key))
.findFirst(); assertTrue(found.isPresent(), "No line found with key = " + key);
assertTrue(found.isPresent(), "No line found with key = " + key); final String line = found.get().trim();
final String line = found.get().trim(); int indexEquals = line.indexOf('(');
int indexEquals = line.indexOf('('); String value = line.substring(indexEquals + 1).trim().substring(1);
String value = line.substring(indexEquals + 1).trim().substring(1); value = value.substring(0, value.length() - 3);
value = value.substring(0, value.length() - 3); assertEquals(expected, value, "Line \"" + line + "\" don't match expected Value \"" + expected + "\"");
assertEquals(expected, value, "Line \"" + line + "\" don't match expected Value \"" + expected + "\"");
}
}
private boolean keyMatches(String line, String key) {
private boolean keyMatches(String line, String key) { line = line.toLowerCase();
line = line.toLowerCase(); key = key.toLowerCase();
key = key.toLowerCase(); return line.contains("\t" + key + " ");
return line.contains("\t" + key + " "); }
}
private StringReader testProperties() {
private StringReader testProperties() { return new StringReader("\r\n" +
return new StringReader("\r\n" + "label = \r\n" +
"label = \r\n" + "\r\n" +
"\r\n" + "label.addarticle = Add Article\r\n" +
"label.addarticle = Add Article\r\n" + "label.cancel = Cancel\r\n" +
"label.cancel = Cancel\r\n" + "label.close = Close\r\n" +
"label.close = Close\r\n" + "label.delete = Delete\r\n" +
"label.delete = Delete\r\n" + "label.discart = Discart\r\n" +
"label.discart = Discart\r\n" + "label.loggedin = Logged in:\r\n" +
"label.loggedin = Logged in:\r\n" + "label.logout = Logout\r\n" +
"label.logout = Logout\r\n" + "label.ok = OK\r\n" +
"label.ok = OK\r\n" + "label.store = Store\r\n" +
"label.store = Store\r\n" + "label.preview = Preview\r\n" +
"label.preview = Preview\r\n" + "label.open = Open\r\n" +
"label.open = Open\r\n" + "label.user.register = Register\r\n" +
"label.user.register = Register\r\n" + "\r\n" +
"\r\n" + "message.article.priceerror = Please set the price.\r\n" +
"message.article.priceerror = Please set the price.\r\n" + "message.delete.text = Delete {0}?\r\n" +
"message.delete.text = Delete {0}?\r\n" + "message.delete.title = Really delete?\r\n" +
"message.delete.title = Really delete?\r\n" + "message.invoiceitem.allfieldsmustbeset = Start, end and article must not be \\r\\n" +
"message.invoiceitem.allfieldsmustbeset = Start, end and article must not be \\r\\n" + " empty!\r\n" +
" empty!\r\n" + "message.invoiceitem.startbeforeend = End must be later than start.\r\n" +
"message.invoiceitem.startbeforeend = End must be later than start.\r\n" + "message.user.create.success = Thanks {0} created!\r\n" +
"message.user.create.success = Thanks {0} created!\r\n" + "message.user.loginfailure = Login Error! Wrong user or password?\r\n" +
"message.user.loginfailure = Login Error! Wrong user or password?\r\n" + "message.user.passwordmissmatch = Passwords don't match.\r\n" +
"message.user.passwordmissmatch = Passwords don't match.\r\n" + "");
""); }
}
} }

@ -1,55 +0,0 @@
package de.kreth.property2java.cli;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.io.File;
import java.io.IOException;
import java.io.Reader;
import java.util.Map;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import de.kreth.property2java.Configuration;
class ArgumentConfigurationTest {
private static File target;
private static File input;
private static File input2;
@BeforeAll
static void createTargetDir() throws IOException {
target = new File("testTargetDir");
target.mkdir();
input = new File(target, "application.properties");
input.createNewFile();
input2 = new File(target, "application2.properties");
input2.createNewFile();
}
@AfterAll
static void deleteTestfiles() {
target.delete();
input.delete();
input2.delete();
}
@Test
void testArgumentParser() throws IOException {
String[] args = { "-t", target.getAbsolutePath(),
"-f",
input.getAbsolutePath() + "," + input2.getAbsolutePath(),
"-p", "de.kreth.clubinvoice" };
Configuration config = ArgumentConfiguration.parse(args);
assertEquals("de.kreth.clubinvoice", config.getPackage());
assertEquals(target.getAbsolutePath(), config.getRootPath().toFile().getAbsolutePath());
Map<String, Reader> inputMap = config.getInput();
assertEquals(2, inputMap.size());
}
}

@ -0,0 +1,46 @@
package de.kreth.property2java.processor;
import static org.mockito.Mockito.when;
import java.util.HashSet;
import java.util.Set;
import javax.annotation.processing.Messager;
import javax.annotation.processing.ProcessingEnvironment;
import javax.annotation.processing.RoundEnvironment;
import javax.lang.model.element.TypeElement;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentMatchers;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
public class Property2JavaGeneratorTest {
private Property2JavaGenerator processor;
@Mock
private ProcessingEnvironment processingEnv;
@Mock
private RoundEnvironment roundEnv;
private Set<TypeElement> annotations;
@Mock
private Messager messanger;
@BeforeEach
void initProcesor() {
MockitoAnnotations.initMocks(this);
annotations = new HashSet<>();
processor = new Property2JavaGenerator();
processor.init(processingEnv);
when(processingEnv.getMessager()).thenReturn(messanger);
}
@Test
void testGeneratorInitializedCorrectly() {
when(roundEnv.getElementsAnnotatedWith(ArgumentMatchers.any(Class.class)))
.thenReturn(annotations);
processor.process(annotations, roundEnv);
}
}
Loading…
Cancel
Save