提交 fbcb3677 编写于 作者: R Ray

update To dynamic table

上级 4852bb60
......@@ -24,17 +24,18 @@ public class EntityManagerContainerFactory extends SliceEntityManagerContainerFa
if (instance != null) {
EntityManagerContainerFactory.close();
}
instance = new EntityManagerContainerFactory(webApplicationDirectory, entities, null);
instance = new EntityManagerContainerFactory(webApplicationDirectory, entities, false, null);
}
}
public static void init(String webApplicationDirectory, List<String> entities, ClassLoader classLoader)
throws Exception {
public static void init(String webApplicationDirectory, List<String> entities, boolean loadDynamicEntityClass,
ClassLoader classLoader) throws Exception {
synchronized (EntityManagerContainerFactory.class) {
if (instance != null) {
EntityManagerContainerFactory.close();
}
instance = new EntityManagerContainerFactory(webApplicationDirectory, entities, classLoader);
instance = new EntityManagerContainerFactory(webApplicationDirectory, entities, loadDynamicEntityClass,
classLoader);
}
}
......@@ -64,8 +65,8 @@ public class EntityManagerContainerFactory extends SliceEntityManagerContainerFa
}
private EntityManagerContainerFactory(String webApplicationDirectory, List<String> entities,
ClassLoader classLoader) throws Exception {
super(webApplicationDirectory, entities, false, classLoader);
boolean loadDynamicEntityClass, ClassLoader classLoader) throws Exception {
super(webApplicationDirectory, entities, false, loadDynamicEntityClass, classLoader);
}
private EntityManagerContainerFactory(String source) {
......
......@@ -156,7 +156,8 @@ public class PersistenceXmlHelper {
}
@SuppressWarnings("unchecked")
public static List<String> write(String path, List<String> entities, ClassLoader classLoader) {
public static List<String> write(String path, List<String> entities, boolean loadDynamicEntityClass,
ClassLoader classLoader) {
List<String> names = new ArrayList<>();
String name = "";
try {
......@@ -177,7 +178,7 @@ public class PersistenceXmlHelper {
unit.addElement("class").addText(o.getName());
}
}
if (null != classLoader) {
if (loadDynamicEntityClass) {
names.addAll(addDynamicClassCreateCombineUnit(persistence, cl));
}
OutputFormat format = OutputFormat.createPrettyPrint();
......@@ -221,13 +222,13 @@ public class PersistenceXmlHelper {
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);
}
}
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;
}
......
......@@ -49,9 +49,10 @@ public abstract class SliceEntityManagerContainerFactory {
@SuppressWarnings("unchecked")
protected SliceEntityManagerContainerFactory(String webApplicationDirectory, List<String> entities,
boolean sliceFeatureEnable, ClassLoader classLoader) throws Exception {
boolean sliceFeatureEnable, boolean loadDynamicEntityClass, ClassLoader classLoader) throws Exception {
File path = new File(webApplicationDirectory + "/WEB-INF/classes/" + PERSISTENCE_XML_PATH);
List<String> classNames = PersistenceXmlHelper.write(path.getAbsolutePath(), entities, classLoader);
List<String> classNames = PersistenceXmlHelper.write(path.getAbsolutePath(), entities, loadDynamicEntityClass,
classLoader);
ClassLoader cl = null == classLoader ? Thread.currentThread().getContextClassLoader() : classLoader;
Class<? extends JpaObject> clz;
for (String className : classNames) {
......@@ -77,14 +78,7 @@ public abstract class SliceEntityManagerContainerFactory {
flagMap.put(clz, Collections.unmodifiableList(flagFields));
restrictFlagMap.put(clz, Collections.unmodifiableList(restrictFlagFields));
}
boolean hasDynamicEntityClass = false;
for (String className : classNames) {
if (StringUtils.startsWith(className, DynamicEntity.CLASS_PACKAGE)) {
hasDynamicEntityClass = true;
break;
}
}
if ((null != classLoader) && hasDynamicEntityClass) {
if (loadDynamicEntityClass) {
clz = (Class<? extends JpaObject>) cl.loadClass("com.x.base.core.entity.dynamic.DynamicBaseEntity");
checkPersistFieldMap.put(clz, new HashMap<>());
checkRemoveFieldMap.put(clz, new HashMap<>());
......
......@@ -263,20 +263,31 @@ public abstract class JpaObject extends GsonPropertyObject implements Serializab
public static final String TYPE_STRING = "string";
public static final String TYPE_INTEGER = "integer";
public static final String TYPE_LONG = "long";
public static final String TYPE_FLOAT = "float";
public static final String TYPE_DOUBLE = "double";
public static final String TYPE_BOOLEAN = "boolean";
public static final String TYPE_DATE = "date";
public static final String TYPE_TIME = "time";
public static final String TYPE_DATETIME = "dateTime";
public static final String TYPE_JSONPROPERTIES = "JsonProperties";
public static final String TYPE_BYTEARRAY = "byteArray";
public static final String TYPE_STRINGLIST = "stringList";
public static final String TYPE_INTEGERLIST = "integerList";
public static final String TYPE_LONGLIST = "longList";
public static final String TYPE_FLOATLIST = "floatList";
public static final String TYPE_DOUBLELIST = "doubleList";
public static final String TYPE_DATETIMELIST = "dateTimeList";
public static final String TYPE_BOOLEANLIST = "booleanList";
public static final String TYPE_STRINGLOB = "stringLob";
public static final String TYPE_STRINGMAP = "stringMap";
public static final String TYPE_INTEGERMAP = "integerMap";
public static final String TYPE_LONGMAP = "longMap";
public static final String TYPE_FLOATMAP = "floatMap";
public static final String TYPE_DOUBLEMAP = "doubleMap";
public static final String TYPE_BOOLEANMAP = "booleanMap";
public static final String TYPE_DATETIMEMAP = "dateTimeMap";
public static final String[] ID_DISTRIBUTEFACTOR = new String[] { id_FIELDNAME, distributeFactor_FIELDNAME };
......
......@@ -6,16 +6,4 @@ public abstract class JsonProperties extends GsonPropertyObject {
private static final long serialVersionUID = -5074100033957236455L;
// public boolean equals(Object o) {
// if (null == o) {
// return false;
// }
// if (!(o instanceof JsonProperties)) {
// return false;
// } else {
// return StringUtils.equals(this.toString(), o.toString());
// }
// }
}
package com.x.base.core.entity.tools;
import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.util.Collection;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.TreeSet;
......@@ -12,12 +14,16 @@ import java.util.TreeSet;
import javax.persistence.Column;
import javax.persistence.EntityManager;
import javax.persistence.MappedSuperclass;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.criteria.Path;
import org.apache.commons.lang3.StringUtils;
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.JsonProperties;
import com.x.base.core.entity.annotation.ContainerEntity;
import com.x.base.core.project.tools.StringTools;
......@@ -140,4 +146,113 @@ public class JpaObjectTools {
return set;
}
public static String type(Field field) {
String value = singleType(field);
if (StringUtils.isNotEmpty(value)) {
return value;
}
if (Collection.class.isAssignableFrom(field.getType())) {
value = collectionType(field);
if (StringUtils.isNotEmpty(value)) {
return value;
}
}
if (Map.class.isAssignableFrom(field.getType())) {
value = mapType(field);
if (StringUtils.isNotEmpty(value)) {
return value;
}
}
return value;
}
private static String singleType(Field field) {
if (String.class.isAssignableFrom(field.getType())) {
return JpaObject.TYPE_STRING;
}
if (Integer.class.isAssignableFrom(field.getType())) {
return JpaObject.TYPE_INTEGER;
}
if (Long.class.isAssignableFrom(field.getType())) {
return JpaObject.TYPE_LONG;
}
if (Float.class.isAssignableFrom(field.getType())) {
return JpaObject.TYPE_FLOAT;
}
if (Double.class.isAssignableFrom(field.getType())) {
return JpaObject.TYPE_DOUBLE;
}
if (Boolean.class.isAssignableFrom(field.getType())) {
return JpaObject.TYPE_BOOLEAN;
}
if (JsonProperties.class.isAssignableFrom(field.getType())) {
return JpaObject.TYPE_JSONPROPERTIES;
}
if ((new byte[] {}).getClass().isAssignableFrom(field.getType())) {
return JpaObject.TYPE_BYTEARRAY;
}
if (Date.class.isAssignableFrom(field.getType())) {
Temporal temporal = field.getAnnotation(Temporal.class);
if ((null != temporal) && (Objects.equals(temporal.value(), TemporalType.DATE))) {
return JpaObject.TYPE_DATE;
}
return JpaObject.TYPE_DATETIME;
}
return null;
}
private static String collectionType(Field field) {
ParameterizedType parameterized = (ParameterizedType) field.getGenericType();
Class<?> actualClass = (Class<?>) parameterized.getActualTypeArguments()[0];
if (String.class.isAssignableFrom(actualClass)) {
return JpaObject.TYPE_STRINGLIST;
}
if (Integer.class.isAssignableFrom(actualClass)) {
return JpaObject.TYPE_INTEGERLIST;
}
if (Long.class.isAssignableFrom(actualClass)) {
return JpaObject.TYPE_LONGLIST;
}
if (Double.class.isAssignableFrom(actualClass)) {
return JpaObject.TYPE_DOUBLELIST;
}
if (Float.class.isAssignableFrom(actualClass)) {
return JpaObject.TYPE_FLOATLIST;
}
if (Date.class.isAssignableFrom(actualClass)) {
return JpaObject.TYPE_DATETIMELIST;
}
if (Boolean.class.isAssignableFrom(actualClass)) {
return JpaObject.TYPE_BOOLEANLIST;
}
return null;
}
private static String mapType(Field field) {
ParameterizedType parameterized = (ParameterizedType) field.getGenericType();
Class<?> actualClass = (Class<?>) parameterized.getActualTypeArguments()[1];
if (String.class.isAssignableFrom(actualClass)) {
return JpaObject.TYPE_STRINGMAP;
}
if (Integer.class.isAssignableFrom(actualClass)) {
return JpaObject.TYPE_INTEGERMAP;
}
if (Long.class.isAssignableFrom(actualClass)) {
return JpaObject.TYPE_LONGMAP;
}
if (Float.class.isAssignableFrom(actualClass)) {
return JpaObject.TYPE_FLOATMAP;
}
if (Double.class.isAssignableFrom(actualClass)) {
return JpaObject.TYPE_DOUBLEMAP;
}
if (Date.class.isAssignableFrom(actualClass)) {
return JpaObject.TYPE_DATETIMEMAP;
}
if (Boolean.class.isAssignableFrom(actualClass)) {
return JpaObject.TYPE_BOOLEANMAP;
}
return null;
}
}
\ No newline at end of file
......@@ -138,15 +138,14 @@ public class Context extends AbstractContext {
this.token = UUID.randomUUID().toString();
this.applications = new Applications();
this.queues = new ArrayList<>();
}
public static Context concrete(ServletContextEvent servletContextEvent) throws Exception {
return concrete(servletContextEvent, null);
return concrete(servletContextEvent, false, null);
}
public static Context concrete(ServletContextEvent servletContextEvent, ClassLoader dynamicEntityClassLoader)
throws Exception {
public static Context concrete(ServletContextEvent servletContextEvent, boolean loadDynamicEntityClass,
ClassLoader classLoader) throws Exception {
// 强制忽略ssl服务器认证
SslTools.ignoreSsl();
ServletContext servletContext = servletContextEvent.getServletContext();
......@@ -162,7 +161,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(dynamicEntityClassLoader);
context.initDatas(loadDynamicEntityClass, classLoader);
servletContext.setAttribute(AbstractContext.class.getName(), context);
SchedulerFactoryProperties schedulerFactoryProperties = SchedulerFactoryProperties.concrete();
schedulerFactoryProperties.setProperty("org.quartz.scheduler.instanceName",
......@@ -275,15 +274,16 @@ 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()), null);
EntityManagerContainerFactory.init(path, ListTools.toList(this.module.containerEntities()), false, null);
}
}
public void initDatas(ClassLoader classLoader) throws Exception {
public void initDatas(boolean loadDynamicEntityClass, 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);
EntityManagerContainerFactory.init(path, ListTools.toList(this.module.containerEntities()),
loadDynamicEntityClass, classLoader);
}
}
......
......@@ -8,14 +8,18 @@ import com.x.base.core.project.annotation.FieldDescribe;
public class Communicate extends ConfigObject {
private static final long serialVersionUID = -9032410002099116514L;
public static final Boolean DEFAULT_WSENABLE = true;
public static final Boolean DEFAULT_PMSENABLE = true;
public static final Boolean DEFAULT_CALENDARENABLE = true;
public static final Boolean DEFAULT_UPDATEQUERYTABLE = true;
public Communicate() {
this.wsEnable = DEFAULT_WSENABLE;
this.pmsEnable = DEFAULT_PMSENABLE;
this.calendarEnable = DEFAULT_CALENDARENABLE;
this.updateQueryTableEnable = DEFAULT_CALENDARENABLE;
}
public static Communicate defaultInstance() {
......@@ -31,42 +35,94 @@ public class Communicate extends ConfigObject {
@FieldDescribe("是否启用calendar消息.")
private Boolean calendarEnable;
@FieldDescribe("是否启用calendar消息.")
private Boolean updateQueryTableEnable;
public Boolean wsEnable() {
return BooleanUtils.isTrue(wsEnable);
return BooleanUtils.isTrue(this.wsEnable);
}
public Boolean pmsEnable() {
return BooleanUtils.isTrue(pmsEnable);
return BooleanUtils.isTrue(this.pmsEnable);
}
public Boolean calendarEnable() {
return BooleanUtils.isTrue(calendarEnable);
return BooleanUtils.isTrue(this.calendarEnable);
}
public Boolean updateQueryTableEnable() {
return BooleanUtils.isTrue(this.updateQueryTableEnable);
}
@FieldDescribe("定时触发发送到消息队列MQ.")
private CronMq cronMq;
public CronMq cronMq() {
return this.cronMq == null ? new CronMq() : this.cronMq;
}
@FieldDescribe("定时触发同步到数据中心自定表.")
private CronUpdateQueryTable cronUpdateQueryTable;
public CronUpdateQueryTable cronUpdateQueryTable() {
return this.cronUpdateQueryTable == null ? new CronUpdateQueryTable() : this.cronUpdateQueryTable;
}
public static class CronMq extends ConfigObject {
private static final long serialVersionUID = 1559477154694423422L;
public static CronMq defaultInstance() {
CronMq o = new CronMq();
return o;
return new CronMq();
}
public static final Boolean DEFAULT_ENABLE = false;
public static final String DEFAULT_CRON = "0 0 * * * ?"; // 每小时运行一次
@FieldDescribe("是否启用")
private Boolean enable = DEFAULT_ENABLE;
@FieldDescribe("定时cron表达式")
private String cron = DEFAULT_CRON;
public String getCron() {
if (StringUtils.isNotEmpty(this.cron) && CronExpression.isValidExpression(this.cron)) {
return this.cron;
} else {
return DEFAULT_CRON;
}
}
public Boolean getEnable() {
return BooleanUtils.isTrue(this.enable);
}
public void setCron(String cron) {
this.cron = cron;
}
public void setEnable(Boolean enable) {
this.enable = enable;
}
}
public static class CronUpdateQueryTable extends ConfigObject {
private static final long serialVersionUID = 1844626333347011848L;
public static CronUpdateQueryTable defaultInstance() {
return new CronUpdateQueryTable();
}
public final static Boolean DEFAULT_ENABLE = false;
public final static String DEFAULT_CRON = "0 0 * * * ? *"; //每小时运行一次
public static final Boolean DEFAULT_ENABLE = true;
public static final String DEFAULT_CRON = "0 0 * * * ?"; // 每小时运行一次
@FieldDescribe("是否启用")
private Boolean enable = DEFAULT_ENABLE;
@FieldDescribe("定时cron表达式")
private String cron = DEFAULT_CRON;
public String getCron() {
if (StringUtils.isNotEmpty(this.cron) && CronExpression.isValidExpression(this.cron)) {
return this.cron;
......@@ -87,7 +143,7 @@ public class Communicate extends ConfigObject {
this.enable = enable;
}
}
@FieldDescribe("清理设置.")
private Clean clean;
......@@ -99,15 +155,14 @@ public class Communicate extends ConfigObject {
private static final long serialVersionUID = 1L;
public static Clean defaultInstance() {
Clean o = new Clean();
return o;
return new Clean();
}
public final static Boolean DEFAULT_ENABLE = true;
public static final Boolean DEFAULT_ENABLE = true;
public final static Integer DEFAULT_KEEP = 7;
public static final Integer DEFAULT_KEEP = 7;
public final static String DEFAULT_CRON = "30 30 6 * * ?";
public static final String DEFAULT_CRON = "30 30 6 * * ?";
@FieldDescribe("是否启用")
private Boolean enable = DEFAULT_ENABLE;
......
......@@ -56,7 +56,7 @@ public class Components extends ConfigObject {
case NAME_ORG:
return new Component(NAME_ORG, NAME_ORG, "组织管理", APPICON_PNG, 2, Component.TYPE_SYSTEM);
case NAME_CMSMANAGER:
return new Component(NAME_CMSMANAGER, "cms.Column", "内容管理平台", APPICON_PNG, 3, Component.TYPE_SYSTEM);
return new Component(NAME_CMSMANAGER, "cms.Column", "内容管理设置", APPICON_PNG, 3, Component.TYPE_SYSTEM);
case NAME_APPLICATIONEXPLORER:
return new Component(NAME_APPLICATIONEXPLORER, "process.ApplicationExplorer", "流程管理平台", APPICON_PNG, 4,
Component.TYPE_SYSTEM);
......@@ -80,7 +80,7 @@ public class Components extends ConfigObject {
case NAME_BAM:
return new Component(NAME_BAM, NAME_BAM, "流程监控", APPICON_PNG, 12, Component.TYPE_SYSTEM);
case NAME_CMS:
return new Component(NAME_CMS, "cms.Index", "信息平台", APPICON_PNG, 12, Component.TYPE_SYSTEM);
return new Component(NAME_CMS, "cms.Index", "内容管理首页", APPICON_PNG, 12, Component.TYPE_SYSTEM);
case NAME_WORKCENTER:
return new Component(NAME_WORKCENTER, "process.workcenter", "办公中心", APPICON_PNG, 13, Component.TYPE_SYSTEM);
case NAME_HOMEPAGE:
......
......@@ -71,11 +71,7 @@ public class Messages extends ConcurrentSkipListMap<String, Message> {
MessageConnector.CONSUME_QIYEWEIXIN, MessageConnector.CONSUME_WELINK, MessageConnector.CONSUME_MQ));
// 待办转已办通知
o.put(MessageConnector.TYPE_TASK_TO_TASKCOMPLETED,
new Message(MessageConnector.CONSUME_WS, MessageConnector.CONSUME_PMS,
MessageConnector.CONSUME_DINGDING, MessageConnector.CONSUME_ZHENGWUDINGDING,
MessageConnector.CONSUME_QIYEWEIXIN, MessageConnector.CONSUME_WELINK,
MessageConnector.CONSUME_MQ));
o.put(MessageConnector.TYPE_TASK_TO_TASKCOMPLETED, new Message(MessageConnector.CONSUME_MQ));
// 待办提醒通知
o.put(MessageConnector.TYPE_TASK_PRESS, new Message(MessageConnector.CONSUME_WS, MessageConnector.CONSUME_PMS,
MessageConnector.CONSUME_DINGDING, MessageConnector.CONSUME_ZHENGWUDINGDING,
......
......@@ -201,7 +201,7 @@ public class Node extends ConfigObject {
private String path = "";
public Boolean enable() {
return (BooleanUtils.isTrue(this.enable)) ? true : false;
return BooleanUtils.isTrue(this.enable);
}
public String cron() {
......
......@@ -142,8 +142,8 @@ public class MessageConnector {
public static final String CONSUME_MPWEIXIN = "mpweixin"; // 微信公众号
public static final String CONSUME_MQ = "mq";
public static final String CONSUME_QUERY = "query";
// 同步到数据中心自定义表
public static final String CONSUME_UPDATEQUERYTABLE = "updateQueryTable";
private static Context context;
......
......@@ -16,7 +16,7 @@ import com.x.base.core.project.tools.ListTools;
import com.x.component.assemble.control.Business;
import com.x.component.core.entity.Component;
class ActionCreate extends ActionBase {
class ActionCreate extends BaseAction {
ActionResult<Wo> execute(EffectivePerson effectivePerson, JsonElement jsonElement) throws Exception {
try (EntityManagerContainer emc = EntityManagerContainerFactory.instance().create()) {
ActionResult<Wo> result = new ActionResult<>();
......
......@@ -14,7 +14,7 @@ import com.x.base.core.project.jaxrs.WrapBoolean;
import com.x.component.assemble.control.Business;
import com.x.component.core.entity.Component;
class ActionDelete extends ActionBase {
class ActionDelete extends BaseAction {
ActionResult<Wo> execute(EffectivePerson effectivePerson, String flag) throws Exception {
try (EntityManagerContainer emc = EntityManagerContainerFactory.instance().create()) {
ActionResult<Wo> result = new ActionResult<>();
......
......@@ -13,7 +13,7 @@ import com.x.base.core.project.logger.LoggerFactory;
import com.x.component.assemble.control.Business;
import com.x.component.core.entity.Component;
class ActionDeleteAll extends ActionBase {
class ActionDeleteAll extends BaseAction {
private static Logger logger = LoggerFactory.getLogger(ActionDeleteAll.class);
......
......@@ -20,7 +20,7 @@ import com.x.base.core.project.tools.ListTools;
import com.x.component.assemble.control.Business;
import com.x.component.core.entity.Component;
class ActionEdit extends ActionBase {
class ActionEdit extends BaseAction {
ActionResult<Wo> execute(EffectivePerson effectivePerson, String flag, JsonElement jsonElement) throws Exception {
try (EntityManagerContainer emc = EntityManagerContainerFactory.instance().create()) {
......
......@@ -10,7 +10,7 @@ import com.x.base.core.project.http.ActionResult;
import com.x.base.core.project.http.EffectivePerson;
import com.x.component.core.entity.Component;
class ActionGet extends ActionBase {
class ActionGet extends BaseAction {
ActionResult<Wo> execute(EffectivePerson effectivePerson, String flag) throws Exception {
try (EntityManagerContainer emc = EntityManagerContainerFactory.instance().create()) {
......
......@@ -21,7 +21,7 @@ import com.x.base.core.project.logger.LoggerFactory;
import com.x.base.core.project.tools.ListTools;
import com.x.component.core.entity.Component;
class ActionListAll extends ActionBase {
class ActionListAll extends BaseAction {
private static Logger logger = LoggerFactory.getLogger(ActionListAll.class);
......
......@@ -4,7 +4,7 @@ import com.x.base.core.project.cache.Cache.CacheCategory;
import com.x.base.core.project.jaxrs.StandardJaxrsAction;
import com.x.component.core.entity.Component;
class ActionBase extends StandardJaxrsAction {
class BaseAction extends StandardJaxrsAction {
CacheCategory cacheCategory = new CacheCategory(Component.class);
......
......@@ -91,7 +91,7 @@ public class DumpData {
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, classLoader);
PersistenceXmlHelper.write(xml.toString(), classNames, true, classLoader);
StorageMappings storageMappings = Config.storageMappings();
Stream<String> stream = BooleanUtils.isTrue(Config.dumpRestoreData().getParallel())
? classNames.parallelStream()
......
......@@ -66,7 +66,7 @@ public abstract class EraseContent {
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);
PersistenceXmlHelper.write(persistence.getAbsolutePath(), classNames, true, classLoader);
for (int i = 0; i < classNames.size(); i++) {
Class<? extends JpaObject> cls = (Class<? extends JpaObject>) Thread.currentThread()
.getContextClassLoader().loadClass(classNames.get(i));
......
......@@ -105,7 +105,7 @@ public class RestoreData {
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, classLoader);
PersistenceXmlHelper.write(xml.toString(), classNames, true, classLoader);
Stream<String> stream = BooleanUtils.isTrue(Config.dumpRestoreData().getParallel())
? classNames.parallelStream()
: classNames.stream();
......
......@@ -37,6 +37,8 @@ public class ThisApplication {
public static final MPWeixinConsumeQueue mpWeixinConsumeQueue = new MPWeixinConsumeQueue();
public static final UpdateQueryTableConsumeQueue updateQueryTableConsumeQueue = new UpdateQueryTableConsumeQueue();
public static Context context() {
return context;
}
......@@ -58,16 +60,7 @@ public class ThisApplication {
}
private static void startQueue() throws Exception {
if (BooleanUtils.isTrue(Config.communicate().wsEnable())) {
context().startQueue(wsConsumeQueue);
}
if (BooleanUtils.isTrue(Config.communicate().pmsEnable())) {
context().startQueue(pmsConsumeQueue);
}
if (BooleanUtils.isTrue(Config.communicate().calendarEnable())) {
context().startQueue(calendarConsumeQueue);
}
startCommunicateQueue();
if (BooleanUtils.isTrue(Config.qiyeweixin().getEnable())
&& BooleanUtils.isTrue(Config.qiyeweixin().getMessageEnable())) {
context().startQueue(qiyeweixinConsumeQueue);
......@@ -85,7 +78,6 @@ public class ThisApplication {
if (Config.weLink().getEnable() && Config.weLink().getMessageEnable()) {
context().startQueue(weLinkConsumeQueue);
}
if (BooleanUtils.isTrue(Config.mq().getEnable())) {
context().startQueue(mqConsumeQueue);
}
......@@ -95,6 +87,21 @@ public class ThisApplication {
}
}
private static void startCommunicateQueue() throws Exception {
if (BooleanUtils.isTrue(Config.communicate().wsEnable())) {
context().startQueue(wsConsumeQueue);
}
if (BooleanUtils.isTrue(Config.communicate().pmsEnable())) {
context().startQueue(pmsConsumeQueue);
}
if (BooleanUtils.isTrue(Config.communicate().calendarEnable())) {
context().startQueue(calendarConsumeQueue);
}
if (BooleanUtils.isTrue(Config.communicate().updateQueryTableEnable())) {
context().startQueue(updateQueryTableConsumeQueue);
}
}
public static void destroy() {
try {
CacheManager.shutdown();
......
package com.x.message.assemble.communicate;
import com.x.base.core.container.EntityManagerContainer;
import com.x.base.core.container.factory.EntityManagerContainerFactory;
import com.x.base.core.project.logger.Logger;
import com.x.base.core.project.logger.LoggerFactory;
import com.x.base.core.project.queue.AbstractQueue;
import com.x.message.core.entity.Message;
public class UpdateQueryTableConsumeQueue extends AbstractQueue<Message> {
private static final Logger LOGGER = LoggerFactory.getLogger(UpdateQueryTableConsumeQueue.class);
protected void execute(Message message) throws Exception {
if (exist(message.getId())) {
}
}
private boolean update(Message message) {
String tableName = message.getTarget();
resp = ThisApplication.context().applications().postQuery(x_query_service_processing.class,
Applications.joinQueryUri("table", "update", tableName), task.getJob());
return true;
}
private boolean exist(String id) throws Exception {
try (EntityManagerContainer emc = EntityManagerContainerFactory.instance().create()) {
Message m = emc.find(id, Message.class);
return null != m;
}
}
private void consumed(String id) throws Exception {
try (EntityManagerContainer emc = EntityManagerContainerFactory.instance().create()) {
Message m = emc.find(id, Message.class);
if (null != m) {
emc.beginTransaction(Message.class);
m.setConsumed(true);
emc.commit();
}
}
}
}
......@@ -45,16 +45,9 @@ class ActionCreate extends BaseAction {
ActionResult<Wo> result = new ActionResult<>();
Wi wi = this.convertToWrapIn(jsonElement, Wi.class);
// List<String> consumers = Config.messages().getConsumers(wi.getType());
Map<String, String> consumersV2 = Config.messages().getConsumersV2(wi.getType());
// for (String consumer : consumers) {
// if (BooleanUtils.isFalse(consumersV2.containsKey(consumer))) {
// consumersV2.put(consumer, "");
// }
// }
Instant instant = this.instant(wi, new ArrayList<>(consumersV2.keySet()));
List<Message> messages = new ArrayList<>();
assemble(wi, consumersV2, instant, messages);
List<Message> messages = assemble(wi, consumersV2, instant);
save(instant, messages);
this.sendMessage(messages);
Wo wo = new Wo();
......@@ -77,8 +70,8 @@ class ActionCreate extends BaseAction {
}
}
private void assemble(Wi wi, Map<String, String> consumersV2, Instant instant, List<Message> messages)
throws Exception {
private List<Message> assemble(Wi wi, Map<String, String> consumersV2, Instant instant) throws Exception {
List<Message> messages = new ArrayList<>();
if (!consumersV2.isEmpty()) {
for (Map.Entry<String, String> en : consumersV2.entrySet()) {
String func = consumersV2.get(en.getKey());
......@@ -91,6 +84,7 @@ class ActionCreate extends BaseAction {
}
}
}
return messages;
}
private Wi executeFun(Wi wi, String func, String consumer) {
......@@ -161,9 +155,9 @@ class ActionCreate extends BaseAction {
case MessageConnector.CONSUME_MPWEIXIN:
message = this.mpweixinMessage(cpWi, instant);
break;
// case MessageConnector.CONSUME_MPWEIXtN:
// message = this.mpweixinMessage(cpWi, instant);
// break;
case MessageConnector.CONSUME_UPDATEQUERYTABLE:
message = this.updateQueryTableMessage(cpWi, instant);
break;
default:
if (consumer.startsWith(MessageConnector.CONSUME_MQ)) {
message = this.mqMessage(cpWi, instant, consumer);
......@@ -209,6 +203,9 @@ class ActionCreate extends BaseAction {
case MessageConnector.CONSUME_MPWEIXIN:
sendMessageMPWeixin(message);
break;
case MessageConnector.CONSUME_UPDATEQUERYTABLE:
sendMessageUpdateQueryTable(message);
break;
default:
if (message.getConsumer().startsWith(MessageConnector.CONSUME_MQ)
&& BooleanUtils.isTrue(Config.mq().getEnable())) {
......@@ -284,6 +281,12 @@ class ActionCreate extends BaseAction {
}
}
private void sendMessageUpdateQueryTable(Message message) throws Exception {
if (BooleanUtils.isTrue(Config.communicate().updateQueryTableEnable())) {
ThisApplication.updateQueryTableConsumeQueue.send(message);
}
}
private Instant instant(Wi wi, List<String> consumers) {
Instant instant = new Instant();
instant.setBody(Objects.toString(wi.getBody()));
......@@ -447,6 +450,26 @@ class ActionCreate extends BaseAction {
return message;
}
private Message updateQueryTableMessage(Wi wi, Instant instant) {
Message message = null;
try {
if (BooleanUtils.isTrue(Config.mPweixin().getEnable())
&& BooleanUtils.isTrue(Config.mPweixin().getMessageEnable())) {
message = new Message();
message.setBody(Objects.toString(wi.getBody()));
message.setType(wi.getType());
message.setPerson(wi.getPerson());
message.setTitle(wi.getTitle());
message.setConsumer(MessageConnector.CONSUME_UPDATEQUERYTABLE);
message.setConsumed(false);
message.setInstant(instant.getId());
}
} catch (Exception e) {
LOGGER.error(e);
}
return message;
}
private Message calendarMessage(Wi wi, Instant instant) {
Message message = null;
try {
......
......@@ -48,13 +48,9 @@ public class Message extends SliceJpaObject {
/* 以上为 JpaObject 默认字段 */
public void onPersist() throws Exception {
// nothing
}
/* 更新运行方法 */
/* flag标志位 */
/* Entity 默认字段结束 */
public static final String title_FIELDNAME = "title";
@FieldDescribe("通知标题.")
@Column(length = length_255B, name = ColumnNamePrefix + title_FIELDNAME)
......@@ -104,6 +100,20 @@ public class Message extends SliceJpaObject {
@CheckPersist(allowEmpty = false)
private String instant;
public static final String TARGET_FIELDNAME = "target";
@FieldDescribe("目标对象.")
@Column(length = length_255B, name = ColumnNamePrefix + TARGET_FIELDNAME)
@CheckPersist(allowEmpty = true)
private String target;
public String getTarget() {
return target;
}
public void setTarget(String target) {
this.target = target;
}
public String getBody() {
return body;
}
......
package com.x.processplatform.assemble.surface.jaxrs.work;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import org.apache.commons.collections4.ListUtils;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
import com.google.gson.JsonElement;
import com.x.base.core.container.EntityManagerContainer;
import com.x.base.core.container.factory.EntityManagerContainerFactory;
import com.x.base.core.entity.JpaObject;
import com.x.base.core.entity.dataitem.DataItem;
import com.x.base.core.entity.dataitem.ItemCategory;
import com.x.base.core.project.bean.WrapCopier;
import com.x.base.core.project.bean.WrapCopierFactory;
import com.x.base.core.project.config.Config;
import com.x.base.core.project.exception.ExceptionAccessDenied;
import com.x.base.core.project.exception.ExceptionEntityExist;
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.base.core.project.organization.Identity;
import com.x.base.core.project.organization.Person;
import com.x.base.core.project.organization.Unit;
import com.x.base.core.project.tools.ListTools;
import com.x.processplatform.assemble.surface.Business;
import com.x.processplatform.assemble.surface.ThisApplication;
import com.x.processplatform.core.entity.content.Attachment;
import com.x.processplatform.core.entity.content.Data;
import com.x.processplatform.core.entity.content.Read;
import com.x.processplatform.core.entity.content.Record;
import com.x.processplatform.core.entity.content.Task;
import com.x.processplatform.core.entity.content.Work;
import com.x.processplatform.core.entity.content.WorkCompleted;
import com.x.processplatform.core.entity.element.Activity;
import com.x.processplatform.core.entity.element.ActivityType;
import com.x.processplatform.core.entity.element.Manual;
import com.x.processplatform.core.entity.element.ManualMode;
import com.x.processplatform.core.entity.element.Route;
import com.x.query.core.entity.Item;
class ActionGet extends BaseAction {
private static final Logger LOGGER = LoggerFactory.getLogger(ActionGet.class);
ActionResult<Wo> execute(EffectivePerson effectivePerson, String id) throws Exception {
ActionResult<Wo> result = new ActionResult<>();
LOGGER.debug("execute:{}, id:{}.", effectivePerson::getDistinguishedName, () -> id);
try (EntityManagerContainer emc = EntityManagerContainerFactory.instance().create()) {
Business business = new Business(emc);
Work work = emc.find(id, Work.class);
if (null == work) {
throw new ExceptionEntityExist(id, Work.class);
}
if (!business.readable(effectivePerson, work)) {
throw new ExceptionAccessDenied(effectivePerson);
}
Wo wo = Wo.copier.copy(work);
result.setData(wo);
}
return result;
}
public static class Wo extends Work {
private static final long serialVersionUID = 3069420284807497002L;
static WrapCopier<Work, Wo> copier = WrapCopierFactory.wo(Work.class, Wo.class, null,
JpaObject.FieldsInvisibleIncludeProperites);
}
}
\ No newline at end of file
......@@ -259,7 +259,7 @@ public class WorkAction extends StandardJaxrsAction {
}
/**
* 不需要申明,这里使用的是chrome在onunload事件运行有特殊的限制@Consumes(MediaType.APPLICATION_JSON)
* 不需要申明,这里使用的是chrome在onunload事件运行有特殊的限制@Consumes(MediaType.APPLICATION_JSON)
*/
@JaxrsMethodDescribe(value = "完成工作关闭时候的检查,1.检查是否要删除处于草稿状态的工作,没有保存过任何数据将被认为是草稿.2.检查是否需要释放抢办.为了支持信标方法(Navigator.sendBeacon())单独增加的方法.", action = ActionCloseCheck.class)
@POST
......@@ -1185,4 +1185,22 @@ public class WorkAction extends StandardJaxrsAction {
asyncResponse.resume(ResponseFactory.getEntityTagActionResultResponse(request, result));
}
@JaxrsMethodDescribe(value = "根据id获取工作.", action = ActionGet.class)
@GET
@Path("{id}")
@Produces(HttpMediaType.APPLICATION_JSON_UTF_8)
@Consumes(MediaType.APPLICATION_JSON)
public void get(@Suspended final AsyncResponse asyncResponse, @Context HttpServletRequest request,
@JaxrsParameterDescribe("工作标识") @PathParam("id") String id) {
ActionResult<ActionGet.Wo> result = new ActionResult<>();
EffectivePerson effectivePerson = this.effectivePerson(request);
try {
result = new ActionGet().execute(effectivePerson, id);
} catch (Exception e) {
logger.error(e, effectivePerson, request, null);
result.error(e);
}
asyncResponse.resume(ResponseFactory.getEntityTagActionResultResponse(request, result));
}
}
......@@ -17,7 +17,8 @@ public class ApplicationServletContextListener implements ServletContextListener
@Override
public void contextInitialized(ServletContextEvent servletContextEvent) {
try {
ThisApplication.setContext(Context.concrete(servletContextEvent, Business.getDynamicEntityClassLoader()));
ThisApplication
.setContext(Context.concrete(servletContextEvent, true, Business.getDynamicEntityClassLoader()));
ThisApplication.init();
ThisApplication.context().regist();
} catch (Exception e) {
......
......@@ -367,7 +367,7 @@ public class Business {
try {
EntityManagerContainerFactory.close();
Business.refreshDynamicEntityClassLoader();
ThisApplication.context().initDatas(Business.getDynamicEntityClassLoader());
ThisApplication.context().initDatas(true, Business.getDynamicEntityClassLoader());
} catch (Exception e) {
LOGGER.error(e);
}
......
......@@ -7,6 +7,7 @@ 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.x_query_service_processing;
import com.x.base.core.project.connection.CipherConnectionAction;
import com.x.base.core.project.exception.ExceptionAccessDenied;
import com.x.base.core.project.exception.ExceptionEntityNotExist;
......@@ -53,6 +54,7 @@ class ActionBuildQueryDispatch extends BaseAction {
});
}
refreshSurface();
refreshProcessing();
wo.setValue(true);
result.setData(wo);
......@@ -66,6 +68,22 @@ class ActionBuildQueryDispatch extends BaseAction {
apps.stream().forEach(o -> {
try {
String url = o.getUrlJaxrsRoot() + "table/reload/dynamic";
LOGGER.info("refresh surface:{}.", url);
CipherConnectionAction.get(false, url);
} catch (Exception e) {
e.printStackTrace();
}
});
}
}
private void refreshProcessing() throws Exception {
List<Application> apps = ThisApplication.context().applications().get(x_query_service_processing.class);
if (ListTools.isNotEmpty(apps)) {
apps.stream().forEach(o -> {
try {
String url = o.getUrlJaxrsRoot() + "table/reload/dynamic";
LOGGER.info("refresh processing:{}.", url);
CipherConnectionAction.get(false, url);
} catch (Exception e) {
e.printStackTrace();
......
......@@ -12,7 +12,8 @@ public class ApplicationServletContextListener implements ServletContextListener
@Override
public void contextInitialized(ServletContextEvent servletContextEvent) {
try {
ThisApplication.setContext(Context.concrete(servletContextEvent, Business.getDynamicEntityClassLoader()));
ThisApplication
.setContext(Context.concrete(servletContextEvent, true, Business.getDynamicEntityClassLoader()));
ThisApplication.init();
ThisApplication.context().regist();
} catch (Exception e) {
......
......@@ -74,7 +74,7 @@ public class Business {
try {
EntityManagerContainerFactory.close();
Business.refreshDynamicEntityClassLoader();
ThisApplication.context().initDatas(Business.getDynamicEntityClassLoader());
ThisApplication.context().initDatas(false, Business.getDynamicEntityClassLoader());
} catch (Exception e) {
LOGGER.error(e);
}
......
package com.x.query.service.processing;
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.filefilter.IOFileFilter;
import org.apache.commons.io.filefilter.WildcardFileFilter;
import com.x.base.core.container.EntityManagerContainer;
import com.x.base.core.container.factory.EntityManagerContainerFactory;
import com.x.base.core.entity.dynamic.DynamicEntity;
import com.x.base.core.project.config.Config;
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.organization.OrganizationDefinition;
import com.x.organization.core.express.Organization;
import com.x.query.service.processing.factory.QueryFactory;
public class Business {
private static final Logger LOGGER = LoggerFactory.getLogger(Business.class);
private EntityManagerContainer emc;
public Business() {
}
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 void reloadClassLoader() {
try {
EntityManagerContainerFactory.close();
Business.refreshDynamicEntityClassLoader();
ThisApplication.context().initDatas(false, Business.getDynamicEntityClassLoader());
} catch (Exception e) {
LOGGER.error(e);
}
}
public Business(EntityManagerContainer emc) throws Exception {
this.emc = emc;
}
......
package com.x.query.service.processing;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import org.apache.commons.lang3.BooleanUtils;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import com.x.base.core.project.Context;
import com.x.base.core.project.cache.CacheManager;
import com.x.base.core.project.config.Config;
......@@ -15,6 +22,20 @@ public class ThisApplication {
// nothing
}
private static ExecutorService threadPool;
public static ExecutorService threadPool() {
return threadPool;
}
private static void initThreadPool() {
int maximumPoolSize = Runtime.getRuntime().availableProcessors() + 1;
ThreadFactory threadFactory = new ThreadFactoryBuilder()
.setNameFormat(ThisApplication.class.getPackageName() + "-threadpool-%d").build();
threadPool = new ThreadPoolExecutor(0, maximumPoolSize, 120, TimeUnit.SECONDS, new ArrayBlockingQueue<>(1000),
threadFactory);
}
protected static Context context;
public static Context context() {
......@@ -23,6 +44,7 @@ public class ThisApplication {
public static void init() {
try {
initThreadPool();
CacheManager.init(context.clazz().getSimpleName());
if (BooleanUtils.isTrue(Config.query().getCrawlWork().getEnable())) {
context.schedule(CrawlWork.class, Config.query().getCrawlWork().getCron());
......
......@@ -8,6 +8,7 @@ import com.x.base.core.project.jaxrs.AbstractActionApplication;
import com.x.query.service.processing.jaxrs.design.DesignAction;
import com.x.query.service.processing.jaxrs.neural.NeuralAction;
import com.x.query.service.processing.jaxrs.segment.SegmentAction;
import com.x.query.service.processing.jaxrs.table.TableAction;
import com.x.query.service.processing.jaxrs.test.TestAction;
@ApplicationPath("jaxrs")
......@@ -18,6 +19,7 @@ public class ActionApplication extends AbstractActionApplication {
classes.add(NeuralAction.class);
classes.add(SegmentAction.class);
classes.add(DesignAction.class);
classes.add(TableAction.class);
return classes;
}
......
package com.x.query.service.processing.jaxrs;
import javax.servlet.annotation.WebFilter;
import com.x.base.core.project.jaxrs.CipherManagerJaxrsFilter;
@WebFilter(urlPatterns = "/jaxrs/table/*", asyncSupported = true)
public class TableJaxrsFilter extends CipherManagerJaxrsFilter {
}
package com.x.query.service.processing.jaxrs.table;
import com.x.base.core.container.EntityManagerContainer;
import com.x.base.core.container.factory.EntityManagerContainerFactory;
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.service.processing.Business;
class ActionReloadDynamic extends BaseAction {
private static final Logger LOGGER = LoggerFactory.getLogger(ActionReloadDynamic.class);
ActionResult<Wo> execute(EffectivePerson effectivePerson) {
LOGGER.debug("execute:{}.", effectivePerson::getDistinguishedName);
try (EntityManagerContainer emc = EntityManagerContainerFactory.instance().create()) {
ActionResult<Wo> result = new ActionResult<>();
Business.reloadClassLoader();
Wo wo = new Wo();
wo.setValue(true);
result.setData(wo);
return result;
}
}
public static class Wo extends WrapBoolean {
private static final long serialVersionUID = -5755898083219447939L;
}
}
package com.x.query.service.processing.jaxrs.table;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.persistence.Column;
import org.apache.commons.beanutils.PropertyUtilsBean;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.reflect.FieldUtils;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonPrimitive;
import com.x.base.core.container.EntityManagerContainer;
import com.x.base.core.container.factory.EntityManagerContainerFactory;
import com.x.base.core.entity.JpaObject;
import com.x.base.core.entity.annotation.CheckPersistType;
import com.x.base.core.entity.dynamic.DynamicEntity;
import com.x.base.core.entity.tools.JpaObjectTools;
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.base.core.project.tools.DateTools;
import com.x.processplatform.core.entity.content.Data;
import com.x.query.core.entity.schema.Table;
import com.x.query.service.processing.Business;
class ActionUpdate extends BaseAction {
private static final Logger LOGGER = LoggerFactory.getLogger(ActionUpdate.class);
private PropertyUtilsBean propertyUtilsBean = new PropertyUtilsBean();
ActionResult<Wo> execute(EffectivePerson effectivePerson, String flag, String bundle, JsonElement jsonElement)
throws Exception {
ClassLoader classLoader = Business.getDynamicEntityClassLoader();
Thread.currentThread().setContextClassLoader(classLoader);
ActionResult<Wo> result = new ActionResult<>();
if (StringUtils.isEmpty(bundle)) {
throw new ExceptionBundleEmpty();
}
try (EntityManagerContainer emc = EntityManagerContainerFactory.instance().create()) {
LOGGER.debug("execute:{}, flag:{}.", effectivePerson::getDistinguishedName, () -> flag);
Table table = emc.flag(flag, Table.class);
if (null == table) {
throw new ExceptionEntityNotExist(flag, Table.class);
}
DynamicEntity dynamicEntity = new DynamicEntity(table.getName());
@SuppressWarnings("unchecked")
Class<? extends JpaObject> cls = (Class<? extends JpaObject>) classLoader
.loadClass(dynamicEntity.className());
JpaObject o = update(jsonElement, cls);
JpaObject obj = emc.find(bundle, cls);
emc.beginTransaction(cls);
if (null != obj) {
o.copyTo(obj, JpaObject.FieldsUnmodify);
emc.check(obj, CheckPersistType.all);
} else {
emc.persist(o);
emc.check(o, CheckPersistType.all);
}
emc.commit();
Wo wo = new Wo();
result.setData(wo);
}
return result;
}
private <T extends JpaObject> T update(JsonElement jsonElement, Class<T> cls)
throws IllegalAccessException, InvocationTargetException, NoSuchMethodException, InstantiationException,
IllegalArgumentException, SecurityException {
List<Field> fields = FieldUtils.getFieldsListWithAnnotation(cls, Column.class);
T t = cls.getConstructor().newInstance();
JsonObject data = null;
JsonObject work = null;
if ((jsonElement != null) && jsonElement.isJsonObject()) {
data = jsonElement.getAsJsonObject();
if (data.has(Data.WORK_PROPERTY)) {
JsonElement jsonElementWork = data.get(Data.WORK_PROPERTY);
if ((null != jsonElementWork) && jsonElementWork.isJsonObject()) {
work = jsonElementWork.getAsJsonObject();
}
}
}
for (Field field : fields) {
switch (JpaObjectTools.type(field)) {
case JpaObject.TYPE_STRING:
propertyUtilsBean.setProperty(t, field.getName(),
extractStringOrDistinguishedName(processPlatformGetJsonElement(data, work, field)));
break;
case JpaObject.TYPE_INTEGER:
propertyUtilsBean.setProperty(t, field.getName(),
extractInteger(processPlatformGetJsonElement(data, work, field)));
break;
case JpaObject.TYPE_LONG:
propertyUtilsBean.setProperty(t, field.getName(),
extractLong(processPlatformGetJsonElement(data, work, field)));
break;
case JpaObject.TYPE_FLOAT:
propertyUtilsBean.setProperty(t, field.getName(),
extractFloat(processPlatformGetJsonElement(data, work, field)));
break;
case JpaObject.TYPE_DOUBLE:
propertyUtilsBean.setProperty(t, field.getName(),
extractDouble(processPlatformGetJsonElement(data, work, field)));
break;
case JpaObject.TYPE_DATETIME:
propertyUtilsBean.setProperty(t, field.getName(),
extractDateTime(processPlatformGetJsonElement(data, work, field)));
break;
case JpaObject.TYPE_DATE:
propertyUtilsBean.setProperty(t, field.getName(),
extractDate(processPlatformGetJsonElement(data, work, field)));
break;
case JpaObject.TYPE_BOOLEAN:
propertyUtilsBean.setProperty(t, field.getName(),
extractBoolean(processPlatformGetJsonElement(data, work, field)));
break;
case JpaObject.TYPE_STRINGLIST:
propertyUtilsBean.setProperty(t, field.getName(),
extractStringOrDistinguishedNameList(processPlatformGetJsonElement(data, work, field)));
break;
case JpaObject.TYPE_INTEGERLIST:
propertyUtilsBean.setProperty(t, field.getName(),
extractIntegerList(processPlatformGetJsonElement(data, work, field)));
break;
case JpaObject.TYPE_LONGLIST:
propertyUtilsBean.setProperty(t, field.getName(),
extractLongList(processPlatformGetJsonElement(data, work, field)));
break;
case JpaObject.TYPE_FLOATLIST:
propertyUtilsBean.setProperty(t, field.getName(),
extractFloatList(processPlatformGetJsonElement(data, work, field)));
break;
case JpaObject.TYPE_DOUBLELIST:
propertyUtilsBean.setProperty(t, field.getName(),
extractDoubleList(processPlatformGetJsonElement(data, work, field)));
break;
case JpaObject.TYPE_DATETIMELIST:
propertyUtilsBean.setProperty(t, field.getName(),
extractDateTimeList(processPlatformGetJsonElement(data, work, field)));
break;
case JpaObject.TYPE_BOOLEANLIST:
propertyUtilsBean.setProperty(t, field.getName(),
extractBooleanList(processPlatformGetJsonElement(data, work, field)));
break;
default:
break;
}
}
return t;
}
private JsonElement processPlatformGetJsonElement(JsonObject data, JsonObject work, Field field) {
JsonElement element = null;
if ((null != work) && work.has(field.getName())) {
element = work.get(field.getName());
} else if ((null != data) && data.has(field.getName())) {
element = data.get(field.getName());
}
return element;
}
private String extractStringOrDistinguishedName(JsonElement jsonElement) {
String value = null;
if (null != jsonElement) {
if (jsonElement.isJsonPrimitive()) {
value = jsonElement.getAsString();
} else if (jsonElement.isJsonObject()) {
JsonObject o = jsonElement.getAsJsonObject();
if (o.has(JpaObject.DISTINGUISHEDNAME)) {
value = o.get(JpaObject.DISTINGUISHEDNAME).getAsString();
}
} else if (jsonElement.isJsonArray()) {
JsonArray os = jsonElement.getAsJsonArray();
if (os.size() > 0) {
value = extractStringOrDistinguishedName(os.get(0));
}
}
}
return value;
}
private List<String> extractStringOrDistinguishedNameList(JsonElement jsonElement) {
List<String> values = new ArrayList<>();
if (null != jsonElement) {
if (jsonElement.isJsonPrimitive()) {
values.add(jsonElement.getAsString());
} else if (jsonElement.isJsonObject()) {
JsonObject o = jsonElement.getAsJsonObject();
if (o.has(JpaObject.DISTINGUISHEDNAME)) {
values.add(o.get(JpaObject.DISTINGUISHEDNAME).getAsString());
}
} else if (jsonElement.isJsonArray()) {
JsonArray os = jsonElement.getAsJsonArray();
for (JsonElement o : os) {
values.add(extractStringOrDistinguishedName(o));
}
}
}
return values;
}
private Integer extractInteger(JsonElement jsonElement) {
Integer value = null;
if (null != jsonElement) {
if (jsonElement.isJsonPrimitive()) {
JsonPrimitive jsonPrimitive = jsonElement.getAsJsonPrimitive();
if (jsonPrimitive.isNumber()) {
value = jsonPrimitive.getAsInt();
}
} else if (jsonElement.isJsonArray()) {
JsonArray os = jsonElement.getAsJsonArray();
if (os.size() > 0) {
value = extractInteger(os.get(0));
}
}
}
return value;
}
private List<Integer> extractIntegerList(JsonElement jsonElement) {
List<Integer> values = new ArrayList<>();
if (null != jsonElement) {
if (jsonElement.isJsonPrimitive()) {
JsonPrimitive jsonPrimitive = jsonElement.getAsJsonPrimitive();
if (jsonPrimitive.isNumber()) {
values.add(jsonPrimitive.getAsInt());
}
} else if (jsonElement.isJsonArray()) {
JsonArray os = jsonElement.getAsJsonArray();
for (JsonElement o : os) {
values.add(extractInteger(o));
}
}
}
return values;
}
private Long extractLong(JsonElement jsonElement) {
Long value = null;
if (null != jsonElement) {
if (jsonElement.isJsonPrimitive()) {
JsonPrimitive jsonPrimitive = jsonElement.getAsJsonPrimitive();
if (jsonPrimitive.isNumber()) {
value = jsonPrimitive.getAsLong();
}
} else if (jsonElement.isJsonArray()) {
JsonArray os = jsonElement.getAsJsonArray();
if (os.size() > 0) {
value = extractLong(os.get(0));
}
}
}
return value;
}
private List<Long> extractLongList(JsonElement jsonElement) {
List<Long> values = new ArrayList<>();
if (null != jsonElement) {
if (jsonElement.isJsonPrimitive()) {
JsonPrimitive jsonPrimitive = jsonElement.getAsJsonPrimitive();
if (jsonPrimitive.isNumber()) {
values.add(jsonPrimitive.getAsLong());
}
} else if (jsonElement.isJsonArray()) {
JsonArray os = jsonElement.getAsJsonArray();
for (JsonElement o : os) {
values.add(extractLong(o));
}
}
}
return values;
}
private Float extractFloat(JsonElement jsonElement) {
Float value = null;
if (null != jsonElement) {
if (jsonElement.isJsonPrimitive()) {
JsonPrimitive jsonPrimitive = jsonElement.getAsJsonPrimitive();
if (jsonPrimitive.isNumber()) {
value = jsonPrimitive.getAsFloat();
}
} else if (jsonElement.isJsonArray()) {
JsonArray os = jsonElement.getAsJsonArray();
if (os.size() > 0) {
value = extractFloat(os.get(0));
}
}
}
return value;
}
private List<Float> extractFloatList(JsonElement jsonElement) {
List<Float> values = new ArrayList<>();
if (null != jsonElement) {
if (jsonElement.isJsonPrimitive()) {
JsonPrimitive jsonPrimitive = jsonElement.getAsJsonPrimitive();
if (jsonPrimitive.isNumber()) {
values.add(jsonPrimitive.getAsFloat());
}
} else if (jsonElement.isJsonArray()) {
JsonArray os = jsonElement.getAsJsonArray();
for (JsonElement o : os) {
values.add(extractFloat(o));
}
}
}
return values;
}
private Double extractDouble(JsonElement jsonElement) {
Double value = null;
if (null != jsonElement) {
if (jsonElement.isJsonPrimitive()) {
JsonPrimitive jsonPrimitive = jsonElement.getAsJsonPrimitive();
if (jsonPrimitive.isNumber()) {
value = jsonPrimitive.getAsDouble();
}
} else if (jsonElement.isJsonArray()) {
JsonArray os = jsonElement.getAsJsonArray();
if (os.size() > 0) {
value = extractDouble(os.get(0));
}
}
}
return value;
}
private List<Double> extractDoubleList(JsonElement jsonElement) {
List<Double> values = new ArrayList<>();
if (null != jsonElement) {
if (jsonElement.isJsonPrimitive()) {
JsonPrimitive jsonPrimitive = jsonElement.getAsJsonPrimitive();
if (jsonPrimitive.isNumber()) {
values.add(jsonPrimitive.getAsDouble());
}
} else if (jsonElement.isJsonArray()) {
JsonArray os = jsonElement.getAsJsonArray();
for (JsonElement o : os) {
values.add(extractDouble(o));
}
}
}
return values;
}
private Date extractDateTime(JsonElement jsonElement) {
Date value = null;
if (null != jsonElement) {
if (jsonElement.isJsonPrimitive()) {
JsonPrimitive jsonPrimitive = jsonElement.getAsJsonPrimitive();
if (jsonPrimitive.isString()) {
try {
value = DateTools.parseDateTime(jsonPrimitive.getAsString());
} catch (Exception e) {
LOGGER.error(e);
}
}
} else if (jsonElement.isJsonArray()) {
JsonArray os = jsonElement.getAsJsonArray();
if (os.size() > 0) {
value = extractDateTime(os.get(0));
}
}
}
return value;
}
private List<Date> extractDateTimeList(JsonElement jsonElement) {
List<Date> values = new ArrayList<>();
if (null != jsonElement) {
if (jsonElement.isJsonPrimitive()) {
JsonPrimitive jsonPrimitive = jsonElement.getAsJsonPrimitive();
if (jsonPrimitive.isString()) {
try {
values.add(DateTools.parseDateTime(jsonPrimitive.getAsString()));
} catch (Exception e) {
LOGGER.error(e);
}
}
} else if (jsonElement.isJsonArray()) {
JsonArray os = jsonElement.getAsJsonArray();
for (JsonElement o : os) {
values.add(extractDateTime(o));
}
}
}
return values;
}
private Date extractDate(JsonElement jsonElement) {
Date value = null;
if (null != jsonElement) {
if (jsonElement.isJsonPrimitive()) {
JsonPrimitive jsonPrimitive = jsonElement.getAsJsonPrimitive();
if (jsonPrimitive.isString()) {
try {
value = DateTools.parseDate(jsonPrimitive.getAsString());
} catch (Exception e) {
LOGGER.error(e);
}
}
} else if (jsonElement.isJsonArray()) {
JsonArray os = jsonElement.getAsJsonArray();
if (os.size() > 0) {
value = extractDate(os.get(0));
}
}
}
return value;
}
private Boolean extractBoolean(JsonElement jsonElement) {
Boolean value = null;
if (null != jsonElement) {
if (jsonElement.isJsonPrimitive()) {
JsonPrimitive jsonPrimitive = jsonElement.getAsJsonPrimitive();
if (jsonPrimitive.isNumber()) {
value = jsonPrimitive.getAsBoolean();
}
} else if (jsonElement.isJsonArray()) {
JsonArray os = jsonElement.getAsJsonArray();
if (os.size() > 0) {
value = extractBoolean(os.get(0));
}
}
}
return value;
}
private List<Boolean> extractBooleanList(JsonElement jsonElement) {
List<Boolean> values = new ArrayList<>();
if (null != jsonElement) {
if (jsonElement.isJsonPrimitive()) {
JsonPrimitive jsonPrimitive = jsonElement.getAsJsonPrimitive();
if (jsonPrimitive.isNumber()) {
values.add(jsonPrimitive.getAsBoolean());
}
} else if (jsonElement.isJsonArray()) {
JsonArray os = jsonElement.getAsJsonArray();
for (JsonElement o : os) {
values.add(extractBoolean(o));
}
}
}
return values;
}
public static class Wo extends WrapBoolean {
private static final long serialVersionUID = 7570720614789228246L;
}
}
\ No newline at end of file
package com.x.query.service.processing.jaxrs.table;
import com.x.base.core.project.jaxrs.StandardJaxrsAction;
abstract class BaseAction extends StandardJaxrsAction {
}
package com.x.query.service.processing.jaxrs.table;
import com.x.base.core.project.exception.LanguagePromptException;
public class ExceptionBundleEmpty extends LanguagePromptException {
private static final long serialVersionUID = -87643358931771164L;
public ExceptionBundleEmpty() {
super("标识不能为空.");
}
}
package com.x.query.service.processing.jaxrs.table;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.container.AsyncResponse;
import javax.ws.rs.container.Suspended;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import com.google.gson.JsonElement;
import com.x.base.core.project.annotation.JaxrsDescribe;
import com.x.base.core.project.annotation.JaxrsMethodDescribe;
import com.x.base.core.project.annotation.JaxrsParameterDescribe;
import com.x.base.core.project.http.ActionResult;
import com.x.base.core.project.http.EffectivePerson;
import com.x.base.core.project.http.HttpMediaType;
import com.x.base.core.project.jaxrs.ResponseFactory;
import com.x.base.core.project.jaxrs.StandardJaxrsAction;
import com.x.base.core.project.logger.Logger;
import com.x.base.core.project.logger.LoggerFactory;
@Path("table")
@JaxrsDescribe("表")
public class TableAction extends StandardJaxrsAction {
private static final Logger LOGGER = LoggerFactory.getLogger(TableAction.class);
@JaxrsMethodDescribe(value = "更新指定表中的行.", action = ActionUpdate.class)
@POST
@Path("{flag}/update/{bundle}")
@Produces(HttpMediaType.APPLICATION_JSON_UTF_8)
@Consumes(MediaType.APPLICATION_JSON)
public void listNext(@Suspended final AsyncResponse asyncResponse, @Context HttpServletRequest request,
@JaxrsParameterDescribe("标识") @PathParam("flag") String flag,
@JaxrsParameterDescribe("数据行标识") @PathParam("bundle") String bundle, JsonElement jsonElement) {
ActionResult<ActionUpdate.Wo> result = new ActionResult<>();
EffectivePerson effectivePerson = this.effectivePerson(request);
try {
result = new ActionUpdate().execute(effectivePerson, flag, bundle, jsonElement);
} catch (Exception e) {
LOGGER.error(e, effectivePerson, request, jsonElement);
result.error(e);
}
asyncResponse.resume(ResponseFactory.getEntityTagActionResultResponse(request, result));
}
@JaxrsMethodDescribe(value = "在服务器重新编译dynamicEntity之后需要重新初始化EntityManagerContainerFactory.", action = ActionReloadDynamic.class)
@GET
@Path("reload/dynamic")
@Produces(HttpMediaType.APPLICATION_JSON_UTF_8)
@Consumes(MediaType.APPLICATION_JSON)
public void reloadDynamic(@Suspended final AsyncResponse asyncResponse, @Context HttpServletRequest request) {
ActionResult<ActionReloadDynamic.Wo> result = new ActionResult<>();
EffectivePerson effectivePerson = this.effectivePerson(request);
try {
result = new ActionReloadDynamic().execute(effectivePerson);
} catch (Exception e) {
LOGGER.error(e, effectivePerson, request, null);
result.error(e);
}
asyncResponse.resume(ResponseFactory.getEntityTagActionResultResponse(request, result));
}
}
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册