Testing yaml annotations

This commit is contained in:
snowleo 2011-08-28 05:12:13 +02:00
parent 3ec0dbd404
commit fba4dd2d9a
19 changed files with 1690 additions and 7 deletions

5
.gitignore vendored
View File

@ -28,4 +28,7 @@
/EssentialsPermissionsCommands/dist/
/Essentials/nbproject/private/
/Essentials/dist/
/Essentials/build/
/Essentials/build/
/YamlAnnotations/nbproject/private/
/YamlAnnotations/build/
/YamlAnnotations/dist/

View File

@ -601,6 +601,13 @@ is divided into following sections:
<propertyfile file="${built-jar.properties}">
<entry key="${basedir}" value=""/>
</propertyfile>
<antcall target="-maybe-call-dep">
<param name="call.built.properties" value="${built-jar.properties}"/>
<param location="${project.YamlAnnotations}" name="call.subproject"/>
<param location="${project.YamlAnnotations}/build.xml" name="call.script"/>
<param name="call.target" value="jar"/>
<param name="transfer.built-jar.properties" value="${built-jar.properties}"/>
</antcall>
</target>
<target depends="init,-check-automatic-build,-clean-after-automatic-build" name="-verify-automatic-build"/>
<target depends="init" name="-check-automatic-build">
@ -1038,6 +1045,13 @@ is divided into following sections:
<propertyfile file="${built-clean.properties}">
<entry key="${basedir}" value=""/>
</propertyfile>
<antcall target="-maybe-call-dep">
<param name="call.built.properties" value="${built-clean.properties}"/>
<param location="${project.YamlAnnotations}" name="call.subproject"/>
<param location="${project.YamlAnnotations}/build.xml" name="call.script"/>
<param name="call.target" value="clean"/>
<param name="transfer.built-clean.properties" value="${built-clean.properties}"/>
</antcall>
</target>
<target depends="init" name="-do-clean">
<delete dir="${build.dir}"/>

View File

@ -3,8 +3,8 @@ build.xml.script.CRC32=3233ee78
build.xml.stylesheet.CRC32=28e38971@1.38.2.45
# This file is used by a NetBeans-based IDE to track changes in generated files such as build-impl.xml.
# Do not edit this file. You may delete it but then the IDE will never regenerate such files for you.
nbproject/build-impl.xml.data.CRC32=4b596d89
nbproject/build-impl.xml.script.CRC32=dbc81ee1
nbproject/build-impl.xml.data.CRC32=1d87756b
nbproject/build-impl.xml.script.CRC32=c2ee0b8b
nbproject/build-impl.xml.stylesheet.CRC32=0ae3a408@1.44.1.45
nbproject/profiler-build-impl.xml.data.CRC32=ab78ce15
nbproject/profiler-build-impl.xml.script.CRC32=abda56ed

View File

@ -1,6 +1,7 @@
annotation.processing.enabled=true
annotation.processing.enabled.in.editor=false
annotation.processing.run.all.processors=true
annotation.processing.enabled.in.editor=true
annotation.processing.processors.list=me.snowleo.yaml.YamlPropertyProcessor
annotation.processing.run.all.processors=false
annotation.processing.source.output=${build.generated.sources.dir}/ap-source-output
application.title=Essentials
application.vendor=
@ -82,7 +83,8 @@ javac.classpath=\
${file.reference.iCo6.jar}:\
${file.reference.MultiCurrency.jar}:\
${file.reference.BOSEconomy7.jar}:\
${file.reference.PermissionsEx.jar}
${file.reference.PermissionsEx.jar}:\
${reference.YamlAnnotations.jar}
# Space-separated list of extra javac options
javac.compilerargs=
javac.deprecation=false
@ -119,6 +121,8 @@ jnlp.signing.keystore=
meta.inf.dir=${src.dir}/META-INF
mkdist.disabled=true
platform.active=default_platform
project.YamlAnnotations=../YamlAnnotations
reference.YamlAnnotations.jar=${project.YamlAnnotations}/dist/YamlAnnotations.jar
run.classpath=\
${javac.classpath}:\
${build.classes.dir}

View File

