Browse Source

无JIRA任务 替换用于JS格式化的JS引擎,解决大文本的JS格式化CPU飙升

bugfix/10.0
richie 6 years ago
parent
commit
386932dd7c
  1. 24
      designer-base/src/main/java/com/fr/design/javascript/beautify/JavaScriptFormatHelper.java

24
designer-base/src/main/java/com/fr/design/javascript/beautify/JavaScriptFormatHelper.java

@ -1,9 +1,14 @@
package com.fr.design.javascript.beautify; package com.fr.design.javascript.beautify;
import com.eclipsesource.v8.V8;
import com.eclipsesource.v8.V8Array;
import com.eclipsesource.v8.V8Object;
import com.eclipsesource.v8.utils.V8ObjectUtils;
import com.fr.log.FineLoggerFactory; import com.fr.log.FineLoggerFactory;
import com.fr.general.IOUtils; import com.fr.general.IOUtils;
import com.fr.script.ScriptFactory; import com.fr.script.ScriptFactory;
import com.fr.stable.EncodeConstants;
import javax.script.Invocable; import javax.script.Invocable;
import javax.script.ScriptEngine; import javax.script.ScriptEngine;
@ -11,6 +16,7 @@ import javax.script.ScriptException;
import java.io.InputStream; import java.io.InputStream;
import java.io.InputStreamReader; import java.io.InputStreamReader;
import java.io.Reader; import java.io.Reader;
import java.io.UnsupportedEncodingException;
public class JavaScriptFormatHelper { public class JavaScriptFormatHelper {
@ -34,15 +40,21 @@ public class JavaScriptFormatHelper {
*/ */
public static String beautify(String jsCode, BeautifyOption option) { public static String beautify(String jsCode, BeautifyOption option) {
InputStream resourceAsStream = IOUtils.readResource("com/fr/design/javascript/beautify/beautify.js"); InputStream resourceAsStream = IOUtils.readResource("com/fr/design/javascript/beautify/beautify.js");
ScriptEngine scriptEngine = ScriptFactory.newScriptEngine();
String result = jsCode; String result = jsCode;
V8 v8 = V8.createV8Runtime();
try { try {
Reader reader = new InputStreamReader(resourceAsStream); v8.executeVoidScript(IOUtils.inputStream2String(resourceAsStream, EncodeConstants.ENCODING_UTF_8));
scriptEngine.eval(reader); V8Array parameters = new V8Array(v8);
Invocable invocable = (Invocable) scriptEngine; parameters.push(jsCode);
result = (String) invocable.invokeFunction("js_beautify_global", jsCode, option.toFormatArgument()); V8Object arg = V8ObjectUtils.toV8Object(v8, option.toFormatArgument());
} catch (ScriptException | NoSuchMethodException e) { parameters.push(arg);
result = v8.executeStringFunction("js_beautify_global", parameters);
parameters.release();
arg.release();
} catch (UnsupportedEncodingException e) {
FineLoggerFactory.getLogger().error(e.getMessage(), e); FineLoggerFactory.getLogger().error(e.getMessage(), e);
} finally {
v8.release(true);
} }
return result; return result;
} }

Loading…
Cancel
Save