de.schegge.enumconverter.EnumConverterWriter Maven / Gradle / Ivy
package de.schegge.enumconverter;
import javax.annotation.processing.ProcessingEnvironment;
import javax.lang.model.element.PackageElement;
import javax.lang.model.element.TypeElement;
import javax.lang.model.util.Elements;
import javax.tools.JavaFileObject;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.Map;
public class EnumConverterWriter {
private final ProcessingEnvironment processingEnv;
private final Elements elements;
private final SourceCodeGenerator classGenerator;
public EnumConverterWriter(ProcessingEnvironment processingEnv, Elements elements) {
this.processingEnv = processingEnv;
this.elements = elements;
classGenerator = new FreshMarkerSourceCodeGenerator(getClass(), "Enum Converter Generator", "2.0.3");
}
public boolean createEnumConverterClassFile(TypeElement enumType, boolean ordinal, List list,
boolean autoApply, boolean exceptionIfMissing, boolean nullKeyForbidden) {
try {
String enumTypeName = enumType.getSimpleName().toString();
JavaFileObject builderFile = processingEnv.getFiler().createSourceFile(enumType.getQualifiedName() + "Converter");
if (builderFile.getLastModified() > 0) {
return false;
}
PackageElement packageOf = elements.getPackageOf(enumType);
try (PrintWriter out = new PrintWriter(builderFile.openWriter())) {
Map root = Map.ofEntries(
Map.entry("package", packageOf.getQualifiedName().toString()),
Map.entry("enumConverterTypeName", enumTypeName + "Converter"),
Map.entry("enumTypeName", enumTypeName),
Map.entry("databaseTypeName", ordinal ? "Integer" : "String"),
Map.entry("elements", list),
Map.entry("autoApply", autoApply),
Map.entry("exceptionIfMissing", exceptionIfMissing),
Map.entry("nullKeyForbidden", nullKeyForbidden));
classGenerator.processTemplate(root, out);
return true;
}
} catch (IOException e) {
throw new IllegalArgumentException(e);
}
}
}