提交 a724efdb 编写于 作者: ibiz4j's avatar ibiz4j

xiugai

上级 64dd9fce
......@@ -23,13 +23,6 @@
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-checkstyle-plugin</artifactId>
<configuration>
<configLocation>${project.parent.basedir}${file.separator}google_checkstyle.xml</configLocation>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
......
......@@ -209,14 +209,13 @@ public class Generate extends IbizLabGeneratorCommand {
try {
final ClientOptInput clientOptInput = configurator.toClientOptInput();
// this null check allows us to inject for unit testing.
if (generator == null) {
generator = new DefaultGenerator(false);
generator = new DefaultGenerator();
}
generator.opts(clientOptInput);
generator.opts(configurator.toClientOptInput());
generator.generate();
} catch (GeneratorNotFoundException e) {
System.err.println(e.getMessage());
......
package com.ibizlab.codegen;
import com.ibizlab.codegen.api.TemplateDefinition;
import io.swagger.v3.parser.core.models.AuthorizationValue;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.experimental.Accessors;
import java.util.List;
@Getter
@Setter
@NoArgsConstructor
@Accessors(chain = true)
public class ClientOptInput {
private CodegenConfig config;
private List<TemplateDefinition> userDefinedTemplates;
}
......@@ -20,53 +20,17 @@ package com.ibizlab.codegen;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.github.benmanes.caffeine.cache.Ticker;
import com.google.common.base.CaseFormat;
import com.google.common.collect.ImmutableMap;
import com.ibizlab.codegen.api.TemplateDefinition;
import com.ibizlab.codegen.api.TemplatingEngineAdapter;
import com.ibizlab.codegen.config.GeneratorSettings;
import com.ibizlab.codegen.templating.TemplatingEngineAdapter;
import com.ibizlab.codegen.config.GlobalSettings;
import com.ibizlab.codegen.templating.MustacheEngineAdapter;
import com.ibizlab.codegen.templating.mustache.*;
import com.samskivert.mustache.Mustache;
import com.samskivert.mustache.Mustache.Compiler;
import io.swagger.v3.core.util.Json;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.Operation;
import io.swagger.v3.oas.models.PathItem;
import io.swagger.v3.oas.models.callbacks.Callback;
import io.swagger.v3.oas.models.examples.Example;
import io.swagger.v3.oas.models.headers.Header;
import io.swagger.v3.oas.models.media.*;
import io.swagger.v3.oas.models.parameters.*;
import io.swagger.v3.oas.models.responses.ApiResponse;
import io.swagger.v3.oas.models.responses.ApiResponses;
import io.swagger.v3.oas.models.security.OAuthFlow;
import io.swagger.v3.oas.models.security.OAuthFlows;
import io.swagger.v3.oas.models.security.SecurityScheme;
import io.swagger.v3.oas.models.servers.Server;
import io.swagger.v3.oas.models.servers.ServerVariable;
import io.swagger.v3.parser.util.SchemaTypeUtil;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.experimental.Accessors;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.Pair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.util.*;
import java.util.concurrent.ConcurrentSkipListSet;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static com.ibizlab.codegen.utils.StringAdvUtils.*;
......@@ -90,6 +54,19 @@ public class CodegenConfig {
private TemplatingEngineAdapter templatingEngine;
public boolean isEnableMinimalUpdate()
{
return Boolean.valueOf(additionalProperties.getOrDefault("enableMinimalUpdate",false).toString());
}
public boolean isSkipOverwrite()
{
return Boolean.valueOf(additionalProperties.getOrDefault("skipOverwrite",false).toString());
}
public String getIgnoreFilePathOverride()
{
return additionalProperties.getOrDefault(CodegenConstants.IGNORE_FILE_OVERRIDE,"").toString();
}
@SuppressWarnings("static-method")
public String sanitizeName(String name) {
......
......@@ -4,7 +4,7 @@ import java.io.File;
import java.util.List;
public interface Generator {
Generator opts(ClientOptInput opts);
Generator opts(CodegenConfig opts);
List<File> generate();
}
\ No newline at end of file
package com.ibizlab.codegen.api;
import java.util.Locale;
public abstract class AbstractTemplatingEngineAdapter implements TemplatingEngineAdapter {
/**
* Gets all possible template paths for a given location.
*
* @param location The full location of the template.
*
* @return A new array of locations, modified according to the extensions or other adapter rules.
*/
protected String[] getModifiedFileLocation(String location) {
String[] extensions = getFileExtensions();
String[] result = new String[extensions.length];
for (int i = 0; i < extensions.length; i++) {
String extension = extensions[i];
result[i] = String.format(Locale.ROOT, "%s.%s", getPathWithoutExtension(location), extension);
}
return result;
}
/**
* Returns the path without an extension for an input location.
*
* @param location The location of the file, with original file extension intact.
*
* @return The full path, without extension (e.g. /path/to/file.txt => /path/to/file)
*/
private String getPathWithoutExtension(String location) {
if (location == null) return null;
int idx = location.lastIndexOf('.');
if (idx == -1) return location;
return location.substring(0, idx);
}
}
......@@ -21,14 +21,12 @@ import com.fasterxml.jackson.databind.Module;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.guava.GuavaModule;
import com.ibizlab.codegen.*;
import com.ibizlab.codegen.api.TemplateDefinition;
import com.ibizlab.codegen.api.TemplatingEngineAdapter;
import com.ibizlab.codegen.templating.TemplatingEngineAdapter;
import com.ibizlab.codegen.templating.TemplatingEngineLoader;
import io.swagger.v3.core.util.Json;
import io.swagger.v3.core.util.Yaml;
import io.swagger.v3.oas.models.OpenAPI;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.Validate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
......@@ -36,7 +34,6 @@ import java.io.File;
import java.io.IOException;
import java.util.*;
import static org.apache.commons.lang3.StringUtils.isEmpty;
import static org.apache.commons.lang3.StringUtils.isNotEmpty;
/**
......@@ -56,8 +53,7 @@ public final class CodegenConfigurator {
private String templateDir;
private String auth;
private String generatorName;
private String templatingEngineName;
private String templatingEngineName="mustache";
private Map<String, String> globalProperties = new HashMap<>();
private Map<String, Object> additionalProperties = new HashMap<>();
......@@ -65,7 +61,6 @@ public final class CodegenConfigurator {
private GeneratorSettings generatorSettings=new GeneratorSettings();
private List<TemplateDefinition> userDefinedTemplates = new ArrayList<>();
public CodegenConfigurator() {
......@@ -81,7 +76,6 @@ public final class CodegenConfigurator {
GeneratorSettings generatorSettings = settings.getGeneratorSettings();
List<TemplateDefinition> userDefinedTemplateSettings = settings.getFiles();
if(generatorSettings.getAdditionalProperties() != null) {
......@@ -89,9 +83,6 @@ public final class CodegenConfigurator {
}
if (userDefinedTemplateSettings != null) {
configurator.userDefinedTemplates.addAll(userDefinedTemplateSettings);
}
return configurator;
}
......@@ -142,6 +133,12 @@ public final class CodegenConfigurator {
}
public CodegenConfigurator setGlobalProperties(Map<String, String> globalProperties) {
this.globalProperties = globalProperties;
return this;
}
public CodegenConfigurator setProjectName(String projectName) {
if (StringUtils.isNotEmpty(projectName)) {
......@@ -152,13 +149,14 @@ public final class CodegenConfigurator {
}
public CodegenConfigurator setAuth(String auth) {
// do not cache this in additional properties.
this.auth = auth;
public CodegenConfigurator setPackageName(String packageName) {
if (StringUtils.isNotEmpty(packageName)) {
addAdditionalProperty(CodegenConstants.PACKAGE_NAME, packageName);
}
generatorSettings.setPackageName(packageName);
return this;
}
public CodegenConfigurator setGitRepoId(String gitRepoId) {
if (StringUtils.isNotEmpty(gitRepoId)) {
addAdditionalProperty(CodegenConstants.GIT_REPO_ID, gitRepoId);
......@@ -202,6 +200,11 @@ public final class CodegenConfigurator {
public CodegenConfigurator setAuth(String auth) {
// do not cache this in additional properties.
this.auth = auth;
return this;
}
public CodegenConfigurator setInputSpec(String inputSpec) {
this.inputSpec = inputSpec;
......@@ -214,35 +217,15 @@ public final class CodegenConfigurator {
return this;
}
public CodegenConfigurator setPackageName(String packageName) {
if (StringUtils.isNotEmpty(packageName)) {
addAdditionalProperty(CodegenConstants.PACKAGE_NAME, packageName);
}
generatorSettings.setPackageName(packageName);
return this;
}
public CodegenConfigurator setGlobalProperties(Map<String, String> globalProperties) {
this.globalProperties = globalProperties;
return this;
}
public CodegenConfigurator setTemplateDir(String templateDir) {
this.templateDir = templateDir;
return this;
}
public ClientOptInput toClientOptInput() {
public CodegenConfig toClientOptInput() {
// We load the config via generatorSettings.getGeneratorName() because this is guaranteed to be set
......@@ -267,11 +250,7 @@ public final class CodegenConfigurator {
config.setTemplateDir(this.templateDir);
config.setAuth(this.auth);
ClientOptInput input = new ClientOptInput()
.setConfig(config)
.setUserDefinedTemplates(userDefinedTemplates);
return input;
return config;
}
......
......@@ -18,8 +18,9 @@ package com.ibizlab.codegen.config;
import com.github.mustachejava.DefaultMustacheFactory;
import com.github.mustachejava.Mustache;
import com.github.mustachejava.MustacheFactory;
import com.github.mustachejava.reflect.ReflectionObjectHandler;
import com.ibizlab.codegen.templating.TemplateFileType;
import com.ibizlab.codegen.model.PojoOption;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
......@@ -29,6 +30,8 @@ import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.StringReader;
import java.io.Writer;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
......@@ -49,6 +52,11 @@ public class Context<TSpecDocument> {
}
public static void main(String[] args) throws IOException {
Path path= Paths.get("/122/33/abc.java");
System.out.println(path.getParent().getFileName());
System.out.println(TemplateFileType.entity.toString());
System.out.println(TemplateFileType.entity.value());
HashMap<String, Object> scopes = new HashMap<String, Object>();
scopes.put("name", "Mustache");
GeneratorSettings generatorSettings=new GeneratorSettings().setGitHost("host");
......@@ -63,12 +71,13 @@ public class Context<TSpecDocument> {
map.put("01","a01");
map.put("02","a02");
scopes.put("map1",map);
System.out.println(map.entrySet());
scopes.put("opt",new PojoOption().set("system_name","ab").set("persistent",false));
scopes.put("type",TemplateFileType.entity);
Writer writer = new OutputStreamWriter(System.out);
DefaultMustacheFactory mf = new DefaultMustacheFactory();
mf.setObjectHandler(new MapMethodReflectionHandler());
Mustache mustache = mf.compile(new StringReader("{{name}}, {{map1.entrySet}}{{#map1.entrySet}}{{key}}{{/map1.entrySet}}!"), "example");
Mustache mustache = mf.compile(new StringReader("{{type}},{{type.value}},{{name}},{{opt.system}},{{opt.physicalField}}, {{map1.entrySet}}{{#map1.entrySet}}{{key}}{{/map1.entrySet}}!"), "example");
mustache.execute(writer, scopes);
writer.flush();
}
......
......@@ -2,16 +2,11 @@ package com.ibizlab.codegen.config;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonUnwrapped;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.ibizlab.codegen.api.TemplateDefinition;
import com.ibizlab.codegen.api.TemplateFileType;
import org.apache.commons.lang3.StringUtils;
import java.lang.reflect.Field;
import java.util.*;
import java.util.stream.Collectors;
public class DynamicSettings {
@JsonAnySetter
......@@ -22,31 +17,7 @@ public class DynamicSettings {
private GeneratorSettings generatorSettings;
/**
* Gets the list of template files allowing user redefinition and addition of templating files
*
* @return A list of template files
*/
public List<TemplateDefinition> getFiles() {
if (files == null) return new ArrayList<>();
return files.entrySet().stream().map(kvp -> {
TemplateDefinition file = kvp.getValue();
String templateFile = kvp.getKey();
String destination = file.getDestinationFilename();
if (TemplateFileType.SupportingFiles.equals(file.getTemplateType()) && StringUtils.isBlank(destination)) {
// this special case allows definitions such as LICENSE:{}
destination = templateFile;
}
TemplateDefinition definition = new TemplateDefinition(templateFile, file.getFolder(), destination);
definition.setTemplateType(file.getTemplateType());
return definition;
}).collect(Collectors.toList());
}
@SuppressWarnings("MismatchedQueryAndUpdateOfCollection")
@JsonProperty("files")
private Map<String, TemplateDefinition> files;
public GeneratorSettings getGeneratorSettings() {
......
......@@ -50,7 +50,7 @@ public class CodegenIgnoreProcessor {
* @param baseDirectory The base directory of the files to be processed. This contains the ignore file.
*/
public CodegenIgnoreProcessor(final String baseDirectory) {
this(baseDirectory, ".openapi-generator-ignore");
this(baseDirectory, ".ibizlab-generator-ignore");
}
/**
......@@ -87,20 +87,6 @@ public class CodegenIgnoreProcessor {
} catch (IOException e) {
LOGGER.error(String.format(Locale.ROOT, "Could not process %s.", targetIgnoreFile.getName()), e.getMessage());
}
} else if (!".swagger-codegen-ignore".equals(targetIgnoreFile.getName())) {
final File legacyIgnoreFile = new File(targetIgnoreFile.getParentFile(), ".swagger-codegen-ignore");
if (legacyIgnoreFile.exists() && legacyIgnoreFile.isFile()) {
LOGGER.info(String.format(Locale.ROOT, "Legacy support: '%s' file renamed to '%s'.", legacyIgnoreFile.getName(), targetIgnoreFile.getName()));
try {
Files.move(legacyIgnoreFile.toPath(), targetIgnoreFile.toPath(), REPLACE_EXISTING);
loadFromFile(targetIgnoreFile);
} catch (IOException e) {
LOGGER.error(String.format(Locale.ROOT, "Could not rename file: %s", e.getMessage()));
}
} else {
// log info message
LOGGER.info(String.format(Locale.ROOT, "No %s file found.", targetIgnoreFile.getName()));
}
} else {
// log info message
LOGGER.info(String.format(Locale.ROOT, "No %s file found.", targetIgnoreFile.getName()));
......
......@@ -53,7 +53,7 @@ public class DynamicModelStorage {
private IPSSystem iPSSystem = null;
private IPSSystem getPSSystem()
public IPSSystem getPSSystem()
{
if(iPSSystem==null)
{
......@@ -283,6 +283,7 @@ public class DynamicModelStorage {
for(IPSDERBase der : dataEntity.getMinorPSDERs())
{
RelationshipModel rel=new RelationshipModel();
rel.setNode(der);
rel.setCodeName(der.getCodeName()).setEntityId(der.getMajorPSDataEntity().getId())
.setEntityCodeName(der.getMajorPSDataEntity().getCodeName()).setEntityName(der.getMajorPSDataEntity().getName())
.setEntityLogicName(der.getMajorPSDataEntity().getLogicName()).setSystemId(iPSSystem.getCodeName()).setTableName(der.getMajorPSDataEntity().getTableName());
......@@ -316,6 +317,7 @@ public class DynamicModelStorage {
if(StringUtils.isEmpty(der.getMinorCodeName()))
continue;
RelationshipModel rel=new RelationshipModel();
rel.setNode(der);
rel.setCodeName(der.getMinorCodeName()).setEntityId(der.getMinorPSDataEntity().getId())
.setEntityCodeName(der.getMinorPSDataEntity().getCodeName()).setEntityName(der.getMinorPSDataEntity().getName())
.setEntityLogicName(der.getMinorPSDataEntity().getLogicName()).setSystemId(iPSSystem.getCodeName()).setTableName(der.getMinorPSDataEntity().getTableName());
......
package com.ibizlab.codegen.model;
import com.alibaba.fastjson.annotation.JSONField;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.ibizlab.codegen.CodegenConstants;
import org.springframework.util.StringUtils;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
@JsonInclude(JsonInclude.Include.NON_EMPTY)
@JsonIgnoreProperties(ignoreUnknown = true)
public class CliOption extends DataObj
{
public CliOption set(String key, Object value)
{
this.put(key,value);
return this;
}
public CliOption setAll(Map map)
{
if(map!=null)
this.putAll(map);
else if(this.size()==0)
return null;
return this;
}
public String getProjectName(){
return this.getStringValue("projectName",this.getStringValue("system_id",this.getStringValue("system",this.getStringValue("system_name"))));
}
public CliOption setProjectName(String projectName)
{
return this.set(CodegenConstants.PROJECT_NAME,projectName);
}
public String getPackageName(){
return this.getStringValue("packageName");
}
public CliOption setPackageName(String packageName)
{
return this.set(CodegenConstants.PACKAGE_NAME,packageName);
}
public String getModule(){
return this.getStringValue("module",this.getStringValue("module_id",this.getStringValue("module_name",this.getStringValue("modules"))));
}
public CliOption setModule(String module)
{
this.set("modules",module);
return this.set("module",module);
}
public String getCodeName(){
return this.getStringValue("code_name","");
}
}
package com.ibizlab.codegen.model;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.annotation.JSONField;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.*;
import lombok.experimental.Accessors;
import org.springframework.util.StringUtils;
import java.io.Serializable;
import java.util.LinkedHashMap;
import java.util.Map;
@Getter
@Setter
@NoArgsConstructor
@Accessors(chain = true)
@JsonInclude(JsonInclude.Include.NON_EMPTY)
@JsonIgnoreProperties(ignoreUnknown = true)
public class DOModel implements Serializable {
/**
* 标识
*/
@JSONField(name = "id")
@JsonProperty("id")
@ApiModelProperty("标识")
private String id;
/**
* 名称
*/
@JSONField(name = "name")
@JsonProperty("name")
@ApiModelProperty("名称")
private String name;
/**
* 名称
*/
@JSONField(name = "title")
@JsonProperty("title")
@ApiModelProperty("名称")
private String title;
/**
* 系统
*/
@JSONField(name = "systemId")
@JsonProperty("systemId")
@ApiModelProperty("系统")
private String systemId;
/**
* 包名
*/
@JSONField(name = "packageName")
@JsonProperty("packageName")
@ApiModelProperty("包名")
private String packageName;
/**
* 描述
*/
@JSONField(name = "description")
@JsonProperty("description")
@ApiModelProperty("描述")
private String description;
/**
* 定义
*/
@JSONField(name = "schema")
@JsonProperty("schema")
@ApiModelProperty("定义")
private PojoSchema schema;
/**
* 模型
*/
@JSONField(name = "model")
@JsonProperty("model")
@ApiModelProperty("模型")
private String model;
public void setSchema(PojoSchema schema) {
if(schema!=null)
{
if(StringUtils.isEmpty(schema.getId()))
schema.setId(schema.getSystem()+".domain."+schema.getName());
this.setId(schema.getId());
if(!StringUtils.isEmpty(schema.getName()))
this.setName(schema.getName());
if(!StringUtils.isEmpty(schema.getSystem()))
this.setSystemId(schema.getSystem());
if(!StringUtils.isEmpty(schema.getTitle()))
this.setTitle(schema.getTitle());
if(!StringUtils.isEmpty(schema.getDescription()))
this.setDescription(schema.getDescription());
if(!StringUtils.isEmpty(schema.getPackage()))
this.setPackageName(schema.getPackage());
}
this.schema = schema;
}
@JSONField(serialize = false)
@JsonIgnore
private Map<String,POSchema> poSchemas;
@JSONField(serialize = false)
@JsonIgnore
public POSchema getDefaultPOSchema()
{
return getPOSchema("default");
}
public DOModel addPOSchema(String name, POSchema poSchema)
{
if(poSchema!=null)
{
if(poSchemas==null)
poSchemas=new LinkedHashMap<>();
poSchemas.put(name,poSchema.build());
}
return this;
}
public POSchema getPOSchema(String name)
{
if(StringUtils.isEmpty(name)&&this.getSchema()!=null&&(!StringUtils.isEmpty(this.getSchema().getDefaultDataSoruce())))
name=this.getSchema().getDefaultDataSoruce();
if(StringUtils.isEmpty(name))
name="mysql";
if(poSchemas==null)
poSchemas=new LinkedHashMap<>();
if(poSchemas.containsKey(name))
{
return poSchemas.get(name);
}
String vendorProvider=POSchema.provider.get(name.toLowerCase());
if((!StringUtils.isEmpty(vendorProvider))&&(!name.equalsIgnoreCase(vendorProvider))&&poSchemas.containsKey(vendorProvider))
return poSchemas.get(vendorProvider);
if(this.getSchema()!=null&&("mongodb".equals(name)))
{
POSchema documentPOSchema= TransUtils.PojoSchema2DocumentPO(this.getSchema());
if(documentPOSchema!=null) {
poSchemas.put(name, documentPOSchema);
return documentPOSchema;
}
}
if(this.getSchema()!=null&&("default".equals(name)||this.getSchema().getDefaultDataSoruce().equalsIgnoreCase(name)))
{
POSchema defaultPOSchema= TransUtils.PojoSchema2PO(this.getSchema());
if(defaultPOSchema!=null) {
poSchemas.put("default", defaultPOSchema);
if(!StringUtils.isEmpty(this.getSchema().getDefaultDataSoruce()))
poSchemas.put(this.getSchema().getDefaultDataSoruce().toLowerCase(),defaultPOSchema);
return defaultPOSchema;
}
}
return null;
}
}
......@@ -3,10 +3,15 @@ package com.ibizlab.codegen.model;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.ibizlab.codegen.CodegenConfig;
import com.ibizlab.codegen.CodegenConstants;
import com.ibizlab.codegen.lite.DynamicModelStorage;
import com.ibizlab.codegen.lite.EntityModel;
import com.ibizlab.codegen.templating.TemplateFileType;
import net.ibizsys.model.IPSSystem;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import java.io.File;
import java.io.IOException;
......@@ -21,19 +26,40 @@ public class ModelStorage {
public static String USER_HOME = Paths.get(System.getProperty("user.home"),".ibizlab").toString();
private DynamicModelStorage dynamicService=DynamicModelStorage.getInstance().modelPath(this.getModelPath());
private static ModelStorage instance=null;
private String system=dynamicService.getDstSystemModel().getPssystemid();
public static ModelStorage getInstance()
{
if(instance==null)
instance=new ModelStorage();
return instance;
}
public String getModelPath()
private CodegenConfig config;
public ModelStorage config(CodegenConfig config)
{
return null;
this.config=config;
return this;
}
private DynamicModelStorage dynamicService=DynamicModelStorage.getInstance();
private String system=dynamicService.getDstSystemModel().getPssystemid();
public DOModel loadDOModel(String entity)
public CliOption newCliOption()
{
CliOption opt=new CliOption();
IPSSystem ipsSystem=dynamicService.getPSSystem();
opt.setProjectName(config.getAdditionalProperties().getOrDefault(CodegenConstants.PROJECT_NAME,ipsSystem.getCodeName().toLowerCase()).toString());
opt.setPackageName(config.getAdditionalProperties().getOrDefault(CodegenConstants.PACKAGE_NAME,ipsSystem.getCodeName().toLowerCase()).toString());
return opt;
}
public PojoSchema getEntitySchema(String entity)
{
EntityModel entityModel= null;
try {
......@@ -44,80 +70,66 @@ public class ModelStorage {
Assert.notNull(entityModel,"loadDOModel未找到实体"+"."+entity);
PojoSchema schema = TransUtils.EntityModelModel2Schema(entityModel);
Assert.notNull(schema,"loadDOModel未找到实体"+"."+entity);
DOModel doModel=new DOModel();
doModel.setSchema(schema);
for (String dsType : entityModel.getDsTypes()) {
POSchema poSchema = TransUtils.EntityModelModel2PO(entityModel, dsType);
if (poSchema != null) {
doModel.addPOSchema(dsType, poSchema);
schema.addPOSchema(dsType, poSchema);
}
}
return doModel;
return schema;
}
private Map<TemplateFileType,List<CliOption>> store=new HashMap<>();
public DOModel getDOModel(String entity)
public List<CliOption> getStore(TemplateFileType type)
{
DOModel doModel=null;
PojoSchema schema=null;
Path storePath = Paths.get(ModelStorage.USER_HOME,system,"repo",entity,"domain",entity+".json");
if(!Files.exists(storePath))
if(!store.containsKey(type))
{
try {
String entityTag=dynamicService.getEntitiyIds().get(entity);
Assert.hasLength(entityTag,"获取模型失败"+entity);
if(!entityTag.endsWith("."+entity))
List<CliOption> rt=new ArrayList();
if(type.equals(TemplateFileType.api))
{
if(dynamicService.getPSSystem().getAllPSSysServiceAPIs()!=null)
{
String[] args=entityTag.split("[.]");
entity=args[2];
storePath = Paths.get(ModelStorage.USER_HOME,system,"repo",entity,"domain",entity+".json");
dynamicService.getPSSystem().getAllPSSysServiceAPIs().forEach(item->{
CliOption opt=newCliOption().set(TemplateFileType.api.toString(),item).set(TemplateFileType.api.value(),item.getCodeName().toLowerCase());
rt.add(opt);
});
}
} catch (Exception exception) {
throw new RuntimeException("获取模型失败"+entity,exception);
}
}
File json= storePath.toFile();
if((json.exists()&&json.lastModified()<dynamicService.getDstSystemModel().getLastModify())||(!json.exists()))
{
doModel = loadDOModel(entity);
schema = doModel.getSchema();
if(schema!=null)
else if(type.equals(TemplateFileType.app))
{
if(doModel.getPoSchemas()!=null)
if(dynamicService.getPSSystem().getAllPSApps()!=null)
{
Path poPath = Paths.get(ModelStorage.USER_HOME,system,"repo",doModel.getName(),"repository",doModel.getName()+".json");
try {
File dir=poPath.getParent().toFile();
if(!dir.exists())
dir.mkdirs();
Files.write(poPath, JSON.toJSONBytes(doModel.getPoSchemas()));
} catch (Exception e) {
throw new RuntimeException("保存文件失败POSchemas:"+poPath.toString());
}
dynamicService.getPSSystem().getAllPSApps().forEach(item->{
CliOption opt=newCliOption().set(TemplateFileType.app.toString(),item).set(TemplateFileType.app.value(),item.getCodeName().toLowerCase());
rt.add(opt);
});
}
schema.writeTo(Paths.get(ModelStorage.USER_HOME,system,"repo",doModel.getName(),"domain",doModel.getName()+".json"));
}
}
else {
doModel = new DOModel();
schema = PojoSchema.fromPath(storePath);
if(schema!=null) {
doModel.setSchema(schema);
Path poPath = Paths.get(ModelStorage.USER_HOME, system,"repo", entity, "repository", entity + ".json");
if (Files.exists(poPath)) {
try {
doModel.setPoSchemas(JSON.parseObject(new String(Files.readAllBytes(poPath), StandardCharsets.UTF_8), new TypeReference<LinkedHashMap<String, POSchema>>() {
}));
} catch (IOException e) {
else if(type.equals(TemplateFileType.serviceApi))
{
dynamicService.getPSSystem().getAllPSSysServiceAPIs().forEach(api->{
if(api.getPSDEServiceAPIs()!=null)
{
api.getPSDEServiceAPIs().forEach(item->{
CliOption opt=newCliOption().set(TemplateFileType.serviceApi.toString(),item).set(TemplateFileType.serviceApi.value(),item.getCodeName());
rt.add(opt);
});
}
}
});
}
else if(type.equals(TemplateFileType.entity))
{
dynamicService.getPSSystem().getAllPSDataEntities().forEach(item->{
PojoSchema pojoSchema=this.getEntitySchema(item.getName());
CliOption opt=newCliOption().setModule(pojoSchema.getModule())
.set(TemplateFileType.entity.toString(),pojoSchema).set(TemplateFileType.entity.value(),item.getCodeName());
rt.add(opt);
});
}
store.put(type,rt);
}
Assert.notNull(schema,"未找到对应的模型"+entity);
return doModel;
return store.get(type);
}
......
......@@ -55,6 +55,10 @@ public class POSchema {
return logicDelVal;
}
@JSONField(serialize = false)
@JsonIgnore
private Object node;
@JSONField(ordinal = 7)
private List<Column> columns;
......@@ -407,6 +411,10 @@ public class POSchema {
@JSONField(ordinal = 11)
private Set<String> searchModes;
@JSONField(serialize = false)
@JsonIgnore
private Object node;
public Column setDefaultValue(String defaultValue)
{
if((!StringUtils.isEmpty(defaultValue))&&(!defaultValue.startsWith("$")))
......
......@@ -47,8 +47,8 @@ public class PojoOption extends DataObj
return this.getStringValue("system_name",this.getStringValue("system",this.getStringValue("system_id")));
}
public String getPackage(){
return this.getStringValue("module_name",this.getStringValue("module",this.getStringValue("moduleid")));
public String getModule(){
return this.getStringValue("module",this.getStringValue("module_id",this.getStringValue("module_name")));
}
......@@ -196,7 +196,7 @@ public class PojoOption extends DataObj
}
public Boolean isPhysicalField() {
return this.getBooleanValue("physical_field",this.getBooleanValue("Persistent",true));
return this.getBooleanValue("physical_field",this.getBooleanValue("persistent",true));
}
public PojoOption setPhysicalField(Boolean physicalField) {
......
......@@ -12,6 +12,9 @@ import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.experimental.Accessors;
import net.ibizsys.model.dataentity.IPSDataEntity;
import net.ibizsys.model.dataentity.defield.IPSDEField;
import net.ibizsys.model.dataentity.defield.PSDEFieldImpl;
import org.springframework.util.StringUtils;
import java.io.File;
......@@ -93,12 +96,40 @@ public class PojoSchema {
@JSONField(serialize = false)
@JsonIgnore
public String getPackage()
public String getModule()
{
return this.getOptions().getPackage();
return this.getOptions().getModule();
}
@JSONField(serialize = false)
@JsonIgnore
private Object node;
@JSONField(serialize = false)
@JsonIgnore
public IPSDataEntity getDataEntity()
{
if(node != null)
{
if(node instanceof IPSDataEntity)
return (IPSDataEntity)node;
else if(node instanceof IPSDEField && owner!=null)
return owner.getDataEntity();
}
return null;
}
@JSONField(serialize = false)
@JsonIgnore
public IPSDEField getField()
{
if(node != null)
{
if(node instanceof IPSDEField)
return (IPSDEField)node;
}
return null;
}
@JSONField(ordinal = 3)
private String title;
......@@ -540,4 +571,68 @@ public class PojoSchema {
}
@JSONField(serialize = false)
@JsonIgnore
private Map<String,POSchema> poSchemas;
@JSONField(serialize = false)
@JsonIgnore
public POSchema getDefaultPOSchema()
{
return getPOSchema("default");
}
public PojoSchema addPOSchema(String name, POSchema poSchema)
{
if(poSchema!=null)
{
if(poSchemas==null)
poSchemas=new LinkedHashMap<>();
poSchemas.put(name,poSchema.build());
}
return this;
}
public POSchema getPOSchema(String name)
{
if(StringUtils.isEmpty(name)&&(!StringUtils.isEmpty(this.getDefaultDataSoruce())))
name=this.getDefaultDataSoruce();
if(StringUtils.isEmpty(name))
name="mysql";
if(poSchemas==null)
poSchemas=new LinkedHashMap<>();
if(poSchemas.containsKey(name))
{
return poSchemas.get(name);
}
String vendorProvider=POSchema.provider.get(name.toLowerCase());
if((!StringUtils.isEmpty(vendorProvider))&&(!name.equalsIgnoreCase(vendorProvider))&&poSchemas.containsKey(vendorProvider))
return poSchemas.get(vendorProvider);
if("mongodb".equals(name))
{
POSchema documentPOSchema= TransUtils.PojoSchema2DocumentPO(this);
if(documentPOSchema!=null) {
poSchemas.put(name, documentPOSchema);
return documentPOSchema;
}
}
if(("default".equals(name)||this.getDefaultDataSoruce().equalsIgnoreCase(name)))
{
POSchema defaultPOSchema= TransUtils.PojoSchema2PO(this);
if(defaultPOSchema!=null) {
poSchemas.put("default", defaultPOSchema);
if(!StringUtils.isEmpty(this.getDefaultDataSoruce()))
poSchemas.put(this.getDefaultDataSoruce().toLowerCase(),defaultPOSchema);
return defaultPOSchema;
}
}
return null;
}
}
......@@ -18,6 +18,7 @@ public class TransUtils {
.setOptions(new PojoOption().setDsTypes(String.join(",",entityModel.getDsTypes())).setLogicValid(entityModel.isLogicValid()).setLogicVal(entityModel.getLogicVal()).setLogicDelVal(entityModel.getLogicDelVal()));
pojoSchema.getOptions().setAll(JSONObject.parseObject(JSON.toJSONString(entityModel.getEntity()))).remove("ext_params");
pojoSchema.setNode(entityModel.getNode());
int order=1;
......@@ -44,6 +45,8 @@ public class TransUtils {
sub.getOptions().remove("ext_params");
sub.setNode(fieldModel.getNode());
if("PICKUP".equals(fieldModel.getField().getFieldType())&&fieldModel.isPhysicalField())
{
......@@ -80,6 +83,8 @@ public class TransUtils {
)
.setRef("domain."+rel.getEntityName());
sub.setNode(rel.getNode());
pojoSchema.addProperty(sub.getName(),sub);
order++;
}
......@@ -110,6 +115,7 @@ public class TransUtils {
.set("table_name",nest.getTableName()).set("ds_name",nest.getDataSourceName())
)
);
sub.setNode(nest.getNode());
pojoSchema.addProperty(sub.getName(),sub);
order++;
}
......@@ -328,6 +334,7 @@ public class TransUtils {
POSchema poSchema=new POSchema().setDsType(dataSourceType).setName(entityModel.getTableName(dataSourceType)).setDefaultDataSource(entityModel.getDsName())
.setRemarks(entityModel.getLogicName()).setLogicVal(entityModel.getLogicVal()).setLogicDelVal(entityModel.getLogicDelVal());
poSchema.setNode(entityModel.getNode());
Map<String,FieldModel> keyMap=new LinkedHashMap<>();
Map<String,RelationshipModel> relationshipModelMap = new LinkedHashMap<>();
......@@ -345,6 +352,8 @@ public class TransUtils {
POSchema.Column column=new POSchema.Column().setName(colName).setAlias(sub.getCodeName()).setRemarks(sub.getFieldLogicName()).setPredefined(sub.getPredefined()).setLength(length).setType(sub.getDataType());
column.setNode(fieldModel.getNode());
if(column.isNumber())
column.setPrecision(precision);
......
package com.ibizlab.codegen.templating;
import com.ibizlab.codegen.TemplateManager;
import com.ibizlab.codegen.api.TemplatePathLocator;
import org.apache.commons.lang3.StringUtils;
import java.io.File;
......
package com.ibizlab.codegen.templating;
import com.ibizlab.codegen.CodegenConfig;
import com.ibizlab.codegen.TemplateManager;
import com.ibizlab.codegen.api.TemplatePathLocator;
import org.apache.commons.lang3.StringUtils;
import java.io.File;
import java.nio.file.Paths;
/**
* Locates templates according to {@link CodegenConfig} settings.
......@@ -23,9 +19,7 @@ public class GeneratorTemplateContentLocator implements TemplatePathLocator {
this.codegenConfig = codegenConfig;
}
private String buildLibraryFilePath(String dir, String library, String file) {
return Paths.get(dir, "libraries", library, file).normalize().toString();
}
/**
* Determines whether an embedded file with the specified name exists.
......
......@@ -16,8 +16,6 @@
package com.ibizlab.codegen.templating;
import com.ibizlab.codegen.api.TemplatingEngineAdapter;
import com.ibizlab.codegen.api.TemplatingExecutor;
import com.samskivert.mustache.Mustache;
import com.samskivert.mustache.Template;
import org.slf4j.Logger;
......@@ -43,7 +41,6 @@ public class MustacheEngineAdapter implements TemplatingEngineAdapter {
return "mustache";
}
private final String[] extensions = {"mustache"};
Mustache.Compiler compiler = Mustache.compiler();
/**
......@@ -66,17 +63,14 @@ public class MustacheEngineAdapter implements TemplatingEngineAdapter {
}
@SuppressWarnings("java:S108") // catch-all is expected, and is later thrown
public Reader findTemplate(TemplatingExecutor generator, String name) {
for (String extension : extensions) {
final String templateName = name + "." + extension;
try {
return new StringReader(generator.getFullTemplateContents(templateName));
} catch (Exception exception) {
LOGGER.error("Failed to read full template {}, {}", templateName, exception.getMessage());
}
public Reader findTemplate(TemplatingExecutor generator, String templateName) {
try {
return new StringReader(generator.getFullTemplateContents(templateName));
} catch (Exception exception) {
LOGGER.error("Failed to read full template {}, {}", templateName, exception.getMessage());
}
throw new TemplateNotFoundException(name);
throw new TemplateNotFoundException(templateName);
}
public Mustache.Compiler getCompiler() {
......@@ -87,8 +81,4 @@ public class MustacheEngineAdapter implements TemplatingEngineAdapter {
this.compiler = compiler;
}
@Override
public String[] getFileExtensions() {
return extensions;
}
}
package com.ibizlab.codegen.api;
package com.ibizlab.codegen.templating;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.experimental.Accessors;
import java.util.Objects;
import java.util.StringJoiner;
@Getter
@Setter
......@@ -15,19 +12,16 @@ import java.util.StringJoiner;
@Accessors(chain = true)
public class TemplateDefinition {
private String templateFile;
private String folder;
private String destinationFilename;
protected TemplateFileType templateType;
public TemplateDefinition(String templateFile, String folder, String destinationFilename) {
public TemplateDefinition(String templateFile) {
if (templateFile == null) throw new IllegalArgumentException("templateFile may not be null.");
if (folder == null) throw new IllegalArgumentException("folder may not be null.");
if (destinationFilename == null) throw new IllegalArgumentException("destinationFilename may not be null.");
this.templateFile = templateFile;
this.folder = folder;
this.destinationFilename = destinationFilename;
this.templateType = TemplateFileType.SupportingFiles;
this.templateType = TemplateFileType.supportingFiles;
}
}
package com.ibizlab.codegen.api;
import java.util.StringJoiner;
package com.ibizlab.codegen.templating;
public enum TemplateFileType {
API(Constants.APIS),
Model(Constants.MODELS),
APIDocs(Constants.API_DOCS),
ModelDocs(Constants.MODEL_DOCS),
APITests(Constants.API_TESTS),
ModelTests(Constants.MODEL_TESTS),
SupportingFiles(Constants.SUPPORTING_FILES);
api(Constants.APIS),
app(Constants.APPS),
entity(Constants.ENTITIES),
serviceApi(Constants.SERVICE_APIS),
appEntity(Constants.APP_ENTITIES),
module(Constants.MODULES),
page(Constants.PAGES),
ctrl(Constants.CTRLS),
supportingFiles(Constants.SUPPORTING_FILES);
private final String templateType;
......@@ -23,13 +23,7 @@ public enum TemplateFileType {
*/
public String value() { return this.templateType; }
/** {@inheritDoc} */
@Override
public String toString() {
return new StringJoiner(", ", TemplateFileType.class.getSimpleName() + "[", "]")
.add("templateType='" + templateType + "'")
.toString();
}
/**
* Obtains the {@link TemplateFileType} for an input string.
......@@ -48,11 +42,13 @@ public enum TemplateFileType {
public static class Constants {
public static final String APIS = "apis";
public static final String MODELS = "models";
public static final String APPS = "apps";
public static final String ENTITIES = "entities";
public static final String SERVICE_APIS = "serviceApis";
public static final String APP_ENTITIES = "appEntities";
public static final String MODULES = "modules";
public static final String PAGES = "pages";
public static final String CTRLS = "ctrls";
public static final String SUPPORTING_FILES = "supportingFiles";
public static final String MODEL_TESTS = "modelTests";
public static final String MODEL_DOCS = "modelDocs";
public static final String API_TESTS = "apiTests";
public static final String API_DOCS = "apiDocs";
}
}
package com.ibizlab.codegen;
package com.ibizlab.codegen.templating;
import com.ibizlab.codegen.api.TemplatePathLocator;
import com.ibizlab.codegen.api.TemplateProcessor;
import com.ibizlab.codegen.api.TemplatingEngineAdapter;
import com.ibizlab.codegen.api.TemplatingExecutor;
import com.ibizlab.codegen.templating.TemplateManagerOptions;
import com.ibizlab.codegen.templating.TemplateNotFoundException;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
......@@ -159,22 +152,8 @@ public class TemplateManager implements TemplatingExecutor, TemplateProcessor {
*/
@Override
public File write(Map<String, Object> data, String template, File target) throws IOException {
if (this.engineAdapter.handlesFile(template)) {
// Only pass files with valid endings through template engine
String templateContent = this.engineAdapter.compileTemplate(this, data, template);
return writeToFile(target.getPath(), templateContent);
} else {
// Do a straight copy of the file if not listed as supported by the template engine.
InputStream is;
try {
// look up the file using the same template resolution logic the adapters would use.
String fullTemplatePath = getFullTemplateFile(template);
is = getInputStream(fullTemplatePath);
} catch (TemplateNotFoundException ex) {
is = new FileInputStream(Paths.get(template).toFile());
}
return writeToFile(target.getAbsolutePath(), IOUtils.toByteArray(is));
}
String templateContent = this.engineAdapter.compileTemplate(this, data, template);
return writeToFile(target.getPath(), templateContent);
}
@Override
......
package com.ibizlab.codegen.api;
package com.ibizlab.codegen.templating;
/**
* Provides means for searching for "actual" template location based on relative template file.
......
......@@ -14,14 +14,12 @@
* limitations under the License.
*/
package com.ibizlab.codegen.api;
package com.ibizlab.codegen.templating;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.Locale;
import java.util.Map;
/**
......@@ -36,24 +34,7 @@ public interface TemplatingEngineAdapter {
*/
String getIdentifier();
/**
* During generation, if a supporting file has a file extension that is
* inside that array, then it is considered a templated supporting file
* and we use the templating engine adapter to generate it
*
* @return string array of the valid file extensions for this templating engine
*/
String[] getFileExtensions();
/**
* Determine if the adapter handles compilation of the file
* @param filename The template filename
*
* @return True if the file should be compiled by this adapter, else false.
*/
default boolean handlesFile(String filename) {
return filename != null && filename.length() > 0 && Arrays.stream(getFileExtensions()).anyMatch(i -> filename.endsWith("." + i));
}
/**
* Compiles a template into a string
......@@ -77,38 +58,28 @@ public interface TemplatingEngineAdapter {
*/
@SuppressWarnings({"java:S2093"}) // ignore java:S2093 because we have double-assignment to the closeable
default boolean templateExists(TemplatingExecutor generator, String templateFile) {
return Arrays.stream(getFileExtensions()).anyMatch(ext -> {
int idx = templateFile.lastIndexOf('.');
String baseName;
if (idx > 0 && idx < templateFile.length() - 1) {
baseName = templateFile.substring(0, idx);
} else {
baseName = templateFile;
}
Path path = generator.getFullTemplatePath(templateFile);
Path path = generator.getFullTemplatePath(String.format(Locale.ROOT, "%s.%s", baseName, ext));
InputStream is = null;
try {
String resourcePath = System.getProperty("os.name").startsWith("Windows") ?
path.toString().replace("\\", "/") :
path.toString();
is = this.getClass().getClassLoader().getResourceAsStream(resourcePath);
if (is == null) {
is = new FileInputStream(path.toFile());
}
InputStream is = null;
return is.available() > 0;
} catch (IOException e) {
// ignore
} finally {
try {
String resourcePath = System.getProperty("os.name").startsWith("Windows") ?
path.toString().replace("\\", "/") :
path.toString();
is = this.getClass().getClassLoader().getResourceAsStream(resourcePath);
if (is == null) {
is = new FileInputStream(path.toFile());
}
return is.available() > 0;
if (is != null) is.close();
} catch (IOException e) {
// ignore
} finally {
try {
if (is != null) is.close();
} catch (IOException e) {
// ignore
}
}
return false;
});
}
return false;
}
}
......@@ -14,11 +14,9 @@
* limitations under the License.
*/
package com.ibizlab.codegen;
package com.ibizlab.codegen.templating;
import com.ibizlab.codegen.api.TemplatingEngineAdapter;
import java.util.Locale;
import java.util.ServiceLoader;
......
......@@ -22,7 +22,10 @@ public class DataObject {
if (objValue == null) {
return strDefault;
}
if (objValue instanceof String) {
if (objValue instanceof String && StringUtils.isEmpty(objValue)) {
return strDefault;
}
else if (objValue instanceof String ) {
return (String) objValue;
}
if (objValue instanceof java.sql.Timestamp||objValue instanceof java.sql.Date||objValue instanceof java.util.Date) {
......
Markdown 格式
0% or
您添加了 0 到此讨论。请谨慎行事。
先完成此消息的编辑!
想要评论请 注册