diff --git a/.github/workflows/maven.yml b/.github/workflows/maven.yml index c8aeb3a..fdc4515 100644 --- a/.github/workflows/maven.yml +++ b/.github/workflows/maven.yml @@ -5,9 +5,9 @@ name: Java CI with Maven on: push: - branches: [ master ] + branches: [ main ] pull_request: - branches: [ master ] + branches: [ main ] jobs: build: diff --git a/Dockerfile b/Dockerfile index be5f150..fd091bf 100644 --- a/Dockerfile +++ b/Dockerfile @@ -3,8 +3,13 @@ # image: yanglibing/code-generator # by yanglb.com # -FROM openjdk:8-jre-alpine -LABEL maintainer "yanglb " +# 升级记录 +# v1.0 | 2021年4月27日 | 原始版本 +# v2.0 | 2024年11月30日 | 升级jdk版本及支持Arm64架构 +# v2.1 | 2025年9月17日 | 升级jdk版本 + +FROM eclipse-temurin:24-jre-alpine +LABEL org.opencontainers.image.authors="yanglb " COPY ./target/code-generator-*-jar-with-dependencies.jar /usr/local/lib/cg/bin/cg.jar COPY ./cg /usr/local/bin/cg diff --git a/README.md b/README.md index db48d15..a6cf99b 100644 --- a/README.md +++ b/README.md @@ -76,7 +76,7 @@ Options: 通过 cg command --help 查看指定命令的详细说明。 --- -Code Generator v4.3.0 +Code Generator v4.4.0 By https://yanglb.com ``` @@ -98,6 +98,6 @@ cg msg.json msg.xlsx ## License -Copyright (c) 2015-2023 yanglb.com. All rights reserved. +Copyright (c) 2015-2025 yanglb.com. All rights reserved. Licensed under the [Apache License 2.0](LICENSE) license. diff --git a/pom.xml b/pom.xml index 580b512..0dc5e73 100644 --- a/pom.xml +++ b/pom.xml @@ -6,7 +6,7 @@ org.yanglb code-generator - 4.3.0 + 4.4.0 jar diff --git a/src/main/java/cg.java b/src/main/java/cg.java index 9b69ba9..3d874e5 100644 --- a/src/main/java/cg.java +++ b/src/main/java/cg.java @@ -1,28 +1,29 @@ /** * Copyright 2015-2023 yanglb.com - * + *

* Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + *

+ * http://www.apache.org/licenses/LICENSE-2.0 + *

* Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ + import com.yanglb.codegen.shell.CGShell; public class cg { - public static void main(String[] args) { - CGShell shell = new CGShell(); - boolean r = shell.invoke(args); - if (!r) { - System.exit(1); - } - } + public static void main(String[] args) { + CGShell shell = new CGShell(); + boolean r = shell.invoke(args); + if (!r) { + System.exit(1); + } + } } diff --git a/src/main/java/com/yanglb/codegen/converter/BeanMapConverter.java b/src/main/java/com/yanglb/codegen/converter/BeanMapConverter.java index 28260d0..e018b53 100644 --- a/src/main/java/com/yanglb/codegen/converter/BeanMapConverter.java +++ b/src/main/java/com/yanglb/codegen/converter/BeanMapConverter.java @@ -1,12 +1,12 @@ /** * Copyright 2015-2023 yanglb.com - * + *

* Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + *

+ * http://www.apache.org/licenses/LICENSE-2.0 + *

* Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -19,84 +19,84 @@ import com.yanglb.codegen.utils.ObjectUtil; import com.yanglb.codegen.utils.Resources; import com.yanglb.codegen.utils.StringUtil; + import java.lang.reflect.Field; import java.util.Map; public class BeanMapConverter { - - /** - * 将Map转换为 cls类的对象 - * @param cls 将要转换为的类 - * @param map 保存数据的Map - * @return 转换结果 - * @throws CodeGenException - */ - public T convert(Class cls, Map map) throws CodeGenException { - T result = null; - try { - result = cls.newInstance(); - for(String key:map.keySet()) { - Field field = ObjectUtil.getDeepField(result.getClass(), key); - field.setAccessible(true); - - String mapValue = map.get(key); - Object value = null; - - // 类型转换 - Class type = field.getType(); - if(boolean.class.equals(type)) { - value = false; - if(!StringUtil.isNullOrEmpty(mapValue)) { - value = this.toBoolean(mapValue); - } - } else if (Boolean.class.equals(type)) { - value = null; - if(!StringUtil.isNullOrEmpty(mapValue)) { - value = this.toBoolean(mapValue); - } - } else if (int.class.equals(type)) { - // 直接转换,出错时向外抛异常 - try{ - value = Integer.parseInt(mapValue); - }catch(NumberFormatException e) { - throw new CodeGenException(String.format(Resources.getString("E_001"), key, e.getMessage())); - } - } else if ( Integer.class.equals(type)) { - // 可以为Null的整型 - if(StringUtil.isNullOrEmpty(mapValue)) { - value = null; - } else { - try{ - value = Integer.parseInt(mapValue); - }catch(NumberFormatException e) { - throw new CodeGenException(String.format(Resources.getString("E_001"), key, e.getMessage())); - } - } - } else { - value = mapValue; - } - field.set(result, value); - } - } catch (NoSuchFieldException e) { - throw new CodeGenException(String.format(Resources.getString("E_002"), e.getMessage())); - } catch (SecurityException e) { - throw new CodeGenException(e.getMessage()); - } catch (Exception e) { - throw new CodeGenException(e.getMessage()); - } - return result; - } - - private boolean toBoolean(String v) { - boolean value = false; - v = v.toLowerCase(); - if("y".equals(v) - || "√".equals(v) - || "yes".equals(v) - || "true".equals(v)){ - value = true; - } - return value; - } + + /** + * 将Map转换为 cls类的对象 + * @param cls 将要转换为的类 + * @param map 保存数据的Map + * @return 转换结果 + */ + public T convert(Class cls, Map map) throws CodeGenException { + T result = null; + try { + result = cls.newInstance(); + for (String key : map.keySet()) { + Field field = ObjectUtil.getDeepField(result.getClass(), key); + field.setAccessible(true); + + String mapValue = map.get(key); + Object value = null; + + // 类型转换 + Class type = field.getType(); + if (boolean.class.equals(type)) { + value = false; + if (!StringUtil.isNullOrEmpty(mapValue)) { + value = this.toBoolean(mapValue); + } + } else if (Boolean.class.equals(type)) { + value = null; + if (!StringUtil.isNullOrEmpty(mapValue)) { + value = this.toBoolean(mapValue); + } + } else if (int.class.equals(type)) { + // 直接转换,出错时向外抛异常 + try { + value = Integer.parseInt(mapValue); + } catch (NumberFormatException e) { + throw new CodeGenException(String.format(Resources.getString("E_001"), key, e.getMessage())); + } + } else if (Integer.class.equals(type)) { + // 可以为Null的整型 + if (StringUtil.isNullOrEmpty(mapValue)) { + value = null; + } else { + try { + value = Integer.parseInt(mapValue); + } catch (NumberFormatException e) { + throw new CodeGenException(String.format(Resources.getString("E_001"), key, e.getMessage())); + } + } + } else { + value = mapValue; + } + field.set(result, value); + } + } catch (NoSuchFieldException e) { + throw new CodeGenException(String.format(Resources.getString("E_002"), e.getMessage())); + } catch (SecurityException e) { + throw new CodeGenException(e.getMessage()); + } catch (Exception e) { + throw new CodeGenException(e.getMessage()); + } + return result; + } + + private boolean toBoolean(String v) { + boolean value = false; + v = v.toLowerCase(); + if ("y".equals(v) + || "√".equals(v) + || "yes".equals(v) + || "true".equals(v)) { + value = true; + } + return value; + } } diff --git a/src/main/java/com/yanglb/codegen/converter/TableModelConverter.java b/src/main/java/com/yanglb/codegen/converter/TableModelConverter.java index 93f0e30..4ca0b75 100644 --- a/src/main/java/com/yanglb/codegen/converter/TableModelConverter.java +++ b/src/main/java/com/yanglb/codegen/converter/TableModelConverter.java @@ -1,12 +1,12 @@ /** * Copyright 2015-2023 yanglb.com - * + *

* Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + *

+ * http://www.apache.org/licenses/LICENSE-2.0 + *

* Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,6 +17,7 @@ import com.yanglb.codegen.exceptions.CodeGenException; import com.yanglb.codegen.model.TableModel; + import java.util.ArrayList; import java.util.List; import java.util.Map; @@ -24,24 +25,24 @@ public class TableModelConverter { - /** - * 将TableModel对象转换为指定的model对象 - * @param cls Model类 - * @param model 数据模型 - * @return cls Bean的列表 - * @throws CodeGenException 转换出错时抛出异常 - */ - public List convert(Class cls, TableModel model) throws CodeGenException { - List result = new ArrayList(); - List

    > modelList = model.toList(); - - BeanMapConverter converter = new BeanMapConverter(); - for(Map itm : modelList) { - T res = converter.convert(cls, itm); - - // 添加到结果集中 - result.add(res); - } - return result; - } + /** + * 将TableModel对象转换为指定的model对象 + * @param cls Model类 + * @param model 数据模型 + * @return cls Bean的列表 + * @throws CodeGenException 转换出错时抛出异常 + */ + public List convert(Class cls, TableModel model) throws CodeGenException { + List result = new ArrayList(); + List
      > modelList = model.toList(); + + BeanMapConverter converter = new BeanMapConverter(); + for (Map itm : modelList) { + T res = converter.convert(cls, itm); + + // 添加到结果集中 + result.add(res); + } + return result; + } } diff --git a/src/main/java/com/yanglb/codegen/core/GenFactory.java b/src/main/java/com/yanglb/codegen/core/GenFactory.java index 472e47d..458b30a 100644 --- a/src/main/java/com/yanglb/codegen/core/GenFactory.java +++ b/src/main/java/com/yanglb/codegen/core/GenFactory.java @@ -1,12 +1,12 @@ /** * Copyright 2015-2023 yanglb.com - * + *

      * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + *

      + * http://www.apache.org/licenses/LICENSE-2.0 + *

      * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -20,31 +20,31 @@ import com.yanglb.codegen.utils.Resources; public class GenFactory { - private GenFactory() { - } + private GenFactory() { + } - /** - * 根据配置文件中配置的名字创建 - * @param 创建接口类型 - * @return T的接口实例 - * @throws CodeGenException 错误信息 - */ - public static T createByName(String className) throws CodeGenException { - T result = null; - try { - GenFactory factory = new GenFactory(); - result = factory.create(className); - } catch (Exception e) { - throw new CodeGenException(String.format(Resources.getString("E_011"), className, e.getMessage())); - } - return result; - } + /** + * 根据配置文件中配置的名字创建 + * @param 创建接口类型 + * @return T的接口实例 + * @throws CodeGenException 错误信息 + */ + public static T createByName(String className) throws CodeGenException { + T result = null; + try { + GenFactory factory = new GenFactory(); + result = factory.create(className); + } catch (Exception e) { + throw new CodeGenException(String.format(Resources.getString("E_011"), className, e.getMessage())); + } + return result; + } - private T create(String implName) - throws InstantiationException, IllegalAccessException, ClassNotFoundException { - if (implName.startsWith(".")) implName = "com.yanglb.codegen" + implName; + private T create(String implName) + throws InstantiationException, IllegalAccessException, ClassNotFoundException { + if (implName.startsWith(".")) implName = "com.yanglb.codegen" + implName; - Object instance = Class.forName(implName).newInstance(); - return ObjectUtil.cast(instance); - } + Object instance = Class.forName(implName).newInstance(); + return ObjectUtil.cast(instance); + } } diff --git a/src/main/java/com/yanglb/codegen/core/generator/BaseGenerator.java b/src/main/java/com/yanglb/codegen/core/generator/BaseGenerator.java index 2480177..b8756e7 100644 --- a/src/main/java/com/yanglb/codegen/core/generator/BaseGenerator.java +++ b/src/main/java/com/yanglb/codegen/core/generator/BaseGenerator.java @@ -1,12 +1,12 @@ /** * Copyright 2015-2023 yanglb.com - * + *

      * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + *

      + * http://www.apache.org/licenses/LICENSE-2.0 + *

      * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -18,58 +18,59 @@ import com.yanglb.codegen.exceptions.CodeGenException; import com.yanglb.codegen.exceptions.ParamaCheckException; import com.yanglb.codegen.model.ParameterModel; + import java.util.Date; import java.util.HashMap; + import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.Option; -public class BaseGenerator implements IGenerator{ - protected ParameterModel parameterModel; - protected HashMap settingMap; - - protected void printInfo() { - System.out.println("生成信息:"); - System.out.printf("%8s: %s\n", "cmd", parameterModel.getCmd()); - System.out.printf("%8s: %s\n", "file", parameterModel.getFile()); - System.out.printf("%8s: \n", "options"); - CommandLine cl = parameterModel.getOptions(); - for(Option opt : cl.getOptions()) { - String s = opt.getLongOpt(); - if (s == null) s = opt.getOpt(); - if (opt.hasArgs()) { - System.out.printf("%8s-%s=%s\n", "", s, opt.getValuesList()); - } else if (opt.hasArg()) { - System.out.printf("%8s-%s=%s\n", "", s, opt.getValue()); - } else { - System.out.printf("%8s-%s\n", "", s); - } - } - System.out.println(); - } +public class BaseGenerator implements IGenerator { + protected ParameterModel parameterModel; + protected HashMap settingMap; + + protected void printInfo() { + System.out.println("生成信息:"); + System.out.printf("%8s: %s\n", "cmd", parameterModel.getCmd()); + System.out.printf("%8s: %s\n", "file", parameterModel.getFile()); + System.out.printf("%8s: \n", "options"); + CommandLine cl = parameterModel.getOptions(); + for (Option opt : cl.getOptions()) { + String s = opt.getLongOpt(); + if (s == null) s = opt.getOpt(); + if (opt.hasArgs()) { + System.out.printf("%8s-%s=%s\n", "", s, opt.getValuesList()); + } else if (opt.hasArg()) { + System.out.printf("%8s-%s=%s\n", "", s, opt.getValue()); + } else { + System.out.printf("%8s-%s\n", "", s); + } + } + System.out.println(); + } + + /** + * 初始化 + */ + protected void init(ParameterModel parameterModel) { + this.parameterModel = parameterModel; + this.settingMap = new HashMap(); + + this.settingMap.put("generationDate", new Date().toString()); + } - /** - * 初始化 - * @param parameterModel - */ - protected void init(ParameterModel parameterModel) { - this.parameterModel = parameterModel; - this.settingMap = new HashMap(); - - this.settingMap.put("generationDate", new Date().toString()); - } + @Override + public final void invoke(ParameterModel parameterModel) throws CodeGenException, ParamaCheckException { + init(parameterModel); - @Override - public final void invoke(ParameterModel parameterModel) throws CodeGenException, ParamaCheckException { - init(parameterModel); + printInfo(); - printInfo(); - - // 生成代码 - onGeneration(); - } + // 生成代码 + onGeneration(); + } - protected void onGeneration() throws CodeGenException { - // 子类实现 - } + protected void onGeneration() throws CodeGenException { + // 子类实现 + } } diff --git a/src/main/java/com/yanglb/codegen/core/generator/IGenerator.java b/src/main/java/com/yanglb/codegen/core/generator/IGenerator.java index 0ad3655..3c81f89 100644 --- a/src/main/java/com/yanglb/codegen/core/generator/IGenerator.java +++ b/src/main/java/com/yanglb/codegen/core/generator/IGenerator.java @@ -1,12 +1,12 @@ /** * Copyright 2015-2023 yanglb.com - * + *

      * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + *

      + * http://www.apache.org/licenses/LICENSE-2.0 + *

      * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -20,10 +20,10 @@ import com.yanglb.codegen.model.ParameterModel; public interface IGenerator { - /** - * 执行生成工作 - * @param parameterModel 参数模型 - * @throws CodeGenException 出错信息 - */ - void invoke(ParameterModel parameterModel) throws CodeGenException, ParamaCheckException; + /** + * 执行生成工作 + * @param parameterModel 参数模型 + * @throws CodeGenException 出错信息 + */ + void invoke(ParameterModel parameterModel) throws CodeGenException, ParamaCheckException; } diff --git a/src/main/java/com/yanglb/codegen/core/generator/impl/DdlGeneratorImpl.java b/src/main/java/com/yanglb/codegen/core/generator/impl/DdlGeneratorImpl.java index ba39486..9cab4c6 100644 --- a/src/main/java/com/yanglb/codegen/core/generator/impl/DdlGeneratorImpl.java +++ b/src/main/java/com/yanglb/codegen/core/generator/impl/DdlGeneratorImpl.java @@ -1,12 +1,12 @@ /** * Copyright 2015-2023 yanglb.com - * + *

      * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + *

      + * http://www.apache.org/licenses/LICENSE-2.0 + *

      * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -26,33 +26,34 @@ import com.yanglb.codegen.utils.Conf; import com.yanglb.codegen.utils.GenTypes; import com.yanglb.codegen.utils.Resources; + import java.util.List; public class DdlGeneratorImpl extends BaseGenerator { - @Override - protected void onGeneration() throws CodeGenException { - super.onGeneration(); - - // 读取DB信息表 - IReader ddlReader = GenFactory.createByName(parameterModel.getCmdModel().getReader()); - List list = ddlReader.reader(this.parameterModel.getFile(), this.parameterModel.getSheets()); - if(list.size() == 0) { - throw new CodeGenException(Resources.getString("E_003")); - } - - // 转换为可写入的Model(单个文件) - String trans = parameterModel.getCmd(); - ITranslator> translator = GenFactory.createByName(parameterModel.getCmdModel().getTranslator()); - WritableModel writableModel = translator.translate(settingMap, this.parameterModel, list); - - // 默认使用UTF-8编码 - GenTypes.Writer supportWriter = GenTypes.Writer.utf8; - if (writableModel.getEncode() == "ascii") supportWriter = GenTypes.Writer.ascii; - - // 写入到文件中 - IWriter writer = GenFactory.createByName(Conf.getString(Conf.CATEGORY_WRITER, supportWriter.name())); - writer.writer(writableModel); - } + @Override + protected void onGeneration() throws CodeGenException { + super.onGeneration(); + + // 读取DB信息表 + IReader ddlReader = GenFactory.createByName(parameterModel.getCmdModel().getReader()); + List list = ddlReader.reader(this.parameterModel.getFile(), this.parameterModel.getSheets()); + if (list.isEmpty()) { + throw new CodeGenException(Resources.getString("E_003")); + } + + // 转换为可写入的Model(单个文件) + String trans = parameterModel.getCmd(); + ITranslator> translator = GenFactory.createByName(parameterModel.getCmdModel().getTranslator()); + WritableModel writableModel = translator.translate(settingMap, this.parameterModel, list); + + // 默认使用UTF-8编码 + GenTypes.Writer supportWriter = GenTypes.Writer.utf8; + if ("ascii".equals(writableModel.getEncode())) supportWriter = GenTypes.Writer.ascii; + + // 写入到文件中 + IWriter writer = GenFactory.createByName(Conf.getString(Conf.CATEGORY_WRITER, supportWriter.name())); + writer.writer(writableModel); + } } diff --git a/src/main/java/com/yanglb/codegen/core/generator/impl/DmlGeneratorImpl.java b/src/main/java/com/yanglb/codegen/core/generator/impl/DmlGeneratorImpl.java index 28fa8e4..a75301b 100644 --- a/src/main/java/com/yanglb/codegen/core/generator/impl/DmlGeneratorImpl.java +++ b/src/main/java/com/yanglb/codegen/core/generator/impl/DmlGeneratorImpl.java @@ -1,12 +1,12 @@ /** * Copyright 2015-2023 yanglb.com - * + *

      * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + *

      + * http://www.apache.org/licenses/LICENSE-2.0 + *

      * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -26,32 +26,33 @@ import com.yanglb.codegen.utils.Conf; import com.yanglb.codegen.utils.GenTypes; import com.yanglb.codegen.utils.Resources; + import java.util.List; public class DmlGeneratorImpl extends BaseGenerator { - @Override - protected void onGeneration() throws CodeGenException { - super.onGeneration(); - - // 读取DML信息表 - IReader ddlReader = GenFactory.createByName(parameterModel.getCmdModel().getReader()); - List list = ddlReader.reader(this.parameterModel.getFile(), this.parameterModel.getSheets()); - if(list.size() == 0) { - throw new CodeGenException(Resources.getString("E_003")); - } - - // 转换为可写入的Model(单个文件) - ITranslator> translator = GenFactory.createByName(parameterModel.getCmdModel().getTranslator()); - WritableModel writableModel = translator.translate(settingMap, this.parameterModel, list); - - // 默认使用UTF-8编码 - GenTypes.Writer supportWriter = GenTypes.Writer.utf8; - if (writableModel.getEncode() == "ascii") supportWriter = GenTypes.Writer.ascii; - - // 写入到文件中 - IWriter writer = GenFactory.createByName(Conf.getString(Conf.CATEGORY_WRITER, supportWriter.name())); - writer.writer(writableModel); - } + @Override + protected void onGeneration() throws CodeGenException { + super.onGeneration(); + + // 读取DML信息表 + IReader ddlReader = GenFactory.createByName(parameterModel.getCmdModel().getReader()); + List list = ddlReader.reader(this.parameterModel.getFile(), this.parameterModel.getSheets()); + if (list.isEmpty()) { + throw new CodeGenException(Resources.getString("E_003")); + } + + // 转换为可写入的Model(单个文件) + ITranslator> translator = GenFactory.createByName(parameterModel.getCmdModel().getTranslator()); + WritableModel writableModel = translator.translate(settingMap, this.parameterModel, list); + + // 默认使用UTF-8编码 + GenTypes.Writer supportWriter = GenTypes.Writer.utf8; + if ("ascii".equals(writableModel.getEncode())) supportWriter = GenTypes.Writer.ascii; + + // 写入到文件中 + IWriter writer = GenFactory.createByName(Conf.getString(Conf.CATEGORY_WRITER, supportWriter.name())); + writer.writer(writableModel); + } } diff --git a/src/main/java/com/yanglb/codegen/core/generator/impl/MsgGeneratorImpl.java b/src/main/java/com/yanglb/codegen/core/generator/impl/MsgGeneratorImpl.java index d8a1633..821fe21 100644 --- a/src/main/java/com/yanglb/codegen/core/generator/impl/MsgGeneratorImpl.java +++ b/src/main/java/com/yanglb/codegen/core/generator/impl/MsgGeneratorImpl.java @@ -1,12 +1,12 @@ /** * Copyright 2015-2023 yanglb.com - * + *

      * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + *

      + * http://www.apache.org/licenses/LICENSE-2.0 + *

      * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -27,45 +27,46 @@ import com.yanglb.codegen.utils.Conf; import com.yanglb.codegen.utils.GenTypes; import com.yanglb.codegen.utils.Resources; + import java.util.ArrayList; import java.util.List; public class MsgGeneratorImpl extends BaseGenerator { - @Override - protected void onGeneration() throws CodeGenException { - super.onGeneration(); + @Override + protected void onGeneration() throws CodeGenException { + super.onGeneration(); + + // 读取DB信息表 + ITableReader tableReader = GenFactory.createByName(parameterModel.getCmdModel().getReader()); + tableReader.setStartPoint(3, 2); + List list = tableReader.reader(this.parameterModel.getFile(), this.parameterModel.getSheets()); + if (list.isEmpty()) { + throw new CodeGenException(Resources.getString("E_003")); + } + + // 获取语言(每种语言翻译一次) + List langList = new ArrayList(); + TableModel tableModel = list.get(0); + for (String key : tableModel.getColumns()) { + if (!"id".equals(key)) { + langList.add(key); - // 读取DB信息表 - ITableReader tableReader = GenFactory.createByName(parameterModel.getCmdModel().getReader()); - tableReader.setStartPoint(3, 2); - List
      list = tableReader.reader(this.parameterModel.getFile(), this.parameterModel.getSheets()); - if(list.size() == 0) { - throw new CodeGenException(Resources.getString("E_003")); - } - - // 获取语言(每种语言翻译一次) - List langList = new ArrayList(); - TableModel tableModel = list.get(0); - for(String key : tableModel.getColumns()) { - if(!"id".equals(key)) { - langList.add(key); - - settingMap.put("MsgLang", key); - String trans = parameterModel.getCmd(); + settingMap.put("MsgLang", key); + String trans = parameterModel.getCmd(); - // 转换为可写入的Model(单个文件) - ITranslator> translator = GenFactory.createByName(parameterModel.getCmdModel().getTranslator()); - WritableModel writableModel = translator.translate(settingMap, parameterModel, list); + // 转换为可写入的Model(单个文件) + ITranslator> translator = GenFactory.createByName(parameterModel.getCmdModel().getTranslator()); + WritableModel writableModel = translator.translate(settingMap, parameterModel, list); - // 默认使用UTF-8编码 - GenTypes.Writer supportWriter = GenTypes.Writer.utf8; - if (writableModel.getEncode() == "ascii") supportWriter = GenTypes.Writer.ascii; + // 默认使用UTF-8编码 + GenTypes.Writer supportWriter = GenTypes.Writer.utf8; + if ("ascii".equals(writableModel.getEncode())) supportWriter = GenTypes.Writer.ascii; - // 写入到文件中 - IWriter writer = GenFactory.createByName(Conf.getString(Conf.CATEGORY_WRITER, supportWriter.name())); - writer.writer(writableModel); - } - } - } + // 写入到文件中 + IWriter writer = GenFactory.createByName(Conf.getString(Conf.CATEGORY_WRITER, supportWriter.name())); + writer.writer(writableModel); + } + } + } } diff --git a/src/main/java/com/yanglb/codegen/core/parser/BaseParser.java b/src/main/java/com/yanglb/codegen/core/parser/BaseParser.java index b265df1..43689b6 100644 --- a/src/main/java/com/yanglb/codegen/core/parser/BaseParser.java +++ b/src/main/java/com/yanglb/codegen/core/parser/BaseParser.java @@ -1,12 +1,12 @@ /** * Copyright 2015-2023 yanglb.com - * + *

      * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + *

      + * http://www.apache.org/licenses/LICENSE-2.0 + *

      * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -19,14 +19,17 @@ import com.yanglb.codegen.utils.Conf; import com.yanglb.codegen.utils.Infos; import com.yanglb.codegen.utils.Resources; + import java.io.File; import java.util.Collections; import java.util.List; + import org.apache.commons.cli.*; public class BaseParser implements IParser { protected String[] args; + @Override public void setArgs(String[] args) { this.args = args; @@ -73,6 +76,7 @@ protected boolean headerHelp() { System.out.println("用法:cg command file [options]"); return true; } + protected boolean commandHelp() { System.out.println("Commands: "); @@ -100,9 +104,9 @@ protected boolean examplesHelp() { System.out.println(); System.out.println("帮助: "); - System.out.println(String.format(" %-23s显示数生成据库结构的更多帮助信息", "cg ddl.mysql --help")); - System.out.println(String.format(" %-23s显示生成初始数据的更多帮助信息", "cg dml --help")); - System.out.println(String.format(" %-23s显示生成国际化资源的更多帮助信息", "cg msg.json --help")); + System.out.printf(" %-23s显示数生成据库结构的更多帮助信息%n", "cg ddl.mysql --help"); + System.out.printf(" %-23s显示生成初始数据的更多帮助信息%n", "cg dml --help"); + System.out.printf(" %-23s显示生成国际化资源的更多帮助信息%n", "cg msg.json --help"); System.out.println(); System.out.println("通过 cg command --help 查看指定命令的详细说明。"); return true; @@ -164,7 +168,7 @@ public ParameterModel parsing() { throw new IllegalArgumentException(String.format("未知命令: %s,请使用 --help 命令查看用法。", cmd)); } File f = new File(file); - if(!(f.exists() && f.isFile())) { + if (!(f.exists() && f.isFile())) { throw new IllegalArgumentException(String.format("指定的文件(%s)不存在或者是一个目录。\n", file)); } diff --git a/src/main/java/com/yanglb/codegen/core/parser/IParser.java b/src/main/java/com/yanglb/codegen/core/parser/IParser.java index c21e8b4..50305c0 100644 --- a/src/main/java/com/yanglb/codegen/core/parser/IParser.java +++ b/src/main/java/com/yanglb/codegen/core/parser/IParser.java @@ -1,12 +1,12 @@ /** * Copyright 2015-2023 yanglb.com - * + *

      * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + *

      + * http://www.apache.org/licenses/LICENSE-2.0 + *

      * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. diff --git a/src/main/java/com/yanglb/codegen/core/parser/impl/DdlMySqlParser.java b/src/main/java/com/yanglb/codegen/core/parser/impl/DdlMySqlParser.java index f4617a8..50a0285 100644 --- a/src/main/java/com/yanglb/codegen/core/parser/impl/DdlMySqlParser.java +++ b/src/main/java/com/yanglb/codegen/core/parser/impl/DdlMySqlParser.java @@ -1,12 +1,12 @@ /** * Copyright 2015-2023 yanglb.com - * + *

      * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + *

      + * http://www.apache.org/licenses/LICENSE-2.0 + *

      * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. diff --git a/src/main/java/com/yanglb/codegen/core/parser/impl/DdlParser.java b/src/main/java/com/yanglb/codegen/core/parser/impl/DdlParser.java index bc8f2dc..21e2ac7 100644 --- a/src/main/java/com/yanglb/codegen/core/parser/impl/DdlParser.java +++ b/src/main/java/com/yanglb/codegen/core/parser/impl/DdlParser.java @@ -1,12 +1,12 @@ /** * Copyright 2015-2023 yanglb.com - * + *

      * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + *

      + * http://www.apache.org/licenses/LICENSE-2.0 + *

      * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. diff --git a/src/main/java/com/yanglb/codegen/core/parser/impl/DmlParser.java b/src/main/java/com/yanglb/codegen/core/parser/impl/DmlParser.java index d5aba10..03734e9 100644 --- a/src/main/java/com/yanglb/codegen/core/parser/impl/DmlParser.java +++ b/src/main/java/com/yanglb/codegen/core/parser/impl/DmlParser.java @@ -1,12 +1,12 @@ /** * Copyright 2015-2023 yanglb.com - * + *

      * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + *

      + * http://www.apache.org/licenses/LICENSE-2.0 + *

      * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. diff --git a/src/main/java/com/yanglb/codegen/core/parser/impl/MsgAndroidParser.java b/src/main/java/com/yanglb/codegen/core/parser/impl/MsgAndroidParser.java index d10f3e7..3c05a11 100644 --- a/src/main/java/com/yanglb/codegen/core/parser/impl/MsgAndroidParser.java +++ b/src/main/java/com/yanglb/codegen/core/parser/impl/MsgAndroidParser.java @@ -1,12 +1,12 @@ /** * Copyright 2015-2023 yanglb.com - * + *

      * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + *

      + * http://www.apache.org/licenses/LICENSE-2.0 + *

      * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. diff --git a/src/main/java/com/yanglb/codegen/core/parser/impl/MsgJSONParser.java b/src/main/java/com/yanglb/codegen/core/parser/impl/MsgJSONParser.java index de973fc..efbda5a 100644 --- a/src/main/java/com/yanglb/codegen/core/parser/impl/MsgJSONParser.java +++ b/src/main/java/com/yanglb/codegen/core/parser/impl/MsgJSONParser.java @@ -1,12 +1,12 @@ /** * Copyright 2015-2023 yanglb.com - * + *

      * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + *

      + * http://www.apache.org/licenses/LICENSE-2.0 + *

      * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. diff --git a/src/main/java/com/yanglb/codegen/core/parser/impl/MsgParser.java b/src/main/java/com/yanglb/codegen/core/parser/impl/MsgParser.java index 4ca314d..4a2d51a 100644 --- a/src/main/java/com/yanglb/codegen/core/parser/impl/MsgParser.java +++ b/src/main/java/com/yanglb/codegen/core/parser/impl/MsgParser.java @@ -1,12 +1,12 @@ /** * Copyright 2015-2023 yanglb.com - * + *

      * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + *

      + * http://www.apache.org/licenses/LICENSE-2.0 + *

      * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. diff --git a/src/main/java/com/yanglb/codegen/core/reader/BaseModelReader.java b/src/main/java/com/yanglb/codegen/core/reader/BaseModelReader.java index a5ff82c..26de938 100644 --- a/src/main/java/com/yanglb/codegen/core/reader/BaseModelReader.java +++ b/src/main/java/com/yanglb/codegen/core/reader/BaseModelReader.java @@ -1,12 +1,12 @@ /** * Copyright 2015-2023 yanglb.com - * + *

      * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + *

      + * http://www.apache.org/licenses/LICENSE-2.0 + *

      * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -27,19 +27,19 @@ * @param */ public class BaseModelReader extends BaseReader { - protected BaseModelReader() { - - } - - protected T onReader(XSSFSheet sheet, Class cls) throws CodeGenException { - T model = null; - try { - model = cls.newInstance(); - ((BaseModel)model).setSheetName(sheet.getSheetName()); - ((BaseModel)model).setExcelFileName(this.excelFile); - } catch (Exception e) { - throw new CodeGenException(e.getMessage()); - } - return model; - } + protected BaseModelReader() { + + } + + protected T onReader(XSSFSheet sheet, Class cls) throws CodeGenException { + T model = null; + try { + model = cls.newInstance(); + ((BaseModel) model).setSheetName(sheet.getSheetName()); + ((BaseModel) model).setExcelFileName(this.excelFile); + } catch (Exception e) { + throw new CodeGenException(e.getMessage()); + } + return model; + } } diff --git a/src/main/java/com/yanglb/codegen/core/reader/BaseReader.java b/src/main/java/com/yanglb/codegen/core/reader/BaseReader.java index 1ac9673..228791b 100644 --- a/src/main/java/com/yanglb/codegen/core/reader/BaseReader.java +++ b/src/main/java/com/yanglb/codegen/core/reader/BaseReader.java @@ -1,12 +1,12 @@ /** * Copyright 2015-2023 yanglb.com - * + *

      * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + *

      + * http://www.apache.org/licenses/LICENSE-2.0 + *

      * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -19,6 +19,7 @@ import com.yanglb.codegen.exceptions.UnImplementException; import com.yanglb.codegen.utils.DataFormatType; import com.yanglb.codegen.utils.Resources; + import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; @@ -29,293 +30,273 @@ import java.util.ArrayList; import java.util.Date; import java.util.List; + import org.apache.poi.hssf.usermodel.HSSFFormulaEvaluator; -import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.CellType; import org.apache.poi.xssf.usermodel.XSSFCell; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; - /** * 读取类 + * * @author yanglibing */ -public class BaseReader implements IReader{ - protected String excelFile; - protected String[] sheets; - protected List results; - protected int startRowNo; - protected int startColNo; - - protected BaseReader() { - this.results = new ArrayList(); - this.startRowNo = 0; - this.startColNo = 0; - } - - /** - * 读取Excel中全部可读取Sheet - * @param excelFile - * @return - * @throws CodeGenException - */ - @Override - public List reader(String excelFile) throws CodeGenException { - return this.reader(excelFile, new String[0]); - } - - /** - * 读取Excel中指定的几个Sheet - * @param excelFile - * @param sheets - * @return - * @throws CodeGenException - */ - @Override - public List reader(String excelFile, String[] sheets) throws CodeGenException { - // 保存传入参数 - this.excelFile = excelFile; - this.sheets = sheets; - - // 进行读取 - this.doReader(); - - // 返回结果 - return this.results; - } - - /** - * 读取Excel中指定的一个Sheet - * @param excelFile - * @param sheet - * @return - * @throws CodeGenException - */ - @Override - public T reader(String excelFile, String sheet) throws CodeGenException { - this.reader(excelFile, new String[]{sheet}); - return this.results.size() == 0 ? null : this.results.get(0); - } - - /** - * 子类必须实现 - * @param sheet - * @return - * @throws UnImplementException - * @throws CodeGenException - */ - protected T onReader(XSSFSheet sheet) throws UnImplementException, CodeGenException { - throw new UnImplementException(); - } - - /** - * 进行读取 - * @throws CodeGenException - */ - private void doReader() throws CodeGenException { - // 打开文件 - XSSFWorkbook wb = null; - try { - // jar中读取时不能使用new File方法 - if(this.excelFile.startsWith("jar://")) { - String path = this.excelFile.substring(5); - InputStream is=this.getClass().getResourceAsStream(path); - wb = new XSSFWorkbook(is); - } else { - File file = new File(this.excelFile); - BufferedInputStream in = new BufferedInputStream(new FileInputStream(file)); - wb = new XSSFWorkbook(in); - } - - // 更新公式 - HSSFFormulaEvaluator.evaluateAllFormulaCells(wb); - - // 逐个读取 - if(this.sheets == null || this.sheets.length == 0) { - // 全部读取 - for(int i=0; i getResults() { - return results; - } - - /** - * @param results the results to set - */ - protected void setResults(List results) { - this.results = results; - } - - /** - * @return the startRowNo - */ - protected int getStartRowNo() { - return startRowNo; - } - - /** - * @param startRowNo the startRowNo to set - */ - protected void setStartRowNo(int startRowNo) { - this.startRowNo = startRowNo; - } - - /** - * @return the startColNo - */ - protected int getStartColNo() { - return startColNo; - } - - /** - * @param startColNo the startColNo to set - */ - protected void setStartColNo(int startColNo) { - this.startColNo = startColNo; - } - - /** - * 设置开始位置 - * @param startRowNo 开始行 - * @param startColNo 开始列 - */ - @Override - public void setStartPoint(int startRowNo, int startColNo) { - this.startRowNo = startRowNo; - this.startColNo = startColNo; - } +public class BaseReader implements IReader { + protected String excelFile; + protected String[] sheets; + protected List results; + protected int startRowNo; + protected int startColNo; + + protected BaseReader() { + this.results = new ArrayList(); + this.startRowNo = 0; + this.startColNo = 0; + } + + /** + * 读取Excel中全部可读取Sheet + */ + @Override + public List reader(String excelFile) throws CodeGenException { + return this.reader(excelFile, new String[0]); + } + + /** + * 读取Excel中指定的几个Sheet + */ + @Override + public List reader(String excelFile, String[] sheets) throws CodeGenException { + // 保存传入参数 + this.excelFile = excelFile; + this.sheets = sheets; + + // 进行读取 + this.doReader(); + + // 返回结果 + return this.results; + } + + /** + * 读取Excel中指定的一个Sheet + */ + @Override + public T reader(String excelFile, String sheet) throws CodeGenException { + this.reader(excelFile, new String[]{sheet}); + return this.results.size() == 0 ? null : this.results.get(0); + } + + /** + * 子类必须实现 + */ + protected T onReader(XSSFSheet sheet) throws UnImplementException, CodeGenException { + throw new UnImplementException(); + } + + /** + * 进行读取 + */ + private void doReader() throws CodeGenException { + // 打开文件 + XSSFWorkbook wb = null; + try { + // jar中读取时不能使用new File方法 + if (this.excelFile.startsWith("jar://")) { + String path = this.excelFile.substring(5); + InputStream is = this.getClass().getResourceAsStream(path); + wb = new XSSFWorkbook(is); + } else { + File file = new File(this.excelFile); + BufferedInputStream in = new BufferedInputStream(new FileInputStream(file)); + wb = new XSSFWorkbook(in); + } + + // 更新公式 + HSSFFormulaEvaluator.evaluateAllFormulaCells(wb); + + // 逐个读取 + if (this.sheets == null || this.sheets.length == 0) { + // 全部读取 + for (int i = 0; i < wb.getNumberOfSheets(); i++) { + XSSFSheet sheet = wb.getSheetAt(i); + + // 过虑不可读取的Sheet + if (!this.isReadable(sheet.getSheetName())) { + continue; + } + this.results.add(this.onReader(sheet)); + } + } else { + // 读取指定的Sheet + for (String sheetName : this.sheets) { + XSSFSheet sheet = wb.getSheet(sheetName); + if (sheet != null) { + this.results.add(this.onReader(sheet)); + } + } + } + } catch (FileNotFoundException e) { + // 该异常已经检查过,不可能还在些出现 + throw new CodeGenException(e.getMessage()); + } catch (UnImplementException e) { + this.results.clear(); + e.printStackTrace(); + } catch (IOException e) { + throw new CodeGenException(Resources.getString("E_005")); + } finally { + try { + if (wb != null) wb.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + + /** + * 检查特定的Sheet名是否可读 + */ + private boolean isReadable(String sheetName) { + return !sheetName.equals("说明") && !sheetName.startsWith("#"); + } + + /** + * 取得Cell的字符串数据,当不是字符串时进行转换 + */ + public String getCellStringValue(XSSFCell cell) { + String result = null; + CellType type = cell.getCellType(); + if (type == CellType.FORMULA) type = cell.getCachedFormulaResultType(); + if (type == CellType.BLANK) return null; + if (type == CellType.ERROR) { + return "#VALUE!"; + } + + switch (type) { + case BOOLEAN: + result = String.valueOf(cell.getBooleanCellValue()); + break; + + case STRING: + result = cell.getStringCellValue(); + break; + + case NUMERIC: { + if (cell.getCellStyle().getDataFormat() == DataFormatType.FORMAT_DATE) { + Date date = cell.getDateCellValue(); + String format = "yyyy/MM/dd";//cell.getCellStyle().getDataFormatString(); + if (cell.getCellStyle().getDataFormatString().contains(":")) { + // 包括时间 + format = "yyyy/MM/dd HH:mm:ss"; + } + SimpleDateFormat df = null; + try { + df = new SimpleDateFormat(format); + } catch (IllegalArgumentException e) { + //df = new SimpleDateFormat("yyyy/MM/dd hh:mm:ss"); + } + result = df.format(date); + } else { + // 如果小数点后有 0则删除 + Number number = cell.getNumericCellValue(); + result = number.toString(); + if (result.indexOf('.') != -1) { + result = result.replaceAll("[0]*$", ""); + } + if (result.endsWith(".")) { + result = result.substring(0, result.length() - 1); + } + } + } + break; + } + return result; + } + + /////////////////////////////////////////////// + // 属性 + /////////////////////////////////////////////// + /** + * @return the excelFile + */ + protected String getExcelFile() { + return excelFile; + } + + /** + * @param excelFile the excelFile to set + */ + protected void setExcelFile(String excelFile) { + this.excelFile = excelFile; + } + + /** + * @return the sheets + */ + protected String[] getSheets() { + return sheets; + } + + /** + * @param sheets the sheets to set + */ + protected void setSheets(String[] sheets) { + this.sheets = sheets; + } + + /** + * @return the results + */ + protected List getResults() { + return results; + } + + /** + * @param results the results to set + */ + protected void setResults(List results) { + this.results = results; + } + + /** + * @return the startRowNo + */ + protected int getStartRowNo() { + return startRowNo; + } + + /** + * @param startRowNo the startRowNo to set + */ + protected void setStartRowNo(int startRowNo) { + this.startRowNo = startRowNo; + } + + /** + * @return the startColNo + */ + protected int getStartColNo() { + return startColNo; + } + + /** + * @param startColNo the startColNo to set + */ + protected void setStartColNo(int startColNo) { + this.startColNo = startColNo; + } + + /** + * 设置开始位置 + * + * @param startRowNo 开始行 + * @param startColNo 开始列 + */ + @Override + public void setStartPoint(int startRowNo, int startColNo) { + this.startRowNo = startRowNo; + this.startColNo = startColNo; + } } diff --git a/src/main/java/com/yanglb/codegen/core/reader/IReader.java b/src/main/java/com/yanglb/codegen/core/reader/IReader.java index 54a8b11..637ef69 100644 --- a/src/main/java/com/yanglb/codegen/core/reader/IReader.java +++ b/src/main/java/com/yanglb/codegen/core/reader/IReader.java @@ -1,12 +1,12 @@ /** * Copyright 2015-2023 yanglb.com - * + *

      * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + *

      + * http://www.apache.org/licenses/LICENSE-2.0 + *

      * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -16,40 +16,30 @@ package com.yanglb.codegen.core.reader; import com.yanglb.codegen.exceptions.CodeGenException; -import java.util.List; +import java.util.List; public interface IReader { - /** - * 读取Excel中全部可读取Sheet - * @param excelFile - * @return - * @throws CodeGenException - */ - List reader(String excelFile) throws CodeGenException; - - /** - * 读取Excel中指定的几个Sheet - * @param excelFile - * @param sheets - * @return - * @throws CodeGenException - */ - List reader(String excelFile, String[] sheets) throws CodeGenException; - - /** - * 读取Excel中指定的一个Sheet - * @param excelFile - * @param sheet - * @return - * @throws CodeGenException - */ - T reader(String excelFile, String sheet) throws CodeGenException; + /** + * 读取Excel中全部可读取Sheet + * @param excelFile Excel文件路径 + */ + List reader(String excelFile) throws CodeGenException; + + /** + * 读取Excel中指定的几个Sheet + */ + List reader(String excelFile, String[] sheets) throws CodeGenException; + + /** + * 读取Excel中指定的一个Sheet + */ + T reader(String excelFile, String sheet) throws CodeGenException; - /** - * 设置开始位置 - * @param startRowNo 开始行 - * @param startColNo 开始列 - */ - void setStartPoint(int startRowNo, int startColNo); + /** + * 设置开始位置 + * @param startRowNo 开始行 + * @param startColNo 开始列 + */ + void setStartPoint(int startRowNo, int startColNo); } diff --git a/src/main/java/com/yanglb/codegen/core/reader/ISettingReader.java b/src/main/java/com/yanglb/codegen/core/reader/ISettingReader.java index b02872d..4e00901 100644 --- a/src/main/java/com/yanglb/codegen/core/reader/ISettingReader.java +++ b/src/main/java/com/yanglb/codegen/core/reader/ISettingReader.java @@ -1,12 +1,12 @@ /** * Copyright 2015-2023 yanglb.com - * + *

      * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + *

      + * http://www.apache.org/licenses/LICENSE-2.0 + *

      * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -16,31 +16,23 @@ package com.yanglb.codegen.core.reader; import com.yanglb.codegen.exceptions.CodeGenException; -import java.util.HashMap; +import java.util.HashMap; public interface ISettingReader extends IReader> { - /** - * 读取配置项目 - * @return - * @throws CodeGenException - */ - HashMap settingReader() throws CodeGenException; - - /** - * 读取一个配置项目(会将Infos内容添加到结果集中,且属性添加generator前缀) - * @param settingSheet - * @return - * @throws CodeGenException - */ - HashMap settingReader(String settingSheet) throws CodeGenException; - - /** - * 读取多个配置项目(会将Infos内容添加到结果集中,且属性添加generator前缀) - * @param settingSheets - * @return - * @throws CodeGenException - */ - HashMap settingReader(String[] settingSheets) throws CodeGenException; + /** + * 读取配置项目 + */ + HashMap settingReader() throws CodeGenException; + + /** + * 读取一个配置项目(会将Infos内容添加到结果集中,且属性添加generator前缀) + */ + HashMap settingReader(String settingSheet) throws CodeGenException; + + /** + * 读取多个配置项目(会将Infos内容添加到结果集中,且属性添加generator前缀) + */ + HashMap settingReader(String[] settingSheets) throws CodeGenException; } diff --git a/src/main/java/com/yanglb/codegen/core/reader/ITableReader.java b/src/main/java/com/yanglb/codegen/core/reader/ITableReader.java index cd7377d..b88f9c8 100644 --- a/src/main/java/com/yanglb/codegen/core/reader/ITableReader.java +++ b/src/main/java/com/yanglb/codegen/core/reader/ITableReader.java @@ -1,12 +1,12 @@ /** * Copyright 2015-2023 yanglb.com - * + *

      * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + *

      + * http://www.apache.org/licenses/LICENSE-2.0 + *

      * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -26,11 +26,8 @@ * */ public interface ITableReader extends IReader

      { - /** - * 根据已知的某个Sheet进行读取 - * @param sheet - * @return - * @throws CodeGenException - */ - TableModel reader(XSSFSheet sheet) throws CodeGenException; + /** + * 根据已知的某个Sheet进行读取 + */ + TableModel reader(XSSFSheet sheet) throws CodeGenException; } diff --git a/src/main/java/com/yanglb/codegen/core/reader/impl/DdlReaderImpl.java b/src/main/java/com/yanglb/codegen/core/reader/impl/DdlReaderImpl.java index b791d46..1262970 100644 --- a/src/main/java/com/yanglb/codegen/core/reader/impl/DdlReaderImpl.java +++ b/src/main/java/com/yanglb/codegen/core/reader/impl/DdlReaderImpl.java @@ -1,12 +1,12 @@ /** * Copyright 2015-2023 yanglb.com - * + *

      * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + *

      + * http://www.apache.org/licenses/LICENSE-2.0 + *

      * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -25,56 +25,52 @@ import com.yanglb.codegen.model.TableModel; import com.yanglb.codegen.utils.Conf; import com.yanglb.codegen.utils.GenTypes; + import java.util.List; + import org.apache.poi.xssf.usermodel.XSSFRow; import org.apache.poi.xssf.usermodel.XSSFSheet; +public class DdlReaderImpl extends BaseModelReader { + /** + * 读取DB定义Sheet + */ + @Override + protected DdlModel onReader(XSSFSheet sheet) throws CodeGenException { + DdlModel model = super.onReader(sheet, DdlModel.class); + XSSFRow row = null; + // 读取基本信息 + row = sheet.getRow(1); + model.setNameSpace(this.getCellStringValue(row.getCell(2))); + model.setAuthor(this.getCellStringValue(row.getCell(4))); + model.setVersion(this.getCellStringValue(row.getCell(6))); + model.setDescription(this.getCellStringValue(row.getCell(8))); -public class DdlReaderImpl extends BaseModelReader { - /** - * 读取DB定义Sheet - * @throws CodeGenException - */ - @Override - protected DdlModel onReader(XSSFSheet sheet) throws CodeGenException { - DdlModel model = super.onReader(sheet, DdlModel.class); - XSSFRow row = null; - - // 读取基本信息 - row = sheet.getRow(1); - model.setNameSpace(this.getCellStringValue(row.getCell(2))); - model.setAuthor(this.getCellStringValue(row.getCell(4))); - model.setVersion(this.getCellStringValue(row.getCell(6))); - model.setDescription(this.getCellStringValue(row.getCell(8))); + row = sheet.getRow(2); + model.setName(this.getCellStringValue(row.getCell(2))); + model.setResponsibility(this.getCellStringValue(row.getCell(4))); + model.setRenewDate(this.getCellStringValue(row.getCell(6))); + + // 列详细信息 + model.setDetail(this.readerTable(sheet)); + return model; + } + + /** + * 读取Table + */ + private List readerTable(XSSFSheet sheet) throws CodeGenException { + List result = null; + + // 通过 TableReader读取表格内容 + ITableReader tableReader = GenFactory.createByName(Conf.getString(Conf.CATEGORY_READER, GenTypes.Reader.table.name())); + tableReader.setStartPoint(6, 2); + TableModel tableModel = tableReader.reader(sheet); - row = sheet.getRow(2); - model.setName(this.getCellStringValue(row.getCell(2))); - model.setResponsibility(this.getCellStringValue(row.getCell(4))); - model.setRenewDate(this.getCellStringValue(row.getCell(6))); - - // 列详细信息 - model.setDetail(this.readerTable(sheet)); - return model; - } - - /** - * 读取Table - * @param sheet - * @return - * @throws CodeGenException - */ - private List readerTable(XSSFSheet sheet) throws CodeGenException { - List result = null; - - // 通过 TableReader读取表格内容 - ITableReader tableReader = GenFactory.createByName(Conf.getString(Conf.CATEGORY_READER, GenTypes.Reader.table.name())); - tableReader.setStartPoint(6, 2); - TableModel tableModel = tableReader.reader(sheet); - - // 将TableModel转换为DdlDetail; - TableModelConverter converter = new TableModelConverter(); - result = converter.convert(DdlDetail.class, tableModel); - return result; - } + // 将TableModel转换为DdlDetail; + TableModelConverter converter = new TableModelConverter(); + result = converter.convert(DdlDetail.class, tableModel); + return result; + } } diff --git a/src/main/java/com/yanglb/codegen/core/reader/impl/DmlReaderImpl.java b/src/main/java/com/yanglb/codegen/core/reader/impl/DmlReaderImpl.java index de5e7c4..ebde00d 100644 --- a/src/main/java/com/yanglb/codegen/core/reader/impl/DmlReaderImpl.java +++ b/src/main/java/com/yanglb/codegen/core/reader/impl/DmlReaderImpl.java @@ -1,12 +1,12 @@ /** * Copyright 2015-2023 yanglb.com - * + *

      * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + *

      + * http://www.apache.org/licenses/LICENSE-2.0 + *

      * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -26,44 +26,39 @@ import org.apache.poi.xssf.usermodel.XSSFRow; import org.apache.poi.xssf.usermodel.XSSFSheet; - public class DmlReaderImpl extends BaseModelReader { - /** - * 读取DB定义Sheet - * @throws CodeGenException - */ - @Override - protected DmlModel onReader(XSSFSheet sheet) throws CodeGenException { - DmlModel model = super.onReader(sheet, DmlModel.class); - XSSFRow row = null; - - // 读取基本信息 - row = sheet.getRow(1); - model.setNameSpace(this.getCellStringValue(row.getCell(2))); - model.setAuthor(this.getCellStringValue(row.getCell(4))); - model.setVersion(this.getCellStringValue(row.getCell(6))); - model.setDescription(this.getCellStringValue(row.getCell(8))); - - row = sheet.getRow(2); - model.setName(this.getCellStringValue(row.getCell(2))); - model.setResponsibility(this.getCellStringValue(row.getCell(4))); - model.setRenewDate(this.getCellStringValue(row.getCell(6))); - - // 列详细信息 - model.setDmlData(this.readerTable(sheet)); - return model; - } - - /** - * 读取Table - * @param sheet - * @return - * @throws CodeGenException - */ - private TableModel readerTable(XSSFSheet sheet) throws CodeGenException { - // 通过 TableReader读取表格内容 - ITableReader tableReader = GenFactory.createByName(Conf.getString(Conf.CATEGORY_READER, GenTypes.Reader.table.name())); - tableReader.setStartPoint(7, 2); - return tableReader.reader(sheet); - } + /** + * 读取DB定义Sheet + */ + @Override + protected DmlModel onReader(XSSFSheet sheet) throws CodeGenException { + DmlModel model = super.onReader(sheet, DmlModel.class); + XSSFRow row = null; + + // 读取基本信息 + row = sheet.getRow(1); + model.setNameSpace(this.getCellStringValue(row.getCell(2))); + model.setAuthor(this.getCellStringValue(row.getCell(4))); + model.setVersion(this.getCellStringValue(row.getCell(6))); + model.setDescription(this.getCellStringValue(row.getCell(8))); + + row = sheet.getRow(2); + model.setName(this.getCellStringValue(row.getCell(2))); + model.setResponsibility(this.getCellStringValue(row.getCell(4))); + model.setRenewDate(this.getCellStringValue(row.getCell(6))); + + // 列详细信息 + model.setDmlData(this.readerTable(sheet)); + return model; + } + + /** + * 读取Table + */ + private TableModel readerTable(XSSFSheet sheet) throws CodeGenException { + // 通过 TableReader读取表格内容 + ITableReader tableReader = GenFactory.createByName(Conf.getString(Conf.CATEGORY_READER, GenTypes.Reader.table.name())); + tableReader.setStartPoint(7, 2); + return tableReader.reader(sheet); + } } diff --git a/src/main/java/com/yanglb/codegen/core/reader/impl/HashMapReaderImpl.java b/src/main/java/com/yanglb/codegen/core/reader/impl/HashMapReaderImpl.java index aa279f0..02017ef 100644 --- a/src/main/java/com/yanglb/codegen/core/reader/impl/HashMapReaderImpl.java +++ b/src/main/java/com/yanglb/codegen/core/reader/impl/HashMapReaderImpl.java @@ -1,12 +1,12 @@ /** * Copyright 2015-2023 yanglb.com - * + *

      * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + *

      + * http://www.apache.org/licenses/LICENSE-2.0 + *

      * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,54 +17,50 @@ import com.yanglb.codegen.core.reader.BaseReader; import com.yanglb.codegen.utils.StringUtil; + import java.util.HashMap; import java.util.List; import org.apache.poi.ss.usermodel.CellType; -import org.apache.poi.xssf.usermodel.XSSFCell; import org.apache.poi.xssf.usermodel.XSSFRow; import org.apache.poi.xssf.usermodel.XSSFSheet; - - /** * HashMapReaderImpl 及其子类读取的数据不支持写入 - * @author yanglibing * + * @author yanglibing */ public class HashMapReaderImpl extends BaseReader> { - - /** - * 读取Sheet内容 - */ - @Override - protected HashMap onReader(XSSFSheet sheet) { - HashMap result = new HashMap(); - - for(int row=this.startRowNo; row <= sheet.getLastRowNum(); row++) { - XSSFRow xssfRow = sheet.getRow(row); - String key = this.getCellStringValue(xssfRow.getCell(this.startColNo)); - // key不为空时添加到Map中 - if(xssfRow.getCell(this.startColNo).getCellType() == CellType.BLANK - || StringUtil.isNullOrEmpty(key)) { - continue; - } - String value = this.getCellStringValue(xssfRow.getCell(this.startColNo+1)); - result.put(key, value); - } - return result; - } - - /** - * 合并 - * @param listMap - * @return - */ - public HashMap mergeResult(List> listMap) { - HashMap result = new HashMap(); - for(HashMap itm : listMap) { - result.putAll(itm); - } - return result; - } + + /** + * 读取Sheet内容 + */ + @Override + protected HashMap onReader(XSSFSheet sheet) { + HashMap result = new HashMap(); + + for (int row = this.startRowNo; row <= sheet.getLastRowNum(); row++) { + XSSFRow xssfRow = sheet.getRow(row); + String key = this.getCellStringValue(xssfRow.getCell(this.startColNo)); + // key不为空时添加到Map中 + if (xssfRow.getCell(this.startColNo).getCellType() == CellType.BLANK + || StringUtil.isNullOrEmpty(key)) { + continue; + } + String value = this.getCellStringValue(xssfRow.getCell(this.startColNo + 1)); + result.put(key, value); + } + return result; + } + + /** + * 合并 + */ + public HashMap mergeResult(List> listMap) { + HashMap result = new HashMap(); + for (HashMap itm : listMap) { + result.putAll(itm); + } + return result; + } } diff --git a/src/main/java/com/yanglb/codegen/core/reader/impl/TableReaderImpl.java b/src/main/java/com/yanglb/codegen/core/reader/impl/TableReaderImpl.java index 92dd25e..fed1a7e 100644 --- a/src/main/java/com/yanglb/codegen/core/reader/impl/TableReaderImpl.java +++ b/src/main/java/com/yanglb/codegen/core/reader/impl/TableReaderImpl.java @@ -1,12 +1,12 @@ /** * Copyright 2015-2023 yanglb.com - * + *

      * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + *

      + * http://www.apache.org/licenses/LICENSE-2.0 + *

      * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -20,6 +20,7 @@ import com.yanglb.codegen.exceptions.CodeGenException; import com.yanglb.codegen.model.TableModel; import com.yanglb.codegen.utils.StringUtil; + import java.util.ArrayList; import java.util.HashMap; import java.util.List; @@ -30,40 +31,36 @@ import org.apache.poi.xssf.usermodel.XSSFRow; import org.apache.poi.xssf.usermodel.XSSFSheet; +public class TableReaderImpl extends BaseModelReader

      implements ITableReader { + /** + * 读取DB定义Sheet + */ + @Override + protected TableModel onReader(XSSFSheet sheet) throws CodeGenException { + TableModel model = super.onReader(sheet, TableModel.class); + // 记录列的KEY + String[] keys = null; + List listKey = new ArrayList(); + Map curValue = null; // 当前行的值 -public class TableReaderImpl extends BaseModelReader
      implements ITableReader { - - /** - * 读取DB定义Sheet - * @throws CodeGenException - */ - @Override - protected TableModel onReader(XSSFSheet sheet) throws CodeGenException { - TableModel model = super.onReader(sheet, TableModel.class); - - // 记录列的KEY - String[] keys = null; - List listKey = new ArrayList(); - Map curValue = null; // 当前行的值 - - for(int rowNo=this.startRowNo; rowNo<=sheet.getlastrownum(); rowNo++) { - XSSFRow row = sheet.getRow(rowNo); - // 第一行为KEY - if(rowNo == this.startRowNo) { - keys = new String[row.getLastCellNum()]; - } else { - curValue = new HashMap(); - } - - // 如果当前行 所有列均为空白,则不添加到结果集中。 - boolean allBlank = true; - - // 开始读取 - if(row == null) { - throw new CodeGenException(String.format("error: sheet(%s), row(%d)", - sheet.getSheetName(), rowNo)); - } + for (int rowNo = this.startRowNo; rowNo <= sheet.getLastRowNum(); rowNo++) { + XSSFRow row = sheet.getRow(rowNo); + // 第一行为KEY + if (rowNo == this.startRowNo) { + keys = new String[row.getLastCellNum()]; + } else { + curValue = new HashMap(); + } + + // 如果当前行 所有列均为空白,则不添加到结果集中。 + boolean allBlank = true; + + // 开始读取 + if (row == null) { + throw new CodeGenException(String.format("error: sheet(%s), row(%d)", + sheet.getSheetName(), rowNo)); + } /* int colNo = 0; @@ -73,59 +70,56 @@ protected TableModel onReader(XSSFSheet sheet) throws CodeGenException { /* } */ - - for(int colNo=this.startColNo; colNo= keys.length) continue; - - // 添加值 - String key = keys[colNo]; - if(!StringUtil.isNullOrEmpty(key)) { - curValue.put(keys[colNo], value); - } - } - } - - // 全部是空白列时不添加到结果集中 - if(!allBlank && curValue != null) { - model.insert(curValue); - } - } - - // 设置列 - model.setColumns((String[]) listKey.toArray(new String[0])); - return model; - } - - /** - * 根据已知的某个Sheet进行读取 - * @param sheet - * @return - * @throws CodeGenException - */ - @Override - public TableModel reader(XSSFSheet sheet) throws CodeGenException { - return this.onReader(sheet); - } + for (int colNo = this.startColNo; colNo < row.getLastCellNum(); colNo++) { + XSSFCell cell = row.getCell(colNo); + if (cell == null) { + throw new CodeGenException(String.format("error: sheet(%s), row(%d), col(%d)", + sheet.getSheetName(), rowNo, colNo)); + } + if (cell.getCellType() != CellType.BLANK + && cell.getCellType() != CellType.ERROR) { + allBlank = false; + } + String value = this.getCellStringValue(cell); + + // 第一行为KEY + if (rowNo == this.startRowNo) { + if (StringUtil.isNullOrEmpty(value) + || cell.getCellType() == CellType.BLANK + || "-".equals(value)) { + // 空白/忽略的列无视 + continue; + } + keys[colNo] = value; + listKey.add(value); + } else { + if (colNo>= keys.length) continue; + + // 添加值 + String key = keys[colNo]; + if (!StringUtil.isNullOrEmpty(key)) { + curValue.put(keys[colNo], value); + } + } + } + + // 全部是空白列时不添加到结果集中 + if (!allBlank && curValue != null) { + model.insert(curValue); + } + } + + // 设置列 + model.setColumns((String[]) listKey.toArray(new String[0])); + return model; + } + + /** + * 根据已知的某个Sheet进行读取 + */ + @Override + public TableModel reader(XSSFSheet sheet) throws CodeGenException { + return this.onReader(sheet); + } } diff --git a/src/main/java/com/yanglb/codegen/core/translator/BaseDdlTranslator.java b/src/main/java/com/yanglb/codegen/core/translator/BaseDdlTranslator.java index c4c9889..d32da9a 100644 --- a/src/main/java/com/yanglb/codegen/core/translator/BaseDdlTranslator.java +++ b/src/main/java/com/yanglb/codegen/core/translator/BaseDdlTranslator.java @@ -1,12 +1,12 @@ /** * Copyright 2015-2023 yanglb.com - * + *

      * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + *

      + * http://www.apache.org/licenses/LICENSE-2.0 + *

      * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -21,189 +21,191 @@ import com.yanglb.codegen.model.ForeignDetailModel; import com.yanglb.codegen.model.ForeignModel; import com.yanglb.codegen.utils.StringUtil; + import java.util.ArrayList; import java.util.List; public class BaseDdlTranslator extends BaseSqlTranslator { - // 外键关系列表 - protected final List foreignKeyList = new ArrayList(); - - @Override - protected void onBeforeTranslate() throws CodeGenException { - super.onBeforeTranslate(); - this.writableModel.setExtension("ddl"); - } - - @Override - protected void onTranslate() throws CodeGenException { - super.onTranslate(); - - // 计算需要处理的外键 - for(DdlModel model : this.model) { - for(DdlDetail detail : model.getDetail()) { - // 外键表信息 - ForeignDetailModel foreignDetailModel = this.getForeignByDdlDetail(model, detail); - - // 有外键 - if(foreignDetailModel != null) { - // 检查当前表中有无相同的外键 - ForeignModel foreignModel = this.findUnionForeignKey(model, foreignDetailModel); - List foreignColumns = null; - - // 为null时不是联合主键的外键,新建一个外键模型 - if(foreignModel == null) { - // 外键模型 - foreignModel = new ForeignModel(); - foreignColumns = new ArrayList(); - foreignModel.setDdlModel(model); - foreignModel.setForeignColumns(foreignColumns); - - // 添加列外键列表中 - this.foreignKeyList.add(foreignModel); - } else { - foreignColumns = foreignModel.getForeignColumns(); - } - - // 保存外键关系 - foreignColumns.add(foreignDetailModel); - } - } - } - } - - /** - * 查询联合外键 - * 标准:同表不同列视为联合外键 - * @param tableModel 表模型 - * @param foreignDetailModel 外键信息模型 - * @return 是联合主键的外键时返回外键模型,否则返回null - */ - protected ForeignModel findUnionForeignKey(DdlModel tableModel, ForeignDetailModel foreignDetailModel) { - // 从后往前查找 - for(int i=this.foreignKeyList.size()-1; i>=0; i--) { - ForeignModel foreignModel = this.foreignKeyList.get(i); - // 不同表时直接跳过(所处理的表) - if(!foreignModel.getDdlModel().equals(tableModel)) { - continue; - } - - // 当前表之前已经处理过的外键List - List savedForeignDetail = foreignModel.getForeignColumns(); - if(!savedForeignDetail.get(0).getForeignDdlModel().equals(foreignDetailModel.getForeignDdlModel())) { - // 不同的主键引用表跳过 - continue; - } - - // 是否找到同表不同列的外键 - boolean hasSameKey = false; - for(ForeignDetailModel itm:savedForeignDetail) { - // 同主键表下查找 - if(itm.getForeignDdlDetail().equals(foreignDetailModel.getForeignDdlDetail())) { - // 找到相同的主键引用 - hasSameKey = true; - } - } - - // 没有相同的主键引用表明当前列的外键与找到的是联合主键(合并到一起) - // 否则表示没找到联合主键的外键 - if(!hasSameKey) { - return foreignModel; - } - } - return null; - } - - /** - * 获取外键信息 - * @param model 表模型 - * @param detail 列模型 - * @return 外键模型(没有外键时返回null) - * @throws CodeGenException - */ - protected ForeignDetailModel getForeignByDdlDetail(DdlModel model, DdlDetail detail) - throws CodeGenException { - // 有外键 - if(!StringUtil.isNullOrEmpty(detail.getColForeign())) { - // 外键表信息 - ForeignDetailModel foreignDetailModel = new ForeignDetailModel(); - - boolean result = true; - do{ - // 外键名 - String referenceName = detail.getColForeign(); - String[] foreign = referenceName.split("\\."); - - // 外键表 - DdlModel foreignTableModel = null; - // 外键表 - DdlDetail foreignColumnModel = null; - - if(foreign.length != 2) { - result = false; - break; - } - - // 获取外键表 - foreignTableModel = this.findFullTableModel(foreign[0]); - if(foreignTableModel == null) { - result = false; - break; - } - - // 获取外键表 - for(DdlDetail item:foreignTableModel.getDetail()) { - if(item.getColName().equals(foreign[1])) { - foreignColumnModel = item; - break; - } - } - - // 转为ForeignDetailModel - foreignDetailModel.setDdlDetail(detail); - foreignDetailModel.setForeignDdlModel(foreignTableModel); - foreignDetailModel.setForeignDdlDetail(foreignColumnModel); - } while(false); - - // 失败时直接抛出异常 - if(!result) { - throw new CodeGenException(String.format("invalid foreign key name: [%s] At %s", - detail.getColForeign(), - model.getSheetName())); - } - - return foreignDetailModel; - } - - // 没有外键时返回null - return null; - } - - /** - * 根据前缀查找全表名 - * @param prefix 前缀 - * @return 表名 - */ - protected DdlModel findFullTableModel(String prefix) { - // 创建别名与表名关系 - for(DdlModel itm : this.model) { - if(itm.getName().startsWith(prefix)) { - return itm; - } - } - return null; - } - - /** - * 生成完整的全表名 - * @param model - * @return - */ - protected String genFullTableName(DdlModel model) { - String space = ""; - if(!StringUtil.isNullOrEmpty(model.getNameSpace()) && !"-".equals(model.getNameSpace())) { - space = String.format("%s%s%s.", this.sqlColumnStart, model.getNameSpace(), this.sqlColumnEnd); - } - return String.format("%s%s%s%s", space, this.sqlColumnStart, model.getName(), this.sqlColumnEnd); - } + // 外键关系列表 + protected final List foreignKeyList = new ArrayList(); + + @Override + protected void onBeforeTranslate() throws CodeGenException { + super.onBeforeTranslate(); + this.writableModel.setExtension("ddl"); + } + + @Override + protected void onTranslate() throws CodeGenException { + super.onTranslate(); + + // 计算需要处理的外键 + for (DdlModel model : this.model) { + for (DdlDetail detail : model.getDetail()) { + // 外键表信息 + ForeignDetailModel foreignDetailModel = this.getForeignByDdlDetail(model, detail); + + // 有外键 + if (foreignDetailModel != null) { + // 检查当前表中有无相同的外键 + ForeignModel foreignModel = this.findUnionForeignKey(model, foreignDetailModel); + List foreignColumns = null; + + // 为null时不是联合主键的外键,新建一个外键模型 + if (foreignModel == null) { + // 外键模型 + foreignModel = new ForeignModel(); + foreignColumns = new ArrayList(); + foreignModel.setDdlModel(model); + foreignModel.setForeignColumns(foreignColumns); + + // 添加列外键列表中 + this.foreignKeyList.add(foreignModel); + } else { + foreignColumns = foreignModel.getForeignColumns(); + } + + // 保存外键关系 + foreignColumns.add(foreignDetailModel); + } + } + } + } + + /** + * 查询联合外键 + * 标准:同表不同列视为联合外键 + * + * @param tableModel 表模型 + * @param foreignDetailModel 外键信息模型 + * @return 是联合主键的外键时返回外键模型,否则返回null + */ + protected ForeignModel findUnionForeignKey(DdlModel tableModel, ForeignDetailModel foreignDetailModel) { + // 从后往前查找 + for (int i = this.foreignKeyList.size() - 1; i>= 0; i--) { + ForeignModel foreignModel = this.foreignKeyList.get(i); + // 不同表时直接跳过(所处理的表) + if (!foreignModel.getDdlModel().equals(tableModel)) { + continue; + } + + // 当前表之前已经处理过的外键List + List savedForeignDetail = foreignModel.getForeignColumns(); + if (!savedForeignDetail.get(0).getForeignDdlModel().equals(foreignDetailModel.getForeignDdlModel())) { + // 不同的主键引用表跳过 + continue; + } + + // 是否找到同表不同列的外键 + boolean hasSameKey = false; + for (ForeignDetailModel itm : savedForeignDetail) { + // 同主键表下查找 + if (itm.getForeignDdlDetail().equals(foreignDetailModel.getForeignDdlDetail())) { + // 找到相同的主键引用 + hasSameKey = true; + break; + } + } + + // 没有相同的主键引用表明当前列的外键与找到的是联合主键(合并到一起) + // 否则表示没找到联合主键的外键 + if (!hasSameKey) { + return foreignModel; + } + } + return null; + } + + /** + * 获取外键信息 + * + * @param model 表模型 + * @param detail 列模型 + * @return 外键模型(没有外键时返回null) + */ + protected ForeignDetailModel getForeignByDdlDetail(DdlModel model, DdlDetail detail) + throws CodeGenException { + // 有外键 + if (!StringUtil.isNullOrEmpty(detail.getColForeign())) { + // 外键表信息 + ForeignDetailModel foreignDetailModel = new ForeignDetailModel(); + + boolean result = true; + do { + // 外键名 + String referenceName = detail.getColForeign(); + String[] foreign = referenceName.split("\\."); + + // 外键表 + DdlModel foreignTableModel = null; + // 外键表 + DdlDetail foreignColumnModel = null; + + if (foreign.length != 2) { + result = false; + break; + } + + // 获取外键表 + foreignTableModel = this.findFullTableModel(foreign[0]); + if (foreignTableModel == null) { + result = false; + break; + } + + // 获取外键表 + for (DdlDetail item : foreignTableModel.getDetail()) { + if (item.getColName().equals(foreign[1])) { + foreignColumnModel = item; + break; + } + } + + // 转为ForeignDetailModel + foreignDetailModel.setDdlDetail(detail); + foreignDetailModel.setForeignDdlModel(foreignTableModel); + foreignDetailModel.setForeignDdlDetail(foreignColumnModel); + } while (false); + + // 失败时直接抛出异常 + if (!result) { + throw new CodeGenException(String.format("invalid foreign key name: [%s] At %s", + detail.getColForeign(), + model.getSheetName())); + } + + return foreignDetailModel; + } + + // 没有外键时返回null + return null; + } + + /** + * 根据前缀查找全表名 + * + * @param prefix 前缀 + * @return 表名 + */ + protected DdlModel findFullTableModel(String prefix) { + // 创建别名与表名关系 + for (DdlModel itm : this.model) { + if (itm.getName().startsWith(prefix)) { + return itm; + } + } + return null; + } + + /** + * 生成完整的全表名 + */ + protected String genFullTableName(DdlModel model) { + String space = ""; + if (!StringUtil.isNullOrEmpty(model.getNameSpace()) && !"-".equals(model.getNameSpace())) { + space = String.format("%s%s%s.", this.sqlColumnStart, model.getNameSpace(), this.sqlColumnEnd); + } + return String.format("%s%s%s%s", space, this.sqlColumnStart, model.getName(), this.sqlColumnEnd); + } } diff --git a/src/main/java/com/yanglb/codegen/core/translator/BaseMsgTranslator.java b/src/main/java/com/yanglb/codegen/core/translator/BaseMsgTranslator.java index 393c044..2ceb61d 100644 --- a/src/main/java/com/yanglb/codegen/core/translator/BaseMsgTranslator.java +++ b/src/main/java/com/yanglb/codegen/core/translator/BaseMsgTranslator.java @@ -1,12 +1,12 @@ /** * Copyright 2015-2023 yanglb.com - * + *

      * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + *

      + * http://www.apache.org/licenses/LICENSE-2.0 + *

      * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,42 +17,42 @@ import com.yanglb.codegen.exceptions.CodeGenException; import com.yanglb.codegen.model.TableModel; + import java.util.List; public class BaseMsgTranslator extends BaseTranslator> { - protected String msgLang = ""; - - @Override - protected void onBeforeTranslate() throws CodeGenException { - super.onBeforeTranslate(); - - // 当前生成的国际化语言 - this.msgLang = this.settingMap.get("MsgLang"); - - // 文件名 - String fileName = getFileName(); - if (fileName.equals("")) { - // 空文件名 - fileName = this.msgLang; - } else { - if(!this.isDefaultLanguage()) { - fileName = fileName + this.getSplitString() + this.msgLang; - } - } - - this.writableModel.setFileName(fileName); - } - - protected String getSplitString() { - return "."; - } - - /** - * 获取当前语言是否为默认语言 - * @return - */ - protected boolean isDefaultLanguage() { - return this.msgLang.equals("default"); - } + protected String msgLang = ""; + + @Override + protected void onBeforeTranslate() throws CodeGenException { + super.onBeforeTranslate(); + + // 当前生成的国际化语言 + this.msgLang = this.settingMap.get("MsgLang"); + + // 文件名 + String fileName = getFileName(); + if (fileName.isEmpty()) { + // 空文件名 + fileName = this.msgLang; + } else { + if (!this.isDefaultLanguage()) { + fileName = fileName + this.getSplitString() + this.msgLang; + } + } + + this.writableModel.setFileName(fileName); + } + + protected String getSplitString() { + return "."; + } + + /** + * 获取当前语言是否为默认语言 + */ + protected boolean isDefaultLanguage() { + return this.msgLang.equals("default"); + } } diff --git a/src/main/java/com/yanglb/codegen/core/translator/BaseSqlTranslator.java b/src/main/java/com/yanglb/codegen/core/translator/BaseSqlTranslator.java index 5e8bc20..415e465 100644 --- a/src/main/java/com/yanglb/codegen/core/translator/BaseSqlTranslator.java +++ b/src/main/java/com/yanglb/codegen/core/translator/BaseSqlTranslator.java @@ -1,12 +1,12 @@ /** * Copyright 2015-2023 yanglb.com - * + *

      * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + *

      + * http://www.apache.org/licenses/LICENSE-2.0 + *

      * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -18,7 +18,7 @@ import java.util.List; public class BaseSqlTranslator extends BaseTranslator> { - // 列引号字符,如:SQL Server为[], MySQL为`等 - protected String sqlColumnStart = "\""; - protected String sqlColumnEnd = "\""; + // 列引号字符,如:SQL Server为[], MySQL为`等 + protected String sqlColumnStart = "\""; + protected String sqlColumnEnd = "\""; } diff --git a/src/main/java/com/yanglb/codegen/core/translator/BaseTranslator.java b/src/main/java/com/yanglb/codegen/core/translator/BaseTranslator.java index d3df172..b1bab01 100644 --- a/src/main/java/com/yanglb/codegen/core/translator/BaseTranslator.java +++ b/src/main/java/com/yanglb/codegen/core/translator/BaseTranslator.java @@ -1,12 +1,12 @@ /** * Copyright 2015-2023 yanglb.com - * + *

      * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + *

      + * http://www.apache.org/licenses/LICENSE-2.0 + *

      * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -18,93 +18,94 @@ import com.yanglb.codegen.exceptions.CodeGenException; import com.yanglb.codegen.model.ParameterModel; import com.yanglb.codegen.model.WritableModel; + import java.io.File; import java.util.HashMap; public class BaseTranslator implements ITranslator { - protected T model; - protected final WritableModel writableModel; - protected HashMap settingMap; - protected ParameterModel parameterModel; - - protected BaseTranslator() { - this.writableModel = new WritableModel(); - } + protected T model; + protected final WritableModel writableModel; + protected HashMap settingMap; + protected ParameterModel parameterModel; + + protected BaseTranslator() { + this.writableModel = new WritableModel(); + } + + /** + * 文件名,优先使用--fn参数指定的文件名,如不指定使用excel名称 + * @return 文件名 + */ + protected String getFileName() { + String fileName = this.parameterModel.getFileName(); + if (fileName != null) { + fileName.replaceAll("\"", ""); + } else { + fileName = this.parameterModel.getFile(); + File file = new File(fileName); + fileName = file.getName(); + + int index = fileName.lastIndexOf("."); + if (index != -1) { + fileName = fileName.substring(0, index); + } + } + + return fileName; + } + + /** + * 进行翻译处理 + * @param settingMap 配置信息 + * @param model 等待翻译的Model + * @param parameterModel 参数/选项模型 + * @return WritableModel 一个可写的Model + * @throws CodeGenException 翻译出错时抛出此异常 + */ + @Override + public WritableModel translate(HashMap settingMap, ParameterModel parameterModel, T model) + throws CodeGenException { + this.settingMap = settingMap; + this.model = model; + this.parameterModel = parameterModel; + + this.doTranslate(); + return this.writableModel; + } - /** - * 文件名,优先使用--fn参数指定的文件名,如不指定使用excel名称 - * @return 文件名 - */ - protected String getFileName() { - String fileName = this.parameterModel.getFileName(); - if (fileName != null) { - fileName.replaceAll("\"", ""); - } else { - fileName = this.parameterModel.getFile(); - File file = new File(fileName); - fileName = file.getName(); + /** + * 预翻译器(子类如果重写,则必须显示调用超类的此方法) + * @throws CodeGenException 错误信息 + */ + protected void onBeforeTranslate() throws CodeGenException { + // 设置文件名、等初始化操作 + this.writableModel.setEncode("utf-8"); + this.writableModel.setFileName(getFileName()); + this.writableModel.setData(new StringBuilder()); + this.writableModel.setOutputDir(this.parameterModel.getOptDir()); + } - int index = fileName.lastIndexOf("."); - if(index != -1) { - fileName = fileName.substring(0, index); - } - } + /** + * 进行转换操作 + * @throws CodeGenException 错误信息 + */ + protected void onTranslate() throws CodeGenException { + // 父类没什么可做的了 + } - return fileName; - } + /** + * 编码转换等操作 + * @throws CodeGenException 错误信息 + */ + protected void onAfterTranslate() throws CodeGenException { + // 编码转换在写入器完成 + } - /** - * 进行翻译处理 - * @param settingMap 配置信息 - * @param model 等待翻译的Model - * @param parameterModel 参数/选项模型 - * @return WritableModel 一个可写的Model - * @throws CodeGenException 翻译出错时抛出此异常 - */ - @Override - public WritableModel translate(HashMap settingMap, ParameterModel parameterModel, T model) - throws CodeGenException { - this.settingMap = settingMap; - this.model = model; - this.parameterModel = parameterModel; - - this.doTranslate(); - return this.writableModel; - } - - /** - * 预翻译器(子类如果重写,则必须显示调用超类的此方法) - * @throws CodeGenException 错误信息 - */ - protected void onBeforeTranslate() throws CodeGenException { - // 设置文件名、等初始化操作 - this.writableModel.setEncode("utf-8"); - this.writableModel.setFileName(getFileName()); - this.writableModel.setData(new StringBuilder()); - this.writableModel.setOutputDir(this.parameterModel.getOptDir()); - } - - /** - * 进行转换操作 - * @throws CodeGenException 错误信息 - */ - protected void onTranslate() throws CodeGenException{ - // 父类没什么可做的了 - } - - /** - * 编码转换等操作 - * @throws CodeGenException 错误信息 - */ - protected void onAfterTranslate() throws CodeGenException { - // 编码转换在写入器完成 - } - - // 翻译操作 - private void doTranslate() throws CodeGenException{ - this.onBeforeTranslate(); - this.onTranslate(); - this.onAfterTranslate(); - } + // 翻译操作 + private void doTranslate() throws CodeGenException { + this.onBeforeTranslate(); + this.onTranslate(); + this.onAfterTranslate(); + } } diff --git a/src/main/java/com/yanglb/codegen/core/translator/ITranslator.java b/src/main/java/com/yanglb/codegen/core/translator/ITranslator.java index b6f458c..a4c6c74 100644 --- a/src/main/java/com/yanglb/codegen/core/translator/ITranslator.java +++ b/src/main/java/com/yanglb/codegen/core/translator/ITranslator.java @@ -1,12 +1,12 @@ /** * Copyright 2015-2023 yanglb.com - * + *

      * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + *

      + * http://www.apache.org/licenses/LICENSE-2.0 + *

      * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -18,17 +18,17 @@ import com.yanglb.codegen.exceptions.CodeGenException; import com.yanglb.codegen.model.ParameterModel; import com.yanglb.codegen.model.WritableModel; -import java.util.HashMap; +import java.util.HashMap; public interface ITranslator { - /** - * 进行翻译处理 - * @param settingMap 配置信息 - * @param model 等待翻译的Model - * @param parameterModel 参数/选项模型 - * @return WritableModel 一个可写的Model - * @throws CodeGenException 翻译出错时抛出此异常 - */ + /** + * 进行翻译处理 + * @param settingMap 配置信息 + * @param model 等待翻译的Model + * @param parameterModel 参数/选项模型 + * @return WritableModel 一个可写的Model + * @throws CodeGenException 翻译出错时抛出此异常 + */ WritableModel translate(HashMap settingMap, ParameterModel parameterModel, T model) throws CodeGenException; } diff --git a/src/main/java/com/yanglb/codegen/core/translator/impl/DdlMysqlTranslatorImpl.java b/src/main/java/com/yanglb/codegen/core/translator/impl/DdlMysqlTranslatorImpl.java index 54c194c..5f23dde 100644 --- a/src/main/java/com/yanglb/codegen/core/translator/impl/DdlMysqlTranslatorImpl.java +++ b/src/main/java/com/yanglb/codegen/core/translator/impl/DdlMysqlTranslatorImpl.java @@ -1,12 +1,12 @@ /** * Copyright 2015-2023 yanglb.com - * + *

      * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + *

      + * http://www.apache.org/licenses/LICENSE-2.0 + *

      * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -24,6 +24,7 @@ import com.yanglb.codegen.utils.Conf; import com.yanglb.codegen.utils.Infos; import com.yanglb.codegen.utils.StringUtil; + import java.util.ArrayList; import java.util.HashMap; import java.util.List; @@ -31,270 +32,262 @@ /** * MySQL 的DDL生成翻译器(单文件) - * + * * @author yanglibing */ public class DdlMysqlTranslatorImpl extends BaseDdlTranslator { - public DdlMysqlTranslatorImpl() { - this.sqlColumnStart = "`"; - this.sqlColumnEnd = "`"; - } - - @Override - protected void onTranslate() throws CodeGenException { - super.onTranslate(); - StringBuilder sb = this.writableModel.getData(); - - // 添加文件头 - sb.append(Infos.sqlHeader()); - sb.append("\n"); - - // 逐个添加内容 - for (DdlModel itm : this.model) { - sb.append(this.genDdl(itm)); - } - - // 添加外键 - sb.append(this.genForeignKey()); - } - - /** - * 生成MySQL的DDL - * - * @param model - * 原始数据 - * @return 生成结果 - * @throws CodeGenException - * 出错信息 - */ - public String genDdl(DdlModel model) throws CodeGenException { - StringBuilder sb = new StringBuilder(); - - // 主键、约束、索引等 - String primaryKey = ""; - HashMap> indexMap = new HashMap>(); - HashMap> uniqueMap = new HashMap>(); - - // 表名 - String tableName = this.genFullTableName(model); - sb.append(String.format("-- %s \n", model.getSheetName())); - sb.append(String.format("-- version %s \n", model.getVersion())); - sb.append(String.format("CREATE TABLE %s (\n", tableName)); - - Integer autoIncrement = null; - for (DdlDetail detail : model.getDetail()) { - // 主键 - if (detail.isColKey()) { - if (!StringUtil.isNullOrEmpty(primaryKey)) { - primaryKey += ", "; - } - primaryKey += String.format("%s%s%s", this.sqlColumnStart, - detail.getColName(), this.sqlColumnEnd); - } - - // 自增初始值 - if (detail.getColAutoIncrement() != null) - autoIncrement = detail.getColAutoIncrement(); - - // 索引 - this.updateIndexUniqueMap(indexMap, detail.getColIndex(), detail); - - // 约束 - this.updateIndexUniqueMap(uniqueMap, detail.getColUnique(), detail); - - // 列明细 - sb.append(this.genDdlDetail(detail)); - } - - // 主键 - if (!StringUtil.isNullOrEmpty(primaryKey)) { - sb.append(String.format(" PRIMARY KEY (%s),\n", primaryKey)); - } - - // 索引 - if (!indexMap.isEmpty()) { - for(List list : indexMap.values()) { - sb.append(String.format(" %s,\n", this.indexUniqueSql(list, true))); - } - } - - // 约束 - if (!uniqueMap.isEmpty()) { - for(List list : uniqueMap.values()) { - sb.append(String.format(" %s,\n", this.indexUniqueSql(list, false))); - } - } - - // 删除最后一个 ,号 - sb.deleteCharAt(sb.lastIndexOf(",")); - - // 引擎、字符集等其它信息 - StringBuilder info = new StringBuilder(); - info.append(String.format("ENGINE=%s ", engine())); - info.append(String.format("DEFAULT CHARSET=%s ", charset())); - if (autoIncrement != null) { - info.append(String.format("AUTO_INCREMENT=%d ", autoIncrement)); - } - - // 注释 - info.append(String.format("COMMENT='%s'", model.getSheetName())); - - // 结束 - sb.append(String.format(") %s;\n\n", info.toString().trim())); - - return sb.toString(); - } - - private String engine() { - return parameterModel.getOptions().getOptionValue("engine", Conf.getSetting("mysql.engine")); - } - private String charset() { - return parameterModel.getOptions().getOptionValue("charset", Conf.getSetting("mysql.charset")); - } - - private void updateIndexUniqueMap(HashMap> map, String names, DdlDetail detail) { - if (!StringUtil.isNullOrEmpty(names)) { - String[] keys = names.split(","); - for (String key : keys) { - key = key.trim(); - List value = map.get(key); - if (value == null) { - value = new ArrayList(); - map.put(key, value); - } - - value.add(detail); - } - } - } - - private String indexUniqueSql(List list, boolean isIndex) { - String name = ""; - StringBuilder sb = new StringBuilder(); - for (DdlDetail detail : list) { - name += detail.getColName() + "_"; - - sb.append(String.format("%s%s%s ASC, ", this.sqlColumnStart, - detail.getColName(), this.sqlColumnEnd)); - } - - // 名字加后缀 - name += isIndex ? "INDEX":"UNIQUE"; - sb.deleteCharAt(sb.lastIndexOf(",")); - - return String.format("%s %s(%s)", isIndex ? "INDEX":"UNIQUE INDEX", name, sb.toString()); - } - - private String genDdlDetail(DdlDetail detail) { - StringBuilder sb = new StringBuilder(); - String type = detail.getColType(); - if (detail.getColLength() != null) { - if (detail.getColPrecision() != null) { - // 长度及精度都有 NUMBER(10,2) - type = String.format("%s(%d, %d)", type, detail.getColLength(), detail.getColPrecision()); - } else { - // 只有长度 VARCHAR2(10) - type = String.format("%s(%d)", type, detail.getColLength()); - } - } else { - // 暂时忽略这种情况 - if (detail.getColPrecision() == null) { - // 长度及精度都没有 VARCHAR - } else { - // 只有精度 NUMBER(2,2) ? 错误? - } - } - sb.append(String.format(" %s%s%s %s", this.sqlColumnStart, - detail.getColName(), this.sqlColumnEnd, type)); - - if (!detail.isColNullable()) { - sb.append(" NOT NULL"); - } - - // 自增长列 - if (detail.getColAutoIncrement() != null) { - sb.append(" AUTO_INCREMENT"); - } - - // 默认值、只有text/char 需要加引号 - if (!StringUtil.isNullOrEmpty(detail.getColDefault())) { - String colType = detail.getColType().toLowerCase(); - if (colType.contains("text") || colType.contains("char")) { - sb.append(String.format(" DEFAULT '%s'", detail.getColDefault())); - } else { - String def = detail.getColDefault(); - if (!StringUtil.isNullOrEmpty(def) && def.toUpperCase().startsWith("ON ")) { - sb.append(" " + detail.getColDefault()); - } else { - sb.append(String.format(" DEFAULT %s", detail.getColDefault())); - } - } - } - - // 注释 - if (!StringUtil.isNullOrEmpty(detail.getFieldName())) { - String name = detail.getFieldName(); - name.replaceAll("'", ""); - name.replaceAll("\r", ""); - name.replaceAll("\n", ""); - sb.append(String.format(" COMMENT '%s'", name)); - } - - sb.append(",\n"); - return sb.toString(); - } - - /** - * 添加外键 - * - * @throws CodeGenException - */ - private String genForeignKey() throws CodeGenException { - StringBuilder sb = new StringBuilder(); - if (this.foreignKeyList.size()> 0) { - sb.append("\n"); - sb.append("-- -------------------------------\n"); - sb.append("-- foreign key list\n"); - sb.append("-- -------------------------------\n"); - } - - // 所有表的外键放在最后处理 - for (ForeignModel model : this.foreignKeyList) { - // 取得主、外键的列名 - String columnName = "", referenceColumnName = ""; - - for (ForeignDetailModel foreignColumns : model.getForeignColumns()) { - if (!StringUtil.isNullOrEmpty(columnName)) { - columnName += ", "; - } - if (!StringUtil.isNullOrEmpty(referenceColumnName)) { - referenceColumnName += ", "; - } - - // 外键列,如:[AddressBizId], [AddressRev] - columnName += String.format("%s%s%s", this.sqlColumnStart, - foreignColumns.getDdlDetail().getColName(), - this.sqlColumnEnd); - - // 主键列,如:[BizId], [Rev] - referenceColumnName += String.format("%s%s%s", - this.sqlColumnStart, foreignColumns - .getForeignDdlDetail().getColName(), - this.sqlColumnEnd); - } - - // 表名 - String tableName = genFullTableName(model.getDdlModel()); - String referenceTableName = genFullTableName(model - .getForeignColumns().get(0).getForeignDdlModel()); - sb.append(String.format("ALTER TABLE %s ADD FOREIGN KEY(%s) \n" - + "REFERENCES %s (%s) \n" - + "ON DELETE CASCADE ON UPDATE CASCADE; \n\n", - tableName, columnName, referenceTableName, - referenceColumnName)); - } - return sb.toString(); - } + public DdlMysqlTranslatorImpl() { + this.sqlColumnStart = "`"; + this.sqlColumnEnd = "`"; + } + + @Override + protected void onTranslate() throws CodeGenException { + super.onTranslate(); + StringBuilder sb = this.writableModel.getData(); + + // 添加文件头 + sb.append(Infos.sqlHeader()); + sb.append("\n"); + + // 逐个添加内容 + for (DdlModel itm : this.model) { + sb.append(this.genDdl(itm)); + } + + // 添加外键 + sb.append(this.genForeignKey()); + } + + /** + * 生成MySQL的DDL + * + * @param model 原始数据 + * @return 生成结果 + * @throws CodeGenException 出错信息 + */ + public String genDdl(DdlModel model) throws CodeGenException { + StringBuilder sb = new StringBuilder(); + + // 主键、约束、索引等 + String primaryKey = ""; + HashMap> indexMap = new HashMap>(); + HashMap> uniqueMap = new HashMap>(); + + // 表名 + String tableName = this.genFullTableName(model); + sb.append(String.format("-- %s \n", model.getSheetName())); + sb.append(String.format("-- version %s \n", model.getVersion())); + sb.append(String.format("CREATE TABLE %s (\n", tableName)); + + Integer autoIncrement = null; + for (DdlDetail detail : model.getDetail()) { + // 主键 + if (detail.isColKey()) { + if (!StringUtil.isNullOrEmpty(primaryKey)) { + primaryKey += ", "; + } + primaryKey += String.format("%s%s%s", this.sqlColumnStart, + detail.getColName(), this.sqlColumnEnd); + } + + // 自增初始值 + if (detail.getColAutoIncrement() != null) + autoIncrement = detail.getColAutoIncrement(); + + // 索引 + this.updateIndexUniqueMap(indexMap, detail.getColIndex(), detail); + + // 约束 + this.updateIndexUniqueMap(uniqueMap, detail.getColUnique(), detail); + + // 列明细 + sb.append(this.genDdlDetail(detail)); + } + + // 主键 + if (!StringUtil.isNullOrEmpty(primaryKey)) { + sb.append(String.format(" PRIMARY KEY (%s),\n", primaryKey)); + } + + // 索引 + if (!indexMap.isEmpty()) { + for (List list : indexMap.values()) { + sb.append(String.format(" %s,\n", this.indexUniqueSql(list, true))); + } + } + + // 约束 + if (!uniqueMap.isEmpty()) { + for (List list : uniqueMap.values()) { + sb.append(String.format(" %s,\n", this.indexUniqueSql(list, false))); + } + } + + // 删除最后一个 ,号 + sb.deleteCharAt(sb.lastIndexOf(",")); + + // 引擎、字符集等其它信息 + StringBuilder info = new StringBuilder(); + info.append(String.format("ENGINE=%s ", engine())); + info.append(String.format("DEFAULT CHARSET=%s ", charset())); + if (autoIncrement != null) { + info.append(String.format("AUTO_INCREMENT=%d ", autoIncrement)); + } + + // 注释 + info.append(String.format("COMMENT='%s'", model.getSheetName())); + + // 结束 + sb.append(String.format(") %s;\n\n", info.toString().trim())); + + return sb.toString(); + } + + private String engine() { + return parameterModel.getOptions().getOptionValue("engine", Conf.getSetting("mysql.engine")); + } + + private String charset() { + return parameterModel.getOptions().getOptionValue("charset", Conf.getSetting("mysql.charset")); + } + + private void updateIndexUniqueMap(HashMap> map, String names, DdlDetail detail) { + if (!StringUtil.isNullOrEmpty(names)) { + String[] keys = names.split(","); + for (String key : keys) { + key = key.trim(); + List value = map.computeIfAbsent(key, k -> new ArrayList()); + value.add(detail); + } + } + } + + private String indexUniqueSql(List list, boolean isIndex) { + StringBuilder name = new StringBuilder(); + StringBuilder sb = new StringBuilder(); + for (DdlDetail detail : list) { + name.append(detail.getColName()).append("_"); + + sb.append(String.format("%s%s%s ASC, ", this.sqlColumnStart, + detail.getColName(), this.sqlColumnEnd)); + } + + // 名字加后缀 + name.append(isIndex ? "INDEX" : "UNIQUE"); + sb.deleteCharAt(sb.lastIndexOf(",")); + + return String.format("%s %s(%s)", isIndex ? "INDEX" : "UNIQUE INDEX", name.toString(), sb.toString()); + } + + private String genDdlDetail(DdlDetail detail) { + StringBuilder sb = new StringBuilder(); + String type = detail.getColType(); + if (detail.getColLength() != null) { + if (detail.getColPrecision() != null) { + // 长度及精度都有 NUMBER(10,2) + type = String.format("%s(%d, %d)", type, detail.getColLength(), detail.getColPrecision()); + } else { + // 只有长度 VARCHAR2(10) + type = String.format("%s(%d)", type, detail.getColLength()); + } +// } else { +// // 暂时忽略这种情况 +// if (detail.getColPrecision() == null) { +// // 长度及精度都没有 VARCHAR +// } else { +// // 只有精度 NUMBER(2,2) ? 错误? +// } + } + sb.append(String.format(" %s%s%s %s", this.sqlColumnStart, + detail.getColName(), this.sqlColumnEnd, type)); + + if (!detail.isColNullable()) { + sb.append(" NOT NULL"); + } + + // 自增长列 + if (detail.getColAutoIncrement() != null) { + sb.append(" AUTO_INCREMENT"); + } + + // 默认值、只有text/char 需要加引号 + if (!StringUtil.isNullOrEmpty(detail.getColDefault())) { + String colType = detail.getColType().toLowerCase(); + if (colType.contains("text") || colType.contains("char")) { + sb.append(String.format(" DEFAULT '%s'", detail.getColDefault())); + } else { + String def = detail.getColDefault(); + if (!StringUtil.isNullOrEmpty(def) && def.toUpperCase().startsWith("ON ")) { + sb.append(" ").append(detail.getColDefault()); + } else { + sb.append(String.format(" DEFAULT %s", detail.getColDefault())); + } + } + } + + // 注释 + if (!StringUtil.isNullOrEmpty(detail.getFieldName())) { + String name = detail.getFieldName(); + name = name.replaceAll("'", ""); + name = name.replaceAll("\r", ""); + name = name.replaceAll("\n", ""); + sb.append(String.format(" COMMENT '%s'", name)); + } + + sb.append(",\n"); + return sb.toString(); + } + + /** + * 添加外键 + */ + private String genForeignKey() throws CodeGenException { + StringBuilder sb = new StringBuilder(); + if (!this.foreignKeyList.isEmpty()) { + sb.append("\n"); + sb.append("-- -------------------------------\n"); + sb.append("-- foreign key list\n"); + sb.append("-- -------------------------------\n"); + } + + // 所有表的外键放在最后处理 + for (ForeignModel model : this.foreignKeyList) { + // 取得主、外键的列名 + String columnName = "", referenceColumnName = ""; + + for (ForeignDetailModel foreignColumns : model.getForeignColumns()) { + if (!StringUtil.isNullOrEmpty(columnName)) { + columnName += ", "; + } + if (!StringUtil.isNullOrEmpty(referenceColumnName)) { + referenceColumnName += ", "; + } + + // 外键列,如:[AddressBizId], [AddressRev] + columnName += String.format("%s%s%s", this.sqlColumnStart, + foreignColumns.getDdlDetail().getColName(), + this.sqlColumnEnd); + + // 主键列,如:[BizId], [Rev] + referenceColumnName += String.format("%s%s%s", + this.sqlColumnStart, foreignColumns + .getForeignDdlDetail().getColName(), + this.sqlColumnEnd); + } + + // 表名 + String tableName = genFullTableName(model.getDdlModel()); + String referenceTableName = genFullTableName(model + .getForeignColumns().get(0).getForeignDdlModel()); + sb.append(String.format("ALTER TABLE %s ADD FOREIGN KEY(%s) \n" + + "REFERENCES %s (%s) \n" + + "ON DELETE CASCADE ON UPDATE CASCADE; \n\n", + tableName, columnName, referenceTableName, + referenceColumnName)); + } + return sb.toString(); + } } diff --git a/src/main/java/com/yanglb/codegen/core/translator/impl/DdlSqlServerTranslatorImpl.java b/src/main/java/com/yanglb/codegen/core/translator/impl/DdlSqlServerTranslatorImpl.java index cae7e35..6cb015c 100644 --- a/src/main/java/com/yanglb/codegen/core/translator/impl/DdlSqlServerTranslatorImpl.java +++ b/src/main/java/com/yanglb/codegen/core/translator/impl/DdlSqlServerTranslatorImpl.java @@ -1,12 +1,12 @@ /** * Copyright 2015-2023 yanglb.com - * + *

      * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + *

      + * http://www.apache.org/licenses/LICENSE-2.0 + *

      * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -26,183 +26,183 @@ import com.yanglb.codegen.utils.StringUtil; public class DdlSqlServerTranslatorImpl extends BaseDdlTranslator { - - public DdlSqlServerTranslatorImpl() { - this.sqlColumnStart = "["; - this.sqlColumnEnd = "]"; - } - - @Override - protected void onTranslate() throws CodeGenException { - super.onTranslate(); - StringBuilder sb = this.writableModel.getData(); - - // 添加文件头 - sb.append(Infos.sqlHeader()); - sb.append("\n"); - - // 逐个添加内容 - for(DdlModel itm : this.model) { - sb.append(this.genDdl(itm)); - } - - // 添加外键 - sb.append(this.genForeignKey()); - } - - - /** - * 添加外键 - * @throws CodeGenException - */ - private String genForeignKey() throws CodeGenException { - StringBuilder sb = new StringBuilder(); - if(this.foreignKeyList.size()>0) { - sb.append("\n"); - sb.append("---------------------------------\n"); - sb.append("-- foreign key list\n"); - sb.append("---------------------------------\n"); - } - - // 所有表的外键放在最后处理 - for(ForeignModel model : this.foreignKeyList) { - // 取得主、外键的列名 - String columnName="",referenceColumnName=""; - // FK_ForeignTable_PrimaryTable_On_ForeignColumn1[_ForeignColumnN] - String foreignKeyName = String.format("FK_%s_%s_ON", - model.getDdlModel().getName(), - model.getForeignColumns().get(0).getForeignDdlModel().getName()); - - for(ForeignDetailModel foreignColumns:model.getForeignColumns()) { - if(!StringUtil.isNullOrEmpty(columnName)) { - columnName+=", "; - } - if(!StringUtil.isNullOrEmpty(referenceColumnName)) { - referenceColumnName += ", "; - } - - // 外键列,如:[AddressBizId], [AddressRev] - columnName += String.format("%s%s%s", - this.sqlColumnStart, - foreignColumns.getDdlDetail().getColName(), - this.sqlColumnEnd); - - // 主键列,如:[BizId], [Rev] - referenceColumnName += String.format("%s%s%s", - this.sqlColumnStart, - foreignColumns.getForeignDdlDetail().getColName(), - this.sqlColumnEnd); - - foreignKeyName += "_" + foreignColumns.getDdlDetail().getColName(); - } - - // 超过128字符时截断 - if(foreignKeyName.length()> 128) { - sb.append(String.format(Resources.getString("E_012"), foreignKeyName)); - foreignKeyName = foreignKeyName.substring(0, 128); - } - - // 表名 - String tableName = genFullTableName(model.getDdlModel()); - String referenceTableName = genFullTableName(model.getForeignColumns().get(0).getForeignDdlModel()); - sb.append(String.format("ALTER TABLE %s WITH CHECK ADD CONSTRAINT %s FOREIGN KEY(%s)\n" - + "REFERENCES %s (%s)\n" - + "GO\n\n", - tableName, - foreignKeyName, - columnName, - referenceTableName, - referenceColumnName)); - } - return sb.toString(); - } - - /** - * 生成MySQL的DDL - * @param model 原始数据 - * @return 生成结果 - * @throws CodeGenException 出错信息 - */ - public String genDdl(DdlModel model) - throws CodeGenException{ - StringBuilder sb = new StringBuilder(); - String primaryKey = ""; - - // 表名 - String tableName = this.genFullTableName(model); - sb.append(String.format("-- %s \n", model.getSheetName())); - sb.append(String.format("-- DROP TABLE %s; \n", tableName)); - sb.append(String.format("CREATE TABLE %s (\n", tableName)); - - // 逐列添加 - for(DdlDetail detail:model.getDetail()) { - if(detail.isColKey()) { - if(!StringUtil.isNullOrEmpty(primaryKey)) { - primaryKey += ", "; - } - primaryKey += String.format("%s%s%s", - this.sqlColumnStart, - detail.getColName(), - this.sqlColumnEnd); - } - sb.append(this.genDdlDetail(detail)); - } - - // 主键 - if(!StringUtil.isNullOrEmpty(primaryKey)) { - sb.append(String.format(" PRIMARY KEY (%s),\n", primaryKey)); - } - - // 删除最后一个 ,号 - sb.deleteCharAt(sb.lastIndexOf(",")); - sb.append(")\nGO \n"); - sb.append("\n"); - - return sb.toString(); - } - - private String genDdlDetail(DdlDetail detail) { - StringBuilder sb = new StringBuilder(); - String type = detail.getColType(); - if(detail.getColLength() != null) { - if(detail.getColPrecision() != null) { - // 长度及精度都有 NUMBER(10,2) - type = String.format("%s(%d, %d)", type - , detail.getColLength().intValue() - , detail.getColPrecision().intValue()); - } else { - // 只有长度 VARCHAR2(10) - type = String.format("%s(%d)", type - , detail.getColLength().intValue()); - } - } else { - // 暂时忽略这种情况 - if(detail.getColPrecision() == null) { - // 长度及精度都没有 VARCHAR - } else { - // 只有精度 NUMBER(2,2) ? 错误? - } - } - sb.append(String.format(" %s%s%s %s" - ,this.sqlColumnStart - ,detail.getColName() - ,this.sqlColumnEnd - ,type)); - - if(!detail.isColNullable()) { - sb.append(" NOT NULL"); - } - - if(!StringUtil.isNullOrEmpty(detail.getColDefault())) { - // 如果是函数类型的默认值则不添加引号 - if(detail.getColDefault().trim().endsWith(")")) { - sb.append(String.format(" DEFAULT %s", detail.getColDefault())); - } else { - sb.append(String.format(" DEFAULT '%s'", detail.getColDefault())); - } - } - - sb.append(",\n"); - return sb.toString(); - } + + public DdlSqlServerTranslatorImpl() { + this.sqlColumnStart = "["; + this.sqlColumnEnd = "]"; + } + + @Override + protected void onTranslate() throws CodeGenException { + super.onTranslate(); + StringBuilder sb = this.writableModel.getData(); + + // 添加文件头 + sb.append(Infos.sqlHeader()); + sb.append("\n"); + + // 逐个添加内容 + for (DdlModel itm : this.model) { + sb.append(this.genDdl(itm)); + } + + // 添加外键 + sb.append(this.genForeignKey()); + } + + + /** + * 添加外键 + */ + private String genForeignKey() throws CodeGenException { + StringBuilder sb = new StringBuilder(); + if (!this.foreignKeyList.isEmpty()) { + sb.append("\n"); + sb.append("---------------------------------\n"); + sb.append("-- foreign key list\n"); + sb.append("---------------------------------\n"); + } + + // 所有表的外键放在最后处理 + for (ForeignModel model : this.foreignKeyList) { + // 取得主、外键的列名 + String columnName = "", referenceColumnName = ""; + // FK_ForeignTable_PrimaryTable_On_ForeignColumn1[_ForeignColumnN] + StringBuilder foreignKeyName = new StringBuilder(String.format("FK_%s_%s_ON", + model.getDdlModel().getName(), + model.getForeignColumns().get(0).getForeignDdlModel().getName())); + + for (ForeignDetailModel foreignColumns : model.getForeignColumns()) { + if (!StringUtil.isNullOrEmpty(columnName)) { + columnName += ", "; + } + if (!StringUtil.isNullOrEmpty(referenceColumnName)) { + referenceColumnName += ", "; + } + + // 外键列,如:[AddressBizId], [AddressRev] + columnName += String.format("%s%s%s", + this.sqlColumnStart, + foreignColumns.getDdlDetail().getColName(), + this.sqlColumnEnd); + + // 主键列,如:[BizId], [Rev] + referenceColumnName += String.format("%s%s%s", + this.sqlColumnStart, + foreignColumns.getForeignDdlDetail().getColName(), + this.sqlColumnEnd); + + foreignKeyName.append("_").append(foreignColumns.getDdlDetail().getColName()); + } + + // 超过128字符时截断 + if (foreignKeyName.length()> 128) { + sb.append(String.format(Resources.getString("E_012"), foreignKeyName.toString())); + foreignKeyName = new StringBuilder(foreignKeyName.substring(0, 128)); + } + + // 表名 + String tableName = genFullTableName(model.getDdlModel()); + String referenceTableName = genFullTableName(model.getForeignColumns().get(0).getForeignDdlModel()); + sb.append(String.format("ALTER TABLE %s WITH CHECK ADD CONSTRAINT %s FOREIGN KEY(%s)\n" + + "REFERENCES %s (%s)\n" + + "GO\n\n", + tableName, + foreignKeyName.toString(), + columnName, + referenceTableName, + referenceColumnName)); + } + return sb.toString(); + } + + /** + * 生成MySQL的DDL + * + * @param model 原始数据 + * @return 生成结果 + * @throws CodeGenException 出错信息 + */ + public String genDdl(DdlModel model) + throws CodeGenException { + StringBuilder sb = new StringBuilder(); + String primaryKey = ""; + + // 表名 + String tableName = this.genFullTableName(model); + sb.append(String.format("-- %s \n", model.getSheetName())); + sb.append(String.format("-- DROP TABLE %s; \n", tableName)); + sb.append(String.format("CREATE TABLE %s (\n", tableName)); + + // 逐列添加 + for (DdlDetail detail : model.getDetail()) { + if (detail.isColKey()) { + if (!StringUtil.isNullOrEmpty(primaryKey)) { + primaryKey += ", "; + } + primaryKey += String.format("%s%s%s", + this.sqlColumnStart, + detail.getColName(), + this.sqlColumnEnd); + } + sb.append(this.genDdlDetail(detail)); + } + + // 主键 + if (!StringUtil.isNullOrEmpty(primaryKey)) { + sb.append(String.format(" PRIMARY KEY (%s),\n", primaryKey)); + } + + // 删除最后一个 ,号 + sb.deleteCharAt(sb.lastIndexOf(",")); + sb.append(")\nGO \n"); + sb.append("\n"); + + return sb.toString(); + } + + private String genDdlDetail(DdlDetail detail) { + StringBuilder sb = new StringBuilder(); + String type = detail.getColType(); + if (detail.getColLength() != null) { + if (detail.getColPrecision() != null) { + // 长度及精度都有 NUMBER(10,2) + type = String.format("%s(%d, %d)", type + , detail.getColLength().intValue() + , detail.getColPrecision().intValue()); + } else { + // 只有长度 VARCHAR2(10) + type = String.format("%s(%d)", type + , detail.getColLength().intValue()); + } + } else { + // 暂时忽略这种情况 + if (detail.getColPrecision() == null) { + // 长度及精度都没有 VARCHAR + } else { + // 只有精度 NUMBER(2,2) ? 错误? + } + } + sb.append(String.format(" %s%s%s %s" + , this.sqlColumnStart + , detail.getColName() + , this.sqlColumnEnd + , type)); + + if (!detail.isColNullable()) { + sb.append(" NOT NULL"); + } + + if (!StringUtil.isNullOrEmpty(detail.getColDefault())) { + // 如果是函数类型的默认值则不添加引号 + if (detail.getColDefault().trim().endsWith(")")) { + sb.append(String.format(" DEFAULT %s", detail.getColDefault())); + } else { + sb.append(String.format(" DEFAULT '%s'", detail.getColDefault())); + } + } + + sb.append(",\n"); + return sb.toString(); + } } diff --git a/src/main/java/com/yanglb/codegen/core/translator/impl/DdlSqliteTranslatorImpl.java b/src/main/java/com/yanglb/codegen/core/translator/impl/DdlSqliteTranslatorImpl.java index c5382af..af07053 100644 --- a/src/main/java/com/yanglb/codegen/core/translator/impl/DdlSqliteTranslatorImpl.java +++ b/src/main/java/com/yanglb/codegen/core/translator/impl/DdlSqliteTranslatorImpl.java @@ -1,12 +1,12 @@ /** * Copyright 2015-2023 yanglb.com - * + *

      * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + *

      + * http://www.apache.org/licenses/LICENSE-2.0 + *

      * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -27,164 +27,164 @@ public class DdlSqliteTranslatorImpl extends BaseDdlTranslator { - public DdlSqliteTranslatorImpl() { - this.sqlColumnStart = "\""; - this.sqlColumnEnd = "\""; - } - - @Override - protected void onTranslate() throws CodeGenException { - super.onTranslate(); - StringBuilder sb = this.writableModel.getData(); - - // 添加文件头 - sb.append(Infos.sqlHeader()); - sb.append("\n"); - - // 逐个添加内容 - for(DdlModel itm : this.model) { - sb.append(this.genDdl(itm)); - } - } - - /** - * 生成MySQL的DDL - * @param model 原始数据 - * @return 生成结果 - * @throws CodeGenException 出错信息 - */ - public String genDdl(DdlModel model) - throws CodeGenException{ - StringBuilder sb = new StringBuilder(); - String primaryKey = ""; - - String tableName = this.genFullTableName(model); - sb.append(String.format("-- %s \n", model.getSheetName())); - sb.append(String.format("-- DROP TABLE %s; \n", tableName)); - sb.append(String.format("CREATE TABLE %s (\n", tableName)); - for(DdlDetail detail:model.getDetail()) { - if(detail.isColKey()) { - if(!StringUtil.isNullOrEmpty(primaryKey)) { - primaryKey += ", "; - } - primaryKey += String.format("%s%s%s", - this.sqlColumnStart, - detail.getColName(), - this.sqlColumnEnd); - } - - sb.append(this.genDdlDetail(detail)); - } - - // 主键 - if(!StringUtil.isNullOrEmpty(primaryKey)) { - sb.append(String.format(" PRIMARY KEY (%s),\n", primaryKey)); - } - - // 外键 - sb.append(this.genForeignKey(model)); - - // 删除最后一个 ,号 - sb.deleteCharAt(sb.lastIndexOf(",")); - sb.append(");\n"); - - sb.append("\n"); - - return sb.toString(); - } - - private String genDdlDetail(DdlDetail detail) { - StringBuilder sb = new StringBuilder(); - String type = detail.getColType(); - if(detail.getColLength() != null) { - if(detail.getColPrecision() != null) { - // 长度及精度都有 NUMBER(10,2) - type = String.format("%s(%d, %d)", type - , detail.getColLength().intValue() - , detail.getColPrecision().intValue()); - } else { - // 只有长度 VARCHAR2(10) - type = String.format("%s(%d)", type - , detail.getColLength().intValue()); - } - } else { - // 暂时忽略这种情况 - if(detail.getColPrecision() == null) { - // 长度及精度都没有 VARCHAR - } else { - // 只有精度 NUMBER(2,2) ? 错误? - } - } - sb.append(String.format(" %s%s%s %s" - ,this.sqlColumnStart - ,detail.getColName() - ,this.sqlColumnEnd - ,type)); - - if(!detail.isColNullable()) { - sb.append(" NOT NULL"); - } - - // TODO: 默认值还有问题 - if(!StringUtil.isNullOrEmpty(detail.getColDefault())) { - // 如果是函数类型的默认值则不添加引号 - if(detail.getColDefault().trim().endsWith(")")) { - sb.append(String.format(" DEFAULT %s", detail.getColDefault())); - } else { - sb.append(String.format(" DEFAULT '%s'", detail.getColDefault())); - } - } - - sb.append(",\n"); - return sb.toString(); - } - - /** - * 添加外键 - * @throws CodeGenException - */ - private String genForeignKey(DdlModel currentTableModel) throws CodeGenException { - StringBuilder sb = new StringBuilder(); - - // 所有表的外键放在最后处理 - for(ForeignModel model : this.foreignKeyList) { - // 只生成当前表的外键 - if(!currentTableModel.equals(model.getDdlModel())) { - continue; - } - - // 取得主、外键的列名 - String columnName="",referenceColumnName=""; - - for(ForeignDetailModel foreignColumns:model.getForeignColumns()) { - if(!StringUtil.isNullOrEmpty(columnName)) { - columnName+=", "; - } - if(!StringUtil.isNullOrEmpty(referenceColumnName)) { - referenceColumnName += ", "; - } - - // 外键列,如:[AddressBizId], [AddressRev] - columnName += String.format("%s%s%s", - this.sqlColumnStart, - foreignColumns.getDdlDetail().getColName(), - this.sqlColumnEnd); - - // 主键列,如:[BizId], [Rev] - referenceColumnName += String.format("%s%s%s", - this.sqlColumnStart, - foreignColumns.getForeignDdlDetail().getColName(), - this.sqlColumnEnd); - } - - // 表名 - //String tableName = genFullTableName(model.getDdlModel()); - String referenceTableName = genFullTableName(model.getForeignColumns().get(0).getForeignDdlModel()); - sb.append(String.format(" FOREIGN KEY(%s) REFERENCES %s(%s),\n", - columnName, - referenceTableName, - referenceColumnName)); - } - return sb.toString(); - } + public DdlSqliteTranslatorImpl() { + this.sqlColumnStart = "\""; + this.sqlColumnEnd = "\""; + } + + @Override + protected void onTranslate() throws CodeGenException { + super.onTranslate(); + StringBuilder sb = this.writableModel.getData(); + + // 添加文件头 + sb.append(Infos.sqlHeader()); + sb.append("\n"); + + // 逐个添加内容 + for (DdlModel itm : this.model) { + sb.append(this.genDdl(itm)); + } + } + + /** + * 生成MySQL的DDL + * + * @param model 原始数据 + * @return 生成结果 + * @throws CodeGenException 出错信息 + */ + public String genDdl(DdlModel model) + throws CodeGenException { + StringBuilder sb = new StringBuilder(); + String primaryKey = ""; + + String tableName = this.genFullTableName(model); + sb.append(String.format("-- %s \n", model.getSheetName())); + sb.append(String.format("-- DROP TABLE %s; \n", tableName)); + sb.append(String.format("CREATE TABLE %s (\n", tableName)); + for (DdlDetail detail : model.getDetail()) { + if (detail.isColKey()) { + if (!StringUtil.isNullOrEmpty(primaryKey)) { + primaryKey += ", "; + } + primaryKey += String.format("%s%s%s", + this.sqlColumnStart, + detail.getColName(), + this.sqlColumnEnd); + } + + sb.append(this.genDdlDetail(detail)); + } + + // 主键 + if (!StringUtil.isNullOrEmpty(primaryKey)) { + sb.append(String.format(" PRIMARY KEY (%s),\n", primaryKey)); + } + + // 外键 + sb.append(this.genForeignKey(model)); + + // 删除最后一个 ,号 + sb.deleteCharAt(sb.lastIndexOf(",")); + sb.append(");\n"); + + sb.append("\n"); + + return sb.toString(); + } + + private String genDdlDetail(DdlDetail detail) { + StringBuilder sb = new StringBuilder(); + String type = detail.getColType(); + if (detail.getColLength() != null) { + if (detail.getColPrecision() != null) { + // 长度及精度都有 NUMBER(10,2) + type = String.format("%s(%d, %d)", type + , detail.getColLength() + , detail.getColPrecision()); + } else { + // 只有长度 VARCHAR2(10) + type = String.format("%s(%d)", type + , detail.getColLength()); + } + } else { + // 暂时忽略这种情况 + if (detail.getColPrecision() == null) { + // 长度及精度都没有 VARCHAR + } else { + // 只有精度 NUMBER(2,2) ? 错误? + } + } + sb.append(String.format(" %s%s%s %s" + , this.sqlColumnStart + , detail.getColName() + , this.sqlColumnEnd + , type)); + + if (!detail.isColNullable()) { + sb.append(" NOT NULL"); + } + + // TODO: 默认值还有问题 + if (!StringUtil.isNullOrEmpty(detail.getColDefault())) { + // 如果是函数类型的默认值则不添加引号 + if (detail.getColDefault().trim().endsWith(")")) { + sb.append(String.format(" DEFAULT %s", detail.getColDefault())); + } else { + sb.append(String.format(" DEFAULT '%s'", detail.getColDefault())); + } + } + + sb.append(",\n"); + return sb.toString(); + } + + /** + * 添加外键 + */ + private String genForeignKey(DdlModel currentTableModel) throws CodeGenException { + StringBuilder sb = new StringBuilder(); + + // 所有表的外键放在最后处理 + for (ForeignModel model : this.foreignKeyList) { + // 只生成当前表的外键 + if (!currentTableModel.equals(model.getDdlModel())) { + continue; + } + + // 取得主、外键的列名 + String columnName = "", referenceColumnName = ""; + + for (ForeignDetailModel foreignColumns : model.getForeignColumns()) { + if (!StringUtil.isNullOrEmpty(columnName)) { + columnName += ", "; + } + if (!StringUtil.isNullOrEmpty(referenceColumnName)) { + referenceColumnName += ", "; + } + + // 外键列,如:[AddressBizId], [AddressRev] + columnName += String.format("%s%s%s", + this.sqlColumnStart, + foreignColumns.getDdlDetail().getColName(), + this.sqlColumnEnd); + + // 主键列,如:[BizId], [Rev] + referenceColumnName += String.format("%s%s%s", + this.sqlColumnStart, + foreignColumns.getForeignDdlDetail().getColName(), + this.sqlColumnEnd); + } + + // 表名 + //String tableName = genFullTableName(model.getDdlModel()); + String referenceTableName = genFullTableName(model.getForeignColumns().get(0).getForeignDdlModel()); + sb.append(String.format(" FOREIGN KEY(%s) REFERENCES %s(%s),\n", + columnName, + referenceTableName, + referenceColumnName)); + } + return sb.toString(); + } } diff --git a/src/main/java/com/yanglb/codegen/core/translator/impl/DmlTranslatorImpl.java b/src/main/java/com/yanglb/codegen/core/translator/impl/DmlTranslatorImpl.java index d462a44..9066c5b 100644 --- a/src/main/java/com/yanglb/codegen/core/translator/impl/DmlTranslatorImpl.java +++ b/src/main/java/com/yanglb/codegen/core/translator/impl/DmlTranslatorImpl.java @@ -1,12 +1,12 @@ /** * Copyright 2015-2023 yanglb.com - * + *

      * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + *

      + * http://www.apache.org/licenses/LICENSE-2.0 + *

      * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -21,119 +21,120 @@ import com.yanglb.codegen.model.TableModel; import com.yanglb.codegen.utils.Infos; import com.yanglb.codegen.utils.StringUtil; + import java.util.Map; public class DmlTranslatorImpl extends BaseSqlTranslator { - @Override - protected void onBeforeTranslate() throws CodeGenException { - super.onBeforeTranslate(); - this.writableModel.setExtension("dml"); - - String target = parameterModel.getOptions().getOptionValue("target", "mysql"); - switch (target) { - case "mysql": - sqlColumnStart = "`"; - sqlColumnEnd = "`"; - break; - case "mssql": - sqlColumnStart = "["; - sqlColumnEnd = "]"; - break; - case "sqlite": - sqlColumnStart = "\""; - sqlColumnEnd = "\""; - break; - } - } - - @Override - protected void onTranslate() throws CodeGenException { - super.onTranslate(); - StringBuilder sb = this.writableModel.getData(); - - // 添加文件头 - sb.append(Infos.sqlHeader()); - - // 逐个添加内容 - for(DmlModel itm : this.model) { - sb.append(this.genDml(itm)); - } - } - - private String genDml(DmlModel model) { - StringBuilder sb = new StringBuilder(); - - // 头部信息 - sb.append("\n"); - sb.append(String.format("-- %s\n", model.getSheetName())); - sb.append(String.format("-- %s %s\n", model.getAuthor(), model.getRenewDate())); - - // 每一行dml语句 - String columns = ""; - String space = ""; - if(!StringUtil.isNullOrEmpty(model.getNameSpace()) && !"-".equals(model.getNameSpace())) { - space = String.format("%s.", model.getNameSpace()); - } - TableModel table = model.getDmlData(); - for(Map itm : table.toList()) { - // 如果模板为空则先生成模板 - if(StringUtil.isNullOrEmpty(columns)) { - columns = this.genColumns(table.getColumns()); - } - - // 生成完整语句并添加到sb中 - sb.append(String.format("INSERT INTO %s%s(%s) VALUES (%s);\n", - space, - model.getName(), - columns, - this.genValues(table.getColumns(), itm))); - } - return sb.toString(); - } - - /** - * 生成dml的values部分 - * @param data dml数据 - * @return values - */ - private String genValues(String[] columns, Map data) { - String result = ""; - - for(String col : columns) { - if(!StringUtil.isNullOrEmpty(result)) { - result += ", "; - } - String value = data.get(col); - if(value == null) { - result += "null"; - } else if(value.startsWith("#")) { - // #开头表示为公式 - result += value.substring(1); - } else if(value.startsWith("'") && value.endsWith("'")){ - // 如果已经使用 ' 引号则不添加' - result += value; - } else { - result += String.format("'%s'", data.get(col)); - } - } - return result; - } - - /** - * 生成dml的column部分 - * @param data dml数据 - * @return 'col1', 'col2' - */ - private String genColumns(String[] data) { - String columns = ""; - - for(String col : data) { - if(!StringUtil.isNullOrEmpty(columns)) { - columns += ", "; - } - columns += String.format("%s%s%s", this.sqlColumnStart, col, this.sqlColumnEnd); - } - return columns; - } + @Override + protected void onBeforeTranslate() throws CodeGenException { + super.onBeforeTranslate(); + this.writableModel.setExtension("dml"); + + String target = parameterModel.getOptions().getOptionValue("target", "mysql"); + switch (target) { + case "mysql": + sqlColumnStart = "`"; + sqlColumnEnd = "`"; + break; + case "mssql": + sqlColumnStart = "["; + sqlColumnEnd = "]"; + break; + case "sqlite": + sqlColumnStart = "\""; + sqlColumnEnd = "\""; + break; + } + } + + @Override + protected void onTranslate() throws CodeGenException { + super.onTranslate(); + StringBuilder sb = this.writableModel.getData(); + + // 添加文件头 + sb.append(Infos.sqlHeader()); + + // 逐个添加内容 + for (DmlModel itm : this.model) { + sb.append(this.genDml(itm)); + } + } + + private String genDml(DmlModel model) { + StringBuilder sb = new StringBuilder(); + + // 头部信息 + sb.append("\n"); + sb.append(String.format("-- %s\n", model.getSheetName())); + sb.append(String.format("-- %s %s\n", model.getAuthor(), model.getRenewDate())); + + // 每一行dml语句 + String columns = ""; + String space = ""; + if (!StringUtil.isNullOrEmpty(model.getNameSpace()) && !"-".equals(model.getNameSpace())) { + space = String.format("%s.", model.getNameSpace()); + } + TableModel table = model.getDmlData(); + for (Map itm : table.toList()) { + // 如果模板为空则先生成模板 + if (StringUtil.isNullOrEmpty(columns)) { + columns = this.genColumns(table.getColumns()); + } + + // 生成完整语句并添加到sb中 + sb.append(String.format("INSERT INTO %s%s(%s) VALUES (%s);\n", + space, + model.getName(), + columns, + this.genValues(table.getColumns(), itm))); + } + return sb.toString(); + } + + /** + * 生成dml的values部分 + * @param data dml数据 + * @return values + */ + private String genValues(String[] columns, Map data) { + String result = ""; + + for (String col : columns) { + if (!StringUtil.isNullOrEmpty(result)) { + result += ", "; + } + String value = data.get(col); + if (value == null) { + result += "null"; + } else if (value.startsWith("#")) { + // #开头表示为公式 + result += value.substring(1); + } else if (value.startsWith("'") && value.endsWith("'")) { + // 如果已经使用 ' 引号则不添加' + result += value; + } else { + result += String.format("'%s'", data.get(col)); + } + } + return result; + } + + /** + * 生成dml的column部分 + * @param data dml数据 + * @return 'col1', 'col2' + */ + private String genColumns(String[] data) { + String columns = ""; + + for (String col : data) { + if (!StringUtil.isNullOrEmpty(columns)) { + columns += ", "; + } + columns += String.format("%s%s%s", this.sqlColumnStart, col, this.sqlColumnEnd); + } + return columns; + } } diff --git a/src/main/java/com/yanglb/codegen/core/translator/impl/MsgAndroidTranslatorImpl.java b/src/main/java/com/yanglb/codegen/core/translator/impl/MsgAndroidTranslatorImpl.java index d0f1d83..0427562 100644 --- a/src/main/java/com/yanglb/codegen/core/translator/impl/MsgAndroidTranslatorImpl.java +++ b/src/main/java/com/yanglb/codegen/core/translator/impl/MsgAndroidTranslatorImpl.java @@ -1,12 +1,12 @@ /** * Copyright 2015-2023 yanglb.com - * + *

      * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + *

      + * http://www.apache.org/licenses/LICENSE-2.0 + *

      * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -20,90 +20,93 @@ import com.yanglb.codegen.model.TableModel; import com.yanglb.codegen.utils.Infos; import com.yanglb.codegen.utils.StringUtil; + +import java.nio.file.Path; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; + import org.apache.commons.text.StringEscapeUtils; public class MsgAndroidTranslatorImpl extends BaseMsgTranslator { - @Override - protected void onBeforeTranslate() throws CodeGenException { - super.onBeforeTranslate(); - this.writableModel.setExtension("xml"); - - // Android 资源输出目录结构为: strings/strings.xml、strings-zh/strings.xml 等 - String path = "values"; - if (!this.isDefaultLanguage()) { - path = String.format("values-%s", this.msgLang); - } - - // 文件名,未设置时默认为strings - String fileName = writableModel.getFileName(); - if (StringUtil.isNullOrEmpty(this.parameterModel.getFileName())) { - fileName = "strings"; - } - - fileName = path + "/" + fileName; - writableModel.setFileName(fileName); - } - - @Override - protected String getSplitString() { - return "-"; - } - - @Override - protected void onTranslate() throws CodeGenException { - super.onTranslate(); - StringBuilder sb = this.writableModel.getData(); - sb.append("\n" + - Infos.xmlHeader() + - "\n"); - - // 用于检查相同的key - Map keys = new HashMap(); - Map> arrays = new HashMap>(); - for(TableModel tblModel : this.model) { - for(Map itm : tblModel.toList()) { - String id = escape(itm.get("id")); - if(StringUtil.isNullOrEmpty(id)) continue; - if (!arrays.containsKey(id)) { - arrays.put(id, new ArrayList()); - } - - // 对字符串进行转换 - String value = escape(itm.get(this.msgLang)); - List items = arrays.get(id); - items.add(value); - } - } - - for(String key:arrays.keySet()) { - List items = arrays.get(key); - - if (items.size()> 1) { - // list - sb.append(String.format(" \n", key)); - for(String value:items) { - sb.append(String.format(" %s\n", value)); - } - sb.append(" \n"); - } else { - sb.append(String.format(" %s\n", key, items.get(0))); - } - } - - sb.append("\n"); - - this.writableModel.setData(sb); - } - - private String escape(String value) { - if(value == null) return null; - - value = StringEscapeUtils.escapeXml10(value); - return value; - } + @Override + protected void onBeforeTranslate() throws CodeGenException { + super.onBeforeTranslate(); + this.writableModel.setExtension("xml"); + + // Android 资源输出目录结构为: strings/strings.xml、strings-zh/strings.xml 等 + String path = "values"; + if (!this.isDefaultLanguage()) { + path = String.format("values-%s", this.msgLang); + } + + // 文件名,未设置时默认为strings + String fileName = this.parameterModel.getFileName(); + if (StringUtil.isNullOrEmpty(fileName)) { + fileName = "strings"; + } + + fileName = path + "/" + fileName; + writableModel.setFileName(fileName); + } + + @Override + protected String getSplitString() { + return "-"; + } + + @Override + protected void onTranslate() throws CodeGenException { + super.onTranslate(); + StringBuilder sb = this.writableModel.getData(); + sb.append("\n" + + Infos.xmlHeader() + + "\n"); + + // 用于检查相同的key + Map keys = new HashMap(); + Map> arrays = new HashMap>(); + for (TableModel tblModel : this.model) { + for (Map itm : tblModel.toList()) { + String id = escape(itm.get("id")); + if (StringUtil.isNullOrEmpty(id)) continue; + if (!arrays.containsKey(id)) { + arrays.put(id, new ArrayList()); + } + + // 对字符串进行转换 + String value = escape(itm.get(this.msgLang)); + List items = arrays.get(id); + items.add(value); + } + } + + for (String key : arrays.keySet()) { + List items = arrays.get(key); + + if (items.size()> 1) { + // list + sb.append(String.format(" \n", key)); + for (String value : items) { + sb.append(String.format(" %s\n", value)); + } + sb.append(" \n"); + } else { + sb.append(String.format(" %s\n", key, items.get(0))); + } + } + + sb.append("\n"); + + this.writableModel.setData(sb); + } + + private String escape(String value) { + if (value == null) return null; + + value = StringEscapeUtils.escapeXml10(value); + return value; + } } diff --git a/src/main/java/com/yanglb/codegen/core/translator/impl/MsgCSTranslatorImpl.java b/src/main/java/com/yanglb/codegen/core/translator/impl/MsgCSTranslatorImpl.java index 3de2e09..c67dc23 100644 --- a/src/main/java/com/yanglb/codegen/core/translator/impl/MsgCSTranslatorImpl.java +++ b/src/main/java/com/yanglb/codegen/core/translator/impl/MsgCSTranslatorImpl.java @@ -1,12 +1,12 @@ /** * Copyright 2015-2023 yanglb.com - * + *

      * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + *

      + * http://www.apache.org/licenses/LICENSE-2.0 + *

      * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -22,92 +22,94 @@ import com.yanglb.codegen.utils.Infos; import com.yanglb.codegen.utils.Resources; import com.yanglb.codegen.utils.StringUtil; + import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.Map; + import org.apache.commons.text.StringEscapeUtils; import org.yaml.snakeyaml.reader.UnicodeReader; public class MsgCSTranslatorImpl extends BaseMsgTranslator { - @Override - protected void onBeforeTranslate() throws CodeGenException { - super.onBeforeTranslate(); - this.writableModel.setExtension("resx"); - } - - protected String readResource(String path) throws CodeGenException { - InputStream inputStream = Conf.class - .getClassLoader() - .getResourceAsStream(path); - - BufferedReader reader = new BufferedReader(new UnicodeReader(inputStream)); - StringBuilder sb = new StringBuilder(); - try { - String tmp; - while ((tmp = reader.readLine()) != null) { - sb.append(tmp); - sb.append("\n"); - } - reader.close(); - } catch (IOException ex) { - throw new CodeGenException(String.format(Resources.getString("E_014"), path)); - } - return sb.toString(); - } - - @Override - protected void onTranslate() throws CodeGenException { - super.onTranslate(); - StringBuilder sb = this.writableModel.getData(); - sb.append("\n" + - Infos.xmlHeader() + - "\n"); - - if (this.isDefaultLanguage()) { - sb.append(readResource("msg/resx/schema.txt")); - } - - // 添加 resheader - sb.append(readResource("msg/resx/resheader.txt")); - - // 用于检查相同的key - Map keys = new HashMap(); - for(TableModel tblModel : this.model) { - // 添加Sheet注释 - sb.append(String.format(" \n")); - sb.append(String.format(" \n", tblModel.getSheetName())); - - for(Map itm : tblModel.toList()) { - String id = itm.get("id"); - if(StringUtil.isNullOrEmpty(id)) continue; - if (keys.containsKey(id)) throw new CodeGenException(String.format(Resources.getString("E_013"), id)); - keys.put(id, true); - - // 对字符串进行转换 - id = escape(id); - String value = this.escape(itm.get(this.msgLang)); - sb.append(String.format(" \n", id)); - sb.append(String.format(" %s\n", value)); - sb.append(String.format(" \n")); - } - } - - int idx = sb.lastIndexOf(","); - if(idx != -1) { - sb.deleteCharAt(idx); - } - sb.append("\n"); - - this.writableModel.setData(sb); - } - - private String escape(String value) { - if(value == null) return null; - - value = StringEscapeUtils.escapeXml10(value); - return value; - } + @Override + protected void onBeforeTranslate() throws CodeGenException { + super.onBeforeTranslate(); + this.writableModel.setExtension("resx"); + } + + protected String readResource(String path) throws CodeGenException { + InputStream inputStream = Conf.class + .getClassLoader() + .getResourceAsStream(path); + + BufferedReader reader = new BufferedReader(new UnicodeReader(inputStream)); + StringBuilder sb = new StringBuilder(); + try { + String tmp; + while ((tmp = reader.readLine()) != null) { + sb.append(tmp); + sb.append("\n"); + } + reader.close(); + } catch (IOException ex) { + throw new CodeGenException(String.format(Resources.getString("E_014"), path)); + } + return sb.toString(); + } + + @Override + protected void onTranslate() throws CodeGenException { + super.onTranslate(); + StringBuilder sb = this.writableModel.getData(); + sb.append("\n" + + Infos.xmlHeader() + + "\n"); + + if (this.isDefaultLanguage()) { + sb.append(readResource("msg/resx/schema.txt")); + } + + // 添加 resheader + sb.append(readResource("msg/resx/resheader.txt")); + + // 用于检查相同的key + Map keys = new HashMap(); + for (TableModel tblModel : this.model) { + // 添加Sheet注释 + sb.append(String.format(" \n")); + sb.append(String.format(" \n", tblModel.getSheetName())); + + for (Map itm : tblModel.toList()) { + String id = itm.get("id"); + if (StringUtil.isNullOrEmpty(id)) continue; + if (keys.containsKey(id)) throw new CodeGenException(String.format(Resources.getString("E_013"), id)); + keys.put(id, true); + + // 对字符串进行转换 + id = escape(id); + String value = this.escape(itm.get(this.msgLang)); + sb.append(String.format(" \n", id)); + sb.append(String.format(" %s\n", value)); + sb.append(String.format(" \n")); + } + } + + int idx = sb.lastIndexOf(","); + if (idx != -1) { + sb.deleteCharAt(idx); + } + sb.append("\n"); + + this.writableModel.setData(sb); + } + + private String escape(String value) { + if (value == null) return null; + + value = StringEscapeUtils.escapeXml10(value); + return value; + } } diff --git a/src/main/java/com/yanglb/codegen/core/translator/impl/MsgIOSTranslatorImpl.java b/src/main/java/com/yanglb/codegen/core/translator/impl/MsgIOSTranslatorImpl.java index c2938eb..726ceb9 100644 --- a/src/main/java/com/yanglb/codegen/core/translator/impl/MsgIOSTranslatorImpl.java +++ b/src/main/java/com/yanglb/codegen/core/translator/impl/MsgIOSTranslatorImpl.java @@ -1,12 +1,12 @@ /** * Copyright 2015-2023 yanglb.com - * + *

      * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + *

      + * http://www.apache.org/licenses/LICENSE-2.0 + *

      * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -21,53 +21,54 @@ import com.yanglb.codegen.utils.Infos; import com.yanglb.codegen.utils.Resources; import com.yanglb.codegen.utils.StringUtil; + import java.util.HashMap; import java.util.Map; public class MsgIOSTranslatorImpl extends BaseMsgTranslator { - @Override - protected void onBeforeTranslate() throws CodeGenException { - super.onBeforeTranslate(); - this.writableModel.setExtension("strings"); + @Override + protected void onBeforeTranslate() throws CodeGenException { + super.onBeforeTranslate(); + this.writableModel.setExtension("strings"); + + // IOS 资源输出目录结构为: Base.lproj/xxx.strings、zh.lproj/xxx.strings 等 + String path = (this.isDefaultLanguage() ? "Base" : this.msgLang) + ".lproj"; + String fileName = path + "/" + getFileName(); + this.writableModel.setFileName(fileName); + } + + @Override + protected void onTranslate() throws CodeGenException { + super.onTranslate(); + StringBuilder sb = this.writableModel.getData(); + + sb.append(Infos.cHeader()); + sb.append("\n"); + + // 用于检查相同的key + Map keys = new HashMap(); + for (TableModel tblModel : this.model) { + for (Map itm : tblModel.toList()) { + String id = itm.get("id"); + if (StringUtil.isNullOrEmpty(id)) continue; + if (keys.containsKey(id)) throw new CodeGenException(String.format(Resources.getString("E_013"), id)); + keys.put(id, true); - // IOS 资源输出目录结构为: Base.lproj/xxx.strings、zh.lproj/xxx.strings 等 - String path = (this.isDefaultLanguage() ? "Base" : this.msgLang) + ".lproj"; - String fileName = path + "/" + getFileName(); - this.writableModel.setFileName(fileName); - } + // 对字符串进行转换 + id = escape(id); + String value = this.escape(itm.get(this.msgLang)); + sb.append(String.format("\"%s\" = \"%s\";\n", id, value)); + } + } - @Override - protected void onTranslate() throws CodeGenException { - super.onTranslate(); - StringBuilder sb = this.writableModel.getData(); - - sb.append(Infos.cHeader()); - sb.append("\n"); + this.writableModel.setData(sb); + } - // 用于检查相同的key - Map keys = new HashMap(); - for(TableModel tblModel : this.model) { - for(Map itm : tblModel.toList()) { - String id = itm.get("id"); - if(StringUtil.isNullOrEmpty(id)) continue; - if (keys.containsKey(id)) throw new CodeGenException(String.format(Resources.getString("E_013"), id)); - keys.put(id, true); - - // 对字符串进行转换 - id = escape(id); - String value = this.escape(itm.get(this.msgLang)); - sb.append(String.format("\"%s\" = \"%s\";\n", id, value)); - } - } - - this.writableModel.setData(sb); - } - - private String escape(String value) { - if(value == null) return null; + private String escape(String value) { + if (value == null) return null; - value = StringUtil.escapeIOSString(value); - return value; - } + value = StringUtil.escapeIOSString(value); + return value; + } } diff --git a/src/main/java/com/yanglb/codegen/core/translator/impl/MsgJavaTranslatorImpl.java b/src/main/java/com/yanglb/codegen/core/translator/impl/MsgJavaTranslatorImpl.java index 5ba3592..5ada7b2 100644 --- a/src/main/java/com/yanglb/codegen/core/translator/impl/MsgJavaTranslatorImpl.java +++ b/src/main/java/com/yanglb/codegen/core/translator/impl/MsgJavaTranslatorImpl.java @@ -1,12 +1,12 @@ /** * Copyright 2015-2023 yanglb.com - * + *

      * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + *

      + * http://www.apache.org/licenses/LICENSE-2.0 + *

      * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -19,45 +19,47 @@ import com.yanglb.codegen.exceptions.CodeGenException; import com.yanglb.codegen.model.TableModel; import com.yanglb.codegen.utils.StringUtil; + import java.util.Map; + import org.apache.commons.text.StringEscapeUtils; public class MsgJavaTranslatorImpl extends BaseMsgTranslator { - @Override - protected String getSplitString() { - return "_"; - } - - @Override - protected void onBeforeTranslate() throws CodeGenException { - super.onBeforeTranslate(); - this.writableModel.setExtension("properties"); - } - - @Override - protected void onTranslate() throws CodeGenException { - super.onTranslate(); - StringBuilder sb = this.writableModel.getData(); - - int cnt = 0; - for(TableModel tblModel : this.model) { - sb.append(String.format("%s# %s\n", (cnt++ == 0)?"":"\n", tblModel.getSheetName())); - for(Map itm : tblModel.toList()) { - String id = itm.get("id"); - if(StringUtil.isNullOrEmpty(id)) continue; - - id = escape(id); - String value = this.escape(itm.get(this.msgLang)); - sb.append(String.format("%s=%s\n", id, value)); - } - } - } - - private String escape(String value) { - if(value == null) return null; - - value = StringEscapeUtils.escapeJava(value); - return value; - } + @Override + protected String getSplitString() { + return "_"; + } + + @Override + protected void onBeforeTranslate() throws CodeGenException { + super.onBeforeTranslate(); + this.writableModel.setExtension("properties"); + } + + @Override + protected void onTranslate() throws CodeGenException { + super.onTranslate(); + StringBuilder sb = this.writableModel.getData(); + + int cnt = 0; + for (TableModel tblModel : this.model) { + sb.append(String.format("%s# %s\n", (cnt++ == 0) ? "" : "\n", tblModel.getSheetName())); + for (Map itm : tblModel.toList()) { + String id = itm.get("id"); + if (StringUtil.isNullOrEmpty(id)) continue; + + id = escape(id); + String value = this.escape(itm.get(this.msgLang)); + sb.append(String.format("%s=%s\n", id, value)); + } + } + } + + private String escape(String value) { + if (value == null) return null; + + value = StringEscapeUtils.escapeJava(value); + return value; + } } diff --git a/src/main/java/com/yanglb/codegen/core/translator/impl/MsgJsonTranslatorImpl.java b/src/main/java/com/yanglb/codegen/core/translator/impl/MsgJsonTranslatorImpl.java index 6df618d..6f08f15 100644 --- a/src/main/java/com/yanglb/codegen/core/translator/impl/MsgJsonTranslatorImpl.java +++ b/src/main/java/com/yanglb/codegen/core/translator/impl/MsgJsonTranslatorImpl.java @@ -1,12 +1,12 @@ /** * Copyright 2015-2023 yanglb.com - * + *

      * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + *

      + * http://www.apache.org/licenses/LICENSE-2.0 + *

      * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -19,52 +19,54 @@ import com.yanglb.codegen.exceptions.CodeGenException; import com.yanglb.codegen.model.TableModel; import com.yanglb.codegen.utils.StringUtil; + import java.util.Map; + import org.json.JSONObject; public class MsgJsonTranslatorImpl extends BaseMsgTranslator { - @Override - protected void onBeforeTranslate() throws CodeGenException { - super.onBeforeTranslate(); - this.writableModel.setExtension("json"); - } + @Override + protected void onBeforeTranslate() throws CodeGenException { + super.onBeforeTranslate(); + this.writableModel.setExtension("json"); + } - private void tblModel2Json(JSONObject json, TableModel tblModel) { - for(Map itm : tblModel.toList()) { - String id = itm.get("id"); - String value = itm.get(this.msgLang); - if(StringUtil.isNullOrEmpty(id)) continue; + private void tblModel2Json(JSONObject json, TableModel tblModel) { + for (Map itm : tblModel.toList()) { + String id = itm.get("id"); + String value = itm.get(this.msgLang); + if (StringUtil.isNullOrEmpty(id)) continue; - json.put(id, value); - } - } + json.put(id, value); + } + } - @Override - protected void onTranslate() throws CodeGenException { - super.onTranslate(); - JSONObject json = new JSONObject(); - StringBuilder sb = this.writableModel.getData(); + @Override + protected void onTranslate() throws CodeGenException { + super.onTranslate(); + JSONObject json = new JSONObject(); + StringBuilder sb = this.writableModel.getData(); - if(this.parameterModel.getOptions().hasOption("combine")) { - // 合并输出 - for(TableModel tblModel : this.model) { - tblModel2Json(json, tblModel); - } - } else { - // 分组输出 - for(TableModel tblModel : this.model) { - JSONObject sub = new JSONObject(); - tblModel2Json(sub, tblModel); + if (this.parameterModel.getOptions().hasOption("combine")) { + // 合并输出 + for (TableModel tblModel : this.model) { + tblModel2Json(json, tblModel); + } + } else { + // 分组输出 + for (TableModel tblModel : this.model) { + JSONObject sub = new JSONObject(); + tblModel2Json(sub, tblModel); - String sheetName = tblModel.getSheetName(); - json.put(sheetName, sub); - } - } + String sheetName = tblModel.getSheetName(); + json.put(sheetName, sub); + } + } - // to JSON string - int indentFactor = 4; - if (parameterModel.getOptions().hasOption("minify")) indentFactor = 0; - sb.append(json.toString(indentFactor)); - } + // to JSON string + int indentFactor = 4; + if (parameterModel.getOptions().hasOption("minify")) indentFactor = 0; + sb.append(json.toString(indentFactor)); + } } diff --git a/src/main/java/com/yanglb/codegen/core/writer/BaseWriter.java b/src/main/java/com/yanglb/codegen/core/writer/BaseWriter.java index 2514a29..47302de 100644 --- a/src/main/java/com/yanglb/codegen/core/writer/BaseWriter.java +++ b/src/main/java/com/yanglb/codegen/core/writer/BaseWriter.java @@ -1,12 +1,12 @@ /** * Copyright 2015-2023 yanglb.com - * + *

      * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + *

      + * http://www.apache.org/licenses/LICENSE-2.0 + *

      * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -18,79 +18,76 @@ import com.yanglb.codegen.exceptions.CodeGenException; import com.yanglb.codegen.model.WritableModel; import com.yanglb.codegen.utils.Resources; + import java.io.File; -public class BaseWriter implements IWriter{ - protected WritableModel writableModel; - - @Override - public void writer(WritableModel writableModel) throws CodeGenException { - this.writableModel = writableModel; - - this.doWriter(); - } - - /** - * 进行写入 - * @throws CodeGenException - */ - private void doWriter() throws CodeGenException{ - // 生成目录 - this.onCreateDir(); - - // 字节编码转换 - this.onCharEncodeTranslator(); - - // 进行写入 - this.onWriter(); - } - - /** - * 生成必要的目录(如包名等) - * @throws CodeGenException - */ - protected void onCreateDir() throws CodeGenException { - String outPath = this.writableModel.getOutputDir(); - outPath = outPath.replace('\\', '/'); - if(outPath.lastIndexOf("/") == outPath.length()-1) { - outPath = outPath.substring(0, outPath.length()-1); - } - - outPath = String.format("%s/%s.%s", - outPath, - this.writableModel.getFileName(), - this.writableModel.getExtension()); - - this.writableModel.setFullPath(outPath); - - File file = new File(outPath); - if(file.isDirectory()) { - // 文件已存在且是目录,不可继续处理 - throw new CodeGenException(String.format(Resources.getString("E_008"), outPath)); - } - - // 目录不存在时创建 - if(!file.getParentFile().exists()) { - if(!file.getParentFile().mkdirs()) { - throw new CodeGenException(String.format(Resources.getString("E_009"), outPath)); - } - } - } - - /** - * 进行写入 - * @throws CodeGenException - */ - protected void onWriter() throws CodeGenException { - // 父类不做任何处理 - } - - /** - * 字符编辑转换(如有必要子类进行实现) - * @throws CodeGenException - */ - protected void onCharEncodeTranslator() throws CodeGenException { - // 子类实现 - } +public class BaseWriter implements IWriter { + protected WritableModel writableModel; + + @Override + public void writer(WritableModel writableModel) throws CodeGenException { + this.writableModel = writableModel; + + this.doWriter(); + } + + /** + * 进行写入 + */ + private void doWriter() throws CodeGenException { + // 生成目录 + this.onCreateDir(); + + // 字节编码转换 + this.onCharEncodeTranslator(); + + // 进行写入 + this.onWriter(); + } + + /** + * 生成必要的目录(如包名等) + */ + protected void onCreateDir() throws CodeGenException { + String outPath = this.writableModel.getOutputDir(); + outPath = outPath.replace('\\', '/'); + if (outPath.lastIndexOf("/") == outPath.length() - 1) { + outPath = outPath.substring(0, outPath.length() - 1); + } + + outPath = String.format("%s/%s.%s", + outPath, + this.writableModel.getFileName(), + this.writableModel.getExtension()); + + this.writableModel.setFullPath(outPath); + + File file = new File(outPath); + if (file.isDirectory()) { + // 文件已存在且是目录,不可继续处理 + throw new CodeGenException(String.format(Resources.getString("E_008"), outPath)); + } + + // 目录不存在时创建 + if (!file.getParentFile().exists()) { + if (!file.getParentFile().mkdirs()) { + throw new CodeGenException(String.format(Resources.getString("E_009"), outPath)); + } + } + } + + /** + * 进行写入 + */ + protected void onWriter() throws CodeGenException { + // 父类不做任何处理 + } + + /** + * 字符编辑转换(如有必要子类进行实现) + */ + protected void onCharEncodeTranslator() throws CodeGenException { + // 子类实现 + } } diff --git a/src/main/java/com/yanglb/codegen/core/writer/IWriter.java b/src/main/java/com/yanglb/codegen/core/writer/IWriter.java index d1ba5f3..a278451 100644 --- a/src/main/java/com/yanglb/codegen/core/writer/IWriter.java +++ b/src/main/java/com/yanglb/codegen/core/writer/IWriter.java @@ -1,12 +1,12 @@ /** * Copyright 2015-2023 yanglb.com - * + *

      * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + *

      + * http://www.apache.org/licenses/LICENSE-2.0 + *

      * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -19,11 +19,9 @@ import com.yanglb.codegen.model.WritableModel; public interface IWriter { - - /** - * 将WritableModel对象写入文件中 - * @param writableModel - * @throws CodeGenException - */ + + /** + * 将WritableModel对象写入文件中 + */ void writer(WritableModel writableModel) throws CodeGenException; } diff --git a/src/main/java/com/yanglb/codegen/core/writer/impl/AsciiWriterImpl.java b/src/main/java/com/yanglb/codegen/core/writer/impl/AsciiWriterImpl.java index af42203..611840f 100644 --- a/src/main/java/com/yanglb/codegen/core/writer/impl/AsciiWriterImpl.java +++ b/src/main/java/com/yanglb/codegen/core/writer/impl/AsciiWriterImpl.java @@ -1,12 +1,12 @@ /** * Copyright 2015-2023 yanglb.com - * + *

      * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + *

      + * http://www.apache.org/licenses/LICENSE-2.0 + *

      * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -18,6 +18,7 @@ import com.yanglb.codegen.core.writer.BaseWriter; import com.yanglb.codegen.exceptions.CodeGenException; import com.yanglb.codegen.utils.Resources; + import java.io.FileOutputStream; import java.io.IOException; import java.nio.charset.StandardCharsets; @@ -29,24 +30,26 @@ * */ public class AsciiWriterImpl extends BaseWriter { - - @Override - protected void onCharEncodeTranslator() throws CodeGenException { - } - @Override - protected void onWriter() throws CodeGenException { - FileOutputStream fos = null; - try { - fos = new FileOutputStream(this.writableModel.getFullPath()); - fos.write(this.writableModel.getData().toString().getBytes(StandardCharsets.US_ASCII)); - fos.flush(); - - } catch (IOException e) { - throw new CodeGenException(String.format(Resources.getString("E_007"), e.getMessage())); - } finally { - try{if(fos != null) fos.close(); - } catch (Exception e){} - } - } + @Override + protected void onCharEncodeTranslator() throws CodeGenException { + } + + @Override + protected void onWriter() throws CodeGenException { + FileOutputStream fos = null; + try { + fos = new FileOutputStream(this.writableModel.getFullPath()); + fos.write(this.writableModel.getData().toString().getBytes(StandardCharsets.US_ASCII)); + fos.flush(); + + } catch (IOException e) { + throw new CodeGenException(String.format(Resources.getString("E_007"), e.getMessage())); + } finally { + try { + if (fos != null) fos.close(); + } catch (Exception e) { + } + } + } } diff --git a/src/main/java/com/yanglb/codegen/core/writer/impl/Utf8WriterImpl.java b/src/main/java/com/yanglb/codegen/core/writer/impl/Utf8WriterImpl.java index f629ac9..bb182f3 100644 --- a/src/main/java/com/yanglb/codegen/core/writer/impl/Utf8WriterImpl.java +++ b/src/main/java/com/yanglb/codegen/core/writer/impl/Utf8WriterImpl.java @@ -1,12 +1,12 @@ /** * Copyright 2015-2023 yanglb.com - * + *

      * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + *

      + * http://www.apache.org/licenses/LICENSE-2.0 + *

      * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -18,6 +18,7 @@ import com.yanglb.codegen.core.writer.BaseWriter; import com.yanglb.codegen.exceptions.CodeGenException; import com.yanglb.codegen.utils.Resources; + import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; @@ -31,24 +32,28 @@ */ public class Utf8WriterImpl extends BaseWriter { - @Override - protected void onWriter() throws CodeGenException { - FileOutputStream fos = null; - OutputStreamWriter osw = null; - try { - fos = new FileOutputStream(this.writableModel.getFullPath()); - osw = new OutputStreamWriter(fos, StandardCharsets.UTF_8); - osw.write(this.writableModel.getData().toString()); - osw.flush(); - - } catch (IOException e) { - throw new CodeGenException(String.format(Resources.getString("E_007"), e.getMessage())); - } finally { - try{if(osw != null) osw.close(); - } catch (Exception e){} - - try{if(fos != null) fos.close(); - } catch (Exception e){} - } - } + @Override + protected void onWriter() throws CodeGenException { + FileOutputStream fos = null; + OutputStreamWriter osw = null; + try { + fos = new FileOutputStream(this.writableModel.getFullPath()); + osw = new OutputStreamWriter(fos, StandardCharsets.UTF_8); + osw.write(this.writableModel.getData().toString()); + osw.flush(); + + } catch (IOException e) { + throw new CodeGenException(String.format(Resources.getString("E_007"), e.getMessage())); + } finally { + try { + if (osw != null) osw.close(); + } catch (Exception e) { + } + + try { + if (fos != null) fos.close(); + } catch (Exception e) { + } + } + } } diff --git a/src/main/java/com/yanglb/codegen/exceptions/CodeGenException.java b/src/main/java/com/yanglb/codegen/exceptions/CodeGenException.java index 9e9750d..5df0c88 100644 --- a/src/main/java/com/yanglb/codegen/exceptions/CodeGenException.java +++ b/src/main/java/com/yanglb/codegen/exceptions/CodeGenException.java @@ -1,12 +1,12 @@ /** * Copyright 2015-2023 yanglb.com - * + *

      * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + *

      + * http://www.apache.org/licenses/LICENSE-2.0 + *

      * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -16,7 +16,7 @@ package com.yanglb.codegen.exceptions; public class CodeGenException extends Exception { - public CodeGenException(String errMsg) { - super(errMsg); - } + public CodeGenException(String errMsg) { + super(errMsg); + } } diff --git a/src/main/java/com/yanglb/codegen/exceptions/ParamaCheckException.java b/src/main/java/com/yanglb/codegen/exceptions/ParamaCheckException.java index f8cbfdc..6e1d573 100644 --- a/src/main/java/com/yanglb/codegen/exceptions/ParamaCheckException.java +++ b/src/main/java/com/yanglb/codegen/exceptions/ParamaCheckException.java @@ -1,12 +1,12 @@ /** * Copyright 2015-2023 yanglb.com - * + *

      * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + *

      + * http://www.apache.org/licenses/LICENSE-2.0 + *

      * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -16,11 +16,11 @@ package com.yanglb.codegen.exceptions; public class ParamaCheckException extends Exception { - public ParamaCheckException() { - super("您输入的参数不正确,请使用 --help 命令查看用法。"); - } - - public ParamaCheckException(String errMsg) { - super(errMsg); - } + public ParamaCheckException() { + super("您输入的参数不正确,请使用 --help 命令查看用法。"); + } + + public ParamaCheckException(String errMsg) { + super(errMsg); + } } diff --git a/src/main/java/com/yanglb/codegen/exceptions/UnImplementException.java b/src/main/java/com/yanglb/codegen/exceptions/UnImplementException.java index 7cc6e53..f052776 100644 --- a/src/main/java/com/yanglb/codegen/exceptions/UnImplementException.java +++ b/src/main/java/com/yanglb/codegen/exceptions/UnImplementException.java @@ -1,12 +1,12 @@ /** * Copyright 2015-2023 yanglb.com - * + *

      * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + *

      + * http://www.apache.org/licenses/LICENSE-2.0 + *

      * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -16,7 +16,7 @@ package com.yanglb.codegen.exceptions; public class UnImplementException extends Exception { - public UnImplementException() { - super("该方法未实现!"); - } + public UnImplementException() { + super("该方法未实现!"); + } } diff --git a/src/main/java/com/yanglb/codegen/model/BaseModel.java b/src/main/java/com/yanglb/codegen/model/BaseModel.java index 3db64f1..20dceab 100644 --- a/src/main/java/com/yanglb/codegen/model/BaseModel.java +++ b/src/main/java/com/yanglb/codegen/model/BaseModel.java @@ -1,12 +1,12 @@ /** * Copyright 2015-2023 yanglb.com - * + *

      * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + *

      + * http://www.apache.org/licenses/LICENSE-2.0 + *

      * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -18,36 +18,36 @@ import java.util.Date; public class BaseModel { - // Excel Sheet名 - private String sheetName; - - // Excel 文件名 - private String excelFileName; - - // 生成日期 - private Date generationDate = new Date(); - - public String getSheetName() { - return sheetName; - } - - public void setSheetName(String sheetName) { - this.sheetName = sheetName; - } - - public String getExcelFileName() { - return excelFileName; - } - - public void setExcelFileName(String excelFileName) { - this.excelFileName = excelFileName; - } - - public Date getGenerationDate() { - return generationDate; - } - - public void setGenerationDate(Date generationDate) { - this.generationDate = generationDate; - } + // Excel Sheet名 + private String sheetName; + + // Excel 文件名 + private String excelFileName; + + // 生成日期 + private Date generationDate = new Date(); + + public String getSheetName() { + return sheetName; + } + + public void setSheetName(String sheetName) { + this.sheetName = sheetName; + } + + public String getExcelFileName() { + return excelFileName; + } + + public void setExcelFileName(String excelFileName) { + this.excelFileName = excelFileName; + } + + public Date getGenerationDate() { + return generationDate; + } + + public void setGenerationDate(Date generationDate) { + this.generationDate = generationDate; + } } diff --git a/src/main/java/com/yanglb/codegen/model/CmdModel.java b/src/main/java/com/yanglb/codegen/model/CmdModel.java index 0ad1a62..2733420 100644 --- a/src/main/java/com/yanglb/codegen/model/CmdModel.java +++ b/src/main/java/com/yanglb/codegen/model/CmdModel.java @@ -1,12 +1,12 @@ /** * Copyright 2015-2023 yanglb.com - * + *

      * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + *

      + * http://www.apache.org/licenses/LICENSE-2.0 + *

      * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -25,7 +25,8 @@ public class CmdModel { public CmdModel() { } - public CmdModel(Map values){ + + public CmdModel(Map values) { parser = values.get("parser"); generator = values.get("generator"); reader = values.get("reader"); diff --git a/src/main/java/com/yanglb/codegen/model/DdlDetail.java b/src/main/java/com/yanglb/codegen/model/DdlDetail.java index 0b9a181..6344c6f 100644 --- a/src/main/java/com/yanglb/codegen/model/DdlDetail.java +++ b/src/main/java/com/yanglb/codegen/model/DdlDetail.java @@ -1,12 +1,12 @@ /** * Copyright 2015-2023 yanglb.com - * + *

      * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + *

      + * http://www.apache.org/licenses/LICENSE-2.0 + *

      * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -16,224 +16,224 @@ package com.yanglb.codegen.model; public class DdlDetail extends BaseModel { - // PO 属性 - // 字段名 - private String fieldName; - // 属性名 - private String poName; - // Java/.NET类型 - private String poType; - - // 表属性 - // 列名 - private String colName; - // 类型 - private String colType; - // 长度 - private Integer colLength; - // 精度 - private Integer colPrecision; - // 主键 - private boolean colKey; - // 允许NULL - private boolean colNullable; - // 索引 - private String colIndex; - // 外键 - private String colForeign; - // 默认值 - private String colDefault; - // 约束信息 - private String colUnique; - // 约束信息 - private Integer colAutoIncrement; - - // 说明 - private String description; - - public String getColUnique() { - return colUnique; - } - - public void setColUnique(String colUnique) { - this.colUnique = colUnique; - } - - public Integer getColAutoIncrement() { - return colAutoIncrement; - } - - public void setColAutoIncrement(Integer colAutoIncrement) { - this.colAutoIncrement = colAutoIncrement; - } - - public String getColIndex() { - return colIndex; - } - - public void setColIndex(String colIndex) { - this.colIndex = colIndex; - } - - public String getColForeign() { - return colForeign; - } - - public void setColForeign(String colForeign) { - this.colForeign = colForeign; - } - - /** - * @return the fieldName - */ - public String getFieldName() { - return fieldName; - } - - /** - * @param fieldName the fieldName to set - */ - public void setFieldName(String fieldName) { - this.fieldName = fieldName; - } - - /** - * @return the poName - */ - public String getPoName() { - return poName; - } - - /** - * @param poName the poName to set - */ - public void setPoName(String poName) { - this.poName = poName; - } - - /** - * @return the poType - */ - public String getPoType() { - return poType; - } - - /** - * @param poType the poType to set - */ - public void setPoType(String poType) { - this.poType = poType; - } - - /** - * @return the colName - */ - public String getColName() { - return colName; - } - - /** - * @param colName the colName to set - */ - public void setColName(String colName) { - this.colName = colName; - } - - /** - * @return the colType - */ - public String getColType() { - return colType; - } - - /** - * @param colType the colType to set - */ - public void setColType(String colType) { - this.colType = colType; - } - - /** - * @return the colLength - */ - public Integer getColLength() { - return colLength; - } - - /** - * @param colLength the colLength to set - */ - public void setColLength(Integer colLength) { - this.colLength = colLength; - } - - /** - * @return the colPrecision - */ - public Integer getColPrecision() { - return colPrecision; - } - - /** - * @param colPrecision the colPrecision to set - */ - public void setColPrecision(Integer colPrecision) { - this.colPrecision = colPrecision; - } - - /** - * @return the colKey - */ - public boolean isColKey() { - return colKey; - } - - /** - * @param colKey the colKey to set - */ - public void setColKey(boolean colKey) { - this.colKey = colKey; - } - - /** - * @return the colNullable - */ - public boolean isColNullable() { - return colNullable; - } - - /** - * @param colNullable the colNullable to set - */ - public void setColNullable(boolean colNullable) { - this.colNullable = colNullable; - } - - /** - * @return the colDefault - */ - public String getColDefault() { - return colDefault; - } - - /** - * @param colDefault the colDefault to set - */ - public void setColDefault(String colDefault) { - this.colDefault = colDefault; - } - - /** - * @return the description - */ - public String getDescription() { - return description; - } - - /** - * @param description the description to set - */ - public void setDescription(String description) { - this.description = description; - } + // PO 属性 + // 字段名 + private String fieldName; + // 属性名 + private String poName; + // Java/.NET类型 + private String poType; + + // 表属性 + // 列名 + private String colName; + // 类型 + private String colType; + // 长度 + private Integer colLength; + // 精度 + private Integer colPrecision; + // 主键 + private boolean colKey; + // 允许NULL + private boolean colNullable; + // 索引 + private String colIndex; + // 外键 + private String colForeign; + // 默认值 + private String colDefault; + // 约束信息 + private String colUnique; + // 约束信息 + private Integer colAutoIncrement; + + // 说明 + private String description; + + public String getColUnique() { + return colUnique; + } + + public void setColUnique(String colUnique) { + this.colUnique = colUnique; + } + + public Integer getColAutoIncrement() { + return colAutoIncrement; + } + + public void setColAutoIncrement(Integer colAutoIncrement) { + this.colAutoIncrement = colAutoIncrement; + } + + public String getColIndex() { + return colIndex; + } + + public void setColIndex(String colIndex) { + this.colIndex = colIndex; + } + + public String getColForeign() { + return colForeign; + } + + public void setColForeign(String colForeign) { + this.colForeign = colForeign; + } + + /** + * @return the fieldName + */ + public String getFieldName() { + return fieldName; + } + + /** + * @param fieldName the fieldName to set + */ + public void setFieldName(String fieldName) { + this.fieldName = fieldName; + } + + /** + * @return the poName + */ + public String getPoName() { + return poName; + } + + /** + * @param poName the poName to set + */ + public void setPoName(String poName) { + this.poName = poName; + } + + /** + * @return the poType + */ + public String getPoType() { + return poType; + } + + /** + * @param poType the poType to set + */ + public void setPoType(String poType) { + this.poType = poType; + } + + /** + * @return the colName + */ + public String getColName() { + return colName; + } + + /** + * @param colName the colName to set + */ + public void setColName(String colName) { + this.colName = colName; + } + + /** + * @return the colType + */ + public String getColType() { + return colType; + } + + /** + * @param colType the colType to set + */ + public void setColType(String colType) { + this.colType = colType; + } + + /** + * @return the colLength + */ + public Integer getColLength() { + return colLength; + } + + /** + * @param colLength the colLength to set + */ + public void setColLength(Integer colLength) { + this.colLength = colLength; + } + + /** + * @return the colPrecision + */ + public Integer getColPrecision() { + return colPrecision; + } + + /** + * @param colPrecision the colPrecision to set + */ + public void setColPrecision(Integer colPrecision) { + this.colPrecision = colPrecision; + } + + /** + * @return the colKey + */ + public boolean isColKey() { + return colKey; + } + + /** + * @param colKey the colKey to set + */ + public void setColKey(boolean colKey) { + this.colKey = colKey; + } + + /** + * @return the colNullable + */ + public boolean isColNullable() { + return colNullable; + } + + /** + * @param colNullable the colNullable to set + */ + public void setColNullable(boolean colNullable) { + this.colNullable = colNullable; + } + + /** + * @return the colDefault + */ + public String getColDefault() { + return colDefault; + } + + /** + * @param colDefault the colDefault to set + */ + public void setColDefault(String colDefault) { + this.colDefault = colDefault; + } + + /** + * @return the description + */ + public String getDescription() { + return description; + } + + /** + * @param description the description to set + */ + public void setDescription(String description) { + this.description = description; + } } diff --git a/src/main/java/com/yanglb/codegen/model/DdlModel.java b/src/main/java/com/yanglb/codegen/model/DdlModel.java index 05ad0dd..7f2b02b 100644 --- a/src/main/java/com/yanglb/codegen/model/DdlModel.java +++ b/src/main/java/com/yanglb/codegen/model/DdlModel.java @@ -1,12 +1,12 @@ /** * Copyright 2015-2023 yanglb.com - * + *

      * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + *

      + * http://www.apache.org/licenses/LICENSE-2.0 + *

      * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -18,123 +18,142 @@ import java.util.List; public class DdlModel extends BaseModel { - private String nameSpace; - private String name; - private String author; - private String responsibility; - private String description; - private String version; - private String renewDate; - private String index; - private String foreign; - private List detail; - - public String getForeign() { - return foreign; - } - public void setForeign(String foreign) { - this.foreign = foreign; - } - /** - * @return the nameSpace - */ - public String getNameSpace() { - return nameSpace; - } - /** - * @param nameSpace the nameSpace to set - */ - public void setNameSpace(String nameSpace) { - this.nameSpace = nameSpace; - } - /** - * @return the name - */ - public String getName() { - return name; - } - /** - * @param name the name to set - */ - public void setName(String name) { - this.name = name; - } - /** - * @return the author - */ - public String getAuthor() { - return author; - } - /** - * @param author the author to set - */ - public void setAuthor(String author) { - this.author = author; - } - /** - * @return the description - */ - public String getDescription() { - return description; - } - /** - * @param description the description to set - */ - public void setDescription(String description) { - this.description = description; - } - /** - * @return the version - */ - public String getVersion() { - return version; - } - /** - * @param version the version to set - */ - public void setVersion(String version) { - this.version = version; - } - /** - * @return the renewDate - */ - public String getRenewDate() { - return renewDate; - } - /** - * @param renewDate the renewDate to set - */ - public void setRenewDate(String renewDate) { - this.renewDate = renewDate; - } - /** - * @return the index - */ - public String getIndex() { - return index; - } - /** - * @param index the index to set - */ - public void setIndex(String index) { - this.index = index; - } - /** - * @return the detail - */ - public List getDetail() { - return detail; - } - /** - * @param detail the detail to set - */ - public void setDetail(List detail) { - this.detail = detail; - } - public String getResponsibility() { - return responsibility; - } - public void setResponsibility(String responsibility) { - this.responsibility = responsibility; - } + private String nameSpace; + private String name; + private String author; + private String responsibility; + private String description; + private String version; + private String renewDate; + private String index; + private String foreign; + private List detail; + + public String getForeign() { + return foreign; + } + + public void setForeign(String foreign) { + this.foreign = foreign; + } + + /** + * @return the nameSpace + */ + public String getNameSpace() { + return nameSpace; + } + + /** + * @param nameSpace the nameSpace to set + */ + public void setNameSpace(String nameSpace) { + this.nameSpace = nameSpace; + } + + /** + * @return the name + */ + public String getName() { + return name; + } + + /** + * @param name the name to set + */ + public void setName(String name) { + this.name = name; + } + + /** + * @return the author + */ + public String getAuthor() { + return author; + } + + /** + * @param author the author to set + */ + public void setAuthor(String author) { + this.author = author; + } + + /** + * @return the description + */ + public String getDescription() { + return description; + } + + /** + * @param description the description to set + */ + public void setDescription(String description) { + this.description = description; + } + + /** + * @return the version + */ + public String getVersion() { + return version; + } + + /** + * @param version the version to set + */ + public void setVersion(String version) { + this.version = version; + } + + /** + * @return the renewDate + */ + public String getRenewDate() { + return renewDate; + } + + /** + * @param renewDate the renewDate to set + */ + public void setRenewDate(String renewDate) { + this.renewDate = renewDate; + } + + /** + * @return the index + */ + public String getIndex() { + return index; + } + + /** + * @param index the index to set + */ + public void setIndex(String index) { + this.index = index; + } + + /** + * @return the detail + */ + public List getDetail() { + return detail; + } + + /** + * @param detail the detail to set + */ + public void setDetail(List detail) { + this.detail = detail; + } + + public String getResponsibility() { + return responsibility; + } + + public void setResponsibility(String responsibility) { + this.responsibility = responsibility; + } } diff --git a/src/main/java/com/yanglb/codegen/model/DmlModel.java b/src/main/java/com/yanglb/codegen/model/DmlModel.java index 7456960..e9cb372 100644 --- a/src/main/java/com/yanglb/codegen/model/DmlModel.java +++ b/src/main/java/com/yanglb/codegen/model/DmlModel.java @@ -1,12 +1,12 @@ /** * Copyright 2015-2023 yanglb.com - * + *

      * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + *

      + * http://www.apache.org/licenses/LICENSE-2.0 + *

      * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -16,63 +16,78 @@ package com.yanglb.codegen.model; public class DmlModel extends BaseModel { - private String nameSpace; - private String name; - private String author; - private String description; - private String version; - private String renewDate; - private TableModel dmlData; - private String responsibility; - - public String getNameSpace() { - return nameSpace; - } - public void setNameSpace(String nameSpace) { - this.nameSpace = nameSpace; - } - public String getName() { - return name; - } - public void setName(String name) { - this.name = name; - } - public String getAuthor() { - return author; - } - public void setAuthor(String author) { - this.author = author; - } - public String getDescription() { - return description; - } - public void setDescription(String description) { - this.description = description; - } - public String getVersion() { - return version; - } - public void setVersion(String version) { - this.version = version; - } - public String getRenewDate() { - return renewDate; - } - public void setRenewDate(String renewDate) { - this.renewDate = renewDate; - } - public TableModel getDmlData() { - return dmlData; - } - public void setDmlData(TableModel dmlData) { - this.dmlData = dmlData; - } - public String getResponsibility() { - return responsibility; - } - public void setResponsibility(String responsibility) { - this.responsibility = responsibility; - } - - + private String nameSpace; + private String name; + private String author; + private String description; + private String version; + private String renewDate; + private TableModel dmlData; + private String responsibility; + + public String getNameSpace() { + return nameSpace; + } + + public void setNameSpace(String nameSpace) { + this.nameSpace = nameSpace; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getAuthor() { + return author; + } + + public void setAuthor(String author) { + this.author = author; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public String getVersion() { + return version; + } + + public void setVersion(String version) { + this.version = version; + } + + public String getRenewDate() { + return renewDate; + } + + public void setRenewDate(String renewDate) { + this.renewDate = renewDate; + } + + public TableModel getDmlData() { + return dmlData; + } + + public void setDmlData(TableModel dmlData) { + this.dmlData = dmlData; + } + + public String getResponsibility() { + return responsibility; + } + + public void setResponsibility(String responsibility) { + this.responsibility = responsibility; + } + + } diff --git a/src/main/java/com/yanglb/codegen/model/ForeignDetailModel.java b/src/main/java/com/yanglb/codegen/model/ForeignDetailModel.java index a2c39cc..80edca3 100644 --- a/src/main/java/com/yanglb/codegen/model/ForeignDetailModel.java +++ b/src/main/java/com/yanglb/codegen/model/ForeignDetailModel.java @@ -1,12 +1,12 @@ /** * Copyright 2015-2023 yanglb.com - * + *

      * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + *

      + * http://www.apache.org/licenses/LICENSE-2.0 + *

      * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,38 +17,38 @@ public class ForeignDetailModel { - // 外键列模型 - private DdlDetail ddlDetail; - - // 外键表模型 - private DdlModel foreignDdlModel; - - // 外键表主键列模型 - private DdlDetail foreignDdlDetail; - - public DdlDetail getDdlDetail() { - return ddlDetail; - } - - public void setDdlDetail(DdlDetail ddlDetail) { - this.ddlDetail = ddlDetail; - } - - public DdlModel getForeignDdlModel() { - return foreignDdlModel; - } - - public void setForeignDdlModel(DdlModel foreignDdlModel) { - this.foreignDdlModel = foreignDdlModel; - } - - public DdlDetail getForeignDdlDetail() { - return foreignDdlDetail; - } - - public void setForeignDdlDetail(DdlDetail foreignDdlDetail) { - this.foreignDdlDetail = foreignDdlDetail; - } - - + // 外键列模型 + private DdlDetail ddlDetail; + + // 外键表模型 + private DdlModel foreignDdlModel; + + // 外键表主键列模型 + private DdlDetail foreignDdlDetail; + + public DdlDetail getDdlDetail() { + return ddlDetail; + } + + public void setDdlDetail(DdlDetail ddlDetail) { + this.ddlDetail = ddlDetail; + } + + public DdlModel getForeignDdlModel() { + return foreignDdlModel; + } + + public void setForeignDdlModel(DdlModel foreignDdlModel) { + this.foreignDdlModel = foreignDdlModel; + } + + public DdlDetail getForeignDdlDetail() { + return foreignDdlDetail; + } + + public void setForeignDdlDetail(DdlDetail foreignDdlDetail) { + this.foreignDdlDetail = foreignDdlDetail; + } + + } diff --git a/src/main/java/com/yanglb/codegen/model/ForeignModel.java b/src/main/java/com/yanglb/codegen/model/ForeignModel.java index 4be4b9e..4a6a02d 100644 --- a/src/main/java/com/yanglb/codegen/model/ForeignModel.java +++ b/src/main/java/com/yanglb/codegen/model/ForeignModel.java @@ -1,12 +1,12 @@ /** * Copyright 2015-2023 yanglb.com - * + *

      * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + *

      + * http://www.apache.org/licenses/LICENSE-2.0 + *

      * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -18,27 +18,25 @@ import java.util.List; public class ForeignModel { - // 表模型 - private DdlModel ddlModel; - - // 外键列(每一外键一条数据,联合主键时该列表才可能有多条数据) - private List foreignColumns; + // 表模型 + private DdlModel ddlModel; - public DdlModel getDdlModel() { - return ddlModel; - } + // 外键列(每一外键一条数据,联合主键时该列表才可能有多条数据) + private List foreignColumns; - public void setDdlModel(DdlModel ddlModel) { - this.ddlModel = ddlModel; - } + public DdlModel getDdlModel() { + return ddlModel; + } - public List getForeignColumns() { - return foreignColumns; - } + public void setDdlModel(DdlModel ddlModel) { + this.ddlModel = ddlModel; + } - public void setForeignColumns(List foreignColumns) { - this.foreignColumns = foreignColumns; - } - - + public List getForeignColumns() { + return foreignColumns; + } + + public void setForeignColumns(List foreignColumns) { + this.foreignColumns = foreignColumns; + } } diff --git a/src/main/java/com/yanglb/codegen/model/OptionModel.java b/src/main/java/com/yanglb/codegen/model/OptionModel.java index 4d95e9d..e9c1de8 100644 --- a/src/main/java/com/yanglb/codegen/model/OptionModel.java +++ b/src/main/java/com/yanglb/codegen/model/OptionModel.java @@ -1,12 +1,12 @@ /** * Copyright 2015-2023 yanglb.com - * + *

      * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + *

      + * http://www.apache.org/licenses/LICENSE-2.0 + *

      * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -16,26 +16,31 @@ package com.yanglb.codegen.model; public class OptionModel { - private String name; - private String value; - private boolean necessary; - - public String getName() { - return name; - } - public void setName(String name) { - this.name = name; - } - public String getValue() { - return value; - } - public void setValue(String value) { - this.value = value; - } - public boolean isNecessary() { - return necessary; - } - public void setNecessary(boolean necessary) { - this.necessary = necessary; - } + private String name; + private String value; + private boolean necessary; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } + + public boolean isNecessary() { + return necessary; + } + + public void setNecessary(boolean necessary) { + this.necessary = necessary; + } } diff --git a/src/main/java/com/yanglb/codegen/model/ParameterModel.java b/src/main/java/com/yanglb/codegen/model/ParameterModel.java index 7bd22a3..e888fd6 100644 --- a/src/main/java/com/yanglb/codegen/model/ParameterModel.java +++ b/src/main/java/com/yanglb/codegen/model/ParameterModel.java @@ -1,12 +1,12 @@ /** * Copyright 2015-2023 yanglb.com - * + *

      * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + *

      + * http://www.apache.org/licenses/LICENSE-2.0 + *

      * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -18,51 +18,53 @@ import org.apache.commons.cli.CommandLine; public class ParameterModel { - private String cmd; - private String file; - CommandLine options; - CmdModel cmdModel; + private String cmd; + private String file; + CommandLine options; + CmdModel cmdModel; - public String[] getSheets() { - return options.getOptionValues("sheets"); - } - public String getOptDir() { - return options.getOptionValue("out", "out"); - } - public String getFileName() { - if (!options.hasOption("fn")) return null; - return options.getOptionValue("fn", ""); - } + public String[] getSheets() { + return options.getOptionValues("sheets"); + } - public String getCmd() { - return cmd; - } + public String getOptDir() { + return options.getOptionValue("out", "out"); + } - public void setCmd(String cmd) { - this.cmd = cmd; - } + public String getFileName() { + if (!options.hasOption("fn")) return null; + return options.getOptionValue("fn", ""); + } - public String getFile() { - return file; - } + public String getCmd() { + return cmd; + } - public void setFile(String file) { - this.file = file; - } + public void setCmd(String cmd) { + this.cmd = cmd; + } - public CommandLine getOptions() { - return options; - } + public String getFile() { + return file; + } - public void setOptions(CommandLine options) { - this.options = options; - } + public void setFile(String file) { + this.file = file; + } - public CmdModel getCmdModel() { - return cmdModel; - } + public CommandLine getOptions() { + return options; + } - public void setCmdModel(CmdModel cmdModel) { - this.cmdModel = cmdModel; - } + public void setOptions(CommandLine options) { + this.options = options; + } + + public CmdModel getCmdModel() { + return cmdModel; + } + + public void setCmdModel(CmdModel cmdModel) { + this.cmdModel = cmdModel; + } } diff --git a/src/main/java/com/yanglb/codegen/model/TableModel.java b/src/main/java/com/yanglb/codegen/model/TableModel.java index 4274d7c..f0c8a67 100644 --- a/src/main/java/com/yanglb/codegen/model/TableModel.java +++ b/src/main/java/com/yanglb/codegen/model/TableModel.java @@ -1,12 +1,12 @@ /** * Copyright 2015-2023 yanglb.com - * + *

      * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + *

      + * http://www.apache.org/licenses/LICENSE-2.0 + *

      * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -20,46 +20,46 @@ import java.util.Map; public class TableModel extends BaseModel { - private final List

        > metaData; - private String[] columns; - - public TableModel() { - this.columns = null; - this.metaData = new ArrayList
          >(); - } - - public Map getAt(int index) { - return this.metaData.get(index); - } - - public void insert(Map row) { - this.metaData.add(row); - } - - public void removeAt(int index) { - this.metaData.remove(index); - } - - public void clear() { - this.metaData.clear(); - } - - public int size() { - return this.metaData.size(); - } - - public List
            > toList() { - return this.metaData; - } - /** - * 获取列对象 - * @return - */ - public String[] getColumns() { - return this.columns; - } - - public void setColumns(String[] columns) { - this.columns = columns; - } + private final List
              > metaData; + private String[] columns; + + public TableModel() { + this.columns = null; + this.metaData = new ArrayList
                >(); + } + + public Map getAt(int index) { + return this.metaData.get(index); + } + + public void insert(Map row) { + this.metaData.add(row); + } + + public void removeAt(int index) { + this.metaData.remove(index); + } + + public void clear() { + this.metaData.clear(); + } + + public int size() { + return this.metaData.size(); + } + + public List
                  > toList() { + return this.metaData; + } + + /** + * 获取列对象 + */ + public String[] getColumns() { + return this.columns; + } + + public void setColumns(String[] columns) { + this.columns = columns; + } } diff --git a/src/main/java/com/yanglb/codegen/model/WritableModel.java b/src/main/java/com/yanglb/codegen/model/WritableModel.java index 07a39f8..6296a07 100644 --- a/src/main/java/com/yanglb/codegen/model/WritableModel.java +++ b/src/main/java/com/yanglb/codegen/model/WritableModel.java @@ -1,12 +1,12 @@ /** * Copyright 2015-2023 yanglb.com - * + *

                  * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + *

                  + * http://www.apache.org/licenses/LICENSE-2.0 + *

                  * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -16,85 +16,94 @@ package com.yanglb.codegen.model; public class WritableModel { - private String encode; - private String extension; - private String fileName; - private String outputDir; - private String fullPath; - private StringBuilder data; - - - /** - * @return the fullPath - */ - public String getFullPath() { - return fullPath; - } - /** - * @param fullPath the fullPath to set - */ - public void setFullPath(String fullPath) { - this.fullPath = fullPath; - } - /** - * @return the outputDir - */ - public String getOutputDir() { - return outputDir; - } - /** - * @param outputDir the outputDir to set - */ - public void setOutputDir(String outputDir) { - this.outputDir = outputDir; - } - /** - * @return the encode - */ - public String getEncode() { - return encode; - } - /** - * @param encode the encode to set - */ - public void setEncode(String encode) { - this.encode = encode; - } - /** - * @return the extension - */ - public String getExtension() { - return extension; - } - /** - * @param extension the extension to set - */ - public void setExtension(String extension) { - this.extension = extension; - } - /** - * @return the data - */ - public StringBuilder getData() { - return data; - } - /** - * @param data the data to set - */ - public void setData(StringBuilder data) { - this.data = data; - } - /** - * @return the fileName - */ - public String getFileName() { - return fileName; - } - /** - * @param fileName the fileName to set - */ - public void setFileName(String fileName) { - this.fileName = fileName; - } - + private String encode; + private String extension; + private String fileName; + private String outputDir; + private String fullPath; + private StringBuilder data; + + /** + * @return the fullPath + */ + public String getFullPath() { + return fullPath; + } + + /** + * @param fullPath the fullPath to set + */ + public void setFullPath(String fullPath) { + this.fullPath = fullPath; + } + + /** + * @return the outputDir + */ + public String getOutputDir() { + return outputDir; + } + + /** + * @param outputDir the outputDir to set + */ + public void setOutputDir(String outputDir) { + this.outputDir = outputDir; + } + + /** + * @return the encode + */ + public String getEncode() { + return encode; + } + + /** + * @param encode the encode to set + */ + public void setEncode(String encode) { + this.encode = encode; + } + + /** + * @return the extension + */ + public String getExtension() { + return extension; + } + + /** + * @param extension the extension to set + */ + public void setExtension(String extension) { + this.extension = extension; + } + + /** + * @return the data + */ + public StringBuilder getData() { + return data; + } + + /** + * @param data the data to set + */ + public void setData(StringBuilder data) { + this.data = data; + } + + /** + * @return the fileName + */ + public String getFileName() { + return fileName; + } + + /** + * @param fileName the fileName to set + */ + public void setFileName(String fileName) { + this.fileName = fileName; + } } diff --git a/src/main/java/com/yanglb/codegen/shell/CGShell.java b/src/main/java/com/yanglb/codegen/shell/CGShell.java index 98c526d..3c1fff7 100644 --- a/src/main/java/com/yanglb/codegen/shell/CGShell.java +++ b/src/main/java/com/yanglb/codegen/shell/CGShell.java @@ -1,12 +1,12 @@ /** * Copyright 2015-2023 yanglb.com - * + *

                  * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + *

                  + * http://www.apache.org/licenses/LICENSE-2.0 + *

                  * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -23,34 +23,32 @@ import com.yanglb.codegen.model.ParameterModel; public class CGShell { - public boolean invoke(String[] args) { - IParser parser = IParser.parserByArgs(args); - ParameterModel model; - try { - model = parser.parsing(); - if (model == null) return true; - } catch (IllegalArgumentException ex) { - System.out.println(ex.getMessage()); - parser.printHelp(); - return false; - } + public boolean invoke(String[] args) { + IParser parser = IParser.parserByArgs(args); + ParameterModel model; + try { + model = parser.parsing(); + if (model == null) return true; + } catch (IllegalArgumentException ex) { + System.out.println(ex.getMessage()); + parser.printHelp(); + return false; + } - // 执行 - try { - IGenerator generator = GenFactory.createByName(model.getCmdModel().getGenerator()); - generator.invoke(model); - } - catch (ParamaCheckException | CodeGenException e) { - System.out.println("生成失败!"); - System.out.println(e.getMessage()); - return false; - } - catch (Exception e) { - System.out.println(e.getMessage()); - return false; - } + // 执行 + try { + IGenerator generator = GenFactory.createByName(model.getCmdModel().getGenerator()); + generator.invoke(model); + } catch (ParamaCheckException | CodeGenException e) { + System.out.println("生成失败!"); + System.out.println(e.getMessage()); + return false; + } catch (Exception e) { + System.out.println(e.getMessage()); + return false; + } - System.out.println("代码生成成功!"); - return true; - } + System.out.println("代码生成成功!"); + return true; + } } diff --git a/src/main/java/com/yanglb/codegen/utils/Conf.java b/src/main/java/com/yanglb/codegen/utils/Conf.java index cf1aad0..1c455d9 100644 --- a/src/main/java/com/yanglb/codegen/utils/Conf.java +++ b/src/main/java/com/yanglb/codegen/utils/Conf.java @@ -1,12 +1,12 @@ /** * Copyright 2015-2023 yanglb.com - * + *

                  * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + *

                  + * http://www.apache.org/licenses/LICENSE-2.0 + *

                  * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -16,56 +16,58 @@ package com.yanglb.codegen.utils; import com.yanglb.codegen.model.CmdModel; + import java.io.InputStream; import java.util.ArrayList; import java.util.List; import java.util.Map; + import org.yaml.snakeyaml.Yaml; public class Conf { - private static Map settings = null; + private static Map settings = null; - private static void init() { - if(settings != null) return; - Yaml yaml = new Yaml(); + private static void init() { + if (settings != null) return; + Yaml yaml = new Yaml(); - InputStream inputStream = Conf.class - .getClassLoader() - .getResourceAsStream("conf.yaml"); - settings = yaml.load(inputStream); - } + InputStream inputStream = Conf.class + .getClassLoader() + .getResourceAsStream("conf.yaml"); + settings = yaml.load(inputStream); + } - public static CmdModel getCmdModel(String cmd) { - init(); + public static CmdModel getCmdModel(String cmd) { + init(); - Map> values = ObjectUtil.cast(settings.get("command")); - Map map = values.get(cmd); - if (map == null) return null; + Map> values = ObjectUtil.cast(settings.get("command")); + Map map = values.get(cmd); + if (map == null) return null; - return new CmdModel(map); - } + return new CmdModel(map); + } - public static final String CATEGORY_READER = "reader"; - public static final String CATEGORY_WRITER = "writer"; - public static final String CATEGORY_SETTINGS = "settings"; + public static final String CATEGORY_READER = "reader"; + public static final String CATEGORY_WRITER = "writer"; + public static final String CATEGORY_SETTINGS = "settings"; - public static String getString(String category, String key) { - // 初始化 - init(); + public static String getString(String category, String key) { + // 初始化 + init(); - Map values = ObjectUtil.cast(settings.get(category)); - return values.get(key).toString(); - } + Map values = ObjectUtil.cast(settings.get(category)); + return values.get(key).toString(); + } - public static String getSetting(String key) { - return getString(CATEGORY_SETTINGS, key); - } + public static String getSetting(String key) { + return getString(CATEGORY_SETTINGS, key); + } - public static List supportCommands() { - init(); + public static List supportCommands() { + init(); - Map> values = ObjectUtil.cast(settings.get("command")); - return new ArrayList(values.keySet()); - } + Map> values = ObjectUtil.cast(settings.get("command")); + return new ArrayList(values.keySet()); + } } diff --git a/src/main/java/com/yanglb/codegen/utils/DataFormatType.java b/src/main/java/com/yanglb/codegen/utils/DataFormatType.java index f4715fc..a3aa026 100644 --- a/src/main/java/com/yanglb/codegen/utils/DataFormatType.java +++ b/src/main/java/com/yanglb/codegen/utils/DataFormatType.java @@ -1,12 +1,12 @@ /** * Copyright 2015-2023 yanglb.com - * + *

                  * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + *

                  + * http://www.apache.org/licenses/LICENSE-2.0 + *

                  * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -21,9 +21,9 @@ * */ public class DataFormatType { - public static final short FORMAT_GENERAL = 0; + public static final short FORMAT_GENERAL = 0; - public static final short FORMAT_INTEGER = 59; - - public static final short FORMAT_DATE = 60; + public static final short FORMAT_INTEGER = 59; + + public static final short FORMAT_DATE = 60; } diff --git a/src/main/java/com/yanglb/codegen/utils/GenTypes.java b/src/main/java/com/yanglb/codegen/utils/GenTypes.java index 57b4d2f..0ea6459 100644 --- a/src/main/java/com/yanglb/codegen/utils/GenTypes.java +++ b/src/main/java/com/yanglb/codegen/utils/GenTypes.java @@ -1,12 +1,12 @@ /** * Copyright 2015-2023 yanglb.com - * + *

                  * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + *

                  + * http://www.apache.org/licenses/LICENSE-2.0 + *

                  * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. diff --git a/src/main/java/com/yanglb/codegen/utils/Infos.java b/src/main/java/com/yanglb/codegen/utils/Infos.java index 8e00401..f3f5dbe 100644 --- a/src/main/java/com/yanglb/codegen/utils/Infos.java +++ b/src/main/java/com/yanglb/codegen/utils/Infos.java @@ -1,12 +1,12 @@ /** * Copyright 2015-2023 yanglb.com - * + *

                  * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + *

                  + * http://www.apache.org/licenses/LICENSE-2.0 + *

                  * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,8 +17,8 @@ public class Infos { public static final String Name = "Code Generator"; - public static final String Version = "4.3.0"; - public static final String Copyright = "Copyright 2015-2024 yanglb.com All Rights Reserved."; + public static final String Version = "4.4.0"; + public static final String Copyright = "Copyright 2015-2025 yanglb.com All Rights Reserved."; public static final String Author = "me@yanglb.com"; public static final String Website = "https://yanglb.com"; public static final String Repository = "https://github.com/excel-code-generator/code-generator"; diff --git a/src/main/java/com/yanglb/codegen/utils/ObjectUtil.java b/src/main/java/com/yanglb/codegen/utils/ObjectUtil.java index 763df52..a784ae8 100644 --- a/src/main/java/com/yanglb/codegen/utils/ObjectUtil.java +++ b/src/main/java/com/yanglb/codegen/utils/ObjectUtil.java @@ -1,12 +1,12 @@ /** * Copyright 2015-2023 yanglb.com - * + *

                  * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + *

                  + * http://www.apache.org/licenses/LICENSE-2.0 + *

                  * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -18,33 +18,30 @@ import java.lang.reflect.Field; public class ObjectUtil { - - /** - * 深层次 - * 获取指定Class的属性 - * @param cls 类名 - * @param name 属性史 - * @return - * @throws NoSuchFieldException - * @throws SecurityException - */ - public static Field getDeepField(Class cls, String name) - throws NoSuchFieldException, SecurityException { - Field field = null; - try { - field = cls.getDeclaredField(name); - } catch (NoSuchFieldException e) { - if(cls.equals(Object.class)) { - throw e; - } - return getDeepField(cls.getSuperclass(), name); - } - - return field; - } - @SuppressWarnings("unchecked") - public static T cast(Object obj) { - return (T) obj; - } + /** + * 深层次 + * 获取指定Class的属性 + * @param cls 类名 + * @param name 属性史 + */ + public static Field getDeepField(Class cls, String name) + throws NoSuchFieldException, SecurityException { + Field field = null; + try { + field = cls.getDeclaredField(name); + } catch (NoSuchFieldException e) { + if (cls.equals(Object.class)) { + throw e; + } + return getDeepField(cls.getSuperclass(), name); + } + + return field; + } + + @SuppressWarnings("unchecked") + public static T cast(Object obj) { + return (T) obj; + } } diff --git a/src/main/java/com/yanglb/codegen/utils/Resources.java b/src/main/java/com/yanglb/codegen/utils/Resources.java index 59f1df5..d8dd021 100644 --- a/src/main/java/com/yanglb/codegen/utils/Resources.java +++ b/src/main/java/com/yanglb/codegen/utils/Resources.java @@ -1,12 +1,12 @@ /** * Copyright 2015-2023 yanglb.com - * + *

                  * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + *

                  + * http://www.apache.org/licenses/LICENSE-2.0 + *

                  * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -18,17 +18,17 @@ import java.util.ResourceBundle; public class Resources { -private static ResourceBundle resourceBundle = null; - - private static void init() { - if(resourceBundle != null) return; - resourceBundle = ResourceBundle.getBundle("message"); - } - - public static String getString(String key) { - // 初始化 - init(); + private static ResourceBundle resourceBundle = null; - return resourceBundle.getString(key); - } + private static void init() { + if (resourceBundle != null) return; + resourceBundle = ResourceBundle.getBundle("message"); + } + + public static String getString(String key) { + // 初始化 + init(); + + return resourceBundle.getString(key); + } } diff --git a/src/main/java/com/yanglb/codegen/utils/StringUtil.java b/src/main/java/com/yanglb/codegen/utils/StringUtil.java index e7b2516..2d9b370 100644 --- a/src/main/java/com/yanglb/codegen/utils/StringUtil.java +++ b/src/main/java/com/yanglb/codegen/utils/StringUtil.java @@ -1,12 +1,12 @@ /** * Copyright 2015-2023 yanglb.com - * + *

                  * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + *

                  + * http://www.apache.org/licenses/LICENSE-2.0 + *

                  * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -18,40 +18,36 @@ import java.lang.reflect.Field; public class StringUtil { - - /** - * 判断某个字符串是否为"空"字符串 - * @param value - * @return - */ - public static boolean isNullOrEmpty(String value) { - return (value == null || "".equals(value)); - } - - public static String enumToString(Class en) { - StringBuilder sb = new StringBuilder(); - for(Field f : en.getFields()) { - if(sb.length() != 0) { - sb.append("|"); - } - sb.append(f.getName()); - } - return sb.toString(); - } - /** - * 处理IOS字符串 - * @param value - * @return - */ - public static String escapeIOSString(String value) { - if(value == null) return null; + /** + * 判断某个字符串是否为"空"字符串 + */ + public static boolean isNullOrEmpty(String value) { + return (value == null || "".equals(value)); + } - value = value.replaceAll("\\\\", "\\\\\\\\"); - value = value.replaceAll("\"", "\\\\\""); + public static String enumToString(Class en) { + StringBuilder sb = new StringBuilder(); + for (Field f : en.getFields()) { + if (sb.length() != 0) { + sb.append("|"); + } + sb.append(f.getName()); + } + return sb.toString(); + } - value = value.replaceAll("\r", ""); - value = value.replaceAll("\n", "\\\\n"); - return value; - } + /** + * 处理IOS字符串 + */ + public static String escapeIOSString(String value) { + if (value == null) return null; + + value = value.replaceAll("\\\\", "\\\\\\\\"); + value = value.replaceAll("\"", "\\\\\""); + + value = value.replaceAll("\r", ""); + value = value.replaceAll("\n", "\\\\n"); + return value; + } }

                  AltStyle によって変換されたページ (->オリジナル) /