提交 7c4f6380 编写于 作者: O o2null

Merge branch 'feat/dynamicCompile' into 'develop'

Feat/dynamic compile

See merge request o2oa/o2oa!427
......@@ -48,4 +48,4 @@ then
exit 1
fi
fi
setsid ${current_dir}/jvm/linux_java11/bin/java -Dnashorn.args=--no-deprecation-warning --add-exports jdk.scripting.nashorn/jdk.nashorn.internal.runtime=ALL-UNNAMED --add-exports jdk.scripting.nashorn/jdk.nashorn.internal.runtime.arrays=ALL-UNNAMED --add-opens java.base/java.lang=ALL-UNNAMED -javaagent:${current_dir}/console.jar -server -Djava.awt.headless=true -Xms512m -XX:MinHeapFreeRatio=20 -XX:MaxHeapFreeRatio=40 -Duser.timezone=GMT+08 -XX:+HeapDumpOnOutOfMemoryError -jar ${current_dir}/console.jar
\ No newline at end of file
setsid ${current_dir}/jvm/linux_java11/bin/java -Dnashorn.args=--no-deprecation-warning --add-exports jdk.scripting.nashorn/jdk.nashorn.internal.runtime=ALL-UNNAMED --add-exports jdk.scripting.nashorn/jdk.nashorn.internal.runtime.arrays=ALL-UNNAMED --add-opens java.base/java.lang=ALL-UNNAMED -javaagent:${current_dir}/console.jar -server -Djava.awt.headless=true -Xms512m -Xmx2g -XX:MinHeapFreeRatio=20 -XX:MaxHeapFreeRatio=40 -Duser.timezone=GMT+08 -XX:+HeapDumpOnOutOfMemoryError -jar ${current_dir}/console.jar
\ No newline at end of file
......@@ -17,18 +17,28 @@ import com.x.base.core.entity.annotation.CheckRemove;
public class EntityManagerContainerFactory extends SliceEntityManagerContainerFactory {
private volatile static EntityManagerContainerFactory instance;
private static EntityManagerContainerFactory instance;
public static void init(String webApplicationDirectory, List<String> entities) throws Exception {
synchronized (EntityManagerContainerFactory.class) {
if (instance != null) {
EntityManagerContainerFactory.close();
}
instance = new EntityManagerContainerFactory(webApplicationDirectory, entities);
instance = new EntityManagerContainerFactory(webApplicationDirectory, entities, null);
}
}
public static void init(String source) throws Exception {
public static void init(String webApplicationDirectory, List<String> entities, ClassLoader classLoader)
throws Exception {
synchronized (EntityManagerContainerFactory.class) {
if (instance != null) {
EntityManagerContainerFactory.close();
}
instance = new EntityManagerContainerFactory(webApplicationDirectory, entities, classLoader);
}
}
public static void init(String source) {
synchronized (EntityManagerContainerFactory.class) {
if (instance != null) {
EntityManagerContainerFactory.close();
......@@ -37,7 +47,7 @@ public class EntityManagerContainerFactory extends SliceEntityManagerContainerFa
}
}
public static void init() throws Exception {
public static void init() {
synchronized (EntityManagerContainerFactory.class) {
if (instance != null) {
EntityManagerContainerFactory.close();
......@@ -46,27 +56,23 @@ public class EntityManagerContainerFactory extends SliceEntityManagerContainerFa
}
}
public static EntityManagerContainerFactory instance() throws Exception {
public static EntityManagerContainerFactory instance() {
if (instance == null) {
throw new Exception("get EntityManagerContainerFactory instance error, not initial.");
throw new IllegalStateException("get EntityManagerContainerFactory instance error, not initial.");
}
return instance;
}
private EntityManagerContainerFactory(String webApplicationDirectory, List<String> entities) throws Exception {
super(webApplicationDirectory, entities,false);
}
private EntityManagerContainerFactory(String webApplicationDirectory, List<String> entities,
boolean sliceFeatureEnable) throws Exception {
super(webApplicationDirectory, entities,sliceFeatureEnable);
ClassLoader classLoader) throws Exception {
super(webApplicationDirectory, entities, false, classLoader);
}
private EntityManagerContainerFactory(String source) throws Exception {
private EntityManagerContainerFactory(String source) {
super(source);
}
public static void close() throws Exception {
public static void close() {
try {
if (instance != null) {
for (EntityManagerFactory emf : instance.entityManagerFactoryMap.values()) {
......@@ -87,42 +93,42 @@ public class EntityManagerContainerFactory extends SliceEntityManagerContainerFa
/* 由于可能重新载入 */
instance = null;
} catch (Exception e) {
throw new Exception("close error.", e);
throw new IllegalStateException("close error.", e);
}
}
public EntityManagerContainer create() {
EntityManagerContainer container = new EntityManagerContainer(this);
return container;
return new EntityManagerContainer(this);
}
public <T extends JpaObject> EntityManager createEntityManager(Class<T> cls) throws Exception {
public <T extends JpaObject> EntityManager createEntityManager(Class<T> cls) {
try {
for (Class<?> clazz : entityManagerFactoryMap.keySet()) {
if (clazz.isAssignableFrom(cls)) {
return entityManagerFactoryMap.get(clazz).createEntityManager();
for (Map.Entry<Class<? extends JpaObject>, EntityManagerFactory> en : entityManagerFactoryMap.entrySet()) {
if (en.getKey().isAssignableFrom(cls)) {
return entityManagerFactoryMap.get(en.getKey()).createEntityManager();
}
}
throw new Exception("can not createEntityManager for class " + cls.getName()
throw new IllegalStateException("can not createEntityManager for class " + cls.getName()
+ ", not registed in EntityManagerContainerFactory.");
} catch (Exception e) {
throw new Exception("get entityManager for " + cls + " error.", e);
throw new IllegalStateException("get entityManager for " + cls + " error.", e);
}
}
public Map<Field, CheckPersist> getCheckPersistFields(Class<?> clazz) throws Exception {
public Map<Field, CheckPersist> getCheckPersistFields(Class<?> clazz) {
return checkPersistFieldMap.get(assignableFrom(clazz));
}
public Map<Field, CheckRemove> getCheckRemoveFields(Class<?> clazz) throws Exception {
public Map<Field, CheckRemove> getCheckRemoveFields(Class<?> clazz) {
return checkRemoveFieldMap.get(assignableFrom(clazz));
}
public List<Field> getFlagFields(Class<?> clazz) throws Exception {
public List<Field> getFlagFields(Class<?> clazz) {
return flagMap.get(assignableFrom(clazz));
}
public List<Field> getRestrictFlagFields(Class<?> clazz) throws Exception {
public List<Field> getRestrictFlagFields(Class<?> clazz) {
return restrictFlagMap.get(assignableFrom(clazz));
}
}
......@@ -2,18 +2,13 @@ package com.x.base.core.container.factory;
import java.io.File;
import java.io.FileWriter;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Properties;
import com.x.base.core.container.FactorDistributionPolicy;
import com.x.base.core.entity.dynamic.DynamicBaseEntity;
import com.x.base.core.entity.JpaObject;
import com.x.base.core.entity.dynamic.DynamicEntity;
import com.x.base.core.entity.tools.JpaObjectTools;
import com.x.base.core.project.config.Config;
import com.x.base.core.project.config.Node;
import com.x.base.core.project.tools.ListTools;
import java.util.Set;
import java.util.TreeSet;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.BooleanUtils;
......@@ -26,34 +21,41 @@ import org.dom4j.QName;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;
import com.x.base.core.container.FactorDistributionPolicy;
import com.x.base.core.entity.JpaObject;
import com.x.base.core.entity.annotation.ContainerEntity;
import com.x.base.core.entity.dynamic.DynamicBaseEntity;
import com.x.base.core.entity.dynamic.DynamicEntity;
import com.x.base.core.entity.tools.JpaObjectTools;
import com.x.base.core.project.config.Config;
import com.x.base.core.project.config.Node;
import com.x.base.core.project.tools.ListTools;
import io.github.classgraph.ClassGraph;
import io.github.classgraph.ClassInfo;
import io.github.classgraph.ScanResult;
public class PersistenceXmlHelper {
private PersistenceXmlHelper() {
}
public static List<String> directWrite(String path, List<String> classNames) throws Exception {
public static List<String> directWriteDynamicEnhance(String path, List<String> classNames) throws Exception {
try {
Document document = DocumentHelper.createDocument();
Element persistence = document.addElement("persistence", "http://java.sun.com/xml/ns/persistence");
persistence.addAttribute(QName.get("schemaLocation", "xsi", "http://www.w3.org/2001/XMLSchema-instance"),
"http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd");
persistence.addAttribute("version", "2.0");
Element persistence = createPersistenceElement(document);
Element unit = persistence.addElement("persistence-unit");
unit.addAttribute("name", "dynamic");
unit.addAttribute("transaction-type", "RESOURCE_LOCAL");
unit.addElement("provider").addText(PersistenceProviderImpl.class.getName());
for (String className : classNames) {
Element unit = persistence.addElement("persistence-unit");
unit.addAttribute("name", className);
unit.addAttribute("transaction-type", "RESOURCE_LOCAL");
Element provider = unit.addElement("provider");
provider.addText(PersistenceProviderImpl.class.getName());
Element mapped_element = unit.addElement("class");
mapped_element.addText(className);
Element sliceJpaObject_element = unit.addElement("class");
sliceJpaObject_element.addText("com.x.base.core.entity.SliceJpaObject");
Element jpaObject_element = unit.addElement("class");
jpaObject_element.addText("com.x.base.core.entity.JpaObject");
unit.addElement("class").addText(className);
}
unit.addElement("class").addText("com.x.base.core.entity.SliceJpaObject");
unit.addElement("class").addText("com.x.base.core.entity.JpaObject");
OutputFormat format = OutputFormat.createPrettyPrint();
format.setEncoding("UTF-8");
format.setEncoding(StandardCharsets.UTF_8.name());
File file = new File(path);
FileUtils.touch(file);
XMLWriter writer = new XMLWriter(new FileWriter(file), format);
......@@ -65,13 +67,19 @@ public class PersistenceXmlHelper {
}
}
private static Element createPersistenceElement(Document document) {
Element persistence = document.addElement("persistence", "http://java.sun.com/xml/ns/persistence");
persistence.addAttribute(QName.get("schemaLocation", "xsi", "http://www.w3.org/2001/XMLSchema-instance"),
"http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd");
persistence.addAttribute("version", "2.0");
return persistence;
}
@SuppressWarnings("unchecked")
public static void writeForDdl(String path) throws Exception {
try {
Document document = DocumentHelper.createDocument();
Element persistence = document.addElement("persistence", "http://java.sun.com/xml/ns/persistence");
persistence.addAttribute(QName.get("schemaLocation", "xsi", "http://www.w3.org/2001/XMLSchema-instance"),
"http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd");
persistence.addAttribute("version", "2.0");
Element persistence = createPersistenceElement(document);
Element unit = persistence.addElement("persistence-unit");
unit.addAttribute("name", "enhance");
unit.addAttribute("transaction-type", "RESOURCE_LOCAL");
......@@ -79,15 +87,15 @@ public class PersistenceXmlHelper {
provider.addText(PersistenceProviderImpl.class.getName());
List<String> entities = new ArrayList<>();
for (String className : (List<String>) Config.resource(Config.RESOURCE_CONTAINERENTITYNAMES)) {
Class<? extends JpaObject> clazz = (Class<JpaObject>) Class.forName(className);
Class<? extends JpaObject> clazz = (Class<JpaObject>) Thread.currentThread().getContextClassLoader()
.loadClass(className);
for (Class<?> o : JpaObjectTools.scanMappedSuperclass(clazz)) {
entities.add(o.getName());
}
}
entities = ListTools.trim(entities, true, true);
for (String className : entities) {
Element class_element = unit.addElement("class");
class_element.addText(className);
unit.addElement("class").addText(className);
}
Element properties = unit.addElement("properties");
if (BooleanUtils.isTrue(Config.externalDataSources().enable())) {
......@@ -147,57 +155,30 @@ public class PersistenceXmlHelper {
property.addAttribute("value", "false");
}
public static List<String> write(String path, List<String> entities, boolean dynamicFlag) throws Exception {
@SuppressWarnings("unchecked")
public static List<String> write(String path, List<String> entities, ClassLoader classLoader) {
List<String> names = new ArrayList<>();
String name = "";
try {
names.addAll((List<String>) Config.resource(Config.RESOURCE_CONTAINERENTITYNAMES));
names = ListTools.includesExcludesWildcard(names, entities, null);
Document document = DocumentHelper.createDocument();
Element persistence = document.addElement("persistence", "http://java.sun.com/xml/ns/persistence");
persistence.addAttribute(QName.get("schemaLocation", "xsi", "http://www.w3.org/2001/XMLSchema-instance"),
"http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd");
persistence.addAttribute("version", "2.0");
List<String> dyClasses = new ArrayList<>();
Element persistence = createPersistenceElement(document);
ClassLoader cl = (null == classLoader) ? Thread.currentThread().getContextClassLoader() : classLoader;
for (String className : names) {
name = className;
Class<? extends JpaObject> clazz = (Class<JpaObject>) Class.forName(className);
Class<? extends JpaObject> clazz = (Class<JpaObject>) cl.loadClass(className);
Element unit = persistence.addElement("persistence-unit");
unit.addAttribute("name", className);
unit.addAttribute("transaction-type", "RESOURCE_LOCAL");
Element provider = unit.addElement("provider");
provider.addText(PersistenceProviderImpl.class.getName());
for (Class<?> o : JpaObjectTools.scanMappedSuperclass(clazz)) {
Element mapped_element = unit.addElement("class");
mapped_element.addText(o.getName());
unit.addElement("class").addText(o.getName());
}
}
if (dynamicFlag) {
for (String className : names) {
if (className.startsWith(DynamicEntity.CLASS_PACKAGE)) {
dyClasses.add(className);
}
}
if (!dyClasses.isEmpty()) {
String dyClassName = DynamicBaseEntity.class.getName();
names.add(dyClassName);
Element unit = persistence.addElement("persistence-unit");
unit.addAttribute("name", dyClassName);
unit.addAttribute("transaction-type", "RESOURCE_LOCAL");
Element provider = unit.addElement("provider");
provider.addText(PersistenceProviderImpl.class.getName());
for (String dyClass : dyClasses) {
Element mapped_element = unit.addElement("class");
mapped_element.addText(dyClass);
}
for (Class<?> o : JpaObjectTools.scanMappedSuperclass(DynamicBaseEntity.class)) {
if (!o.getName().equals(DynamicBaseEntity.class.getName())) {
Element mapped_element = unit.addElement("class");
mapped_element.addText(o.getName());
}
}
}
if (null != classLoader) {
names.addAll(addDynamicClassCreateCombineUnit(persistence, cl));
}
OutputFormat format = OutputFormat.createPrettyPrint();
format.setEncoding("UTF-8");
......@@ -208,27 +189,66 @@ public class PersistenceXmlHelper {
writer.close();
return names;
} catch (Exception e) {
throw new Exception("write error.className:" + name, e);
throw new IllegalStateException("write error.className:" + name, e);
}
}
private static Collection<String> addDynamicClassCreateCombineUnit(Element persistence, ClassLoader cl)
throws ClassNotFoundException {
Set<String> names = new TreeSet<>();
Set<String> combineNames = new TreeSet<>();
try (ScanResult sr = new ClassGraph().addClassLoader(cl).enableAnnotationInfo().scan()) {
for (ClassInfo info : sr.getClassesWithAnnotation(ContainerEntity.class.getName())) {
Class<?> cls = cl.loadClass(info.getName());
if (StringUtils.startsWith(cls.getName(), DynamicEntity.CLASS_PACKAGE)) {
names.add(cls.getName());
for (Class<?> o : JpaObjectTools.scanMappedSuperclass(cls)) {
combineNames.add(o.getName());
}
}
}
}
if (!names.isEmpty()) {
for (String className : names) {
@SuppressWarnings("unchecked")
Class<? extends JpaObject> clazz = (Class<JpaObject>) cl.loadClass(className);
Element unit = persistence.addElement("persistence-unit");
unit.addAttribute("name", className);
unit.addAttribute("transaction-type", "RESOURCE_LOCAL");
Element provider = unit.addElement("provider");
provider.addText(PersistenceProviderImpl.class.getName());
for (Class<?> o : JpaObjectTools.scanMappedSuperclass(clazz)) {
unit.addElement("class").addText(o.getName());
}
}
Element unit = persistence.addElement("persistence-unit");
unit.addAttribute("name", DynamicBaseEntity.class.getName());
unit.addAttribute("transaction-type", "RESOURCE_LOCAL");
unit.addElement("provider").addText(PersistenceProviderImpl.class.getName());
for (String name : combineNames) {
unit.addElement("class").addText(name);
}
}
return names;
}
public static Properties properties(String className, boolean sliceFeatureEnable) throws Exception {
if (sliceFeatureEnable) {
if (Config.externalDataSources().enable()) {
return properties_external_slice(className);
if (BooleanUtils.isTrue(Config.externalDataSources().enable())) {
return propertiesExternalSlice(className);
} else {
return properties_internal_slice(className);
return propertiesInternalSlice(className);
}
} else {
if (Config.externalDataSources().enable()) {
return properties_external_single(className);
if (BooleanUtils.isTrue(Config.externalDataSources().enable())) {
return propertiesExternalSingle(className);
} else {
return properties_internal_single(className);
return propertiesInternalSingle(className);
}
}
}
private static Properties properties_base_slice(String className) throws Exception {
private static Properties propertiesBaseSlice(String className) throws Exception {
Properties properties = new Properties();
properties.put("openjpa.BrokerFactory", "slice");
properties.put("openjpa.slice.Lenient", "false");
......@@ -246,8 +266,8 @@ public class PersistenceXmlHelper {
return properties;
}
private static Properties properties_external_slice(String className) throws Exception {
Properties properties = properties_base_slice(className);
private static Properties propertiesExternalSlice(String className) throws Exception {
Properties properties = propertiesBaseSlice(className);
properties.put("openjpa.jdbc.DBDictionary", Config.externalDataSources().dictionary());
/* 如果是DB2 添加 Schema,mysql 不需要Schema 如果用了Schema H2数据库就会报错说没有Schema */
if (Config.externalDataSources().hasSchema()) {
......@@ -262,8 +282,8 @@ public class PersistenceXmlHelper {
return properties;
}
private static Properties properties_internal_slice(String className) throws Exception {
Properties properties = properties_base_slice(className);
private static Properties propertiesInternalSlice(String className) throws Exception {
Properties properties = propertiesBaseSlice(className);
properties.put("openjpa.jdbc.DBDictionary", SlicePropertiesBuilder.dictionary_h2);
properties.put("openjpa.slice.Names",
StringUtils.join(Config.nodes().dataServers().findNamesOfContainerEntity(className), ","));
......@@ -274,7 +294,7 @@ public class PersistenceXmlHelper {
return properties;
}
private static Properties properties_base_single(String className) throws Exception {
private static Properties propertiesBaseSingle(String className) throws Exception {
Properties properties = new Properties();
properties.put("openjpa.QueryCompilationCache", "false");
properties.put("openjpa.IgnoreChanges", "true");
......@@ -290,8 +310,8 @@ public class PersistenceXmlHelper {
return properties;
}
private static Properties properties_external_single(String className) throws Exception {
Properties properties = properties_base_single(className);
private static Properties propertiesExternalSingle(String className) throws Exception {
Properties properties = propertiesBaseSingle(className);
properties.put("openjpa.jdbc.DBDictionary", Config.externalDataSources().dictionary());
/* 如果是DB2 添加 Schema,mysql 不需要Schema 如果用了Schema H2数据库就会报错说没有Schema */
if (Config.externalDataSources().hasSchema()) {
......@@ -308,8 +328,8 @@ public class PersistenceXmlHelper {
return properties;
}
private static Properties properties_internal_single(String className) throws Exception {
Properties properties = properties_base_single(className);
private static Properties propertiesInternalSingle(String className) throws Exception {
Properties properties = propertiesBaseSingle(className);
properties.put("openjpa.jdbc.DBDictionary", SlicePropertiesBuilder.dictionary_h2);
for (String name : Config.nodes().dataServers().findNamesOfContainerEntity(className)) {
properties.put("openjpa.ConnectionFactoryName", Config.RESOURCE_JDBC_PREFIX + name);
......
......@@ -29,29 +29,36 @@ import com.x.base.core.entity.annotation.CheckPersist;
import com.x.base.core.entity.annotation.CheckRemove;
import com.x.base.core.entity.annotation.Flag;
import com.x.base.core.entity.annotation.RestrictFlag;
import com.x.base.core.entity.dynamic.DynamicBaseEntity;
import com.x.base.core.entity.dynamic.DynamicEntity;
import com.x.base.core.project.gson.XGsonBuilder;
import com.x.base.core.project.tools.ClassLoaderTools;
public abstract class SliceEntityManagerContainerFactory {
protected static String META_INF = "META-INF";
protected static String PERSISTENCE_XML_PATH = META_INF + "/persistence.xml";
protected static final String META_INF = "META-INF";
protected static final String PERSISTENCE_XML_PATH = META_INF + "/persistence.xml";
/* class 与 entityManagerFactory 映射表 */
protected Map<Class<? extends JpaObject>, EntityManagerFactory> entityManagerFactoryMap = new ConcurrentHashMap<Class<? extends JpaObject>, EntityManagerFactory>();
protected Map<Class<? extends JpaObject>, EntityManagerFactory> entityManagerFactoryMap = new ConcurrentHashMap<>();
/* class 与 @Flag字段 映射表 */
protected Map<Class<? extends JpaObject>, List<Field>> flagMap = new ConcurrentHashMap<Class<? extends JpaObject>, List<Field>>();
protected Map<Class<? extends JpaObject>, List<Field>> flagMap = new ConcurrentHashMap<>();
/* class 与 entityManagerFactory 映射表 */
protected Map<Class<? extends JpaObject>, List<Field>> restrictFlagMap = new ConcurrentHashMap<Class<? extends JpaObject>, List<Field>>();
protected Map<Class<? extends JpaObject>, List<Field>> restrictFlagMap = new ConcurrentHashMap<>();
/* class 与 class 中需要检查 Persist 字段的对应表 */
protected Map<Class<? extends JpaObject>, Map<Field, CheckPersist>> checkPersistFieldMap = new ConcurrentHashMap<Class<? extends JpaObject>, Map<Field, CheckPersist>>();
protected Map<Class<? extends JpaObject>, Map<Field, CheckPersist>> checkPersistFieldMap = new ConcurrentHashMap<>();
/* class 与 class 中需要检查 Remove 字段的对应表 */
protected Map<Class<? extends JpaObject>, Map<Field, CheckRemove>> checkRemoveFieldMap = new ConcurrentHashMap<Class<? extends JpaObject>, Map<Field, CheckRemove>>();
protected Map<Class<? extends JpaObject>, Map<Field, CheckRemove>> checkRemoveFieldMap = new ConcurrentHashMap<>();
@SuppressWarnings("unchecked")
protected SliceEntityManagerContainerFactory(String webApplicationDirectory, List<String> entities,
boolean sliceFeatureEnable) throws Exception {
boolean sliceFeatureEnable, ClassLoader classLoader) throws Exception {
File path = new File(webApplicationDirectory + "/WEB-INF/classes/" + PERSISTENCE_XML_PATH);
List<String> classNames = PersistenceXmlHelper.write(path.getAbsolutePath(), entities, true);
List<String> classNames = PersistenceXmlHelper.write(path.getAbsolutePath(), entities, classLoader);
ClassLoader cl = null == classLoader ? Thread.currentThread().getContextClassLoader() : classLoader;
Class<? extends JpaObject> clz;
for (String className : classNames) {
Class<? extends JpaObject> clz = (Class<? extends JpaObject>) Class.forName(className);
clz = (Class<? extends JpaObject>) cl.loadClass(className);
checkPersistFieldMap.put(clz, this.loadCheckPersistField(clz));
checkRemoveFieldMap.put(clz, this.loadCheckRemoveField(clz));
Properties properties = PersistenceXmlHelper.properties(clz.getName(), sliceFeatureEnable);
......@@ -73,9 +80,19 @@ public abstract class SliceEntityManagerContainerFactory {
flagMap.put(clz, Collections.unmodifiableList(flagFields));
restrictFlagMap.put(clz, Collections.unmodifiableList(restrictFlagFields));
}
if (null != classLoader) {
clz = (Class<? extends JpaObject>) cl.loadClass("com.x.base.core.entity.dynamic.DynamicBaseEntity");
checkPersistFieldMap.put(clz, new HashMap<>());
checkRemoveFieldMap.put(clz, new HashMap<>());
Properties properties = PersistenceXmlHelper.properties(clz.getName(), sliceFeatureEnable);
entityManagerFactoryMap.put(clz,
OpenJPAPersistence.createEntityManagerFactory(clz.getName(), PERSISTENCE_XML_PATH, properties));
flagMap.put(clz, new ArrayList<>());
restrictFlagMap.put(clz, new ArrayList<>());
}
}
protected SliceEntityManagerContainerFactory(String source) throws Exception {
protected SliceEntityManagerContainerFactory(String source) {
Set<Class<? extends JpaObject>> classes = this.listUnitClass(source);
for (Class<? extends JpaObject> clz : classes) {
checkPersistFieldMap.put(clz, this.loadCheckPersistField(clz));
......@@ -100,17 +117,17 @@ public abstract class SliceEntityManagerContainerFactory {
}
@SuppressWarnings("unchecked")
public <T> Class<T> assignableFrom(Class<T> cls) throws Exception {
public <T> Class<T> assignableFrom(Class<T> cls) {
for (Class<?> clazz : this.entityManagerFactoryMap.keySet()) {
if (clazz.isAssignableFrom(cls)) {
return (Class<T>) clazz;
}
}
throw new Exception("can not find jpa assignable class for " + cls + ".");
throw new IllegalStateException("can not find jpa assignable class for " + cls + ".");
}
private <T extends JpaObject> Map<Field, CheckPersist> loadCheckPersistField(Class<T> cls) throws Exception {
Map<Field, CheckPersist> map = new HashMap<Field, CheckPersist>();
private <T extends JpaObject> Map<Field, CheckPersist> loadCheckPersistField(Class<T> cls) {
Map<Field, CheckPersist> map = new HashMap<>();
for (Field fld : cls.getDeclaredFields()) {
CheckPersist checkPersist = fld.getAnnotation(CheckPersist.class);
if (null != checkPersist) {
......@@ -120,8 +137,8 @@ public abstract class SliceEntityManagerContainerFactory {
return map;
}
private <T extends JpaObject> Map<Field, CheckRemove> loadCheckRemoveField(Class<T> cls) throws Exception {
Map<Field, CheckRemove> map = new HashMap<Field, CheckRemove>();
private <T extends JpaObject> Map<Field, CheckRemove> loadCheckRemoveField(Class<T> cls) {
Map<Field, CheckRemove> map = new HashMap<>();
for (Field fld : cls.getDeclaredFields()) {
CheckRemove checkRemove = fld.getAnnotation(CheckRemove.class);
if (null != checkRemove) {
......@@ -131,7 +148,8 @@ public abstract class SliceEntityManagerContainerFactory {
return map;
}
private Set<Class<? extends JpaObject>> listUnitClass(String source) throws Exception {
@SuppressWarnings("unchecked")
private Set<Class<? extends JpaObject>> listUnitClass(String source) {
try {
Set<Class<? extends JpaObject>> classes = new HashSet<>();
URL url;
......@@ -141,19 +159,53 @@ public abstract class SliceEntityManagerContainerFactory {
url = this.getClass().getClassLoader().getResource(source);
}
if (null == url) {
throw new Exception("can not load resource: " + source + ".");
throw new IllegalStateException("can not load resource: " + source + ".");
}
File file = new File(url.toURI());
SAXReader reader = new SAXReader();
reader.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
reader.setFeature("http://xml.org/sax/features/external-general-entities", false);
reader.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
Document document = reader.read(file);
for (Object o : document.getRootElement().elements("persistence-unit")) {
Element unit = (Element) o;
classes.add((Class<JpaObject>) Class.forName(unit.attribute("name").getValue()));
for (Element unit : document.getRootElement().elements("persistence-unit")) {
classes.add((Class<JpaObject>) Thread.currentThread().getContextClassLoader().loadClass(unit.attribute("name").getValue()));
}
return classes;
} catch (Exception e) {
throw new Exception("list unit error:" + source, e);
throw new IllegalStateException("list unit error:" + source, e);
}
}
// public void refreshDynamicEntity(String webApplicationDirectory, List<String> entities) throws Exception {
// File path = new File(webApplicationDirectory + "/WEB-INF/classes/" + PERSISTENCE_XML_PATH);
// List<String> classNames = PersistenceXmlHelper.write(path.getAbsolutePath(), entities, true);
// ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
// for (String className : classNames) {
// if (className.startsWith(DynamicEntity.CLASS_PACKAGE)
// || className.equals(DynamicBaseEntity.class.getName())) {
// @SuppressWarnings("unchecked")
// Class<? extends JpaObject> clz = (Class<? extends JpaObject>) classLoader.loadClass(className);
// checkPersistFieldMap.put(clz, this.loadCheckPersistField(clz));
// checkRemoveFieldMap.put(clz, this.loadCheckRemoveField(clz));
// Properties properties = PersistenceXmlHelper.properties(clz.getName(), false);
// entityManagerFactoryMap.put(clz,
// OpenJPAPersistence.createEntityManagerFactory(clz.getName(), PERSISTENCE_XML_PATH, properties));
// List<Field> flagFields = new ArrayList<>();
// List<Field> restrictFlagFields = new ArrayList<>();
// for (Field o : FieldUtils.getFieldsListWithAnnotation(clz, Id.class)) {
// flagFields.add(o);
// restrictFlagFields.add(o);
// }
// for (Field o : FieldUtils.getFieldsListWithAnnotation(clz, Flag.class)) {
// flagFields.add(o);
// restrictFlagFields.add(o);
// }
// for (Field o : FieldUtils.getFieldsListWithAnnotation(clz, RestrictFlag.class)) {
// restrictFlagFields.add(o);
// }
// flagMap.put(clz, Collections.unmodifiableList(flagFields));
// restrictFlagMap.put(clz, Collections.unmodifiableList(restrictFlagFields));
// }
// }
// }
}
\ No newline at end of file
......@@ -72,7 +72,7 @@ public class JsonPropertiesValueHandler extends AbstractValueHandler {
return null;
try {
String className = vm.getDeclaredType().getName();
Class<?> cls = Class.forName(className);
Class<?> cls = Thread.currentThread().getContextClassLoader().loadClass(className);
return gson.fromJson(val.toString(), cls);
} catch (ClassNotFoundException e) {
throw new InternalException(e);
......
......@@ -61,11 +61,6 @@ public class DynamicEntity extends GsonPropertyObject {
return CLASS_PACKAGE + "." + name;
}
@SuppressWarnings("unchecked")
public Class<? extends JpaObject> getObjectClass() throws Exception {
return (Class<? extends JpaObject>) Class.forName(this.className());
}
public DynamicEntity() {
this.fieldList = new ArrayList<>();
}
......
......@@ -91,10 +91,10 @@ public class EnhanceBuilder {
List<Class<?>> list = new ArrayList<Class<?>>();
try (ScanResult sr = new ClassGraph().enableAnnotationInfo().disableJarScanning().scan()) {
for (ClassInfo info : sr.getClassesWithAnnotation(Entity.class.getName())) {
list.add(Class.forName(info.getName()));
list.add(Thread.currentThread().getContextClassLoader().loadClass(info.getName()));
}
for (ClassInfo info : sr.getClassesWithAnnotation(MappedSuperclass.class.getName())) {
list.add(Class.forName(info.getName()));
list.add(Thread.currentThread().getContextClassLoader().loadClass(info.getName()));
}
return list.stream().sorted(Comparator.comparing(Class::getName)).collect(Collectors.toList());
}
......
......@@ -69,7 +69,7 @@ public class EnhancePersistenceXmlWriter {
try (ScanResult scanResult = new ClassGraph().enableAnnotationInfo().scan()) {
List<ClassInfo> classInfos = scanResult.getClassesWithAnnotation(Entity.class.getName());
for (ClassInfo info : classInfos) {
list.add(Class.forName(info.getName()));
list.add(Thread.currentThread().getContextClassLoader().loadClass(info.getName()));
}
return list.stream().sorted(Comparator.comparing(Class::getName)).collect(Collectors.toList());
}
......
......@@ -7,18 +7,27 @@ import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.TreeSet;
import javax.persistence.Column;
import javax.persistence.EntityManager;
import javax.persistence.MappedSuperclass;
import javax.persistence.criteria.Path;
import org.apache.commons.collections4.ListUtils;
import org.apache.commons.lang3.reflect.FieldUtils;
import org.apache.openjpa.persistence.jdbc.ElementColumn;
import com.x.base.core.entity.JpaObject;
import com.x.base.core.entity.annotation.ContainerEntity;
import com.x.base.core.project.annotation.Module;
import com.x.base.core.project.tools.ListTools;
import com.x.base.core.project.tools.StringTools;
import io.github.classgraph.ClassGraph;
import io.github.classgraph.ClassInfo;
import io.github.classgraph.ScanResult;
public class JpaObjectTools {
public static boolean isList(Path<?> path) {
......@@ -109,4 +118,29 @@ public class JpaObjectTools {
}
}
public static Collection<String> scanContainerEntityNames(ClassLoader classLoader) throws ClassNotFoundException {
Set<String> set = new TreeSet<>();
try (ScanResult sr = new ClassGraph().addClassLoader(classLoader).enableAnnotationInfo().scan()) {
for (ClassInfo info : sr.getClassesWithAnnotation(ContainerEntity.class.getName())) {
@SuppressWarnings("unchecked")
Class<? extends JpaObject> cls = (Class<? extends JpaObject>) classLoader.loadClass(info.getName());
set.add(cls.getName());
}
}
return set;
}
public static Collection<Class<? extends JpaObject>> scanContainerEntities(ClassLoader classLoader)
throws ClassNotFoundException {
Set<Class<? extends JpaObject>> set = new TreeSet<>();
try (ScanResult sr = new ClassGraph().addClassLoader(classLoader).enableAnnotationInfo().scan()) {
for (ClassInfo info : sr.getClassesWithAnnotation(ContainerEntity.class.getName())) {
@SuppressWarnings("unchecked")
Class<? extends JpaObject> cls = (Class<? extends JpaObject>) classLoader.loadClass(info.getName());
set.add(cls);
}
}
return set;
}
}
\ No newline at end of file
......@@ -79,11 +79,11 @@ public class PersistenceXmlWriter {
List<ClassInfo> classInfos = scanResult.getClassesWithAnnotation(Module.class.getName());
for (ClassInfo info : classInfos) {
if (StringUtils.equals(info.getSimpleName(), project)) {
Class<?> cls = Class.forName(info.getName());
Class<?> cls = Thread.currentThread().getContextClassLoader().loadClass(info.getName());
Module moudle = cls.getAnnotation(Module.class);
for (String str : moudle.containerEntities()) {
if (StringUtils.isNotEmpty(str)) {
list.add(Class.forName(str));
list.add(Thread.currentThread().getContextClassLoader().loadClass(str));
}
}
}
......@@ -92,25 +92,6 @@ public class PersistenceXmlWriter {
}
}
// @SuppressWarnings("unchecked")
// private static List<Class<?>> scanContainerEntity(String project) throws Exception {
// Set<Class<?>> ces = new HashSet<>();
// String className = "com.x.base.core.project." + project;
// Class<?> cls = Class.forName(className);
// for (String str : (List<String>) FieldUtils.readStaticField(cls, "containerEntities")) {
// if (StringUtils.isNotEmpty(str)) {
// ces.add(Class.forName(str));
// }
// }
// List<Class<?>> sortedList = new ArrayList<Class<?>>(ces);
// Collections.sort(sortedList, new Comparator<Class<?>>() {
// public int compare(Class<?> c1, Class<?> c2) {
// return c1.getCanonicalName().compareTo(c2.getCanonicalName());
// }
// });
// return sortedList;
// }
private static Set<Class<?>> scanMappedSuperclass(Class<?> clz) throws Exception {
Set<Class<?>> set = new HashSet<Class<?>>();
set.add(clz);
......
......@@ -131,15 +131,6 @@ public class Context extends AbstractContext {
private AbstractQueue<WrapClearCacheRequest> clearCacheRequestQueue;
// @Override
// public AbstractQueue<WrapClearCacheRequest> clearCacheRequestQueue() {
// return this.clearCacheRequestQueue;
// }
// public ThreadFactory threadFactory() {
// return this.threadFactory;
// }
/* 队列 */
private List<AbstractQueue<?>> queues;
......@@ -147,18 +138,22 @@ public class Context extends AbstractContext {
this.token = UUID.randomUUID().toString();
this.applications = new Applications();
this.queues = new ArrayList<>();
// this.scheduler = new StdSchedulerFactory(SchedulerFactoryProperties.concrete()).getScheduler();
// this.scheduler.getListenerManager().addJobListener(new JobReportListener(), EverythingMatcher.allJobs());
// this.scheduler.start();
}
public static Context concrete(ServletContextEvent servletContextEvent) throws Exception {
return concrete(servletContextEvent, null);
}
public static Context concrete(ServletContextEvent servletContextEvent, ClassLoader dynamicEntityClassLoader)
throws Exception {
// 强制忽略ssl服务器认证
SslTools.ignoreSsl();
ServletContext servletContext = servletContextEvent.getServletContext();
Context context = new Context();
context.contextPath = servletContext.getContextPath();
context.clazz = Class.forName(servletContext.getInitParameter(INITPARAMETER_PORJECT));
context.clazz = Thread.currentThread().getContextClassLoader()
.loadClass(servletContext.getInitParameter(INITPARAMETER_PORJECT));
context.module = context.clazz.getAnnotation(Module.class);
context.name = context.module.name();
context.path = servletContext.getRealPath("");
......@@ -167,7 +162,7 @@ public class Context extends AbstractContext {
context.weight = Config.currentNode().getApplication().weight(context.clazz);
context.scheduleWeight = Config.currentNode().getApplication().scheduleWeight(context.clazz);
context.sslEnable = Config.currentNode().getApplication().getSslEnable();
context.initDatas();
context.initDatas(dynamicEntityClassLoader);
servletContext.setAttribute(AbstractContext.class.getName(), context);
SchedulerFactoryProperties schedulerFactoryProperties = SchedulerFactoryProperties.concrete();
schedulerFactoryProperties.setProperty("org.quartz.scheduler.instanceName",
......@@ -196,10 +191,6 @@ public class Context extends AbstractContext {
JsonElement jsonElement = XGsonBuilder.instance().toJsonTree(application);
// 将当前的application写入到servletContext
servletContext.setAttribute(SERVLETCONTEXT_ATTRIBUTE_APPLICATION, jsonElement.toString());
// 发送注册到本地的信号
// JsonObject registApplicationLocal = jsonElement.getAsJsonObject();
// registApplicationLocal.addProperty("type", "registApplicationLocal");
// Config.resource_node_eventQueue().put(registApplicationLocal);
}
public <T extends AbstractJob> void scheduleLocal(Class<T> cls, String cron) throws Exception {
......@@ -284,7 +275,15 @@ public class Context extends AbstractContext {
if (ArrayUtils.isNotEmpty(this.module.containerEntities())) {
logger.info("{} loading datas, entity size:{}.", this.clazz.getName(),
this.module.containerEntities().length);
EntityManagerContainerFactory.init(path, ListTools.toList(this.module.containerEntities()));
EntityManagerContainerFactory.init(path, ListTools.toList(this.module.containerEntities()), null);
}
}
public void initDatas(ClassLoader classLoader) throws Exception {
if (ArrayUtils.isNotEmpty(this.module.containerEntities())) {
logger.info("{} loading datas, entity size:{}.", this.clazz.getName(),
this.module.containerEntities().length);
EntityManagerContainerFactory.init(path, ListTools.toList(this.module.containerEntities()), classLoader);
}
}
......
......@@ -488,8 +488,7 @@ public class DescribeWoBuilder {
typeName = ss[ss.length-1];
listParam = true;
}
//logger.print("Class.forName=" + typeName);
Class clz = Class.forName(typeName);
Class clz = Thread.currentThread().getContextClassLoader().loadClass(typeName);
if(!clz.isEnum()){
//不是枚举类型
List<Field> fields = FieldUtils.getAllFieldsList(clz);
......
......@@ -39,8 +39,6 @@ public @interface Module {
public String[] customJars() default {};
public String[] dynamicJars() default {};
public StorageType[] storageTypes() default {};
}
\ No newline at end of file
......@@ -28,7 +28,7 @@ public class CheckAssemble {
}
}
for (ClassInfo info : list) {
Class<?> cls = Class.forName(info.getName());
Class<?> cls = Thread.currentThread().getContextClassLoader().loadClass(info.getName());
if (FieldUtils.getFieldsListWithAnnotation(cls, FieldDescribe.class).isEmpty()) {
System.err.println(String.format("%s not set FieldDescribe", info.getName()));
}
......@@ -36,7 +36,7 @@ public class CheckAssemble {
try (ScanResult scanResult = new ClassGraph().disableJarScanning().enableAllInfo().scan()) {
ClassInfoList classInfoList = scanResult.getClassesWithAnnotation(WebFilter.class.getName());
for (ClassInfo info : classInfoList) {
Class cls = Class.forName(info.getName());
Class cls = Thread.currentThread().getContextClassLoader().loadClass(info.getName());
WebFilter webFilter = (WebFilter) cls.getAnnotation(WebFilter.class);
if (webFilter.asyncSupported() == false) {
System.err.println("webFilter not set asyncSupported:" + info.getName());
......
......@@ -36,7 +36,7 @@ public class CheckCore {
List<ClassInfo> classInfos = sr.getClassesWithAnnotation(ContainerEntity.class.getName());
List<Class<?>> classes = new ArrayList<>();
for (ClassInfo info : classInfos) {
classes.add(Class.forName(info.getName()));
classes.add(Thread.currentThread().getContextClassLoader().loadClass(info.getName()));
}
checkColumnName(classes);
checkColumnLength(classes);
......@@ -55,7 +55,7 @@ public class CheckCore {
List<ClassInfo> classInfos = scanResult.getClassesWithAnnotation(Module.class.getName());
for (ClassInfo info : classInfos) {
if (StringUtils.equals(info.getSimpleName(), name)) {
Class<?> cls = Class.forName(info.getName());
Class<?> cls = Thread.currentThread().getContextClassLoader().loadClass(info.getName());
Module module = cls.getAnnotation(Module.class);
return module.packageName();
}
......
......@@ -28,7 +28,7 @@ public class CheckService {
}
}
for (ClassInfo info : list) {
Class<?> cls = Class.forName(info.getName());
Class<?> cls = Thread.currentThread().getContextClassLoader().loadClass(info.getName());
if (FieldUtils.getFieldsListWithAnnotation(cls, FieldDescribe.class).isEmpty()) {
System.err.println(String.format("%s not set FieldDescribe", info.getName()));
}
......@@ -36,7 +36,7 @@ public class CheckService {
try (ScanResult scanResult = new ClassGraph().disableJarScanning().enableAllInfo().scan()) {
ClassInfoList classInfoList = scanResult.getClassesWithAnnotation(WebFilter.class.getName());
for (ClassInfo info : classInfoList) {
Class cls = Class.forName(info.getName());
Class cls = Thread.currentThread().getContextClassLoader().loadClass(info.getName());
WebFilter webFilter = (WebFilter) cls.getAnnotation(WebFilter.class);
if (webFilter.asyncSupported() == false) {
System.err.println("webFilter not set asyncSupported:" + info.getName());
......
......@@ -35,7 +35,7 @@ public class CreateWebXml {
}
private static String metadataCompleteFalse(String project, String thisApplicationClassName) throws Exception {
Class<?> thisApplication = Class.forName(thisApplicationClassName);
Class<?> thisApplication = Thread.currentThread().getContextClassLoader().loadClass(thisApplicationClassName);
try (ScanResult scanResult = new ClassGraph().enableAnnotationInfo()
.whitelistPackages(thisApplication.getPackage().getName(), Compilable.class.getPackage().getName())
.scan()) {
......@@ -71,7 +71,7 @@ public class CreateWebXml {
List<ClassInfo> classInfos = scanResult.getClassesWithAnnotation(Module.class.getName());
for (ClassInfo info : classInfos) {
if (StringUtils.equals(info.getSimpleName(), project)) {
Class<?> cls = Class.forName(info.getName());
Class<?> cls = Thread.currentThread().getContextClassLoader().loadClass(info.getName());
Module module = cls.getAnnotation(Module.class);
return module.packageName() + ".ThisApplication";
}
......
......@@ -243,7 +243,7 @@ public class Config {
// return new File(base(), DIR_COMMONS_EXT);
// }
public static Path dir_commons_ext() throws Exception {
public static Path dir_commons_ext() throws IOException, URISyntaxException {
if (SystemUtils.IS_JAVA_11) {
return Paths.get(base()).resolve(DIR_COMMONS_EXT + "_java11");
} else {
......@@ -277,12 +277,10 @@ public class Config {
return new File(base(), DIR_CUSTOM_JARS);
}
public static File dir_custom_jars(Boolean force) throws Exception {
public static File dir_custom_jars(Boolean force) throws IOException, URISyntaxException {
File dir = new File(base(), DIR_CUSTOM_JARS);
if (force) {
if ((!dir.exists()) || dir.isFile()) {
FileUtils.forceMkdir(dir);
}
if (BooleanUtils.isTrue(force) && ((!dir.exists()) || dir.isFile())) {
FileUtils.forceMkdir(dir);
}
return dir;
}
......@@ -295,12 +293,10 @@ public class Config {
return dir_dynamic_jars(false);
}
public static File dir_dynamic_jars(Boolean force) throws Exception {
public static File dir_dynamic_jars(Boolean force) throws IOException, URISyntaxException {
File dir = new File(base(), DIR_DYNAMIC_JARS);
if (force) {
if ((!dir.exists()) || dir.isFile()) {
FileUtils.forceMkdir(dir);
}
if (BooleanUtils.isTrue(force) && ((!dir.exists()) || dir.isFile())) {
FileUtils.forceMkdir(dir);
}
return dir;
}
......@@ -354,7 +350,7 @@ public class Config {
return new File(base(), DIR_LOCAL_TEMP);
}
public static File dir_local_temp_classes() throws Exception {
public static File dir_local_temp_classes() throws IOException, URISyntaxException {
return new File(base(), DIR_LOCAL_TEMP_CLASSES);
}
......@@ -484,12 +480,10 @@ public class Config {
return new File(base(), DIR_STORE_JARS);
}
public static File dir_store_jars(Boolean force) throws Exception {
public static File dir_store_jars(Boolean force) throws IOException, URISyntaxException {
File dir = new File(base(), DIR_STORE_JARS);
if (force) {
if ((!dir.exists()) || dir.isFile()) {
FileUtils.forceMkdir(dir);
}
if (BooleanUtils.isTrue(force) && ((!dir.exists()) || dir.isFile())) {
FileUtils.forceMkdir(dir);
}
return dir;
}
......@@ -555,7 +549,7 @@ public class Config {
private String base;
public static synchronized String base() throws Exception {
public static synchronized String base() throws IOException, URISyntaxException {
if (null == instance().base) {
instance().base = BaseTools.getBasePath();
}
......
......@@ -15,12 +15,13 @@ class ActionExecute extends BaseAction {
private static Logger logger = LoggerFactory.getLogger(ActionExecute.class);
@SuppressWarnings("unchecked")
ActionResult<Wo> execute(EffectivePerson effectivePerson, @Context ServletContext servletContext, String className)
throws Exception {
logger.debug(effectivePerson, "execute:{}.", className);
logger.debug("execute:{}.", () -> className);
ActionResult<Wo> result = new ActionResult<>();
AbstractContext ctx = AbstractContext.fromServletContext(servletContext);
Class<?> clz = Class.forName(className);
Class<?> clz = Thread.currentThread().getContextClassLoader().loadClass(className);
ctx.fireScheduleOnLocal((Class<AbstractJob>) clz, 1);
Wo wo = new Wo();
wo.setValue(true);
......
//package com.x.base.core.project.jaxrs.proxy;
//
//import com.x.base.core.project.Context;
//import com.x.base.core.project.annotation.AuditLog;
//import com.x.base.core.project.annotation.JaxrsMethodDescribe;
//import com.x.base.core.project.config.Config;
//import com.x.base.core.project.http.EffectivePerson;
//import com.x.base.core.project.logger.Audit;
//import com.x.base.core.project.logger.Logger;
//import com.x.base.core.project.logger.LoggerFactory;
//import net.sf.cglib.proxy.Enhancer;
//import net.sf.cglib.proxy.MethodInterceptor;
//import net.sf.cglib.proxy.MethodProxy;
//import org.apache.commons.lang3.ArrayUtils;
//import org.apache.commons.lang3.StringUtils;
//
//import java.lang.annotation.Annotation;
//import java.lang.reflect.Method;
//
//public class StandardJaxrsActionProxy implements MethodInterceptor {
// private Enhancer enhancer = new Enhancer();
// private Context context;
//
// public StandardJaxrsActionProxy(Context context) {
// this.context = context;
// }
//
// public Object getProxy(Class clazz){
// enhancer.setSuperclass(clazz);
// enhancer.setCallback(this);
// return enhancer.create();
// }
//
// @Override
// public Object intercept( Object o, Method method, Object[] objects, MethodProxy methodProxy ) throws Throwable {
// Object result = methodProxy.invokeSuper(o, objects);
// try{
// //尝试记录审计日志
// if( Config.logLevel().audit().enable() ){
// tryToRecordAuditLog( o, method, objects, methodProxy );
// }
// }catch(Exception e){
// e.printStackTrace();
// }
// return result;
// }
//
// /**
// * 根据调用方法的注释判断该类的操作是否需要记录到审计日志
// * 如果需要记录,则执行审计日志记录方法
// * @param o
// * @param method
// * @param objects
// * @param methodProxy
// * @throws ClassNotFoundException
// */
// private void tryToRecordAuditLog(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws ClassNotFoundException {
// //分析调用过程,记录审计日志
// Annotation[] annotations_auditLog = method.getAnnotationsByType(AuditLog.class);
// //该方法是否有AuditLog注解,如果有,则需要记录审计日志
// if( ArrayUtils.isNotEmpty( annotations_auditLog )){
// //获取操作名称,首选AuditLog的value属性属性,如果没有,则选择JaxrsMethodDescribe的value属性
// String operationName = getOperationName( method, annotations_auditLog );
// //有AuditLog注解,说明需要记录审计日志
// doRecordAuditLog( method, objects, operationName );
// }
// }
//
// /**
// * 获取方法的操作名称,首选AuditLog的value属性属性,如果没有,则选择JaxrsMethodDescribe的value属性
// * @param method
// * @param annotations_auditLog
// * @return
// */
// private String getOperationName( Method method, Annotation[] annotations_auditLog ) {
// String operationName = ((AuditLog)annotations_auditLog[0]).operation();
// Annotation[] annotations_jaxrsMethodDescribe = null;
// if( StringUtils.isEmpty(operationName)){
// //取JaxrsMethodDescribe
// annotations_jaxrsMethodDescribe = method.getAnnotationsByType(JaxrsMethodDescribe.class);
// if( ArrayUtils.isNotEmpty( annotations_jaxrsMethodDescribe )){
// operationName = ((JaxrsMethodDescribe)annotations_auditLog[0]).value();
// }
// }
// return operationName;
// }
//
// /**
// * 记录审计日志执行方法
// * @param method
// * @param objects
// * @param operationName
// */
// private void doRecordAuditLog( Method method, Object[] objects, String operationName ) throws ClassNotFoundException {
// if( StringUtils.isEmpty(operationName)){
// operationName = method.getName();
// }
// int parameterCount = method.getParameterCount();
// Class<?>[] parameterClasses = method.getParameterTypes();
// EffectivePerson effectivePerson = null;
// if( parameterCount > 0 && ArrayUtils.isNotEmpty( parameterClasses ) && ArrayUtils.isNotEmpty( objects ) ){
// //解析出参数effectivePerson
// int effectivePersonParamIndex = 99;
// for( int i = 0 ; i< parameterClasses.length; i++ ){
// if(StringUtils.equals( "com.x.base.core.project.http.EffectivePerson", parameterClasses[i].getName() )){
// effectivePersonParamIndex = i;
// break;
// }
// }
// if( effectivePersonParamIndex < 99 ){
// effectivePerson = (EffectivePerson) objects[effectivePersonParamIndex];
// Logger logger = LoggerFactory.getLogger(Class.forName( method.getDeclaringClass().getName() ));
// Audit audit = logger.audit(effectivePerson);
// audit.log(null, operationName);
// }
// }
// }
//}
......@@ -274,6 +274,10 @@ public class Logger {
System.out.println(format(message, os));
}
public void print(String message, Supplier<?>... suppliers) {
System.out.println(format(message, getAll(suppliers)));
}
private String requestToString(EffectivePerson effectivePerson, HttpServletRequest request, String headString,
String bodyString) {
return format(HTTPMESSAGEFORMAT, effectivePerson.getDistinguishedName(), request.getMethod(), this.url(request),
......
......@@ -27,12 +27,12 @@ public class ClassLoaderTools {
private static final String JAR = ".jar";
private static final String ZIP = ".zip";
public static URLClassLoader urlClassLoader(boolean systemParent, boolean ext, boolean store, boolean custom,
public static URLClassLoader urlClassLoader(ClassLoader parent, boolean ext, boolean store, boolean custom,
boolean dynamic, Path... paths) throws Exception {
return urlClassLoader(systemParent, ext, store, custom, dynamic, ListTools.toList(paths));
return urlClassLoader(parent, ext, store, custom, dynamic, ListTools.toList(paths));
}
public static URLClassLoader urlClassLoader(boolean systemParent, boolean ext, boolean store, boolean custom,
public static URLClassLoader urlClassLoader(ClassLoader parent, boolean ext, boolean store, boolean custom,
boolean dynamic, List<Path> paths) throws Exception {
Set<Path> set = new HashSet<>();
if (ext) {
......@@ -48,8 +48,8 @@ public class ClassLoaderTools {
set.addAll(dir(Config.dir_dynamic_jars().toPath()));
}
set.addAll(paths);
if (systemParent) {
return URLClassLoader.newInstance(toURL(set), ClassLoader.getSystemClassLoader());
if (null != parent) {
return URLClassLoader.newInstance(toURL(set), parent);
} else {
return URLClassLoader.newInstance(toURL(set));
}
......
package com.x.base.core.project.tools;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class ClassTools {
public static List<Class<?>> forName(List<String> names) throws Exception {
List<Class<?>> list = new ArrayList<>();
for (String str : names) {
Class<?> clz = Class.forName(str);
list.add(clz);
}
return list;
}
public static List<Class<?>> forName(final boolean asc, List<String> names) throws Exception {
List<Class<?>> list = forName(names);
Collections.sort(list, new Comparator<Class<?>>() {
public int compare(Class<?> c1, Class<?> c2) {
if (asc) {
return c1.getName().compareTo(c2.getName());
} else {
return c2.getName().compareTo(c1.getName());
}
}
});
return list;
}
public static boolean isClass(String className) {
try {
Class.forName(className);
return true;
} catch (ClassNotFoundException e) {
return false;
}
}
}
package com.x.base.core.project.tools;
import java.io.File;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;
public class URLClassLoaderTools {
private URLClassLoaderTools() {
}
public static void add(URLClassLoader classLoader, File file) throws Exception {
Class<?> urlClass = URLClassLoader.class;
Method method = urlClass.getDeclaredMethod("addURL", new Class[] { URL.class });
method.setAccessible(true);
method.invoke(classLoader, new Object[] { file.toURI().toURL() });
}
}
\ No newline at end of file
......@@ -5,6 +5,35 @@ import com.x.base.core.project.annotation.Module;
import com.x.base.core.project.annotation.ModuleCategory;
import com.x.base.core.project.annotation.ModuleType;
//@Module(type = ModuleType.ASSEMBLE, category = ModuleCategory.OFFICIAL, name = "流程设计", packageName = "com.x.processplatform.assemble.designer", containerEntities = {
// "com.x.processplatform.core.entity.content.Snap", "com.x.processplatform.core.entity.content.DocumentVersion",
// "com.x.processplatform.core.entity.content.Draft", "com.x.processplatform.core.entity.content.Attachment",
// "com.x.processplatform.core.entity.content.Read", "com.x.processplatform.core.entity.content.ReadCompleted",
// "com.x.processplatform.core.entity.content.Review", "com.x.processplatform.core.entity.content.Record",
// "com.x.processplatform.core.entity.content.SerialNumber", "com.x.processplatform.core.entity.content.Task",
// "com.x.processplatform.core.entity.content.TaskCompleted", "com.x.processplatform.core.entity.content.Work",
// "com.x.processplatform.core.entity.content.WorkCompleted", "com.x.processplatform.core.entity.content.WorkLog",
// "com.x.processplatform.core.entity.content.Record", "com.x.processplatform.core.entity.element.Invoke",
// "com.x.processplatform.core.entity.element.Split", "com.x.processplatform.core.entity.element.File",
// "com.x.processplatform.core.entity.element.Form", "com.x.processplatform.core.entity.element.FormVersion",
// "com.x.processplatform.core.entity.element.FormField", "com.x.processplatform.core.entity.element.TemplateForm",
// "com.x.processplatform.core.entity.element.Application", "com.x.processplatform.core.entity.element.Script",
// "com.x.processplatform.core.entity.element.ScriptVersion", "com.x.processplatform.core.entity.element.Merge",
// "com.x.processplatform.core.entity.element.Agent", "com.x.processplatform.core.entity.element.Process",
// "com.x.processplatform.core.entity.element.ProcessVersion", "com.x.processplatform.core.entity.element.Choice",
// "com.x.processplatform.core.entity.element.Delay", "com.x.processplatform.core.entity.element.Parallel",
// "com.x.processplatform.core.entity.element.Begin", "com.x.processplatform.core.entity.element.Cancel",
// "com.x.processplatform.core.entity.element.Embed", "com.x.processplatform.core.entity.element.Service",
// "com.x.processplatform.core.entity.element.Manual", "com.x.processplatform.core.entity.element.Route",
// "com.x.processplatform.core.entity.element.End", "com.x.processplatform.core.entity.element.ApplicationDict",
// "com.x.processplatform.core.entity.element.ApplicationDictItem",
// "com.x.processplatform.core.entity.element.QueryView", "com.x.processplatform.core.entity.element.QueryStat",
// "com.x.processplatform.core.entity.element.Mapping", "com.x.query.core.entity.Item",
// "com.x.cms.core.entity.element.Script", "com.x.portal.core.entity.Script",
// "com.x.query.dynamic.entity.*" }, storeJars = { "x_organization_core_entity", "x_organization_core_express",
// "x_processplatform_core_entity", "x_processplatform_core_express", "x_query_core_entity",
// "x_cms_core_entity", "x_portal_core_entity" }, dynamicJars = {
// "x_query_dynamic_entity", }, storageTypes = { StorageType.processPlatform })
@Module(type = ModuleType.ASSEMBLE, category = ModuleCategory.OFFICIAL, name = "流程设计", packageName = "com.x.processplatform.assemble.designer", containerEntities = {
"com.x.processplatform.core.entity.content.Snap", "com.x.processplatform.core.entity.content.DocumentVersion",
"com.x.processplatform.core.entity.content.Draft", "com.x.processplatform.core.entity.content.Attachment",
......@@ -29,11 +58,10 @@ import com.x.base.core.project.annotation.ModuleType;
"com.x.processplatform.core.entity.element.ApplicationDictItem",
"com.x.processplatform.core.entity.element.QueryView", "com.x.processplatform.core.entity.element.QueryStat",
"com.x.processplatform.core.entity.element.Mapping", "com.x.query.core.entity.Item",
"com.x.cms.core.entity.element.Script", "com.x.portal.core.entity.Script",
"com.x.query.dynamic.entity.*" }, storeJars = { "x_organization_core_entity", "x_organization_core_express",
"x_processplatform_core_entity", "x_processplatform_core_express", "x_query_core_entity",
"x_cms_core_entity", "x_portal_core_entity" }, dynamicJars = {
"x_query_dynamic_entity", }, storageTypes = { StorageType.processPlatform })
"com.x.cms.core.entity.element.Script", "com.x.portal.core.entity.Script" }, storeJars = {
"x_organization_core_entity", "x_organization_core_express", "x_processplatform_core_entity",
"x_processplatform_core_express", "x_query_core_entity", "x_cms_core_entity",
"x_portal_core_entity" }, storageTypes = { StorageType.processPlatform })
public class x_processplatform_assemble_designer extends Deployable {
}
......@@ -5,6 +5,35 @@ import com.x.base.core.project.annotation.Module;
import com.x.base.core.project.annotation.ModuleCategory;
import com.x.base.core.project.annotation.ModuleType;
//@Module(type = ModuleType.SERVICE, category = ModuleCategory.OFFICIAL, name = "流程服务", packageName = "com.x.processplatform.service.processing", containerEntities = {
// "com.x.processplatform.core.entity.content.Snap", "com.x.processplatform.core.entity.content.Draft",
// "com.x.processplatform.core.entity.content.Attachment",
// "com.x.processplatform.core.entity.content.TaskCompleted",
// "com.x.processplatform.core.entity.content.ReadCompleted", "com.x.processplatform.core.entity.content.Review",
// "com.x.processplatform.core.entity.content.Record", "com.x.processplatform.core.entity.content.WorkCompleted",
// "com.x.processplatform.core.entity.content.WorkLog", "com.x.processplatform.core.entity.content.Record",
// "com.x.processplatform.core.entity.content.Task", "com.x.processplatform.core.entity.content.Work",
// "com.x.processplatform.core.entity.content.Read", "com.x.processplatform.core.entity.content.DocumentVersion",
// "com.x.processplatform.core.entity.content.SerialNumber", "com.x.processplatform.core.entity.element.End",
// "com.x.processplatform.core.entity.content.DocSign", "com.x.processplatform.core.entity.content.DocSignScrawl",
// "com.x.processplatform.core.entity.element.Application",
// "com.x.processplatform.core.entity.element.ApplicationDict",
// "com.x.processplatform.core.entity.element.ApplicationDictItem",
// "com.x.processplatform.core.entity.element.Script", "com.x.processplatform.core.entity.element.Cancel",
// "com.x.processplatform.core.entity.element.Merge", "com.x.processplatform.core.entity.element.Route",
// "com.x.processplatform.core.entity.element.Choice", "com.x.processplatform.core.entity.element.Invoke",
// "com.x.processplatform.core.entity.element.Manual", "com.x.processplatform.core.entity.element.Parallel",
// "com.x.processplatform.core.entity.element.Begin", "com.x.processplatform.core.entity.element.Split",
// "com.x.processplatform.core.entity.element.Process", "com.x.processplatform.core.entity.element.Service",
// "com.x.processplatform.core.entity.element.Agent", "com.x.processplatform.core.entity.element.Delay",
// "com.x.processplatform.core.entity.element.File", "com.x.processplatform.core.entity.element.Form",
// "com.x.processplatform.core.entity.element.FormField", "com.x.processplatform.core.entity.element.Embed",
// "com.x.processplatform.core.entity.element.Mapping", "com.x.processplatform.core.entity.log.SignalStackLog",
// "com.x.query.core.entity.Item", "com.x.cms.core.entity.element.Script", "com.x.portal.core.entity.Script",
// "com.x.query.dynamic.entity.*" }, storageTypes = { StorageType.processPlatform }, storeJars = {
// "x_organization_core_entity", "x_organization_core_express", "x_processplatform_core_entity",
// "x_processplatform_core_express", "x_query_core_entity", "x_cms_core_entity",
// "x_portal_core_entity" }, dynamicJars = { "x_query_dynamic_entity" })
@Module(type = ModuleType.SERVICE, category = ModuleCategory.OFFICIAL, name = "流程服务", packageName = "com.x.processplatform.service.processing", containerEntities = {
"com.x.processplatform.core.entity.content.Snap", "com.x.processplatform.core.entity.content.Draft",
"com.x.processplatform.core.entity.content.Attachment",
......@@ -29,11 +58,10 @@ import com.x.base.core.project.annotation.ModuleType;
"com.x.processplatform.core.entity.element.File", "com.x.processplatform.core.entity.element.Form",
"com.x.processplatform.core.entity.element.FormField", "com.x.processplatform.core.entity.element.Embed",
"com.x.processplatform.core.entity.element.Mapping", "com.x.processplatform.core.entity.log.SignalStackLog",
"com.x.query.core.entity.Item", "com.x.cms.core.entity.element.Script", "com.x.portal.core.entity.Script",
"com.x.query.dynamic.entity.*" }, storageTypes = { StorageType.processPlatform }, storeJars = {
"com.x.query.core.entity.Item", "com.x.cms.core.entity.element.Script",
"com.x.portal.core.entity.Script" }, storageTypes = { StorageType.processPlatform }, storeJars = {
"x_organization_core_entity", "x_organization_core_express", "x_processplatform_core_entity",
"x_processplatform_core_express", "x_query_core_entity", "x_cms_core_entity",
"x_portal_core_entity" }, dynamicJars = { "x_query_dynamic_entity" })
"x_processplatform_core_express", "x_query_core_entity", "x_cms_core_entity", "x_portal_core_entity" })
public class x_processplatform_service_processing extends Deployable {
}
......@@ -18,12 +18,12 @@ import com.x.base.core.project.annotation.ModuleType;
"com.x.organization.core.entity.Person", "com.x.organization.core.entity.Identity",
"com.x.organization.core.entity.PersonAttribute", "com.x.organization.core.entity.Unit",
"com.x.organization.core.entity.UnitAttribute", "com.x.organization.core.entity.UnitDuty",
"com.x.general.core.entity.area.District", "com.x.program.center.core.entity.AppPackApkFile" }, storageTypes = { StorageType.structure }, storeJars = {
"x_organization_core_express", "x_program_center_core_entity", "x_attendance_core_entity",
"x_cms_core_entity", "x_message_core_entity", "x_component_core_entity", "x_file_core_entity",
"x_meeting_core_entity", "x_okr_core_entity", "x_organization_core_entity",
"x_processplatform_core_entity", "x_query_core_entity", "x_portal_core_entity",
"x_general_core_entity" }, dynamicJars = { "x_query_dynamic_entity" })
"com.x.general.core.entity.area.District", "com.x.program.center.core.entity.AppPackApkFile" }, storageTypes = {
StorageType.structure }, storeJars = { "x_organization_core_express", "x_program_center_core_entity",
"x_attendance_core_entity", "x_cms_core_entity", "x_message_core_entity",
"x_component_core_entity", "x_file_core_entity", "x_meeting_core_entity", "x_okr_core_entity",
"x_organization_core_entity", "x_processplatform_core_entity", "x_query_core_entity",
"x_portal_core_entity", "x_general_core_entity" })
public class x_program_center extends Deployable {
}
......@@ -5,6 +5,25 @@ import com.x.base.core.project.annotation.Module;
import com.x.base.core.project.annotation.ModuleCategory;
import com.x.base.core.project.annotation.ModuleType;
//@Module(type = ModuleType.ASSEMBLE, category = ModuleCategory.OFFICIAL, name = "数据查询设计", packageName = "com.x.query.assemble.designer", containerEntities = {
// "com.x.query.core.entity.program.Argument", "com.x.query.core.entity.Item", "com.x.query.core.entity.Query",
// "com.x.query.core.entity.View", "com.x.query.core.entity.Stat", "com.x.query.core.entity.Reveal",
// "com.x.query.core.entity.neural.Entry", "com.x.query.core.entity.neural.InText",
// "com.x.query.core.entity.neural.OutText", "com.x.query.core.entity.neural.InValue",
// "com.x.query.core.entity.neural.OutValue", "com.x.query.core.entity.neural.Model",
// "com.x.query.core.entity.schema.Table", "com.x.query.core.entity.schema.Statement",
// "com.x.query.core.entity.ImportModel",
// "com.x.processplatform.core.entity.content.Review", "com.x.processplatform.core.entity.content.Work",
// "com.x.processplatform.core.entity.content.WorkCompleted", "com.x.processplatform.core.entity.content.Task",
// "com.x.processplatform.core.entity.content.TaskCompleted", "com.x.processplatform.core.entity.content.Read",
// "com.x.processplatform.core.entity.content.ReadCompleted","com.x.processplatform.core.entity.element.Process",
// "com.x.processplatform.core.entity.content.Attachment", "com.x.cms.core.entity.Document",
// "com.x.cms.core.entity.AppInfo", "com.x.cms.core.entity.CategoryInfo", "com.x.cms.core.entity.Review",
// "com.x.organization.core.entity.Person", "com.x.organization.core.entity.Unit", "com.x.organization.core.entity.Group",
// "com.x.query.dynamic.entity.*" }, storageTypes = { StorageType.processPlatform }, storeJars = {
// "x_query_core_entity", "x_organization_core_entity", "x_organization_core_express",
// "x_processplatform_core_entity", "x_cms_core_entity",
// "x_query_core_express" }, dynamicJars = { "x_query_dynamic_entity" })
@Module(type = ModuleType.ASSEMBLE, category = ModuleCategory.OFFICIAL, name = "数据查询设计", packageName = "com.x.query.assemble.designer", containerEntities = {
"com.x.query.core.entity.program.Argument", "com.x.query.core.entity.Item", "com.x.query.core.entity.Query",
"com.x.query.core.entity.View", "com.x.query.core.entity.Stat", "com.x.query.core.entity.Reveal",
......@@ -12,17 +31,15 @@ import com.x.base.core.project.annotation.ModuleType;
"com.x.query.core.entity.neural.OutText", "com.x.query.core.entity.neural.InValue",
"com.x.query.core.entity.neural.OutValue", "com.x.query.core.entity.neural.Model",
"com.x.query.core.entity.schema.Table", "com.x.query.core.entity.schema.Statement",
"com.x.query.core.entity.ImportModel",
"com.x.processplatform.core.entity.content.Review", "com.x.processplatform.core.entity.content.Work",
"com.x.processplatform.core.entity.content.WorkCompleted", "com.x.processplatform.core.entity.content.Task",
"com.x.processplatform.core.entity.content.TaskCompleted", "com.x.processplatform.core.entity.content.Read",
"com.x.processplatform.core.entity.content.ReadCompleted","com.x.processplatform.core.entity.element.Process",
"com.x.processplatform.core.entity.content.Attachment", "com.x.cms.core.entity.Document",
"com.x.cms.core.entity.AppInfo", "com.x.cms.core.entity.CategoryInfo", "com.x.cms.core.entity.Review",
"com.x.organization.core.entity.Person", "com.x.organization.core.entity.Unit", "com.x.organization.core.entity.Group",
"com.x.query.dynamic.entity.*" }, storageTypes = { StorageType.processPlatform }, storeJars = {
"com.x.query.core.entity.ImportModel", "com.x.processplatform.core.entity.content.Review",
"com.x.processplatform.core.entity.content.Work", "com.x.processplatform.core.entity.content.WorkCompleted",
"com.x.processplatform.core.entity.content.Task", "com.x.processplatform.core.entity.content.TaskCompleted",
"com.x.processplatform.core.entity.content.Read", "com.x.processplatform.core.entity.content.ReadCompleted",
"com.x.processplatform.core.entity.element.Process", "com.x.processplatform.core.entity.content.Attachment",
"com.x.cms.core.entity.Document", "com.x.cms.core.entity.AppInfo", "com.x.cms.core.entity.CategoryInfo",
"com.x.cms.core.entity.Review", "com.x.organization.core.entity.Person", "com.x.organization.core.entity.Unit",
"com.x.organization.core.entity.Group" }, storageTypes = { StorageType.processPlatform }, storeJars = {
"x_query_core_entity", "x_organization_core_entity", "x_organization_core_express",
"x_processplatform_core_entity", "x_cms_core_entity",
"x_query_core_express" }, dynamicJars = { "x_query_dynamic_entity" })
"x_processplatform_core_entity", "x_cms_core_entity", "x_query_core_express" })
public class x_query_assemble_designer extends Deployable {
}
......@@ -5,6 +5,32 @@ import com.x.base.core.project.annotation.Module;
import com.x.base.core.project.annotation.ModuleCategory;
import com.x.base.core.project.annotation.ModuleType;
//@Module(type = ModuleType.ASSEMBLE, category = ModuleCategory.OFFICIAL, name = "数据查询", packageName = "com.x.query.assemble.surface", containerEntities = {
// "com.x.query.core.entity.program.Argument", "com.x.query.core.entity.Item", "com.x.query.core.entity.Query",
// "com.x.query.core.entity.View", "com.x.query.core.entity.Stat", "com.x.query.core.entity.Reveal",
// "com.x.query.core.entity.segment.Word", "com.x.query.core.entity.segment.Entry",
// "com.x.query.core.entity.neural.Entry", "com.x.query.core.entity.neural.InText",
// "com.x.query.core.entity.neural.OutText", "com.x.query.core.entity.neural.InValue",
// "com.x.query.core.entity.neural.OutValue", "com.x.query.core.entity.neural.Model",
// "com.x.query.core.entity.schema.Table", "com.x.query.core.entity.schema.Statement",
// "com.x.query.core.entity.ImportModel","com.x.query.core.entity.ImportRecord",
// "com.x.query.core.entity.ImportRecordItem",
// "com.x.processplatform.core.entity.content.Task", "com.x.processplatform.core.entity.content.TaskCompleted",
// "com.x.processplatform.core.entity.content.Read", "com.x.processplatform.core.entity.content.ReadCompleted",
// "com.x.processplatform.core.entity.content.Review", "com.x.processplatform.core.entity.content.Work",
// "com.x.processplatform.core.entity.content.WorkCompleted","com.x.processplatform.core.entity.element.Process",
// "com.x.processplatform.core.entity.content.Attachment", "com.x.cms.core.entity.Document",
// "com.x.cms.core.entity.Review", "com.x.cms.core.entity.AppInfo", "com.x.cms.core.entity.CategoryInfo",
// "com.x.cms.core.entity.Document", "com.x.cms.core.entity.DocumentViewRecord","com.x.cms.core.entity.DocumentCommentInfo",
// "com.x.cms.core.entity.element.File", "com.x.cms.core.entity.FileInfo",
// "com.x.cms.core.entity.DocumentCommentContent", "com.x.cms.core.entity.DocumentCommentCommend",
// "com.x.organization.core.entity.Person", "com.x.organization.core.entity.Unit", "com.x.organization.core.entity.Group",
// "com.x.organization.core.entity.Role", "com.x.organization.core.entity.Identity",
// "com.x.query.dynamic.entity.*", "com.x.general.core.entity.GeneralFile"},
// storageTypes = { StorageType.processPlatform, StorageType.cms, StorageType.general}, storeJars = {
// "x_query_core_entity", "x_organization_core_entity", "x_organization_core_express",
// "x_processplatform_core_entity", "x_cms_core_entity",
// "x_query_core_express", "x_general_core_entity" }, dynamicJars = { "x_query_dynamic_entity" })
@Module(type = ModuleType.ASSEMBLE, category = ModuleCategory.OFFICIAL, name = "数据查询", packageName = "com.x.query.assemble.surface", containerEntities = {
"com.x.query.core.entity.program.Argument", "com.x.query.core.entity.Item", "com.x.query.core.entity.Query",
"com.x.query.core.entity.View", "com.x.query.core.entity.Stat", "com.x.query.core.entity.Reveal",
......@@ -13,23 +39,23 @@ import com.x.base.core.project.annotation.ModuleType;
"com.x.query.core.entity.neural.OutText", "com.x.query.core.entity.neural.InValue",
"com.x.query.core.entity.neural.OutValue", "com.x.query.core.entity.neural.Model",
"com.x.query.core.entity.schema.Table", "com.x.query.core.entity.schema.Statement",
"com.x.query.core.entity.ImportModel","com.x.query.core.entity.ImportRecord",
"com.x.query.core.entity.ImportRecordItem",
"com.x.processplatform.core.entity.content.Task", "com.x.processplatform.core.entity.content.TaskCompleted",
"com.x.processplatform.core.entity.content.Read", "com.x.processplatform.core.entity.content.ReadCompleted",
"com.x.processplatform.core.entity.content.Review", "com.x.processplatform.core.entity.content.Work",
"com.x.processplatform.core.entity.content.WorkCompleted","com.x.processplatform.core.entity.element.Process",
"com.x.processplatform.core.entity.content.Attachment", "com.x.cms.core.entity.Document",
"com.x.cms.core.entity.Review", "com.x.cms.core.entity.AppInfo", "com.x.cms.core.entity.CategoryInfo",
"com.x.cms.core.entity.Document", "com.x.cms.core.entity.DocumentViewRecord","com.x.cms.core.entity.DocumentCommentInfo",
"com.x.query.core.entity.ImportModel", "com.x.query.core.entity.ImportRecord",
"com.x.query.core.entity.ImportRecordItem", "com.x.processplatform.core.entity.content.Task",
"com.x.processplatform.core.entity.content.TaskCompleted", "com.x.processplatform.core.entity.content.Read",
"com.x.processplatform.core.entity.content.ReadCompleted", "com.x.processplatform.core.entity.content.Review",
"com.x.processplatform.core.entity.content.Work", "com.x.processplatform.core.entity.content.WorkCompleted",
"com.x.processplatform.core.entity.element.Process", "com.x.processplatform.core.entity.content.Attachment",
"com.x.cms.core.entity.Document", "com.x.cms.core.entity.Review", "com.x.cms.core.entity.AppInfo",
"com.x.cms.core.entity.CategoryInfo", "com.x.cms.core.entity.Document",
"com.x.cms.core.entity.DocumentViewRecord", "com.x.cms.core.entity.DocumentCommentInfo",
"com.x.cms.core.entity.element.File", "com.x.cms.core.entity.FileInfo",
"com.x.cms.core.entity.DocumentCommentContent", "com.x.cms.core.entity.DocumentCommentCommend",
"com.x.organization.core.entity.Person", "com.x.organization.core.entity.Unit", "com.x.organization.core.entity.Group",
"com.x.organization.core.entity.Role", "com.x.organization.core.entity.Identity",
"com.x.query.dynamic.entity.*", "com.x.general.core.entity.GeneralFile"},
storageTypes = { StorageType.processPlatform, StorageType.cms, StorageType.general}, storeJars = {
"x_query_core_entity", "x_organization_core_entity", "x_organization_core_express",
"x_processplatform_core_entity", "x_cms_core_entity",
"x_query_core_express", "x_general_core_entity" }, dynamicJars = { "x_query_dynamic_entity" })
"com.x.organization.core.entity.Person", "com.x.organization.core.entity.Unit",
"com.x.organization.core.entity.Group", "com.x.organization.core.entity.Role",
"com.x.organization.core.entity.Identity", "com.x.general.core.entity.GeneralFile" }, storageTypes = {
StorageType.processPlatform, StorageType.cms, StorageType.general }, storeJars = {
"x_query_core_entity", "x_organization_core_entity", "x_organization_core_express",
"x_processplatform_core_entity", "x_cms_core_entity", "x_query_core_express",
"x_general_core_entity" })
public class x_query_assemble_surface extends Deployable {
}
{
"enable": true,
"center": {
"enable": true,
"order" : 4,
"sslEnable": false,
"redeploy": true,
"port": 20030.0,
"httpProtocol": "",
"proxyHost": "",
"proxyPort": 20030.0,
"scanInterval": 0.0,
"statEnable": true
},
"application": {
"enable": true,
"port": 20020.0,
"sslEnable": false,
"proxyHost": "",
"proxyPort": 20020.0,
"redeploy": true,
"scanInterval": 0.0,
"includes": [],
"excludes": ["*_attendance_*", "*_bbs_*", "*_calendar_*", "*_file_*", "*_okr_*", "*_hotpic_*", "*_meeting_*", "*_mind_*", "*_teamwork_*", "*_jpush_*"],
"weights": [],
"statEnable": true
},
"web": {
"enable": true,
"sslEnable": false,
"proxyHost": "",
"port": 8080,
"weight": 100.0,
"statEnable": false
},
"data": {
"enable": false,
"tcpPort": 20050.0,
"webPort": 20051.0,
"includes": [],
"excludes": [],
"jmxEnable": false,
"cacheSize": 512.0,
"logLevel": "WARN"
},
"storage": {
"enable": true,
"port": 20040.0,
"sslEnable": false,
"name": "s004",
"accounts": []
},
"dumpData": {
"enable": false,
"cron": "",
"size": 14.0,
"path": ""
},
"dumpStorage": {
"enable": false,
"cron": "",
"size": 14.0,
"path": ""
},
"restoreData": {
"cron": "",
"path": ""
},
"restoreStorage": {
"cron": "",
"path": ""
},
"nodeAgentEnable": false,
"nodeAgentPort": 20010.0,
"nodeAgentEncrypt": false,
"autoStart": true
}
......@@ -11,7 +11,6 @@ import java.util.Objects;
import java.util.jar.JarFile;
import java.util.stream.Stream;
public class InstrumentationAgent {
private InstrumentationAgent() {
......@@ -23,8 +22,9 @@ public class InstrumentationAgent {
private static final String CFG = "manifest.cfg";
private static final String GIT = ".gitignore";
private static final String CUSTOM_JARS = "custom/jars";
private static final String DYNAMIC_JARS = "dynamic/jars";
// private static final String DYNAMIC_JARS = "dynamic/jars";
private static final String STORE_JARS = "store/jars";
private static final String STORE_JARS_BASE_CORE_PROJECT = STORE_JARS + "/" + "x_base_core_project.jar";
private static final String COMMONS_EXT = "commons/ext";
public static String JAVAVERSION = "java8";
......@@ -56,11 +56,13 @@ public class InstrumentationAgent {
if (Files.exists(base.resolve(CUSTOM_JARS))) {
load(base, CUSTOM_JARS);
}
if (Files.exists(base.resolve(DYNAMIC_JARS))) {
load(base, DYNAMIC_JARS);
}
// if (Files.exists(base.resolve(DYNAMIC_JARS))) {
// load(base, DYNAMIC_JARS);
// }
setLog4j2(base, args);
loadWithCfg(base, STORE_JARS);
checkStoreJarWithCfg(base);
loadBaseCoreProject(base);
// loadWithCfg(base, STORE_JARS);
loadWithCfg(base, ext());
} catch (Exception e) {
e.printStackTrace();
......@@ -71,6 +73,40 @@ public class InstrumentationAgent {
return JAVAVERSION.equals(JAVAVERSION_JAVA8) ? COMMONS_EXT : COMMONS_EXT + "_" + JAVAVERSION;
}
private static void checkStoreJarWithCfg(Path base) throws IOException {
Path dir = base.resolve(STORE_JARS);
Path cfg = dir.resolve(CFG);
if (Files.exists(dir) && Files.isDirectory(dir) && Files.exists(cfg) && Files.isRegularFile(cfg)) {
List<String> names = Files.readAllLines(cfg);
if (names.isEmpty()) {
throw new IOException(String.format("%s manifest is empty.", STORE_JARS));
}
try (Stream<Path> stream = Files.list(dir)) {
stream.filter(o -> !(o.getFileName().toString().equalsIgnoreCase(CFG)
|| o.getFileName().toString().equalsIgnoreCase(GIT))).forEach(o -> {
try {
if (!names.remove(o.getFileName().toString())) {
Files.delete(o);
System.out.println(String.format("delete unnecessary file from %s: %s.", STORE_JARS,
o.getFileName().toString()));
}
} catch (IOException e) {
e.printStackTrace();
}
});
}
for (String name : names) {
System.out.println(String.format("can not find jar from %s: %s", STORE_JARS, name));
}
} else {
throw new IOException(String.format("invalid directory: %s", STORE_JARS));
}
}
private static void loadBaseCoreProject(Path base) throws IOException {
INST.appendToSystemClassLoaderSearch(new JarFile(base.resolve(STORE_JARS_BASE_CORE_PROJECT).toString()));
}
private static void loadWithCfg(Path base, String sub) throws IOException {
Path dir = base.resolve(sub);
Path cfg = dir.resolve(CFG);
......@@ -90,6 +126,7 @@ public class InstrumentationAgent {
System.out.println(String.format("delete unnecessary file from %s: %s.", sub,
o.getFileName().toString()));
}
} catch (IOException e) {
e.printStackTrace();
}
......
......@@ -696,21 +696,6 @@ public class Main {
}
throw new IOException("can not define o2server base directory.");
}
// private static String getBasePath() throws Exception {
// String path = Main.class.getProtectionDomain().getCodeSource().getLocation().getPath();
// File file = new File(path);
// if (!file.isDirectory()) {
// file = file.getParentFile();
// }
// while (null != file) {
// File versionFile = new File(file, "version.o2");
// if (versionFile.exists()) {
// return file.getAbsolutePath();
// }
// file = file.getParentFile();
// }
// throw new Exception("can not define o2server base directory.");
// }
private static void cleanTempDir(String base) throws Exception {
File temp = new File(base, "local/temp");
......
......@@ -547,79 +547,6 @@ public class NodeAgent extends Thread {
FileUtils.cleanDirectory(tempFile);
}
// private List<ClassInfo> listModuleDependencyWith(String name) throws Exception {
// List<ClassInfo> list = new ArrayList<>();
// try (ScanResult scanResult = new ClassGraph()
// .addClassLoader(ClassLoaderTools.urlClassLoader(true, false, false, false, false))
// .enableAnnotationInfo().scan()) {
// List<ClassInfo> classInfos = scanResult.getClassesWithAnnotation(Module.class.getName());
// for (ClassInfo info : classInfos) {
// Class<?> cls = Class.forName(info.getName());
// Module module = cls.getAnnotation(Module.class);
// if (Objects.equals(module.type(), ModuleType.ASSEMBLE)
// || Objects.equals(module.type(), ModuleType.SERVICE)
// || Objects.equals(module.type(), ModuleType.CENTER)) {
// if (ArrayUtils.contains(module.storeJars(), name) || ArrayUtils.contains(module.customJars(), name)
// || ArrayUtils.contains(module.dynamicJars(), name)) {
// list.add(info);
// }
// }
// }
// }
// return list;
// }
// private ClassInfo scanModuleClassInfo(String name) throws Exception {
// try (ScanResult scanResult = new ClassGraph()
// .addClassLoader(ClassLoaderTools.urlClassLoader(true, false, false, false, false))
// .enableAnnotationInfo().scan()) {
// List<ClassInfo> classInfos = scanResult.getClassesWithAnnotation(Module.class.getName());
// for (ClassInfo info : classInfos) {
// Class<?> clz = Class.forName(info.getName());
// if (StringUtils.equals(clz.getSimpleName(), name)) {
// return info;
// }
// }
// return null;
// }
// }
// private void modified(byte[] bytes, File war, File dir) throws Exception {
// File lastModified = new File(dir, "WEB-INF/lastModified");
// if ((!lastModified.exists()) || lastModified.isDirectory() || (war.lastModified() != NumberUtils
// .toLong(FileUtils.readFileToString(lastModified, DefaultCharset.charset_utf_8), 0))) {
// if (dir.exists()) {
// FileUtils.forceDelete(dir);
// }
// JarTools.unjar(bytes, "", dir, true);
// FileUtils.writeStringToFile(lastModified, war.lastModified() + "", DefaultCharset.charset_utf_8, false);
// }
// }
// private static void modified(File war, File dir) throws IOException {
// File lastModified = new File(dir, "WEB-INF/lastModified");
// if ((!lastModified.exists()) || lastModified.isDirectory() || (war.lastModified() != NumberUtils
// .toLong(FileUtils.readFileToString(lastModified, DefaultCharset.charset_utf_8), 0))) {
// if (dir.exists()) {
// FileUtils.forceDelete(dir);
// }
// JarTools.unjar(war, "", dir, true);
// FileUtils.writeStringToFile(lastModified, war.lastModified() + "", DefaultCharset.charset_utf_8, false);
// }
// }
// private static String contextParamProject(File dir) throws Exception {
// DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
// DocumentBuilder builder = factory.newDocumentBuilder();
// Document doc = builder
// .parse(new ByteArrayInputStream(FileUtils.readFileToByteArray(new File(dir, "WEB-INF/web.xml"))));
// XPathFactory xPathfactory = XPathFactory.newInstance();
// XPath xpath = xPathfactory.newXPath();
// XPathExpression expr = xpath.compile("web-app/context-param[param-name='project']/param-value");
// String str = expr.evaluate(doc, XPathConstants.STRING).toString();
// return StringUtils.trim(str);
// }
protected static String calculateExtraClassPath(Class<?> cls, Path... paths) throws Exception {
List<String> jars = new ArrayList<>();
jars.addAll(calculateExtraClassPathDefault());
......@@ -636,12 +563,6 @@ public class NodeAgent extends Thread {
jars.add(file.getAbsolutePath());
}
}
for (String str : module.dynamicJars()) {
File file = new File(Config.dir_dynamic_jars(), str + ".jar");
if (file.exists()) {
jars.add(file.getAbsolutePath());
}
}
for (Path path : paths) {
if (Files.exists(path) && Files.isDirectory(path)) {
try (Stream<Path> stream = Files.walk(path, FileVisitOption.FOLLOW_LINKS)) {
......
......@@ -58,7 +58,7 @@ import io.github.classgraph.ScanResult;
*/
public class ResourceFactory {
private static final Logger logger = LoggerFactory.getLogger(ResourceFactory.class);
private static final Logger LOGGER = LoggerFactory.getLogger(ResourceFactory.class);
private static final int TOKENTHRESHOLDSMAXSIZE = 2000;
......@@ -72,14 +72,14 @@ public class ResourceFactory {
}
public static void init() throws Exception {
ClassLoader cl = ClassLoaderTools.urlClassLoader(true, false, true, true, true, unzipCustomWar());
ClassLoader cl = ClassLoaderTools.urlClassLoader(ClassLoader.getSystemClassLoader(), false, true, true, false,
unzipCustomWar());
try (ScanResult sr = new ClassGraph().addClassLoader(cl).enableAnnotationInfo().scan()) {
node();
containerEntities(cl, sr);
containerEntityNames(sr);
stroageContainerEntityNames(sr);
disableDruidMysqlUsePingMethod();
}
if (BooleanUtils.isTrue(Config.externalDataSources().enable())) {
external();
......
......@@ -239,10 +239,7 @@ public class ActionControl extends ActionBase {
logger.print("unkown parameter:{}.", type);
} else {
EraseContentEntity eraseContentEntity = new EraseContentEntity();
for (String str : names) {
eraseContentEntity.addClass(str);
}
eraseContentEntity.execute();
eraseContentEntity.execute(names);
}
break;
}
......
......@@ -37,8 +37,6 @@ public class CompactLocalH2 {
logger.print("data server is running, must stop data server first.");
return false;
}
/* 需要注入驱动程序 */
// Class.forName(SlicePropertiesBuilder.driver_h2).newInstance();
DriverManager.registerDriver(new org.h2.Driver());
logger.print("compact data start at {}.", DateTools.format(start));
String dir = StringUtils.replace(Config.base(), "\\", "/") + "/local/repository/data";
......
......@@ -27,8 +27,8 @@ public class Ddl {
new Thread(() -> {
try {
ClassLoader cl = ClassLoaderTools.urlClassLoader(true, true, true, true, true,
Config.dir_local_temp_classes().toPath());
ClassLoader cl = ClassLoaderTools.urlClassLoader(ClassLoader.getSystemClassLoader(), true, true, true,
true, Config.dir_local_temp_classes().toPath());
Thread.currentThread().setContextClassLoader(cl);
String flag = "build";
if (StringUtils.equalsIgnoreCase(type, "createDB")) {
......
package com.x.server.console.action;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
......@@ -8,7 +10,6 @@ import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Stream;
......@@ -31,26 +32,23 @@ import com.x.base.core.container.factory.PersistenceXmlHelper;
import com.x.base.core.entity.JpaObject;
import com.x.base.core.entity.StorageObject;
import com.x.base.core.entity.annotation.ContainerEntity;
import com.x.base.core.entity.annotation.ContainerEntity.Reference;
import com.x.base.core.entity.dataitem.DataItem;
import com.x.base.core.entity.dataitem.ItemCategory;
import com.x.base.core.entity.tools.JpaObjectTools;
import com.x.base.core.project.config.Config;
import com.x.base.core.project.config.DumpRestoreData;
import com.x.base.core.project.config.StorageMapping;
import com.x.base.core.project.config.StorageMappings;
import com.x.base.core.project.gson.XGsonBuilder;
import com.x.base.core.project.logger.Logger;
import com.x.base.core.project.logger.LoggerFactory;
import com.x.base.core.project.tools.ClassLoaderTools;
import com.x.base.core.project.tools.DateTools;
import com.x.base.core.project.tools.ListTools;
import com.x.query.core.entity.Item;
public class DumpData {
private static Logger logger = LoggerFactory.getLogger(DumpData.class);
public boolean execute(String path) throws Exception {
public boolean execute(String path) throws IOException, URISyntaxException {
Path dir = null;
Date start = new Date();
if (StringUtils.isEmpty(path)) {
......@@ -62,8 +60,10 @@ public class DumpData {
return false;
}
}
ClassLoader classLoader = EntityClassLoaderTools.concreteClassLoader();
Files.createDirectories(dir);
Thread thread = new Thread(new RunnableImpl(dir, start));
Thread thread = new Thread(new RunnableImpl(dir, start, classLoader));
thread.setContextClassLoader(classLoader);
thread.start();
return true;
}
......@@ -74,37 +74,38 @@ public class DumpData {
private Date start;
private DumpRestoreDataCatalog catalog;
private Gson pureGsonDateFormated;
private ClassLoader classLoader;
public RunnableImpl(Path dir, Date start) {
public RunnableImpl(Path dir, Date start, ClassLoader classLoader) {
this.dir = dir;
this.start = start;
this.catalog = new DumpRestoreDataCatalog();
this.pureGsonDateFormated = XGsonBuilder.instance();
this.classLoader = classLoader;
Thread.currentThread().setContextClassLoader(classLoader);
}
private Thread dumpDataThread = new Thread(() -> {
public void run() {
try {
List<String> classNames = entities();
List<String> classNames = new ArrayList<>(JpaObjectTools.scanContainerEntityNames(classLoader));
logger.print("find {} data to dump, start at {}.", classNames.size(), DateTools.format(start));
Path xml = Paths.get(Config.dir_local_temp_classes().getAbsolutePath(),
DateTools.compact(start) + "_dump.xml");
PersistenceXmlHelper.write(xml.toString(), classNames, false);
PersistenceXmlHelper.write(xml.toString(), classNames, classLoader);
StorageMappings storageMappings = Config.storageMappings();
Stream<String> stream = BooleanUtils.isTrue(Config.dumpRestoreData().getParallel())
? classNames.parallelStream()
: classNames.stream();
AtomicInteger idx = new AtomicInteger(1);
stream.forEach(className -> {
Thread.currentThread().setContextClassLoader(classLoader);
String nameOfThread = Thread.currentThread().getName();
Thread.currentThread().setName(DumpData.class.getName() + ":" + className);
EntityManagerFactory emf = null;
EntityManager em = null;
try {
Thread.currentThread().setContextClassLoader(ClassLoaderTools.urlClassLoader(false, false,
false, false, false, Config.dir_local_temp_classes().toPath()));
Thread.currentThread().setName(DumpData.class.getName() + ":" + className);
@SuppressWarnings("unchecked")
Class<JpaObject> cls = (Class<JpaObject>) Thread.currentThread().getContextClassLoader()
.loadClass(className);
Class<JpaObject> cls = (Class<JpaObject>) classLoader.loadClass(className);
emf = OpenJPAPersistence.createEntityManagerFactory(cls.getName(), xml.getFileName().toString(),
PersistenceXmlHelper.properties(cls.getName(), Config.slice().getEnable()));
em = emf.createEntityManager();
......@@ -113,42 +114,26 @@ public class DumpData {
cls.getName(), estimateCount);
dump(cls, em, storageMappings, estimateCount);
} catch (Exception e) {
e.printStackTrace();
logger.error(new Exception(String.format("dump:%s error.", className), e));
} finally {
Thread.currentThread().setName(nameOfThread);
em.close();
emf.close();
if (null != em) {
em.close();
}
if (null != emf) {
emf.close();
}
}
});
Files.write(dir.resolve("catalog.json"),
pureGsonDateFormated.toJson(catalog).getBytes(StandardCharsets.UTF_8));
logger.print("dump data completed, directory: {}, count: {}, elapsed: {} minutes.", dir.toString(),
count(), (System.currentTimeMillis() - start.getTime()) / 1000 / 60);
} catch (Exception e) {
e.printStackTrace();
}
}, "dumpDataThread");
public void run() {
dumpDataThread.start();
}
@SuppressWarnings("unchecked")
private List<String> entities() throws Exception {
List<String> list = new ArrayList<>();
if (StringUtils.equals(Config.dumpRestoreData().getMode(), DumpRestoreData.TYPE_FULL)) {
list.addAll((List<String>) Config.resource(Config.RESOURCE_CONTAINERENTITYNAMES));
}else {
for (String str : (List<String>) Config.resource(Config.RESOURCE_CONTAINERENTITYNAMES)) {
Class<?> cls = Thread.currentThread().getContextClassLoader().loadClass(str);
ContainerEntity containerEntity = cls.getAnnotation(ContainerEntity.class);
if (Objects.equals(containerEntity.reference(), Reference.strong)) {
list.add(str);
}
}
}
return ListTools.includesExcludesWildcard(list, Config.dumpRestoreData().getIncludes(),
Config.dumpRestoreData().getExcludes());
}
private <T extends JpaObject> long estimateCount(EntityManager em, Class<T> cls) {
......@@ -171,7 +156,8 @@ public class DumpData {
if (StringUtils.isNotEmpty(id)) {
p = cb.greaterThan(root.get(JpaObject.id_FIELDNAME), id);
}
if ((Item.class == cls) && (StringUtils.isNotBlank(Config.dumpRestoreData().getItemCategory()))) {
if (StringUtils.equals(cls.getName(), "com.x.query.core.entity.Item")
&& (StringUtils.isNotBlank(Config.dumpRestoreData().getItemCategory()))) {
p = cb.and(p, cb.equal(root.get(DataItem.itemCategory_FIELDNAME),
ItemCategory.valueOf(Config.dumpRestoreData().getItemCategory())));
}
......
package com.x.server.console.action;
import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.filefilter.IOFileFilter;
import org.apache.commons.io.filefilter.WildcardFileFilter;
import org.apache.commons.lang3.StringUtils;
import com.x.base.core.project.config.Config;
public class EntityClassLoaderTools {
public static ClassLoader concreteClassLoader() throws IOException, URISyntaxException {
List<URL> urlList = new ArrayList<>();
IOFileFilter filter = new WildcardFileFilter("*.jar");
for (File o : FileUtils.listFiles(Config.dir_dynamic_jars(true), filter, null)) {
urlList.add(o.toURI().toURL());
}
for (File o : FileUtils.listFiles(Config.dir_custom_jars(true), filter, null)) {
urlList.add(o.toURI().toURL());
}
for (File o : FileUtils.listFiles(Config.dir_store_jars(true), filter, null)) {
if (!StringUtils.equalsIgnoreCase(FilenameUtils.getBaseName(o.toString()), "x_base_core_project")) {
urlList.add(o.toURI().toURL());
}
}
urlList.add(Config.dir_local_temp_classes().toURI().toURL());
URL[] urls = new URL[urlList.size()];
return URLClassLoader.newInstance(urlList.toArray(urls), ClassLoader.getSystemClassLoader());
}
}
......@@ -21,18 +21,18 @@ import com.x.base.core.entity.StorageObject;
import com.x.base.core.entity.annotation.ContainerEntity;
import com.x.base.core.entity.dataitem.DataItem;
import com.x.base.core.entity.dataitem.ItemCategory;
import com.x.base.core.entity.tools.JpaObjectTools;
import com.x.base.core.project.config.Config;
import com.x.base.core.project.config.StorageMapping;
import com.x.base.core.project.config.StorageMappings;
import com.x.base.core.project.logger.Logger;
import com.x.base.core.project.logger.LoggerFactory;
import com.x.base.core.project.tools.ClassLoaderTools;
import com.x.base.core.project.tools.DateTools;
import com.x.base.core.project.tools.ListTools;
public abstract class EraseContent {
private static Logger logger = LoggerFactory.getLogger(EraseContent.class);
private static final Logger LOGGER = LoggerFactory.getLogger(EraseContent.class);
private Date start;
......@@ -42,60 +42,56 @@ public abstract class EraseContent {
private ItemCategory itemCategory;
public abstract boolean execute() throws Exception;
private ClassLoader classLoader;
public abstract boolean execute();
protected void addClass(Class<?> cls) {
this.classNames.add(cls.getName());
}
protected void addClass(String className) {
this.classNames.add(className);
}
protected void init(String name, ItemCategory itemCategory) throws Exception {
protected void init(String name, ItemCategory itemCategory, ClassLoader classLoader) {
this.name = name;
this.itemCategory = itemCategory;
this.start = new Date();
this.classLoader = classLoader;
}
protected void run() throws Exception {
new Thread(() -> {
try {
Thread.currentThread().setContextClassLoader(ClassLoaderTools.urlClassLoader(false, false, false, false,
false, Config.dir_local_temp_classes().toPath()));
logger.print("erase {} content data: start at {}.", name, DateTools.format(start));
this.classNames = ListUtils.intersection(this.classNames,
(List<String>) Config.resource(Config.RESOURCE_CONTAINERENTITYNAMES));
StorageMappings storageMappings = Config.storageMappings();
File persistence = new File(Config.dir_local_temp_classes(),
DateTools.compact(this.start) + "_eraseContent.xml");
PersistenceXmlHelper.write(persistence.getAbsolutePath(), classNames, false);
for (int i = 0; i < classNames.size(); i++) {
Class<? extends JpaObject> cls = (Class<? extends JpaObject>) Thread.currentThread()
.getContextClassLoader().loadClass(classNames.get(i));
EntityManagerFactory emf = OpenJPAPersistence.createEntityManagerFactory(cls.getName(),
persistence.getName(),
PersistenceXmlHelper.properties(cls.getName(), Config.slice().getEnable()));
EntityManager em = emf.createEntityManager();
if (DataItem.class.isAssignableFrom(cls)) {
Long total = this.estimateItemCount(em, cls);
logger.print("erase {} content data:{}, total {}.", name, cls.getName(), total);
this.eraseItem(cls, em, total);
} else {
Long total = this.estimateCount(em, cls);
logger.print("erase {} content data:{}, total {}.", name, cls.getName(), total);
this.erase(cls, em, storageMappings, total);
}
em.close();
emf.close();
@SuppressWarnings("unchecked")
protected void run() {
try {
LOGGER.print("erase {} content data: start at {}.", name, DateTools.format(start));
this.classNames = ListUtils.intersection(this.classNames,
new ArrayList<>(JpaObjectTools.scanContainerEntityNames(classLoader)));
StorageMappings storageMappings = Config.storageMappings();
File persistence = new File(Config.dir_local_temp_classes(),
DateTools.compact(this.start) + "_eraseContent.xml");
PersistenceXmlHelper.write(persistence.getAbsolutePath(), classNames, classLoader);
for (int i = 0; i < classNames.size(); i++) {
Class<? extends JpaObject> cls = (Class<? extends JpaObject>) Thread.currentThread()
.getContextClassLoader().loadClass(classNames.get(i));
EntityManagerFactory emf = OpenJPAPersistence.createEntityManagerFactory(cls.getName(),
persistence.getName(),
PersistenceXmlHelper.properties(cls.getName(), Config.slice().getEnable()));
EntityManager em = emf.createEntityManager();
if (DataItem.class.isAssignableFrom(cls)) {
Long total = this.estimateItemCount(em, cls);
LOGGER.print("erase {} content data:{}, total {}.", name, cls.getName(), total);
this.eraseItem(cls, em, total);
} else {
Long total = this.estimateCount(em, cls);
LOGGER.print("erase {} content data:{}, total {}.", name, cls.getName(), total);
this.erase(cls, em, storageMappings, total);
}
Date end = new Date();
logger.print("erase {} content data: completed at {}, elapsed {} ms.", name, DateTools.format(end),
(end.getTime() - start.getTime()));
} catch (Exception e) {
logger.error(e);
em.close();
emf.close();
}
}, "eraseContentThread").start();
Date end = new Date();
LOGGER.print("erase {} content data: completed at {}, elapsed {} ms.", name, DateTools.format(end),
(end.getTime() - start.getTime()));
} catch (Exception e) {
LOGGER.error(e);
}
}
private <T extends JpaObject> long estimateCount(EntityManager em, Class<T> cls) {
......@@ -122,37 +118,53 @@ public abstract class EraseContent {
ContainerEntity containerEntity = cls.getAnnotation(ContainerEntity.class);
do {
if (ListTools.isNotEmpty(list)) {
em.getTransaction().begin();
for (T t : list) {
em.remove(t);
}
em.getTransaction().commit();
delete(em, list);
if (StorageObject.class.isAssignableFrom(cls)) {
for (T t : list) {
StorageObject storageObject = (StorageObject) t;
String storageName = storageObject.getStorage();
StorageMapping mapping = storageMappings.get(storageObject.getClass(), storageName);
if (null != mapping) {
storageObject.deleteContent(mapping);
} else {
logger.print("can not find storage mapping {}.", storageName);
}
}
deleteStorage(storageMappings, list);
}
if (null != list) {
count += list.size();
}
count += list.size();
em.clear();
logger.print("erase {} content data:{}, {}/{}.", name, cls.getName(), count, total);
LOGGER.print("erase {} content data:{}, {}/{}.", name, cls.getName(), count, total);
}
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<T> cq = cb.createQuery(cls);
Root<T> root = cq.from(cls);
cq.select(root);
list = em.createQuery(cq).setMaxResults(containerEntity.dumpSize()).getResultList();
list = list(cls, em, containerEntity);
} while (ListTools.isNotEmpty(list));
return count;
}
private <T> Long eraseItem(Class<T> cls, EntityManager em, Long total) throws Exception {
private <T> void deleteStorage(StorageMappings storageMappings, List<T> list) throws Exception {
for (T t : list) {
StorageObject storageObject = (StorageObject) t;
String storageName = storageObject.getStorage();
StorageMapping mapping = storageMappings.get(storageObject.getClass(), storageName);
if (null != mapping) {
storageObject.deleteContent(mapping);
} else {
LOGGER.print("can not find storage mapping {}.", storageName);
}
}
}
private <T> void delete(EntityManager em, List<T> list) {
em.getTransaction().begin();
for (T t : list) {
em.remove(t);
}
em.getTransaction().commit();
}
private <T> List<T> list(Class<T> cls, EntityManager em, ContainerEntity containerEntity) {
List<T> list;
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<T> cq = cb.createQuery(cls);
Root<T> root = cq.from(cls);
cq.select(root);
list = em.createQuery(cq).setMaxResults(containerEntity.dumpSize()).getResultList();
return list;
}
private <T> Long eraseItem(Class<T> cls, EntityManager em, Long total) {
Long count = 0L;
List<T> list = null;
ContainerEntity containerEntity = cls.getAnnotation(ContainerEntity.class);
......@@ -163,9 +175,11 @@ public abstract class EraseContent {
em.remove(t);
}
em.getTransaction().commit();
count += list.size();
if (null != list) {
count += list.size();
}
em.clear();
logger.print("erase {} content data:{}, {}/{}.", name, cls.getName(), count, total);
LOGGER.print("erase {} content data:{}, {}/{}.", name, cls.getName(), count, total);
}
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<T> cq = cb.createQuery(cls);
......
......@@ -3,33 +3,31 @@ package com.x.server.console.action;
import com.x.base.core.entity.dataitem.ItemCategory;
import com.x.base.core.project.logger.Logger;
import com.x.base.core.project.logger.LoggerFactory;
import com.x.bbs.entity.BBSOperationRecord;
import com.x.bbs.entity.BBSReplyInfo;
import com.x.bbs.entity.BBSSubjectAttachment;
import com.x.bbs.entity.BBSSubjectContent;
import com.x.bbs.entity.BBSSubjectInfo;
import com.x.bbs.entity.BBSSubjectVoteResult;
import com.x.bbs.entity.BBSVoteOption;
import com.x.bbs.entity.BBSVoteOptionGroup;
import com.x.bbs.entity.BBSVoteRecord;
public class EraseContentBbs extends EraseContent {
private static Logger logger = LoggerFactory.getLogger(EraseContentBbs.class);
private static final Logger LOGGER = LoggerFactory.getLogger(EraseContentBbs.class);
@Override
public boolean execute() throws Exception {
this.init("bbs", ItemCategory.bbs);
addClass(BBSOperationRecord.class);
addClass(BBSReplyInfo.class);
addClass(BBSSubjectAttachment.class);
addClass(BBSSubjectContent.class);
addClass(BBSSubjectInfo.class);
addClass(BBSSubjectVoteResult.class);
addClass(BBSVoteOption.class);
addClass(BBSVoteOptionGroup.class);
addClass(BBSVoteRecord.class);
this.run();
return true;
public boolean execute() {
try {
ClassLoader classLoader = EntityClassLoaderTools.concreteClassLoader();
Thread.currentThread().setContextClassLoader(classLoader);
this.init("bbs", ItemCategory.bbs, classLoader);
addClass(classLoader.loadClass("com.x.bbs.entity.BBSOperationRecord"));
addClass(classLoader.loadClass("com.x.bbs.entity.BBSReplyInfo"));
addClass(classLoader.loadClass("com.x.bbs.entity.BBSSubjectAttachment"));
addClass(classLoader.loadClass("com.x.bbs.entity.BBSSubjectContent"));
addClass(classLoader.loadClass("com.x.bbs.entity.BBSSubjectInfo"));
addClass(classLoader.loadClass("com.x.bbs.entity.BBSSubjectVoteResult"));
addClass(classLoader.loadClass("com.x.bbs.entity.BBSVoteOption"));
addClass(classLoader.loadClass("com.x.bbs.entity.BBSVoteOptionGroup"));
addClass(classLoader.loadClass("com.x.bbs.entity.BBSVoteRecord"));
this.run();
return true;
} catch (Exception e) {
LOGGER.error(e);
}
return false;
}
}
\ No newline at end of file
......@@ -3,39 +3,34 @@ package com.x.server.console.action;
import com.x.base.core.entity.dataitem.ItemCategory;
import com.x.base.core.project.logger.Logger;
import com.x.base.core.project.logger.LoggerFactory;
import com.x.cms.core.entity.CmsBatchOperation;
import com.x.cms.core.entity.Document;
import com.x.cms.core.entity.DocumentCommend;
import com.x.cms.core.entity.DocumentCommentCommend;
import com.x.cms.core.entity.DocumentCommentContent;
import com.x.cms.core.entity.DocumentCommentInfo;
import com.x.cms.core.entity.DocumentViewRecord;
import com.x.cms.core.entity.FileInfo;
import com.x.cms.core.entity.Log;
import com.x.cms.core.entity.ReadRemind;
import com.x.cms.core.entity.Review;
import com.x.query.core.entity.Item;
public class EraseContentCms extends EraseContent {
private static Logger logger = LoggerFactory.getLogger(EraseContentCms.class);
private static final Logger LOGGER = LoggerFactory.getLogger(EraseContentCms.class);
@Override
public boolean execute() throws Exception {
this.init("cms", ItemCategory.cms);
addClass(Document.class);
addClass(Review.class);
addClass(DocumentViewRecord.class);
addClass(FileInfo.class);
addClass(Log.class);
addClass(ReadRemind.class);
addClass(DocumentCommentInfo.class);
addClass(DocumentCommentContent.class);
addClass(DocumentCommentCommend.class);
addClass(DocumentCommend.class);
addClass(CmsBatchOperation.class);
addClass(Item.class);
this.run();
return true;
public boolean execute() {
try {
ClassLoader classLoader = EntityClassLoaderTools.concreteClassLoader();
Thread.currentThread().setContextClassLoader(classLoader);
this.init("cms", ItemCategory.cms, classLoader);
addClass(classLoader.loadClass("com.x.cms.core.entity.CmsBatchOperation"));
addClass(classLoader.loadClass("com.x.cms.core.entity.Document"));
addClass(classLoader.loadClass("com.x.cms.core.entity.DocumentCommend"));
addClass(classLoader.loadClass("com.x.cms.core.entity.DocumentCommentCommend"));
addClass(classLoader.loadClass("com.x.cms.core.entity.DocumentCommentContent"));
addClass(classLoader.loadClass("com.x.cms.core.entity.DocumentCommentInfo"));
addClass(classLoader.loadClass("com.x.cms.core.entity.DocumentViewRecord"));
addClass(classLoader.loadClass("com.x.cms.core.entity.FileInfo"));
addClass(classLoader.loadClass("com.x.cms.core.entity.Log"));
addClass(classLoader.loadClass("com.x.cms.core.entity.ReadRemind"));
addClass(classLoader.loadClass("com.x.cms.core.entity.Review"));
addClass(classLoader.loadClass("com.x.query.core.entity.Item"));
this.run();
return true;
} catch (Exception e) {
LOGGER.error(e);
}
return false;
}
}
\ No newline at end of file
package com.x.server.console.action;
import java.util.Collection;
import com.x.base.core.project.logger.Logger;
import com.x.base.core.project.logger.LoggerFactory;
public class EraseContentEntity extends EraseContent {
private static Logger logger = LoggerFactory.getLogger(EraseContentEntity.class);
private static final Logger LOGGER = LoggerFactory.getLogger(EraseContentEntity.class);
public boolean execute(Collection<String> names) {
try {
ClassLoader classLoader = EntityClassLoaderTools.concreteClassLoader();
Thread.currentThread().setContextClassLoader(classLoader);
this.init("entity", null, classLoader);
for (String name : names) {
this.addClass(classLoader.loadClass(name));
}
return execute();
} catch (Exception e) {
LOGGER.error(e);
}
return false;
}
@Override
public boolean execute() throws Exception {
this.init("entity", null);
public boolean execute() {
this.run();
return true;
}
......
......@@ -2,31 +2,30 @@ package com.x.server.console.action;
import com.x.base.core.project.logger.Logger;
import com.x.base.core.project.logger.LoggerFactory;
import com.x.processplatform.core.entity.element.FormVersion;
import com.x.processplatform.core.entity.element.ProcessVersion;
import com.x.processplatform.core.entity.element.ScriptVersion;
import com.x.processplatform.core.entity.log.SignalStackLog;
import com.x.program.center.core.entity.PromptErrorLog;
import com.x.program.center.core.entity.ScheduleLog;
import com.x.program.center.core.entity.UnexpectedErrorLog;
import com.x.program.center.core.entity.WarnLog;
public class EraseContentLog extends EraseContent {
private static Logger logger = LoggerFactory.getLogger(EraseContentLog.class);
private static final Logger LOGGER = LoggerFactory.getLogger(EraseContentLog.class);
@Override
public boolean execute() throws Exception {
this.init("log", null);
addClass(ScheduleLog.class);
addClass(PromptErrorLog.class);
addClass(UnexpectedErrorLog.class);
addClass(WarnLog.class);
addClass(ProcessVersion.class);
addClass(FormVersion.class);
addClass(ScriptVersion.class);
addClass(SignalStackLog.class);
this.run();
return true;
public boolean execute() {
try {
ClassLoader classLoader = EntityClassLoaderTools.concreteClassLoader();
Thread.currentThread().setContextClassLoader(classLoader);
this.init("log", null, classLoader);
addClass(classLoader.loadClass("com.x.processplatform.core.entity.element.FormVersion"));
addClass(classLoader.loadClass("com.x.processplatform.core.entity.element.ProcessVersion"));
addClass(classLoader.loadClass("com.x.processplatform.core.entity.element.ScriptVersion"));
addClass(classLoader.loadClass("com.x.processplatform.core.entity.log.SignalStackLog"));
addClass(classLoader.loadClass("com.x.program.center.core.entity.PromptErrorLog"));
addClass(classLoader.loadClass("com.x.program.center.core.entity.ScheduleLog"));
addClass(classLoader.loadClass("com.x.program.center.core.entity.UnexpectedErrorLog"));
addClass(classLoader.loadClass("com.x.program.center.core.entity.WarnLog"));
this.run();
return true;
} catch (Exception e) {
LOGGER.error(e);
}
return false;
}
}
\ No newline at end of file
......@@ -2,29 +2,29 @@ package com.x.server.console.action;
import com.x.base.core.project.logger.Logger;
import com.x.base.core.project.logger.LoggerFactory;
import com.x.message.core.entity.IMConversation;
import com.x.message.core.entity.IMConversationExt;
import com.x.message.core.entity.IMMsg;
import com.x.message.core.entity.Instant;
import com.x.message.core.entity.Mass;
import com.x.message.core.entity.Message;
import com.x.message.core.entity.Org;
public class EraseContentMessage extends EraseContent {
private static Logger logger = LoggerFactory.getLogger(EraseContentMessage.class);
private static final Logger LOGGER = LoggerFactory.getLogger(EraseContentMessage.class);
@Override
public boolean execute() throws Exception {
this.init("message", null);
addClass(IMConversation.class);
addClass(IMConversationExt.class);
addClass(IMMsg.class);
addClass(Instant.class);
addClass(Mass.class);
addClass(Message.class);
addClass(Org.class);
this.run();
return true;
public boolean execute() {
try {
ClassLoader classLoader = EntityClassLoaderTools.concreteClassLoader();
Thread.currentThread().setContextClassLoader(classLoader);
this.init("message", null, classLoader);
addClass(classLoader.loadClass("com.x.message.core.entity.IMConversation"));
addClass(classLoader.loadClass("com.x.message.core.entity.IMConversationExt"));
addClass(classLoader.loadClass("com.x.message.core.entity.IMMsg"));
addClass(classLoader.loadClass("com.x.message.core.entity.Instant"));
addClass(classLoader.loadClass("com.x.message.core.entity.Mass"));
addClass(classLoader.loadClass("com.x.message.core.entity.Message"));
addClass(classLoader.loadClass("com.x.message.core.entity.Org"));
this.run();
return true;
} catch (Exception e) {
LOGGER.error(e);
}
return false;
}
}
\ No newline at end of file
package com.x.server.console.action;
import javax.wsdl.Definition;
import com.x.base.core.project.logger.Logger;
import com.x.base.core.project.logger.LoggerFactory;
import com.x.organization.core.entity.Bind;
import com.x.organization.core.entity.Custom;
import com.x.organization.core.entity.Group;
import com.x.organization.core.entity.Identity;
import com.x.organization.core.entity.OauthCode;
import com.x.organization.core.entity.Person;
import com.x.organization.core.entity.PersonAttribute;
import com.x.organization.core.entity.PersonCard;
import com.x.organization.core.entity.Role;
import com.x.organization.core.entity.Unit;
import com.x.organization.core.entity.UnitAttribute;
import com.x.organization.core.entity.UnitDuty;
import com.x.organization.core.entity.accredit.Empower;
import com.x.organization.core.entity.accredit.EmpowerLog;
public class EraseContentOrg extends EraseContent {
private static Logger logger = LoggerFactory.getLogger(EraseContentOrg.class);
private static final Logger LOGGER = LoggerFactory.getLogger(EraseContentOrg.class);
@Override
public boolean execute() throws Exception {
this.init("org", null);
addClass(Group.class);
addClass(Role.class);
addClass(UnitDuty.class);
addClass(UnitAttribute.class);
addClass(Unit.class);
addClass(PersonCard.class);
addClass(Bind.class);
addClass(Definition.class);
addClass(OauthCode.class);
addClass(Empower.class);
addClass(EmpowerLog.class);
addClass(Identity.class);
addClass(Custom.class);
addClass(PersonAttribute.class);
addClass(Person.class);
this.run();
return true;
public boolean execute() {
try {
ClassLoader classLoader = EntityClassLoaderTools.concreteClassLoader();
Thread.currentThread().setContextClassLoader(classLoader);
this.init("org", null, classLoader);
addClass(classLoader.loadClass("com.x.organization.core.entity.Bind"));
addClass(classLoader.loadClass("com.x.organization.core.entity.Custom"));
addClass(classLoader.loadClass("com.x.organization.core.entity.Definition"));
addClass(classLoader.loadClass("com.x.organization.core.entity.Group"));
addClass(classLoader.loadClass("com.x.organization.core.entity.Identity"));
addClass(classLoader.loadClass("com.x.organization.core.entity.OauthCode"));
addClass(classLoader.loadClass("com.x.organization.core.entity.Person"));
addClass(classLoader.loadClass("com.x.organization.core.entity.PersonAttribute"));
addClass(classLoader.loadClass("com.x.organization.core.entity.PersonCard"));
addClass(classLoader.loadClass("com.x.organization.core.entity.Role"));
addClass(classLoader.loadClass("com.x.organization.core.entity.Unit"));
addClass(classLoader.loadClass("com.x.organization.core.entity.UnitAttribute"));
addClass(classLoader.loadClass("com.x.organization.core.entity.UnitDuty"));
addClass(classLoader.loadClass("com.x.organization.core.entity.accredit.Empower"));
addClass(classLoader.loadClass("com.x.organization.core.entity.accredit.EmpowerLog"));
this.run();
return true;
} catch (Exception e) {
LOGGER.error(e);
}
return false;
}
}
\ No newline at end of file
......@@ -3,44 +3,36 @@ package com.x.server.console.action;
import com.x.base.core.entity.dataitem.ItemCategory;
import com.x.base.core.project.logger.Logger;
import com.x.base.core.project.logger.LoggerFactory;
import com.x.processplatform.core.entity.content.Attachment;
import com.x.processplatform.core.entity.content.DocumentVersion;
import com.x.processplatform.core.entity.content.Draft;
import com.x.processplatform.core.entity.content.Read;
import com.x.processplatform.core.entity.content.ReadCompleted;
import com.x.processplatform.core.entity.content.Record;
import com.x.processplatform.core.entity.content.Review;
import com.x.processplatform.core.entity.content.SerialNumber;
import com.x.processplatform.core.entity.content.Task;
import com.x.processplatform.core.entity.content.TaskCompleted;
import com.x.processplatform.core.entity.content.Work;
import com.x.processplatform.core.entity.content.WorkCompleted;
import com.x.processplatform.core.entity.content.WorkLog;
import com.x.processplatform.core.entity.log.SignalStackLog;
import com.x.query.core.entity.Item;
public class EraseContentProcessPlatform extends EraseContent {
private static Logger logger = LoggerFactory.getLogger(EraseContentProcessPlatform.class);
public boolean execute() throws Exception {
this.init("processPlatform", ItemCategory.pp);
addClass(Attachment.class);
addClass(DocumentVersion.class);
addClass(Draft.class);
addClass(Read.class);
addClass(ReadCompleted.class);
addClass(Record.class);
addClass(Review.class);
addClass(SerialNumber.class);
addClass(Task.class);
addClass(TaskCompleted.class);
addClass(Work.class);
addClass(WorkCompleted.class);
addClass(WorkLog.class);
addClass(Item.class);
addClass(SignalStackLog.class);
this.run();
return true;
private static final Logger LOGGER = LoggerFactory.getLogger(EraseContentProcessPlatform.class);
public boolean execute() {
try {
ClassLoader classLoader = EntityClassLoaderTools.concreteClassLoader();
Thread.currentThread().setContextClassLoader(classLoader);
this.init("processPlatform", ItemCategory.pp, classLoader);
addClass(classLoader.loadClass("com.x.processplatform.core.entity.content.Attachment"));
addClass(classLoader.loadClass("com.x.processplatform.core.entity.content.DocumentVersion"));
addClass(classLoader.loadClass("com.x.processplatform.core.entity.content.Draft"));
addClass(classLoader.loadClass("com.x.processplatform.core.entity.content.Read"));
addClass(classLoader.loadClass("com.x.processplatform.core.entity.content.ReadCompleted"));
addClass(classLoader.loadClass("com.x.processplatform.core.entity.content.Record"));
addClass(classLoader.loadClass("com.x.processplatform.core.entity.content.Review"));
addClass(classLoader.loadClass("com.x.processplatform.core.entity.content.SerialNumber"));
addClass(classLoader.loadClass("com.x.processplatform.core.entity.content.Task"));
addClass(classLoader.loadClass("com.x.processplatform.core.entity.content.TaskCompleted"));
addClass(classLoader.loadClass("com.x.processplatform.core.entity.content.Work"));
addClass(classLoader.loadClass("com.x.processplatform.core.entity.content.WorkCompleted"));
addClass(classLoader.loadClass("com.x.processplatform.core.entity.content.WorkLog"));
addClass(classLoader.loadClass("com.x.processplatform.core.entity.log.SignalStackLog"));
addClass(classLoader.loadClass("com.x.query.core.entity.Item"));
this.run();
return true;
} catch (Exception e) {
LOGGER.error(e);
}
return false;
}
}
\ No newline at end of file
......@@ -2,6 +2,7 @@ package com.x.server.console.action;
import java.io.IOException;
import java.io.InputStream;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
......@@ -36,6 +37,7 @@ import com.x.base.core.entity.StorageObject;
import com.x.base.core.entity.annotation.ContainerEntity;
import com.x.base.core.entity.dataitem.DataItem;
import com.x.base.core.entity.dataitem.ItemCategory;
import com.x.base.core.entity.tools.JpaObjectTools;
import com.x.base.core.project.config.Config;
import com.x.base.core.project.config.DumpRestoreData;
import com.x.base.core.project.config.StorageMapping;
......@@ -43,36 +45,35 @@ import com.x.base.core.project.config.StorageMappings;
import com.x.base.core.project.gson.XGsonBuilder;
import com.x.base.core.project.logger.Logger;
import com.x.base.core.project.logger.LoggerFactory;
import com.x.base.core.project.tools.ClassLoaderTools;
import com.x.base.core.project.tools.DateTools;
import com.x.base.core.project.tools.ListTools;
import com.x.query.core.entity.Item;
import net.sf.ehcache.hibernate.management.impl.BeanUtils;
public class RestoreData {
private static Logger logger = LoggerFactory.getLogger(RestoreData.class);
private static final Logger LOGGER = LoggerFactory.getLogger(RestoreData.class);
public boolean execute(String path) throws Exception {
public boolean execute(String path) throws IOException, URISyntaxException {
Date start = new Date();
Path dir;
if (StringUtils.isEmpty(path)) {
logger.warn("path is empty.");
LOGGER.warn("{}.", () -> "path is empty.");
}
ClassLoader classLoader = EntityClassLoaderTools.concreteClassLoader();
if (BooleanUtils.isTrue(DateTools.isCompactDateTime(path))) {
dir = Paths.get(Config.base(), "local", "dump", "dumpData_" + path);
} else {
dir = Paths.get(path);
if ((!Files.exists(dir)) || (!Files.isDirectory(dir))) {
logger.warn("directory not exist: {}.", path);
LOGGER.warn("directory not exist: {}.", path);
return false;
} else if (dir.startsWith(Paths.get(Config.base()))) {
logger.warn("path can not in base directory.");
LOGGER.warn("path can not in base directory.");
return false;
}
}
Thread thread = new Thread(new RunnableImpl(dir, start));
Thread thread = new Thread(new RunnableImpl(dir, start, classLoader));
thread.start();
return true;
}
......@@ -83,10 +84,13 @@ public class RestoreData {
private Date start;
private DumpRestoreDataCatalog catalog;
private Gson gson;
private ClassLoader classLoader;
public RunnableImpl(Path dir, Date start) throws IOException {
public RunnableImpl(Path dir, Date start, ClassLoader classLoader) throws IOException {
this.dir = dir;
this.start = start;
this.classLoader = classLoader;
Thread.currentThread().setContextClassLoader(classLoader);
this.catalog = new DumpRestoreDataCatalog();
this.gson = XGsonBuilder.instance();
Path path = dir.resolve("catalog.json");
......@@ -97,53 +101,37 @@ public class RestoreData {
@Override
public void run() {
try {
List<String> classNames = this.entities();
logger.print("find: {} data to restore, path: {}.", classNames.size(), this.dir.toString());
List<String> classNames = entities(catalog);
LOGGER.print("find: {} data to restore, path: {}.", classNames.size(), this.dir.toString());
Path xml = Paths.get(Config.dir_local_temp_classes().getAbsolutePath(),
DateTools.compact(start) + "_restore.xml");
PersistenceXmlHelper.write(xml.toString(), classNames, false);
PersistenceXmlHelper.write(xml.toString(), classNames, classLoader);
Stream<String> stream = BooleanUtils.isTrue(Config.dumpRestoreData().getParallel())
? classNames.parallelStream()
: classNames.stream();
AtomicInteger idx = new AtomicInteger(1);
AtomicLong total = new AtomicLong(0);
stream.forEach(className -> {
String nameOfThread = Thread.currentThread().getName();
Thread.currentThread().setContextClassLoader(classLoader);
try {
Thread.currentThread().setContextClassLoader(ClassLoaderTools.urlClassLoader(false, false,
false, false, false, Config.dir_local_temp_classes().toPath()));
Thread.currentThread().setName(RestoreData.class.getName() + ":" + className);
@SuppressWarnings("unchecked")
Class<JpaObject> cls = (Class<JpaObject>) Thread.currentThread().getContextClassLoader()
.loadClass(className);
logger.print("restore data({}/{}): {}.", idx.getAndAdd(1), classNames.size(), cls.getName());
LOGGER.print("restore data({}/{}): {}.", idx.getAndAdd(1), classNames.size(), cls.getName());
long size = restore(cls, xml);
total.getAndAdd(size);
} catch (Exception e) {
logger.error(new Exception(String.format("restore:%s error.", className), e));
} finally {
Thread.currentThread().setName(nameOfThread);
LOGGER.error(new Exception(String.format("restore:%s error.", className), e));
}
});
logger.print("restore data completed, directory: {}, count: {}, total: {}, elapsed: {} minutes.",
LOGGER.print("restore data completed, directory: {}, count: {}, total: {}, elapsed: {} minutes.",
dir.toString(), idx.get(), total.longValue(),
(System.currentTimeMillis() - start.getTime()) / 1000 / 60);
} catch (Exception e) {
logger.error(e);
LOGGER.error(e);
}
}
@SuppressWarnings("unchecked")
private List<String> entities() throws Exception {
List<String> containerEntityNames = new ArrayList<>();
containerEntityNames.addAll((List<String>) Config.resource(Config.RESOURCE_CONTAINERENTITYNAMES));
List<String> classNames = new ArrayList<>();
classNames.addAll(this.catalog.keySet());
classNames = ListTools.includesExcludesWildcard(classNames, Config.dumpRestoreData().getIncludes(),
Config.dumpRestoreData().getExcludes());
return ListTools.includesExcludesWildcard(containerEntityNames, classNames, null);
}
private long restore(Class<?> cls, Path xml) throws Exception {
EntityManagerFactory emf = OpenJPAPersistence.createEntityManagerFactory(cls.getName(),
xml.getFileName().toString(),
......@@ -165,7 +153,7 @@ public class RestoreData {
}
List<Path> paths = this.list(directory);
paths.stream().forEach(o -> {
logger.print("restore {}/{} part of data:{}.", batch.getAndAdd(1), paths.size(), cls.getName());
LOGGER.print("restore {}/{} part of data:{}.", batch.getAndAdd(1), paths.size(), cls.getName());
try {
em.getTransaction().begin();
JsonArray raws = this.convert(o);
......@@ -186,12 +174,12 @@ public class RestoreData {
em.getTransaction().commit();
em.clear();
} catch (Exception e) {
logger.error(new Exception(String.format("restore error with file:%s.", o.toString()), e));
LOGGER.error(new Exception(String.format("restore error with file:%s.", o.toString()), e));
}
});
logger.print("restore data: {} completed, count: {}.", cls.getName(), count.intValue());
LOGGER.print("restore data: {} completed, count: {}.", cls.getName(), count.intValue());
} catch (Exception e) {
logger.error(e);
LOGGER.error(e);
} finally {
em.close();
emf.close();
......@@ -212,6 +200,16 @@ public class RestoreData {
return list;
}
private List<String> entities(DumpRestoreDataCatalog catalog) throws Exception {
List<String> containerEntityNames = new ArrayList<>();
containerEntityNames.addAll(JpaObjectTools.scanContainerEntityNames(classLoader));
List<String> classNames = new ArrayList<>();
classNames.addAll(catalog.keySet());
classNames = ListTools.includesExcludesWildcard(classNames, Config.dumpRestoreData().getIncludes(),
Config.dumpRestoreData().getExcludes());
return ListTools.includesExcludesWildcard(containerEntityNames, classNames, null);
}
@SuppressWarnings("unchecked")
private void binary(Object o, Class<?> cls, Path sub, StorageMappings storageMappings) throws Exception {
StorageObject so = (StorageObject) o;
......@@ -226,8 +224,8 @@ public class RestoreData {
}
Path path = sub.resolve(Paths.get(so.path()).getFileName());
if (!Files.exists(path)) {
logger.warn("file not exist: {}.", path.toString());
}else {
LOGGER.warn("file not exist: {}.", path.toString());
} else {
try (InputStream input = Files.newInputStream(path)) {
so.saveContent(mapping, input, so.getName());
}
......@@ -260,17 +258,23 @@ public class RestoreData {
}
em.getTransaction().commit();
}
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<T> cq = cb.createQuery(cls);
Root<T> root = cq.from(cls);
Predicate p = cb.conjunction();
if ((Item.class == cls) && (StringUtils.isNotBlank(Config.dumpRestoreData().getItemCategory()))) {
p = cb.and(p, cb.equal(root.get(DataItem.itemCategory_FIELDNAME),
ItemCategory.valueOf(Config.dumpRestoreData().getItemCategory())));
}
list = em.createQuery(cq.select(root).where(p)).setMaxResults(containerEntity.dumpSize())
.getResultList();
list = list(cls, em, containerEntity);
} while (ListTools.isNotEmpty(list));
}
private <T> List<T> list(Class<T> cls, EntityManager em, ContainerEntity containerEntity) throws Exception {
List<T> list;
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<T> cq = cb.createQuery(cls);
Root<T> root = cq.from(cls);
Predicate p = cb.conjunction();
if (StringUtils.equals(cls.getName(), "com.x.query.core.entity.Item")
&& (StringUtils.isNotBlank(Config.dumpRestoreData().getItemCategory()))) {
p = cb.and(p, cb.equal(root.get(DataItem.itemCategory_FIELDNAME),
ItemCategory.valueOf(Config.dumpRestoreData().getItemCategory())));
}
list = em.createQuery(cq.select(root).where(p)).setMaxResults(containerEntity.dumpSize()).getResultList();
return list;
}
}
}
\ No newline at end of file
......@@ -93,12 +93,12 @@ public abstract class JettySeverTools {
jars.add(file.getAbsolutePath());
}
}
if (module.dynamicJars() != null && module.dynamicJars().length > 0) {
IOFileFilter filter = new WildcardFileFilter(DynamicEntity.JAR_PREFIX + "*.jar");
for (File o : FileUtils.listFiles(Config.dir_dynamic_jars(true), filter, null)) {
jars.add(o.getAbsolutePath());
}
}
// if (module.dynamicJars() != null && module.dynamicJars().length > 0) {
// IOFileFilter filter = new WildcardFileFilter(DynamicEntity.JAR_PREFIX + "*.jar");
// for (File o : FileUtils.listFiles(Config.dir_dynamic_jars(true), filter, null)) {
// jars.add(o.getAbsolutePath());
// }
// }
for (Path path : paths) {
if (Files.exists(path) && Files.isDirectory(path)) {
try (Stream<Path> stream = Files.walk(path, FileVisitOption.FOLLOW_LINKS)) {
......
......@@ -200,7 +200,7 @@ public class ApplicationServerTools extends JettySeverTools {
if (Files.exists(war)) {
modified(war, dir);
String className = contextParamProject(dir);
Class<?> cls = ClassLoaderTools.urlClassLoader(false, false, false, false, false,
Class<?> cls = ClassLoaderTools.urlClassLoader(null, false, false, false, false,
Paths.get(dir.toString(), PathTools.WEB_INF_CLASSES)).loadClass(className);
QuickStartWebApp webApp = new QuickStartWebApp();
webApp.setAutoPreconfigure(false);
......@@ -249,7 +249,7 @@ public class ApplicationServerTools extends JettySeverTools {
List<ClassInfo> officialClassInfos) {
officialClassInfos.parallelStream().forEach(info -> {
try {
Class<?> clz = Class.forName(info.getName());
Class<?> clz = Thread.currentThread().getContextClassLoader().loadClass(info.getName());
Path war = Paths.get(Config.dir_store().toString(), info.getSimpleName() + PathTools.DOT_WAR);
Path dir = Paths.get(Config.dir_servers_applicationServer_work().toString(), info.getSimpleName());
if (Files.exists(war)) {
......@@ -297,12 +297,13 @@ public class ApplicationServerTools extends JettySeverTools {
private static List<ClassInfo> listOfficial() throws Exception {
try (ScanResult scanResult = new ClassGraph()
.addClassLoader(ClassLoaderTools.urlClassLoader(true, false, true, false, false)).enableAnnotationInfo()
.scan()) {
.addClassLoader(
ClassLoaderTools.urlClassLoader(ClassLoader.getSystemClassLoader(), false, true, false, false))
.enableAnnotationInfo().scan()) {
List<ClassInfo> list = new ArrayList<>();
List<ClassInfo> classInfos = scanResult.getClassesWithAnnotation(Module.class.getName());
for (ClassInfo info : classInfos) {
Class<?> clz = Class.forName(info.getName());
Class<?> clz = Thread.currentThread().getContextClassLoader().loadClass(info.getName());
Module module = clz.getAnnotation(Module.class);
if (Objects.equals(module.type(), ModuleType.ASSEMBLE)
|| Objects.equals(module.type(), ModuleType.SERVICE)) {
......@@ -311,7 +312,7 @@ public class ApplicationServerTools extends JettySeverTools {
}
List<String> filters = new ArrayList<>();
for (ClassInfo info : list) {
Class<?> clz = Class.forName(info.getName());
Class<?> clz = Thread.currentThread().getContextClassLoader().loadClass(info.getName());
Module module = clz.getAnnotation(Module.class);
if (Objects.equals(ModuleCategory.OFFICIAL, module.category())) {
filters.add(info.getName());
......
......@@ -61,7 +61,7 @@ class ActionCreate extends BaseAction {
this.duplicate(business, mapping);
try {
Class.forName(DynamicEntity.CLASS_PACKAGE + "." + mapping.getTableName());
Thread.currentThread().getContextClassLoader().loadClass(DynamicEntity.CLASS_PACKAGE + "." + mapping.getTableName());
} catch (Exception e) {
throw new ExceptionDynamicClassNotExist(mapping.getTableName());
}
......
......@@ -61,7 +61,8 @@ class ActionEdit extends BaseAction {
this.duplicate(business, mapping);
try {
Class.forName(DynamicEntity.CLASS_PACKAGE + "." + mapping.getTableName());
Thread.currentThread().getContextClassLoader()
.loadClass(DynamicEntity.CLASS_PACKAGE + "." + mapping.getTableName());
} catch (Exception e) {
throw new ExceptionDynamicClassNotExist(mapping.getTableName());
}
......
......@@ -225,8 +225,6 @@ class ActionHtmlToImage extends BaseAction {
}
public static void main(String[] args) throws Exception{
System.out.println(10);
System.out.println("!!!!!!!!");
try (Playwright playwright = Playwright.create()) {
List<BrowserType> browserTypes = Arrays.asList(
playwright.chromium(),
......
......@@ -24,23 +24,9 @@ import com.x.processplatform.core.entity.element.Mapping;
public class MappingFactory {
// public static void mappingWorkCompleted(Mapping mapping, Data data, WorkCompleted workCompleted) throws Exception {
// mapping(mapping, data, workCompleted);
// }
public static void mapping(Mapping mapping, WorkCompleted workCompleted, Data data, JpaObject jpaObject)
throws Exception {
// if (BooleanUtils.isNotTrue(mapping.getEnable())) {
// return;
// }
//
// try {
// Class.forName(DynamicEntity.CLASS_PACKAGE + "." + mapping.getTableName());
// } catch (Exception e) {
// throw new ExceptionDynamicClassNotExist(mapping.getTableName());
// }
List<Mapping.Item> items = XGsonBuilder.instance().fromJson(mapping.getData(),
new TypeToken<List<Mapping.Item>>() {
}.getType());
......
......@@ -160,7 +160,8 @@ public class InvokeProcessor extends AbstractInvokeProcessor {
private boolean jaxrsInternal(AeiObjects aeiObjects, Invoke invoke) throws Exception {
ActionResponse resp = null;
Class<?> clz = Class.forName("com.x.base.core.project." + invoke.getInternalProject());
Class<?> clz = Thread.currentThread().getContextClassLoader()
.loadClass("com.x.base.core.project." + invoke.getInternalProject());
String uri = this.jaxrsUrl(aeiObjects, invoke);
switch (StringUtils.upperCase(invoke.getJaxrsMethod())) {
case ConnectionAction.METHOD_POST:
......
......@@ -139,13 +139,15 @@ public class Context extends AbstractContext {
ServletContext servletContext = servletContextEvent.getServletContext();
Context context = new Context();
context.contextPath = servletContext.getContextPath();
context.clazz = Class.forName(servletContext.getInitParameter(INITPARAMETER_PORJECT));
context.clazz = Thread.currentThread().getContextClassLoader()
.loadClass(servletContext.getInitParameter(INITPARAMETER_PORJECT));
context.module = context.clazz.getAnnotation(Module.class);
context.name = context.module.name();
context.path = servletContext.getRealPath("");
context.servletContext = servletContext;
context.servletContextName = servletContext.getServletContextName();
context.clazz = Class.forName(servletContextEvent.getServletContext().getInitParameter(INITPARAMETER_PORJECT));
context.clazz = Thread.currentThread().getContextClassLoader()
.loadClass(servletContextEvent.getServletContext().getInitParameter(INITPARAMETER_PORJECT));
context.initDatas();
// context.threadFactory = new ThreadFactory(context);
try (EntityManagerContainer emc = EntityManagerContainerFactory.instance().create()) {
......
package com.x.program.center.jaxrs.datastructure;
import com.x.base.core.project.annotation.FieldDescribe;
import com.x.base.core.project.http.ActionResult;
import com.x.base.core.project.http.EffectivePerson;
import com.x.base.core.project.logger.Logger;
import com.x.base.core.project.logger.LoggerFactory;
import javax.servlet.http.HttpServletRequest;
import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import com.x.base.core.project.annotation.FieldDescribe;
import com.x.base.core.project.http.ActionResult;
import com.x.base.core.project.http.EffectivePerson;
import com.x.base.core.project.logger.Logger;
import com.x.base.core.project.logger.LoggerFactory;
/**
* 获取所有应用的实体依赖以及数据表依赖
*/
class ActionGetAllModuleStructure extends BaseAction {
private static Logger logger = LoggerFactory.getLogger(ActionGetAllModuleStructure.class);
ActionResult<List<Wo>> execute( EffectivePerson effectivePerson, HttpServletRequest request ) throws Exception {
ActionResult<List<Wo>> execute(EffectivePerson effectivePerson, HttpServletRequest request) throws Exception {
ActionResult<List<Wo>> result = new ActionResult<>();
List<Wo> wos = new ArrayList<>();
Wo wo = null;
//遍历所有的模块
for( String className : OFFICIAL_MODULE_SORTED_TEMPLATE ){
wo = getEntityStructure( className );
wos.add( wo );
// 遍历所有的模块
for (String className : OFFICIAL_MODULE_SORTED_TEMPLATE) {
wo = getEntityStructure(className);
wos.add(wo);
}
result.setData( wos );
result.setData(wos);
return result;
}
/**
* 获取指定模块的实体依赖信息
*
* @param className
* @return
*/
private Wo getEntityStructure(String className) {
Wo wo = new Wo();
List<WoTable> woTables = new ArrayList<>();
wo.setModuleName( className );
wo.setModuleName(className);
try {
Class cls = Class.forName( className );
Class cls_annotation_moudle = Class.forName( "com.x.base.core.project.annotation.Module" );
Class cls = Thread.currentThread().getContextClassLoader().loadClass(className);
Class cls_annotation_moudle = Thread.currentThread().getContextClassLoader()
.loadClass("com.x.base.core.project.annotation.Module");
Method method_containerEntities = cls_annotation_moudle.getMethod("containerEntities");
Annotation annotation = cls.getAnnotation(cls_annotation_moudle);
Object result = null;
if( annotation != null ){
if (annotation != null) {
result = method_containerEntities.invoke(annotation);
if( result != null ){
String[] containerEntities = (String[])result;
if( containerEntities != null && containerEntities.length > 0 ){
for( String containerEntity : containerEntities ){
woTables.add( getTableStructure( containerEntity ));
if (result != null) {
String[] containerEntities = (String[]) result;
if (containerEntities != null && containerEntities.length > 0) {
for (String containerEntity : containerEntities) {
woTables.add(getTableStructure(containerEntity));
}
}
}
......@@ -66,31 +70,33 @@ class ActionGetAllModuleStructure extends BaseAction {
} catch (InvocationTargetException e) {
e.printStackTrace();
}
wo.setTables( woTables );
wo.setTables(woTables);
return wo;
}
/**
* 获取指定实体对应的表名信息
*
* @param containerEntity
* @return
*/
private WoTable getTableStructure( String containerEntity ) {
private WoTable getTableStructure(String containerEntity) {
WoTable woTable = new WoTable();
woTable.setEntityName( containerEntity );
woTable.setEntityName(containerEntity);
try {
Class cls_entity = Class.forName( containerEntity );
Class cls_annotation_table = Class.forName( "javax.persistence.Table" );
Class cls_entity = Thread.currentThread().getContextClassLoader().loadClass(containerEntity);
Class cls_annotation_table = Thread.currentThread().getContextClassLoader()
.loadClass("javax.persistence.Table");
Method cls_annotation_table_method_name = cls_annotation_table.getMethod("name");
Annotation annotation_table = cls_entity.getAnnotation(cls_annotation_table);
Object result = null;
if( annotation_table != null ){
if (annotation_table != null) {
result = cls_annotation_table_method_name.invoke(annotation_table);
woTable.setTableName( result.toString() );
woTable.setTableName(result.toString());
}
} catch (ClassNotFoundException | NoSuchMethodException e) {
logger.info("无法解析实体类" + containerEntity + ",请检查类依赖情况。" );
logger.info("无法解析实体类" + containerEntity + ",请检查类依赖情况。");
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
......@@ -149,4 +155,3 @@ class ActionGetAllModuleStructure extends BaseAction {
}
}
}
......@@ -24,22 +24,22 @@ class ActionGetAllTableFields extends BaseAction {
private static Logger logger = LoggerFactory.getLogger(ActionGetAllTableFields.class);
/**
* 已经分析过的数据表
* 已经分析过的数据表
*/
private List<String> analyzedEntityNames = new ArrayList<>();
ActionResult<List<Wo>> execute( EffectivePerson effectivePerson, HttpServletRequest request ) throws Exception {
ActionResult<List<Wo>> execute(EffectivePerson effectivePerson, HttpServletRequest request) throws Exception {
ActionResult<List<Wo>> result = new ActionResult<>();
List<Wo> wos = new ArrayList<>();
List<Wo> wos_newTables = null;
Wo wo = null;
//遍历所有的模块
for( String className : OFFICIAL_MODULE_SORTED_TEMPLATE ){
wos_newTables = getDataStructure( className );
wos.addAll( wos_newTables );
// 遍历所有的模块
for (String className : OFFICIAL_MODULE_SORTED_TEMPLATE) {
wos_newTables = getDataStructure(className);
wos.addAll(wos_newTables);
}
result.setData( wos );
result.setData(wos);
return result;
}
......@@ -48,23 +48,24 @@ class ActionGetAllTableFields extends BaseAction {
List<Wo> wos_tableFiels = new ArrayList<>();
Wo wo = null;
try {
Class cls = Class.forName( className );
Class cls_annotation_moudle = Class.forName( "com.x.base.core.project.annotation.Module" );
Class cls = Thread.currentThread().getContextClassLoader().loadClass(className);
Class cls_annotation_moudle = Thread.currentThread().getContextClassLoader()
.loadClass("com.x.base.core.project.annotation.Module");
Method method_containerEntities = cls_annotation_moudle.getMethod("containerEntities");
Annotation annotation = cls.getAnnotation(cls_annotation_moudle);
Object result = null;
if( annotation != null ){
if (annotation != null) {
result = method_containerEntities.invoke(annotation);
if( result != null ){
String[] containerEntities = (String[])result;
if( containerEntities != null && containerEntities.length > 0 ){
for( String containerEntity : containerEntities ){
if( !analyzedEntityNames.contains( containerEntity ) ){
wos_tableFiels = getTableStructure( containerEntity );
if(ListTools.isNotEmpty( wos_tableFiels ) ){
wos.addAll( wos_tableFiels );
analyzedEntityNames.add( containerEntity );
if (result != null) {
String[] containerEntities = (String[]) result;
if (containerEntities != null && containerEntities.length > 0) {
for (String containerEntity : containerEntities) {
if (!analyzedEntityNames.contains(containerEntity)) {
wos_tableFiels = getTableStructure(containerEntity);
if (ListTools.isNotEmpty(wos_tableFiels)) {
wos.addAll(wos_tableFiels);
analyzedEntityNames.add(containerEntity);
}
}
}
......@@ -81,33 +82,34 @@ class ActionGetAllTableFields extends BaseAction {
return wos;
}
private List<Wo> getTableStructure( String containerEntity ) {
private List<Wo> getTableStructure(String containerEntity) {
List<Wo> wos = new ArrayList<>();
Wo wo = null;
try {
Class cls_entity = Class.forName( containerEntity );
Class cls_annotation_table = Class.forName( "javax.persistence.Table" );
Class cls_entity = Thread.currentThread().getContextClassLoader().loadClass(containerEntity);
Class cls_annotation_table = Thread.currentThread().getContextClassLoader()
.loadClass("javax.persistence.Table");
Method cls_annotation_table_method_name = cls_annotation_table.getMethod("name");
Annotation annotation_table = cls_entity.getAnnotation(cls_annotation_table);
Object result = null;
if( annotation_table != null ){
//遍历所有的有@Column的属性
if (annotation_table != null) {
// 遍历所有的有@Column的属性
Field[] fileds = cls_entity.getDeclaredFields();
if( fileds != null && fileds.length > 0 ){
for( Field field : fileds ){
wo = getFieldStructure( new Wo(), field );
if( wo != null && StringUtils.isNotEmpty( wo.getFieldName() ) ) {
wo.setEntityName( containerEntity );
if (fileds != null && fileds.length > 0) {
for (Field field : fileds) {
wo = getFieldStructure(new Wo(), field);
if (wo != null && StringUtils.isNotEmpty(wo.getFieldName())) {
wo.setEntityName(containerEntity);
result = cls_annotation_table_method_name.invoke(annotation_table);
wo.setTableName( result.toString() );
wos.add( wo );
wo.setTableName(result.toString());
wos.add(wo);
}
}
}
}
} catch (ClassNotFoundException | NoSuchMethodException e) {
logger.info("无法解析实体类" + containerEntity + ",请检查类依赖情况。" );
logger.info("无法解析实体类" + containerEntity + ",请检查类依赖情况。");
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
......@@ -117,11 +119,13 @@ class ActionGetAllTableFields extends BaseAction {
return wos;
}
private Wo getFieldStructure( Wo wo, Field field) {
private Wo getFieldStructure(Wo wo, Field field) {
Object result = null;
try {
Class cls_annotation_field_column = Class.forName("javax.persistence.Column");
Class cls_annotation_field_describe = Class.forName("com.x.base.core.project.annotation.FieldDescribe");
Class cls_annotation_field_column = Thread.currentThread().getContextClassLoader()
.loadClass("javax.persistence.Column");
Class cls_annotation_field_describe = Thread.currentThread().getContextClassLoader()
.loadClass("com.x.base.core.project.annotation.FieldDescribe");
Method cls_annotation_field_method_name = cls_annotation_field_describe.getMethod("value");
Method cls_annotation_field_column_legnth = cls_annotation_field_column.getMethod("length");
Method cls_annotation_field_column_name = cls_annotation_field_column.getMethod("name");
......@@ -129,18 +133,18 @@ class ActionGetAllTableFields extends BaseAction {
Annotation annotation_field_column = field.getAnnotation(cls_annotation_field_column);
Annotation annotation_field_describe = null;
if (annotation_field_column != null) {//说明有@Column这个注解,是一个列,开始
if (annotation_field_column != null) {// 说明有@Column这个注解,是一个列,开始
annotation_field_describe = field.getAnnotation(cls_annotation_field_describe);
if (annotation_field_describe != null) {
result = cls_annotation_field_method_name.invoke(annotation_field_describe);
if (result != null) {
wo.setDescription( result.toString() );
wo.setFieldType( field.getType().getSimpleName() );
wo.setDescription(result.toString());
wo.setFieldType(field.getType().getSimpleName());
}
result = cls_annotation_field_column_legnth.invoke(annotation_field_column);
if (result != null) {
wo.setFieldLength( result.toString() );
wo.setFieldLength(result.toString());
}
result = cls_annotation_field_column_name.invoke(annotation_field_column);
......@@ -229,4 +233,3 @@ class ActionGetAllTableFields extends BaseAction {
}
}
......@@ -26,18 +26,18 @@ class ActionGetAllTableStructure extends BaseAction {
*/
private List<String> analyzedEntityNames = new ArrayList<>();
ActionResult<List<Wo>> execute( EffectivePerson effectivePerson, HttpServletRequest request ) throws Exception {
ActionResult<List<Wo>> execute(EffectivePerson effectivePerson, HttpServletRequest request) throws Exception {
ActionResult<List<Wo>> result = new ActionResult<>();
List<Wo> wos = new ArrayList<>();
List<Wo> wos_newTables = null;
Wo wo = null;
//遍历所有的模块
for( String className : OFFICIAL_MODULE_SORTED_TEMPLATE ){
wos_newTables = getDataStructure( className );
wos.addAll( wos_newTables );
// 遍历所有的模块
for (String className : OFFICIAL_MODULE_SORTED_TEMPLATE) {
wos_newTables = getDataStructure(className);
wos.addAll(wos_newTables);
}
result.setData( wos );
result.setData(wos);
return result;
}
......@@ -45,23 +45,24 @@ class ActionGetAllTableStructure extends BaseAction {
List<Wo> wos = new ArrayList<>();
Wo wo = null;
try {
Class cls = Class.forName( className );
Class cls_annotation_moudle = Class.forName( "com.x.base.core.project.annotation.Module" );
Class cls = Thread.currentThread().getContextClassLoader().loadClass(className);
Class cls_annotation_moudle = Thread.currentThread().getContextClassLoader()
.loadClass("com.x.base.core.project.annotation.Module");
Method method_containerEntities = cls_annotation_moudle.getMethod("containerEntities");
Annotation annotation = cls.getAnnotation(cls_annotation_moudle);
Object result = null;
if( annotation != null ){
if (annotation != null) {
result = method_containerEntities.invoke(annotation);
if( result != null ){
String[] containerEntities = (String[])result;
if( containerEntities != null && containerEntities.length > 0 ){
for( String containerEntity : containerEntities ){
if( !analyzedEntityNames.contains( containerEntity ) ){
wo = getTableStructure( containerEntity );
if( wo != null ){
wos.add( wo );
analyzedEntityNames.add( containerEntity );
if (result != null) {
String[] containerEntities = (String[]) result;
if (containerEntities != null && containerEntities.length > 0) {
for (String containerEntity : containerEntities) {
if (!analyzedEntityNames.contains(containerEntity)) {
wo = getTableStructure(containerEntity);
if (wo != null) {
wos.add(wo);
analyzedEntityNames.add(containerEntity);
}
}
}
......@@ -78,36 +79,37 @@ class ActionGetAllTableStructure extends BaseAction {
return wos;
}
private Wo getTableStructure( String containerEntity ) {
private Wo getTableStructure(String containerEntity) {
Wo woTable = null;
List<WoField> woFields = new ArrayList<>();
try {
Class cls_entity = Class.forName( containerEntity );
Class cls_annotation_table = Class.forName( "javax.persistence.Table" );
Class cls_entity = Thread.currentThread().getContextClassLoader().loadClass(containerEntity);
Class cls_annotation_table = Thread.currentThread().getContextClassLoader()
.loadClass("javax.persistence.Table");
Method cls_annotation_table_method_name = cls_annotation_table.getMethod("name");
Annotation annotation_table = cls_entity.getAnnotation(cls_annotation_table);
Object result = null;
if( annotation_table != null ){
if (annotation_table != null) {
woTable = new Wo();
woTable.setEntityName( containerEntity );
woTable.setEntityName(containerEntity);
result = cls_annotation_table_method_name.invoke(annotation_table);
woTable.setTableName( result.toString() );
woTable.setTableName(result.toString());
//遍历所有的有@Column的属性
// 遍历所有的有@Column的属性
Field[] fileds = cls_entity.getDeclaredFields();
if( fileds != null && fileds.length > 0 ){
for( Field field : fileds ){
WoField wofield = getFieldStructure( field );
if( wofield != null ) {
woFields.add( wofield );
if (fileds != null && fileds.length > 0) {
for (Field field : fileds) {
WoField wofield = getFieldStructure(field);
if (wofield != null) {
woFields.add(wofield);
}
}
}
woTable.setFields( woFields );
woTable.setFields(woFields);
}
} catch (ClassNotFoundException | NoSuchMethodException e) {
logger.info("无法解析实体类" + containerEntity + ",请检查类依赖情况。" );
logger.info("无法解析实体类" + containerEntity + ",请检查类依赖情况。");
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
......@@ -121,8 +123,10 @@ class ActionGetAllTableStructure extends BaseAction {
WoField woField = null;
Object result = null;
try {
Class cls_annotation_field_column = Class.forName("javax.persistence.Column");
Class cls_annotation_field_describe = Class.forName("com.x.base.core.project.annotation.FieldDescribe");
Class cls_annotation_field_column = Thread.currentThread().getContextClassLoader()
.loadClass("javax.persistence.Column");
Class cls_annotation_field_describe = Thread.currentThread().getContextClassLoader()
.loadClass("com.x.base.core.project.annotation.FieldDescribe");
Method cls_annotation_field_method_name = cls_annotation_field_describe.getMethod("value");
Method cls_annotation_field_column_legnth = cls_annotation_field_column.getMethod("length");
Method cls_annotation_field_column_name = cls_annotation_field_column.getMethod("name");
......@@ -130,19 +134,19 @@ class ActionGetAllTableStructure extends BaseAction {
Annotation annotation_field_column = field.getAnnotation(cls_annotation_field_column);
Annotation annotation_field_describe = null;
if (annotation_field_column != null) {//说明有@Column这个注解,是一个列,开始
if (annotation_field_column != null) {// 说明有@Column这个注解,是一个列,开始
annotation_field_describe = field.getAnnotation(cls_annotation_field_describe);
if (annotation_field_describe != null) {
woField = new WoField();
result = cls_annotation_field_method_name.invoke(annotation_field_describe);
if (result != null) {
woField.setDescription( result.toString() );
woField.setFieldType( field.getType().getSimpleName() );
woField.setDescription(result.toString());
woField.setFieldType(field.getType().getSimpleName());
}
result = cls_annotation_field_column_legnth.invoke(annotation_field_column);
if (result != null) {
woField.setFieldLength( result.toString() );
woField.setFieldLength(result.toString());
}
result = cls_annotation_field_column_name.invoke(annotation_field_column);
......@@ -244,4 +248,3 @@ class ActionGetAllTableStructure extends BaseAction {
}
}
}
......@@ -190,7 +190,7 @@ public class DingTalkEncryptor {
Class clazz = null;
try {
clazz = Class.forName(className);
clazz = Thread.currentThread().getContextClassLoader().loadClass(className);
} catch (Exception var3) {
var3.printStackTrace();
}
......
......@@ -170,15 +170,15 @@ abstract class BaseAction extends StandardJaxrsAction {
@SuppressWarnings("unchecked")
private synchronized List<Class<?>> listAssemble() throws Exception {
if (null == assembles) {
try (ScanResult scanResult = new ClassGraph()
.addClassLoader(ClassLoaderTools.urlClassLoader(true, false, false, false, false))
try (ScanResult scanResult = new ClassGraph().addClassLoader(
ClassLoaderTools.urlClassLoader(ClassLoader.getSystemClassLoader(), false, false, false, false))
.enableAnnotationInfo().scan()) {
assembles = new CopyOnWriteArrayList<Class<?>>();
List<ClassInfo> list = new ArrayList<>();
list.addAll(scanResult.getClassesWithAnnotation(Module.class.getName()));
list = list.stream().sorted(Comparator.comparing(ClassInfo::getName)).collect(Collectors.toList());
for (ClassInfo info : list) {
Class<?> cls = Class.forName(info.getName());
Class<?> cls = Thread.currentThread().getContextClassLoader().loadClass(info.getName());
Module module = cls.getAnnotation(Module.class);
if (Objects.equal(module.type(), ModuleType.ASSEMBLE)) {
assembles.add(cls);
......
package com.x.query.assemble.designer;
import java.net.URL;
import java.net.URLClassLoader;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import org.eclipse.jetty.webapp.WebAppClassLoader;
import com.x.base.core.project.Context;
/**
* web应用初始化
*
* @author sword
*/
@WebListener
public class ApplicationServletContextListener implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent servletContextEvent) {
try {
ThisApplication.context = Context.concrete(servletContextEvent);
ThisApplication.setContext(Context.concrete(servletContextEvent, Business.getDynamicEntityClassLoader()));
ThisApplication.init();
ThisApplication.context().regist();
} catch (Exception e) {
......@@ -30,4 +40,4 @@ public class ApplicationServletContextListener implements ServletContextListener
}
}
}
\ No newline at end of file
}
package com.x.query.assemble.designer;
import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.EnumSet;
......@@ -19,10 +23,14 @@ import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.io.filefilter.DirectoryFileFilter;
import org.apache.commons.io.filefilter.FileFilterUtils;
import org.apache.commons.io.filefilter.IOFileFilter;
import org.apache.commons.io.filefilter.WildcardFileFilter;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.SystemUtils;
import com.x.base.core.container.EntityManagerContainer;
import com.x.base.core.container.factory.EntityManagerContainerFactory;
import com.x.base.core.container.factory.PersistenceXmlHelper;
import com.x.base.core.entity.dynamic.DynamicEntity;
import com.x.base.core.entity.dynamic.DynamicEntityBuilder;
......@@ -56,13 +64,34 @@ import com.x.query.core.entity.schema.Table;
*/
public class Business {
private static Logger logger = LoggerFactory.getLogger(Business.class);
private static final Logger LOGGER = LoggerFactory.getLogger(Business.class);
private static ClassLoader dynamicEntityClassLoader = null;
public static ClassLoader getDynamicEntityClassLoader() throws IOException, URISyntaxException {
if (null == dynamicEntityClassLoader) {
refreshDynamicEntityClassLoader();
}
return dynamicEntityClassLoader;
}
public static synchronized void refreshDynamicEntityClassLoader() throws IOException, URISyntaxException {
List<URL> urlList = new ArrayList<>();
IOFileFilter filter = new WildcardFileFilter(DynamicEntity.JAR_PREFIX + "*.jar");
for (File o : FileUtils.listFiles(Config.dir_dynamic_jars(true), filter, null)) {
urlList.add(o.toURI().toURL());
}
URL[] urls = new URL[urlList.size()];
dynamicEntityClassLoader = URLClassLoader.newInstance(urlList.toArray(urls),
null != ThisApplication.context() ? ThisApplication.context().servletContext().getClassLoader()
: Thread.currentThread().getContextClassLoader());
}
public static final String DOT_JAR = ".jar";
private EntityManagerContainer emc;
public Business(EntityManagerContainer emc) throws Exception {
public Business(EntityManagerContainer emc) {
this.emc = emc;
}
......@@ -70,9 +99,17 @@ public class Business {
return this.emc;
}
/**
* 获取包含自定义jar包的ClassLoader
*
* @param refresh
* @return
* @throws Exception
*/
private Organization organization;
public Organization organization() throws Exception {
public Organization organization() {
if (null == this.organization) {
this.organization = new Organization(ThisApplication.context());
}
......@@ -153,7 +190,7 @@ public class Business {
public boolean controllable(EffectivePerson effectivePerson) throws Exception {
boolean result = false;
if (effectivePerson.isManager() || (this.organization().person().hasRole(effectivePerson,
if (effectivePerson.isManager() || BooleanUtils.isTrue(this.organization().person().hasRole(effectivePerson,
OrganizationDefinition.Manager, OrganizationDefinition.QueryManager))) {
result = true;
}
......@@ -162,7 +199,7 @@ public class Business {
public boolean editable(EffectivePerson effectivePerson, Query o) throws Exception {
boolean result = false;
if (effectivePerson.isManager() || (this.organization().person().hasRole(effectivePerson,
if (effectivePerson.isManager() || BooleanUtils.isTrue(this.organization().person().hasRole(effectivePerson,
OrganizationDefinition.Manager, OrganizationDefinition.QueryManager))) {
result = true;
}
......@@ -175,72 +212,54 @@ public class Business {
}
public boolean editable(EffectivePerson effectivePerson, Table o) throws Exception {
boolean result = false;
if (effectivePerson.isManager() || (this.organization().person().hasRole(effectivePerson,
if (effectivePerson.isManager() || BooleanUtils.isTrue(this.organization().person().hasRole(effectivePerson,
OrganizationDefinition.Manager, OrganizationDefinition.QueryManager))) {
result = true;
return true;
}
if (!result && (null != o)) {
if (null != o) {
if (ListTools.isEmpty(o.getEditPersonList()) && ListTools.isEmpty(o.getEditUnitList())) {
result = true;
if (!result) {
if (effectivePerson.isPerson(o.getEditPersonList())) {
result = true;
}
if (!result && ListTools.isNotEmpty(o.getEditUnitList())) {
List<String> units = this.organization().unit()
.listWithPerson(effectivePerson.getDistinguishedName());
if (ListTools.containsAny(units, o.getEditUnitList())) {
result = true;
}
}
}
return true;
}
}
return result;
}
public boolean executable(EffectivePerson effectivePerson, Statement o) throws Exception {
boolean result = false;
if (null != o) {
if (ListTools.isEmpty(o.getExecutePersonList()) && ListTools.isEmpty(o.getExecuteUnitList())) {
result = true;
if (ListTools.isNotEmpty(o.getEditPersonList()) && effectivePerson.isPerson(o.getEditPersonList())) {
return true;
}
if (!result) {
if (effectivePerson.isManager()
|| (this.organization().person().hasRole(effectivePerson, OrganizationDefinition.Manager,
OrganizationDefinition.QueryManager))
|| effectivePerson.isPerson(o.getExecutePersonList())) {
result = true;
}
if ((!result) && ListTools.isNotEmpty(o.getExecuteUnitList())) {
List<String> units = this.organization().unit()
.listWithPerson(effectivePerson.getDistinguishedName());
if (ListTools.containsAny(units, o.getExecuteUnitList())) {
result = true;
}
if (ListTools.isNotEmpty(o.getEditUnitList())) {
List<String> units = this.organization().unit().listWithPerson(effectivePerson.getDistinguishedName());
if (ListTools.containsAny(units, o.getEditUnitList())) {
return true;
}
}
}
return result;
return false;
}
public boolean buildAllTable() throws Exception {
File jar = new File(Config.dir_dynamic_jars(true), DynamicEntity.JAR_NAME + DOT_JAR);
List<Query> queryList = emc.fetchAll(Query.class);
for(Query query : queryList){
this.buildAllTable(query.getId());
public boolean executable(EffectivePerson effectivePerson, Statement o) throws Exception {
if (null == o) {
return false;
}
if (ListTools.isEmpty(o.getExecutePersonList()) && ListTools.isEmpty(o.getExecuteUnitList())) {
return true;
}
if(jar.exists()){
jar.delete();
if (effectivePerson.isManager()
|| BooleanUtils.isTrue(this.organization().person().hasRole(effectivePerson,
OrganizationDefinition.Manager, OrganizationDefinition.QueryManager))
|| effectivePerson.isPerson(o.getExecutePersonList())) {
return true;
}
return true;
if (ListTools.isNotEmpty(o.getExecuteUnitList())) {
List<String> units = this.organization().unit().listWithPerson(effectivePerson.getDistinguishedName());
if (ListTools.containsAny(units, o.getExecuteUnitList())) {
return true;
}
}
return false;
}
public boolean buildAllTable(String query) throws Exception {
public boolean buildQuery(String query) throws Exception {
boolean result = false;
List<Table> tables = emc.listEqualAndEqual(Table.class, Table.status_FIELDNAME, Table.STATUS_build, Table.query_FIELDNAME, query);
if(ListTools.isEmpty(tables)){
List<Table> tables = emc.listEqualAndEqual(Table.class, Table.status_FIELDNAME, Table.STATUS_build,
Table.query_FIELDNAME, query);
if (ListTools.isEmpty(tables)) {
return true;
}
File dir = new File(Config.dir_local_temp_dynamic(true), StringTools.uniqueToken());
......@@ -265,13 +284,12 @@ public class Business {
t.setBuildSuccess(true);
emc.commit();
} catch (Exception e) {
logger.error(e);
LOGGER.error(e);
}
}
if (!classNames.isEmpty()) {
PersistenceXmlHelper.directWrite(new File(resources, "META-INF/persistence.xml").getAbsolutePath(),
classNames);
PersistenceXmlHelper.directWriteDynamicEnhance(
new File(resources, "META-INF/persistence.xml").getAbsolutePath(), classNames);
List<File> classPath = new ArrayList<>();
classPath.addAll(FileUtils.listFiles(Config.dir_commons_ext().toFile(),
FileFilterUtils.suffixFileFilter(DOT_JAR), DirectoryFileFilter.INSTANCE));
......@@ -289,10 +307,10 @@ public class Business {
Iterable<JavaFileObject> res = fileManager.list(StandardLocation.SOURCE_PATH, DynamicEntity.CLASS_PACKAGE,
EnumSet.of(JavaFileObject.Kind.SOURCE), true);
DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<>();
StringWriter out = new StringWriter();
if (!compiler.getTask(out, fileManager, diagnostics, null, null, res).call()) {
if (BooleanUtils.isFalse(compiler.getTask(out, fileManager, diagnostics, null, null, res).call())) {
for (Diagnostic<? extends JavaFileObject> diagnostic : diagnostics.getDiagnostics()) {
out.append("Error on line " + diagnostic.getLineNumber() + " in " + diagnostic).append('\n');
}
......@@ -305,6 +323,8 @@ public class Business {
File jar = new File(Config.dir_dynamic_jars(true), DynamicEntity.JAR_PREFIX + query + DOT_JAR);
JarTools.jar(target, jar);
LOGGER.info("build table reload jar:{}", jar.getName());
this.reloadClassLoader();
}
FileUtils.cleanDirectory(dir);
return result;
......@@ -323,7 +343,7 @@ public class Business {
+ StringUtils.join(paths, File.pathSeparator) + "\" " + Enhance.class.getName() + " \""
+ target.getAbsolutePath() + "\"";
logger.debug("enhance command:{}.", command);
LOGGER.info("enhance command:{}.", () -> command);
ProcessBuilder processBuilder = new ProcessBuilder();
......@@ -333,13 +353,24 @@ public class Business {
processBuilder.command("sh", "-c", command);
}
Process process = processBuilder.start();
Process p = processBuilder.start();
String resp = IOUtils.toString(process.getErrorStream(), DefaultCharset.charset_utf_8);
String resp = IOUtils.toString(p.getErrorStream(), DefaultCharset.charset_utf_8);
process.destroy();
p.destroy();
logger.info("enhance result:{}.", resp);
LOGGER.info("enhance result:{}.", () -> resp);
}
private void reloadClassLoader() {
try {
EntityManagerContainerFactory.close();
Business.refreshDynamicEntityClassLoader();
ThisApplication.context().initDatas(Business.getDynamicEntityClassLoader());
} catch (Exception e) {
LOGGER.error(e);
}
}
}
......@@ -5,6 +5,8 @@ import com.x.base.core.project.gson.GsonPropertyObject;
public class CompareQuery extends GsonPropertyObject {
private static final long serialVersionUID = 675001251642041128L;
@FieldDescribe("导入名称")
private String name;
......
......@@ -15,6 +15,10 @@ public class ThisApplication {
return context;
}
protected static void setContext(Context context) {
ThisApplication.context = context;
}
public static void init() {
try {
CacheManager.init(context.clazz().getSimpleName());
......
......@@ -27,7 +27,8 @@ import com.x.query.core.entity.schema.Statement;
import com.x.query.core.entity.schema.Table;
class ActionGetEntityProperties extends BaseAction {
ActionResult<List<Wo>> execute(EffectivePerson effectivePerson, String entity, String entityCategory) throws Exception {
ActionResult<List<Wo>> execute(EffectivePerson effectivePerson, String entity, String entityCategory)
throws Exception {
try (EntityManagerContainer emc = EntityManagerContainerFactory.instance().create()) {
ActionResult<List<Wo>> result = new ActionResult<>();
Business business = new Business(emc);
......@@ -35,12 +36,12 @@ class ActionGetEntityProperties extends BaseAction {
throw new ExceptionAccessDenied(effectivePerson);
}
Class<? extends JpaObject> cls = this.clazz(business, entity, entityCategory);
result.setData(this.getEntityDes(cls,true,false));
result.setData(this.getEntityDes(cls, true, false));
return result;
}
}
private <T extends JpaObject> List<Wo> getEntityDes(Class<T> clz, Boolean excludeInvisible, Boolean excludeLob){
private <T extends JpaObject> List<Wo> getEntityDes(Class<T> clz, Boolean excludeInvisible, Boolean excludeLob) {
List<Wo> wos = new ArrayList<>();
Wo wo = null;
for (Field field : FieldUtils.getFieldsListWithAnnotation(clz, Column.class)) {
......@@ -52,7 +53,8 @@ class ActionGetEntityProperties extends BaseAction {
continue;
} else {
Strategy strategy = field.getAnnotation(Strategy.class);
if ((null != strategy) && StringUtils.equals(JpaObject.JsonPropertiesValueHandler, strategy.value())) {
if ((null != strategy)
&& StringUtils.equals(JpaObject.JsonPropertiesValueHandler, strategy.value())) {
continue;
}
}
......@@ -61,7 +63,7 @@ class ActionGetEntityProperties extends BaseAction {
wo.setName(field.getName());
wo.setType(field.getType().getSimpleName());
FieldDescribe fd = field.getAnnotation(FieldDescribe.class);
if(fd!=null){
if (fd != null) {
wo.setDescription(fd.value());
}
wos.add(wo);
......@@ -69,12 +71,13 @@ class ActionGetEntityProperties extends BaseAction {
return wos;
}
@SuppressWarnings("unchecked")
private Class<? extends JpaObject> clazz(Business business, String entity, String entityCategory) throws Exception {
Class<? extends JpaObject> cls = null;
if (StringUtils.equals(Statement.ENTITYCATEGORY_OFFICIAL, entityCategory)
|| StringUtils.equals(Statement.ENTITYCATEGORY_CUSTOM, entityCategory)) {
try {
cls = (Class<? extends JpaObject>) Class.forName(entity);
cls = (Class<? extends JpaObject>) Thread.currentThread().getContextClassLoader().loadClass(entity);
} catch (Exception e) {
throw new ExceptionEntityNotExist(entity, entityCategory);
}
......@@ -85,7 +88,8 @@ class ActionGetEntityProperties extends BaseAction {
}
DynamicEntity dynamicEntity = new DynamicEntity(table.getName());
try {
cls = (Class<? extends JpaObject>) Class.forName(dynamicEntity.className());
cls = (Class<? extends JpaObject>) Thread.currentThread().getContextClassLoader()
.loadClass(dynamicEntity.className());
} catch (Exception e) {
throw new ExceptionEntityNotExist(entity, entityCategory);
}
......
......@@ -44,8 +44,8 @@ class ActionCreate extends BaseAction {
}
statement.setTable(table.getId());
} else {
try {
Class.forName(statement.getEntityClassName());
try {
Thread.currentThread().getContextClassLoader().loadClass(statement.getEntityClassName());
} catch (Exception e) {
throw new ExceptionEntityClass(statement.getEntityClassName());
}
......
......@@ -58,7 +58,7 @@ class ActionEdit extends BaseAction {
statement.setTable(table.getId());
} else {
try {
Class.forName(statement.getEntityClassName());
Thread.currentThread().getContextClassLoader().loadClass(statement.getEntityClassName());
} catch (Exception e) {
throw new ExceptionEntityClass(statement.getEntityClassName());
}
......
......@@ -141,14 +141,16 @@ class ActionExecute extends BaseAction {
Class<? extends JpaObject> cls = null;
if (StringUtils.equals(Statement.ENTITYCATEGORY_OFFICIAL, statement.getEntityCategory())
|| StringUtils.equals(Statement.ENTITYCATEGORY_CUSTOM, statement.getEntityCategory())) {
cls = (Class<? extends JpaObject>) Class.forName(statement.getEntityClassName());
cls = (Class<? extends JpaObject>) Thread.currentThread().getContextClassLoader()
.loadClass(statement.getEntityClassName());
} else {
Table table = business.entityManagerContainer().flag(statement.getTable(), Table.class);
if (null == table) {
throw new ExceptionEntityNotExist(statement.getTable(), Table.class);
}
DynamicEntity dynamicEntity = new DynamicEntity(table.getName());
cls = (Class<? extends JpaObject>) Class.forName(dynamicEntity.className());
cls = (Class<? extends JpaObject>) Thread.currentThread().getContextClassLoader()
.loadClass(dynamicEntity.className());
}
return cls;
}
......
......@@ -175,10 +175,10 @@ class ActionExecuteV2 extends BaseAction {
LOGGER.debug("jpql:{}.", jpql);
if (upJpql.indexOf(JOIN_KEY) > -1 && upJpql.indexOf(JOIN_ON_KEY) > -1) {
query = em.createNativeQuery(jpql);
if(runtime.getParameters().size() > 0){
if (runtime.getParameters().size() > 0) {
List<Object> values = new ArrayList<>(runtime.getParameters().values());
for(int i=0;i<values.size();i++){
query.setParameter(i+1, values.get(i));
for (int i = 0; i < values.size(); i++) {
query.setParameter(i + 1, values.get(i));
}
}
} else {
......@@ -221,14 +221,16 @@ class ActionExecuteV2 extends BaseAction {
Class<? extends JpaObject> cls = null;
if (StringUtils.equals(Statement.ENTITYCATEGORY_OFFICIAL, statement.getEntityCategory())
|| StringUtils.equals(Statement.ENTITYCATEGORY_CUSTOM, statement.getEntityCategory())) {
cls = (Class<? extends JpaObject>) Class.forName(statement.getEntityClassName());
cls = (Class<? extends JpaObject>) Thread.currentThread().getContextClassLoader()
.loadClass(statement.getEntityClassName());
} else {
Table table = business.entityManagerContainer().flag(statement.getTable(), Table.class);
if (null == table) {
throw new ExceptionEntityNotExist(statement.getTable(), Table.class);
}
DynamicEntity dynamicEntity = new DynamicEntity(table.getName());
cls = (Class<? extends JpaObject>) Class.forName(dynamicEntity.className());
cls = (Class<? extends JpaObject>) Thread.currentThread().getContextClassLoader()
.loadClass(dynamicEntity.className());
}
return cls;
}
......
package com.x.query.assemble.designer.jaxrs.table;
import java.util.Date;
import java.util.List;
import com.x.base.core.container.EntityManagerContainer;
import com.x.base.core.container.factory.EntityManagerContainerFactory;
import com.x.base.core.project.Application;
import com.x.base.core.project.x_query_assemble_designer;
import com.x.base.core.project.connection.CipherConnectionAction;
import com.x.base.core.project.exception.ExceptionAccessDenied;
import com.x.base.core.project.http.ActionResult;
import com.x.base.core.project.http.EffectivePerson;
import com.x.base.core.project.jaxrs.WrapBoolean;
import com.x.base.core.project.logger.Logger;
import com.x.base.core.project.logger.LoggerFactory;
import com.x.base.core.project.tools.ListTools;
import com.x.query.assemble.designer.Business;
import com.x.query.assemble.designer.ThisApplication;
class ActionBuildAll extends BaseAction {
private static Logger logger = LoggerFactory.getLogger(ActionBuildAll.class);
ActionResult<Wo> execute(EffectivePerson effectivePerson) throws Exception {
try (EntityManagerContainer emc = EntityManagerContainerFactory.instance().create()) {
ActionResult<Wo> result = new ActionResult<>();
Wo wo = new Wo();
Business business = new Business(emc);
if (!business.controllable(effectivePerson)) {
throw new ExceptionAccessDenied(effectivePerson);
}
List<Application> apps = ThisApplication.context().applications().get(x_query_assemble_designer.class);
if (ListTools.isNotEmpty(apps)) {
apps.stream().forEach(o -> {
String url = o.getUrlJaxrsRoot() + "table/build?tt="+System.currentTimeMillis();
logger.print("{} do dispatch build table request to : {}", effectivePerson.getDistinguishedName(), url);
try {
CipherConnectionAction.get(effectivePerson.getDebugger(), url);
} catch (Exception e) {
e.printStackTrace();
}
});
}
wo.setValue(true);
result.setData(wo);
return result;
}
}
public static class Wo extends WrapBoolean {
}
}
package com.x.query.assemble.designer.jaxrs.table;
import java.io.File;
import java.nio.file.Files;
import java.util.List;
import com.x.base.core.container.EntityManagerContainer;
import com.x.base.core.container.factory.EntityManagerContainerFactory;
import com.x.base.core.entity.dynamic.DynamicEntity;
......@@ -13,16 +17,13 @@ import com.x.base.core.project.logger.Logger;
import com.x.base.core.project.logger.LoggerFactory;
import com.x.query.assemble.designer.Business;
import com.x.query.core.entity.Query;
import com.x.query.core.entity.schema.Table;
import java.io.File;
import java.util.List;
class ActionBuildTable extends BaseAction {
class ActionBuildQuery extends BaseAction {
private static Logger logger = LoggerFactory.getLogger(ActionBuildTable.class);
private static final Logger LOGGER = LoggerFactory.getLogger(ActionBuildQuery.class);
ActionResult<Wo> execute(EffectivePerson effectivePerson, String queryId) throws Exception {
LOGGER.debug("execute:{}.", effectivePerson::getDistinguishedName);
try (EntityManagerContainer emc = EntityManagerContainerFactory.instance().create()) {
ActionResult<Wo> result = new ActionResult<>();
Wo wo = new Wo();
......@@ -34,18 +35,19 @@ class ActionBuildTable extends BaseAction {
if (null == curQuery) {
throw new ExceptionEntityNotExist(queryId, Query.class);
}
// 兼容老版本的jar,删除统一的一个jar
File jar = new File(Config.dir_dynamic_jars(true), DynamicEntity.JAR_NAME + Business.DOT_JAR);
if(jar.exists()){
if (jar.exists()) {
List<Query> queryList = emc.fetchAll(Query.class);
for(Query query : queryList){
business.buildAllTable(query.getId());
for (Query query : queryList) {
business.buildQuery(query.getId());
}
jar.delete();
Files.delete(jar.toPath());
wo.setValue(true);
}else {
wo.setValue(business.buildAllTable(queryId));
} else {
wo.setValue(business.buildQuery(queryId));
}
logger.info("build query {} table complete!", queryId);
LOGGER.info("build query {} table complete!", queryId);
result.setData(wo);
return result;
......@@ -54,6 +56,8 @@ class ActionBuildTable extends BaseAction {
public static class Wo extends WrapBoolean {
private static final long serialVersionUID = 4060403776149004018L;
}
}
package com.x.query.assemble.designer.jaxrs.table;
import java.util.List;
import com.x.base.core.container.EntityManagerContainer;
import com.x.base.core.container.factory.EntityManagerContainerFactory;
import com.x.base.core.project.Application;
import com.x.base.core.project.x_query_assemble_designer;
import com.x.base.core.project.x_query_assemble_surface;
import com.x.base.core.project.connection.CipherConnectionAction;
import com.x.base.core.project.exception.ExceptionAccessDenied;
import com.x.base.core.project.exception.ExceptionEntityNotExist;
......@@ -12,19 +16,16 @@ import com.x.base.core.project.jaxrs.WrapBoolean;
import com.x.base.core.project.logger.Logger;
import com.x.base.core.project.logger.LoggerFactory;
import com.x.base.core.project.tools.ListTools;
import com.x.base.core.project.x_query_assemble_designer;
import com.x.query.assemble.designer.Business;
import com.x.query.assemble.designer.ThisApplication;
import com.x.query.core.entity.Query;
import com.x.query.core.entity.schema.Table;
import java.util.List;
class ActionBuildQueryDispatch extends BaseAction {
class ActionBuildTableDispatch extends BaseAction {
private static Logger logger = LoggerFactory.getLogger(ActionBuildTableDispatch.class);
private static final Logger LOGGER = LoggerFactory.getLogger(ActionBuildQueryDispatch.class);
ActionResult<Wo> execute(EffectivePerson effectivePerson, String queryId) throws Exception {
LOGGER.debug("execute:{}.", effectivePerson::getDistinguishedName);
ActionResult<Wo> result = new ActionResult<>();
Wo wo = new Wo();
try (EntityManagerContainer emc = EntityManagerContainerFactory.instance().create()) {
......@@ -40,8 +41,10 @@ class ActionBuildTableDispatch extends BaseAction {
List<Application> apps = ThisApplication.context().applications().get(x_query_assemble_designer.class);
if (ListTools.isNotEmpty(apps)) {
apps.stream().forEach(o -> {
String url = o.getUrlJaxrsRoot() + "table/"+ queryId +"/build?tt="+System.currentTimeMillis();
logger.info("{} do dispatch build query {} table request to : {}", effectivePerson.getDistinguishedName(), queryId, url);
String url = o.getUrlJaxrsRoot() + "table/" + queryId + "/build?timestamp="
+ System.currentTimeMillis();
LOGGER.info("{} do dispatch build query {} table request to : {}.",
effectivePerson.getDistinguishedName(), queryId, url);
try {
CipherConnectionAction.get(effectivePerson.getDebugger(), url);
} catch (Exception e) {
......@@ -49,6 +52,7 @@ class ActionBuildTableDispatch extends BaseAction {
}
});
}
refreshSurface();
wo.setValue(true);
result.setData(wo);
......@@ -56,8 +60,24 @@ class ActionBuildTableDispatch extends BaseAction {
return result;
}
private void refreshSurface() throws Exception {
List<Application> apps = ThisApplication.context().applications().get(x_query_assemble_surface.class);
if (ListTools.isNotEmpty(apps)) {
apps.stream().forEach(o -> {
String url = o.getUrlJaxrsRoot() + "table/reload/classloader";
try {
CipherConnectionAction.get(false, url);
} catch (Exception e) {
e.printStackTrace();
}
});
}
}
public static class Wo extends WrapBoolean {
private static final long serialVersionUID = -7885741023719404711L;
}
}
......@@ -22,6 +22,8 @@ import com.x.base.core.project.gson.XGsonBuilder;
import com.x.base.core.project.http.ActionResult;
import com.x.base.core.project.http.EffectivePerson;
import com.x.base.core.project.jaxrs.WoId;
import com.x.base.core.project.logger.Logger;
import com.x.base.core.project.logger.LoggerFactory;
import com.x.base.core.project.tools.ListTools;
import com.x.query.assemble.designer.Business;
import com.x.query.core.entity.Query;
......@@ -29,7 +31,10 @@ import com.x.query.core.entity.schema.Table;
class ActionCreate extends BaseAction {
private static final Logger LOGGER = LoggerFactory.getLogger(ActionCreate.class);
ActionResult<Wo> execute(EffectivePerson effectivePerson, JsonElement jsonElement) throws Exception {
LOGGER.debug("execute:{}.", effectivePerson::getDistinguishedName);
try (EntityManagerContainer emc = EntityManagerContainerFactory.instance().create()) {
ActionResult<Wo> result = new ActionResult<>();
Business business = new Business(emc);
......@@ -80,6 +85,8 @@ class ActionCreate extends BaseAction {
public static class Wo extends WoId {
private static final long serialVersionUID = -8218197923183204124L;
}
public static class Wi extends Table {
......
......@@ -10,12 +10,18 @@ import com.x.base.core.project.exception.ExceptionEntityNotExist;
import com.x.base.core.project.http.ActionResult;
import com.x.base.core.project.http.EffectivePerson;
import com.x.base.core.project.jaxrs.WoId;
import com.x.base.core.project.logger.Logger;
import com.x.base.core.project.logger.LoggerFactory;
import com.x.query.assemble.designer.Business;
import com.x.query.core.entity.schema.Statement;
import com.x.query.core.entity.schema.Table;
class ActionDelete extends BaseAction {
private static final Logger LOGGER = LoggerFactory.getLogger(ActionDelete.class);
ActionResult<Wo> execute(EffectivePerson effectivePerson, String flag) throws Exception {
LOGGER.debug("execute:{}.", effectivePerson::getDistinguishedName);
try (EntityManagerContainer emc = EntityManagerContainerFactory.instance().create()) {
ActionResult<Wo> result = new ActionResult<>();
Business business = new Business(emc);
......@@ -46,5 +52,7 @@ class ActionDelete extends BaseAction {
public static class Wo extends WoId {
private static final long serialVersionUID = 5408521814879545848L;
}
}
\ No newline at end of file
......@@ -19,13 +19,19 @@ import com.x.base.core.project.gson.XGsonBuilder;
import com.x.base.core.project.http.ActionResult;
import com.x.base.core.project.http.EffectivePerson;
import com.x.base.core.project.jaxrs.WoId;
import com.x.base.core.project.logger.Logger;
import com.x.base.core.project.logger.LoggerFactory;
import com.x.base.core.project.tools.ListTools;
import com.x.query.assemble.designer.Business;
import com.x.query.core.entity.schema.Statement;
import com.x.query.core.entity.schema.Table;
class ActionEdit extends BaseAction {
private static final Logger LOGGER = LoggerFactory.getLogger(ActionEdit.class);
ActionResult<Wo> execute(EffectivePerson effectivePerson, String flag, JsonElement jsonElement) throws Exception {
LOGGER.debug("execute:{}.", effectivePerson::getDistinguishedName);
try (EntityManagerContainer emc = EntityManagerContainerFactory.instance().create()) {
ActionResult<Wo> result = new ActionResult<>();
Business business = new Business(emc);
......@@ -41,9 +47,6 @@ class ActionEdit extends BaseAction {
DynamicEntity dynamicEntity = XGsonBuilder.instance().fromJson(wi.getDraftData(), DynamicEntity.class);
DynamicEntity existDynamicEntity = XGsonBuilder.instance().fromJson(table.getDraftData(),
DynamicEntity.class);
if (ListTools.isEmpty(dynamicEntity.getFieldList())) {
throw new ExceptionFieldEmpty();
}
......@@ -58,9 +61,9 @@ class ActionEdit extends BaseAction {
emc.beginTransaction(Table.class);
table.setLastUpdatePerson(effectivePerson.getDistinguishedName());
table.setLastUpdateTime(new Date());
if(Table.STATUS_build.equals(table.getStatus())){
if (Table.STATUS_build.equals(table.getStatus())) {
table.setData(table.getDraftData());
}else{
} else {
table.setData("");
table.setAlias(wi.getAlias());
table.setName(wi.getName());
......@@ -78,6 +81,8 @@ class ActionEdit extends BaseAction {
public static class Wo extends WoId {
private static final long serialVersionUID = 580689168809784572L;
}
public static class Wi extends Table {
......
package com.x.query.assemble.designer.jaxrs.table;
import java.util.Date;
import com.google.gson.JsonElement;
import com.x.base.core.container.EntityManagerContainer;
import com.x.base.core.container.factory.EntityManagerContainerFactory;
......@@ -12,16 +14,20 @@ import com.x.base.core.project.exception.ExceptionEntityNotExist;
import com.x.base.core.project.http.ActionResult;
import com.x.base.core.project.http.EffectivePerson;
import com.x.base.core.project.jaxrs.WoId;
import com.x.base.core.project.logger.Logger;
import com.x.base.core.project.logger.LoggerFactory;
import com.x.base.core.project.tools.ListTools;
import com.x.query.assemble.designer.Business;
import com.x.query.core.entity.Query;
import com.x.query.core.entity.schema.Statement;
import com.x.query.core.entity.schema.Table;
import java.util.Date;
class ActionEditPermission extends BaseAction {
private static final Logger LOGGER = LoggerFactory.getLogger(ActionEditPermission.class);
ActionResult<Wo> execute(EffectivePerson effectivePerson, String flag, JsonElement jsonElement) throws Exception {
LOGGER.debug("execute:{}.", effectivePerson::getDistinguishedName);
try (EntityManagerContainer emc = EntityManagerContainerFactory.instance().create()) {
ActionResult<Wo> result = new ActionResult<>();
Business business = new Business(emc);
......@@ -57,6 +63,8 @@ class ActionEditPermission extends BaseAction {
public static class Wo extends WoId {
private static final long serialVersionUID = 2706685216257429716L;
}
public static class Wi extends Table {
......@@ -65,8 +73,8 @@ class ActionEditPermission extends BaseAction {
static WrapCopier<Wi, Table> copier = WrapCopierFactory.wi(Wi.class, Table.class,
ListTools.toList(Table.readPersonList_FIELDNAME, Table.readUnitList_FIELDNAME,
Table.readGroupList_FIELDNAME, Table.editPersonList_FIELDNAME,
Table.editUnitList_FIELDNAME, Table.editGroupList_FIELDNAME),
Table.readGroupList_FIELDNAME, Table.editPersonList_FIELDNAME, Table.editUnitList_FIELDNAME,
Table.editGroupList_FIELDNAME),
null);
}
}
......@@ -16,15 +16,22 @@ import com.x.base.core.project.exception.ExceptionEntityNotExist;
import com.x.base.core.project.gson.GsonPropertyObject;
import com.x.base.core.project.http.ActionResult;
import com.x.base.core.project.http.EffectivePerson;
import com.x.base.core.project.logger.Logger;
import com.x.base.core.project.logger.LoggerFactory;
import com.x.query.assemble.designer.Business;
import com.x.query.core.entity.schema.Statement;
import com.x.query.core.entity.schema.Table;
class ActionExecute extends BaseAction {
private static final Logger LOGGER = LoggerFactory.getLogger(ActionExecute.class);
ActionResult<Object> execute(EffectivePerson effectivePerson, String flag, JsonElement jsonElement)
throws Exception {
LOGGER.debug("execute:{}.", effectivePerson::getDistinguishedName);
ClassLoader classLoader = Business.getDynamicEntityClassLoader();
Thread.currentThread().setContextClassLoader(classLoader);
Thread.currentThread().setContextClassLoader(Business.getDynamicEntityClassLoader());
try (EntityManagerContainer emc = EntityManagerContainerFactory.instance().create()) {
ActionResult<Object> result = new ActionResult<>();
Business business = new Business(emc);
......@@ -36,8 +43,7 @@ class ActionExecute extends BaseAction {
this.check(effectivePerson, business, table);
DynamicEntity dynamicEntity = new DynamicEntity(table.getName());
@SuppressWarnings("unchecked")
Class<? extends JpaObject> cls = (Class<JpaObject>) Class.forName(dynamicEntity.className());
Class<? extends JpaObject> cls = (Class<JpaObject>) classLoader.loadClass(dynamicEntity.className());
Object data = null;
if (StringUtils.equalsIgnoreCase(wi.getType(), Statement.TYPE_SELECT)) {
EntityManager em = emc.get(DynamicBaseEntity.class);
......@@ -49,9 +55,9 @@ class ActionExecute extends BaseAction {
query.setFirstResult(wi.getFirstResult());
}
data = query.getResultList();
if(StringUtils.isNotBlank(wi.getCountData())){
if (StringUtils.isNotBlank(wi.getCountData())) {
query = em.createQuery(wi.getCountData());
result.setCount((Long)query.getSingleResult());
result.setCount((Long) query.getSingleResult());
}
} else {
EntityManager em = emc.get(cls);
......@@ -67,6 +73,8 @@ class ActionExecute extends BaseAction {
public static class Wi extends GsonPropertyObject {
private static final long serialVersionUID = -6511081486196917840L;
@FieldDescribe("类型")
private String type;
......
......@@ -8,11 +8,17 @@ import com.x.base.core.project.bean.WrapCopierFactory;
import com.x.base.core.project.exception.ExceptionEntityNotExist;
import com.x.base.core.project.http.ActionResult;
import com.x.base.core.project.http.EffectivePerson;
import com.x.base.core.project.logger.Logger;
import com.x.base.core.project.logger.LoggerFactory;
import com.x.query.assemble.designer.Business;
import com.x.query.core.entity.schema.Table;
class ActionGet extends BaseAction {
private static final Logger LOGGER = LoggerFactory.getLogger(ActionGet.class);
ActionResult<Wo> execute(EffectivePerson effectivePerson, String flag) throws Exception {
LOGGER.debug("execute:{}.", effectivePerson::getDistinguishedName);
try (EntityManagerContainer emc = EntityManagerContainerFactory.instance().create()) {
ActionResult<Wo> result = new ActionResult<>();
Business business = new Business(emc);
......
......@@ -25,14 +25,16 @@ import com.x.query.core.entity.schema.Table;
class ActionListRowNext extends BaseAction {
private static Logger logger = LoggerFactory.getLogger(ActionListRowNext.class);
private static final Logger LOGGER = LoggerFactory.getLogger(ActionListRowNext.class);
ActionResult<List<JsonObject>> execute(EffectivePerson effectivePerson, String tableFlag, String id, Integer count)
throws Exception {
LOGGER.debug("execute:{}.", effectivePerson::getDistinguishedName);
ClassLoader classLoader = Business.getDynamicEntityClassLoader();
Thread.currentThread().setContextClassLoader(classLoader);
try (EntityManagerContainer emc = EntityManagerContainerFactory.instance().create()) {
ActionResult<List<JsonObject>> result = new ActionResult<>();
logger.debug(effectivePerson, "table:{}, id:{}, count:{}.", tableFlag, id, count);
LOGGER.debug("table:{}, id:{}, count:{}.", () -> tableFlag, () -> id, () -> count);
Business business = new Business(emc);
Table table = emc.flag(tableFlag, Table.class);
if (null == table) {
......@@ -40,7 +42,9 @@ class ActionListRowNext extends BaseAction {
}
this.check(effectivePerson, business, table);
DynamicEntity dynamicEntity = new DynamicEntity(table.getName());
Class<? extends JpaObject> cls = dynamicEntity.getObjectClass();
@SuppressWarnings("unchecked")
Class<? extends JpaObject> cls = (Class<? extends JpaObject>) classLoader
.loadClass(dynamicEntity.className());
EntityManager em = emc.get(cls);
Object sequence = null;
if (!StringUtils.equals(EMPTY_SYMBOL, id)) {
......@@ -66,6 +70,7 @@ class ActionListRowNext extends BaseAction {
if (null != sequence) {
q.setParameter(1, sequence);
}
@SuppressWarnings("unchecked")
List<Object[]> list = q.setMaxResults(Math.max(Math.min(count, list_max), list_min)).getResultList();
List<JsonObject> wos = new ArrayList<>();
result.setCount(emc.count(cls));
......
......@@ -26,14 +26,16 @@ import com.x.query.core.entity.schema.Table;
class ActionListRowPrev extends BaseAction {
private static Logger logger = LoggerFactory.getLogger(ActionListRowPrev.class);
private static final Logger LOGGER = LoggerFactory.getLogger(ActionListRowPrev.class);
ActionResult<List<JsonObject>> execute(EffectivePerson effectivePerson, String tableFlag, String id, Integer count)
throws Exception {
LOGGER.debug("execute:{}.", effectivePerson::getDistinguishedName);
ClassLoader classLoader = Business.getDynamicEntityClassLoader();
Thread.currentThread().setContextClassLoader(classLoader);
try (EntityManagerContainer emc = EntityManagerContainerFactory.instance().create()) {
ActionResult<List<JsonObject>> result = new ActionResult<>();
logger.debug(effectivePerson, "table:{}, id:{}, count:{}.", tableFlag, id, count);
LOGGER.debug("table:{}, id:{}, count:{}.", () -> tableFlag, () -> id, () -> count);
Business business = new Business(emc);
Table table = emc.flag(tableFlag, Table.class);
if (null == table) {
......@@ -41,7 +43,9 @@ class ActionListRowPrev extends BaseAction {
}
this.check(effectivePerson, business, table);
DynamicEntity dynamicEntity = new DynamicEntity(table.getName());
Class<? extends JpaObject> cls = dynamicEntity.getObjectClass();
@SuppressWarnings("unchecked")
Class<? extends JpaObject> cls = (Class<? extends JpaObject>) classLoader
.loadClass(dynamicEntity.className());
EntityManager em = emc.get(cls);
Object sequence = null;
if (!StringUtils.equals(EMPTY_SYMBOL, id)) {
......@@ -60,30 +64,26 @@ class ActionListRowPrev extends BaseAction {
String sql = "select " + StringUtils.join(selects, ", ") + " from " + cls.getName() + " o";
Long rank = 0L;
List<JsonObject> wos = new ArrayList<>();
Query q;
if (null != sequence) {
sql += " where o." + JpaObject.sequence_FIELDNAME + " > ?1 order by o." + JpaObject.sequence_FIELDNAME
+ " ASC";
rank = emc.countGreaterThan(cls, JpaObject.sequence_FIELDNAME, sequence);
Query q = em.createQuery(sql, Object[].class);
q = em.createQuery(sql, Object[].class);
q.setParameter(1, sequence);
List<Object[]> list = q.setMaxResults(Math.max(Math.min(count, list_max), list_min)).getResultList();
for (Object[] os : list) {
JsonObject jsonObject = XGsonBuilder.instance().toJsonTree(JpaObject.cast(cls, fields, os))
.getAsJsonObject();
jsonObject.getAsJsonObject().addProperty("rank", rank--);
wos.add(jsonObject);
}
} else {
sql += " order by o." + JpaObject.sequence_FIELDNAME + " ASC";
rank = result.getCount();
Query q = em.createQuery(sql, Object[].class);
List<Object[]> list = q.setMaxResults(Math.max(Math.min(count, list_max), list_min)).getResultList();
for (Object[] os : list) {
JsonObject jsonObject = XGsonBuilder.instance().toJsonTree(JpaObject.cast(cls, fields, os))
.getAsJsonObject();
jsonObject.getAsJsonObject().addProperty("rank", rank--);
wos.add(jsonObject);
}
q = em.createQuery(sql, Object[].class);
}
@SuppressWarnings("unchecked")
List<Object[]> list = q.setMaxResults(Math.max(Math.min(count, list_max), list_min)).getResultList();
for (Object[] os : list) {
JsonObject jsonObject = XGsonBuilder.instance().toJsonTree(JpaObject.cast(cls, fields, os))
.getAsJsonObject();
jsonObject.getAsJsonObject().addProperty("rank", rank--);
wos.add(jsonObject);
}
Collections.reverse(wos);
result.setData(wos);
......
......@@ -13,12 +13,19 @@ import com.x.base.core.entity.dynamic.DynamicEntity;
import com.x.base.core.project.exception.ExceptionEntityNotExist;
import com.x.base.core.project.http.ActionResult;
import com.x.base.core.project.http.EffectivePerson;
import com.x.base.core.project.logger.Logger;
import com.x.base.core.project.logger.LoggerFactory;
import com.x.query.assemble.designer.Business;
import com.x.query.core.entity.schema.Table;
class ActionListRowSelectWhere extends BaseAction {
private static final Logger LOGGER = LoggerFactory.getLogger(ActionListRowSelectWhere.class);
ActionResult<List<?>> execute(EffectivePerson effectivePerson, String tableFlag, String where) throws Exception {
LOGGER.debug("execute:{}.", effectivePerson::getDistinguishedName);
ClassLoader classLoader = Business.getDynamicEntityClassLoader();
Thread.currentThread().setContextClassLoader(classLoader);
try (EntityManagerContainer emc = EntityManagerContainerFactory.instance().create()) {
ActionResult<List<?>> result = new ActionResult<>();
Table table = emc.flag(tableFlag, Table.class);
......@@ -29,7 +36,7 @@ class ActionListRowSelectWhere extends BaseAction {
this.check(effectivePerson, business, table);
DynamicEntity dynamicEntity = new DynamicEntity(table.getName());
@SuppressWarnings("unchecked")
Class<? extends JpaObject> clz = (Class<JpaObject>) Class.forName(dynamicEntity.className());
Class<? extends JpaObject> clz = (Class<JpaObject>) classLoader.loadClass(dynamicEntity.className());
EntityManager em = emc.get(clz);
String sql = "SELECT o FROM " + clz.getName() + " o";
if (StringUtils.isNotBlank(where) && (!StringUtils.equals(where, EMPTY_SYMBOL))) {
......
......@@ -11,14 +11,19 @@ import com.x.base.core.project.exception.ExceptionAccessDenied;
import com.x.base.core.project.exception.ExceptionEntityNotExist;
import com.x.base.core.project.http.ActionResult;
import com.x.base.core.project.http.EffectivePerson;
import com.x.base.core.project.logger.Logger;
import com.x.base.core.project.logger.LoggerFactory;
import com.x.base.core.project.tools.ListTools;
import com.x.query.assemble.designer.Business;
import com.x.query.core.entity.Query;
import com.x.query.core.entity.schema.Statement;
import com.x.query.core.entity.schema.Table;
class ActionListWithQuery extends BaseAction {
private static final Logger LOGGER = LoggerFactory.getLogger(ActionListWithQuery.class);
ActionResult<List<Wo>> execute(EffectivePerson effectivePerson, String flag) throws Exception {
LOGGER.debug("execute:{}.", effectivePerson::getDistinguishedName);
try (EntityManagerContainer emc = EntityManagerContainerFactory.instance().create()) {
ActionResult<List<Wo>> result = new ActionResult<>();
Business business = new Business(emc);
......
package com.x.query.assemble.designer.jaxrs.table;
import java.util.List;
import com.x.base.core.container.EntityManagerContainer;
import com.x.base.core.container.factory.EntityManagerContainerFactory;
import com.x.base.core.entity.JpaObject;
......@@ -8,13 +10,17 @@ import com.x.base.core.project.bean.WrapCopierFactory;
import com.x.base.core.project.exception.ExceptionAccessDenied;
import com.x.base.core.project.http.ActionResult;
import com.x.base.core.project.http.EffectivePerson;
import com.x.base.core.project.logger.Logger;
import com.x.base.core.project.logger.LoggerFactory;
import com.x.query.assemble.designer.Business;
import com.x.query.core.entity.schema.Table;
import java.util.List;
class ActionManageList extends BaseAction {
private static final Logger LOGGER = LoggerFactory.getLogger(ActionManageList.class);
ActionResult<List<Wo>> execute(EffectivePerson effectivePerson) throws Exception {
LOGGER.debug("execute:{}.", effectivePerson::getDistinguishedName);
try (EntityManagerContainer emc = EntityManagerContainerFactory.instance().create()) {
ActionResult<List<Wo>> result = new ActionResult<>();
Business business = new Business(emc);
......
......@@ -12,13 +12,19 @@ import com.x.base.core.project.exception.ExceptionEntityNotExist;
import com.x.base.core.project.http.ActionResult;
import com.x.base.core.project.http.EffectivePerson;
import com.x.base.core.project.jaxrs.WrapLong;
import com.x.base.core.project.logger.Logger;
import com.x.base.core.project.logger.LoggerFactory;
import com.x.query.assemble.designer.Business;
import com.x.query.core.entity.schema.Table;
class ActionRowCountWhere extends BaseAction {
ActionResult<Wo> execute(EffectivePerson effectivePerson, String tableFlag, String where)
throws Exception {
private static final Logger LOGGER = LoggerFactory.getLogger(ActionRowCountWhere.class);
ActionResult<Wo> execute(EffectivePerson effectivePerson, String tableFlag, String where) throws Exception {
LOGGER.debug("execute:{}.", effectivePerson::getDistinguishedName);
ClassLoader classLoader = Business.getDynamicEntityClassLoader();
Thread.currentThread().setContextClassLoader(classLoader);
try (EntityManagerContainer emc = EntityManagerContainerFactory.instance().create()) {
ActionResult<Wo> result = new ActionResult<>();
Table table = emc.flag(tableFlag, Table.class);
......@@ -29,7 +35,7 @@ class ActionRowCountWhere extends BaseAction {
this.check(effectivePerson, business, table);
DynamicEntity dynamicEntity = new DynamicEntity(table.getName());
@SuppressWarnings("unchecked")
Class<? extends JpaObject> cls = (Class<JpaObject>) Class.forName(dynamicEntity.className());
Class<? extends JpaObject> cls = (Class<JpaObject>) classLoader.loadClass(dynamicEntity.className());
EntityManager em = emc.get(cls);
String sql = "SELECT count(o) FROM " + cls.getName() + " o";
if (StringUtils.isNotBlank(where) && (!StringUtils.equals(where, EMPTY_SYMBOL))) {
......@@ -45,6 +51,8 @@ class ActionRowCountWhere extends BaseAction {
public static class Wo extends WrapLong {
private static final long serialVersionUID = 7879265956595981220L;
}
}
\ No newline at end of file
......@@ -8,11 +8,19 @@ import com.x.base.core.project.exception.ExceptionEntityNotExist;
import com.x.base.core.project.http.ActionResult;
import com.x.base.core.project.http.EffectivePerson;
import com.x.base.core.project.jaxrs.WrapBoolean;
import com.x.base.core.project.logger.Logger;
import com.x.base.core.project.logger.LoggerFactory;
import com.x.query.assemble.designer.Business;
import com.x.query.core.entity.schema.Table;
class ActionRowDelete extends BaseAction {
private static final Logger LOGGER = LoggerFactory.getLogger(ActionRowDelete.class);
ActionResult<Wo> execute(EffectivePerson effectivePerson, String tableFlag, String id) throws Exception {
LOGGER.debug("execute:{}.", effectivePerson::getDistinguishedName);
ClassLoader classLoader = Business.getDynamicEntityClassLoader();
Thread.currentThread().setContextClassLoader(classLoader);
try (EntityManagerContainer emc = EntityManagerContainerFactory.instance().create()) {
ActionResult<Wo> result = new ActionResult<>();
Table table = emc.flag(tableFlag, Table.class);
......@@ -23,7 +31,7 @@ class ActionRowDelete extends BaseAction {
this.check(effectivePerson, business, table);
DynamicEntity dynamicEntity = new DynamicEntity(table.getName());
@SuppressWarnings("unchecked")
Class<? extends JpaObject> cls = (Class<JpaObject>) Class.forName(dynamicEntity.className());
Class<? extends JpaObject> cls = (Class<JpaObject>) classLoader.loadClass(dynamicEntity.className());
JpaObject o = emc.find(id, cls);
Wo wo = new Wo();
wo.setValue(false);
......@@ -40,6 +48,8 @@ class ActionRowDelete extends BaseAction {
public static class Wo extends WrapBoolean {
private static final long serialVersionUID = -6967852502783946854L;
}
}
\ No newline at end of file
......@@ -16,11 +16,19 @@ import com.x.base.core.project.exception.ExceptionEntityNotExist;
import com.x.base.core.project.http.ActionResult;
import com.x.base.core.project.http.EffectivePerson;
import com.x.base.core.project.jaxrs.WrapLong;
import com.x.base.core.project.logger.Logger;
import com.x.base.core.project.logger.LoggerFactory;
import com.x.query.assemble.designer.Business;
import com.x.query.core.entity.schema.Table;
class ActionRowDeleteAll extends BaseAction {
private static final Logger LOGGER = LoggerFactory.getLogger(ActionRowDeleteAll.class);
ActionResult<Wo> execute(EffectivePerson effectivePerson, String tableFlag) throws Exception {
LOGGER.debug("execute:{}.", effectivePerson::getDistinguishedName);
ClassLoader classLoader = Business.getDynamicEntityClassLoader();
Thread.currentThread().setContextClassLoader(classLoader);
try (EntityManagerContainer emc = EntityManagerContainerFactory.instance().create()) {
ActionResult<Wo> result = new ActionResult<>();
Table table = emc.flag(tableFlag, Table.class);
......@@ -31,7 +39,7 @@ class ActionRowDeleteAll extends BaseAction {
this.check(effectivePerson, business, table);
DynamicEntity dynamicEntity = new DynamicEntity(table.getName());
@SuppressWarnings("unchecked")
Class<? extends JpaObject> cls = (Class<JpaObject>) Class.forName(dynamicEntity.className());
Class<? extends JpaObject> cls = (Class<JpaObject>) classLoader.loadClass(dynamicEntity.className());
List<String> ids = null;
Long count = 0L;
......@@ -55,9 +63,7 @@ class ActionRowDeleteAll extends BaseAction {
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<String> cq = cb.createQuery(String.class);
Root<T> root = cq.from(cls);
List<String> os = em.createQuery(cq.select(root.get(JpaObject.id_FIELDNAME))).setMaxResults(2000)
.getResultList();
return os;
return em.createQuery(cq.select(root.get(JpaObject.id_FIELDNAME))).setMaxResults(2000).getResultList();
}
private <T extends JpaObject> Integer delete(Business business, Class<T> cls, List<String> ids) throws Exception {
......@@ -69,6 +75,8 @@ class ActionRowDeleteAll extends BaseAction {
public static class Wo extends WrapLong {
private static final long serialVersionUID = -3697198277884949479L;
}
}
\ No newline at end of file
......@@ -18,13 +18,21 @@ import com.x.base.core.project.http.ActionResult;
import com.x.base.core.project.http.EffectivePerson;
import com.x.base.core.project.jaxrs.WrapIdList;
import com.x.base.core.project.jaxrs.WrapLong;
import com.x.base.core.project.logger.Logger;
import com.x.base.core.project.logger.LoggerFactory;
import com.x.base.core.project.tools.ListTools;
import com.x.query.assemble.designer.Business;
import com.x.query.core.entity.schema.Table;
class ActionRowDeleteBatch extends BaseAction {
private static final Logger LOGGER = LoggerFactory.getLogger(ActionRowDeleteBatch.class);
ActionResult<Wo> execute(EffectivePerson effectivePerson, String tableFlag, JsonElement jsonElement)
throws Exception {
LOGGER.debug("execute:{}.", effectivePerson::getDistinguishedName);
ClassLoader classLoader = Business.getDynamicEntityClassLoader();
Thread.currentThread().setContextClassLoader(classLoader);
try (EntityManagerContainer emc = EntityManagerContainerFactory.instance().create()) {
ActionResult<Wo> result = new ActionResult<>();
Table table = emc.flag(tableFlag, Table.class);
......@@ -35,7 +43,7 @@ class ActionRowDeleteBatch extends BaseAction {
this.check(effectivePerson, business, table);
DynamicEntity dynamicEntity = new DynamicEntity(table.getName());
@SuppressWarnings("unchecked")
Class<? extends JpaObject> cls = (Class<JpaObject>) Class.forName(dynamicEntity.className());
Class<? extends JpaObject> cls = (Class<JpaObject>) classLoader.loadClass(dynamicEntity.className());
Wi wi = this.convertToWrapIn(jsonElement, Wi.class);
Long count = 0L;
if (ListTools.isNotEmpty(wi.getIdList())) {
......@@ -64,10 +72,14 @@ class ActionRowDeleteBatch extends BaseAction {
public static class Wi extends WrapIdList {
private static final long serialVersionUID = -1952375433576535017L;
}
public static class Wo extends WrapLong {
private static final long serialVersionUID = -3916502854502067334L;
}
}
\ No newline at end of file
......@@ -19,14 +19,14 @@ import com.x.query.core.entity.schema.Table;
class ActionRowExport extends BaseAction {
private static Logger logger = LoggerFactory.getLogger(ActionRowExport.class);
private static final Logger LOGGER = LoggerFactory.getLogger(ActionRowExport.class);
ActionResult<Wo> execute(EffectivePerson effectivePerson, String tableFlag, Integer count)
throws Exception {
ActionResult<Wo> execute(EffectivePerson effectivePerson, String tableFlag, Integer count) throws Exception {
LOGGER.debug("table:{}, count:{}.", () -> tableFlag, () -> count);
ClassLoader classLoader = Business.getDynamicEntityClassLoader();
Thread.currentThread().setContextClassLoader(classLoader);
try (EntityManagerContainer emc = EntityManagerContainerFactory.instance().create()) {
ActionResult<Wo> result = new ActionResult<>();
logger.debug(effectivePerson, "table:{}, id:{}, count:{}.", tableFlag, count);
Business business = new Business(emc);
Table table = emc.flag(tableFlag, Table.class);
if (null == table) {
......@@ -34,13 +34,15 @@ class ActionRowExport extends BaseAction {
}
this.check(effectivePerson, business, table);
DynamicEntity dynamicEntity = new DynamicEntity(table.getName());
Class<? extends JpaObject> cls = dynamicEntity.getObjectClass();
@SuppressWarnings("unchecked")
Class<? extends JpaObject> cls = (Class<JpaObject>) classLoader.loadClass(dynamicEntity.className());
EntityManager em = emc.get(cls);
String sql = "select o from " + cls.getName() + " o";
Query query = em.createQuery(sql);
Object data = query.setMaxResults(Math.min(count, 2000)).getResultList();
Wo wo = new Wo(gson.toJson(data).getBytes(DefaultCharset.charset), this.contentType(true, table.getName() +".json"),
this.contentDisposition(true, table.getName() +".json"));
Wo wo = new Wo(gson.toJson(data).getBytes(DefaultCharset.charset),
this.contentType(true, table.getName() + ".json"),
this.contentDisposition(true, table.getName() + ".json"));
result.setData(wo);
return result;
}
......@@ -48,6 +50,8 @@ class ActionRowExport extends BaseAction {
public static class Wo extends WoFile {
private static final long serialVersionUID = 3739863790195069870L;
public Wo(byte[] bytes, String contentType, String contentDisposition) {
super(bytes, contentType, contentDisposition);
}
......
......@@ -7,11 +7,19 @@ import com.x.base.core.entity.dynamic.DynamicEntity;
import com.x.base.core.project.exception.ExceptionEntityNotExist;
import com.x.base.core.project.http.ActionResult;
import com.x.base.core.project.http.EffectivePerson;
import com.x.base.core.project.logger.Logger;
import com.x.base.core.project.logger.LoggerFactory;
import com.x.query.assemble.designer.Business;
import com.x.query.core.entity.schema.Table;
class ActionRowGet extends BaseAction {
private static final Logger LOGGER = LoggerFactory.getLogger(ActionRowGet.class);
ActionResult<Object> execute(EffectivePerson effectivePerson, String tableFlag, String id) throws Exception {
LOGGER.debug("execute:{}.", effectivePerson::getDistinguishedName);
ClassLoader classLoader = Business.getDynamicEntityClassLoader();
Thread.currentThread().setContextClassLoader(classLoader);
try (EntityManagerContainer emc = EntityManagerContainerFactory.instance().create()) {
ActionResult<Object> result = new ActionResult<>();
Table table = emc.flag(tableFlag, Table.class);
......@@ -22,7 +30,7 @@ class ActionRowGet extends BaseAction {
this.check(effectivePerson, business, table);
DynamicEntity dynamicEntity = new DynamicEntity(table.getName());
@SuppressWarnings("unchecked")
Class<? extends JpaObject> cls = (Class<JpaObject>) Class.forName(dynamicEntity.className());
Class<? extends JpaObject> cls = (Class<JpaObject>) classLoader.loadClass(dynamicEntity.className());
JpaObject o = emc.find(id, cls);
result.setData(o);
return result;
......
......@@ -13,12 +13,20 @@ import com.x.base.core.project.exception.ExceptionEntityNotExist;
import com.x.base.core.project.http.ActionResult;
import com.x.base.core.project.http.EffectivePerson;
import com.x.base.core.project.jaxrs.WrapStringList;
import com.x.base.core.project.logger.Logger;
import com.x.base.core.project.logger.LoggerFactory;
import com.x.query.assemble.designer.Business;
import com.x.query.core.entity.schema.Table;
class ActionRowInsert extends BaseAction {
private static final Logger LOGGER = LoggerFactory.getLogger(ActionRowInsert.class);
ActionResult<Wo> execute(EffectivePerson effectivePerson, String tableFlag, JsonElement jsonElement)
throws Exception {
LOGGER.debug("execute:{}.", effectivePerson::getDistinguishedName);
ClassLoader classLoader = Business.getDynamicEntityClassLoader();
Thread.currentThread().setContextClassLoader(classLoader);
try (EntityManagerContainer emc = EntityManagerContainerFactory.instance().create()) {
ActionResult<Wo> result = new ActionResult<>();
Table table = emc.flag(tableFlag, Table.class);
......@@ -29,13 +37,12 @@ class ActionRowInsert extends BaseAction {
this.check(effectivePerson, business, table);
DynamicEntity dynamicEntity = new DynamicEntity(table.getName());
@SuppressWarnings("unchecked")
Class<? extends JpaObject> cls = (Class<JpaObject>) Class.forName(dynamicEntity.className());
Class<? extends JpaObject> cls = (Class<? extends JpaObject>) classLoader
.loadClass(dynamicEntity.className());
List<Object> os = new ArrayList<>();
if (jsonElement.isJsonArray()) {
jsonElement.getAsJsonArray().forEach(o -> {
os.add(gson.fromJson(o, cls));
});
jsonElement.getAsJsonArray().forEach(o -> os.add(gson.fromJson(o, cls)));
} else if (jsonElement.isJsonObject()) {
os.add(gson.fromJson(jsonElement, cls));
}
......@@ -46,7 +53,7 @@ class ActionRowInsert extends BaseAction {
emc.commit();
Wo wo = new Wo();
for (Object o : os) {
wo.addValue(((JpaObject)o).getId(), true);
wo.addValue(((JpaObject) o).getId(), true);
}
result.setData(wo);
return result;
......@@ -55,6 +62,8 @@ class ActionRowInsert extends BaseAction {
public static class Wo extends WrapStringList {
private static final long serialVersionUID = 8695439000472972753L;
}
}
\ No newline at end of file
......@@ -20,10 +20,13 @@ import com.x.query.core.entity.schema.Table;
class ActionRowSave extends BaseAction {
private static Logger logger = LoggerFactory.getLogger(ActionRowSave.class);
private static final Logger LOGGER = LoggerFactory.getLogger(ActionRowSave.class);
ActionResult<Wo> execute(EffectivePerson effectivePerson, String tableFlag, JsonElement jsonElement)
throws Exception {
LOGGER.debug("execute:{}.", effectivePerson::getDistinguishedName);
ClassLoader classLoader = Business.getDynamicEntityClassLoader();
Thread.currentThread().setContextClassLoader(classLoader);
try (EntityManagerContainer emc = EntityManagerContainerFactory.instance().create()) {
ActionResult<Wo> result = new ActionResult<>();
Table table = emc.flag(tableFlag, Table.class);
......@@ -34,7 +37,7 @@ class ActionRowSave extends BaseAction {
this.check(effectivePerson, business, table);
DynamicEntity dynamicEntity = new DynamicEntity(table.getName());
@SuppressWarnings("unchecked")
Class<? extends JpaObject> cls = (Class<JpaObject>) Class.forName(dynamicEntity.className());
Class<? extends JpaObject> cls = (Class<JpaObject>) classLoader.loadClass(dynamicEntity.className());
List<Object> os = new ArrayList<>();
if (jsonElement.isJsonArray()) {
jsonElement.getAsJsonArray().forEach(o -> {
......@@ -78,6 +81,8 @@ class ActionRowSave extends BaseAction {
public static class Wo extends WrapStringList {
private static final long serialVersionUID = 6370333126842440871L;
}
}
\ No newline at end of file
......@@ -11,12 +11,20 @@ import com.x.base.core.project.gson.XGsonBuilder;
import com.x.base.core.project.http.ActionResult;
import com.x.base.core.project.http.EffectivePerson;
import com.x.base.core.project.jaxrs.WrapBoolean;
import com.x.base.core.project.logger.Logger;
import com.x.base.core.project.logger.LoggerFactory;
import com.x.query.assemble.designer.Business;
import com.x.query.core.entity.schema.Table;
class ActionRowUpdate extends BaseAction {
private static final Logger LOGGER = LoggerFactory.getLogger(ActionRowUpdate.class);
ActionResult<Wo> execute(EffectivePerson effectivePerson, String tableFlag, String id, JsonElement jsonElement)
throws Exception {
LOGGER.debug("execute:{}.", effectivePerson::getDistinguishedName);
ClassLoader classLoader = Business.getDynamicEntityClassLoader();
Thread.currentThread().setContextClassLoader(classLoader);
try (EntityManagerContainer emc = EntityManagerContainerFactory.instance().create()) {
ActionResult<Wo> result = new ActionResult<>();
Table table = emc.flag(tableFlag, Table.class);
......@@ -27,7 +35,7 @@ class ActionRowUpdate extends BaseAction {
this.check(effectivePerson, business, table);
DynamicEntity dynamicEntity = new DynamicEntity(table.getName());
@SuppressWarnings("unchecked")
Class<? extends JpaObject> cls = (Class<JpaObject>) Class.forName(dynamicEntity.className());
Class<? extends JpaObject> cls = (Class<JpaObject>) classLoader.loadClass(dynamicEntity.className());
JpaObject o = emc.find(id, cls);
Wo wo = new Wo();
wo.setValue(false);
......@@ -46,6 +54,8 @@ class ActionRowUpdate extends BaseAction {
public static class Wo extends WrapBoolean {
private static final long serialVersionUID = -1182404750937701550L;
}
}
\ No newline at end of file
......@@ -10,12 +10,18 @@ import com.x.base.core.project.exception.ExceptionEntityNotExist;
import com.x.base.core.project.http.ActionResult;
import com.x.base.core.project.http.EffectivePerson;
import com.x.base.core.project.jaxrs.WoId;
import com.x.base.core.project.logger.Logger;
import com.x.base.core.project.logger.LoggerFactory;
import com.x.query.assemble.designer.Business;
import com.x.query.core.entity.schema.Statement;
import com.x.query.core.entity.schema.Table;
class ActionStatusBuild extends BaseAction {
private static final Logger LOGGER = LoggerFactory.getLogger(ActionStatusBuild.class);
ActionResult<Wo> execute(EffectivePerson effectivePerson, String flag) throws Exception {
LOGGER.debug("execute:{}.", effectivePerson::getDistinguishedName);
try (EntityManagerContainer emc = EntityManagerContainerFactory.instance().create()) {
ActionResult<Wo> result = new ActionResult<>();
Table table = emc.flag(flag, Table.class);
......@@ -42,5 +48,7 @@ class ActionStatusBuild extends BaseAction {
public static class Wo extends WoId {
private static final long serialVersionUID = 301191937947918554L;
}
}
\ No newline at end of file
......@@ -7,12 +7,18 @@ import com.x.base.core.project.exception.ExceptionEntityNotExist;
import com.x.base.core.project.http.ActionResult;
import com.x.base.core.project.http.EffectivePerson;
import com.x.base.core.project.jaxrs.WoId;
import com.x.base.core.project.logger.Logger;
import com.x.base.core.project.logger.LoggerFactory;
import com.x.query.assemble.designer.Business;
import com.x.query.core.entity.schema.Statement;
import com.x.query.core.entity.schema.Table;
class ActionStatusDraft extends BaseAction {
private static final Logger LOGGER = LoggerFactory.getLogger(ActionStatusDraft.class);
ActionResult<Wo> execute(EffectivePerson effectivePerson, String flag) throws Exception {
LOGGER.debug("execute:{}.", effectivePerson::getDistinguishedName);
try (EntityManagerContainer emc = EntityManagerContainerFactory.instance().create()) {
ActionResult<Wo> result = new ActionResult<>();
Table table = emc.flag(flag, Table.class);
......@@ -35,5 +41,7 @@ class ActionStatusDraft extends BaseAction {
public static class Wo extends WoId {
private static final long serialVersionUID = 3787520133855908412L;
}
}
\ No newline at end of file
......@@ -20,4 +20,4 @@ abstract class BaseAction extends StandardJaxrsAction {
}
}
}
}
\ No newline at end of file
......@@ -53,51 +53,20 @@ public class TableAction extends StandardJaxrsAction {
asyncResponse.resume(ResponseFactory.getEntityTagActionResultResponse(request, result));
}
@JaxrsMethodDescribe(value = "编译表(会编译平台所有自建表),执行后需要立即重新启动,支持集群环境.", action = ActionBuildAll.class)
@GET
@Path("build/all")
@Produces(HttpMediaType.APPLICATION_JSON_UTF_8)
@Consumes(MediaType.APPLICATION_JSON)
public synchronized void buildAll(@Suspended final AsyncResponse asyncResponse, @Context HttpServletRequest request) {
ActionResult<ActionBuildAll.Wo> result = new ActionResult<>();
EffectivePerson effectivePerson = this.effectivePerson(request);
try {
result = new ActionBuildAll().execute(effectivePerson);
} catch (Exception e) {
logger.error(e, effectivePerson, request, null);
result.error(e);
}
asyncResponse.resume(ResponseFactory.getEntityTagActionResultResponse(request, result));
}
@JaxrsMethodDescribe(value = "编译表(会编译平台所有自建表),执行后需要立即重新启动,仅对当前服务器.", action = ActionBuild.class)
@GET
@Path("build")
@Produces(HttpMediaType.APPLICATION_JSON_UTF_8)
@Consumes(MediaType.APPLICATION_JSON)
public void build(@Suspended final AsyncResponse asyncResponse, @Context HttpServletRequest request) {
ActionResult<ActionBuild.Wo> result = new ActionResult<>();
EffectivePerson effectivePerson = this.effectivePerson(request);
try {
result = new ActionBuild().execute(effectivePerson);
} catch (Exception e) {
logger.error(e, effectivePerson, request, null);
result.error(e);
}
asyncResponse.resume(ResponseFactory.getEntityTagActionResultResponse(request, result));
}
@JaxrsMethodDescribe(value = "编译指定应用所有表,执行后需要立即重新启动,支持集群环境.", action = ActionBuildTableDispatch.class)
@JaxrsMethodDescribe(value = "编译指定应用所有表,执行后需要立即重新启动,支持集群环境.", action = ActionBuildQueryDispatch.class)
@GET
@Path("{query}/build/dispatch")
@Produces(HttpMediaType.APPLICATION_JSON_UTF_8)
@Consumes(MediaType.APPLICATION_JSON)
public synchronized void buildDispatch(@Suspended final AsyncResponse asyncResponse, @Context HttpServletRequest request,
@JaxrsParameterDescribe("应用标识") @PathParam("query") String query) {
ActionResult<ActionBuildTableDispatch.Wo> result = new ActionResult<>();
public synchronized void buildDispatch(@Suspended final AsyncResponse asyncResponse,
@Context HttpServletRequest request, @JaxrsParameterDescribe("应用标识") @PathParam("query") String query) {
ActionResult<ActionBuildQueryDispatch.Wo> result = new ActionResult<>();
EffectivePerson effectivePerson = this.effectivePerson(request);
try {
result = new ActionBuildTableDispatch().execute(effectivePerson, query);
result = new ActionBuildQueryDispatch().execute(effectivePerson, query);
} catch (Exception e) {
logger.error(e, effectivePerson, request, null);
result.error(e);
......@@ -105,17 +74,17 @@ public class TableAction extends StandardJaxrsAction {
asyncResponse.resume(ResponseFactory.getEntityTagActionResultResponse(request, result));
}
@JaxrsMethodDescribe(value = "编译指定应用所有表,执行后需要立即重新启动,仅对当前服务器.", action = ActionBuildTable.class)
@JaxrsMethodDescribe(value = "编译指定应用所有表,执行后需要立即重新启动,仅对当前服务器.", action = ActionBuildQuery.class)
@GET
@Path("{query}/build")
@Produces(HttpMediaType.APPLICATION_JSON_UTF_8)
@Consumes(MediaType.APPLICATION_JSON)
public void buildTable(@Suspended final AsyncResponse asyncResponse, @Context HttpServletRequest request,
@JaxrsParameterDescribe("应用标识") @PathParam("query") String query) {
ActionResult<ActionBuildTable.Wo> result = new ActionResult<>();
public void buildQuery(@Suspended final AsyncResponse asyncResponse, @Context HttpServletRequest request,
@JaxrsParameterDescribe("应用标识") @PathParam("query") String query) {
ActionResult<ActionBuildQuery.Wo> result = new ActionResult<>();
EffectivePerson effectivePerson = this.effectivePerson(request);
try {
result = new ActionBuildTable().execute(effectivePerson, query);
result = new ActionBuildQuery().execute(effectivePerson, query);
} catch (Exception e) {
logger.error(e, effectivePerson, request, null);
result.error(e);
......@@ -218,7 +187,7 @@ public class TableAction extends StandardJaxrsAction {
@Produces(HttpMediaType.APPLICATION_JSON_UTF_8)
@Consumes(MediaType.APPLICATION_JSON)
public void updatePermission(@Suspended final AsyncResponse asyncResponse, @Context HttpServletRequest request,
@JaxrsParameterDescribe("标识") @PathParam("id") String id, JsonElement jsonElement) {
@JaxrsParameterDescribe("标识") @PathParam("id") String id, JsonElement jsonElement) {
ActionResult<ActionEditPermission.Wo> result = new ActionResult<>();
EffectivePerson effectivePerson = this.effectivePerson(request);
try {
......@@ -442,8 +411,8 @@ public class TableAction extends StandardJaxrsAction {
@Path("export/{tableFlag}/count/{count}")
@Consumes(MediaType.APPLICATION_JSON)
public void exportRow(@Suspended final AsyncResponse asyncResponse, @Context HttpServletRequest request,
@JaxrsParameterDescribe("表标识") @PathParam("tableFlag") String tableFlag,
@JaxrsParameterDescribe("数量(最大2000)") @PathParam("count") Integer count) {
@JaxrsParameterDescribe("表标识") @PathParam("tableFlag") String tableFlag,
@JaxrsParameterDescribe("数量(最大2000)") @PathParam("count") Integer count) {
ActionResult<ActionRowExport.Wo> result = new ActionResult<>();
EffectivePerson effectivePerson = this.effectivePerson(request);
try {
......@@ -455,23 +424,23 @@ public class TableAction extends StandardJaxrsAction {
asyncResponse.resume(ResponseFactory.getEntityTagActionResultResponse(request, result));
}
@JaxrsMethodDescribe(value = "指定表中批量保存或更新数据.", action = ActionRowSave.class)
@POST
@Path("{tableFlag}/row/save")
@Produces(HttpMediaType.APPLICATION_JSON_UTF_8)
@Consumes(MediaType.APPLICATION_JSON)
public void rowSave(@Suspended final AsyncResponse asyncResponse, @Context HttpServletRequest request,
@JaxrsParameterDescribe("表标识") @PathParam("tableFlag") String tableFlag, JsonElement jsonElement) {
ActionResult<ActionRowSave.Wo> result = new ActionResult<>();
EffectivePerson effectivePerson = this.effectivePerson(request);
try {
result = new ActionRowSave().execute(effectivePerson, tableFlag, jsonElement);
} catch (Exception e) {
logger.error(e, effectivePerson, request, jsonElement);
result.error(e);
}
asyncResponse.resume(ResponseFactory.getEntityTagActionResultResponse(request, result));
}
@JaxrsMethodDescribe(value = "指定表中批量保存或更新数据.", action = ActionRowSave.class)
@POST
@Path("{tableFlag}/row/save")
@Produces(HttpMediaType.APPLICATION_JSON_UTF_8)
@Consumes(MediaType.APPLICATION_JSON)
public void rowSave(@Suspended final AsyncResponse asyncResponse, @Context HttpServletRequest request,
@JaxrsParameterDescribe("表标识") @PathParam("tableFlag") String tableFlag, JsonElement jsonElement) {
ActionResult<ActionRowSave.Wo> result = new ActionResult<>();
EffectivePerson effectivePerson = this.effectivePerson(request);
try {
result = new ActionRowSave().execute(effectivePerson, tableFlag, jsonElement);
} catch (Exception e) {
logger.error(e, effectivePerson, request, jsonElement);
result.error(e);
}
asyncResponse.resume(ResponseFactory.getEntityTagActionResultResponse(request, result));
}
@JaxrsMethodDescribe(value = "列示所有table对象.", action = ActionManageList.class)
@GET
......
{
"filterList":[ {
"value": "",
"otherValue": "新增加的值,用于between时的第二个值",
"path": "",
"formatType": "",
"logic": "",
"comparison": ""
}],
"parameter":{}
}
\ No newline at end of file
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册