Compare commits

...

2 Commits

  1. 5
      src/main/java/de/kreth/property2java/Configuration.java
  2. 11
      src/main/java/de/kreth/property2java/Generator.java
  3. 15
      src/main/java/de/kreth/property2java/config/FreemarkerConfig.java
  4. 9
      src/main/java/de/kreth/property2java/processor/Format.java
  5. 46
      src/main/java/de/kreth/property2java/processor/GenerateResourceBundleProperty2Java.java
  6. 21
      src/main/java/de/kreth/property2java/processor/GenerateResourceBundleProperty2Javas.java
  7. 23
      src/main/java/de/kreth/property2java/processor/ProcessorConfiguration.java
  8. 47
      src/main/java/de/kreth/property2java/processor/Property2JavaGenerator.java
  9. 59
      src/main/resources/template/enum_template_with_initializer.tpl
  10. 48
      src/main/resources/template/enum_template_with_inner_properties.tpl
  11. 48
      src/main/resources/template/enum_template_with_inner_propertyresourcebundle.tpl

@ -12,6 +12,7 @@ import java.util.Map;
import org.apache.commons.text.WordUtils;
import de.kreth.property2java.config.Regex;
import de.kreth.property2java.processor.Format;
public interface Configuration {
@ -23,6 +24,10 @@ public interface Configuration {
*/
String getPackage();
default Format getFormat() {
return Format.WithUnaryOperatorParameter;
}
/**
* Filename to InputReader Entries
*

@ -31,7 +31,7 @@ public class Generator {
public Generator(Configuration config) {
this.config = config;
try {
template = FreemarkerConfig.INSTANCE.getTemplate();
template = FreemarkerConfig.INSTANCE.getTemplate(config.getFormat());
} catch (IOException e) {
throw new IllegalStateException("Unable to load freemarker template", e);
}
@ -62,6 +62,7 @@ public class Generator {
root.put("generation_date", dateTimeInstance.format(new Date()));
root.put("package", config.getPackage());
root.put("fileName", 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<>();
@ -81,6 +82,14 @@ public class Generator {
template.process(root, out);
}
int min(int a, int b) {
int result = Math.min(a, b);
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();

@ -2,6 +2,7 @@ package de.kreth.property2java.config;
import java.io.IOException;
import de.kreth.property2java.processor.Format;
import freemarker.template.Configuration;
import freemarker.template.Template;
@ -11,8 +12,20 @@ public enum FreemarkerConfig {
private final Configuration cfg;
public Template getTemplate() throws IOException {
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() {

@ -0,0 +1,9 @@
package de.kreth.property2java.processor;
public enum Format {
WithUnaryOperatorParameter,
WithInnerPropertyResourceBundle,
WithInnerPropertyLoader,
WithInitializer
}

@ -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();
}

@ -9,6 +9,7 @@ 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;
@ -26,17 +27,16 @@ 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);
String className = mapFilenameToClassName(resource);
input.put(className, ressource.openReader(false));
FileObject ressource = filer.getResource(StandardLocation.CLASS_PATH, "", resource);
input.put(resource, ressource.openReader(false));
}
}
@ -52,6 +52,11 @@ public class ProcessorConfiguration implements Configuration {
return packageName;
}
@Override
public Format getFormat() {
return format;
}
@Override
public Map<String, Reader> getInput() {
return input;
@ -67,7 +72,7 @@ public class ProcessorConfiguration implements Configuration {
public Writer outWriter(String fileName) throws IOException {
String packageName = getPackage();
if (packageName != null && !packageName.isBlank()) {
fileName = packageName + "." + fileName;
fileName = packageName + "." + mapFilenameToClassName(fileName);
}
return filer.createSourceFile(fileName, element).openWriter();
}
@ -80,6 +85,7 @@ public class ProcessorConfiguration implements Configuration {
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;
@ -87,6 +93,11 @@ public class ProcessorConfiguration implements Configuration {
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;

@ -4,6 +4,7 @@ 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;
@ -17,7 +18,9 @@ import javax.tools.Diagnostic.Kind;
import de.kreth.property2java.GeneratorException;
@SupportedAnnotationTypes({ "de.kreth.property2java.processor.GenerateProperty2Java" })
@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 {
@ -25,29 +28,55 @@ public class Property2JavaGenerator extends AbstractProcessor {
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);
processElements(elementsAnnotatedWith);
} else {
processingEnv.getMessager().printMessage(Kind.NOTE,
"finished working on annotation " + GenerateProperty2Java.class);
for (Element element : elementsAnnotatedWith) {
GenerateProperty2Java generateAnnotation = element.getAnnotation(GenerateProperty2Java.class);
String[] resources = generateAnnotation.resources();
generateElementProperties(element, Arrays.asList(resources), Format.WithUnaryOperatorParameter);
}
return true;
}
private void processElements(Set<? extends Element> elementsAnnotatedWith) {
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) {
String[] resources = element.getAnnotation(GenerateProperty2Java.class).resources();
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();
@ -57,5 +86,5 @@ public class Property2JavaGenerator extends AbstractProcessor {
element);
}
}
}
}

@ -0,0 +1,59 @@
<#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}
*/
@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,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);
}
}
Loading…
Cancel
Save