Added spotless plugin

This commit is contained in:
Gaetano_Piazzolla
2023-02-26 16:43:54 +01:00
parent 8a2dcb948e
commit b3287e16a5
15 changed files with 374 additions and 369 deletions

View File

@@ -4,6 +4,7 @@ plugins {
id 'java-gradle-plugin'
id 'maven-publish'
id 'application'
id "com.diffplug.spotless" version "6.15.0"
id 'com.gradle.plugin-publish' version '0.12.0'
}
@@ -74,3 +75,12 @@ installDist {
exclude 'gradle-api-6.6.1.jar'
}
spotless {
java {
importOrder()
removeUnusedImports()
cleanthat()
googleJavaFormat()
formatAnnotations()
}
}

View File

@@ -2,11 +2,6 @@ package gae.piaz.layer3gen;
import freemarker.template.TemplateException;
import gae.piaz.layer3gen.config.CodeGeneratorConfig;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.reflections.Reflections;
import org.reflections.scanners.FieldAnnotationsScanner;
import java.io.IOException;
import java.lang.reflect.Field;
import java.net.URLClassLoader;
@@ -14,259 +9,292 @@ import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Optional;
import java.util.Set;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.reflections.Reflections;
import org.reflections.scanners.FieldAnnotationsScanner;
@Slf4j
public class CodeGenerator {
private CodeGenerator() { }
private CodeGenerator() {}
private static CodeGeneratorConfig config;
private static CodeGeneratorConfig config;
private static URLClassLoader classLoader;
private static URLClassLoader classLoader;
public static void run(CodeGeneratorConfig arg, URLClassLoader classLoader) throws IOException, TemplateException {
public static void run(CodeGeneratorConfig arg, URLClassLoader classLoader)
throws IOException, TemplateException {
CodeGenerator.config = arg;
CodeGenerator.classLoader = classLoader;
log.debug("configuration: {}", config);
log.debug("ClassLoader: {}", classLoader);
CodeGenerator.config = arg;
CodeGenerator.classLoader = classLoader;
log.debug("configuration: {}", config);
log.debug("ClassLoader: {}", classLoader);
Set<Class<?>> entities = getEntityClasses();
log.debug("found {} entities", entities.size());
generateCode(entities);
Set<Class<?>> entities = getEntityClasses();
log.debug("found {} entities", entities.size());
generateCode(entities);
}
private static void generateCode(Set<Class<?>> entities) throws IOException, TemplateException {
createCrudInterfaces();
for (Class<?> entity : entities) {
createRepository(entity);
if (Boolean.TRUE.equals(config.getOptions().getServiceInterface())) {
createServiceBean(entity);
createServiceInterface(entity);
} else {
createService(entity);
}
if (Boolean.TRUE.equals(config.getOptions().getEntityControllers())) {
createController(entity);
}
if (Boolean.TRUE.equals(config.getOptions().getDtoLayer())) {
createDto(entity);
createMapper(entity);
createControllerDTO(entity);
}
}
}
private static void generateCode(Set<Class<?>> entities) throws IOException, TemplateException {
private static Set<Class<?>> getEntityClasses() {
Reflections reflections =
new Reflections(config.getInputPackages().getJpaEntities(), classLoader);
Set<Class<?>> classes = reflections.getTypesAnnotatedWith(javax.persistence.Entity.class);
classes.addAll(reflections.getTypesAnnotatedWith(jakarta.persistence.Entity.class));
return classes;
}
createCrudInterfaces();
private static void createControllerDTO(Class<?> entity) throws IOException, TemplateException {
for (Class<?> entity : entities) {
CodeRenderer.RenderingData data = new CodeRenderer.RenderingData();
data.setConfig(config);
data.setEntityClass(entity.getSimpleName());
data.setPrimaryKeyClass(getPrimaryKeyClass(entity));
data.setEntityPackage(entity.getPackageName());
String code = CodeRenderer.render("controllerdto.ftl", data);
createRepository(entity);
if (Boolean.TRUE.equals(config.getOptions().getServiceInterface())) {
createServiceBean(entity);
createServiceInterface(entity);
} else {
createService(entity);
}
if (Boolean.TRUE.equals(config.getOptions().getEntityControllers())){
createController(entity);
}
if (Boolean.TRUE.equals(config.getOptions().getDtoLayer())) {
createDto(entity);
createMapper(entity);
createControllerDTO(entity);
}
}
}
private static Set<Class<?>> getEntityClasses() {
Reflections reflections = new Reflections(config.getInputPackages().getJpaEntities(), classLoader);
Set<Class<?>> classes = reflections.getTypesAnnotatedWith(javax.persistence.Entity.class);
classes.addAll(reflections.getTypesAnnotatedWith(jakarta.persistence.Entity.class));
return classes;
}
private static void createControllerDTO(Class<?> entity) throws IOException, TemplateException {
CodeRenderer.RenderingData data = new CodeRenderer.RenderingData();
data.setConfig(config);
data.setEntityClass(entity.getSimpleName());
data.setPrimaryKeyClass(getPrimaryKeyClass(entity));
data.setEntityPackage(entity.getPackageName());
String code = CodeRenderer.render("controllerdto.ftl", data);
String filepath = Paths.get(config.getProjectPath(), config.getOutputDirectory(),
String filepath =
Paths.get(
config.getProjectPath(),
config.getOutputDirectory(),
config.getOutputPackages().getControllers().replaceAll("\\.", "/"),
entity.getSimpleName() + "ControllerDTO.java").toString();
entity.getSimpleName() + "ControllerDTO.java")
.toString();
writeFile(code, filepath);
writeFile(code, filepath);
}
private static void createMapper(Class<?> entity) throws IOException, TemplateException {
if (StringUtils.isBlank(config.getOutputPackages().getMappers())) {
config.getOutputPackages().setMappers(config.getOutputPackages().getServices() + ".mapper");
}
private static void createMapper(Class<?> entity) throws IOException, TemplateException {
CodeRenderer.RenderingData data = new CodeRenderer.RenderingData();
data.setConfig(config);
data.setEntityClass(entity.getSimpleName());
data.setEntityPackage(entity.getPackageName());
if(StringUtils.isBlank(config.getOutputPackages().getMappers())){
config.getOutputPackages().setMappers(config.getOutputPackages().getServices() + ".mapper");
}
CodeRenderer.RenderingData data = new CodeRenderer.RenderingData();
data.setConfig(config);
data.setEntityClass(entity.getSimpleName());
data.setEntityPackage(entity.getPackageName());
String code = CodeRenderer.render("mapper.ftl", data);
String filepath = Paths.get(config.getProjectPath(), config.getOutputDirectory(),
String code = CodeRenderer.render("mapper.ftl", data);
String filepath =
Paths.get(
config.getProjectPath(),
config.getOutputDirectory(),
config.getOutputPackages().getMappers().replaceAll("\\.", "/"),
entity.getSimpleName() + "Mapper.java").toString();
entity.getSimpleName() + "Mapper.java")
.toString();
writeFile(code, filepath);
writeFile(code, filepath);
}
private static void createDto(Class<?> entity) throws IOException, TemplateException {
if (StringUtils.isBlank(config.getOutputPackages().getDtos())) {
config.getOutputPackages().setDtos(config.getOutputPackages().getControllers() + ".dto");
}
private static void createDto(Class<?> entity) throws IOException, TemplateException {
CodeRenderer.RenderingData data = new CodeRenderer.RenderingData();
data.setConfig(config);
data.setEntityClass(entity.getSimpleName());
data.setEntityFields(Arrays.asList(entity.getDeclaredFields()));
if(StringUtils.isBlank(config.getOutputPackages().getDtos())){
config.getOutputPackages().setDtos(config.getOutputPackages().getControllers() + ".dto");
}
CodeRenderer.RenderingData data = new CodeRenderer.RenderingData();
data.setConfig(config);
data.setEntityClass(entity.getSimpleName());
data.setEntityFields(Arrays.asList(entity.getDeclaredFields()));
String code = CodeRenderer.render("dto.ftl", data);
String filepath = Paths.get(config.getProjectPath(), config.getOutputDirectory(),
String code = CodeRenderer.render("dto.ftl", data);
String filepath =
Paths.get(
config.getProjectPath(),
config.getOutputDirectory(),
config.getOutputPackages().getDtos().replaceAll("\\.", "/"),
entity.getSimpleName() + "DTO.java").toString();
entity.getSimpleName() + "DTO.java")
.toString();
writeFile(code, filepath);
writeFile(code, filepath);
}
}
private static void createController(Class<?> entity) throws IOException, TemplateException {
private static void createController(Class<?> entity) throws IOException, TemplateException {
CodeRenderer.RenderingData data = new CodeRenderer.RenderingData();
data.setConfig(config);
data.setEntityClass(entity.getSimpleName());
data.setPrimaryKeyClass(getPrimaryKeyClass(entity));
data.setEntityPackage(entity.getPackageName());
String code = CodeRenderer.render("controller.ftl", data);
CodeRenderer.RenderingData data = new CodeRenderer.RenderingData();
data.setConfig(config);
data.setEntityClass(entity.getSimpleName());
data.setPrimaryKeyClass(getPrimaryKeyClass(entity));
data.setEntityPackage(entity.getPackageName());
String code = CodeRenderer.render("controller.ftl", data);
String filepath = Paths.get(config.getProjectPath(), config.getOutputDirectory(),
String filepath =
Paths.get(
config.getProjectPath(),
config.getOutputDirectory(),
config.getOutputPackages().getControllers().replaceAll("\\.", "/"),
entity.getSimpleName() + "Controller.java").toString();
entity.getSimpleName() + "Controller.java")
.toString();
writeFile(code, filepath);
writeFile(code, filepath);
}
}
private static void createService(Class<?> entity) throws IOException, TemplateException {
private static void createService(Class<?> entity) throws IOException, TemplateException {
CodeRenderer.RenderingData data = new CodeRenderer.RenderingData();
data.setConfig(config);
data.setEntityClass(entity.getSimpleName());
data.setPrimaryKeyClass(getPrimaryKeyClass(entity));
data.setEntityPackage(entity.getPackageName());
CodeRenderer.RenderingData data = new CodeRenderer.RenderingData();
data.setConfig(config);
data.setEntityClass(entity.getSimpleName());
data.setPrimaryKeyClass(getPrimaryKeyClass(entity));
data.setEntityPackage(entity.getPackageName());
String code = CodeRenderer.render("service.ftl", data);
String code = CodeRenderer.render("service.ftl", data);
String filepath = Paths.get(config.getProjectPath(), config.getOutputDirectory(),
String filepath =
Paths.get(
config.getProjectPath(),
config.getOutputDirectory(),
config.getOutputPackages().getServices().replaceAll("\\.", "/"),
entity.getSimpleName() + "Service.java").toString();
entity.getSimpleName() + "Service.java")
.toString();
writeFile(code, filepath);
writeFile(code, filepath);
}
}
private static void createServiceInterface(Class<?> entity)
throws IOException, TemplateException {
private static void createServiceInterface(Class<?> entity) throws IOException, TemplateException {
CodeRenderer.RenderingData data = new CodeRenderer.RenderingData();
data.setConfig(config);
data.setEntityClass(entity.getSimpleName());
data.setPrimaryKeyClass(getPrimaryKeyClass(entity));
data.setEntityPackage(entity.getPackageName());
CodeRenderer.RenderingData data = new CodeRenderer.RenderingData();
data.setConfig(config);
data.setEntityClass(entity.getSimpleName());
data.setPrimaryKeyClass(getPrimaryKeyClass(entity));
data.setEntityPackage(entity.getPackageName());
String code = CodeRenderer.render("serviceInterface.ftl", data);
String code = CodeRenderer.render("serviceInterface.ftl", data);
String filepath = Paths.get(config.getProjectPath(), config.getOutputDirectory(),
String filepath =
Paths.get(
config.getProjectPath(),
config.getOutputDirectory(),
config.getOutputPackages().getServices().replaceAll("\\.", "/"),
entity.getSimpleName() + "Service.java").toString();
entity.getSimpleName() + "Service.java")
.toString();
writeFile(code, filepath);
writeFile(code, filepath);
}
}
private static void createServiceBean(Class<?> entity) throws IOException, TemplateException {
private static void createServiceBean(Class<?> entity) throws IOException, TemplateException {
CodeRenderer.RenderingData data = new CodeRenderer.RenderingData();
data.setConfig(config);
data.setEntityClass(entity.getSimpleName());
data.setPrimaryKeyClass(getPrimaryKeyClass(entity));
data.setEntityPackage(entity.getPackageName());
CodeRenderer.RenderingData data = new CodeRenderer.RenderingData();
data.setConfig(config);
data.setEntityClass(entity.getSimpleName());
data.setPrimaryKeyClass(getPrimaryKeyClass(entity));
data.setEntityPackage(entity.getPackageName());
String code = CodeRenderer.render("serviceBean.ftl", data);
String code = CodeRenderer.render("serviceBean.ftl", data);
String filepath = Paths.get(config.getProjectPath(), config.getOutputDirectory(),
String filepath =
Paths.get(
config.getProjectPath(),
config.getOutputDirectory(),
config.getOutputPackages().getServices().replaceAll("\\.", "/"),
"impl", entity.getSimpleName() + "ServiceBean.java").toString();
"impl",
entity.getSimpleName() + "ServiceBean.java")
.toString();
writeFile(code, filepath);
writeFile(code, filepath);
}
}
private static void createCrudInterfaces() throws IOException, TemplateException {
private static void createCrudInterfaces() throws IOException, TemplateException {
CodeRenderer.RenderingData data = new CodeRenderer.RenderingData();
data.setConfig(config);
CodeRenderer.RenderingData data = new CodeRenderer.RenderingData();
data.setConfig(config);
String code = CodeRenderer.render("crudservice.ftl", data);
String filepath =
Paths.get(
config.getProjectPath(),
config.getOutputDirectory(),
config.getOutputPackages().getServices().replaceAll("\\.", "/"),
"CrudService.java")
.toString();
writeFile(code, filepath);
String code = CodeRenderer.render("crudservice.ftl", data);
String filepath = Paths.get(config.getProjectPath() , config.getOutputDirectory(),
config.getOutputPackages().getServices().replaceAll("\\.", "/"), "CrudService.java").toString();
writeFile(code, filepath);
code = CodeRenderer.render("crudcontroller.ftl", data);
filepath =
Paths.get(
config.getProjectPath(),
config.getOutputDirectory(),
config.getOutputPackages().getControllers().replaceAll("\\.", "/"),
"CrudController.java")
.toString();
writeFile(code, filepath);
}
code = CodeRenderer.render("crudcontroller.ftl", data);
filepath = Paths.get(config.getProjectPath() , config.getOutputDirectory() ,
config.getOutputPackages().getControllers().replaceAll("\\.", "/"), "CrudController.java").toString();
writeFile(code, filepath);
private static void createRepository(Class<?> entity) throws IOException, TemplateException {
}
CodeRenderer.RenderingData data = new CodeRenderer.RenderingData();
data.setConfig(config);
data.setEntityClass(entity.getSimpleName());
data.setPrimaryKeyClass(getPrimaryKeyClass(entity));
private static void createRepository(Class<?> entity) throws IOException, TemplateException {
String code = CodeRenderer.render("repository.ftl", data);
CodeRenderer.RenderingData data = new CodeRenderer.RenderingData();
data.setConfig(config);
data.setEntityClass(entity.getSimpleName());
data.setPrimaryKeyClass(getPrimaryKeyClass(entity));
String code = CodeRenderer.render("repository.ftl", data);
String filepath = Paths.get(config.getProjectPath() , config.getOutputDirectory(),
String filepath =
Paths.get(
config.getProjectPath(),
config.getOutputDirectory(),
config.getOutputPackages().getRepositories().replaceAll("\\.", "/"),
entity.getSimpleName() + "Repository.java").toString();
entity.getSimpleName() + "Repository.java")
.toString();
writeFile(code, filepath);
writeFile(code, filepath);
}
private static void writeFile(String code, String filepath) throws IOException {
Path path = Paths.get(filepath);
if (!Files.exists(path)) {
Files.createDirectories(path.getParent());
}
Files.write(path, code.getBytes());
log.debug("path: {}, code: {}", path, code);
}
private static String getPrimaryKeyClass(Class<?> entity) {
Reflections reflections = new Reflections(entity, classLoader, new FieldAnnotationsScanner());
Set<Field> ids = reflections.getFieldsAnnotatedWith(javax.persistence.Id.class);
ids.addAll(reflections.getFieldsAnnotatedWith(jakarta.persistence.Id.class));
if (ids.isEmpty()) {
ids = reflections.getFieldsAnnotatedWith(javax.persistence.EmbeddedId.class);
ids.addAll(reflections.getFieldsAnnotatedWith(javax.persistence.EmbeddedId.class));
if (ids.isEmpty()) {
log.warn("No @Id found for " + entity + " using generic object \"Object\" ");
return "Object";
}
}
private static void writeFile(String code, String filepath) throws IOException {
Path path = Paths.get(filepath);
if (!Files.exists(path)) {
Files.createDirectories(path.getParent());
}
Files.write(path, code.getBytes());
log.debug("path: {}, code: {}", path, code);
}
private static String getPrimaryKeyClass(Class<?> entity) {
Reflections reflections = new Reflections(entity, classLoader, new FieldAnnotationsScanner());
Set<Field> ids = reflections.getFieldsAnnotatedWith(javax.persistence.Id.class);
ids.addAll(reflections.getFieldsAnnotatedWith(jakarta.persistence.Id.class));
if (ids.isEmpty()) {
ids = reflections.getFieldsAnnotatedWith(javax.persistence.EmbeddedId.class);
ids.addAll(reflections.getFieldsAnnotatedWith(javax.persistence.EmbeddedId.class));
if (ids.isEmpty()) {
log.warn("No @Id found for " + entity + " using generic object \"Object\" ");
return "Object";
}
}
return ids.stream().findFirst().get().getType().getName();
}
return ids.stream().findFirst().get().getType().getName();
}
}

View File

@@ -7,59 +7,51 @@ import freemarker.template.Template;
import freemarker.template.TemplateException;
import freemarker.template.TemplateExceptionHandler;
import gae.piaz.layer3gen.config.CodeGeneratorConfig;
import lombok.Data;
import java.io.*;
import java.lang.reflect.Field;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
import lombok.Data;
/**
* Code renderer.
*/
/** Code renderer. */
public class CodeRenderer {
/**
* Renders source code by using Freemarker template engine.
*/
public static String render(String templatePath, RenderingData data) throws IOException, TemplateException {
Configuration config = new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS);
StringTemplateLoader templateLoader = new StringTemplateLoader();
String source;
try (InputStream is = ResourceReader.getResourceAsStream(templatePath);
BufferedReader buffer = new BufferedReader(new InputStreamReader(is))) {
source = buffer.lines().collect(Collectors.joining("\n"));
}
templateLoader.putTemplate("template", source);
config.setTemplateLoader(templateLoader);
config.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
config.setObjectWrapper(new BeansWrapper(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS));
config.setWhitespaceStripping(true);
try (Writer writer = new StringWriter()) {
Template template = config.getTemplate("template");
template.process(data, writer);
return writer.toString();
}
/** Renders source code by using Freemarker template engine. */
public static String render(String templatePath, RenderingData data)
throws IOException, TemplateException {
Configuration config = new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS);
StringTemplateLoader templateLoader = new StringTemplateLoader();
String source;
try (InputStream is = ResourceReader.getResourceAsStream(templatePath);
BufferedReader buffer = new BufferedReader(new InputStreamReader(is))) {
source = buffer.lines().collect(Collectors.joining("\n"));
}
templateLoader.putTemplate("template", source);
config.setTemplateLoader(templateLoader);
config.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
config.setObjectWrapper(new BeansWrapper(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS));
config.setWhitespaceStripping(true);
/**
* Data used when rendering source code.
*/
@Data
public static class RenderingData {
private String entityClass;
private String entityPackage;
private String primaryKeyClass;
private CodeGeneratorConfig config;
private List<Field> entityFields;
private Date dateGen = new Date();
try (Writer writer = new StringWriter()) {
Template template = config.getTemplate("template");
template.process(data, writer);
return writer.toString();
}
}
/** Data used when rendering source code. */
@Data
public static class RenderingData {
private String entityClass;
private String entityPackage;
private String primaryKeyClass;
private CodeGeneratorConfig config;
private List<Field> entityFields;
private Date dateGen = new Date();
}
}

View File

@@ -5,21 +5,17 @@ import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
/**
* Utility to reader classpath resources.
*/
/** Utility to reader classpath resources. */
public class ResourceReader {
private ResourceReader() {
}
private ResourceReader() {}
public static InputStream getResourceAsStream(String path) throws IOException {
InputStream classPathResource = ResourceReader.class.getClassLoader().getResourceAsStream(path);
if (classPathResource != null) {
return classPathResource;
}
InputStream fileResource = new FileInputStream(new File(path));
return fileResource;
public static InputStream getResourceAsStream(String path) throws IOException {
InputStream classPathResource = ResourceReader.class.getClassLoader().getResourceAsStream(path);
if (classPathResource != null) {
return classPathResource;
}
InputStream fileResource = new FileInputStream(new File(path));
return fileResource;
}
}

View File

@@ -1,52 +1,46 @@
package gae.piaz.layer3gen.config;
import gae.piaz.layer3gen.ResourceReader;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.yaml.snakeyaml.Yaml;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
@Data
@Slf4j
public class CodeGeneratorConfig implements Serializable {
private String projectPath;
private String classesDirectory;
private String outputDirectory;
private Options options;
private InputPackages inputPackages;
private OutputPackages outputPackages;
private String projectPath;
private String classesDirectory;
private String outputDirectory;
private Options options;
private InputPackages inputPackages;
private OutputPackages outputPackages;
private static final Yaml YAML = new Yaml();
private static final Yaml YAML = new Yaml();
public static CodeGeneratorConfig load(String path, boolean fromClassPath) throws IOException {
if(StringUtils.isBlank(path)){
path = "3layer-settings.yml";
}
InputStream is;
if(!fromClassPath) {
Path a = Paths.get(path);
log.info("Configuration path: {}",a.toString());
is = Files.newInputStream(a);
}
else{
is = ResourceReader.getResourceAsStream(path);
}
try (Reader reader = new InputStreamReader(is)) {
return YAML.loadAs(reader, CodeGeneratorConfig.class);
}
public static CodeGeneratorConfig load(String path, boolean fromClassPath) throws IOException {
if (StringUtils.isBlank(path)) {
path = "3layer-settings.yml";
}
InputStream is;
if (!fromClassPath) {
Path a = Paths.get(path);
log.info("Configuration path: {}", a.toString());
is = Files.newInputStream(a);
} else {
is = ResourceReader.getResourceAsStream(path);
}
try (Reader reader = new InputStreamReader(is)) {
return YAML.loadAs(reader, CodeGeneratorConfig.class);
}
}
}

View File

@@ -4,5 +4,5 @@ import lombok.Data;
@Data
public class InputPackages {
private String jpaEntities;
private String jpaEntities;
}

View File

@@ -4,7 +4,7 @@ import lombok.Data;
@Data
public class Options {
private Boolean dtoLayer;
private Boolean serviceInterface;
private Boolean entityControllers;
private Boolean dtoLayer;
private Boolean serviceInterface;
private Boolean entityControllers;
}

View File

@@ -4,9 +4,9 @@ import lombok.Data;
@Data
public class OutputPackages {
private String repositories;
private String services;
private String controllers;
private String dtos;
private String mappers;
private String repositories;
private String services;
private String controllers;
private String dtos;
private String mappers;
}

View File

@@ -1,32 +1,28 @@
package gae.piaz.layer3gen.gradle;
import gae.piaz.layer3gen.config.CodeGeneratorConfig;
import org.gradle.api.Project;
import org.gradle.api.file.FileCollection;
import org.gradle.api.invocation.Gradle;
import org.gradle.api.plugins.JavaPluginConvention;
import org.gradle.api.tasks.SourceSetContainer;
import org.gradle.tooling.model.GradleProject;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.List;
import org.gradle.api.Project;
import org.gradle.api.file.FileCollection;
import org.gradle.api.plugins.JavaPluginConvention;
import org.gradle.api.tasks.SourceSetContainer;
public final class ClassLoaderBuilderGradle {
private ClassLoaderBuilderGradle(){
}
private ClassLoaderBuilderGradle() {}
public static URLClassLoader getClassLoader(Project project) throws MalformedURLException {
List<URL> listOfURL = new ArrayList<>();
SourceSetContainer ssc = project.getConvention().getPlugin(JavaPluginConvention.class).getSourceSets();
FileCollection classesDir = ssc.getByName("main").getOutput().getClassesDirs();
for (File file : classesDir) {
listOfURL.add(file.toURI().toURL());
}
return new java.net.URLClassLoader(listOfURL.toArray(new URL[0]));
public static URLClassLoader getClassLoader(Project project) throws MalformedURLException {
List<URL> listOfURL = new ArrayList<>();
SourceSetContainer ssc =
project.getConvention().getPlugin(JavaPluginConvention.class).getSourceSets();
FileCollection classesDir = ssc.getByName("main").getOutput().getClassesDirs();
for (File file : classesDir) {
listOfURL.add(file.toURI().toURL());
}
return new java.net.URLClassLoader(listOfURL.toArray(new URL[0]));
}
}

View File

@@ -5,6 +5,5 @@ import lombok.Data;
@Data
public class Layer3GenExtension {
private String configPath = "src/main/resources/3layer-settings.yml";
private String configPath = "src/main/resources/3layer-settings.yml";
}

View File

@@ -1,24 +1,20 @@
package gae.piaz.layer3gen.gradle;
import gae.piaz.layer3gen.CodeGenerator;
import org.gradle.api.Plugin;
import org.gradle.api.Project;
import org.gradle.api.Task;
/**
* entityGen Gradle plugin.
*/
/** entityGen Gradle plugin. */
public class Layer3GenPlugin implements Plugin<Project> {
@Override
public void apply(Project project) {
@Override
public void apply(Project project) {
project.getExtensions().create("layer3gen", Layer3GenExtension.class);
project.getTasks().create("layer3gen", Layer3GenTask.class);
project.getExtensions().create("layer3gen", Layer3GenExtension.class);
project.getTasks().create("layer3gen", Layer3GenTask.class);
/*project.getExtensions().create("layer3gen", Layer3GenExtension.class);
Task task = project.getTasks().create("layer3gen", Layer3GenTask.class);
org.gradle.api.Task javaCompile = project.getTasks().getByName("compileJava");
task.dependsOn(javaCompile);*/
}
/*project.getExtensions().create("layer3gen", Layer3GenExtension.class);
Task task = project.getTasks().create("layer3gen", Layer3GenTask.class);
org.gradle.api.Task javaCompile = project.getTasks().getByName("compileJava");
task.dependsOn(javaCompile);*/
}
}

View File

@@ -5,19 +5,17 @@ import gae.piaz.layer3gen.config.CodeGeneratorConfig;
import org.gradle.api.DefaultTask;
import org.gradle.api.tasks.TaskAction;
/**
* entityGen Gradle task.
*/
/** entityGen Gradle task. */
public class Layer3GenTask extends DefaultTask {
@TaskAction
public void generateAll() throws Exception {
@TaskAction
public void generateAll() throws Exception {
Layer3GenExtension ext = getProject().getExtensions().getByType(Layer3GenExtension.class);
if (ext == null) {
ext = new Layer3GenExtension();
}
CodeGeneratorConfig config = CodeGeneratorConfig.load(ext.getConfigPath(),true);
CodeGenerator.run(config,ClassLoaderBuilderGradle.getClassLoader(getProject()));
Layer3GenExtension ext = getProject().getExtensions().getByType(Layer3GenExtension.class);
if (ext == null) {
ext = new Layer3GenExtension();
}
CodeGeneratorConfig config = CodeGeneratorConfig.load(ext.getConfigPath(), true);
CodeGenerator.run(config, ClassLoaderBuilderGradle.getClassLoader(getProject()));
}
}

View File

@@ -1,7 +1,6 @@
package gae.piaz.layer3gen.main;
import gae.piaz.layer3gen.config.CodeGeneratorConfig;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
@@ -11,12 +10,13 @@ import java.util.List;
public final class ClassLoaderBuilderMain {
private ClassLoaderBuilderMain() {}
public static URLClassLoader getClassLoader(CodeGeneratorConfig config) throws MalformedURLException {
final File classes = new File(Paths.get(config.getProjectPath(), config.getClassesDirectory()).toString());
List<URL> listOfURL = List.of(classes.toURI().toURL());
return new URLClassLoader(listOfURL.toArray(new URL[0]));
}
private ClassLoaderBuilderMain() {}
public static URLClassLoader getClassLoader(CodeGeneratorConfig config)
throws MalformedURLException {
final File classes =
new File(Paths.get(config.getProjectPath(), config.getClassesDirectory()).toString());
List<URL> listOfURL = List.of(classes.toURI().toURL());
return new URLClassLoader(listOfURL.toArray(new URL[0]));
}
}

View File

@@ -6,13 +6,12 @@ import org.apache.commons.lang3.ArrayUtils;
public class Layer3GenMain {
public static void main(String[] args) throws Exception {
String configFile = "";
if(!ArrayUtils.isEmpty(args)){
configFile = args[0];
}
CodeGeneratorConfig config = CodeGeneratorConfig.load(configFile,false);
CodeGenerator.run(config,ClassLoaderBuilderMain.getClassLoader(config));
public static void main(String[] args) throws Exception {
String configFile = "";
if (!ArrayUtils.isEmpty(args)) {
configFile = args[0];
}
}
CodeGeneratorConfig config = CodeGeneratorConfig.load(configFile, false);
CodeGenerator.run(config, ClassLoaderBuilderMain.getClassLoader(config));
}
}

View File

@@ -1,26 +1,23 @@
package gae.piaz.layer3gen.test;
import freemarker.template.TemplateException;
import gae.piaz.layer3gen.CodeGenerator;
import gae.piaz.layer3gen.config.CodeGeneratorConfig;
import gae.piaz.layer3gen.main.ClassLoaderBuilderMain;
import org.junit.Test;
import java.io.IOException;
import org.junit.Test;
public class TestMainGenerator {
@Test
public void testGeneration() throws IOException, TemplateException {
CodeGeneratorConfig config = CodeGeneratorConfig.load("3layer-settings.yml",true);
CodeGenerator.run(config,ClassLoaderBuilderMain.getClassLoader(config));
}
@Test
public void testJakartaGeneration() throws IOException, TemplateException {
CodeGeneratorConfig config = CodeGeneratorConfig.load("3layer-settings-jakarta.yml",true);
CodeGenerator.run(config,ClassLoaderBuilderMain.getClassLoader(config));
}
@Test
public void testGeneration() throws IOException, TemplateException {
CodeGeneratorConfig config = CodeGeneratorConfig.load("3layer-settings.yml", true);
CodeGenerator.run(config, ClassLoaderBuilderMain.getClassLoader(config));
}
@Test
public void testJakartaGeneration() throws IOException, TemplateException {
CodeGeneratorConfig config = CodeGeneratorConfig.load("3layer-settings-jakarta.yml", true);
CodeGenerator.run(config, ClassLoaderBuilderMain.getClassLoader(config));
}
}