@ -14,6 +14,15 @@
<libraries xmlns="http://www.netbeans.org/ns/ant-project-libraries/1">
<definitions>../lib/nblibraries.properties</definitions>
</libraries>
<references xmlns="http://www.netbeans.org/ns/ant-project-references/1"/>
<references xmlns="http://www.netbeans.org/ns/ant-project-references/1">
<reference>
<foreign-project>YamlAnnotations</foreign-project>
<artifact-type>jar</artifact-type>
<script>build.xml</script>
<target>jar</target>
<clean-target>clean</clean-target>
<id>jar</id>
</reference>
</references>
</configuration>
</project>

View File

@ -0,0 +1,31 @@
package com.earth2me.essentials.yaml;
import java.util.logging.Level;
import java.util.logging.Logger;
public abstract class BaseYaml<T>
{
protected BaseYaml()
{
}
protected abstract Class<? extends T> getClazz();
public T load() {
try
{
return getClazz().newInstance();
}
catch (InstantiationException ex)
{
Logger.getLogger(BaseYaml.class.getName()).log(Level.SEVERE, null, ex);
}
catch (IllegalAccessException ex)
{
Logger.getLogger(BaseYaml.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
}

View File

@ -0,0 +1,12 @@
package com.earth2me.essentials.yaml;
public class ConfigLoader
{
public ConfigLoader()
{
new Settings().getTest();
}
}

View File

@ -0,0 +1,55 @@
package com.earth2me.essentials.yaml;
import java.io.Serializable;
public class General implements Serializable
{
private boolean debug = false;
private boolean updateCheck = true;
private String location = "null";
public General()
{
}
public boolean isDebug()
{
return debug;
}
public void setDebug(final boolean debug)
{
this.debug = debug;
}
public boolean isUpdateCheck()
{
return updateCheck;
}
public void setUpdateCheck(final boolean updateCheck)
{
this.updateCheck = updateCheck;
}
public boolean isStupid()
{
return true;
}
public void setStupid(final boolean bla)
{
return;
}
public String getLocation()
{
return location;
}
public void setLocation(final String location)
{
this.location = location;
}
}

View File

@ -0,0 +1,16 @@
package com.earth2me.essentials.yaml;
import me.snowleo.yaml.YamlClass;
import me.snowleo.yaml.YamlComment;
@YamlClass
public class Settings extends SettingsYaml
{
@YamlComment(comment = "Hello")
protected General test = new General();
boolean test2 = true;
public Settings() {
}
}

View File

@ -0,0 +1,37 @@
package com.earth2me.essentials;
import junit.framework.TestCase;
import org.yaml.snakeyaml.DumperOptions;
import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.nodes.Tag;
import com.earth2me.essentials.yaml.Settings;
import org.bukkit.Location;
import org.bukkit.World.Environment;
import org.yaml.snakeyaml.constructor.Constructor;
public class YamlTest extends TestCase
{
public YamlTest()
{
}
public void testYaml()
{
final DumperOptions options = new DumperOptions();
options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
options.setExplicitRoot(Tag.MAP);
final Yaml yaml = new Yaml(options);
//Settings settings = (Settings)yaml.load("");
Settings set1 = new Settings();
final String dump = yaml.dump(set1);
final Yaml yaml2 = new Yaml(new Constructor(Settings.class));
final Settings set = (Settings)yaml2.load(dump);
if (set != null)
{
//assert set.getGeneral().getLocation() == null;
//assert set.equals(new Settings());
System.out.println(dump);
}
}
}

74
YamlAnnotations/build.xml Normal file
View File

@ -0,0 +1,74 @@
<?xml version="1.0" encoding="UTF-8"?>
<!-- You may freely edit this file. See commented blocks below for -->
<!-- some examples of how to customize the build. -->
<!-- (If you delete it and reopen the project it will be recreated.) -->
<!-- By default, only the Clean and Build commands use this build script. -->
<!-- Commands such as Run, Debug, and Test only use this build script if -->
<!-- the Compile on Save feature is turned off for the project. -->
<!-- You can turn off the Compile on Save (or Deploy on Save) setting -->
<!-- in the project's Project Properties dialog box.-->
<project name="YamlAnnotations" default="default" basedir=".">
<description>Builds, tests, and runs the project YamlAnnotations.</description>
<import file="nbproject/build-impl.xml"/>
<!--
There exist several targets which are by default empty and which can be
used for execution of your tasks. These targets are usually executed
before and after some main targets. They are:
-pre-init: called before initialization of project properties
-post-init: called after initialization of project properties
-pre-compile: called before javac compilation
-post-compile: called after javac compilation
-pre-compile-single: called before javac compilation of single file
-post-compile-single: called after javac compilation of single file
-pre-compile-test: called before javac compilation of JUnit tests
-post-compile-test: called after javac compilation of JUnit tests
-pre-compile-test-single: called before javac compilation of single JUnit test
-post-compile-test-single: called after javac compilation of single JUunit test
-pre-jar: called before JAR building
-post-jar: called after JAR building
-post-clean: called after cleaning build products
(Targets beginning with '-' are not intended to be called on their own.)
Example of inserting an obfuscator after compilation could look like this:
<target name="-post-compile">
<obfuscate>
<fileset dir="${build.classes.dir}"/>
</obfuscate>
</target>
For list of available properties check the imported
nbproject/build-impl.xml file.
Another way to customize the build is by overriding existing main targets.
The targets of interest are:
-init-macrodef-javac: defines macro for javac compilation
-init-macrodef-junit: defines macro for junit execution
-init-macrodef-debug: defines macro for class debugging
-init-macrodef-java: defines macro for class execution
-do-jar-with-manifest: JAR building (if you are using a manifest)
-do-jar-without-manifest: JAR building (if you are not using a manifest)
run: execution of project
-javadoc-build: Javadoc generation
test-report: JUnit report generation
An example of overriding the target for project execution could look like this:
<target name="run" depends="YamlAnnotations-impl.jar">
<exec dir="bin" executable="launcher.exe">
<arg file="${dist.jar}"/>
</exec>
</target>
Notice that the overridden target depends on the jar target and not only on
the compile target as the regular run target does. Again, for a list of available
properties which you can use, check the target you are overriding in the
nbproject/build-impl.xml file.
-->
</project>

View File

@ -0,0 +1,3 @@
Manifest-Version: 1.0
X-COMMENT: Main-Class will be added automatically by build

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,8 @@
build.xml.data.CRC32=6b9374e7
build.xml.script.CRC32=b35f5bf5
build.xml.stylesheet.CRC32=28e38971@1.44.1.45
# This file is used by a NetBeans-based IDE to track changes in generated files such as build-impl.xml.
# Do not edit this file. You may delete it but then the IDE will never regenerate such files for you.
nbproject/build-impl.xml.data.CRC32=6b9374e7
nbproject/build-impl.xml.script.CRC32=822a2f91
nbproject/build-impl.xml.stylesheet.CRC32=0ae3a408@1.44.1.45

View File

@ -0,0 +1,71 @@
annotation.processing.enabled=true
annotation.processing.enabled.in.editor=false
annotation.processing.processor.options=
annotation.processing.processors.list=
annotation.processing.run.all.processors=true
annotation.processing.source.output=${build.generated.sources.dir}/ap-source-output
build.classes.dir=${build.dir}/classes
build.classes.excludes=**/*.java,**/*.form
# This directory is removed when the project is cleaned:
build.dir=build
build.generated.dir=${build.dir}/generated
build.generated.sources.dir=${build.dir}/generated-sources
# Only compile against the classpath explicitly listed here:
build.sysclasspath=ignore
build.test.classes.dir=${build.dir}/test/classes
build.test.results.dir=${build.dir}/test/results
# Uncomment to specify the preferred debugger connection transport:
#debug.transport=dt_socket
debug.classpath=\
${run.classpath}
debug.test.classpath=\
${run.test.classpath}
# This directory is removed when the project is cleaned:
dist.dir=dist
dist.jar=${dist.dir}/YamlAnnotations.jar
dist.javadoc.dir=${dist.dir}/javadoc
excludes=
includes=**
jar.compress=false
javac.classpath=
# Space-separated list of extra javac options
javac.compilerargs=
javac.deprecation=false
javac.processorpath=\
${javac.classpath}
javac.source=1.6
javac.target=1.6
javac.test.classpath=\
${javac.classpath}:\
${build.classes.dir}
javac.test.processorpath=\
${javac.test.classpath}
javadoc.additionalparam=
javadoc.author=false
javadoc.encoding=${source.encoding}
javadoc.noindex=false
javadoc.nonavbar=false
javadoc.notree=false
javadoc.private=false
javadoc.splitindex=true
javadoc.use=true
javadoc.version=false
javadoc.windowtitle=
main.class=
manifest.file=manifest.mf
meta.inf.dir=${src.dir}/META-INF
mkdist.disabled=false
platform.active=default_platform
run.classpath=\
${javac.classpath}:\
${build.classes.dir}
# Space-separated list of JVM arguments used when running the project
# (you may also define separate properties like run-sys-prop.name=value instead of -Dname=value
# or test-sys-prop.name=value to set system properties for unit tests):
run.jvmargs=
run.test.classpath=\
${javac.test.classpath}:\
${build.test.classes.dir}
source.encoding=UTF-8
src.dir=src
test.src.dir=test

View File

@ -0,0 +1,18 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://www.netbeans.org/ns/project/1">
<type>org.netbeans.modules.java.j2seproject</type>
<configuration>
<data xmlns="http://www.netbeans.org/ns/j2se-project/3">
<name>YamlAnnotations</name>
<source-roots>
<root id="src.dir"/>
</source-roots>
<test-roots>
<root id="test.src.dir"/>
</test-roots>
</data>
<libraries xmlns="http://www.netbeans.org/ns/ant-project-libraries/1">
<definitions>../lib/nblibraries.properties</definitions>
</libraries>
</configuration>
</project>

View File

@ -0,0 +1,11 @@
package me.snowleo.yaml;
import java.lang.annotation.ElementType;
import java.lang.annotation.Target;
@Target(ElementType.TYPE)
public @interface YamlClass
{
}

View File

@ -0,0 +1,12 @@
package me.snowleo.yaml;
import java.lang.annotation.ElementType;
import java.lang.annotation.Target;
@Target(ElementType.FIELD)
public @interface YamlComment
{
String[] comment() default "";
}

View File

@ -0,0 +1,238 @@
package me.snowleo.yaml;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import javax.annotation.processing.AbstractProcessor;
import javax.annotation.processing.Filer;
import javax.annotation.processing.Messager;
import javax.annotation.processing.ProcessingEnvironment;
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.ElementKind;
import javax.lang.model.element.Modifier;
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.VariableElement;
import javax.lang.model.type.TypeMirror;
import javax.lang.model.util.ElementFilter;
import javax.lang.model.util.Elements;
import javax.tools.Diagnostic;
import javax.tools.JavaFileObject;
@SupportedAnnotationTypes("me.snowleo.yaml.YamlClass")
@SupportedSourceVersion(SourceVersion.RELEASE_6)
public class YamlPropertyProcessor extends AbstractProcessor
{
private transient Filer filer;
private transient Messager messager;
private Elements eltUtils;
public YamlPropertyProcessor()
{
super();
}
@Override
public void init(final ProcessingEnvironment processingEnv)
{
super.init(processingEnv);
filer = processingEnv.getFiler();
messager = processingEnv.getMessager();
eltUtils = processingEnv.getElementUtils();
}
@Override
public boolean process(final Set<? extends TypeElement> set, final RoundEnvironment roundEnv)
{
for (Element elem : roundEnv.getElementsAnnotatedWith(YamlClass.class))
{
if (elem.getKind() != ElementKind.CLASS)
{
messager.printMessage(Diagnostic.Kind.ERROR, "YamlClass has to be a class", elem);
continue;
}
final TypeElement clazz = (TypeElement)elem;
String superClassName = clazz.getSuperclass().toString();
if (!superClassName.startsWith(clazz.getEnclosingElement().toString()))
{
superClassName = clazz.getEnclosingElement().toString() + "." + superClassName;
}
if (!superClassName.equalsIgnoreCase(clazz.getQualifiedName().toString() + "Yaml"))
{
messager.printMessage(Diagnostic.Kind.ERROR, "YamlClass must be extended by " + clazz.getQualifiedName().toString() + "Yaml", elem);
continue;
}
final List<VariableElement> fields = new ArrayList<VariableElement>();
for (VariableElement field : ElementFilter.fieldsIn(clazz.getEnclosedElements()))
{
if (!(field.getModifiers().contains(Modifier.STATIC))
&& field.getModifiers().contains(Modifier.PROTECTED))
{
fields.add(field);
}
else if (field.getAnnotation(YamlComment.class) != null)
{
messager.printMessage(Diagnostic.Kind.ERROR, "YamlComment fields have to be nonstatic and protected.", field);
continue;
}
}
if (fields.isEmpty())
{
messager.printMessage(Diagnostic.Kind.ERROR, "YamlClass needs at least one protected field.", clazz);
continue;
}
createImplclass(clazz, fields);
createSuperclass(clazz, fields);
}
return true;
}
private void createSuperclass(final TypeElement clazz, final List<VariableElement> fields)
{
try
{
final JavaFileObject file = filer.createSourceFile(clazz.getQualifiedName() + "Yaml");
messager.printMessage(Diagnostic.Kind.NOTE, "Creating " + file.toUri());
final Writer writer = file.openWriter();
//Add the content to the newly generated file.
final PrintWriter pwriter = new PrintWriter(writer);
try
{
pwriter.print("package ");
pwriter.print(clazz.getEnclosingElement());
pwriter.println(';');
pwriter.println();
pwriter.print("public class ");
pwriter.print(clazz.getSimpleName());
pwriter.print("Yaml extends BaseYaml<");
pwriter.print(clazz.getSimpleName());
pwriter.println("> {");
pwriter.println(" @Override");
pwriter.print(" protected Class<");
pwriter.print(clazz.getSimpleName());
pwriter.print("YamlImpl> getClazz() { return ");
pwriter.print(clazz.getSimpleName());
pwriter.println("YamlImpl.class; };");
for (VariableElement var : fields)
{
final TypeMirror type = var.asType();
final String name = capitalize(var.getSimpleName().toString());
pwriter.print(" public ");
pwriter.print(type.toString());
if (type.toString().equalsIgnoreCase("boolean"))
{
pwriter.print(" is");
}
else
{
pwriter.print(" get");
}
pwriter.print(name);
pwriter.println("() { throw new AssertionError(\"Cannot be called.\"); }");
pwriter.print(" public void set");
pwriter.print(name);
pwriter.print("(final ");
pwriter.print(type.toString());
pwriter.print(' ');
pwriter.print(name);
pwriter.println(") { throw new AssertionError(\"Cannot be called.\"); }");
}
pwriter.println("}");
pwriter.flush();
}
finally
{
pwriter.close();
}
}
catch (IOException ex)
{
messager.printMessage(Diagnostic.Kind.ERROR, ex.toString());
}
}
private void createImplclass(final TypeElement clazz, final List<VariableElement> fields)
{
try
{
final JavaFileObject file = filer.createSourceFile(clazz.getQualifiedName() + "YamlImpl");
messager.printMessage(Diagnostic.Kind.NOTE, "Creating " + file.toUri());
final Writer writer = file.openWriter();
//Add the content to the newly generated file.
final PrintWriter pwriter = new PrintWriter(writer);
try
{
pwriter.print("package ");
pwriter.print(clazz.getEnclosingElement());
pwriter.println(';');
pwriter.println();
pwriter.print("public class ");
pwriter.print(clazz.getSimpleName());
pwriter.print("YamlImpl extends ");
pwriter.print(clazz.getSimpleName());
pwriter.println(" {");
for (VariableElement var : fields)
{
final TypeMirror type = var.asType();
final String name = capitalize(var.getSimpleName().toString());
pwriter.print(" public ");
pwriter.print(type.toString());
if (type.toString().equalsIgnoreCase("boolean"))
{
pwriter.print(" is");
}
else
{
pwriter.print(" get");
}
pwriter.print(name);
pwriter.print("() { return this.");
pwriter.print(var.getSimpleName().toString());
pwriter.println("; }");
pwriter.print(" public void set");
pwriter.print(name);
pwriter.print("(final ");
pwriter.print(type.toString());
pwriter.print(' ');
pwriter.print(name);
pwriter.print(") { this.");
pwriter.print(var.getSimpleName().toString());
pwriter.print(" = ");
pwriter.print(name);
pwriter.println("; }");
}
pwriter.println("}");
pwriter.flush();
}
finally
{
pwriter.close();
}
}
catch (IOException ex)
{
messager.printMessage(Diagnostic.Kind.ERROR, ex.toString());
}
}
private static String capitalize(String name)
{
char[] c = name.toCharArray();
c[0] = Character.toUpperCase(c[0]);
return new String(c);
}
}