提交 65615621 编写于 作者: O o2null

Merge branch 'feature/removeNashorn' into 'wrdp'

invoke update to ScriptingFactory

See merge request o2oa/o2oa!6211
......@@ -2,6 +2,8 @@ package com.x.base.core.project.config;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Path;
......@@ -518,7 +520,7 @@ public class Config {
INSTANCE = null;
}
private static synchronized Config instance() throws Exception {
private static synchronized Config instance() {
if (null == INSTANCE) {
INSTANCE = new Config();
}
......@@ -752,33 +754,24 @@ public class Config {
return instance().dumpRestoreData;
}
public String initialScriptText;
private String initialScriptText;
public static synchronized String initialScriptText() throws Exception {
public static synchronized String initialScriptText() throws IOException, URISyntaxException {
if (null == instance().initialScriptText) {
instance().initialScriptText = BaseTools.readString(PATH_COMMONS_INITIALSCRIPTTEXT);
}
return instance().initialScriptText;
}
public String initialServiceScriptText;
private String initialServiceScriptText;
public static synchronized String initialServiceScriptText() throws Exception {
public static synchronized String initialServiceScriptText() throws IOException, URISyntaxException {
if (null == instance().initialServiceScriptText) {
instance().initialServiceScriptText = BaseTools.readString(PATH_COMMONS_INITIALSERVICESCRIPTTEXT);
}
return instance().initialServiceScriptText;
}
public String mooToolsScriptText;
public static synchronized String mooToolsScriptText() throws Exception {
if (null == instance().mooToolsScriptText) {
instance().mooToolsScriptText = BaseTools.readString(PATH_COMMONS_MOOTOOLSSCRIPTTEXT);
}
return instance().mooToolsScriptText;
}
private MimeTypes mimeTypes;
public static synchronized MimeTypes mimeTypes() throws Exception {
......
......@@ -8,7 +8,7 @@ public class WoSeeOther extends GsonPropertyObject {
public WoSeeOther() {
}
public WoSeeOther(String url) throws Exception {
public WoSeeOther(String url) {
this.url = url;
}
......
......@@ -8,7 +8,7 @@ public class WoTemporaryRedirect extends GsonPropertyObject {
public WoTemporaryRedirect() {
}
public WoTemporaryRedirect(String url) throws Exception {
public WoTemporaryRedirect(String url) {
this.url = url;
}
......
......@@ -5,7 +5,6 @@ import java.util.ArrayList;
import java.util.List;
import java.util.Map.Entry;
import java.util.Objects;
import java.util.Optional;
import javax.script.CompiledScript;
import javax.script.ScriptContext;
......@@ -15,7 +14,9 @@ import org.apache.commons.lang3.StringUtils;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonNull;
import com.google.gson.JsonObject;
import com.google.gson.JsonPrimitive;
import com.google.gson.reflect.TypeToken;
import com.x.base.core.entity.JpaObject;
import com.x.base.core.project.gson.XGsonBuilder;
......@@ -28,219 +29,185 @@ public class JsonScriptingExecutor {
// nothing
}
private static Logger logger = LoggerFactory.getLogger(JsonScriptingExecutor.class);
private static final Logger LOGGER = LoggerFactory.getLogger(JsonScriptingExecutor.class);
private static Type stringsType = new TypeToken<ArrayList<String>>() {
}.getType();
public static Optional<JsonElement> jsonElement(CompiledScript cs, ScriptContext scriptContext) {
/**
* 将脚本运行后的对象toJson成JsonElement返回.
*
* @param cs
* @param scriptContext
* @return null 将返回JsonNull
*/
public static JsonElement jsonElement(CompiledScript cs, ScriptContext scriptContext) {
Objects.requireNonNull(cs);
Objects.requireNonNull(scriptContext);
JsonElement jsonElement = JsonNull.INSTANCE;
try {
Object o = cs.eval(scriptContext);
String json = Objects.toString(o, "");
JsonElement element = XGsonBuilder.instance().fromJson(json, JsonElement.class);
if (null != element && (!element.isJsonNull())) {
return Optional.of(element);
}
jsonElement = XGsonBuilder.instance().toJsonTree(o);
} catch (ScriptException e) {
logger.error(e);
LOGGER.error(e);
}
return Optional.empty();
return jsonElement;
}
public static void jsonElement(CompiledScript cs, ScriptContext scriptContext, Consumer<JsonElement> consumer) {
Optional<JsonElement> optional = jsonElement(cs, scriptContext);
if (optional.isPresent()) {
consumer.accept(optional.get());
}
consumer.accept(jsonElement(cs, scriptContext));
}
public static Optional<JsonArray> jsonArray(CompiledScript cs, ScriptContext scriptContext) {
Optional<JsonElement> optional = jsonElement(cs, scriptContext);
if (optional.isPresent() && optional.get().isJsonArray()) {
JsonArray jsonArray = optional.get().getAsJsonArray();
if ((null != jsonArray) && (jsonArray.size() > 0)) {
return Optional.of(jsonArray);
}
public static JsonArray jsonArray(CompiledScript cs, ScriptContext scriptContext) {
JsonElement jsonElement = jsonElement(cs, scriptContext);
if (jsonElement.isJsonArray()) {
return jsonElement.getAsJsonArray();
}
return Optional.of(new JsonArray());
return new JsonArray();
}
public static void jsonArray(CompiledScript cs, ScriptContext scriptContext, Consumer<JsonArray> consumer) {
Optional<JsonArray> optional = jsonArray(cs, scriptContext);
consumer.accept(optional.get());
consumer.accept(jsonArray(cs, scriptContext));
}
public static Optional<JsonObject> jsonObject(CompiledScript cs, ScriptContext scriptContext) {
Optional<JsonElement> optional = jsonElement(cs, scriptContext);
if (optional.isPresent() && optional.get().isJsonObject()) {
JsonObject jsonObject = optional.get().getAsJsonObject();
if (null != jsonObject) {
return Optional.of(jsonObject);
}
public static JsonObject jsonObject(CompiledScript cs, ScriptContext scriptContext) {
JsonElement jsonElement = jsonElement(cs, scriptContext);
if (jsonElement.isJsonObject()) {
return jsonElement.getAsJsonObject();
}
return Optional.empty();
return new JsonObject();
}
public static void jsonObject(CompiledScript cs, ScriptContext scriptContext, Consumer<JsonObject> consumer) {
Optional<JsonObject> optional = jsonObject(cs, scriptContext);
if (optional.isPresent()) {
consumer.accept(optional.get().getAsJsonObject());
}
consumer.accept(jsonObject(cs, scriptContext));
}
public static Optional<String> evalString(CompiledScript cs, ScriptContext scriptContext) {
Optional<JsonElement> optional = jsonElement(cs, scriptContext);
if (optional.isPresent() && optional.get().isJsonPrimitive()) {
String value = optional.get().getAsJsonPrimitive().getAsString();
if (StringUtils.isNotEmpty(value)) {
return Optional.of(value);
}
public static String evalString(CompiledScript cs, ScriptContext scriptContext) {
JsonElement jsonElement = jsonElement(cs, scriptContext);
if (jsonElement.isJsonPrimitive()) {
return jsonElement.getAsString();
}
return Optional.empty();
return null;
}
public static void evalString(CompiledScript cs, ScriptContext scriptContext, Consumer<String> consumer) {
Optional<String> optional = evalString(cs, scriptContext);
if (optional.isPresent()) {
consumer.accept(optional.get());
}
consumer.accept(evalString(cs, scriptContext));
}
public static Optional<Integer> evalInteger(CompiledScript cs, ScriptContext scriptContext) {
Optional<JsonElement> optional = jsonElement(cs, scriptContext);
if (optional.isPresent() && optional.get().isJsonPrimitive()) {
Integer value = optional.get().getAsJsonPrimitive().getAsInt();
if (null != value) {
return Optional.of(value);
public static Integer evalInteger(CompiledScript cs, ScriptContext scriptContext) {
JsonElement jsonElement = jsonElement(cs, scriptContext);
if (jsonElement.isJsonPrimitive()) {
JsonPrimitive jsonPrimitive = jsonElement.getAsJsonPrimitive();
if (jsonPrimitive.isNumber()) {
return jsonPrimitive.getAsInt();
}
}
return Optional.empty();
return null;
}
public static void evalInteger(CompiledScript cs, ScriptContext scriptContext, Consumer<Integer> consumer) {
Optional<Integer> optional = evalInteger(cs, scriptContext);
if (optional.isPresent()) {
consumer.accept(optional.get());
}
consumer.accept(evalInteger(cs, scriptContext));
}
public static Optional<Double> evalDouble(CompiledScript cs, ScriptContext scriptContext) {
Optional<JsonElement> optional = jsonElement(cs, scriptContext);
if (optional.isPresent() && optional.get().isJsonPrimitive()) {
Double value = optional.get().getAsJsonPrimitive().getAsDouble();
if (null != value) {
return Optional.of(value);
public static Double evalDouble(CompiledScript cs, ScriptContext scriptContext) {
JsonElement jsonElement = jsonElement(cs, scriptContext);
if (jsonElement.isJsonPrimitive()) {
JsonPrimitive jsonPrimitive = jsonElement.getAsJsonPrimitive();
if (jsonPrimitive.isNumber()) {
return jsonPrimitive.getAsDouble();
}
}
return Optional.empty();
return null;
}
public static void evalDouble(CompiledScript cs, ScriptContext scriptContext, Consumer<Double> consumer) {
Optional<Double> optional = evalDouble(cs, scriptContext);
if (optional.isPresent()) {
consumer.accept(optional.get());
}
consumer.accept(evalDouble(cs, scriptContext));
}
public static Optional<Float> evalFloat(CompiledScript cs, ScriptContext scriptContext) {
Optional<JsonElement> optional = jsonElement(cs, scriptContext);
if (optional.isPresent() && optional.get().isJsonPrimitive()) {
Float value = optional.get().getAsJsonPrimitive().getAsFloat();
if (null != value) {
return Optional.of(value);
public static Float evalFloat(CompiledScript cs, ScriptContext scriptContext) {
JsonElement jsonElement = jsonElement(cs, scriptContext);
if (jsonElement.isJsonPrimitive()) {
JsonPrimitive jsonPrimitive = jsonElement.getAsJsonPrimitive();
if (jsonPrimitive.isNumber()) {
return jsonPrimitive.getAsFloat();
}
}
return Optional.empty();
return null;
}
public static void evalFloat(CompiledScript cs, ScriptContext scriptContext, Consumer<Float> consumer) {
Optional<Float> optional = evalFloat(cs, scriptContext);
if (optional.isPresent()) {
consumer.accept(optional.get());
}
consumer.accept(evalFloat(cs, scriptContext));
}
public static Optional<Number> evalNumber(CompiledScript cs, ScriptContext scriptContext) {
Optional<JsonElement> optional = jsonElement(cs, scriptContext);
if (optional.isPresent() && optional.get().isJsonPrimitive()) {
Number value = optional.get().getAsJsonPrimitive().getAsNumber();
if (null != value) {
return Optional.of(value);
public static Number evalNumber(CompiledScript cs, ScriptContext scriptContext) {
JsonElement jsonElement = jsonElement(cs, scriptContext);
if (jsonElement.isJsonPrimitive()) {
JsonPrimitive jsonPrimitive = jsonElement.getAsJsonPrimitive();
if (jsonPrimitive.isNumber()) {
return jsonPrimitive.getAsNumber();
}
}
return Optional.empty();
return null;
}
public static void evalNumber(CompiledScript cs, ScriptContext scriptContext, Consumer<Number> consumer) {
Optional<Number> optional = evalNumber(cs, scriptContext);
if (optional.isPresent()) {
consumer.accept(optional.get());
}
}
public static Optional<Boolean> evalBoolean(CompiledScript cs, ScriptContext scriptContext) {
Optional<JsonElement> optional = jsonElement(cs, scriptContext);
if (optional.isPresent() && optional.get().isJsonPrimitive()) {
Boolean value = optional.get().getAsJsonPrimitive().getAsBoolean();
if (null != value) {
return Optional.of(value);
consumer.accept(evalNumber(cs, scriptContext));
}
/**
* 非boolean值或者null返回Boolean.FALSE
*
* @param cs
* @param scriptContext
* @return
*/
public static Boolean evalBoolean(CompiledScript cs, ScriptContext scriptContext) {
JsonElement jsonElement = jsonElement(cs, scriptContext);
if (jsonElement.isJsonPrimitive()) {
JsonPrimitive jsonPrimitive = jsonElement.getAsJsonPrimitive();
if (jsonPrimitive.isBoolean()) {
return jsonPrimitive.getAsBoolean();
}
}
return Optional.empty();
return Boolean.FALSE;
}
public static void evalBoolean(CompiledScript cs, ScriptContext scriptContext, Consumer<Boolean> consumer) {
Optional<Boolean> optional = evalBoolean(cs, scriptContext);
if (optional.isPresent()) {
consumer.accept(optional.get());
}
consumer.accept(evalBoolean(cs, scriptContext));
}
public static Optional<List<String>> evalStrings(CompiledScript cs, ScriptContext scriptContext) {
Optional<JsonElement> optional = jsonElement(cs, scriptContext);
if (optional.isPresent() && optional.get().isJsonArray()) {
List<String> list = XGsonBuilder.instance().fromJson(optional.get(), stringsType);
if (!list.isEmpty()) {
return Optional.of(list);
}
public static List<String> evalStrings(CompiledScript cs, ScriptContext scriptContext) {
JsonElement jsonElement = jsonElement(cs, scriptContext);
if (jsonElement.isJsonArray()) {
return XGsonBuilder.instance().fromJson(jsonElement, stringsType);
}
return Optional.of(new ArrayList<>());
return new ArrayList<>();
}
public static void evalStrings(CompiledScript cs, ScriptContext scriptContext, Consumer<List<String>> consumer) {
Optional<List<String>> optional = evalStrings(cs, scriptContext);
consumer.accept(optional.get());
consumer.accept(evalStrings(cs, scriptContext));
}
public static Optional<List<String>> evalDistinguishedNames(CompiledScript cs, ScriptContext scriptContext) {
public static List<String> evalDistinguishedNames(CompiledScript cs, ScriptContext scriptContext) {
List<String> list = new ArrayList<>();
Optional<JsonElement> optional = jsonElement(cs, scriptContext);
if (optional.isPresent()) {
if (optional.get().isJsonObject()) {
dfsDistinguishedNames(optional.get().getAsJsonObject(), list);
} else if (optional.get().isJsonArray()) {
for (JsonElement element : optional.get().getAsJsonArray()) {
if (element.isJsonPrimitive() && element.getAsJsonPrimitive().isString()) {
list.add(element.getAsJsonPrimitive().getAsString());
} else if (element.isJsonObject()) {
dfsDistinguishedNames(element.getAsJsonObject(), list);
}
JsonElement jsonElement = jsonElement(cs, scriptContext);
if (jsonElement.isJsonObject()) {
dfsDistinguishedNames(jsonElement.getAsJsonObject(), list);
} else if (jsonElement.isJsonArray()) {
for (JsonElement element : jsonElement.getAsJsonArray()) {
if (element.isJsonPrimitive() && element.getAsJsonPrimitive().isString()) {
list.add(element.getAsJsonPrimitive().getAsString());
} else if (element.isJsonObject()) {
dfsDistinguishedNames(element.getAsJsonObject(), list);
}
}
if (!list.isEmpty()) {
return Optional.of(list);
}
}
return Optional.of(new ArrayList<>());
return list;
}
public static void evalDistinguishedNames(CompiledScript cs, ScriptContext scriptContext,
Consumer<List<String>> consumer) {
Optional<List<String>> optional = evalDistinguishedNames(cs, scriptContext);
consumer.accept(optional.get());
consumer.accept(evalDistinguishedNames(cs, scriptContext));
}
private static void dfsDistinguishedNames(JsonObject jsonObject, List<String> list) {
......@@ -256,41 +223,33 @@ public class JsonScriptingExecutor {
}
}
public static <T> Optional<T> eval(CompiledScript cs, ScriptContext scriptContext, Class<T> clz) {
Optional<JsonElement> optional = jsonElement(cs, scriptContext);
if (optional.isPresent()) {
return Optional.of(XGsonBuilder.instance().fromJson(optional.get(), clz));
public static void eval(CompiledScript cs, ScriptContext scriptContext) {
Objects.requireNonNull(cs);
Objects.requireNonNull(scriptContext);
try {
cs.eval(scriptContext);
} catch (ScriptException e) {
LOGGER.error(e);
}
return Optional.empty();
}
public static <T> Optional<T> eval(CompiledScript cs, ScriptContext scriptContext, Supplier<T> supplier) {
Optional<JsonElement> optional = jsonElement(cs, scriptContext);
if (optional.isPresent()) {
T t = supplier.get(optional.get());
if (null != t) {
return Optional.of(t);
}
}
return Optional.empty();
public static <T> T eval(CompiledScript cs, ScriptContext scriptContext, Class<T> clz) {
return XGsonBuilder.instance().fromJson(jsonElement(cs, scriptContext), clz);
}
public static <T> T eval(CompiledScript cs, ScriptContext scriptContext, Supplier<T> supplier) {
JsonElement jsonElement = jsonElement(cs, scriptContext);
return supplier.get(jsonElement);
}
public static <T> void eval(CompiledScript cs, ScriptContext scriptContext, Class<T> clz, Consumer<T> consumer) {
Optional<T> optional = eval(cs, scriptContext, clz);
if (optional.isPresent()) {
consumer.accept(optional.get());
}
T t = eval(cs, scriptContext, clz);
consumer.accept(t);
}
public static <T> void eval(CompiledScript cs, ScriptContext scriptContext, Supplier<T> supplier,
Consumer<T> consumer) {
Optional<JsonElement> optional = jsonElement(cs, scriptContext);
if (optional.isPresent()) {
T t = supplier.get(optional.get());
if (null != t) {
consumer.accept(t);
}
}
consumer.accept(supplier.get(jsonElement(cs, scriptContext)));
}
}
}
\ No newline at end of file
package com.x.base.core.project.scripting;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.Objects;
import javax.script.Compilable;
import javax.script.CompiledScript;
import javax.script.ScriptContext;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import javax.script.SimpleScriptContext;
import com.x.base.core.project.config.Config;
import com.x.base.core.project.logger.Logger;
......@@ -14,7 +18,7 @@ import com.x.base.core.project.logger.LoggerFactory;
public class ScriptingFactory {
private static Logger logger = LoggerFactory.getLogger(ScriptingFactory.class);
private static final Logger LOGGER = LoggerFactory.getLogger(ScriptingFactory.class);
private ScriptingFactory() {
......@@ -55,11 +59,16 @@ public class ScriptingFactory {
public static final String BINDING_NAME_SERIAL = "serial";
public static final String BINDING_NAME_PROCESS = "process";
public static final String BINDING_NAME_REQUESTTEXT = "requestText";
public static final String BINDING_NAME_REQUEST = "request";
public static final String BINDING_NAME_CUSTOMRESPONSE = "customResponse";
public static ScriptEngine newScriptEngine() {
return (new ScriptEngineManager()).getEngineByName(Config.SCRIPTING_ENGINE_NAME);
}
public static synchronized CompiledScript initialServiceScriptText() throws Exception {
public static synchronized CompiledScript initialServiceScript()
throws IOException, ScriptException, URISyntaxException {
if (compiledScriptInitialServiceScriptText == null) {
String text = Config.initialServiceScriptText();
compiledScriptInitialServiceScriptText = ((Compilable) scriptEngine).compile(text);
......@@ -67,7 +76,7 @@ public class ScriptingFactory {
return compiledScriptInitialServiceScriptText;
}
public static synchronized CompiledScript initialScriptText() throws Exception {
public static synchronized CompiledScript initialScript() throws IOException, ScriptException, URISyntaxException {
if (compiledScriptInitialScriptText == null) {
String text = Config.initialScriptText();
compiledScriptInitialScriptText = ((Compilable) scriptEngine).compile(text);
......@@ -83,7 +92,7 @@ public class ScriptingFactory {
StringBuilder sb = new StringBuilder();
sb.append("JSON.stringify((function(){").append(System.lineSeparator());
sb.append(Objects.toString(text, "")).append(System.lineSeparator());
sb.append("})());");
sb.append("}).apply(this));");
return sb.toString();
}
......@@ -91,4 +100,24 @@ public class ScriptingFactory {
return ((Compilable) scriptEngine).compile(functionalization(text));
}
public static ScriptContext scriptContextEvalInitialServiceScript() {
ScriptContext scriptContext = new SimpleScriptContext();
try {
ScriptingFactory.initialServiceScript().eval(scriptContext);
} catch (ScriptException | URISyntaxException | IOException e) {
LOGGER.error(e);
}
return scriptContext;
}
public static ScriptContext scriptContextEvalInitialScript() {
ScriptContext scriptContext = new SimpleScriptContext();
try {
ScriptingFactory.initialScript().eval(scriptContext);
} catch (ScriptException | URISyntaxException | IOException e) {
LOGGER.error(e);
}
return scriptContext;
}
}
\ No newline at end of file
......@@ -159,20 +159,19 @@ public class BaseTools {
FileUtils.writeStringToFile(file, StringUtils.trim(value), DefaultCharset.charset);
}
public static byte[] readBytes(String path) throws Exception {
public static byte[] readBytes(String path) throws IOException, URISyntaxException {
String base = BaseTools.getBasePath();
File file = new File(base, path);
if ((!file.exists()) || file.isDirectory()) {
throw new Exception("can not get file with path:" + file.getAbsolutePath());
throw new IOException("can not get file with path:" + file.getAbsolutePath());
}
return FileUtils.readFileToByteArray(file);
}
public static String readString(String path) throws Exception {
public static String readString(String path) throws IOException, URISyntaxException {
String base = BaseTools.getBasePath();
File file = new File(base, path);
if ((!file.exists()) || file.isDirectory()) {
// throw new Exception("can not get file with path:" + file.getAbsolutePath());
return null;
}
return FileUtils.readFileToString(file, DefaultCharset.charset);
......
package com.x.program.center.jaxrs.invoke;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
import com.google.gson.JsonElement;
import com.x.base.core.project.cache.Cache.CacheCategory;
......@@ -19,11 +15,13 @@ import com.x.program.center.core.entity.Invoke;
class ActionExecute extends BaseAction {
private static Logger logger = LoggerFactory.getLogger(ActionExecute.class);
private static final Logger LOGGER = LoggerFactory.getLogger(ActionExecute.class);
ActionResult<Object> execute(HttpServletRequest request, EffectivePerson effectivePerson, String flag,
JsonElement jsonElement) throws Exception {
LOGGER.debug("{} invoke :{}.", effectivePerson.getDistinguishedName(), flag);
CacheCategory cacheCategory = new CacheCategory(Invoke.class);
Invoke invoke = this.get(cacheCategory, flag);
......@@ -32,21 +30,16 @@ class ActionExecute extends BaseAction {
throw new ExceptionEntityNotExist(flag, Invoke.class);
}
if (!BooleanUtils.isTrue(invoke.getEnable())) {
throw new ExceptionNotEnable(invoke.getName());
}
checkEnable(invoke);
checkRemoteAddrRegex(request, invoke);
if (StringUtils.isNotEmpty(invoke.getRemoteAddrRegex())) {
Matcher matcher = Pattern.compile(invoke.getRemoteAddrRegex()).matcher(request.getRemoteAddr());
if (!matcher.find()) {
throw new ExceptionInvalidRemoteAddr(request.getRemoteAddr(), invoke.getName());
}
}
if (BooleanUtils.isTrue(invoke.getEnableToken())) {
throw new ExceptionEnableToken(invoke.getName());
}
return executeInvoke(request, effectivePerson, jsonElement, cacheCategory, invoke);
}
}
\ No newline at end of file
package com.x.program.center.jaxrs.invoke;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
import com.google.gson.JsonElement;
......@@ -23,17 +21,21 @@ import com.x.base.core.project.http.EffectivePerson;
import com.x.base.core.project.logger.Logger;
import com.x.base.core.project.logger.LoggerFactory;
import com.x.base.core.project.tools.Crypto;
import com.x.base.core.project.tools.DefaultCharset;
import com.x.program.center.Business;
import com.x.program.center.core.entity.Invoke;
class ActionExecuteToken extends BaseAction {
private static Logger logger = LoggerFactory.getLogger(ActionExecuteToken.class);
private static final Logger LOGGER = LoggerFactory.getLogger(ActionExecuteToken.class);
// 时间限制
private static final int THRESHOLD = 60000 * 30;
ActionResult<Object> execute(HttpServletRequest request, EffectivePerson effectivePerson, String flag,
String client, String token, JsonElement jsonElement) throws Exception {
LOGGER.debug("{} invoke :{}.", effectivePerson.getDistinguishedName(), flag);
CacheCategory cacheCategory = new CacheCategory(Invoke.class);
Invoke invoke = this.get(cacheCategory, flag);
......@@ -42,47 +44,25 @@ class ActionExecuteToken extends BaseAction {
throw new ExceptionEntityNotExist(flag, Invoke.class);
}
if (!BooleanUtils.isTrue(invoke.getEnable())) {
throw new ExceptionNotEnable(invoke.getName());
}
checkEnable(invoke);
if (StringUtils.isNotEmpty(invoke.getRemoteAddrRegex())) {
Matcher matcher = Pattern.compile(invoke.getRemoteAddrRegex()).matcher(request.getRemoteAddr());
if (!matcher.find()) {
throw new ExceptionInvalidRemoteAddr(request.getRemoteAddr(), invoke.getName());
}
}
checkRemoteAddrRegex(request, invoke);
checkClient(client);
checkToken(token);
if (StringUtils.isEmpty(client)) {
throw new ExceptionClientEmpty();
}
if (StringUtils.isEmpty(token)) {
throw new ExceptionTokenEmpty();
}
Sso sso = Config.token().findSso(client);
if (null == sso) {
throw new ExceptionClientNotExist(client);
}
String content = null;
logger.debug("decrypt sso client:{}, token:{}, key:{}.", client, token, sso.getKey());
try {
content = Crypto.decrypt(token, sso.getKey());
logger.debug("decrypt sso client:{}, token:{}, key:{}, content:{}.", client, token, sso.getKey(), content);
} catch (Exception e) {
throw new ExceptionReadToken(client, token);
}
String content = decrypt(client, token, sso);
checkTimeThreshold(StringUtils.substringAfter(content, SPLIT));
String credential = URLDecoder.decode(StringUtils.substringBefore(content, SPLIT),
DefaultCharset.name_iso_utf_8);
String timeString = StringUtils.substringAfter(content, SPLIT);
StandardCharsets.UTF_8.name());
if (StringUtils.isEmpty(credential)) {
throw new ExceptionEmptyCredential();
}
Date date = new Date(Long.parseLong(timeString));
Date now = new Date();
// 15分钟
if (Math.abs((now.getTime() - date.getTime())) >= (60000 * 15)) {
throw new ExceptionTokenExpired();
}
if ((!StringUtils.equals(EffectivePerson.CIPHER, credential))
&& (!Config.token().isInitialManager(credential))) {
try (EntityManagerContainer emc = EntityManagerContainerFactory.instance().create()) {
......@@ -96,4 +76,24 @@ class ActionExecuteToken extends BaseAction {
return executeInvoke(request, effectivePerson, jsonElement, cacheCategory, invoke);
}
private void checkTimeThreshold(String time) throws ExceptionTokenExpired {
Date date = new Date(Long.parseLong(time));
Date now = new Date();
if (Math.abs((now.getTime() - date.getTime())) >= THRESHOLD) {
throw new ExceptionTokenExpired();
}
}
private String decrypt(String client, String token, Sso sso) throws ExceptionReadToken {
String value = "";
try {
value = Crypto.decrypt(token, sso.getKey());
LOGGER.debug("decrypt sso client:{}, token:{}, key:{}, content:{}.", client::toString, token::toString,
sso::getKey, value::toString);
} catch (Exception e) {
throw new ExceptionReadToken(client, token);
}
return value;
}
}
\ No newline at end of file
......@@ -2,13 +2,16 @@ package com.x.program.center.jaxrs.invoke;
import java.util.Objects;
import java.util.Optional;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.script.Bindings;
import javax.script.CompiledScript;
import javax.script.ScriptContext;
import javax.script.SimpleScriptContext;
import javax.script.ScriptException;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
import com.google.gson.JsonElement;
......@@ -26,7 +29,8 @@ import com.x.base.core.project.jaxrs.WoTemporaryRedirect;
import com.x.base.core.project.jaxrs.WoText;
import com.x.base.core.project.jaxrs.WoValue;
import com.x.base.core.project.script.AbstractResources;
import com.x.base.core.project.script.ScriptFactory;
import com.x.base.core.project.scripting.JsonScriptingExecutor;
import com.x.base.core.project.scripting.ScriptingFactory;
import com.x.base.core.project.webservices.WebservicesClient;
import com.x.organization.core.express.Organization;
import com.x.program.center.ThisApplication;
......@@ -35,51 +39,35 @@ import com.x.program.center.core.entity.Invoke;
abstract class BaseAction extends StandardJaxrsAction {
protected static final String SPLIT = "#";
private static final String SEEOTHER = "seeOther";
private static final String TEMPORARYREDIRECT = "temporaryRedirect";
protected ActionResult<Object> executeInvoke(HttpServletRequest request, EffectivePerson effectivePerson,
JsonElement jsonElement, CacheCategory cacheCategory, Invoke invoke)
throws Exception, ExceptionExecuteError {
JsonElement jsonElement, CacheCategory cacheCategory, Invoke invoke) throws Exception {
ActionResult<Object> result = new ActionResult<>();
CompiledScript compiledScript = this.getCompiledScript(cacheCategory, invoke);
ScriptContext scriptContext = new SimpleScriptContext();
Bindings bindings = scriptContext.getBindings(ScriptContext.ENGINE_SCOPE);
Resources resources = new Resources();
resources.setContext(ThisApplication.context());
resources.setOrganization(new Organization(ThisApplication.context()));
resources.setWebservicesClient(new WebservicesClient());
resources.setApplications(ThisApplication.context().applications());
bindings.put(ScriptFactory.BINDING_NAME_RESOURCES, resources);
bindings.put("requestText", gson.toJson(jsonElement));
bindings.put("request", request);
bindings.put("effectivePerson", effectivePerson);
bindings.put(ScriptFactory.BINDING_NAME_APPLICATIONS, ThisApplication.context().applications());
ScriptContext scriptContext = ScriptingFactory.scriptContextEvalInitialServiceScript();
CustomResponse customResponse = new CustomResponse();
bindings.put("customResponse", customResponse);
binding(request, effectivePerson, jsonElement, scriptContext, customResponse);
Wo wo = new Wo();
try {
ScriptFactory.initialServiceScriptText().eval(scriptContext);
Object o = compiledScript.eval(scriptContext);
if (StringUtils.equals("seeOther", customResponse.type)) {
WoSeeOther woSeeOther = new WoSeeOther(Objects.toString(customResponse.value, ""));
result.setData(woSeeOther);
} else if (StringUtils.equals("temporaryRedirect", customResponse.type)) {
WoTemporaryRedirect woTemporaryRedirect = new WoTemporaryRedirect(
Objects.toString(customResponse.value, ""));
result.setData(woTemporaryRedirect);
} else {
if (null != customResponse.value) {
if (StringUtils.isNotEmpty(customResponse.contentType)) {
result.setData(new WoContentType(customResponse.value, customResponse.contentType));
} else if (customResponse.value instanceof WoText) {
result.setData(customResponse.value);
} else {
wo.setValue(customResponse.value);
result.setData(wo);
}
JsonElement element = JsonScriptingExecutor.jsonElement(compiledScript, scriptContext);
if (StringUtils.equals(SEEOTHER, customResponse.type)) {
seeOther(result, customResponse);
} else if (StringUtils.equals(TEMPORARYREDIRECT, customResponse.type)) {
temporayRedirect(result, customResponse);
} else if (null != customResponse.value) {
if (StringUtils.isNotEmpty(customResponse.contentType)) {
result.setData(new WoContentType(customResponse.value, customResponse.contentType));
} else if (customResponse.value instanceof WoText) {
result.setData(customResponse.value);
} else {
wo.setValue(o);
wo.setValue(customResponse.value);
result.setData(wo);
}
} else {
wo.setValue(element.toString());
result.setData(wo);
}
} catch (Exception e) {
throw new ExceptionExecuteError(invoke.getName(), e);
......@@ -87,14 +75,41 @@ abstract class BaseAction extends StandardJaxrsAction {
return result;
}
protected CompiledScript getCompiledScript(CacheCategory cacheCategory, Invoke invoke) throws Exception {
CacheKey cacheKey = new CacheKey(ActionExecuteToken.class, "CompiledScript", invoke.getId());
private void temporayRedirect(ActionResult<Object> result, CustomResponse customResponse) {
WoTemporaryRedirect woTemporaryRedirect = new WoTemporaryRedirect(Objects.toString(customResponse.value, ""));
result.setData(woTemporaryRedirect);
}
private void seeOther(ActionResult<Object> result, CustomResponse customResponse) {
WoSeeOther woSeeOther = new WoSeeOther(Objects.toString(customResponse.value, ""));
result.setData(woSeeOther);
}
private void binding(HttpServletRequest request, EffectivePerson effectivePerson, JsonElement jsonElement,
ScriptContext scriptContext, CustomResponse customResponse) throws Exception {
Bindings bindings = scriptContext.getBindings(ScriptContext.ENGINE_SCOPE);
Resources resources = new Resources();
resources.setContext(ThisApplication.context());
resources.setOrganization(new Organization(ThisApplication.context()));
resources.setWebservicesClient(new WebservicesClient());
resources.setApplications(ThisApplication.context().applications());
bindings.put(ScriptingFactory.BINDING_NAME_RESOURCES, resources);
bindings.put(ScriptingFactory.BINDING_NAME_REQUESTTEXT, gson.toJson(jsonElement));
bindings.put(ScriptingFactory.BINDING_NAME_REQUEST, request);
bindings.put(ScriptingFactory.BINDING_NAME_EFFECTIVEPERSON, effectivePerson);
bindings.put(ScriptingFactory.BINDING_NAME_APPLICATIONS, ThisApplication.context().applications());
bindings.put(ScriptingFactory.BINDING_NAME_CUSTOMRESPONSE, customResponse);
}
protected CompiledScript getCompiledScript(CacheCategory cacheCategory, Invoke invoke) throws ScriptException {
CacheKey cacheKey = new CacheKey(ActionExecuteToken.class, CompiledScript.class.getSimpleName(),
invoke.getId());
CompiledScript compiledScript = null;
Optional<?> optional = CacheManager.get(cacheCategory, cacheKey);
if (optional.isPresent()) {
compiledScript = (CompiledScript) optional.get();
} else {
compiledScript = ScriptFactory.compile(invoke.getText());
compiledScript = ScriptingFactory.functionalizationCompile(invoke.getText());
CacheManager.put(cacheCategory, cacheKey, compiledScript);
}
return compiledScript;
......@@ -122,12 +137,12 @@ abstract class BaseAction extends StandardJaxrsAction {
protected String contentType;
public void seeOther(String url) {
this.type = "seeOther";
this.type = SEEOTHER;
this.value = url;
}
public void temporaryRedirect(String url) {
this.type = "temporaryRedirect";
this.type = TEMPORARYREDIRECT;
this.value = url;
}
......@@ -161,4 +176,30 @@ abstract class BaseAction extends StandardJaxrsAction {
}
protected void checkEnable(Invoke invoke) throws ExceptionNotEnable {
if (!BooleanUtils.isTrue(invoke.getEnable())) {
throw new ExceptionNotEnable(invoke.getName());
}
}
protected void checkRemoteAddrRegex(HttpServletRequest request, Invoke invoke) throws ExceptionInvalidRemoteAddr {
if (StringUtils.isNotEmpty(invoke.getRemoteAddrRegex())) {
Matcher matcher = Pattern.compile(invoke.getRemoteAddrRegex()).matcher(request.getRemoteAddr());
if (!matcher.find()) {
throw new ExceptionInvalidRemoteAddr(request.getRemoteAddr(), invoke.getName());
}
}
}
protected void checkToken(String token) throws ExceptionTokenEmpty {
if (StringUtils.isEmpty(token)) {
throw new ExceptionTokenEmpty();
}
}
protected void checkClient(String client) throws ExceptionClientEmpty {
if (StringUtils.isEmpty(client)) {
throw new ExceptionClientEmpty();
}
}
}
package com.x.program.center.jaxrs.invoke;
import com.x.base.core.project.exception.LanguagePromptException;
import com.x.base.core.project.exception.PromptException;
class ExceptionClientEmpty extends LanguagePromptException {
......
package com.x.program.center.jaxrs.mpweixin;
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.jaxrs.WoText;
import com.x.base.core.project.logger.Logger;
import com.x.base.core.project.logger.LoggerFactory;
import com.x.program.center.core.entity.MPWeixinMenu;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import java.io.InputStream;
import java.io.StringWriter;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import com.x.base.core.project.http.ActionResult;
import com.x.base.core.project.jaxrs.WoText;
import com.x.base.core.project.logger.Logger;
import com.x.base.core.project.logger.LoggerFactory;
import com.x.program.center.core.entity.MPWeixinMenu;
/**
* 微信公众号接收到消息的处理
* 暂时不做处理
......
......@@ -223,6 +223,7 @@ public class Business {
}
public boolean buildAllTable() throws Exception {
logger.warn("query designer execute build all table command, The server must be restarted immediately.");
boolean result = false;
File dir = new File(Config.dir_local_temp_dynamic(true), StringTools.uniqueToken());
FileUtils.forceMkdir(dir);
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册