com.sprhibrad.generator.Generator Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of sprhibrad-generator Show documentation
Show all versions of sprhibrad-generator Show documentation
The generator of the SprHibRAD suite - Stefano Pizzocaro - 62
/*
Copyright (c) 2017, Stefano Pizzocaro. All rights reserved. Use is subject to license terms.
This file is part of SprHibRAD 1.0.
SprHibRAD 1.0 is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SprHibRAD 1.0 is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with SprHibRAD 1.0. If not, see .
*/
package com.sprhibrad.generator;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.CopyOption;
import java.nio.file.DirectoryNotEmptyException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Vector;
import java.util.function.BiConsumer;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import com.sprhibrad.generator.SprHibRadGen.DetailDescriptor;
import com.sprhibrad.names.Names;
/**
* The class performs the generation of the code of a SprHibRAD based
* application. It processes the content of the SprHibRAD Generator project (the
* Json tree) developed through the use of the gui object provided by the
* {@link SprHibRadGen} class. Like the project editor class, the project
* processor too makes use of the package {@code org.json.simple} to do the job,
* by being the project file a Json file.
*
* Part of the generated files (MVC files) are completely synthesized basing on
* the project content, others (like configuration files) are template based
* generated with the pattern substitution mechanism, again based on the project
* file. Other part of the files that make the final SprHibRAD application
* project are completely copied "as are" from the 'resources' directory.
*
* @see ShrgJSONArray
* @see ShrgJsonPeeker
*/
public class Generator {
class ShrgFileWriter extends FileWriter {
int indentationCount;
int indentationIncrease = 0;
boolean noTerminator;
public Vector injectors;
public void addInjector(Injector injector) {
if (injectors == null)
injectors = new Vector();
injectors.add(injector);
}
public boolean isNoTerminator() {
return noTerminator;
}
public void setNoTerminator(boolean noTerminator) {
this.noTerminator = noTerminator;
}
public ShrgFileWriter(String fileName) throws IOException {
super(fileName);
}
void increaseIndent() {
indentationCount++;
}
void decreaseIndent() {
indentationCount--;
}
public int getIndentationCount() {
return indentationCount;
}
public void setIndentationCount(int indentationCount) {
this.indentationCount = indentationCount;
}
@Override
public void write(String str) throws IOException {
indentationCount += indentationIncrease;
StringBuilder builder = new StringBuilder("");
for (int i=0; i < indentationCount; i++)
builder.append("\t");
super.write(builder.toString() + str);
}
public void setIndentationIncrease(int increase) {
indentationIncrease = increase;
}
}
class FkManager {
JSONObject entityObj;
JSONObject fksObj;
HashSet fks = new HashSet();
ShrgFileWriter writer;
protected int counter;
public FkManager(JSONObject entityObj, ShrgFileWriter writer) {
this.entityObj = entityObj;
this.writer = writer;
render();
}
public int counter() {
return counter;
}
void render() {
fksObj = (JSONObject) entityObj.get("fks");
if (fksObj != null) {
if (fksObj.size() > 0)
prolog();
fksObj.forEach(new BiConsumer() {
@Override
public void accept(String fkField, JSONObject fkFieldObj) {
fks.add(fkField);
String targetEntity = getAttribute(fkFieldObj, "fieldTargetEntity");
if (targetEntity != null)
renderBody(writer, memberName(fkField), targetEntity, fkField);
}
});
if (fksObj.size() > 0)
epilog();
}
}
protected void epilog() {}
protected void prolog() {}
public void renderBody(ShrgFileWriter writer, String memberName, String targetEntity, String fkField) {};
}
String memberName(String fieldName) {
int index = fieldName.indexOf("_id");
return index == fieldName.length() - 3 ? fieldName.substring(0, index) : fieldName;
}
JSONObject project;
ShrgFileWriter fileWriter;
SprHibRadGen app = SprHibRadGen.app;
Map> packagesMap;
Map modelWriters;
Map daoWriters;
Map serviceWriters;
Map controllerWriters;
Map converterWriters;
Map reportsWriters;
Map lookUpJspsWriters;
Map formJspsWriters;
Map configWriters;
ShrgFileWriter birtEngineFactory_writer;
ShrgFileWriter birtView_writer;
ShrgFileWriter applicationInitializer_writer;
ShrgFileWriter applicationWebConf_writer;
ShrgFileWriter securityInitializer_writer;
ShrgFileWriter securityConfig_writer;
ShrgFileWriter dictionary_en_US_writer;
ShrgFileWriter applicationConf_writer;
String modelPath;
String daoPath;
String servicePath;
String controllerPath;
String converterPath;
String reportsPath;
String configPath;
private String resourcesFolderPath;
private String packagePath;
Map packagesPathMap;
private String jsps_FolderPath;
HashSet messagesSet = new HashSet();
HashMap> dataObjectRenderings = new HashMap>();
public Generator() {
init(false);
}
public void init(boolean onGeneration) {
if ( ! app.checkMainData())
return;
modelWriters = new HashMap();
daoWriters = new HashMap();
serviceWriters = new HashMap();
controllerWriters = new HashMap();
converterWriters = new HashMap();
reportsWriters = new HashMap();
lookUpJspsWriters = new HashMap();
formJspsWriters = new HashMap();
configWriters = new HashMap();
packagesMap = new HashMap>();
packagesMap.put("model", modelWriters);
packagesMap.put("dao", daoWriters);
packagesMap.put("service", serviceWriters);
packagesMap.put("controller", controllerWriters);
packagesMap.put("converter", converterWriters);
packagesMap.put("reports", reportsWriters);
packagesMap.put(configurePackage, configWriters);
project = app.prjProperties.obj;
String projectPath = targetProjectPath();
String src_main_FolderPath = projectPath + "/src/main";
String javaFolderPath = src_main_FolderPath + "/java";
resourcesFolderPath = src_main_FolderPath + "/resources";
if (app.targetPackage != null) {
packagePath = javaFolderPath + "/" + app.targetPackage.replace(".", "/");
packagesPathMap = new HashMap<>();
packagesMap.forEach(new BiConsumer>() {
@Override
public void accept(String packageName, Map writer) {
packagesPathMap.put(packageName, packagePath + "/" + packageName);
createDirectories(packagePath + "/" + packageName);
}});
createDirectories(resourcesFolderPath);
jsps_FolderPath = projectPath + "/WebContent/WEB-INF/views/";
createDirectories(jsps_FolderPath);
messagesSet.clear();
dataObjectRenderings.clear();
}
if (onGeneration) {
copyFile("resources", "messages_en_US.properties", "/src/main");
copyFile("", ".classpath", "");
copyFile("WebContent/reports/", "en_US", "");
copyFile("WebContent/WEB-INF/resources/css", "shr.css", "");
copyFile("WebContent/WEB-INF/resources/images", "handout.jpg", "");
copyFile("WebContent/WEB-INF/resources/images", "noImg.jpg", "");
copyFile("WebContent/WEB-INF/resources/js", "SprHibRAD.js", "");
copyFile("WebContent/WEB-INF/views", "changePwd_form.jsp", "");
copyFile("WebContent/WEB-INF/views", "exception.jsp", "");
copyFile("WebContent/WEB-INF/views", "home.jsp", "");
copyFile("WebContent/WEB-INF/views", "login.jsp", "");
copyFile("WebContent/WEB-INF/views", "noaccess.jsp", "");
copyFile("WebContent/WEB-INF/views", "sessionexp.jsp", "");
copyFile("WebContent/WEB-INF/views", "uploadBinary.jsp", "");
copyFile("WebContent/WEB-INF/views", "userPrefs_form.jsp", "");
copyFile("WebContent/WEB-INF", "log4j2.xml", "");
copyFile("WebContent/WEB-INF", "SprHibRad.tld", "");
copyFile("WebContent/META-INF", "MANIFEST.MF", "");
copyFile(".settings", "org.eclipse.jdt.core.prefs", "");
copyFile(".settings", "org.eclipse.m2e.core.prefs", "");
copyFile(".settings", "org.eclipse.wst.common.project.facet.core.xml", "");
copyFile(".settings", "org.eclipse.wst.validation.prefs", "");
}
}
protected void copyFile(String path, String fileName, String targetPath) {
try {
Path source = Paths.get(genResPath() + "/" + path + "/" + fileName);
String targetPathString = targetProjectPath() + targetPath + "/" + path;
createDirectories(targetPathString);
Files.copy(source, Paths.get(targetPathString).resolve(source.getFileName()),
new CopyOption[] {StandardCopyOption.REPLACE_EXISTING});
} catch (IOException e) {
if ( ! (e instanceof DirectoryNotEmptyException))
app.outToConsole(e);
}
}
protected void createDirectories(String path) {
try {
Files.createDirectories(Paths.get(path));
} catch (IOException e) {
app.outToConsole(e);
}
}
protected void includeImports(String packageName, Map writers) {
writers.forEach(new BiConsumer() {
@Override
public void accept(String entity, ShrgFileWriter writer) {
includeImports(packageName, writer, entity);
}});
}
interface Injector {
void inject(ShrgFileWriter writer);
}
String genResPath() {
return Paths.get("").toAbsolutePath().toString() + "/resources/";
}
String targetProjectPath() {
SprHibRadGen app = SprHibRadGen.app;
String storedTargetDir = app.txtTargetDir.getText();
return storedTargetDir.isEmpty() ? app.projectPathName.substring(0, app.projectPathName.indexOf(".")) : (storedTargetDir + "/" + app.txtShrAppName.getText().replace(" ", "_"));
}
protected void includeImports(String packageName, ShrgFileWriter writer, String entity) {
if (writer == null)
return;
FileReader fileReader = null;
try {
boolean isVerboseLiteral = entityIs(entity, "verboseLiteral") && packageName.compareTo("model") == 0;
fileReader = new FileReader(genResPath() + "imports/" + (isVerboseLiteral ? "literalCollections" : packageName) + ".java");
} catch (FileNotFoundException e) {
app.outToConsole(e);
}
String input;
int c;
try {
while ((c=fileReader.read()) != -1)
writer.write(c);
} catch (IOException e) {
app.outToConsole(e);
}
}
FileReader templateReader(String dir, String ext, String name) {
FileReader fileReader = null;
try {
fileReader = new FileReader(genResPath() + dir + (dir.length() == 0 ? "" : "/") + name + (ext != null && ! ext.isEmpty() ? "." + ext : ""));
} catch (FileNotFoundException e) {
app.outToConsole(e);
}
return fileReader;
}
protected void copyJavaTemplate(ShrgFileWriter writer, String name) {
copyTemplate(templateReader("templates", "java", name), writer);
}
void copyTemplate(FileReader fileReader, ShrgFileWriter writer) {
String input;
int c = 0;
int injectionIndex = 0;
try {
while ((c = fileReader.read()) != -1) {
if (c == '\u00a7') {
writer.injectors.get(injectionIndex++).inject(writer);
while (((c = fileReader.read()) == 10 || c == 13) && c != -1);
}
if (c != -1)
writer.write(c);
}
} catch (IOException e) {
app.outToConsole(e);
}
}
private boolean entityIs(String entity, String feature) {
return app.shrgJsonPeeker.isAttributeSet(project, new String[] {"entities", entity, feature, "value"});
}
public final String configurePackage = "configuration";
public void createConfigWriter(String fileName) throws IOException {
configWriters.put(fileName, new ShrgFileWriter(packagesPathMap.get(configurePackage) + "/" + fileName + ".java"));
}
public void createConfigWriters() {
try {
createConfigWriter("BirtEngineFactory");
createConfigWriter("BirtView");
createConfigWriter("Initializer");
createConfigWriter("WebConf");
createConfigWriter("SecurityWebApplicationInitializer");
createConfigWriter("WebSecurityConfig");
createConfigWriter("UserManagerImpl");
} catch (IOException e) {
app.outToConsole(e);
}
}
public void createWriters(String entity) {
String classTheme = toClassName(entity);
try {
boolean isVerboseLiteral = entityIs(entity, "verboseLiteral");
boolean withReports = entityIs(entity, "formPrintable");
modelWriters.put( entity, new ShrgFileWriter(packagesPathMap.get("model") + "/" + classTheme + ".java"));
daoWriters.put( entity, new ShrgFileWriter(packagesPathMap.get("dao") + "/" + classTheme + "Dao.java"));
serviceWriters.put( entity, new ShrgFileWriter(packagesPathMap.get("service") + "/" + classTheme + "Service.java"));
reportsWriters.put( entity, withReports ? new ShrgFileWriter(packagesPathMap.get("reports") + "/" + classTheme + "Reports.java") :
null);
converterWriters.put( entity, isVerboseLiteral ? new ShrgFileWriter(packagesPathMap.get("converter") + "/" + classTheme + "Converter.java") :
null);
controllerWriters.put( entity, isVerboseLiteral ? null :
new ShrgFileWriter(packagesPathMap.get("controller") + "/" + classTheme + "Controller.java"));
lookUpJspsWriters.put( entity, isVerboseLiteral ? null :
new ShrgFileWriter(jsps_FolderPath + Names.plural(entity) + ".jsp"));
formJspsWriters.put(entity, isVerboseLiteral ? null :
new ShrgFileWriter(jsps_FolderPath + entity + "_form.jsp"));
} catch (IOException e) {
app.outToConsole(e);
}
}
private String toClassName(String entity) {
return entity.substring(0,1).toUpperCase() + entity.substring(1);
}
public void closeFiles(Map fileWriters) {
fileWriters.forEach (new BiConsumer() {
@Override
public void accept(String t, ShrgFileWriter writer) {
if (writer != null) {
try {
writer.close();
} catch (IOException e) {
app.outToConsole(e);
}
}
}
});
}
public void closeFile(ShrgFileWriter fileWriter) {
try {
fileWriter.close();
} catch (IOException e) {
app.outToConsole(e);
}
}
public void store(Map fileWriters, String text) {
fileWriters.forEach(new BiConsumer() {
@Override
public void accept(String entity, ShrgFileWriter writer) {
if (writer != null) {
try {
writer.write(text + ";\n");
} catch (IOException e) {
app.outToConsole(e);
}
}
}});
}
public void write(ShrgFileWriter fileWriter, String text) {
write(fileWriter, text, false);
}
public void write(ShrgFileWriter fileWriter, String text, boolean noTerminator) {
try {
text = text.trim();
ShrgFileWriter shrgFileWriter = fileWriter;
int len = text.length();
boolean openingBlock = len > 0 && text.charAt(len-1) == '{';
boolean closingBlock = len > 0 && text.charAt(len-1) == '}';
if (closingBlock)
shrgFileWriter.decreaseIndent();
shrgFileWriter.write(text + (len == 0 || text.indexOf("@") == 0 || text.charAt(len-1) == '>' ||
openingBlock || closingBlock || shrgFileWriter.isNoTerminator() || noTerminator ? "" : ";") + "\n");
if (openingBlock)
shrgFileWriter.increaseIndent();
} catch (IOException e) {
app.outToConsole(e);
}
}
ShrgFileWriter createResourceWriter(String fileName) {
return createWriter(resourcesFolderPath + "/" + fileName);
}
ShrgFileWriter createWriter(String filePathName) {
ShrgFileWriter writer = null;
try {
writer = new ShrgFileWriter(filePathName);
writer.setNoTerminator(true);
} catch (IOException e) {
app.outToConsole(e);
}
return writer;
}
public void generate() {
app.long_op_success = true;
app.setWaitCursor(true);
init(true);
ShrgFileWriter pomFileWriter = null;
ShrgFileWriter eclipseProjectFileWriter = null;
ShrgFileWriter eclipseComponentFileWriter = null;
try {
String aValidProjectLiteral = app.txtShrAppName.getText().replace(" ", "_");
pomFileWriter = createWriter(targetProjectPath() + "/pom.xml");
pomFileWriter.addInjector(new Injector() {
@Override
public void inject(ShrgFileWriter writer) {
writer.setIndentationCount(1);
write(writer, "" + aValidProjectLiteral + " ");
write(writer, "" + aValidProjectLiteral + " ");
}
});
copyTemplate(templateReader("", "xml", "pom"), pomFileWriter);
eclipseProjectFileWriter = createWriter(targetProjectPath() + "/.project");
eclipseProjectFileWriter.addInjector(new Injector() {
@Override
public void inject(ShrgFileWriter writer) {
writer.setIndentationCount(1);
write(writer, "" + aValidProjectLiteral + " ");
}
});
copyTemplate(templateReader("", "project", ""), eclipseProjectFileWriter);
eclipseComponentFileWriter = createWriter(
targetProjectPath() + "/.settings/org.eclipse.wst.common.component");
eclipseComponentFileWriter.addInjector(new Injector() {
@Override
public void inject(ShrgFileWriter writer) {
writer.setIndentationCount(1);
write(writer, "");
}
});
eclipseComponentFileWriter.addInjector(new Injector() {
@Override
public void inject(ShrgFileWriter writer) {
writer.setIndentationCount(2);
write(writer, " ");
write(writer, " ");
}
});
copyTemplate(templateReader(".settings", "", "org.eclipse.wst.common.component"),
eclipseComponentFileWriter);
if (app.withLanguageFile())
dictionary_en_US_writer = createResourceWriter("dictionary_en_US.properties");
applicationConf_writer = createResourceWriter("application.properties");
JSONObject entities = (JSONObject) project.get("entities");
entities.forEach(new BiConsumer() {
@Override
public void accept(String entityName, JSONObject entityObj) {
createWriters(entityName);
}
});
createConfigWriters();
createApplicationConfigurationFile();
String packageRow = "package " + app.targetPackage + ".";
packagesMap.forEach(new BiConsumer>() {
@Override
public void accept(String packageName, Map writers) {
store(writers, packageRow + packageName);
if (packageName.compareTo(configurePackage) != 0)
includeImports(packageName, writers);
}
});
setConfigurationClassesInjectors(entities);
configWriters.forEach(new BiConsumer() {
@Override
public void accept(String fileName, ShrgFileWriter writer) {
copyJavaTemplate(writer, fileName);
}
});
entities.forEach(new BiConsumer() {
@Override
public void accept(String entityName, JSONObject entityObj) {
storeMessage("entity." + entityName + "=" + entityName);
boolean isVerboseLiteral = isAttributeSet(entityObj, "verboseLiteral");
createModelPojo(entityName, entityObj, isVerboseLiteral);
createDaoClass(entityName, entityObj, entities, isVerboseLiteral);
createServiceClass(entityName, entityObj);
if (isVerboseLiteral)
createConverterClass(entityName, entityObj);
else {
storeMessage("entities." + Names.plural(entityName) + "=" + Names.plural(entityName));
createControllerClass(entityName, entityObj);
createJsp(entityName, entityObj);
}
if (isAttributeSet(entityObj, "formPrintable"))
createReportsClass(entityName, entityObj);
}
});
if (app.withLanguageFile()) {
storeMessage("entity.userPrefs=User's preferences");
storeMessage("attr.menuAtTheTop=at the top");
storeMessage("attr.menuOnTheLeft=on the left");
storeMessage("attr.locale=Language and country");
storeMessage("attr.hmenu=Menu position");
}
} catch (Exception e) {
app.long_op_success = false;
} finally {
packagesMap.forEach(new BiConsumer>() {
@Override
public void accept(String packageName, Map fileWriters) {
closeFiles(fileWriters);
}
});
closeFiles(lookUpJspsWriters);
closeFiles(formJspsWriters);
if (app.withLanguageFile())
closeFile(dictionary_en_US_writer);
closeFile(applicationConf_writer);
closeFile(pomFileWriter);
closeFile(eclipseProjectFileWriter);
closeFile(eclipseComponentFileWriter);
}
app.outToConsole("Code generation : " + (app.long_op_success ? "Success" : "FAILURE") + " !");
app.setWaitCursor(false);
}
private void createApplicationConfigurationFile() {
write(applicationConf_writer, "#Hibernate Configuration");
write(applicationConf_writer, "db.driver = " + app.txtjdbcDriverClass.getText());
write(applicationConf_writer, "db.url = " + app.txtDbPath.getText());
write(applicationConf_writer, "db.username = " + app.txtUserName.getText());
write(applicationConf_writer, "db.password = " + app.txtPassword.getText());
write(applicationConf_writer, "");
write(applicationConf_writer, "#Hibernate Configuration");
write(applicationConf_writer, "hibernate.dialect = " + app.txtHibDialect.getText());
write(applicationConf_writer, "hibernate.show_sql = " + app.txtHibShowSql.getText());
write(applicationConf_writer, "hibernate.format_sql = " + app.txtHibFormatSql.getText());
write(applicationConf_writer, "hibernate.id.new_generator_mappings = false");
write(applicationConf_writer, "entitymanager.shr_packages.to.scan = com.sprhibrad.framework.model");
write(applicationConf_writer, "entitymanager.packages.to.scan = " + app.txtTargetPackage.getText() + ".model");
write(applicationConf_writer, "");
write(applicationConf_writer, "#SprHibRad application configuration");
write(applicationConf_writer, "sprHibRad.appName = " + app.txtShrAppName.getText());
write(applicationConf_writer, "sprHibRad.pagesize = " + app.txtShrPageSize.getText());
write(applicationConf_writer, "sprHibRad.userprefsmenu = " + app.txtShrUserprefsMenu.getText());
write(applicationConf_writer, "sprHibRad.dateStyle = " + app.txtShrDateStyle.getText());
write(applicationConf_writer, "sprHibRad.currencyCountry = " + app.txtShrCurrencyCountry.getText());
write(applicationConf_writer, "sprHibRad.langParameterizedReports = " + app.txtShrLangParameterizedReports.getText());
write(applicationConf_writer, "sprHibRad.minPwdSize = " + app.txtShrMinPwdSize.getText());
write(applicationConf_writer, "");
write(applicationConf_writer, "#BIRT");
write(applicationConf_writer, "birt.logDir = " + app.txtBirtLogDir.getText());
write(applicationConf_writer, "");
write(applicationConf_writer, "#Session");
write(applicationConf_writer, "session.maxInactiveMinutes = " + app.txtSessionMaxInactiveMinutes.getText());
}
private void setConfigurationClassesInjectors(JSONObject entities) {
configWriters.get("Initializer").addInjector(new Injector() {
@Override
public void inject(ShrgFileWriter writer) {
writer.setIndentationCount(0);
write(writer, "import " + app.targetPackage + ".configuration.Initializer");
write(writer, "");
}
});
configWriters.get("Initializer").addInjector(new Injector() {
@Override
public void inject(ShrgFileWriter writer) {
writer.setIndentationCount(2);
JSONArray menuEntities = (JSONArray) project.get("menuEntities");
for (Object object : menuEntities)
write(writer, "menuConfig.addItem(\"" + ShrgJSONArray.getKey((JSONObject) object)
+ "\", null)");
}
});
Vector verboseLiterals = new Vector();
Vector printables = new Vector();
entities.forEach(new BiConsumer() {
@Override
public void accept(String entityName, JSONObject entityObj) {
if (isAttributeSet(entityObj, "verboseLiteral"))
verboseLiterals.add(entityName);
if (isAttributeSet(entityObj, "formPrintable"))
printables.add(entityName);
}
});
configWriters.get("WebConf").addInjector(new Injector() {
@Override
public void inject(ShrgFileWriter writer) {
for (String literalCollection : verboseLiterals) {
write(writer, "import " + app.targetPackage
+ ".converter." + toClassName(literalCollection)
+ "Converter");
}
for (String printable : printables) {
write(writer, "import " + app.targetPackage
+ ".reports." + toClassName(printable)
+ "Reports");
}
}
});
configWriters.get("WebConf").addInjector(new Injector() {
@Override
public void inject(ShrgFileWriter writer) {
writer.setIndentationCount(0);
write(writer, "import " + app.targetPackage + ".configuration.BirtEngineFactory");
write(writer, "");
}
});
addOneRowInjector("WebConf", "@ComponentScan(basePackages = \"" + app.targetPackage + ",com.sprhibrad\")", 0);
configWriters.get("WebConf").addInjector(new Injector() {
@Override
public void inject(ShrgFileWriter writer) {
writer.setIndentationCount(1);
for (String literalCollection : verboseLiterals) {
write(writer, "");
write(writer, "@Autowired");
write(writer, toClassName(literalCollection)
+ "Converter " + literalCollection
+ "Converter");
}
}
});
configWriters.get("WebConf").addInjector(new Injector() {
@Override
public void inject(ShrgFileWriter writer) {
for (String printable : printables) {
write(writer, "");
write(writer, "@Bean");
write(writer, toClassName(printable) + "Reports " + printable + "Reports() {");
write(writer, "return new " + toClassName(printable) + "Reports()");
write(writer, "}");
}
}
});
configWriters.get("WebConf").addInjector(new Injector() {
@Override
public void inject(ShrgFileWriter writer) {
writer.setIndentationCount(2);
for (String literalCollection : verboseLiterals) {
write(writer, "registry.addConverter(" + literalCollection + "Converter)");
}
}
});
String usersTable = getAttribute(project, "usersTable");
String userName = getAttribute(project, "userColumn");
String password = getAttribute(project, "passwordColumn");
configWriters.get("WebSecurityConfig").addInjector(new Injector() {
@Override
public void inject(ShrgFileWriter writer) {
writer.setIndentationCount(3);
String rolesTable = getAttribute(project, "rolesTable");
String userRolesTable = getAttribute(project, "userRolesTable");
String roleFk = getAttribute(project, "roleFk");
String userFk = getAttribute(project, "userFk");
String roleName = getAttribute(project, "roleColumn");
write(writer, ".usersByUsernameQuery(\"select " + userName + " username, " +
password + " password, true enabled from " + usersTable +
" where username=?\")", true);
write(writer, ".authoritiesByUsernameQuery(", true);
writer.setIndentationCount(4);
write(writer, "\"SELECT " + usersTable + "." + userName
+ " username, CONCAT('ROLE_', " + rolesTable + "." + roleName + ") role \" +", true);
write(writer, "\"FROM " + usersTable + " \" +", true);
write(writer, "\"LEFT JOIN " + userRolesTable + " ON " + usersTable + ".id = "
+ userRolesTable + "." + userFk + " \" +", true);
write(writer, "\"LEFT JOIN " + rolesTable + " ON " + rolesTable + ".id = " +
userRolesTable + "." + roleFk + " \" +", true);
write(writer, "\"where " + usersTable + "." + userName + " =?\")", true);
}
});
configWriters.get("WebSecurityConfig").addInjector(new Injector() {
@Override
public void inject(ShrgFileWriter writer) {
writer.setIndentationCount(3);
entities.forEach(new BiConsumer() {
@Override
public void accept(String entityName, JSONObject entityObj) {
JSONObject roles = (JSONObject) app.shrgJsonPeeker.peek(entityObj, new String[] {"roles"}).hostingObj;
if (roles != null) {
roles.forEach(new BiConsumer() {
@Override
public void accept(String role, JSONObject roleObj) {
JSONObject roleAccessModes = (JSONObject) app.shrgJsonPeeker.peek(roleObj, new String[] {"roleAccessModes"}).hostingObj;
if (roleAccessModes != null && roleAccessModes.size() > 0)
roleAccessModes.forEach(new BiConsumer() {
@Override
public void accept(String roleAccessMode, JSONObject roleAccessModeObj) {
write(writer, ".antMatchers(\"/" + entityName + "/" + roleAccessMode + "/**\").hasRole(\"" + role + "\")", true);
}
});
else
write(writer, ".antMatchers(\"/" + entityName + "/**\").hasRole(\"" + role + "\")", true);
}
});
}
}
}
);
}
});
configWriters.get("UserManagerImpl").addInjector(new Injector() {
@Override
public void inject(ShrgFileWriter writer) {
write(writer, "import " + app.targetPackage + ".model." + toClassName(usersTable));
}
});
addOneRowInjector("UserManagerImpl", "private IShrService<" + toClassName(usersTable) + "> " + usersTable + "Service", 1);
addOneRowInjector("UserManagerImpl", "return \"" + usersTable + "\"", 2);
addOneRowInjector("UserManagerImpl", "return ((" + toClassName(usersTable) + ") entity)." + accessorName(password, "get") + "()", 2);
addOneRowInjector("UserManagerImpl", "((" + toClassName(usersTable) + ") entity)." + accessorName(password, "set") + "(clearPwd)", 2);
addOneRowInjector("UserManagerImpl", "return ((" + toClassName(usersTable) + ") entity)." + accessorName(userName, "get") + "()", 2);
addOneRowInjector("UserManagerImpl", "return " + usersTable + "Service", 2);
addOneRowInjector("UserManagerImpl", "return \"" + userName + "\"", 2);
}
private void addOneRowInjector(String className, String row, int indentValue) {
configWriters.get(className).addInjector(new Injector() {
@Override
public void inject(ShrgFileWriter writer) {
writer.setIndentationCount(indentValue);
write(writer, row);
}
});
}
protected void createConverterClass(String entityName, JSONObject entityObj) {
ShrgFileWriter writer = converterWriters.get(entityName);
String className = toClassName(entityName);
writeModelAndServiceImports(writer, className);
write(writer, "");
write(writer, "@Component");
write(writer, "public class " + className
+ "Converter extends VerboseLiteralConverter<" + className
+ ">{");
write(writer, "@Autowired");
write(writer, "IShrService<" + className + "> " + entityName + "Service");
write(writer, "@Override");
write(writer, "protected " + className
+ " getObject(Serializable id) {");
write(writer, "return " + entityName
+ "Service.getObject(Integer.parseInt((String) id))");
write(writer, "}");
write(writer, "}");
}
class ReportCriterium {
String fieldArg;
String operatorArg;
}
protected void createReportsClass(String entityName, JSONObject entityObj) {
ShrgFileWriter writer = reportsWriters.get(entityName);
String className = toClassName(entityName);
write(writer, "import " + app.targetPackage + ".model." + className);
ShrgJSONArray criteriaFields = app.shrgJsonPeeker.peek(entityObj, new String[] {"criteriaFields"}).array;
JSONObject criteriaFieldObj;
int count = 1;
Vector criteria = new Vector();
ReportCriterium criterium;
for (Object object : criteriaFields) {
criterium = new ReportCriterium();
criterium.fieldArg = ShrgJSONArray.getKey((JSONObject) object);
criteriaFieldObj = ShrgJSONArray.getValue((JSONObject) object);
criterium.operatorArg = isAttributeSet(criteriaFieldObj, "withOp") ? (criterium.fieldArg + "_op" + (count > 1 ? String.valueOf(count) : "" )) : null;
criteria.add(criterium);
}
write(writer, "");
write(writer, "@Service");
write(writer, "@Transactional");
write(writer, "public class " + className + "Reports extends ShrService<" + className + "> {");
write(writer, "");
write(writer, "@Autowired");
write(writer, "private IShrDao<" + className + "> " + entityName + "DAO");
write(writer, "");
write(writer, "@Override");
write(writer, "protected IShrDao<" + className + "> getDao() {");
write(writer, "return " + entityName + "DAO");
write(writer, "}");
write(writer, "");
write(writer, "public List<" + className + "> list(String criteria[], String criteria_op[], String orders, String orientations) {");
write(writer, "DataSetClauses clauses = new DataSetClauses()");
int index = 0;
for (ReportCriterium reportCriterium : criteria) {
write(writer, "clauses.addCriterionForReport(\"" + reportCriterium.fieldArg + "\", criteria_op[" + index + "], criteria[" + index + "])");
index++;
}
write(writer, "clauses.loadOrderClauses(orders, orientations)");
write(writer, "return super.getObjects(0, clauses, 0)");
write(writer, "}");
write(writer, "}");
}
private void jspHeading(ShrgFileWriter writer) {
write(writer, "<%@ page language=\"java\" contentType=\"text/html; charset=UTF-8\" pageEncoding=\"UTF-8\"%>");
write(writer, "<%@ taglib prefix=\"form\" uri=\"http://www.springframework.org/tags/form\"%>");
write(writer, "<%@ taglib prefix=\"shr\" uri=\"/WEB-INF/SprHibRad.tld\"%>");
write(writer, "");
write(writer, "");
}
protected void createJsp(String entityName, JSONObject entityObj) {
ShrgFileWriter writer = formJspsWriters.get(entityName);
jspHeading(writer);
writer.setIndentationIncrease(1);
write(writer, "");
write(writer, "");
write(writer, "");
writer.setIndentationIncrease(0);
writer.increaseIndent();
writeBody(entityName, entityObj, writer);
writer.setIndentationIncrease(-1);
write(writer, "");
write(writer, "
");
writer.setIndentationIncrease(0);
write(writer, " ");
write(writer, " ");
JSONArray childrenEntities = (JSONArray) entityObj.get("childrenEntities");
ShrgJSONArray detailsEntities = new ShrgJSONArray((JSONArray) entityObj.get("detailsEntities"));
DetailDescriptor detailDescriptor = null;
ShrgJSONArray detailFields = null;
String childEntityName = null;
boolean viewProperty;
boolean noDelete;
boolean noAdd;
JSONObject detailEntityObj;
for (Object childEntity : childrenEntities) {
childEntityName = ShrgJSONArray.getKey((JSONObject) childEntity);
detailDescriptor = app.getDetailEntityFromTheChildOne(
childEntityName,
ShrgJSONArray.getValue((JSONObject) childEntity));
detailEntityObj = (JSONObject) detailsEntities.get(detailDescriptor.entity);
detailFields = app.shrgJsonPeeker.peek(detailEntityObj,
new String[] { "detailFields" }).array;
viewProperty = isAttributeSet(detailEntityObj, "viewProperty");
noDelete = isAttributeSet(detailEntityObj, "noDelete");
noAdd = isAttributeSet(detailEntityObj, "noAdd");
write(writer, " ");
}
writer.setIndentationIncrease(-1);
write(writer, " ");
write(writer, "");
writer = lookUpJspsWriters.get(entityName);
jspHeading(writer);
writer.setIndentationIncrease(1);
write(writer, "");
write(writer, "");
JSONArray criteriaFields = (JSONArray) entityObj.get("criteriaFields");
if (criteriaFields.size() > 0) {
write(writer, "");
writer.setIndentationIncrease(0);
writer.increaseIndent();
String fieldName = null;
boolean withOp;
for (Object criteriaField : criteriaFields) {
fieldName = ShrgJSONArray.getKey((JSONObject) criteriaField);
withOp = isAttributeSet(ShrgJSONArray.getValue((JSONObject) criteriaField), "withOp");
write(writer, "");
writer.increaseIndent();
writeDataObject(writer, memberName(fieldName));
writer.decreaseIndent();
write(writer, " ");
}
writer.decreaseIndent();
write(writer, " ");
}
write(writer, " ");
writeResultManager(writer, entityObj, entityName);
if (isAttributeSet(entityObj, "formPrintable"))
write(writer, " ");
else
write(writer, " ");
writer.setIndentationIncrease(-1);
write(writer, " ");
write(writer, " ");
write(writer, "