processors.ObjectBoxProcessor Maven / Gradle / Ivy
The newest version!
package processors;
import annotations.StorableObject;
import util.Stubber;
import javax.annotation.processing.*;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.*;
import javax.lang.model.type.TypeMirror;
import javax.tools.JavaFileObject;
import java.io.*;
import java.util.*;
/**
* Annotation-Processor für die @annotations.Collection-Annotationen
* Generiert die Zugriffspunkte und registriert die Collections in der Registry
*
* @author Simon Danner, 30.03.2016.
*/
@SupportedAnnotationTypes("annotations.StorableObject")
@SupportedSourceVersion(SourceVersion.RELEASE_7)
public class ObjectBoxProcessor extends AbstractProcessor
{
private final static String REGISTRY_NAME = "BoxRegistry";
private final static String REGISTRY_PATH = "registry";
@Override
public boolean process(Set extends TypeElement> annotations, RoundEnvironment roundEnv)
{
Set packages = new HashSet<>();
StringBuilder collections = new StringBuilder();
StringBuilder register = new StringBuilder();
Set extends Element> elements = roundEnv.getElementsAnnotatedWith(StorableObject.class);
TypeMirror superClass = processingEnv.getElementUtils().getTypeElement("definition.AbstractStorableObject").asType();
//Nur annotierte Klassen, die AbstractDocument implementieren akzeptieren
for (Element element : elements)
{
if (element.getKind() == ElementKind.CLASS && processingEnv.getTypeUtils().isAssignable(element.asType(), superClass))
{
String name = element.getSimpleName().toString();
packages.add(processingEnv.getElementUtils().getPackageOf(element).getSimpleName().toString());
StorableObject annotation = element.getAnnotation(StorableObject.class);
String displayName = annotation.fieldName();
String collectionName = annotation.boxName();
String declaration = "public static final ObjectBox<" + name + "> " + displayName.toUpperCase();
String args = "\"" + collectionName + "\", " + name + ".class, " + annotation.allowInsertion() +
", " + annotation.allowDeletion();
String instantiation = " = new ObjectBox(" + args + ");";
collections.append(declaration).append(instantiation).append("\n\t");
register.append("register(").append(displayName.toUpperCase()).append(");\n\t\t");
}
}
StringBuilder imports = new StringBuilder();
for (String packageName : packages)
imports.append("import ").append(packageName).append(".*;");
Writer writer;
try
{
JavaFileObject sourceFile = processingEnv.getFiler().createSourceFile(REGISTRY_PATH + "." + REGISTRY_NAME);
writer = sourceFile.openWriter();
if (register.length() != 0)
register.deleteCharAt(register.lastIndexOf("\n\t\t")); //Letztes \n entfernen
writer.write(Stubber.createFromStub(REGISTRY_NAME, imports.toString(), collections.toString(), register.toString()));
writer.flush();
writer.close();
}
catch (IOException pE)
{
//Nichts machen, dann existiert die File schon
}
return true;
}
}