提交 b1f8c0e3 编写于 作者: O o2null

Merge branch 'feature/数据中心优化' into 'wrdp'

【数据中心】数据中心优化 to wrdp

See merge request o2oa/o2oa!1920
......@@ -2,9 +2,9 @@ package com.x.query.assemble.designer.jaxrs;
import javax.servlet.annotation.WebFilter;
import com.x.base.core.project.jaxrs.AnonymousCipherManagerUserJaxrsFilter;
import com.x.base.core.project.jaxrs.CipherManagerUserJaxrsFilter;
@WebFilter(urlPatterns = "/jaxrs/statement/*", asyncSupported = true)
public class StatementJaxrsFilter extends AnonymousCipherManagerUserJaxrsFilter {
public class StatementJaxrsFilter extends CipherManagerUserJaxrsFilter {
}
......@@ -73,7 +73,13 @@ class ActionExecute extends BaseAction {
scriptContext);
String text = ScriptFactory.asString(o);
Class<? extends JpaObject> cls = this.clazz(business, statement);
EntityManager em = business.entityManagerContainer().get(cls);
EntityManager em;
if(StringUtils.equalsIgnoreCase(statement.getEntityCategory(), Statement.ENTITYCATEGORY_DYNAMIC)
&& StringUtils.equalsIgnoreCase(statement.getType(), Statement.TYPE_SELECT)){
em = business.entityManagerContainer().get(DynamicBaseEntity.class);
}else{
em = business.entityManagerContainer().get(cls);
}
Query query = em.createQuery(text);
for (Parameter<?> p : query.getParameters()) {
if (runtime.hasParameter(p.getName())) {
......
package com.x.query.assemble.designer.jaxrs.statement;
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.dynamic.DynamicBaseEntity;
import com.x.base.core.entity.dynamic.DynamicEntity;
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.script.AbstractResources;
import com.x.base.core.project.script.ScriptFactory;
import com.x.base.core.project.webservices.WebservicesClient;
import com.x.organization.core.express.Organization;
import com.x.query.assemble.designer.Business;
import com.x.query.assemble.designer.ThisApplication;
import com.x.query.core.entity.schema.Statement;
import com.x.query.core.entity.schema.Table;
import com.x.query.core.express.statement.Runtime;
import org.apache.commons.lang3.StringUtils;
import javax.persistence.EntityManager;
import javax.persistence.Parameter;
import javax.persistence.Query;
import javax.script.Bindings;
import javax.script.ScriptContext;
import javax.script.SimpleScriptContext;
import java.util.Objects;
class ActionExecuteV2 extends BaseAction {
private static Logger logger = LoggerFactory.getLogger(ActionExecuteV2.class);
ActionResult<Object> execute(EffectivePerson effectivePerson, String flag, String mode, Integer page, Integer size,
JsonElement jsonElement) throws Exception {
try (EntityManagerContainer emc = EntityManagerContainerFactory.instance().create()) {
ActionResult<Object> result = new ActionResult<>();
Business business = new Business(emc);
Statement statement = emc.flag(flag, Statement.class);
if (null == statement) {
throw new ExceptionEntityNotExist(flag, Statement.class);
}
if (!business.executable(effectivePerson, statement)) {
throw new ExceptionAccessDenied(effectivePerson, statement);
}
Runtime runtime = this.runtime(effectivePerson, jsonElement, business, page, size);
Object data = null;
Object count = null;
switch (mode){
case Statement.MODE_DATA:
switch (Objects.toString(statement.getFormat(), "")) {
case Statement.FORMAT_SCRIPT:
data = this.script(effectivePerson, business, statement, runtime, mode);
break;
default:
data = this.jpql(effectivePerson, business, statement, runtime, mode);
break;
}
result.setData(data);
break;
case Statement.MODE_COUNT:
switch (Objects.toString(statement.getFormat(), "")) {
case Statement.FORMAT_SCRIPT:
count = this.script(effectivePerson, business, statement, runtime, mode);
break;
default:
count = this.jpql(effectivePerson, business, statement, runtime, mode);
break;
}
result.setData(count);
result.setCount((Long)count);
break;
default:
switch (Objects.toString(statement.getFormat(), "")) {
case Statement.FORMAT_SCRIPT:
data = this.script(effectivePerson, business, statement, runtime, Statement.MODE_DATA);
count = this.script(effectivePerson, business, statement, runtime, Statement.MODE_COUNT);
break;
default:
data = this.jpql(effectivePerson, business, statement, runtime, Statement.MODE_DATA);
count = this.jpql(effectivePerson, business, statement, runtime, Statement.MODE_COUNT);
break;
}
result.setData(data);
result.setCount((Long)count);
}
return result;
}
}
private Object script(EffectivePerson effectivePerson, Business business, Statement statement, Runtime runtime, String mode)
throws Exception {
Object data = null;
ScriptContext scriptContext = this.scriptContext(effectivePerson, business, runtime);
ScriptFactory.initialServiceScriptText().eval(scriptContext);
String scriptText = statement.getScriptText();
if(Statement.MODE_COUNT.equals(mode)) {
scriptText = statement.getCountScriptText();
}
Object o = ScriptFactory.scriptEngine.eval(ScriptFactory.functionalization(scriptText),
scriptContext);
String text = ScriptFactory.asString(o);
Class<? extends JpaObject> cls = this.clazz(business, statement);
EntityManager em;
if(StringUtils.equalsIgnoreCase(statement.getEntityCategory(), Statement.ENTITYCATEGORY_DYNAMIC)
&& StringUtils.equalsIgnoreCase(statement.getType(), Statement.TYPE_SELECT)){
em = business.entityManagerContainer().get(DynamicBaseEntity.class);
}else{
em = business.entityManagerContainer().get(cls);
}
Query query = em.createQuery(text);
for (Parameter<?> p : query.getParameters()) {
if (runtime.hasParameter(p.getName())) {
query.setParameter(p.getName(), runtime.getParameter(p.getName()));
}
}
if (StringUtils.equalsIgnoreCase(statement.getType(), Statement.TYPE_SELECT)) {
if(Statement.MODE_COUNT.equals(mode)) {
data = query.getSingleResult();
}else{
query.setFirstResult((runtime.page - 1) * runtime.size);
query.setMaxResults(runtime.size);
data = query.getResultList();
}
} else {
business.entityManagerContainer().beginTransaction(cls);
data = query.executeUpdate();
business.entityManagerContainer().commit();
}
return data;
}
private Object jpql(EffectivePerson effectivePerson, Business business, Statement statement, Runtime runtime, String mode)
throws Exception {
Object data = null;
Class<? extends JpaObject> cls = this.clazz(business, statement);
EntityManager em;
if(StringUtils.equalsIgnoreCase(statement.getEntityCategory(), Statement.ENTITYCATEGORY_DYNAMIC)
&& StringUtils.equalsIgnoreCase(statement.getType(), Statement.TYPE_SELECT)){
em = business.entityManagerContainer().get(DynamicBaseEntity.class);
}else{
em = business.entityManagerContainer().get(cls);
}
String jpqlData = statement.getData();
if(Statement.MODE_COUNT.equals(mode)) {
jpqlData = statement.getCountData();
}
Query query = em.createQuery(jpqlData);
for (Parameter<?> p : query.getParameters()) {
if (runtime.hasParameter(p.getName())) {
query.setParameter(p.getName(), runtime.getParameter(p.getName()));
}
}
if (StringUtils.equalsIgnoreCase(statement.getType(), Statement.TYPE_SELECT)) {
if(Statement.MODE_COUNT.equals(mode)) {
data = query.getSingleResult();
}else{
query.setFirstResult((runtime.page - 1) * runtime.size);
query.setMaxResults(runtime.size);
data = query.getResultList();
}
} else {
business.entityManagerContainer().beginTransaction(cls);
data = Integer.valueOf(query.executeUpdate());
business.entityManagerContainer().commit();
}
return data;
}
private Class<? extends JpaObject> clazz(Business business, Statement statement) throws Exception {
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());
} 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());
}
return cls;
}
private ScriptContext scriptContext(EffectivePerson effectivePerson, Business business, Runtime runtime)
throws Exception {
ScriptContext scriptContext = new SimpleScriptContext();
Resources resources = new Resources();
resources.setEntityManagerContainer(business.entityManagerContainer());
resources.setContext(ThisApplication.context());
resources.setApplications(ThisApplication.context().applications());
resources.setWebservicesClient(new WebservicesClient());
resources.setOrganization(new Organization(ThisApplication.context()));
Bindings bindings = scriptContext.getBindings(ScriptContext.ENGINE_SCOPE);
bindings.put(ScriptFactory.BINDING_NAME_RESOURCES, resources);
bindings.put(ScriptFactory.BINDING_NAME_EFFECTIVEPERSON, effectivePerson);
bindings.put(ScriptFactory.BINDING_NAME_PARAMETERS, gson.toJson(runtime.getParameters()));
return scriptContext;
}
public static class Resources extends AbstractResources {
private Organization organization;
public Organization getOrganization() {
return organization;
}
public void setOrganization(Organization organization) {
this.organization = organization;
}
}
}
\ No newline at end of file
......@@ -142,4 +142,25 @@ public class StatementAction extends StandardJaxrsAction {
}
asyncResponse.resume(ResponseFactory.getEntityTagActionResultResponse(request, result));
}
@JaxrsMethodDescribe(value = "执行语句V2,可以同时执行查询结果及查询总数.", action = ActionExecuteV2.class)
@POST
@Path("{flag}/execute/mode/{mode}page/{page}/size/{size}")
@Produces(HttpMediaType.APPLICATION_JSON_UTF_8)
@Consumes(MediaType.APPLICATION_JSON)
public void executeV2(@Suspended final AsyncResponse asyncResponse, @Context HttpServletRequest request,
@JaxrsParameterDescribe("标识") @PathParam("flag") String flag,
@JaxrsParameterDescribe("执行模式:data|count|all") @PathParam("mode") String mode,
@JaxrsParameterDescribe("页码") @PathParam("page") Integer page,
@JaxrsParameterDescribe("每页数量") @PathParam("size") Integer size, JsonElement jsonElement) {
ActionResult<Object> result = new ActionResult<>();
EffectivePerson effectivePerson = this.effectivePerson(request);
try {
result = new ActionExecuteV2().execute(effectivePerson, flag, mode, page, size, jsonElement);
} catch (Exception e) {
logger.error(e, effectivePerson, request, jsonElement);
result.error(e);
}
asyncResponse.resume(ResponseFactory.getEntityTagActionResultResponse(request, result));
}
}
\ No newline at end of file
......@@ -4,6 +4,7 @@ import java.util.List;
import com.x.query.assemble.surface.factory.*;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
import com.x.base.core.container.EntityManagerContainer;
......@@ -203,6 +204,39 @@ public class Business {
return false;
}
public boolean readable(EffectivePerson effectivePerson, Statement statement) throws Exception {
if (null == statement) {
return false;
}
if(BooleanUtils.isTrue(statement.getAnonymousAccessible())){
return true;
}
if (effectivePerson.isManager()) {
return true;
}
if (statement.getExecutePersonList().isEmpty() && statement.getExecuteUnitList().isEmpty()) {
return true;
}
if (CollectionUtils.containsAny(statement.getExecutePersonList(),
organization().identity().listWithPerson(effectivePerson))) {
return true;
}
if (CollectionUtils.containsAny(statement.getExecuteUnitList(),
organization().unit().listWithPersonSupNested(effectivePerson))) {
return true;
}
Query query = this.entityManagerContainer().find(statement.getQuery(), Query.class);
/** 在所属query的管理人员中 */
if (null != query && ListTools.contains(query.getControllerList(), effectivePerson.getDistinguishedName())) {
return true;
}
if (organization().person().hasRole(effectivePerson, OrganizationDefinition.Manager,
OrganizationDefinition.QueryManager)) {
return true;
}
return false;
}
public boolean readable(EffectivePerson effectivePerson, Reveal reveal) throws Exception {
if (null == reveal) {
return false;
......@@ -293,22 +327,26 @@ public class Business {
public boolean executable(EffectivePerson effectivePerson, Statement o) throws Exception {
boolean result = false;
if (null != o) {
if (ListTools.isEmpty(o.getExecutePersonList()) && ListTools.isEmpty(o.getExecuteUnitList())) {
if(BooleanUtils.isTrue(o.getAnonymousAccessible())){
result = true;
}
if (!result) {
if (effectivePerson.isManager()
|| (this.organization().person().hasRole(effectivePerson, OrganizationDefinition.Manager,
OrganizationDefinition.QueryManager))
|| effectivePerson.isPerson(o.getExecutePersonList())) {
}else {
if (ListTools.isEmpty(o.getExecutePersonList()) && ListTools.isEmpty(o.getExecuteUnitList())) {
result = true;
}
if ((!result) && ListTools.isNotEmpty(o.getExecuteUnitList())) {
List<String> units = this.organization().unit()
.listWithPerson(effectivePerson.getDistinguishedName());
if (ListTools.containsAny(units, o.getExecuteUnitList())) {
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;
}
}
}
}
}
......
......@@ -110,7 +110,13 @@ class ActionExecute extends BaseAction {
Object o = compiledScript.eval(scriptContext);
String text = ScriptFactory.asString(o);
Class<? extends JpaObject> cls = this.clazz(business, statement);
EntityManager em = business.entityManagerContainer().get(cls);
EntityManager em;
if(StringUtils.equalsIgnoreCase(statement.getEntityCategory(), Statement.ENTITYCATEGORY_DYNAMIC)
&& StringUtils.equalsIgnoreCase(statement.getType(), Statement.TYPE_SELECT)){
em = business.entityManagerContainer().get(DynamicBaseEntity.class);
}else{
em = business.entityManagerContainer().get(cls);
}
Query query = em.createQuery(text);
for (Parameter<?> p : query.getParameters()) {
if (runtime.hasParameter(p.getName())) {
......
package com.x.query.assemble.surface.jaxrs.statement;
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.dynamic.DynamicBaseEntity;
import com.x.base.core.entity.dynamic.DynamicEntity;
import com.x.base.core.project.annotation.FieldDescribe;
import com.x.base.core.project.annotation.FieldTypeDescribe;
import com.x.base.core.project.exception.ExceptionAccessDenied;
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.base.core.project.script.AbstractResources;
import com.x.base.core.project.script.ScriptFactory;
import com.x.base.core.project.webservices.WebservicesClient;
import com.x.organization.core.express.Organization;
import com.x.query.assemble.surface.Business;
import com.x.query.assemble.surface.ThisApplication;
import com.x.query.core.entity.schema.Statement;
import com.x.query.core.entity.schema.Table;
import com.x.query.core.express.plan.Comparison;
import com.x.query.core.express.plan.FilterEntry;
import com.x.query.core.express.statement.Runtime;
import org.apache.commons.collections4.list.TreeList;
import org.apache.commons.lang3.StringUtils;
import javax.persistence.EntityManager;
import javax.persistence.Parameter;
import javax.persistence.Query;
import javax.script.Bindings;
import javax.script.ScriptContext;
import javax.script.SimpleScriptContext;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
class ActionExecuteV2 extends BaseAction {
private static Logger logger = LoggerFactory.getLogger(ActionExecuteV2.class);
private final static String[] keys = {"group by","GROUP BY","order by","ORDER BY","limit","LIMIT"};
ActionResult<Object> execute(EffectivePerson effectivePerson, String flag, String mode, Integer page, Integer size,
JsonElement jsonElement) throws Exception {
try (EntityManagerContainer emc = EntityManagerContainerFactory.instance().create()) {
ActionResult<Object> result = new ActionResult<>();
Business business = new Business(emc);
Statement statement = emc.flag(flag, Statement.class);
if (null == statement) {
throw new ExceptionEntityNotExist(flag, Statement.class);
}
if (!business.executable(effectivePerson, statement)) {
throw new ExceptionAccessDenied(effectivePerson, statement);
}
Wi wi = this.convertToWrapIn(jsonElement, Wi.class);
Runtime runtime = this.runtime(effectivePerson, wi.getParameter(), business, page, size);
Object data = null;
Object count = null;
switch (mode){
case Statement.MODE_DATA:
switch (Objects.toString(statement.getFormat(), "")) {
case Statement.FORMAT_SCRIPT:
data = this.script(effectivePerson, business, statement, runtime, mode, wi);
break;
default:
data = this.jpql(effectivePerson, business, statement, runtime, mode, wi);
break;
}
result.setData(data);
break;
case Statement.MODE_COUNT:
switch (Objects.toString(statement.getFormat(), "")) {
case Statement.FORMAT_SCRIPT:
count = this.script(effectivePerson, business, statement, runtime, mode, wi);
break;
default:
count = this.jpql(effectivePerson, business, statement, runtime, mode, wi);
break;
}
result.setData(count);
result.setCount((Long)count);
break;
default:
switch (Objects.toString(statement.getFormat(), "")) {
case Statement.FORMAT_SCRIPT:
data = this.script(effectivePerson, business, statement, runtime, Statement.MODE_DATA, wi);
count = this.script(effectivePerson, business, statement, runtime, Statement.MODE_COUNT, wi);
break;
default:
data = this.jpql(effectivePerson, business, statement, runtime, Statement.MODE_DATA, wi);
count = this.jpql(effectivePerson, business, statement, runtime, Statement.MODE_COUNT, wi);
break;
}
result.setData(data);
result.setCount((Long)count);
}
return result;
}
}
private Object script(EffectivePerson effectivePerson, Business business, Statement statement, Runtime runtime, String mode, Wi wi)
throws Exception {
Object data = null;
ScriptContext scriptContext = this.scriptContext(effectivePerson, business, runtime);
ScriptFactory.initialServiceScriptText().eval(scriptContext);
String scriptText = statement.getScriptText();
if(Statement.MODE_COUNT.equals(mode)) {
scriptText = statement.getCountScriptText();
}
Object o = ScriptFactory.scriptEngine.eval(ScriptFactory.functionalization(scriptText),
scriptContext);
String text = ScriptFactory.asString(o);
Class<? extends JpaObject> cls = this.clazz(business, statement);
EntityManager em;
if(StringUtils.equalsIgnoreCase(statement.getEntityCategory(), Statement.ENTITYCATEGORY_DYNAMIC)
&& StringUtils.equalsIgnoreCase(statement.getType(), Statement.TYPE_SELECT)){
em = business.entityManagerContainer().get(DynamicBaseEntity.class);
}else{
em = business.entityManagerContainer().get(cls);
}
text = joinSql(text, wi);
logger.print("执行的sql:{}",text);
Query query = em.createQuery(text);
for (Parameter<?> p : query.getParameters()) {
if (runtime.hasParameter(p.getName())) {
query.setParameter(p.getName(), runtime.getParameter(p.getName()));
}
}
if (StringUtils.equalsIgnoreCase(statement.getType(), Statement.TYPE_SELECT)) {
if(Statement.MODE_COUNT.equals(mode)) {
data = query.getSingleResult();
}else{
query.setFirstResult((runtime.page - 1) * runtime.size);
query.setMaxResults(runtime.size);
data = query.getResultList();
}
} else {
business.entityManagerContainer().beginTransaction(cls);
data = query.executeUpdate();
business.entityManagerContainer().commit();
}
return data;
}
private Object jpql(EffectivePerson effectivePerson, Business business, Statement statement, Runtime runtime, String mode, Wi wi)
throws Exception {
Object data = null;
Class<? extends JpaObject> cls = this.clazz(business, statement);
EntityManager em;
if(StringUtils.equalsIgnoreCase(statement.getEntityCategory(), Statement.ENTITYCATEGORY_DYNAMIC)
&& StringUtils.equalsIgnoreCase(statement.getType(), Statement.TYPE_SELECT)){
em = business.entityManagerContainer().get(DynamicBaseEntity.class);
}else{
em = business.entityManagerContainer().get(cls);
}
String jpqlData = statement.getData();
if(Statement.MODE_COUNT.equals(mode)) {
jpqlData = statement.getCountData();
}
jpqlData = joinSql(jpqlData, wi);
logger.print("执行的sql:{}",jpqlData);
Query query = em.createQuery(jpqlData);
for (Parameter<?> p : query.getParameters()) {
if (runtime.hasParameter(p.getName())) {
query.setParameter(p.getName(), runtime.getParameter(p.getName()));
}
}
if (StringUtils.equalsIgnoreCase(statement.getType(), Statement.TYPE_SELECT)) {
if(Statement.MODE_COUNT.equals(mode)) {
data = query.getSingleResult();
}else{
query.setFirstResult((runtime.page - 1) * runtime.size);
query.setMaxResults(runtime.size);
data = query.getResultList();
}
} else {
business.entityManagerContainer().beginTransaction(cls);
data = Integer.valueOf(query.executeUpdate());
business.entityManagerContainer().commit();
}
return data;
}
private Class<? extends JpaObject> clazz(Business business, Statement statement) throws Exception {
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());
} 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());
}
return cls;
}
private ScriptContext scriptContext(EffectivePerson effectivePerson, Business business, Runtime runtime)
throws Exception {
ScriptContext scriptContext = new SimpleScriptContext();
Resources resources = new Resources();
resources.setEntityManagerContainer(business.entityManagerContainer());
resources.setContext(ThisApplication.context());
resources.setApplications(ThisApplication.context().applications());
resources.setWebservicesClient(new WebservicesClient());
resources.setOrganization(new Organization(ThisApplication.context()));
Bindings bindings = scriptContext.getBindings(ScriptContext.ENGINE_SCOPE);
bindings.put(ScriptFactory.BINDING_NAME_RESOURCES, resources);
bindings.put(ScriptFactory.BINDING_NAME_EFFECTIVEPERSON, effectivePerson);
bindings.put(ScriptFactory.BINDING_NAME_PARAMETERS, gson.toJson(runtime.getParameters()));
return scriptContext;
}
private String joinSql(String sql, Wi wi) throws Exception{
if(wi.getFilterList()!=null && !wi.getFilterList().isEmpty()) {
List<String> list = new ArrayList<>();
String whereSql = sql.replaceAll("\\s{1,}", " ");
String rightSql = "";
String leftSql = "";
boolean hasWhere = false;
if (sql.indexOf("where") > -1) {
whereSql = StringUtils.substringAfter(sql, "where");
leftSql = StringUtils.substringBefore(sql, "where");
hasWhere = true;
} else if (sql.indexOf("WHERE") > -1) {
whereSql = StringUtils.substringAfter(sql, "WHERE");
leftSql = StringUtils.substringBefore(sql, "WHERE");
hasWhere = true;
}
String matchKey = "";
for(String key : keys){
if (whereSql.indexOf(key) > -1) {
matchKey = key;
rightSql = StringUtils.substringAfter(whereSql, key);
whereSql = StringUtils.substringBefore(whereSql, key);
break;
}
}
List<String> filterList = new ArrayList<>();
for (FilterEntry filterEntry : wi.getFilterList()){
if(StringUtils.isNotBlank(filterEntry.path) && StringUtils.isNotBlank(filterEntry.value)){
StringBuilder sb = new StringBuilder();
sb.append(filterEntry.path);
sb.append(" ");
sb.append(Comparison.getMatchCom(filterEntry.comparison));
sb.append(" ");
sb.append(":"+filterEntry.value);
filterList.add(sb.toString());
}
}
if(hasWhere){
list.add(leftSql);
list.add("WHERE");
}else{
list.add(whereSql);
if(!filterList.isEmpty()){
list.add("WHERE");
}
}
if(!filterList.isEmpty()){
list.add("(");
list.add(StringUtils.join(filterList, " AND "));
list.add(")");
}
if(hasWhere){
list.add("AND");
list.add("(");
list.add(whereSql);
list.add(")");
}
if(StringUtils.isNotBlank(matchKey)){
list.add(matchKey);
list.add(rightSql);
}
sql = StringUtils.join(list, " ");
}
return sql;
}
public static class Resources extends AbstractResources {
private Organization organization;
public Organization getOrganization() {
return organization;
}
public void setOrganization(Organization organization) {
this.organization = organization;
}
}
public static class Wi extends GsonPropertyObject {
@FieldDescribe("过滤")
@FieldTypeDescribe(fieldType="class",fieldTypeName = "com.x.query.core.express.plan.FilterEntry",
fieldValue="{\"logic\": \"and\", \"path\": \"o.name\", \"comparison\": \"equals\", \"value\": \"name\", \"formatType\": \"textValue\"}",
fieldSample="{\"logic\":\"逻辑运算:and\",\"path\":\"data数据的路径:o.title\",\"comparison\":\"比较运算符:equals|notEquals|like|notLike|greaterThan|greaterThanOrEqualTo|lessThan|lessThanOrEqualTo\"," +
"\"value\":\"7月\",\"formatType\":\"textValue|numberValue|dateTimeValue|booleanValue\"}")
private List<FilterEntry> filterList = new TreeList<>();
@FieldDescribe("参数")
private JsonElement parameter;
public List<FilterEntry> getFilterList() {
return filterList;
}
public void setFilterList(List<FilterEntry> filterList) {
this.filterList = filterList;
}
public JsonElement getParameter() {
return parameter;
}
public void setParameter(JsonElement parameter) {
this.parameter = parameter;
}
}
}
\ No newline at end of file
package com.x.query.assemble.surface.jaxrs.statement;
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.project.bean.WrapCopier;
import com.x.base.core.project.bean.WrapCopierFactory;
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.query.assemble.surface.Business;
import com.x.query.core.entity.Query;
import com.x.query.core.entity.schema.Statement;
class ActionGet extends BaseAction {
ActionResult<Wo> execute(EffectivePerson effectivePerson, String flag) throws Exception {
try (EntityManagerContainer emc = EntityManagerContainerFactory.instance().create()) {
ActionResult<Wo> result = new ActionResult<>();
Business business = new Business(emc);
Statement statement = emc.flag(flag, Statement.class);
if (null == statement) {
throw new ExceptionEntityNotExist(flag, Statement.class);
}
Query query = emc.flag(statement.getQuery(), Query.class);
if (null == query) {
throw new ExceptionEntityNotExist(flag, Query.class);
}
if (!business.readable(effectivePerson, query)) {
throw new ExceptionAccessDenied(effectivePerson, query);
}
if (!business.readable(effectivePerson, statement)) {
throw new ExceptionAccessDenied(effectivePerson, statement);
}
Wo wo = Wo.copier.copy(statement);
result.setData(wo);
return result;
}
}
public static class Wo extends Statement {
private static final long serialVersionUID = -5755898083219447939L;
static WrapCopier<Statement, Wo> copier = WrapCopierFactory.wo(Statement.class, Wo.class, null,
JpaObject.FieldsInvisible);
}
}
package com.x.query.assemble.surface.jaxrs.statement;
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.project.bean.WrapCopier;
import com.x.base.core.project.bean.WrapCopierFactory;
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.query.assemble.surface.Business;
import com.x.query.core.entity.Query;
import com.x.query.core.entity.schema.Statement;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
import java.util.ArrayList;
import java.util.List;
class ActionListWithQuery extends BaseAction {
ActionResult<List<Wo>> execute(EffectivePerson effectivePerson, String queryFlag, Boolean justSelect, Boolean hasView) throws Exception {
try (EntityManagerContainer emc = EntityManagerContainerFactory.instance().create()) {
ActionResult<List<Wo>> result = new ActionResult<>();
Business business = new Business(emc);
Query query = emc.flag(queryFlag, Query.class);
if (null == query) {
throw new ExceptionEntityNotExist(queryFlag);
}
if (!business.readable(effectivePerson, query)) {
throw new ExceptionAccessDenied(effectivePerson.getDistinguishedName());
}
List<Wo> wos = new ArrayList<>();
for (String id : emc.idsEqual(Statement.class, Statement.query_FIELDNAME, query.getId())) {
Statement o = business.pick(id, Statement.class);
if (null != o) {
if(BooleanUtils.isTrue(hasView) && StringUtils.isBlank(o.getView())){
continue;
}
if(BooleanUtils.isTrue(justSelect) && !Statement.TYPE_SELECT.equals(o.getType())){
continue;
}
if (business.readable(effectivePerson, o)) {
wos.add(Wo.copier.copy(o));
}
}
}
result.setData(wos);
return result;
}
}
public static class Wo extends Statement {
private static final long serialVersionUID = -5755898083219447939L;
static WrapCopier<Statement, Wo> copier = WrapCopierFactory.wo(Statement.class, Wo.class,
JpaObject.singularAttributeField(Statement.class, true, true), JpaObject.FieldsInvisible);
}
}
......@@ -29,7 +29,7 @@ abstract class BaseAction extends StandardJaxrsAction {
}
runtime.page = this.adjustPage(page);
runtime.size = this.adjustSize(size);
Set<String> keys = runtime.parameters.keySet();
/*Set<String> keys = runtime.parameters.keySet();
if (keys.contains(Runtime.PARAMETER_PERSON)) {
runtime.parameters.put(Runtime.PARAMETER_PERSON, effectivePerson.getDistinguishedName());
}
......@@ -52,7 +52,7 @@ abstract class BaseAction extends StandardJaxrsAction {
if (keys.contains(Runtime.PARAMETER_ROLELIST)) {
runtime.parameters.put(Runtime.PARAMETER_ROLELIST,
business.organization().role().listWithPerson(effectivePerson));
}
}*/
return runtime;
}
......
package com.x.query.assemble.surface.jaxrs.statement;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.*;
import javax.ws.rs.container.AsyncResponse;
import javax.ws.rs.container.Suspended;
import javax.ws.rs.core.Context;
......@@ -23,6 +19,8 @@ import com.x.base.core.project.jaxrs.StandardJaxrsAction;
import com.x.base.core.project.logger.Logger;
import com.x.base.core.project.logger.LoggerFactory;
import java.util.List;
@Path("statement")
@JaxrsDescribe("语句")
public class StatementAction extends StandardJaxrsAction {
......@@ -49,4 +47,63 @@ public class StatementAction extends StandardJaxrsAction {
asyncResponse.resume(ResponseFactory.getEntityTagActionResultResponse(request, result));
}
@JaxrsMethodDescribe(value = "根据查询列示语句对象.", action = ActionListWithQuery.class)
@GET
@Path("list/query/{queryFlag}")
@Produces(HttpMediaType.APPLICATION_JSON_UTF_8)
@Consumes(MediaType.APPLICATION_JSON)
public void listWithQuery(@Suspended final AsyncResponse asyncResponse, @Context HttpServletRequest request,
@JaxrsParameterDescribe("查询标识") @PathParam("queryFlag") String queryFlag,
@JaxrsParameterDescribe("是否只查询select语句") @QueryParam("justSelect") Boolean justSelect,
@JaxrsParameterDescribe("是否只查询含有视图的语句") @QueryParam("hasView") Boolean hasView) {
ActionResult<List<ActionListWithQuery.Wo>> result = new ActionResult<>();
EffectivePerson effectivePerson = this.effectivePerson(request);
try {
result = new ActionListWithQuery().execute(effectivePerson, queryFlag, justSelect, hasView);
} catch (Exception e) {
logger.error(e, effectivePerson, request, null);
result.error(e);
}
asyncResponse.resume(ResponseFactory.getEntityTagActionResultResponse(request, result));
}
@JaxrsMethodDescribe(value = "获取语句内容.", 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));
}
@JaxrsMethodDescribe(value = "执行语句V2,可以同时执行查询结果及查询总数.", action = ActionExecuteV2.class)
@POST
@Path("{flag}/execute/mode/{mode}page/{page}/size/{size}")
@Produces(HttpMediaType.APPLICATION_JSON_UTF_8)
@Consumes(MediaType.APPLICATION_JSON)
public void executeV2(@Suspended final AsyncResponse asyncResponse, @Context HttpServletRequest request,
@JaxrsParameterDescribe("标识") @PathParam("flag") String flag,
@JaxrsParameterDescribe("执行模式:data|count|all") @PathParam("mode") String mode,
@JaxrsParameterDescribe("页码") @PathParam("page") Integer page,
@JaxrsParameterDescribe("每页数量") @PathParam("size") Integer size, JsonElement jsonElement) {
ActionResult<Object> result = new ActionResult<>();
EffectivePerson effectivePerson = this.effectivePerson(request);
try {
result = new ActionExecuteV2().execute(effectivePerson, flag, mode, page, size, jsonElement);
} catch (Exception e) {
logger.error(e, effectivePerson, request, jsonElement);
result.error(e);
}
asyncResponse.resume(ResponseFactory.getEntityTagActionResultResponse(request, result));
}
}
\ No newline at end of file
......@@ -49,6 +49,9 @@ public class Statement extends SliceJpaObject {
public static final String TYPE_UPDATE = "update";
public static final String TYPE_INSERT = "insert";
public static final String MODE_DATA = "data";
public static final String MODE_COUNT = "count";
public static final String FORMAT_JPQL = "jpql";
public static final String FORMAT_SCRIPT = "script";
......@@ -153,7 +156,7 @@ public class Statement extends SliceJpaObject {
@FieldDescribe("jpql语句.")
@Lob
@Basic(fetch = FetchType.EAGER)
@Column(length = JpaObject.length_10M, name = ColumnNamePrefix + data_FIELDNAME)
@Column(length = JpaObject.length_4K, name = ColumnNamePrefix + data_FIELDNAME)
@CheckPersist(allowEmpty = true)
private String data;
......@@ -161,10 +164,34 @@ public class Statement extends SliceJpaObject {
@FieldDescribe("类型为script的执行脚本.")
@Lob
@Basic(fetch = FetchType.EAGER)
@Column(length = JpaObject.length_10M, name = ColumnNamePrefix + scriptText_FIELDNAME)
@Column(length = JpaObject.length_32K, name = ColumnNamePrefix + scriptText_FIELDNAME)
@CheckPersist(allowEmpty = true)
private String scriptText;
public static final String countData_FIELDNAME = "countData";
@FieldDescribe("jpql语句,用于查询总数.")
@Lob
@Basic(fetch = FetchType.EAGER)
@Column(length = JpaObject.length_4K, name = ColumnNamePrefix + countData_FIELDNAME)
@CheckPersist(allowEmpty = true)
private String countData;
public static final String countScriptText_FIELDNAME = "countScriptText";
@FieldDescribe("类型为script的执行脚本,用于查询总数.")
@Lob
@Basic(fetch = FetchType.EAGER)
@Column(length = JpaObject.length_32K, name = ColumnNamePrefix + countScriptText_FIELDNAME)
@CheckPersist(allowEmpty = true)
private String countScriptText;
public static final String view_FIELDNAME = "view";
@FieldDescribe("展现视图.")
@Lob
@Basic(fetch = FetchType.EAGER)
@Column(length = JpaObject.length_32K, name = ColumnNamePrefix + view_FIELDNAME)
@CheckPersist(allowEmpty = true)
private String view;
public static final String creatorPerson_FIELDNAME = "creatorPerson";
@FieldDescribe("创建者")
@CheckPersist(allowEmpty = false)
......@@ -202,6 +229,20 @@ public class Statement extends SliceJpaObject {
@CheckPersist(allowEmpty = true)
private String entityCategory;
public static final String testParameters_FIELDNAME = "testParameters";
@FieldDescribe("测试参数(json格式文本).")
@Lob
@Basic(fetch = FetchType.EAGER)
@Column(length = JpaObject.length_4K, name = ColumnNamePrefix + testParameters_FIELDNAME)
@CheckPersist(allowEmpty = true)
private String testParameters;
public static final String anonymousAccessible_FIELDNAME = "anonymousAccessible";
@FieldDescribe("是否允许匿名访问(boolean类型)")
@CheckPersist(allowEmpty = true)
@Column(name = ColumnNamePrefix + anonymousAccessible_FIELDNAME)
private Boolean anonymousAccessible;
public void setEntityCategory(String entityCategory) {
this.entityCategory = entityCategory;
}
......@@ -322,4 +363,43 @@ public class Statement extends SliceJpaObject {
this.query = query;
}
public String getCountData() {
return countData;
}
public void setCountData(String countData) {
this.countData = countData;
}
public String getCountScriptText() {
return countScriptText;
}
public void setCountScriptText(String countScriptText) {
this.countScriptText = countScriptText;
}
public String getView() {
return view;
}
public void setView(String view) {
this.view = view;
}
public String getTestParameters() {
return testParameters;
}
public void setTestParameters(String testParameters) {
this.testParameters = testParameters;
}
public Boolean getAnonymousAccessible() {
return anonymousAccessible;
}
public void setAnonymousAccessible(Boolean anonymousAccessible) {
this.anonymousAccessible = anonymousAccessible;
}
}
\ No newline at end of file
......@@ -10,8 +10,8 @@ public abstract class Comparison {
private static String[] lessThan = new String[] { "lessThan", "<" };
private static String[] lessThanOrEqualTo = new String[] { "lessThanOrEqualTo", "<=" };
private static String[] like = new String[] { "like" };
private static String[] notLike = new String[] { "notLike" };
private static String[] between = new String[] { "between", "range" };
private static String[] notLike = new String[] { "notLike", "not like" };
private static String[] between = new String[] { "range", "between" };
public static boolean isEquals(String comparison) throws Exception {
for (String str : equals) {
......@@ -93,4 +93,31 @@ public abstract class Comparison {
}
return false;
}
public static String getMatchCom(String comparison) throws Exception {
if(isNotEquals(comparison)){
return notEquals[notEquals.length-1];
}else if(isGreaterThan(comparison)){
return greaterThan[greaterThan.length-1];
}else if(isGreaterThanOrEqualTo(comparison)){
return greaterThanOrEqualTo[greaterThanOrEqualTo.length-1];
}else if(isLessThan(comparison)){
return lessThan[lessThan.length-1];
}else if(isLessThanOrEqualTo(comparison)){
return lessThanOrEqualTo[lessThanOrEqualTo.length-1];
}else if(isLike(comparison)){
return like[like.length-1];
}else if(isNotLike(comparison)){
return notLike[notLike.length-1];
}else{
return equals[equals.length-1];
}
}
}
\ No newline at end of file
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册