uk.co.wansdykehouse.JsonSchemaMavenPlugin Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of jsonschema-maven-plugin Show documentation
Show all versions of jsonschema-maven-plugin Show documentation
Generate JSON schemas from Java POJOs with Maven.
package uk.co.wansdykehouse;
import java.io.File;
import java.lang.annotation.Annotation;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugins.annotations.Component;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.plugins.annotations.ResolutionScope;
import org.apache.maven.project.MavenProject;
import uk.co.wansdyke.jsonschema.JsonSchema;
import uk.co.wansdyke.jsonschema.Main;
import com.google.common.io.Files;
@Mojo(name = "jsonschema", requiresDependencyResolution = ResolutionScope.RUNTIME)
public class JsonSchemaMavenPlugin extends AbstractMojo {
@Component
private MavenProject project;
@Parameter(property = "basedir")
private String basedir;
@Parameter(property = "project.build.directory")
private String target;
public void execute() throws MojoExecutionException {
getLog().info( "Exporting JSON schemas." );
final List urls = new ArrayList<>();
try {
final List elements = project.getCompileClasspathElements();
for (final String element : elements) {
final URL url = new File(element).toURI().toURL();
urls.add(url);
}
} catch (final Exception e) {
e.printStackTrace();
}
try (final URLClassLoader loader = new URLClassLoader(
urls.toArray(new URL[0]),
Thread.currentThread().getContextClassLoader());) {
final List classes = list(new File(target));
for (final File file : classes) {
final String className = file.getPath().substring(
(target +File.separator +"classes" +File.separator).length(),
file.getPath().length() - ".class".length())
.replace('/', '.');
final Class> clazz = loader.loadClass(className);
final Annotation[] annotations = clazz.getAnnotations();
for (final Annotation annotation : annotations) {
if (annotation.annotationType().getCanonicalName().equals(JsonSchema.class.getCanonicalName())) {
final String schema = Main.process(clazz);
Files.write(schema.getBytes(),
Paths.get(target, clazz.getSimpleName().toLowerCase() +".schema.json").toFile());
break;
}
}
}
} catch (final Exception e) {
e.printStackTrace();
}
}
private List list(final File folder) {
final List files = new ArrayList<>();
for (final File entry : folder.listFiles()) {
if (entry.isDirectory()) {
files.addAll(list(entry));
} else if (entry.getName().endsWith(".class")) {
files.add(entry);
}
}
return files;
}
}