Commit 74414af5 by s_guodong

init

parent 4fa35709
.gradle/
build/
target/
bin/
logs/
# Eclipse Project Files
.classpath
.project
.settings/
# IntelliJ IDEA Files
*.iml
*.ipr
*.iws
*.idea
*.class
*.factorypath
*.springBeans
File added
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.10.RELEASE</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<groupId>com.brilliance</groupId>
<artifactId>gjjs-mda</artifactId>
<version>0.0.1</version>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
<druid.spring.boot.starter.version>1.1.10</druid.spring.boot.starter.version>
<spring.version>2.4.5</spring.version>
<jackson.version>2.11.4</jackson.version>
<dom4j.version>2.1.1</dom4j.version>
<jaxen.version>1.2.0</jaxen.version>
<itextpdf.version>5.5.13</itextpdf.version>
<itext-asian.version>5.2.0</itext-asian.version>
<xmlworker.version>5.5.8</xmlworker.version>
<mybatis.spring.boot.starter.version>2.1.4</mybatis.spring.boot.starter.version>
<mysql.connector.java.version>5.1.29</mysql.connector.java.version>
<poi.ooxml.version>4.1.0</poi.ooxml.version>
<commons.io.version>2.6</commons.io.version>
<commons.codec.version>1.10</commons.codec.version>
<commons.beanutils.version>1.9.3</commons.beanutils.version>
<commons.compress.version>1.18</commons.compress.version>
<guava.version>30.1.1-jre</guava.version>
<lombok.version>1.18.20</lombok.version>
<gson.version>2.8.5</gson.version>
<javax.persistence.api.version>2.2</javax.persistence.api.version>
<velocity.version>1.7</velocity.version>
<velocity.tools.version>2.0</velocity.tools.version>
<jackson.databind.version>2.11.4</jackson.databind.version>
<commons.lang3.version>3.3.2</commons.lang3.version>
<validation.api.version>1.1.0.Final</validation.api.version>
<commons.text.version>1.9</commons.text.version>
<kryo5.version>5.3.0</kryo5.version>
<jackson.annotations.version>2.9.0</jackson.annotations.version>
<slf4j.api.version>1.7.25</slf4j.api.version>
<spring.context.version>5.2.9.RELEASE</spring.context.version>
<fastjson.version>1.2.53</fastjson.version>
</properties>
<dependencies>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${lombok.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.databind.version}</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>${druid.spring.boot.starter.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.sun</groupId>
<artifactId>tools</artifactId>
<version>1.8</version>
<scope>system</scope>
<systemPath>${basedir}/lib/tools.jar</systemPath>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>${java.version}</source>
<target>${java.version}</target>
</configuration>
<executions>
<execution>
<id>default-compile</id>
<configuration>
<compilerArgument>-proc:none</compilerArgument>
<includes>
<include>com/brilliance/annotation/processor/*.java</include>
<include>com/brilliance/annotation/processor/enhance/*.java</include>
</includes>
</configuration>
</execution>
<execution>
<id>compile-project</id>
<phase>compile</phase>
<goals>
<goal>compile</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
<distributionManagement>
<repository>
<id>brilliance-virtual</id>
<name>brilliance-virtual</name>
<url>http://114.115.138.98:9620/artifactory/gjjs-mda/</url>
</repository>
</distributionManagement>
<repositories>
<repository>
<id>brilliance-virtual</id>
<name>brilliance-virtual</name>
<url>http://114.115.138.98:9620/artifactory/brilliance-virtual/</url>
<releases>
<enabled>true</enabled>
</releases>
</repository>
</repositories>
</project>
\ No newline at end of file
package com.brilliance.annotation.processor;
import com.sun.tools.javac.tree.JCTree;
import java.util.List;
public class AnnotationEnhanceUtils {
public static String findAnnotationArguments(List<JCTree.JCExpression> args, String key) {
return findAnnotationArguments(args, key, null);
}
public static String findAnnotationArguments(List<JCTree.JCExpression> args, String key, String defaultValue) {
String value = defaultValue;
if (null != args && args.size() > 0) {
for (JCTree.JCExpression jcExpression : args) {
if (jcExpression instanceof JCTree.JCAssign) {
JCTree.JCAssign jcAssign = (JCTree.JCAssign) jcExpression;
if (key.equals(jcAssign.lhs.toString())) {
value = jcAssign.rhs.toString();
break;
}
}
}
}
return value;
}
public static int findAnnotationArgumentsInt(List<JCTree.JCExpression> args, String key, int defaultValue) {
String value = findAnnotationArguments(args, key, null);
if (null == value || "".equals(value)) {
return defaultValue;
}
try {
return Integer.parseInt(value);
} catch (Exception e) {
return defaultValue;
}
}
protected static boolean findAnnotationArgumentsBoolean(List<JCTree.JCExpression> args, String key, Boolean defaultValue) {
String value = findAnnotationArguments(args, key, null);
if (null == value || "".equals(value)) {
return true;
}
try {
return Boolean.valueOf(value);
} catch (Exception e) {
return defaultValue;
}
}
}
package com.brilliance.annotation.processor;
import com.sun.source.util.Trees;
import com.sun.tools.javac.processing.JavacProcessingEnvironment;
import com.sun.tools.javac.tree.TreeMaker;
import com.sun.tools.javac.util.Context;
import com.sun.tools.javac.util.Name;
import com.sun.tools.javac.util.Names;
import javax.annotation.processing.AbstractProcessor;
import javax.annotation.processing.Messager;
import javax.annotation.processing.ProcessingEnvironment;
import javax.tools.Diagnostic;
public abstract class BaseProcessor extends AbstractProcessor {
/**
* 用于在编译器打印消息的组件
*/
Messager messager;
/**
* 语法树
*/
Trees trees;
/**
* 用来构造语法树节点
*/
TreeMaker treeMaker;
/**
* 用于创建标识符的对象
*/
Name.Table names;
@Override
public synchronized void init(ProcessingEnvironment processingEnvironment) {
super.init(processingEnvironment);
messager = processingEnvironment.getMessager();
trees = Trees.instance(processingEnvironment);
Context context = ((JavacProcessingEnvironment) processingEnvironment).getContext();
treeMaker = TreeMaker.instance(context);
names = Names.instance(context).table;
messager.printMessage(Diagnostic.Kind.NOTE, "父类BaseProcessor执行init()方法");
}
}
package com.brilliance.annotation.processor;
import com.brilliance.annotation.processor.enhance.AbstractAnnotationEnhance;
import com.brilliance.annotation.processor.enhance.impl.*;
import com.brilliance.mda.runtime.annotation.BDGetter;
import com.brilliance.mda.runtime.annotation.Module;
import com.brilliance.mda.runtime.annotation.TDGetter;
import com.brilliance.mda.runtime.annotation.TDSetter;
import com.sun.source.tree.Tree;
import com.sun.tools.javac.tree.JCTree;
import com.sun.tools.javac.tree.TreeMaker;
import com.sun.tools.javac.tree.TreeTranslator;
import com.sun.tools.javac.util.Name;
import javax.annotation.processing.Messager;
import javax.lang.model.element.Modifier;
import javax.tools.Diagnostic;
import java.util.List;
import java.util.Set;
public class ModuleAnnotationTranslator extends TreeTranslator {
private Name.Table names;
private TreeMaker treeMaker;
private Name moduleName;
private Messager messager;
public ModuleAnnotationTranslator(Name.Table names, TreeMaker treeMaker, Name moduleName, Messager messager) {
this.names = names;
this.treeMaker = treeMaker;
this.moduleName = moduleName;
this.messager = messager;
}
@Override
public void visitClassDef(JCTree.JCClassDecl jcClassDecl) {
if ("AbstractModule".equals(moduleName.toString())) {
messager.printMessage(Diagnostic.Kind.NOTE, "AbstractModule 不会被增强.");
return;
}
if (jcClassDecl.name == moduleName) {
jcClassDecl.defs
.stream().filter(it -> it.getKind() == Tree.Kind.VARIABLE)
.map(it -> (JCTree.JCVariableDecl) it)
.forEach(it -> {
JCTree.JCModifiers modifiers = it.getModifiers();
List<JCTree.JCAnnotation> annotations = modifiers.getAnnotations();
for (JCTree.JCAnnotation annotation : annotations) {
AbstractAnnotationEnhance annotationEnhance = getAnnotationEnhance(annotation);
if (annotationEnhance != null) {
processAnnotationEnhance(annotationEnhance, annotation, jcClassDecl, it);
}
}
if (needGenerateMethod(annotations, TDSetter.class.getName()) && isValidField(it)) {
AbstractAnnotationEnhance annotationEnhance = new ModuleSetterEnhance();
processAnnotationEnhance(annotationEnhance, null, jcClassDecl, it);
}
if (needGenerateMethod(annotations, TDGetter.class.getName()) && isValidField(it)) {
AbstractAnnotationEnhance annotationEnhance = new ModuleGetterEnhance();
processAnnotationEnhance(annotationEnhance, null, jcClassDecl, it);
}
if (needGenerateMethod(annotations, BDGetter.class.getName()) && isValidField(it)) {
AbstractAnnotationEnhance annotationEnhance = new ModuleGetterEnhance();
processAnnotationEnhance(annotationEnhance, null, jcClassDecl, it);
}
});
}
super.visitClassDef(jcClassDecl);
}
/**
* 注解增强处理方法
* 1.先找到对应的注解增强实现类
* 2.生成方法名
* 3.找到是否存在该方法
* 4.构造方法体
*
* @param annotationEnhance
* @param annotation
* @param jcClassDecl
* @param it
*/
private void processAnnotationEnhance(AbstractAnnotationEnhance annotationEnhance, JCTree.JCAnnotation annotation, JCTree.JCClassDecl jcClassDecl, JCTree.JCVariableDecl it) {
annotationEnhance.setNames(names);
annotationEnhance.setTreeMaker(treeMaker);
String methodName = annotationEnhance.getMethodName(it);
JCTree.JCMethodDecl methodDecl = annotationEnhance.findJCMethodDecl(jcClassDecl, it, methodName);
if (null == methodDecl) {
messager.printMessage(Diagnostic.Kind.NOTE, "正在增强:" + jcClassDecl.name.toString() + "." + methodName);
List<JCTree.JCExpression> args = annotation == null ? null : annotation.getArguments();
JCTree.JCMethodDecl setterMethod = annotationEnhance.createJCMethodDecl(jcClassDecl, it, methodName, args);
if (setterMethod != null) {
messager.printMessage(Diagnostic.Kind.NOTE, "已增强:" + jcClassDecl.name.toString() + "." + methodName);
jcClassDecl.defs = jcClassDecl.defs.append(setterMethod);
}
} else {
messager.printMessage(Diagnostic.Kind.NOTE, jcClassDecl.name.toString() + "." + methodName + "已经存在,跳过增强");
}
}
/**
* 是否存在注解(@param annotationName)
*
* @param annotations
* @param annotationName
* @return
*/
private boolean includeAnnotation(List<JCTree.JCAnnotation> annotations, String annotationName) {
for (JCTree.JCAnnotation annotation : annotations) {
if (annotation.annotationType.type.toString().equals(annotationName)) {
return true;
}
}
return false;
}
/**
* 根据注解找到对应的实现类
*
* @param annotation
* @return
*/
private AbstractAnnotationEnhance getAnnotationEnhance(JCTree.JCAnnotation annotation) {
if (annotation.annotationType.type.toString().equals(TDSetter.class.getName())) {
return new TDSetterEnhance();
} else if (annotation.annotationType.type.toString().equals(TDGetter.class.getName())) {
return new TDGetterEnhance();
} else if (annotation.annotationType.type.toString().equals(BDGetter.class.getName())) {
return new BDGetterEnhance();
} else {
return null;
}
}
/**
* 字段如果是 final 或者static 修饰的, 不生产getset方法
*
* @param it
* @return
*/
private boolean isValidField(JCTree.JCVariableDecl it) {
Set<Modifier> flagSets = it.getModifiers().getFlags();
return (!flagSets.contains(Modifier.STATIC)
&& !flagSets.contains(Modifier.FINAL));
}
/**
* 是否需要生成对应的getter 或者 setter 方法
* 1. module getter setter
* 2. 是否已经存在TDSetter TDGetter
*
* @param annotations
* @param annotationName
* @return
*/
private boolean needGenerateMethod(List<JCTree.JCAnnotation> annotations, String annotationName) {
boolean flag = true;
String key = "";
if (annotationName.lastIndexOf(".") > -1) {
key = annotationName.substring(annotationName.lastIndexOf(".") + 3).toLowerCase();
} else {
key = annotationName.substring(2).toLowerCase();
}
for (JCTree.JCAnnotation annotation : annotations) {
if (annotation.annotationType.type.toString().equals(Module.class.getName())) {
flag = AnnotationEnhanceUtils.findAnnotationArgumentsBoolean(annotation.getArguments(), key, Boolean.TRUE);
}
}
return flag && !includeAnnotation(annotations, annotationName);
}
}
package com.brilliance.annotation.processor;
import com.sun.source.util.TreePath;
import com.sun.tools.javac.tree.JCTree;
import com.sun.tools.javac.util.Name;
import javax.annotation.processing.RoundEnvironment;
import javax.annotation.processing.SupportedAnnotationTypes;
import javax.annotation.processing.SupportedSourceVersion;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.TypeElement;
import javax.tools.Diagnostic;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
@SupportedAnnotationTypes("com.brilliance.mda.runtime.annotation.Module")
@SupportedSourceVersion(SourceVersion.RELEASE_8)
public class ModuleProcessor extends BaseProcessor{
@Override
public boolean process(Set<? extends TypeElement> set, RoundEnvironment roundEnvironment) {
if (null != set && set.size() > 0) {
messager.printMessage(Diagnostic.Kind.NOTE, "开始编译增强Module");
TypeElement tmpTypeElement = null;
try {
for (TypeElement annotation : set) {
messager.printMessage(Diagnostic.Kind.NOTE, String.format("正在处理增强:%s", annotation.getSimpleName()));
List<TypeElement> typeElementList = roundEnvironment.getElementsAnnotatedWith(annotation)
.stream().filter(it -> (it instanceof TypeElement))
.map(it -> (TypeElement) it)
.collect(Collectors.toList());
messager.printMessage(Diagnostic.Kind.NOTE, String.format("增强Module数量:%d", typeElementList.size()));
for (TypeElement it : typeElementList) {
TreePath treePath = trees.getPath(it);
JCTree.JCCompilationUnit cu = (JCTree.JCCompilationUnit) treePath.getCompilationUnit();
addImport(cu);
JCTree jcTree = (JCTree) trees.getTree(it);
tmpTypeElement = it;
translate(it, jcTree);
}
}
} catch (Exception e) {
messager.printMessage(Diagnostic.Kind.ERROR, "编译增强模型["+tmpTypeElement.getSimpleName().toString()+"]发生错误, 错误原因 : " + e.getMessage());
}
messager.printMessage(Diagnostic.Kind.NOTE, "结束编译增强");
}
return true;
}
private void translate(TypeElement curElement, JCTree curTree) {
treeMaker.pos = curTree.pos;
curTree.accept(new ModuleAnnotationTranslator(names, treeMaker, (Name) curElement.getSimpleName(), messager));
}
private void addImport(JCTree.JCCompilationUnit cu) {
addImport(cu,
"com.brilliance.mda.runtime.mda.impl.PanelImpl",
"com.brilliance.mda.runtime.mda.impl.StreamImpl",
"com.brilliance.mda.runtime.mda.impl.ModuleList",
"com.brilliance.mda.runtime.mda.util.MdaUtils",
"java.lang.*");
}
private void addImport(JCTree.JCCompilationUnit cu, String... importPackages) {
if (null == importPackages)
return;
List<JCTree.JCImport> jcImports = cu.defs.stream()
.filter(it -> (it instanceof JCTree.JCImport))
.map(it -> (JCTree.JCImport) it)
.collect(Collectors.toList());
boolean[] exists = new boolean[importPackages.length];
for (JCTree.JCImport jcImport : jcImports) {
for (int i = 0; i < importPackages.length; i++) {
if (jcImport.toString().equals(importPackages[i])) {
exists[i] = true;
break;
}
}
}
for (int i = 0; i < exists.length; i++) {
if (!exists[i]) {
JCTree.JCFieldAccess fieldAccess = treeMaker.Select(
treeMaker.Ident(names.fromString(importPackages[i].substring(0, importPackages[i].lastIndexOf(".")))),
names.fromString(importPackages[i].substring(importPackages[i].lastIndexOf(".") + 1)));
cu.defs = cu.defs.append(treeMaker.Import(fieldAccess, false));
}
}
}
}
package com.brilliance.annotation.processor;
public enum PrimitiveEnums {
INT("int", "Integer"),
SHORT("short", "Short"),
FLOAT("float", "Float"),
DOUBLE("double", "Double"),
BYTE("byte", "Byte"),
CHAR("char", "Char"),
BOOLEAN("boolean", "Boolean"),
LONG("long", "Long");
private String code;
private String value;
PrimitiveEnums(String code, String value) {
this.code = code;
this.value = value;
}
public static PrimitiveEnums getValues(String code) {
for (PrimitiveEnums e : values()) {
if (e.code.equals(code)) {
return e;
}
}
return null;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
package com.brilliance.annotation.processor.enhance;
import com.sun.tools.javac.tree.TreeMaker;
import com.sun.tools.javac.util.Name;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public abstract class AbstractAnnotationEnhance implements AnnotationEnhance{
protected Name.Table names;
protected TreeMaker treeMaker;
public void setNames(Name.Table names) {
this.names = names;
}
public void setTreeMaker(TreeMaker treeMaker) {
this.treeMaker = treeMaker;
}
public static Properties moduleClassNameProperties;
static {
try {
moduleClassNameProperties = new Properties();
InputStream inputStream = AbstractAnnotationEnhance.class.getResourceAsStream("/META-INF/moduleClassName.properties");
moduleClassNameProperties.load(inputStream);
} catch (IOException e) {
}
}
}
package com.brilliance.annotation.processor.enhance;
import com.sun.tools.javac.tree.JCTree;
import java.util.List;
public interface AnnotationEnhance {
/**
* 得到要增强的方法名称
* @param variableDecl
* @return
*/
String getMethodName(JCTree.JCVariableDecl variableDecl);
/**
* 找到是否存在已增加的注解方法
* @param jcClassDecl
* @param variableDecl
* @param methodName
* @return
*/
JCTree.JCMethodDecl findJCMethodDecl(JCTree.JCClassDecl jcClassDecl, JCTree.JCVariableDecl variableDecl, String methodName);
/**
* 增强注解方法
* @param jcClassDecl
* @param variableDecl
* @param methodName
* @param args
* @return
*/
JCTree.JCMethodDecl createJCMethodDecl(JCTree.JCClassDecl jcClassDecl, JCTree.JCVariableDecl variableDecl, String methodName, List<JCTree.JCExpression> args);
}
package com.brilliance.annotation.processor.enhance.impl;
import com.brilliance.annotation.processor.AnnotationEnhanceUtils;
import com.brilliance.annotation.processor.enhance.AbstractAnnotationEnhance;
import com.sun.tools.javac.code.Flags;
import com.sun.tools.javac.code.TypeTag;
import com.sun.tools.javac.tree.JCTree;
import com.sun.tools.javac.util.ListBuffer;
import java.util.List;
import java.util.stream.Collectors;
/**
* BDGetter注解增强实现类
*/
public class BDGetterEnhance extends AbstractAnnotationEnhance {
@Override
public String getMethodName(JCTree.JCVariableDecl variableDecl) {
String variableName = variableDecl.name.toString();
return "get" + variableName.substring(0, 1).toUpperCase() + variableName.substring(1);
}
@Override
public JCTree.JCMethodDecl findJCMethodDecl(JCTree.JCClassDecl jcClassDecl, JCTree.JCVariableDecl variableDecl, String methodName) {
List<JCTree.JCMethodDecl> jcMethodDecls = jcClassDecl.defs
.stream().filter(it -> (it instanceof JCTree.JCMethodDecl))
.map(it -> (JCTree.JCMethodDecl) it)
.collect(Collectors.toList());
for (JCTree.JCMethodDecl jcMethodDecl : jcMethodDecls) {
if (jcMethodDecl.name.toString().equals(methodName)
&& jcMethodDecl.params.size() == 0
&& jcMethodDecl.restype.type.toString().equals(variableDecl.vartype.type.toString())) {
return jcMethodDecl;
}
}
return null;
}
@Override
public JCTree.JCMethodDecl createJCMethodDecl(JCTree.JCClassDecl jcClassDecl, JCTree.JCVariableDecl variableDecl, String methodName, List<JCTree.JCExpression> args) {
ListBuffer<JCTree.JCStatement> body = new ListBuffer<>();
String instance = variableDecl.name.toString();
if ("tmpint".equals(instance.trim())) {
instance = "int";
}
JCTree.JCNewClass jcNewClass = null;
if (variableDecl.vartype.type.toString().startsWith(moduleClassNameProperties.get("IModuleList") + "<")
|| variableDecl.vartype.type.toString().startsWith(moduleClassNameProperties.get("ModuleList") + "<")) {
JCTree.JCTypeApply typeApply = (JCTree.JCTypeApply) variableDecl.vartype;
List<JCTree.JCExpression> argsuments = typeApply.arguments;
String tClass = argsuments.get(0).toString();
int initSize = AnnotationEnhanceUtils.findAnnotationArgumentsInt(args, "initSize", 0);
jcNewClass = treeMaker.NewClass(null,
com.sun.tools.javac.util.List.nil(),
treeMaker.TypeApply(treeMaker.Ident(names.fromString("ModuleList")),
com.sun.tools.javac.util.List.nil()),
new ListBuffer<JCTree.JCExpression>()
.append(treeMaker.Literal(variableDecl.name.toString()))
.append(treeMaker.Ident(names.fromString("this")))
.append(treeMaker.Literal(initSize))
.append(treeMaker.Select(treeMaker.Ident(names.fromString(tClass)), names.fromString("class")))
.toList(),
null);
} else if (variableDecl.vartype.type.toString().equals(moduleClassNameProperties.get("IPanel"))
|| variableDecl.vartype.type.toString().equals(moduleClassNameProperties.get("PanelImpl"))) {
String i18n = AnnotationEnhanceUtils.findAnnotationArguments(args, "i18n", "").replaceAll("\"", "");
jcNewClass = treeMaker.NewClass(null,
com.sun.tools.javac.util.List.nil(),
treeMaker.Ident(names.fromString("PanelImpl")),
new ListBuffer<JCTree.JCExpression>()
.append(treeMaker.Literal(variableDecl.name.toString()))
.append(treeMaker.Apply(
com.sun.tools.javac.util.List.nil(),
treeMaker.Select(treeMaker.Ident(names.fromString("MdaUtils")), names.fromString("getI18NString")),
new ListBuffer<JCTree.JCExpression>()
.append(treeMaker.Ident(names.fromString("this")))
.append(treeMaker.Literal(TypeTag.CLASS, i18n))
.toList()
))
.append(treeMaker.Ident(names.fromString("this")))
.toList(),
null);
} else if (variableDecl.vartype.type.toString().equals(moduleClassNameProperties.get("IStream"))
|| variableDecl.vartype.type.toString().equals(moduleClassNameProperties.get("StreamImpl"))) {
jcNewClass = treeMaker.NewClass(null,
com.sun.tools.javac.util.List.nil(),
treeMaker.Ident(names.fromString("StreamImpl")),
com.sun.tools.javac.util.List.nil(),
null);
} else if ((!variableDecl.vartype.type.isPrimitive() && variableDecl.vartype.type.toString().startsWith("com.ceb"))) {
jcNewClass = treeMaker.NewClass(null,
com.sun.tools.javac.util.List.nil(),
variableDecl.vartype,
new ListBuffer<JCTree.JCExpression>()
.append(treeMaker.Literal(instance))
.append(treeMaker.Ident(names.fromString("this")))
.toList(),
null);
}
//当jcNewClass == null 时 生成简单的get方法
if (null != jcNewClass) {
body.append(
treeMaker.If(
treeMaker.Parens(treeMaker.Binary(JCTree.Tag.EQ, treeMaker.Select(treeMaker.Ident(names.fromString("this")), variableDecl.name), treeMaker.Literal(TypeTag.BOT, "null"))),
treeMaker.Exec(treeMaker.Assign(treeMaker.Select(treeMaker.Ident(names.fromString("this")), variableDecl.name), jcNewClass)), null));
}
body.append(treeMaker.Return(treeMaker.Select(treeMaker.Ident(names.fromString("this")), variableDecl.name)));
JCTree.JCBlock jcBlock = treeMaker.Block(0, body.toList());
return treeMaker.MethodDef(
treeMaker.Modifiers(Flags.PUBLIC), //方法可见性
names.fromString(methodName), //方法名称
variableDecl.vartype, //返回值类型
com.sun.tools.javac.util.List.nil(), //泛型参数列表
com.sun.tools.javac.util.List.nil(), //参数列表
com.sun.tools.javac.util.List.nil(), //抛出异常列表
jcBlock, null);
}
}
package com.brilliance.annotation.processor.enhance.impl;
import com.brilliance.annotation.processor.enhance.AbstractAnnotationEnhance;
import com.sun.tools.javac.code.Flags;
import com.sun.tools.javac.tree.JCTree;
import com.sun.tools.javac.util.ListBuffer;
import java.util.List;
import java.util.stream.Collectors;
/**
* Module 注解增强类
* 实现普通的get方法
*/
public class ModuleGetterEnhance extends AbstractAnnotationEnhance {
@Override
public String getMethodName(JCTree.JCVariableDecl variableDecl) {
String variableName = variableDecl.name.toString();
return "get" + variableName.substring(0, 1).toUpperCase() + variableName.substring(1);
}
@Override
public JCTree.JCMethodDecl findJCMethodDecl(JCTree.JCClassDecl jcClassDecl, JCTree.JCVariableDecl variableDecl, String methodName) {
List<JCTree.JCMethodDecl> jcMethodDecls = jcClassDecl.defs
.stream().filter(it -> (it instanceof JCTree.JCMethodDecl))
.map(it -> (JCTree.JCMethodDecl) it)
.collect(Collectors.toList());
for (JCTree.JCMethodDecl jcMethodDecl : jcMethodDecls) {
if (jcMethodDecl.name.toString().equals(methodName)
&& jcMethodDecl.params.size() == 0
&& jcMethodDecl.restype.type.toString().equals(variableDecl.vartype.type.toString())) {
return jcMethodDecl;
}
}
return null;
}
@Override
public JCTree.JCMethodDecl createJCMethodDecl(JCTree.JCClassDecl jcClassDecl, JCTree.JCVariableDecl variableDecl, String methodName, List<JCTree.JCExpression> args) {
ListBuffer<JCTree.JCStatement> body = new ListBuffer<>();
body.append(treeMaker.Return(treeMaker.Select(treeMaker.Ident(names.fromString("this")), variableDecl.name)));
JCTree.JCBlock jcBlock = treeMaker.Block(0, body.toList());
return treeMaker.MethodDef(
treeMaker.Modifiers(Flags.PUBLIC), //方法可见性
names.fromString(methodName), //方法名称
variableDecl.vartype, //返回值类型
com.sun.tools.javac.util.List.nil(), //泛型参数列表
com.sun.tools.javac.util.List.nil(), //参数列表
com.sun.tools.javac.util.List.nil(), //抛出异常列表
jcBlock, null);
}
}
package com.brilliance.annotation.processor.enhance.impl;
import com.brilliance.annotation.processor.enhance.AbstractAnnotationEnhance;
import com.sun.tools.javac.code.Flags;
import com.sun.tools.javac.code.TypeTag;
import com.sun.tools.javac.tree.JCTree;
import com.sun.tools.javac.util.ListBuffer;
import java.util.List;
import java.util.stream.Collectors;
/**
* Module 注解增强类
* 实现普通的set方法
*/
public class ModuleSetterEnhance extends AbstractAnnotationEnhance {
@Override
public String getMethodName(JCTree.JCVariableDecl variableDecl) {
String variableName = variableDecl.name.toString();
return "set" + variableName.substring(0, 1).toUpperCase() + variableName.substring(1);
}
@Override
public JCTree.JCMethodDecl findJCMethodDecl(JCTree.JCClassDecl jcClassDecl, JCTree.JCVariableDecl variableDecl, String methodName) {
List<JCTree.JCMethodDecl> jcMethodDecls = jcClassDecl.defs
.stream().filter(it -> (it instanceof JCTree.JCMethodDecl))
.map(it -> (JCTree.JCMethodDecl) it)
.collect(Collectors.toList());
for (JCTree.JCMethodDecl jcMethodDecl : jcMethodDecls) {
if (jcMethodDecl.name.toString().equals(methodName)
&& jcMethodDecl.params.size() == 1
&& jcMethodDecl.params.get(0).vartype.type.toString().equals(variableDecl.vartype.type.toString())) {
return jcMethodDecl;
}
}
return null;
}
@Override
public JCTree.JCMethodDecl createJCMethodDecl(JCTree.JCClassDecl jcClassDecl, JCTree.JCVariableDecl variableDecl, String methodName, List<JCTree.JCExpression> args) {
ListBuffer<JCTree.JCStatement> body = new ListBuffer<>();
//添加语句 " this.xxx = xxx; "
body.append(
treeMaker.Exec(
treeMaker.Assign(
treeMaker.Select(
treeMaker.Ident(names.fromString("this")),
variableDecl.name
),
treeMaker.Ident(variableDecl)
)
)
);
JCTree.JCBlock jcBlock = treeMaker.Block(0, body.toList());
return treeMaker.MethodDef(
treeMaker.Modifiers(Flags.PUBLIC), //方法可见性
names.fromString(methodName), //方法名称
treeMaker.TypeIdent(TypeTag.VOID), //方法返回值
com.sun.tools.javac.util.List.nil(), //泛型参数列表
new ListBuffer<JCTree.JCVariableDecl>()
.append(treeMaker.VarDef(treeMaker.Modifiers(Flags.PARAMETER), variableDecl.name, variableDecl.vartype, null))
.toList(),
com.sun.tools.javac.util.List.nil(), //抛出异常列表
jcBlock, null);
}
}
package com.brilliance.annotation.processor.enhance.impl;
import com.brilliance.annotation.processor.AnnotationEnhanceUtils;
import com.brilliance.annotation.processor.enhance.AbstractAnnotationEnhance;
import com.sun.tools.javac.code.Flags;
import com.sun.tools.javac.code.TypeTag;
import com.sun.tools.javac.tree.JCTree;
import com.sun.tools.javac.util.ListBuffer;
import java.util.List;
import java.util.stream.Collectors;
/**
* TDGetter注解增强实现类
*/
public class TDGetterEnhance extends AbstractAnnotationEnhance {
@Override
public String getMethodName(JCTree.JCVariableDecl variableDecl) {
String variableName = variableDecl.name.toString();
return "get" + variableName.substring(0, 1).toUpperCase() + variableName.substring(1);
}
@Override
public JCTree.JCMethodDecl findJCMethodDecl(JCTree.JCClassDecl jcClassDecl, JCTree.JCVariableDecl variableDecl, String methodName) {
List<JCTree.JCMethodDecl> jcMethodDecls = jcClassDecl.defs
.stream().filter(it -> (it instanceof JCTree.JCMethodDecl))
.map(it -> (JCTree.JCMethodDecl) it)
.collect(Collectors.toList());
for (JCTree.JCMethodDecl jcMethodDecl : jcMethodDecls) {
if (jcMethodDecl.name.toString().equals(methodName)
&& jcMethodDecl.params.size() == 0
&& jcMethodDecl.restype.type.toString().equals(variableDecl.vartype.type.toString())) {
return jcMethodDecl;
}
}
return null;
}
@Override
public JCTree.JCMethodDecl createJCMethodDecl(JCTree.JCClassDecl jcClassDecl, JCTree.JCVariableDecl variableDecl, String methodName, List<JCTree.JCExpression> args) {
ListBuffer<JCTree.JCStatement> body = new ListBuffer<>();
String instance = variableDecl.name.toString();
if ("tmpint".equals(instance.trim())) {
instance = "int";
}
JCTree.JCNewClass jcNewClass = null;
if (variableDecl.vartype.type.toString().startsWith(moduleClassNameProperties.get("IModuleList") + "<")
|| variableDecl.vartype.type.toString().startsWith(moduleClassNameProperties.get("ModuleList") + "<")) {
JCTree.JCTypeApply typeApply = (JCTree.JCTypeApply) variableDecl.vartype;
List<JCTree.JCExpression> argsuments = typeApply.arguments;
String tClass = argsuments.get(0).toString();
int initSize = AnnotationEnhanceUtils.findAnnotationArgumentsInt(args, "initSize", 0);
jcNewClass = treeMaker.NewClass(null,
com.sun.tools.javac.util.List.nil(),
treeMaker.TypeApply(treeMaker.Ident(names.fromString("ModuleList")),
com.sun.tools.javac.util.List.nil()),
new ListBuffer<JCTree.JCExpression>()
.append(treeMaker.Literal(variableDecl.name.toString()))
.append(treeMaker.Ident(names.fromString("this")))
.append(treeMaker.Literal(initSize))
.append(treeMaker.Select(treeMaker.Ident(names.fromString(tClass)), names.fromString("class")))
.toList(),
null);
} else if (variableDecl.vartype.type.toString().equals(moduleClassNameProperties.get("IPanel"))
|| variableDecl.vartype.type.toString().equals(moduleClassNameProperties.get("PanelImpl"))) {
String i18n = AnnotationEnhanceUtils.findAnnotationArguments(args, "i18n", "").replaceAll("\"", "");
jcNewClass = treeMaker.NewClass(null,
com.sun.tools.javac.util.List.nil(),
treeMaker.Ident(names.fromString("PanelImpl")),
new ListBuffer<JCTree.JCExpression>()
.append(treeMaker.Literal(variableDecl.name.toString()))
.append(treeMaker.Apply(
com.sun.tools.javac.util.List.nil(),
treeMaker.Select(treeMaker.Ident(names.fromString("MdaUtils")), names.fromString("getI18NString")),
new ListBuffer<JCTree.JCExpression>()
.append(treeMaker.Ident(names.fromString("this")))
.append(treeMaker.Literal(TypeTag.CLASS, i18n))
.toList()
))
.append(treeMaker.Ident(names.fromString("this")))
.toList(),
null);
} else if (variableDecl.vartype.type.toString().equals(moduleClassNameProperties.get("IStream"))
|| variableDecl.vartype.type.toString().equals(moduleClassNameProperties.get("StreamImpl"))) {
jcNewClass = treeMaker.NewClass(null,
com.sun.tools.javac.util.List.nil(),
treeMaker.Ident(names.fromString("StreamImpl")),
com.sun.tools.javac.util.List.nil(),
null);
} else if ((!variableDecl.vartype.type.isPrimitive() && variableDecl.vartype.type.toString().startsWith("com.ceb"))) {
jcNewClass = treeMaker.NewClass(null,
com.sun.tools.javac.util.List.nil(),
variableDecl.vartype,
new ListBuffer<JCTree.JCExpression>()
.append(treeMaker.Literal(instance))
.append(treeMaker.Ident(names.fromString("this")))
.toList(),
null);
}
//当jcNewClass == null 时 生成简单的get方法
if (null != jcNewClass) {
body.append(
treeMaker.If(
treeMaker.Parens(treeMaker.Binary(JCTree.Tag.EQ, treeMaker.Select(treeMaker.Ident(names.fromString("this")), variableDecl.name), treeMaker.Literal(TypeTag.BOT, "null"))),
treeMaker.Exec(treeMaker.Assign(treeMaker.Select(treeMaker.Ident(names.fromString("this")), variableDecl.name), jcNewClass)), null));
}
body.append(treeMaker.Return(treeMaker.Select(treeMaker.Ident(names.fromString("this")), variableDecl.name)));
JCTree.JCBlock jcBlock = treeMaker.Block(0, body.toList());
return treeMaker.MethodDef(
treeMaker.Modifiers(Flags.PUBLIC), //方法可见性
names.fromString(methodName), //方法名称
variableDecl.vartype, //返回值类型
com.sun.tools.javac.util.List.nil(), //泛型参数列表
com.sun.tools.javac.util.List.nil(), //参数列表
com.sun.tools.javac.util.List.nil(), //抛出异常列表
jcBlock, null);
}
}
package com.brilliance.annotation.processor.enhance.impl;
import com.brilliance.annotation.processor.AnnotationEnhanceUtils;
import com.brilliance.annotation.processor.PrimitiveEnums;
import com.brilliance.annotation.processor.enhance.AbstractAnnotationEnhance;
import com.sun.tools.javac.code.Flags;
import com.sun.tools.javac.code.TypeTag;
import com.sun.tools.javac.tree.JCTree;
import com.sun.tools.javac.util.ListBuffer;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
/**
* TDSetter注解增强实现类
*/
public class TDSetterEnhance extends AbstractAnnotationEnhance {
@Override
public String getMethodName(JCTree.JCVariableDecl variableDecl) {
String variableName = variableDecl.name.toString();
return "set" + variableName.substring(0, 1).toUpperCase() + variableName.substring(1);
}
@Override
public JCTree.JCMethodDecl findJCMethodDecl(JCTree.JCClassDecl jcClassDecl, JCTree.JCVariableDecl variableDecl, String methodName) {
List<JCTree.JCMethodDecl> jcMethodDecls = jcClassDecl.defs
.stream().filter(it -> (it instanceof JCTree.JCMethodDecl))
.map(it -> (JCTree.JCMethodDecl) it)
.collect(Collectors.toList());
for (JCTree.JCMethodDecl jcMethodDecl : jcMethodDecls) {
if (jcMethodDecl.name.toString().equals(methodName)
&& jcMethodDecl.params.size() == 1
&& jcMethodDecl.params.get(0).vartype.type.toString().equals(variableDecl.vartype.type.toString())) {
return jcMethodDecl;
}
}
return null;
}
@Override
public JCTree.JCMethodDecl createJCMethodDecl(JCTree.JCClassDecl jcClassDecl, JCTree.JCVariableDecl variableDecl, String methodName, List<JCTree.JCExpression> args) {
ListBuffer<JCTree.JCStatement> body = new ListBuffer<>();
boolean isNotifyDefault = AnnotationEnhanceUtils.findAnnotationArguments(args, "notifyDefault", "true").equals("true");
if (String.class.getName().equals(variableDecl.vartype.type.toString())) {
int maxLength = AnnotationEnhanceUtils.findAnnotationArgumentsInt(args, "max", 0);
body.append(treeMaker.VarDef(
treeMaker.Modifiers(Flags.PARAMETER),
names.fromString("rs"),
treeMaker.TypeApply(treeMaker.Ident(names.fromString("Result")),
new ListBuffer<JCTree.JCExpression>().append(variableDecl.vartype).toList()),
treeMaker.Apply(
com.sun.tools.javac.util.List.nil(),
treeMaker.Select(treeMaker.Ident(names.fromString("this")), names.fromString("compareAndGetStr")),
new ListBuffer<JCTree.JCExpression>()
.append(treeMaker.Literal(variableDecl.name.toString()))
.append(treeMaker.Ident(names.fromString(variableDecl.name.toString())))
.append(treeMaker.Select(treeMaker.Ident(names.fromString("this")), variableDecl.name))
.append(treeMaker.Literal(maxLength))
.toList()
)));
body.append(treeMaker.Exec(
treeMaker.Assign(
treeMaker.Select(treeMaker.Ident(names.fromString("this")), variableDecl.name),
treeMaker.Select(treeMaker.Ident(names.fromString("rs")), names.fromString("value")))));
if (isNotifyDefault) {
body.append(treeMaker.Exec(
treeMaker.Apply(
com.sun.tools.javac.util.List.nil(),
treeMaker.Select(treeMaker.Ident(names.fromString("rs")), names.fromString("notifyDefault")),
com.sun.tools.javac.util.List.nil()
)
));
}
} else if (BigDecimal.class.getName().equals(variableDecl.vartype.type.toString())) {
int scale = AnnotationEnhanceUtils.findAnnotationArgumentsInt(args, "scale", 2);
body.append(treeMaker.VarDef(
treeMaker.Modifiers(Flags.PARAMETER),
names.fromString("rs"),
treeMaker.TypeApply(treeMaker.Ident(names.fromString("Result")),
new ListBuffer<JCTree.JCExpression>().append(variableDecl.vartype).toList()),
treeMaker.Apply(
com.sun.tools.javac.util.List.nil(),
treeMaker.Select(treeMaker.Ident(names.fromString("this")), names.fromString("compareAndGetDecimal")),
new ListBuffer<JCTree.JCExpression>()
.append(treeMaker.Literal(variableDecl.name.toString()))
.append(treeMaker.Ident(names.fromString(variableDecl.name.toString())))
.append(treeMaker.Select(treeMaker.Ident(names.fromString("this")), variableDecl.name))
.append(treeMaker.Literal(scale))
.toList()
)));
body.append(treeMaker.Exec(
treeMaker.Assign(
treeMaker.Select(treeMaker.Ident(names.fromString("this")), variableDecl.name),
treeMaker.Select(treeMaker.Ident(names.fromString("rs")), names.fromString("value")))));
if (isNotifyDefault) {
body.append(treeMaker.Exec(
treeMaker.Apply(
com.sun.tools.javac.util.List.nil(),
treeMaker.Select(treeMaker.Ident(names.fromString("rs")), names.fromString("notifyDefault")),
com.sun.tools.javac.util.List.nil()
)
));
}
} else if (Date.class.getName().equals(variableDecl.vartype.type.toString())
|| moduleClassNameProperties.get("IStream").equals(variableDecl.vartype.type.toString())
|| moduleClassNameProperties.get("StreamImpl").equals(variableDecl.vartype.type.toString())
|| variableDecl.vartype.type.isPrimitive()) {
body.append(treeMaker.VarDef(
treeMaker.Modifiers(Flags.PARAMETER),
names.fromString("rs"),
treeMaker.TypeApply(treeMaker.Ident(names.fromString("Result")),
variableDecl.vartype.type.isPrimitive() ?
new ListBuffer<JCTree.JCExpression>().append(treeMaker.Ident(names.fromString(PrimitiveEnums.getValues(variableDecl.vartype.toString()).getValue()))).toList()
: new ListBuffer<JCTree.JCExpression>().append(variableDecl.vartype).toList()
),
treeMaker.Apply(
com.sun.tools.javac.util.List.nil(),
treeMaker.Select(treeMaker.Ident(names.fromString("this")), names.fromString("compareAndGet")),
new ListBuffer<JCTree.JCExpression>()
.append(treeMaker.Literal(variableDecl.name.toString()))
.append(treeMaker.Ident(names.fromString(variableDecl.name.toString())))
.append(treeMaker.Select(treeMaker.Ident(names.fromString("this")), variableDecl.name))
.toList()
)));
body.append(treeMaker.Exec(
treeMaker.Assign(
treeMaker.Select(treeMaker.Ident(names.fromString("this")), variableDecl.name),
treeMaker.Select(treeMaker.Ident(names.fromString("rs")), names.fromString("value")))));
if (isNotifyDefault) {
body.append(treeMaker.Exec(
treeMaker.Apply(
com.sun.tools.javac.util.List.nil(),
treeMaker.Select(treeMaker.Ident(names.fromString("rs")), names.fromString("notifyDefault")),
com.sun.tools.javac.util.List.nil()
)
));
}
} else {
return null;
}
JCTree.JCBlock jcBlock = treeMaker.Block(0, body.toList());
return treeMaker.MethodDef(
treeMaker.Modifiers(Flags.PUBLIC), //方法可见性
names.fromString(methodName), //方法名称
treeMaker.TypeIdent(TypeTag.VOID), //方法返回值
com.sun.tools.javac.util.List.nil(), //泛型参数列表
new ListBuffer<JCTree.JCVariableDecl>()
.append(treeMaker.VarDef(treeMaker.Modifiers(Flags.PARAMETER), variableDecl.name, variableDecl.vartype, null))
.toList(),
com.sun.tools.javac.util.List.nil(), //抛出异常列表
jcBlock, null);
}
}
package com.brilliance.mda.runtime.annotation;
import java.lang.annotation.*;
@Documented
@Inherited
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface BDGetter {
}
package com.brilliance.mda.runtime.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
/**
* check函数
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Check {
int order() default 100;
String target() default "";
String[] value() default {};
}
package com.brilliance.mda.runtime.annotation;
import java.lang.annotation.*;
/**
* default函数
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Default {
int order() default 100;
String target() default "";
String[] value() default {};
}
package com.brilliance.mda.runtime.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* 初始化函数
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Init {
int order() default 100;
}
package com.brilliance.mda.runtime.annotation;
import java.lang.annotation.*;
@Inherited
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.FIELD})
public @interface Module {
boolean getter() default true;
boolean setter() default true;
}
package com.brilliance.mda.runtime.annotation;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import com.brilliance.mda.runtime.mda.DirType;
/**
* 视图映射注解
* @author fukai
*
*/
@Documented
@Retention(RUNTIME)
@Target({TYPE,FIELD})
public @interface RelPath {
String value() default ""; //路径
DirType dir() default DirType.BOTH ; //输入输出方向
boolean recursion() default false; //是否递归关联
}
package com.brilliance.mda.runtime.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* 事件函数
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Rule {
String target() default "";
int order() default 100;
String[] value() default {};
}
package com.brilliance.mda.runtime.annotation;
import java.lang.annotation.*;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
/**
* 用于引用模型的get函数
*/
@Documented
@Retention(RUNTIME)
@Target(ElementType.TYPE)
@Repeatable(Setters.class)
public @interface Setter {
String path();
String value();
}
package com.brilliance.mda.runtime.annotation;
import java.lang.annotation.*;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
/**
* 用于引用模型的get函数
*/
@Documented
@Retention(RUNTIME)
@Target(ElementType.TYPE)
public @interface Setters {
Setter[] value();
}
package com.brilliance.mda.runtime.annotation;
import java.lang.annotation.*;
/**
* 标记为已简化处理
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface SimpleType {
Class type();
}
package com.brilliance.mda.runtime.annotation;
import java.lang.annotation.*;
@Documented
@Inherited
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface TDGetter {
String i18n() default "";
int initSize() default 0;
}
package com.brilliance.mda.runtime.annotation;
import java.lang.annotation.*;
/**
* 标记为TD的Method
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface TDMethod {
boolean value() default true;
}
package com.brilliance.mda.runtime.annotation;
import java.lang.annotation.*;
@Documented
@Inherited
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface TDSetter {
int max() default 0;
int scale() default 2;
boolean notifyDefault() default true;
}
package com.brilliance.mda.runtime.annotation;
import java.lang.annotation.*;
/**
* 标记为TD的Static方法
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface TDStatic {
boolean value() default true;
}
package com.brilliance.mda.runtime.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import com.brilliance.mda.runtime.mda.EmptyVO;
/**
* 交易注解
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface Transaction {
String value() default "";
Class<?> vo() default EmptyVO.class;
}
package com.brilliance.mda.runtime.mda;
public enum AttrType {
ATTRIBUTE,
MODIFIED,
ENABLED,
VALUES,
VISIABLE;
}
package com.brilliance.mda.runtime.mda;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;
import java.util.List;
@AllArgsConstructor
@NoArgsConstructor
public class CodeEntity {
public String path;
public List<String> values;
public boolean visited;
}
package com.brilliance.mda.runtime.mda;
public class CodetableItem
{
private String label;
private String value;
private String description;
public CodetableItem(String label, String value, String description)
{
this.label = label;
this.value = value;
this.description = description;
}
public CodetableItem(String label, String value)
{
this.label = label;
this.value = value;
}
public String getLabel()
{
return this.label;
}
public void setLabel(String label)
{
this.label = label;
}
public String getValue()
{
return this.value;
}
public void setValue(String value)
{
this.value = value;
}
public String getDescription()
{
return this.description;
}
public void setDescription(String description)
{
this.description = description;
}
}
package com.brilliance.mda.runtime.mda;
public enum DecodeType {
DECODE_BASE64, DECODE_MD5, DECODE_SHA, DECODE_SHA256, DECODE_SHA384, DECODE_SHA512;
}
package com.brilliance.mda.runtime.mda;
public enum DirType {
IN,OUT,BOTH
}
package com.brilliance.mda.runtime.mda;
/**
* 标记无VO
* @author fukai
*
*/
public class EmptyVO {
}
package com.brilliance.mda.runtime.mda;
/**
* @Description
* @Author s_guodong
* @Date 2022/11/11
*/
public class Event {
public static final int UNSELECTED_INDEX = -1;
private IAttribute target;
private EventType type;
private Object data;
public Event(IAttribute target, EventType type, Object data) {
this.target = target;
this.type = type;
this.data = data;
}
public IAttribute getTarget() {
return this.target;
}
public final EventType getType() {
return this.type;
}
public final Object getData() {
return this.data;
}
}
package com.brilliance.mda.runtime.mda;
/**
* @Description
* @Author s_guodong
* @Date 2022/11/11
*/
public enum EventType {
DEFAULT, ON_KEY_PRESS, ON_PULL_DOWN, ON_PULL_UP, ON_CHANGE, ON_CLICK, ON_DBLCLICK, ON_ROW_INSERT, ON_ROW_REMOVE, ON_STREAM_UPLOAD, ON_STREAM_DOWNLOAD, ON_PANEL_SHOW, ON_PANEL_CLOSE, ON_TIMER;
}
package com.brilliance.mda.runtime.mda;
/**
* @Description
* @Author s_guodong
* @Date 2022/11/11
*/
public class ExitEventException extends RuntimeException {
}
package com.brilliance.mda.runtime.mda;
import com.fasterxml.jackson.annotation.JsonIgnoreType;
@JsonIgnoreType
public interface FieldHolder<T> {
void setValue(T t);
T getValue();
String getPath();
}
package com.brilliance.mda.runtime.mda;
import java.util.Locale;
public interface I18n {
public static final String I18N_IDENT = "/";
String getString(Locale paramLocale, String paramString1, String paramString2, int paramInt);
String getString(Locale paramLocale, String paramString1, String paramString2);
String getString(Locale paramLocale, String paramString, int paramInt);
String getString(Locale paramLocale, String paramString);
}
package com.brilliance.mda.runtime.mda;
/**
* @Description
* @Author s_guodong
* @Date 2022/11/11
*/
public interface IAttribute<E> {
public static final String ID = "ID";
public static final String DESCRIPTION = "DESCRIPTION";
public static final String REQUIRED = "REQUIRED";
public static final String VISIBLE = "VISIBLE";
public static final String ENABLE = "ENABLE";
public static final String MODIFY = "MODIFY";
public static final String BYINPUT = "BYINPUT";
public static final String CODEVALUES = "CODEVALUES";
public static final String FORMAT = "FORMAT";
public static final String WIDTH = "WIDTH";
public static final String COLSPAN = "COLSPAN";
public static final String ROWSPAN = "ROWSPAN";
public static final String HEIGHT = "HEIGHT";
public static final String LENGTH = "LENGTH";
public static final String LINE = "LINE";
public static final String VIEWTYPE = "VIEWTYPE";
public static final String STYLE = "STYLE";
public static final String STYLECLASS = "STYLECLASS";
public static final String HINT = "HINT";
public static final String ARGS = "ARGS";
public static final String SAVEDISPLAY = "SAVEDISPLAY";
Object setAttribute(String paramString, Object paramObject);
Object getAttribute(String paramString);
}
package com.brilliance.mda.runtime.mda;
/**
* @Description
* @Author s_guodong
* @Date 2022/11/11
*/
public interface IAttributeValue<E> extends IValue<E>, IAttribute {
void addCheckRule(IRule paramIRule);
void addEventRule(IEventRule paramIEventRule);
boolean invokeCheckRules(IContext paramIContext);
boolean invokeEventRules(IContext paramIContext, EventType paramEventType, Object paramObject, int... paramVarArgs);
}
package com.brilliance.mda.runtime.mda;
public interface IAuthInfo {
//获取当前用户登录ID
String getUserId();
IStream getSysStream();
IStream getDdsStream();
IStream getKeepAuthInfo();
void recoveryAuthInfo();
}
package com.brilliance.mda.runtime.mda;
import java.io.Serializable;
public interface IBaseObject extends Serializable {
String getName();
IModule getParent();
String getPath();
void clear();
String separator = "\\";
default String getDescription(){
return "";
}
}
package com.brilliance.mda.runtime.mda;
/**
* @Description
* @Author s_guodong
* @Date 2022/11/15
*/
public interface ICallback {
Object invoke(Object... paramVarArgs);
}
package com.brilliance.mda.runtime.mda;
import com.brilliance.mda.runtime.mda.impl.EnvConfig;
import java.io.Serializable;
import java.util.Locale;
import java.util.Map;
public interface IContext extends Serializable {
int ErrorHandled = 0,ErrorUnHandled=1;
String DISPLAY_KEY = "DISPLAY_KEY";
String getTransName();
Map<String,Object> getModified();
Map<String,String> getFieldErrors();
String getMessage();
String getErrorNo();
void setModified(String path, Object value);//Platform.setModified()
void setFieldError(IModule m,String path, String errMsg);//Platform.error()
void setFieldError(IModule m,String path, String format,Object... obj);//Platform.error()
void setFieldError(IBaseObject baseobj, String errMsg);//Platform.error()
void setFieldError(IBaseObject baseobj, String format,Object... obj);//Platform.error()
void setMessage(String errorNo, String message);//Platform.message()
IModule getRoot();
boolean checkAll(IModule module);
boolean postRule(RuleType ruleType, String target);
boolean postInit();
boolean postRule(IModule m,String target);
boolean postRule(IModule m,String target,boolean isInModuleList);
boolean postRule(IBaseObject baseObject);
boolean postCheck(String target);
void setParams(Map<String, Object> params);
Map<String, CodeEntity> getValuesSet();
void visitValues();
Map<String,Object> getRetMap();
IDaoSession getDaoSession() ;
Pagination getPagination(String path);
void storeCacheData(String key, Object data);
void deleteCacheData(String key);
void clearCacheData();
Object restoreCacheData(String key);
EnvConfig getEnvConfig();
boolean saveDisplay(String fileName);
int getErrorCode();
void setErrorCode(int errorCode);
void setErrorCode(int errorCode,String message);
void setErrorMessage(String errorMessage);
void setErrorMessage(String format,Object... values);
void setMessage(String format,Object... values);
String getErrorMessage();
ILocker getLocker();
Locale getLocale();
void setLocale(Locale locale);
void setEmitter(IRuleEmitter emitter);
IRuleEmitter getEmitter();
void logout();
<T> T getVo();
void setVo(Object vo);
<T> void setAttribute(Object parent,String prop,String ATTR,T val);
<T> T getAttribute(Object parent,String prop,String ATTR);
void mallocPrintBuffer();
String releasePrintBuffer();
StringBuilder getCurPrintBuffer();
PrintSegment getCurPrintSegment();
void pushEventPath(String path);
String getEventPath();
void popEventPath();
void setError(IDatafield t);
void setError(String str);
void reraise();
int getErrorState();
void resetErrorState();
void clearEntireError();
void setConcurrentCallStack(String path);
String getConcurrentCallStack();
<T> T absGet(Class<T> clazz);
<T> T absGet(Class<T> clazz,String instName);
Object restoreData(String key);
void storeData(String key,Object data);
void deleteData(String key);
void clearData();
<T> T getParam(String key);
<T> void setParam(String key,T t);
void resetParams(Map<String, Object> params);
int assignSerialNo();
}
package com.brilliance.mda.runtime.mda;
import com.fasterxml.jackson.annotation.JsonIgnoreType;
@JsonIgnoreType
public interface IControl extends IBaseObject {
}
package com.brilliance.mda.runtime.mda;
import com.brilliance.mda.runtime.mda.impl.Argument;
import java.util.Date;
public interface IDaoSession {
void dbBegin();
void dbCommit();
void dbRollback();
void putDao(Class<?> key, Object dao);
int dbCounter(String seqname);
int dbInsert(IModule modull);
int dbUpdate(IModule module,Object v1,String whereCol1);
int dbUpdate(IModule module,Object v1,String whereCol1,Object v2,String whereCol2);
<T extends IModule> int dbUpdate(T module);
int dbDelete(IModule module);
int dbDelete(IModule module, Object val, String col);
int dbDelete(IModule module, Object val, String col,Object val2,String col2);
int dbDelete(IModule module, Argument<? extends Object>... args);
<T extends IModule> T dbRead(T module, Object... args);
<T extends IModule> T dbRead(T module, Argument... args);
<T extends IModule> T dbReadNoData(T module, Object... args);
<T extends IModule> T dbReadByArguments(T module, Argument<? extends Object>... args);
<T extends IModule> T dbReadHold(T module, Object... args);
<T extends IModule> int dbReadSet(IModuleList<T> list, Object... args);
<T extends IModule> int dbReadset(IModuleList<T> list, Object... args);
<T extends IModule> int dbReadSetByArguments(IModuleList<T> list, Argument<? extends Object>... args);
@SuppressWarnings("rawtypes")
<T extends IModule> int dbReadset(IModuleList<T> list,int limitSize, Argument... args);
<T extends IModule> int dbReadset(IModuleList<T> list, String whereSql);
<T extends IModule> int dbReadset(IModuleList<T> list, String whereSql,Object[] params);
<T extends IModule> int dbReadset(IModuleList<T>[] lists, int maxSize, String whereClause, Object[] datas);
void dbReadset(IModuleList[] lists, String whereClause, Object[] datas);
void dbReadset(IModuleList list, int maxSize, String sql);
void dbExecuteSQL(IStream stm);
void dbExecuteSQL(IStream sql, IStream retstream);
void dbExecuteSQL(String sql,Object... params);
void dbFetch(IModule module);
void dbFetchStream(IStream args);
void dbFetchFields(Object... args);
void dbFetchFields(Argument<? extends Object>... arguments);
void dbCloseCursor();
String dbSqlDate(Date endDat);
//TODO 待实现
void dbFreeAll();
void setWaitCursor();
void dbHold(IModule module);
void dbFree(IModule module);
void dbSelect(IModule module, String string, String sql, Object... val);
void DBOpen(IModule module);
void dbSelectCursor(IModule module,String whereSql,Object... params);
boolean isOpenTrans();
void dbConnect();
void dbDisconnect();
String dbName();
}
package com.brilliance.mda.runtime.mda;
import java.io.File;
import java.io.IOException;
import java.util.List;
public interface IDataGrid {
String getLine(int idx);
String deleteLine(int idx);
void sortLines();
int countLines();
int searchLine(String line);
void setRows(List<String> list);
List<String> getRows();
void insertLine(int idx,String line);
void setLine(int idx,String line);
void clearLines();
void addLine(String line);
void saveLines(File file)throws IOException;
void loadLines(File file) throws IOException;
boolean isLinesChanged();
<T> void setAttribute(String attr,T t);
<T> T getAttribute(String attr);
String defaultColDelimiter = "\t";
}
package com.brilliance.mda.runtime.mda;
public interface IDatafield<T> extends IBaseObject{
T getValue();
void setValue(T value);
Class<T> getDataType();
void setAttribute(Object k,Object v);
Object getAttribute(Object k);
}
package com.brilliance.mda.runtime.mda;
/**
* 快照保存接口,保存的东西,可以使文件路径/或者是文件保存key。具体实现由实施情况决定。
* 可以使保存至数据库/保存至NOSQL数据库/保存至文件存储器
* @author fukai
*
*/
public interface IDisplay {
boolean saveDisplay(String filePathOrKey, String data);
String readDisplay(String filePathOrKey);
}
package com.brilliance.mda.runtime.mda;
import java.io.Serializable;
/**
* @Description
* @Author s_guodong
* @Date 2022/11/11
*/
public interface IEventRule extends Serializable {
int getOrder();
EventType getType();
boolean invoke(IContext paramIContext, Event paramEvent);
}
package com.brilliance.mda.runtime.mda;
import java.io.Serializable;
public interface ILocker {
boolean lock(Serializable key);
boolean lock(Serializable key, int expireflg);
boolean lock(Serializable key, long timeout);
LockInfo lock(String userName,Serializable key);
boolean unlock(Serializable key);
boolean unlock(String lockname, Serializable key);
}
package com.brilliance.mda.runtime.mda;
/**
* TODO 认证实现类,实现登录签发Token,认证Token
* @author fukai
*
*/
public interface ILoginContext {
Object login(String id, String pwd);
Object auth(String token);
Object logout(String token);
}
package com.brilliance.mda.runtime.mda;
import java.util.Collection;
import java.util.List;
import java.util.Map;
public interface IModule extends IBaseObject{
default boolean isEntity() {return false;};
String getSerialNum();
void assignSerialNum();
void copyValue(IModule src);
void copyValues(IModule src);
Map<String, Object> getAttrMaps();
default String getFieldPath(String fieldName) {return null;};
/**
* 废弃的方法,不要再使用了
* @return
*/
@Deprecated
default Collection<IDatafield> getDatafields(){return null;};
/**
* 基于反射实现的,尽量不要用了
* @return
*/
@Deprecated
default List<IModule> getModules(){return null;};
default String getTableName()
{
return null;
}
IBaseObject get(String paramString);
}
package com.brilliance.mda.runtime.mda;
/**
* @Description
* @Author s_guodong
* @Date 2022/11/11
*/
public interface IModuleAttribute extends IModule {
// void clearIdAttribute();
}
package com.brilliance.mda.runtime.mda;
import java.util.List;
public interface IModuleList<T extends IModule> extends IModule,List<T> {
int getFullDbSize();
int fullSize();
Class<T> getDataClass();
void removeAll();
@Override
default String getSerialNum() {
return null;
}
@Override
default void assignSerialNum() {};
/**
* 废弃的方法,不建议使用
* @param args IDatafield Argument 两项参数
*/
@Deprecated
T add(Object... args);
void addElement(T em);
void addElement(int index,T em);
default void copyValues(IModule src){
}
default void copyValue(IModule src)
{
copyValues(src);
}
boolean executeInit();
boolean executeInit(int idx);
void executeDefault(String... paths);
void executeDefault(int idx,String... paths);
void executeCheckAll();
}
\ No newline at end of file
package com.brilliance.mda.runtime.mda;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* @Description
* @Author s_guodong
* @Date 2022/11/11
*/
public interface IModuleRoot extends IModuleAttribute {
public static final Log log = LogFactory.getLog(IModuleRoot.class);
}
package com.brilliance.mda.runtime.mda;
import com.fasterxml.jackson.annotation.JsonIgnoreType;
@JsonIgnoreType
public interface IPanel extends IBaseObject{
String getLanguage();
IModule getModule();
String getTitleI18nKey();
void setWindow(Object paramObject);
Object getWindow();
void addEventRule(IEventRule paramIEventRule);
boolean invokeEventRules(IContext paramIContext, Event paramEvent);
}
package com.brilliance.mda.runtime.mda;
/**
* @Description
* @Author s_guodong
* @Date 2022/11/15
*/
public interface IParent extends IBaseObject {
public static final IParent[] EMPTY = new IParent[0];
void addChild();
void bindEvents(IContext paramIContext);
void init(IContext paramIContext);
void copyValues(IParent paramIParent);
Object getAttribute(IBaseObject paramIBaseObject, String paramString);
Object setAttribute(IBaseObject paramIBaseObject, String paramString, Object paramObject);
void updateSubUrls(int paramInt);
String getSubUrl(Object paramObject);
}
package com.brilliance.mda.runtime.mda;
public interface IResult<E> extends IValue<E> {
String getName();
}
\ No newline at end of file
package com.brilliance.mda.runtime.mda;
import java.io.Serializable;
/**
* @Description
* @Author s_guodong
* @Date 2022/11/11
*/
public interface IRule extends Serializable {
int getOrder();
boolean invoke(IContext paramIContext, IAttributeValue paramIAttributeValue);
}
package com.brilliance.mda.runtime.mda;
import java.util.List;
import java.util.Map;
public interface IRuleEmitter {
String EMITTER_PRE = "emitter2.";
boolean executeInit();
boolean executeInit(int order);
boolean executeRule(String target);
boolean executeCheck(String target);
boolean executeRule(String target,int order);
boolean executeCheck(String target,int order);
boolean executeCheckAll();
boolean executeDefault(String target);
boolean executeDefault(String target, int order);
boolean executeDefaultAfterInit();
boolean executeDefaultAll();
// boolean executeDefaultAfterRule(String target);
Map<String,Object> getDefaultRuleQue();
IModule getRoot();
String getModuleName();
Class<?> relatedTransaction();
String getRealPath(String path);
List<IModuleList> getAllModuleList();
}
package com.brilliance.mda.runtime.mda;
import java.util.List;
import java.util.Map;
public interface ISqlTemplate {
<T> List<T> dbQuery(String statement, Map<String,Object> params);
}
package com.brilliance.mda.runtime.mda;
/**
* @Description
* @Author s_guodong
* @Date 2022/11/15
*/
public interface IState {
boolean getContinued();
void sleep();
void setStopCallback(IStopCallback paramIStopCallback);
public static interface IStopCallback {
void stop();
}
}
package com.brilliance.mda.runtime.mda;
import com.brilliance.mda.support.jakson.serialize.IStreamDeSerialized;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Serializable;
@JsonDeserialize(using = IStreamDeSerialized.class)
public interface IStream extends IDataGrid,Serializable {
InputStream getInputStream();
OutputStream getOutputStream();
void close();
boolean isEmpty();
void setType(String type);
String getType();
void setName(String name);
String getName();
String setValue(String value);
String getValue();
boolean isKeepsort();
void setKeepsort(boolean keepsort);
}
package com.brilliance.mda.runtime.mda;
/**
* @Description
* @Author s_guodong
* @Date 2022/11/11
*/
public interface IValue<E> extends Comparable<IValue<E>> {
E setValue(E value);
E getValue();
Class getDataType();
}
package com.brilliance.mda.runtime.mda;
import java.text.SimpleDateFormat;
import java.util.Date;
public class LockInfo
{
public Date date;
public String name;
public LockInfo(Date date, String name)
{
this.date = date;
this.name = name;
}
public String toString()
{
return String.format("Lock by %s at %s", new Object[] { this.name, new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(this.date) });
}
}
\ No newline at end of file
package com.brilliance.mda.runtime.mda;
/**
* @Description
* @Author s_guodong
* @Date 2022/11/11
*/
public enum MessageType {
INFORMATION, ERROR, QUESTION;
}
package com.brilliance.mda.runtime.mda;
import com.fasterxml.jackson.annotation.JsonIgnoreType;
@JsonIgnoreType
@FunctionalInterface
public interface ModuleHolder<T> {
T get();
}
package com.brilliance.mda.runtime.mda;
public interface ModuleInfoGetter {
String get(IModule module);
}
package com.brilliance.mda.runtime.mda;
public enum OpType
{
EQ, NE, GE, LE, GT, LT, IN, LIKE, NOTLIKE, BETWEEN, OR, AND, NOT, ISNULL, ISNOTNULL, ASC, DESC;
}
package com.brilliance.mda.runtime.mda;
public class Pagination {
public String dir; //排序方向
public String sortField; //排序字段
public int pageno; //从0开始计算
public int total; //总数量
}
package com.brilliance.mda.runtime.mda;
public class PrintSegment {
private StringBuilder buffer;
private String segname;
public PrintSegment()
{
buffer = new StringBuilder();
}
public StringBuilder getBuffer() {
return buffer;
}
public void setBuffer(StringBuilder buffer) {
this.buffer = buffer;
}
public String getSegname() {
return segname;
}
public void setSegname(String segname) {
this.segname = segname;
}
}
package com.brilliance.mda.runtime.mda;
public class RuleExecuteException extends RuntimeException {
public RuleExecuteException(String message,Throwable e)
{
super(message,e);
}
}
package com.brilliance.mda.runtime.mda;
public class RuleExitException extends RuntimeException {
public RuleExitException(String message)
{
super(message);
}
}
package com.brilliance.mda.runtime.mda;
/**
* 设置为弹出处理的异常
*/
public class RulePromptException extends RuntimeException {
public RulePromptException(String message)
{
super(message);
}
}
package com.brilliance.mda.runtime.mda;
public enum RuleType {
RULE("RULE"),
INIT("INIT"),
CHECK("CHECK");
private String type;
private RuleType(String type){
this.type = type;
}
public String toString(){
return this.type;
}
}
package com.brilliance.mda.runtime.mda;
public class RuleWarnException extends RuntimeException{
public RuleWarnException(String message)
{
super(message);
}
}
package com.brilliance.mda.runtime.mda;
@FunctionalInterface
public interface Ruleable<T> {
T exec();
}
package com.brilliance.mda.runtime.mda;
/**
* @Description
* @Author s_guodong
* @Date 2022/11/11
*/
public enum ViewType {
VIEW_LABEL, VIEW_EDIT, VIEW_DATEBOX, VIEW_DECIMALBOX, VIEW_COMBO, VIEW_CHECK, VIEW_RADIO, VIEW_RADIOS, VIEW_HYPER, VIEW_BUTTON;
}
package com.brilliance.mda.runtime.mda.config;
import java.util.Properties;
public class Bundle extends Properties {
private static Bundle bundle = new Bundle();
public static Bundle get() {
return bundle;
}
private static final long serialVersionUID = 1L;
public boolean getBoolean(String key) {
return getBoolean(key, false);
}
public boolean getBoolean(String key, boolean defaultValue) {
String temp = getProperty(key);
if (temp == null || temp.length() == 0) {
return defaultValue;
}
return Boolean.parseBoolean(temp);
}
public double getDouble(String key) {
return getDouble(key, 0);
}
public double getDouble(String key, double defaultValue) {
String temp = getProperty(key);
if (temp == null || temp.length() == 0) {
return defaultValue;
}
return Double.parseDouble(temp);
}
public int getInteger(String key) {
return getInteger(key, 0);
}
public int getInteger(String key, int defaultValue) {
String temp = getProperty(key);
if (temp == null || temp.length() == 0) {
return defaultValue;
}
return Integer.parseInt(temp);
}
public long getLong(String key) {
return getLong(key, 0);
}
public long getLong(String key, long defaultValue) {
String temp = getProperty(key);
if (temp == null || temp.length() == 0) {
return defaultValue;
}
return Long.parseLong(temp);
}
private void addLine(String line) {
if (line == null || line.length() == 0) {
return;
}
int index = line.indexOf("=");
if (index == -1) {
return;
}
String key = line.substring(0, index);
String value = line.substring(index + 1);
key = trim(key);
value = trim(value);
put(key, value);
}
public Properties loadString(String content) {
if (content == null || content.length() == 0) {
return this;
}
String[] lines = content.split("\n");
for (String line : lines) {
addLine(line);
}
return this;
}
private String trim(String value) {
return value.trim().replace("\r", "").replace("\t", "");
}
}
package com.brilliance.mda.runtime.mda.config;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import java.io.*;
import java.util.HashMap;
import java.util.Map;
public class IniConfig {
private static Logger logger = LoggerFactory.getLogger(IniConfig.class);
private static Map<String,IniConfig> iniConfigMap = new HashMap<>();
public static String getIniConfig(String iniName,String block,String key){
//返回默认币种
if(key!=null && (key.equalsIgnoreCase("SysCurrency")
||key.equalsIgnoreCase("RateBaseCurrency")
||key.equalsIgnoreCase("CURRENCY"))){
return "EUR";
}
//后续需要添加在trade.ini中
if(iniConfigMap.containsKey(iniName.toUpperCase()))
return iniConfigMap.get(iniName.toUpperCase()).get(block.toUpperCase(),key.toUpperCase());
return "";
}
private Map<String, Map<String,String>> data = new HashMap<>();
public String get(String block,String key){
if(data.containsKey(block))
return data.get(block).get(key);
return null;
}
public void set(String block,String key,String value){
if(!data.containsKey(block))
data.put(block,new HashMap<>());
data.get(block).put(key,value);
}
public static void loadIni(File file){
IniConfig config = new IniConfig();
try(BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file),"gb2312"))) {
String str="",block="";
while ((str = br.readLine()) != null){
if(StringUtils.isEmpty(str))
continue;
if(str.indexOf('[')==0){
if (str.indexOf(']') < 0){
block = str.substring(1);
}else{
block = str.substring(1,str.indexOf(']'));
}
block = block.toUpperCase();
}else if(str.indexOf('=')>-1){
if (str.indexOf(';') == 0){
continue;
}
if (str.indexOf(';') > 0){
str = str.substring(0, str.indexOf(';'));
}
String[] ary = str.trim().split("=");
String val = "";
if (ary.length >= 2){
val = ary[1];
}
config.set(block,ary[0].trim().toUpperCase(),val);
}
}
} catch (Exception e) {
logger.error(String.format("解析INI配置[%s]错误!", file.getAbsolutePath()));
System.exit(-1);
}
iniConfigMap.put(file.getName().toUpperCase(),config);
}
public static Map<String, IniConfig> getIniConfigMap() {
return iniConfigMap;
}
public Map<String, Map<String, String>> getData() {
return data;
}
}
package com.brilliance.mda.runtime.mda.driver;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;
import org.springframework.context.ResourceLoaderAware;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternUtils;
import org.springframework.core.type.classreading.CachingMetadataReaderFactory;
import org.springframework.core.type.classreading.MetadataReader;
import org.springframework.core.type.classreading.MetadataReaderFactory;
import org.springframework.stereotype.Component;
/**
* 扫描包路径的交易类
* @author fukai
*
*/
@Component
@Data
@Slf4j
public class MdaScanner implements ResourceLoaderAware, BeanDefinitionRegistryPostProcessor {
private ResourceLoader resourceLoader;
private BeanDefinitionRegistry beanDefinitionRegistry;
@Override
public void setResourceLoader(ResourceLoader resourceLoader) {
this.resourceLoader = resourceLoader;
}
@Override
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry beanDefinitionRegistry) throws BeansException {
this.beanDefinitionRegistry = beanDefinitionRegistry;
}
/**
*
* @param packagePath 类路径,以"/"斜线分隔
* @return 该包下的添加了该注解的类
* @throws IOException
* @throws ClassNotFoundException
*/
public Set<Class<?>> doScan(String packagePath,Class<? extends Annotation> anoclazz) throws IOException, ClassNotFoundException
{
HashSet<Class<?>> set = new HashSet<Class<?>>();
ResourcePatternResolver resolver = ResourcePatternUtils.getResourcePatternResolver(resourceLoader);
MetadataReaderFactory metaReader = new CachingMetadataReaderFactory(resourceLoader);
String path = "classpath*:"+packagePath+"/**/*.class";
log.info("MdaScanner doScan:{}", path);
Resource[] resources = resolver.getResources(path);
for (Resource r : resources) {
if(!r.isReadable())
continue;
MetadataReader reader = metaReader.getMetadataReader(r);
if(!reader.getClassMetadata().isConcrete()) // 当类型不是抽象类或接口在添加到集合
continue;
String className = reader.getClassMetadata().getClassName();
Class<?> clazz = Class.forName(className);
if(clazz.isAnnotationPresent(anoclazz))
{
set.add(clazz);
}
}
return set;
}
public Map<Class<?>, Set<Class<?>>> doScan(Map<Class<?>, Set<Class<?>>> map, String packagePath, Class<? extends Annotation>... annotationClasses) throws IOException, ClassNotFoundException {
ResourcePatternResolver resolver = ResourcePatternUtils.getResourcePatternResolver(resourceLoader);
MetadataReaderFactory metaReader = new CachingMetadataReaderFactory(resourceLoader);
String path = "classpath*:" + packagePath + "/**/*.class";
log.info("MdaScanner doScan:{}", path);
Resource[] resources = resolver.getResources(path);
for (Resource r : resources) {
if (!r.isReadable())
continue;
MetadataReader reader = metaReader.getMetadataReader(r);
if (!reader.getClassMetadata().isConcrete()) // 当类型不是抽象类或接口在添加到集合
continue;
String className = reader.getClassMetadata().getClassName();
Class<?> clazz = Class.forName(className);
for (Class<? extends Annotation> annotationClass : annotationClasses) {
if (clazz.isAnnotationPresent(annotationClass)) {
Set<Class<?>> set = map.computeIfAbsent(annotationClass, k -> new LinkedHashSet<>());
set.add(Class.forName(className));
}
}
}
return map;
}
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory configurableListableBeanFactory) throws BeansException {
}
}
package com.brilliance.mda.runtime.mda.driver;
import java.util.HashMap;
import java.util.Map;
/**
*
* @author fukai
* 扫描vo类、配置目录,实现VO长短类名检测
*/
public class NamesMapper {
private static Map<String,Alias> trnAlias = new HashMap<String,Alias>();
public static Alias genTransAlias(String trnName)
{
Alias alias = trnAlias.get(trnName);
if(alias == null)
{
alias = new Alias(trnName);
trnAlias.put(trnName, alias);
}
return alias;
}
public static Alias getAlias(String trnName){
return trnAlias.get(trnName);
}
public static class Alias{
private Map<String,String> pathAliasMap = new HashMap<String,String>();
private Map<String,String> revertMap = new HashMap<String,String>();
private String trnName;
public Alias(String trnName)
{
this.trnName = trnName;
}
public Map<String, String> getPathAliasMap() {
return pathAliasMap;
}
public void setPathAliasMap(Map<String, String> pathAliasMap) {
this.pathAliasMap = pathAliasMap;
}
public Map<String, String> getRevertMap() {
return revertMap;
}
public void setRevertMap(Map<String, String> revertMap) {
this.revertMap = revertMap;
}
public String getRelPath(String alias) {
return this.pathAliasMap.get(alias);
}
public String getPathAlias(String path)
{
return revertMap.get(path);
}
public String getTrnName() {
return trnName;
}
}
}
package com.brilliance.mda.runtime.mda.driver;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.Data;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import java.io.InputStream;
import java.util.*;
@Data
public class StatusInfoConfig {
private static StatusInfoConfig config = null;
public static Map<String, Map<String, Set<String>>> statusInfoMap = new HashMap<>();
private static String location = "classpath:statusInfo/*";
private static String separator = ".";
static {
ResourcePatternResolver resourceResolver = new PathMatchingResourcePatternResolver();
try {
Resource[] resources = resourceResolver.getResources(location);
for (Resource resource : resources) {
statusInfoMap.put(Objects.requireNonNull(resource.getFilename()).substring(0, resource.getFilename().indexOf(".")), collecSignleTranMap(resource.getInputStream()));
}
} catch (Exception e) {
e.printStackTrace();
}
}
private static Map<String, Set<String>> collecSignleTranMap(InputStream inputStream)throws Exception{
ObjectMapper om = new ObjectMapper();
Map<String,Object> map = om.readValue(inputStream, Map.class);
Map<String, Set<String>> result = new HashMap<>();
collectMapInfo("", map, result);
return result;
}
private static void collectMapInfo(String path, Map<String, Object> map, Map<String, Set<String>> result) {
for (Map.Entry<String, Object> entry : map.entrySet()) {
String currPath = path + separator + entry.getKey();
if (entry.getValue() instanceof List){
List value = (List) entry.getValue();
String[] statusInfo_list = new String[]{"visiable", "modified", "enabled"};
//for (String status : MdaDriver.statusInfo_list) {
for (String status : statusInfo_list) {
if(value.contains(status)){
if(!result.containsKey(status)){
result.put(status, new HashSet<>());
}
result.get(status).add(formatPath(currPath));
}
}
}else{
collectMapInfo(currPath, (Map)entry.getValue(), result);
}
}
}
public static String formatPath(String path){
if (path.isEmpty()){
return path;
}
if (separator.equals(path.charAt(0)+"")){
return path.substring(1);
}
return path;
}
}
package com.brilliance.mda.runtime.mda.driver.compile.component;
import lombok.Data;
@Data
public class FieldInfo {
private String name;
private int type; // 0 基本类型 1 模型 2 模型List 3 引用模型 4引用字段
private String typeName;
}
package com.brilliance.mda.runtime.mda.driver.compile.component;
import lombok.Data;
import java.lang.reflect.Method;
import java.util.*;
import java.util.stream.Collectors;
@Data
public class ModuleRuleContext {
//RULE编译的层次
public static int RULE_COMPILE_DEPTH=1;
private Map<String, List<RuleItem>> checkRule = new LinkedHashMap<>();
private Map<String, List<RuleItem>> eventRule = new LinkedHashMap<>();
private Map<String, List<RuleItem>> defaultRule = new LinkedHashMap<>();
private List<RuleItem> initList = new ArrayList<>();
private List<String> moduleList = new ArrayList<>();
private Map<String,Method> globalMethod = new HashMap<>();
private Map<String,RuleItem> staticMethod = new HashMap<>();
private String moduleName;
private boolean useEmitter;
private boolean isTrans;
private ModuleRuleContext mergedContext;
public ModuleRuleContext(String moduleName){
this.moduleName = moduleName;
this.useEmitter = false;
}
public ModuleRuleContext(String moduleName,boolean useEmitter){
this.moduleName = moduleName;
this.useEmitter = useEmitter;
}
public void mergeChild(String nodePath,ModuleRuleContext nodeContext){
nodeContext.moduleList.forEach(item->this.moduleList.add(nodePath+"."+item));
nodeContext.initList.forEach(item->{
RuleItem newItem = item.clone();
String belongPath = nodePath+"."+newItem.getDotPath();
//newItem.getBelongClass().push(this.moduleName);
newItem.initGetPath(belongPath);
this.initList.add(newItem);
});
mergeRuleMap(nodePath,this.checkRule,nodeContext.checkRule);
mergeRuleMap(nodePath,this.defaultRule,nodeContext.defaultRule);
mergeRuleMap(nodePath,this.eventRule,nodeContext.eventRule);
nodeContext.staticMethod.forEach((key,ruleItem)->{
RuleItem newItem = ruleItem.clone();
String belongPath = nodePath+"."+newItem.getDotPath();
newItem.initGetPath(belongPath);
this.staticMethod.put(key,newItem);
});
this.globalMethod.putAll(nodeContext.globalMethod);
}
private void mergeRuleMap(String nodePath,Map<String, List<RuleItem>> dest,Map<String, List<RuleItem>> src){
src.entrySet().forEach(entry->{
String key = entry.getKey();
if(!entry.getValue().isEmpty()){
RuleItem ruleItem = entry.getValue().get(0);
if(ruleItem.getRuleType().equals("CHECK") && key.endsWith("sdamod.dadsnd")){
return;
}
}
//顶层交易模块,自动识别去除开始的.
// if(key.charAt(0) == '.' && useEmitter){
// key = key.substring(1);
// }
if(key.charAt(0) != '.') {
//合并rule路径
key = nodePath + "." + key;
}
List<RuleItem> ruleItemList = dest.get(key);
if(ruleItemList == null){
ruleItemList = new ArrayList<>();
dest.put(key,ruleItemList);
}
List<RuleItem> finalRuleItemList = ruleItemList;
String entirePath = key;
entry.getValue().forEach(item->{
RuleItem newItem = item.clone();
String belongPath = nodePath+"."+newItem.getDotPath();
newItem.initGetPath(belongPath);
newItem.setEntirePath(entirePath);
//newItem.getBelongClass().push(this.moduleName);
finalRuleItemList.add(newItem);
});
});
}
public void sortRule(){
this.checkRule.values().stream().forEach(list->list.sort(new RuleItem.RuleItemComparator()));
this.eventRule.values().stream().forEach(list->list.sort(new RuleItem.RuleItemComparator()));
this.defaultRule.values().stream().forEach(list->list.sort(new RuleItem.RuleItemComparator()));
List<RuleItem> nInitRule = new ArrayList<>();
//EnterTransaction
List<RuleItem> tempList = initList.stream().filter(a->a.getOrder()>9000000).sorted(Comparator.comparingInt(RuleItem::getOrder)).collect(Collectors.toList());
//InitTransaction
List<RuleItem> tempList2 = initList.stream().filter(a->a.getOrder()<9000000 && a.getOrder()>=900000).sorted(Comparator.comparingInt(RuleItem::getOrder)).collect(Collectors.toList());
//ModuleTransaction
List<RuleItem> tempList3 = initList.stream().filter(a->a.getOrder()<900000).collect(Collectors.toList());
nInitRule.addAll(tempList);
nInitRule.addAll(tempList3);
nInitRule.addAll(tempList2);
initList = nInitRule;
}
public boolean isRuleEmpty(){
return checkRule.size() ==0
&& defaultRule.size() == 0
&& eventRule.size() == 0
&& initList.size() == 0;
}
public void putGlobalMethod(Method method){
String key = getMethodKey(method);
globalMethod.put(key,method);
}
public static String getMethodKey(Method method){
StringBuilder key = new StringBuilder(method.getName());
for(Class clazz : method.getParameterTypes()){
key.append(",").append(clazz.getCanonicalName());
}
key.append(",").append(method.getReturnType().getCanonicalName());
return key.toString();
}
}
package com.brilliance.mda.runtime.mda.driver.compile.component;
import com.brilliance.mda.runtime.mda.Ruleable;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Data;
import java.lang.reflect.Method;
import java.util.Comparator;
@Data
public class RuleItem {
public static final String INIT = "INIT";
public static final String RULE = "RULE";
public static final String CHECK = "CHECK";
public static final String DEFAULT = "DEFAULT";
public static final String STATIC = "STATIC";
public static final String LOCAL = "LOCAL";
public static final String GLOBAL = "GLOBAL";
public static final String LIST = "LIST";
// private String methodName;
//String or Method
@JsonIgnore
private Object method;
private int order;
@JsonIgnore
private String getPath;
private String dotPath;
@JsonIgnore
private String entirePath;
@JsonIgnore
private int depth;
@JsonIgnore
private String ruleType;
@JsonIgnore
private String module;
@JsonIgnore
private String transName;
@JsonIgnore
private Ruleable<Boolean> ruleableIns;
//private Stack<String> belongClass = new Stack<>();
public void initGetPath(String dotPath)
{
if(dotPath.endsWith(".")){
dotPath = dotPath.substring(0,dotPath.length()-1);
}
this.dotPath = dotPath;
if(dotPath.length() == 0)
{
this.getPath = "";
this.depth = 0;
return ;
}
String[] pathArr = dotPath.split("\\.");
this.depth = pathArr.length;
// StringBuilder sb = new StringBuilder();
// for(String item:pathArr)
// {
// sb.append(".get");
// sb.append(firstUpper(item));
// sb.append("()");
// }
// getPath = sb.toString();
}
private String firstUpper(String s){
if(s.length() == 1)
return s.toUpperCase();
return s.substring(0,1).toUpperCase()+s.substring(1);
}
public static class RuleItemComparator implements Comparator<RuleItem> {
@Override
public int compare(RuleItem o1, RuleItem o2) {
if(o1.getOrder() > o2.getOrder())
return 1;
else if(o1.getOrder() < o2.getOrder())
return -1;
//TD的Rule执行顺序,由上到下,由里到外
if(o1.getDepth() > o2.getDepth())
return -1;
else if(o1.getDepth() < o2.getDepth())
return 1;
return 0;
}
}
public String getTransName() {
return transName;
}
public void setTransName(String transName) {
this.transName = transName;
}
public RuleItem clone(){
RuleItem clone = new RuleItem();
// clone.methodName = this.methodName;
clone.order = this.order;
clone.getPath = this.getPath;
clone.dotPath = this.dotPath;
clone.entirePath = this.entirePath;
clone.depth = this.depth;
clone.ruleType = this.ruleType;
clone.module = this.module;
clone.transName = this.transName;
clone.method = this.method;
// Stack<String> belongClassStack = new Stack<>();
// belongClassStack.addAll(this.belongClass);
// clone.belongClass = belongClassStack;
return clone;
}
public String getMethodName(){
if(method instanceof Method)
return ((Method)method).getName();
return (String)method;
}
}
\ No newline at end of file
package com.brilliance.mda.runtime.mda.impl;
import com.brilliance.mda.runtime.mda.IResult;
import com.brilliance.mda.runtime.mda.OpType;
public class Argument<E> implements IResult {
public String fieldName;
public OpType opType;
public E value;
public Object attachField;
public Argument() {
}
public Argument(String fieldName) {
this.fieldName = fieldName;
}
public Argument(String fieldName, OpType opType, E value) {
this.fieldName = fieldName;
this.opType = opType;
this.value = value;
}
public Argument(String fieldName, OpType opType) {
this.fieldName = fieldName;
this.opType = opType;
this.value = null;
}
public Argument(String fieldName, E value) {
this(fieldName, OpType.EQ, value);
}
public Argument(OpType opType, E value) {
this(null, opType, value);
}
@SuppressWarnings({"rawtypes", "unchecked"})
public static Argument or(Argument arg1, Argument arg2) {
return new Argument(OpType.OR, new Argument[]{arg1, arg2});
}
@SuppressWarnings({"rawtypes", "unchecked"})
public static Argument and(Argument arg1, Argument arg2) {
return new Argument(OpType.AND, new Argument[]{arg1, arg2});
}
@SuppressWarnings({"rawtypes", "unchecked"})
public static Argument not(Argument argument) {
return new Argument(OpType.NOT, argument);
}
@SuppressWarnings({"rawtypes", "unchecked"})
public static Argument in(String column, Object[] values) {
return new Argument(column, OpType.IN, values);
}
@SuppressWarnings({"rawtypes", "unchecked"})
public static Argument between(String column, Object value1, Object value2) {
return new Argument(column, OpType.BETWEEN, new Object[]{value1, value2});
}
@SuppressWarnings({"rawtypes", "unchecked"})
public static Argument eq(String column, Object value) {
return new Argument(column, value);
}
@SuppressWarnings({"rawtypes", "unchecked"})
public static Argument gt(String column, Object value) {
return new Argument(column, OpType.GT, value);
}
@SuppressWarnings({"rawtypes", "unchecked"})
public static Argument ge(String column, Object value) {
return new Argument(column, OpType.GE, value);
}
@SuppressWarnings({"rawtypes", "unchecked"})
public static Argument lt(String column, Object value) {
return new Argument(column, OpType.LT, value);
}
@SuppressWarnings({"rawtypes", "unchecked"})
public static Argument le(String column, Object value) {
return new Argument(column, OpType.LE, value);
}
@SuppressWarnings({"rawtypes", "unchecked"})
public static Argument isNotNull(String column) {
return new Argument(column, OpType.ISNOTNULL);
}
@SuppressWarnings({"rawtypes", "unchecked"})
public static Argument isNull(String column) {
return new Argument(column, OpType.ISNULL);
}
@SuppressWarnings({"rawtypes", "unchecked"})
public static Argument like(String column, Object value) {
return new Argument(column, OpType.LIKE, value);
}
@SuppressWarnings({"rawtypes", "unchecked"})
public static Argument notLike(String column, Object value) {
return new Argument(column, OpType.NOTLIKE, value);
}
@SuppressWarnings({"rawtypes"})
public Argument and(Argument argument) {
return this.opType == null ? argument : and(this, argument);
}
@SuppressWarnings({"rawtypes"})
public Argument and(String fieldName, Object value) {
return and(fieldName, OpType.EQ, value);
}
@SuppressWarnings({"rawtypes", "unchecked"})
public Argument and(String fieldName, OpType opType) {
return and(new Argument(fieldName, opType));
}
@SuppressWarnings({"rawtypes", "unchecked"})
public Argument and(String fieldName, OpType opType, Object value) {
return and(new Argument(fieldName, opType, value));
}
@SuppressWarnings({"rawtypes"})
public Argument or(Argument argument) {
return this.opType == null ? argument : or(this, argument);
}
@SuppressWarnings({"rawtypes"})
public Argument or(String fieldName, Object value) {
return or(fieldName, OpType.EQ, value);
}
@SuppressWarnings({"rawtypes", "unchecked"})
public Argument or(String fieldName, OpType opType) {
return or(new Argument(fieldName, opType));
}
@SuppressWarnings({"rawtypes", "unchecked"})
public Argument or(String fieldName, OpType opType, Object value) {
return or(new Argument(fieldName, opType, value));
}
@Override
public Object setValue(Object value) {
this.value = (E) value;
return value;
}
@Override
public E getValue() {
return value;
}
@Override
public Class getDataType() {
return this.getClass();
}
public String getFieldName() {
return this.fieldName;
}
@Override
public String getName() {
return this.fieldName;
}
@Override
public int compareTo(Object o) {
return 0;
}
public static <T> Argument<T> box(T value){
return new Argument<T>("",value);
}
}
package com.brilliance.mda.runtime.mda.impl;
import com.brilliance.mda.runtime.mda.IDataGrid;
import com.fasterxml.jackson.annotation.JsonIgnore;
import java.io.*;
import java.util.*;
public class DataGrid implements IDataGrid, Serializable {
protected List<String> rows = new ArrayList<>();
protected List<String> initRows = new ArrayList<>();
protected Map<String,Object> attrs = new HashMap<>();
private boolean keepsort;
@Override
public void insertLine(int idx, String line) {
if (idx <= 0 || idx > rows.size()) {
rows.add(line);
return;
}
if(line != null)
rows.add(--idx,line);
}
@JsonIgnore
public String getLine(int idx) {
if(idx == 0) idx =1;
idx--;
if(idx >= rows.size())
return "";
return rows.get(idx);
}
@JsonIgnore
@Override
public String deleteLine(int idx) {
if(idx == 0) idx =1;
return rows.remove(--idx);
}
@Override
public void sortLines() {
Collections.sort(rows);
}
@Override
public int countLines() {
return rows.size();
}
@JsonIgnore
@Override
public int searchLine(String line) {
if(line ==null) return 0;
for (int i = 0; i <rows.size() ; i++) {
if(rows.get(i) == null) continue;
if(!keepsort && rows.get(i).toLowerCase().startsWith(line.toLowerCase())){
return i+1;
}
if(keepsort && rows.get(i).startsWith(line)){
return i+1;
}
}
return 0;
}
@Override
public void setRows(List<String> list) {
this.rows.clear();
rows.addAll(list);
}
@Override
public List<String> getRows() {
return rows;
}
@Override
public void clearLines() {
this.rows.clear();
}
@Override
public void addLine(String line) {
if(line != null)
this.rows.add(line);
}
@JsonIgnore
public void setLine(int idx, String line) {
if(idx == 0) idx =1;
if(line == null){
return;
}
//String[] lines = line.split("[\\r\\n]{1,2}");
String[] lines = new String[]{line};
//计算替换区间
int endIdx = idx +lines.length;
for(int n=this.rows.size()+1;n<endIdx;n++){
this.rows.add("");
}
for(int n=idx;n<endIdx;n++){
this.rows.set(n-1,lines[n-idx]);
}
}
@JsonIgnore
public void loadLines(File file)throws IOException {
BufferedReader br = null;
rows.clear();
try{
br = new BufferedReader(new FileReader(file));
String str = null;
while((str = br.readLine())!=null){
rows.add(str);
}
}catch (IOException e){
rows.clear();
throw e;
}finally {
if(br != null){
br.close();
}
}
}
@JsonIgnore
public void saveLines(File file)throws IOException{
BufferedWriter br = null;
try{
if(!file.exists()){
file.createNewFile();
}
br = new BufferedWriter(new FileWriter(file));
for (String s : rows) {
br.write(s);
br.newLine();
}
}catch (Exception e){
rows.clear();
throw new RuntimeException(e);
}
finally {
if(br != null){
br.close();
}
}
}
@JsonIgnore
public boolean isLinesChanged(){
if(rows.size() != initRows.size())
return true;
for (int i = 0; i < initRows.size(); i++) {
if(!initRows.get(i).equals(rows.get(i))){
return true;
}
}
return false;
}
@JsonIgnore
public <T> void setAttribute(String attr,T stream){
this.attrs.put(attr,stream);
}
@JsonIgnore
public <T> T getAttribute(String attr){
return (T)this.attrs.get(attr);
}
public boolean isKeepsort() {
return keepsort;
}
public void setKeepsort(boolean keepsort) {
this.keepsort = keepsort;
}
}
package com.brilliance.mda.runtime.mda.impl;
import com.brilliance.mda.runtime.mda.config.IniConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import javax.annotation.PostConstruct;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
/**
* 放置环境参数
*/
@Configuration
public class EnvConfig {
private static Logger logger = LoggerFactory.getLogger(EnvConfig.class);
private static Map<String,Object> config = new HashMap<>();
@Value("${envConfig.rootPath}")
private String rootPath;
public String getRootPath() {
return rootPath;
}
public void setRootPath(String rootPath) {
this.rootPath = rootPath;
}
@PostConstruct
public void init(){
File dir = new File(rootPath);
if(!dir.exists()){
dir.mkdirs();
}else {
recursionFile(dir);
}
config.put("rootPath",rootPath);
}
public void recursionFile(File file){
if(file.isFile()){
parse(file);
return;
}
for (File f: file.listFiles()) {
recursionFile(f);
}
}
public void parse(File file){
String lowerFileName = file.getName().toLowerCase();
if(lowerFileName.endsWith(".ini") || lowerFileName.endsWith(".dof")){
IniConfig.loadIni(file);
}
}
}
package com.brilliance.mda.runtime.mda.impl;
import com.brilliance.mda.runtime.mda.FieldHolder;
public class FieldConstantHolder<T> implements FieldHolder<T> {
private T constantValue;
public FieldConstantHolder(T constantValue){
this.constantValue = constantValue;
}
public FieldConstantHolder(){
this(null);
}
public void setValue(T o) {
this.constantValue = o;
}
public T getValue() {
return this.constantValue;
}
@Override
public String getPath() {
return null;
}
}
package com.brilliance.mda.runtime.mda.impl;
import com.brilliance.mda.runtime.mda.IStream;
import com.fasterxml.jackson.annotation.JsonIgnore;
import java.io.*;
import java.util.Arrays;
public class StreamImpl extends DataGrid implements IStream,Serializable {
transient ByteArrayOutputStream bos = new ByteArrayOutputStream();
private String name;
private String type;
private String value;
@JsonIgnore
public InputStream getInputStream()
{
return new ByteArrayInputStream(this.bos.toByteArray());
}
@JsonIgnore
public OutputStream getOutputStream()
{
return this.bos;
}
public boolean isEmpty()
{
for (String row : getRows()) {
if (!row.trim().isEmpty()){
return false;
}
}
return true;
}
@JsonIgnore
public String getValue()
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i < rows.size(); i++) {
sb.append(rows.get(i));
if(i<rows.size() - 1)
sb.append("\r\n");
}
return sb.toString();
}
@JsonIgnore
public Class getDataType()
{
return String.class;
}
@JsonIgnore
public String getName()
{
return this.name;
}
@JsonIgnore
public void setName(String name)
{
this.name = name;
}
@JsonIgnore
public String getType()
{
return this.type;
}
@JsonIgnore
public void setType(String type)
{
this.type = type;
}
public long size()
{
return this.bos.size();
}
public void close()
{
this.bos.reset();
this.clearLines();
}
public String setValue(String value)
{
this.value = value;
if(value != null && value.length() > 0){
Arrays.stream(value.split("\r\n")).forEach(rows::add);
}
return value;
}
public String toString(){
return this.getValue();
}
}
package com.brilliance.mda.runtime.mda.util;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import java.util.Optional;
@Component
public class ApplicationContextHolder implements ApplicationContextAware {
private static ApplicationContext context;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
context = applicationContext;
}
public static <T> Optional<T> getBean(Class<T> type){
if(context == null){
return Optional.empty();
}
return Optional.of(context.getBean(type));
}
public static <T> Optional<T> getBean(String name,Class<T> type){
if(context == null){
return Optional.empty();
}
return Optional.of(context.getBean(name,type));
}
}
package com.brilliance.mda.runtime.request;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class BaseVO {
protected Map<String,Object> params = new HashMap<>();
protected List changes;
protected String pageId;
/**新增,用于记录码表,使快照上的码值能正确显示**/
protected Map<String, List<String>> valuesSet;
public Map<String, Object> getParams() {
return params;
}
public void setParams(Map<String, Object> params) {
this.params = params;
}
public List getChanges() {
return changes;
}
public void setChanges(List changes) {
this.changes = changes;
}
protected Map<String, Map<String, Object>> statusInfo = new HashMap<>();
public String getPageId() {
return pageId;
}
public void setPageId(String pageId) {
this.pageId = pageId;
}
public Map<String, Map<String, Object>> getStatusInfo() {
return statusInfo;
}
public Map<String, List<String>> getValuesSet() {
return valuesSet;
}
public void setValuesSet(Map<String, List<String>> valuesSet) {
this.valuesSet = valuesSet;
}
}
package com.brilliance.mda.runtime.request;
public class RequestSet<T> {
private T data;
private String changes;
public Object getData(){
return this.data;
}
public void setData(T data) {
this.data = data;
}
}
package com.brilliance.mda.support.cache;
public interface ICache<K, V> {
K store(V v);
default void store(String key,V v){
}
V get(K k);
void remove(K k);
String generateKey();
default void keeplive(K key){
get(key);
}
default void cleanup(){
};
default boolean contains(K key){
return false;
};
String CTX_CACHE="ctxCache";
String AUTH_CACHE="authCache";
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment