Browse Source

无JIRA任务 升级新的JxBrowser+language level提升到1.8

persist/11.0
richie 5 years ago
parent
commit
455caa72fc
  1. 3
      designer-base/src/main/java/com/fr/design/bridge/exec/JSExecutor.java
  2. 18
      designer-base/src/main/java/com/fr/design/dcm/UniversalDatabasePane.java
  3. 12
      designer-base/src/main/java/com/fr/design/dcm/UniversalDcmBridge.java
  4. 68
      designer-base/src/main/java/com/fr/design/ui/Assistant.java
  5. 130
      designer-base/src/main/java/com/fr/design/ui/EmbProtocolHandler.java
  6. 147
      designer-base/src/main/java/com/fr/design/ui/ModernUIPane.java
  7. 85
      designer-base/src/main/java/com/fr/design/ui/NxComplexInterceptRequestCallback.java
  8. 134
      designer-base/src/main/java/com/fr/design/ui/NxInterceptRequestCallback.java
  9. 230
      designer-base/src/main/java/com/fr/design/upm/UpmBridge.java
  10. 2
      designer-base/src/main/java/com/fr/design/upm/UpmFinder.java
  11. 15
      designer-base/src/main/java/com/fr/design/upm/UpmShowPane.java
  12. 15
      designer-base/src/main/java/com/fr/design/upm/exec/UpmBrowserExecutor.java
  13. 4
      pom.xml

3
designer-base/src/main/java/com/fr/design/bridge/exec/JSExecutor.java

@ -4,5 +4,8 @@ package com.fr.design.bridge.exec;
* Created by ibm on 2017/6/21. * Created by ibm on 2017/6/21.
*/ */
public interface JSExecutor { public interface JSExecutor {
String CALLBACK_FUNCTION_NAME = "action";
void executor(String newValue); void executor(String newValue);
} }

18
designer-base/src/main/java/com/fr/design/dcm/UniversalDatabasePane.java

@ -2,9 +2,8 @@ package com.fr.design.dcm;
import com.fr.design.dialog.BasicPane; import com.fr.design.dialog.BasicPane;
import com.fr.design.ui.ModernUIPane; import com.fr.design.ui.ModernUIPane;
import com.teamdev.jxbrowser.chromium.JSValue; import com.teamdev.jxbrowser.browser.callback.InjectJsCallback;
import com.teamdev.jxbrowser.chromium.events.ScriptContextAdapter; import com.teamdev.jxbrowser.js.JsObject;
import com.teamdev.jxbrowser.chromium.events.ScriptContextEvent;
import java.awt.*; import java.awt.*;
@ -26,14 +25,13 @@ public class UniversalDatabasePane extends BasicPane {
setLayout(new BorderLayout()); setLayout(new BorderLayout());
modernUIPane = new ModernUIPane.Builder<>() modernUIPane = new ModernUIPane.Builder<>()
.withComponent(UniversalDatabaseComponent.KEY) .withComponent(UniversalDatabaseComponent.KEY)
.prepare(new ScriptContextAdapter() { .prepare(params -> {
@Override JsObject window = params.frame().executeJavaScript("window");
public void onScriptContextCreated(ScriptContextEvent event) { if (window != null) {
JSValue window = event.getBrowser().executeJavaScriptAndReturnValue("window"); window.putProperty("DcmHelper", UniversalDcmBridge.getBridge());
window.asObject().setProperty("DcmHelper", UniversalDcmBridge.getBridge(event.getBrowser()));
} }
}) return InjectJsCallback.Response.proceed();
.build(); }).build();
add(modernUIPane, BorderLayout.CENTER); add(modernUIPane, BorderLayout.CENTER);
} }
} }

12
designer-base/src/main/java/com/fr/design/dcm/UniversalDcmBridge.java

@ -2,8 +2,6 @@ package com.fr.design.dcm;
import com.fr.decision.webservice.bean.BaseBean; import com.fr.decision.webservice.bean.BaseBean;
import com.fr.design.bridge.exec.JSBridge; import com.fr.design.bridge.exec.JSBridge;
import com.teamdev.jxbrowser.chromium.Browser;
import com.teamdev.jxbrowser.chromium.JSObject;
/** /**
* @author richie * @author richie
@ -13,18 +11,18 @@ import com.teamdev.jxbrowser.chromium.JSObject;
*/ */
public class UniversalDcmBridge { public class UniversalDcmBridge {
public static UniversalDcmBridge getBridge(Browser browser) { public static UniversalDcmBridge getBridge() {
return new UniversalDcmBridge(browser); return new UniversalDcmBridge();
} }
private JSObject window;
private UniversalDcmBridge(Browser browser) { private UniversalDcmBridge() {
this.window = browser.executeJavaScriptAndReturnValue("window").asObject();
} }
/** /**
* 获取所有的数据连接 * 获取所有的数据连接
*
* @return 数据连接集合 * @return 数据连接集合
*/ */
@JSBridge @JSBridge

68
designer-base/src/main/java/com/fr/design/ui/Assistant.java

@ -1,68 +0,0 @@
package com.fr.design.ui;
import com.fr.stable.StringUtils;
import com.teamdev.jxbrowser.chromium.Browser;
import com.teamdev.jxbrowser.chromium.BrowserContext;
import com.teamdev.jxbrowser.chromium.ProtocolService;
import com.teamdev.jxbrowser.chromium.URLResponse;
import javax.activation.MimetypesFileTypeMap;
import java.io.DataInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
/**
* @author richie
* @version 10.0
* Created by richie on 2019-03-07
*/
public class Assistant {
public static URLResponse inputStream2Response(InputStream inputStream, String filePath) throws Exception {
URLResponse response = new URLResponse();
DataInputStream stream = new DataInputStream(inputStream);
byte[] data = new byte[stream.available()];
stream.readFully(data);
response.setData(data);
String mimeType = getMimeType(filePath);
response.getHeaders().setHeader("Content-Type", mimeType);
return response;
}
private static String getMimeType(String path) {
if (StringUtils.isBlank(path)) {
return "text/html";
}
if (path.endsWith(".html")) {
return "text/html";
}
if (path.endsWith(".css")) {
return "text/css";
}
if (path.endsWith(".js")) {
return "text/javascript";
}
if (path.endsWith(".svg")) {
return "image/svg+xml";
}
Path file = new File(path).toPath();
try {
return Files.probeContentType(file);
} catch (IOException e) {
return "text/html";
}
}
public static void setEmbProtocolHandler(Browser browser, EmbProtocolHandler handler) {
BrowserContext browserContext = browser.getContext();
ProtocolService protocolService = browserContext.getProtocolService();
// 支持读取jar包中文件的自定义协议————emb:/com/fr/design/images/bbs.png
protocolService.setProtocolHandler("emb", handler);
protocolService.setProtocolHandler("file", handler);
}
}

130
designer-base/src/main/java/com/fr/design/ui/EmbProtocolHandler.java

@ -1,130 +0,0 @@
package com.fr.design.ui;
import com.fr.base.TemplateUtils;
import com.fr.general.IOUtils;
import com.fr.log.FineLoggerFactory;
import com.fr.stable.EncodeConstants;
import com.fr.stable.StringUtils;
import com.fr.third.org.apache.commons.codec.net.URLCodec;
import com.fr.third.org.apache.commons.io.FileUtils;
import com.fr.third.org.apache.commons.io.FilenameUtils;
import com.fr.web.struct.AssembleComponent;
import com.fr.web.struct.AtomBuilder;
import com.fr.web.struct.PathGroup;
import com.fr.web.struct.category.ScriptPath;
import com.fr.web.struct.category.StylePath;
import com.teamdev.jxbrowser.chromium.ProtocolHandler;
import com.teamdev.jxbrowser.chromium.URLRequest;
import com.teamdev.jxbrowser.chromium.URLResponse;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.Map;
/**
* @author richie
* @version 10.0
* Created by richie on 2019-03-07
*/
public class EmbProtocolHandler implements ProtocolHandler {
private AssembleComponent component;
private Map<String, String> map;
public EmbProtocolHandler() {
}
public EmbProtocolHandler(AssembleComponent component) {
this.component = component;
}
public EmbProtocolHandler(AssembleComponent component, Map<String, String> map) {
this.component = component;
this.map = map;
}
public EmbProtocolHandler(Map<String, String> map) {
this.map = map;
}
@Override
public URLResponse onRequest(URLRequest req) {
InputStream inputStream = null;
try {
String path = req.getURL();
if (path.startsWith("file:")) {
String url = new URLCodec().decode(path);
String filePath = TemplateUtils.renderParameter4Tpl(url, map);
File file = new File(URI.create(filePath).getPath());
inputStream = IOUtils.readResource(file.getAbsolutePath());
String text = IOUtils.inputStream2String(inputStream, EncodeConstants.ENCODING_UTF_8);
text = TemplateUtils.renderParameter4Tpl(text, map);
return Assistant.inputStream2Response(new ByteArrayInputStream(text.getBytes(StandardCharsets.UTF_8)), path);
} else if (path.startsWith("emb:dynamic")) {
URLResponse response = new URLResponse();
response.setData(htmlText(map).getBytes());
response.getHeaders().setHeader("Content-Type", "text/html");
return response;
} else {
int index = path.indexOf("=");
if (index > 0) {
path = path.substring(index + 1);
} else {
path = path.substring(4);
}
inputStream = IOUtils.readResource(path);
return Assistant.inputStream2Response(inputStream, path);
}
} catch (Exception e) {
FineLoggerFactory.getLogger().info(e.getMessage());
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
FineLoggerFactory.getLogger().error(e.getMessage(), e);
}
}
}
return null;
}
private String htmlText(Map<String, String> map) {
PathGroup pathGroup = AtomBuilder.create().buildAssembleFilePath(ModernRequestClient.KEY, component);
StylePath[] stylePaths = pathGroup.toStylePathGroup();
StringBuilder styleText = new StringBuilder();
for (StylePath path : stylePaths) {
if (StringUtils.isNotBlank(path.toFilePath())) {
styleText.append("<link rel=\"stylesheet\" href=\"emb:");
styleText.append(path.toFilePath());
styleText.append("\"/>");
}
}
String result = ModernUIConstants.HTML_TPL.replaceAll("##style##", styleText.toString());
ScriptPath[] scriptPaths = pathGroup.toScriptPathGroup();
StringBuilder scriptText = new StringBuilder();
for (ScriptPath path : scriptPaths) {
if (StringUtils.isNotBlank(path.toFilePath())) {
scriptText.append("<script src=\"emb:");
scriptText.append(path.toFilePath());
scriptText.append("\"></script>");
}
}
result = result.replaceAll("##script##", scriptText.toString());
if (map != null) {
for (Map.Entry<String, String> entry : map.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
result = result.replaceAll("\\$\\{" + key + "}", value);
}
}
return result;
}
}

147
designer-base/src/main/java/com/fr/design/ui/ModernUIPane.java

@ -7,21 +7,18 @@ import com.fr.design.gui.itoolbar.UIToolbar;
import com.fr.design.i18n.Toolkit; import com.fr.design.i18n.Toolkit;
import com.fr.design.utils.gui.GUICoreUtils; import com.fr.design.utils.gui.GUICoreUtils;
import com.fr.web.struct.AssembleComponent; import com.fr.web.struct.AssembleComponent;
import com.teamdev.jxbrowser.chromium.Browser; import com.teamdev.jxbrowser.browser.Browser;
import com.teamdev.jxbrowser.chromium.BrowserPreferences; import com.teamdev.jxbrowser.browser.callback.InjectJsCallback;
import com.teamdev.jxbrowser.chromium.JSValue; import com.teamdev.jxbrowser.engine.Engine;
import com.teamdev.jxbrowser.chromium.events.FinishLoadingEvent; import com.teamdev.jxbrowser.engine.EngineOptions;
import com.teamdev.jxbrowser.chromium.events.LoadAdapter; import com.teamdev.jxbrowser.engine.RenderingMode;
import com.teamdev.jxbrowser.chromium.events.LoadListener; import com.teamdev.jxbrowser.js.JsObject;
import com.teamdev.jxbrowser.chromium.events.ScriptContextAdapter; import com.teamdev.jxbrowser.net.Network;
import com.teamdev.jxbrowser.chromium.events.ScriptContextEvent; import com.teamdev.jxbrowser.net.callback.InterceptRequestCallback;
import com.teamdev.jxbrowser.chromium.events.ScriptContextListener; import com.teamdev.jxbrowser.view.swing.BrowserView;
import com.teamdev.jxbrowser.chromium.swing.BrowserView;
import javax.swing.*; import javax.swing.*;
import java.awt.*; import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Map; import java.util.Map;
/** /**
@ -42,9 +39,8 @@ public class ModernUIPane<T> extends BasicPane {
} }
private void initialize() { private void initialize() {
setLayout(new BorderLayout());
if (browser == null) { if (browser == null) {
setLayout(new BorderLayout());
BrowserPreferences.setChromiumSwitches("--disable-google-traffic");
if (DesignerEnvManager.getEnvManager().isOpenDebug()) { if (DesignerEnvManager.getEnvManager().isOpenDebug()) {
UIToolbar toolbar = new UIToolbar(); UIToolbar toolbar = new UIToolbar();
add(toolbar, BorderLayout.NORTH); add(toolbar, BorderLayout.NORTH);
@ -55,75 +51,67 @@ public class ModernUIPane<T> extends BasicPane {
UIButton closeButton = new UIButton(Toolkit.i18nText("Fine-Design_Basic_Close_Window")); UIButton closeButton = new UIButton(Toolkit.i18nText("Fine-Design_Basic_Close_Window"));
toolbar.add(closeButton); toolbar.add(closeButton);
openDebugButton.addActionListener(new ActionListener() { openDebugButton.addActionListener(e -> showDebuggerDialog());
@Override
public void actionPerformed(ActionEvent e) {
showDebuggerDialog();
}
});
reloadButton.addActionListener(new ActionListener() { reloadButton.addActionListener(e -> browser.navigation().reloadIgnoringCache());
@Override
public void actionPerformed(ActionEvent e) {
browser.reloadIgnoringCache();
}
});
closeButton.addActionListener(new ActionListener() { closeButton.addActionListener(e -> SwingUtilities.getWindowAncestor(ModernUIPane.this).setVisible(false));
@Override
public void actionPerformed(ActionEvent e) {
SwingUtilities.getWindowAncestor(ModernUIPane.this).setVisible(false);
}
});
BrowserPreferences.setChromiumSwitches("--remote-debugging-port=9222");
initializeBrowser(); initializeBrowser();
add(new BrowserView(browser), BorderLayout.CENTER); add(BrowserView.newInstance(browser), BorderLayout.CENTER);
} else { } else {
initializeBrowser(); initializeBrowser();
add(new BrowserView(browser), BorderLayout.CENTER); add(BrowserView.newInstance(browser), BorderLayout.CENTER);
} }
} }
} }
private void showDebuggerDialog() { private void showDebuggerDialog() {
JDialog dialog = new JDialog(SwingUtilities.getWindowAncestor(this)); JDialog dialog = new JDialog(SwingUtilities.getWindowAncestor(this));
Browser debugger = new Browser(); Engine engine = Engine.newInstance(
BrowserView debuggerView = new BrowserView(debugger); EngineOptions.newBuilder(RenderingMode.HARDWARE_ACCELERATED)
.addSwitch("--disable-google-traffic")
.remoteDebuggingPort(9222).build());
Browser debugger = engine.newBrowser();
BrowserView debuggerView = BrowserView.newInstance(debugger);
dialog.add(debuggerView, BorderLayout.CENTER); dialog.add(debuggerView, BorderLayout.CENTER);
dialog.setSize(new Dimension(800, 400)); dialog.setSize(new Dimension(800, 400));
GUICoreUtils.centerWindow(dialog); GUICoreUtils.centerWindow(dialog);
dialog.setVisible(true); dialog.setVisible(true);
dialog.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); dialog.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
debugger.loadURL(browser.getRemoteDebuggingURL()); browser.devTools().remoteDebuggingUrl().ifPresent(url -> {
debugger.navigation().loadUrl(url);
});
} }
private void initializeBrowser() { private void initializeBrowser() {
browser = new Browser(); Engine engine = Engine.newInstance(EngineOptions.newBuilder(RenderingMode.HARDWARE_ACCELERATED).addSwitch("--disable-google-traffic").build());
browser = engine.newBrowser();
// 初始化的时候,就把命名空间对象初始化好,确保window.a.b.c("a.b.c"为命名空间)对象都是初始化过的 // 初始化的时候,就把命名空间对象初始化好,确保window.a.b.c("a.b.c"为命名空间)对象都是初始化过的
browser.addScriptContextListener(new ScriptContextAdapter() { browser.set(InjectJsCallback.class, params -> {
@Override params.frame().executeJavaScript(String.format(ModernUIConstants.SCRIPT_INIT_NAME_SPACE, namespace));
public void onScriptContextCreated(ScriptContextEvent event) { return InjectJsCallback.Response.proceed();
event.getBrowser().executeJavaScript(String.format(ModernUIConstants.SCRIPT_INIT_NAME_SPACE, namespace));
}
}); });
} }
/** /**
* 转向一个新的地址相当于重新加载 * 转向一个新的地址相当于重新加载
*
* @param url 新的地址 * @param url 新的地址
*/ */
public void redirect(String url) { public void redirect(String url) {
browser.loadURL(url); browser.navigation().loadUrl(url);
} }
/** /**
* 转向一个新的地址相当于重新加载 * 转向一个新的地址相当于重新加载
*
* @param url 新的地址 * @param url 新的地址
* @param map 初始化参数 * @param map 初始化参数
*/ */
public void redirect(String url, Map<String, String> map) { public void redirect(String url, Map<String, String> map) {
Assistant.setEmbProtocolHandler(browser, new EmbProtocolHandler(map)); Network network = browser.engine().network();
browser.loadURL(url); network.set(InterceptRequestCallback.class, new NxInterceptRequestCallback(network, map));
browser.navigation().loadUrl(url);
} }
@Override @Override
@ -133,19 +121,18 @@ public class ModernUIPane<T> extends BasicPane {
public void populate(final T t) { public void populate(final T t) {
browser.addScriptContextListener(new ScriptContextAdapter() { browser.set(InjectJsCallback.class, params -> {
@Override JsObject ns = params.frame().executeJavaScript("window." + namespace);
public void onScriptContextCreated(ScriptContextEvent event) { if (ns != null) {
JSValue ns = event.getBrowser().executeJavaScriptAndReturnValue("window." + namespace); ns.putProperty(variable, t);
ns.asObject().setProperty(variable, t);
} }
return InjectJsCallback.Response.proceed();
}); });
} }
public T update() { public T update() {
JSValue jsValue = browser.executeJavaScriptAndReturnValue("window." + namespace + "." + expression); if (browser.mainFrame().isPresent()) {
if (jsValue.isObject()) { return browser.mainFrame().get().executeJavaScript("window." + namespace + "." + expression);
return (T)jsValue.asJavaObject();
} }
return null; return null;
} }
@ -154,79 +141,89 @@ public class ModernUIPane<T> extends BasicPane {
private ModernUIPane<T> pane = new ModernUIPane<>(); private ModernUIPane<T> pane = new ModernUIPane<>();
public Builder<T> prepare(ScriptContextListener contextListener) { public Builder<T> prepare(InjectJsCallback callback) {
pane.browser.addScriptContextListener(contextListener); pane.browser.set(InjectJsCallback.class, callback);
return this;
}
public Builder<T> prepare(LoadListener loadListener) {
pane.browser.addLoadListener(loadListener);
return this; return this;
} }
/** /**
* 加载jar包中的资源 * 加载jar包中的资源
*
* @param path 资源路径 * @param path 资源路径
*/ */
public Builder<T> withEMB(final String path) { public Builder<T> withEMB(final String path) {
Assistant.setEmbProtocolHandler(pane.browser, new EmbProtocolHandler()); Network network = pane.browser.engine().network();
pane.browser.loadURL("emb:" + path); network.set(InterceptRequestCallback.class, new NxInterceptRequestCallback(network));
pane.browser.navigation().loadUrl("emb:" + path);
return this; return this;
} }
/** /**
* 加载url指向的资源 * 加载url指向的资源
*
* @param url 文件的地址 * @param url 文件的地址
*/ */
public Builder<T> withURL(final String url) { public Builder<T> withURL(final String url) {
Assistant.setEmbProtocolHandler(pane.browser, new EmbProtocolHandler()); Network network = pane.browser.engine().network();
pane.browser.loadURL(url); network.set(InterceptRequestCallback.class, new NxInterceptRequestCallback(network));
pane.browser.navigation().loadUrl(url);
return this; return this;
} }
/** /**
* 加载url指向的资源 * 加载url指向的资源
*
* @param url 文件的地址 * @param url 文件的地址
*/ */
public Builder<T> withURL(final String url, Map<String, String> map) { public Builder<T> withURL(final String url, Map<String, String> map) {
Assistant.setEmbProtocolHandler(pane.browser, new EmbProtocolHandler(map)); Network network = pane.browser.engine().network();
pane.browser.loadURL(url); network.set(InterceptRequestCallback.class, new NxInterceptRequestCallback(network, map));
pane.browser.navigation().loadUrl(url);
return this; return this;
} }
/** /**
* 加载Atom组件 * 加载Atom组件
*
* @param component Atom组件 * @param component Atom组件
*/ */
public Builder<T> withComponent(AssembleComponent component) { public Builder<T> withComponent(AssembleComponent component) {
Assistant.setEmbProtocolHandler(pane.browser, new EmbProtocolHandler(component)); Network network = pane.browser.engine().network();
pane.browser.loadURL("emb:dynamic"); network.set(InterceptRequestCallback.class, new NxComplexInterceptRequestCallback(network, component));
pane.browser.navigation().loadUrl("emb:dynamic");
return this; return this;
} }
/** /**
* 加载Atom组件 * 加载Atom组件
*
* @param component Atom组件 * @param component Atom组件
*/ */
public Builder<T> withComponent(AssembleComponent component, Map<String, String> map) { public Builder<T> withComponent(AssembleComponent component, Map<String, String> map) {
Assistant.setEmbProtocolHandler(pane.browser, new EmbProtocolHandler(component, map)); Network network = pane.browser.engine().network();
pane.browser.loadURL("emb:dynamic"); network.set(InterceptRequestCallback.class, new NxComplexInterceptRequestCallback(network, component, map));
pane.browser.navigation().loadUrl("emb:dynamic");
return this; return this;
} }
/** /**
* 加载html文本内容 * 加载html文本内容
*
* @param html 要加载html文本内容 * @param html 要加载html文本内容
*/ */
public Builder<T> withHTML(String html) { public Builder<T> withHTML(String html) {
Assistant.setEmbProtocolHandler(pane.browser, new EmbProtocolHandler()); Network network = pane.browser.engine().network();
pane.browser.loadHTML(html); network.set(InterceptRequestCallback.class, new NxInterceptRequestCallback(network));
pane.browser.mainFrame().ifPresent(frame -> {
frame.loadHtml(html);
});
return this; return this;
} }
/** /**
* 设置该前端页面做数据交换所使用的对象 * 设置该前端页面做数据交换所使用的对象
*
* @param namespace 对象名 * @param namespace 对象名
*/ */
public Builder<T> namespace(String namespace) { public Builder<T> namespace(String namespace) {
@ -236,6 +233,7 @@ public class ModernUIPane<T> extends BasicPane {
/** /**
* java端往js端传数据时使用的变量名字 * java端往js端传数据时使用的变量名字
*
* @param name 变量的名字 * @param name 变量的名字
*/ */
public Builder<T> variable(String name) { public Builder<T> variable(String name) {
@ -245,6 +243,7 @@ public class ModernUIPane<T> extends BasicPane {
/** /**
* js端往java端传数据时执行的函数表达式 * js端往java端传数据时执行的函数表达式
*
* @param expression 函数表达式 * @param expression 函数表达式
*/ */
public Builder<T> expression(String expression) { public Builder<T> expression(String expression) {

85
designer-base/src/main/java/com/fr/design/ui/NxComplexInterceptRequestCallback.java

@ -0,0 +1,85 @@
package com.fr.design.ui;
import com.fr.general.IOUtils;
import com.fr.stable.StringUtils;
import com.fr.web.struct.AssembleComponent;
import com.fr.web.struct.AtomBuilder;
import com.fr.web.struct.PathGroup;
import com.fr.web.struct.category.ScriptPath;
import com.fr.web.struct.category.StylePath;
import com.teamdev.jxbrowser.net.Network;
import com.teamdev.jxbrowser.net.UrlRequest;
import com.teamdev.jxbrowser.net.callback.InterceptRequestCallback;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.Map;
/**
* @author richie
* @version 10.0
* Created by richie on 2020/3/25
*/
public class NxComplexInterceptRequestCallback extends NxInterceptRequestCallback {
private AssembleComponent component;
public NxComplexInterceptRequestCallback(Network network, AssembleComponent component) {
super(network);
this.component = component;
}
public NxComplexInterceptRequestCallback(Network network, AssembleComponent component, Map<String, String> map) {
super(network, map);
this.component = component;
}
@Override
protected Response next(UrlRequest urlRequest, String path) {
if (path.startsWith("emb:dynamic")) {
String text = htmlText(map);
return InterceptRequestCallback.Response.intercept(generateBasicUrlRequestJob(urlRequest, "text/html", text.getBytes(StandardCharsets.UTF_8)));
} else {
int index = path.indexOf("=");
if (index > 0) {
path = path.substring(index + 1);
} else {
path = path.substring(4);
}
InputStream inputStream = IOUtils.readResource(path);
return InterceptRequestCallback.Response.intercept(generateBasicUrlRequestJob(urlRequest, getMimeType(path), IOUtils.inputStream2Bytes(inputStream)));
}
}
private String htmlText(Map<String, String> map) {
PathGroup pathGroup = AtomBuilder.create().buildAssembleFilePath(ModernRequestClient.KEY, component);
StylePath[] stylePaths = pathGroup.toStylePathGroup();
StringBuilder styleText = new StringBuilder();
for (StylePath path : stylePaths) {
if (StringUtils.isNotBlank(path.toFilePath())) {
styleText.append("<link rel=\"stylesheet\" href=\"emb:");
styleText.append(path.toFilePath());
styleText.append("\"/>");
}
}
String result = ModernUIConstants.HTML_TPL.replaceAll("##style##", styleText.toString());
ScriptPath[] scriptPaths = pathGroup.toScriptPathGroup();
StringBuilder scriptText = new StringBuilder();
for (ScriptPath path : scriptPaths) {
if (StringUtils.isNotBlank(path.toFilePath())) {
scriptText.append("<script src=\"emb:");
scriptText.append(path.toFilePath());
scriptText.append("\"></script>");
}
}
result = result.replaceAll("##script##", scriptText.toString());
if (map != null) {
for (Map.Entry<String, String> entry : map.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
result = result.replaceAll("\\$\\{" + key + "}", value);
}
}
return result;
}
}

134
designer-base/src/main/java/com/fr/design/ui/NxInterceptRequestCallback.java

@ -0,0 +1,134 @@
package com.fr.design.ui;
import com.fr.base.TemplateUtils;
import com.fr.general.IOUtils;
import com.fr.log.FineLoggerFactory;
import com.fr.stable.ArrayUtils;
import com.fr.stable.EncodeConstants;
import com.fr.stable.StringUtils;
import com.fr.third.org.apache.commons.codec.net.URLCodec;
import com.teamdev.jxbrowser.net.HttpHeader;
import com.teamdev.jxbrowser.net.HttpStatus;
import com.teamdev.jxbrowser.net.Network;
import com.teamdev.jxbrowser.net.UrlRequest;
import com.teamdev.jxbrowser.net.UrlRequestJob;
import com.teamdev.jxbrowser.net.callback.InterceptRequestCallback;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Map;
import java.util.Optional;
/**
* @author richie
* @version 10.0
* Created by richie on 2020/3/25
*/
public class NxInterceptRequestCallback implements InterceptRequestCallback {
Network network;
Map<String, String> map;
public NxInterceptRequestCallback(Network network) {
this.network = network;
}
public NxInterceptRequestCallback(Network network, Map<String, String> map) {
this.network = network;
this.map = map;
}
@Override
public Response on(Params params) {
UrlRequest urlRequest = params.urlRequest();
String path = urlRequest.url();
if (path.startsWith("file:")) {
Optional<UrlRequestJob> optional = generateFileProtocolUrlRequestJob(urlRequest, path);
if (optional.isPresent()) {
return InterceptRequestCallback.Response.intercept(optional.get());
}
} else {
return next(urlRequest, path);
}
return Response.proceed();
}
Response next(UrlRequest urlRequest, String path) {
return Response.proceed();
}
private Optional<UrlRequestJob> generateFileProtocolUrlRequestJob(UrlRequest urlRequest, String path) {
try {
String url = new URLCodec().decode(path);
String filePath = TemplateUtils.renderParameter4Tpl(url, map);
File file = new File(URI.create(filePath).getPath());
InputStream inputStream = IOUtils.readResource(file.getAbsolutePath());
String mimeType = getMimeType(path);
byte[] bytes;
if (isPlainText(mimeType)) {
String text = IOUtils.inputStream2String(inputStream, EncodeConstants.ENCODING_UTF_8);
text = TemplateUtils.renderParameter4Tpl(text, map);
bytes = text.getBytes(StandardCharsets.UTF_8);
} else {
bytes = IOUtils.inputStream2Bytes(inputStream);
}
return Optional.of(generateBasicUrlRequestJob(urlRequest, mimeType, bytes));
} catch (Exception e) {
FineLoggerFactory.getLogger().error(e.getMessage(), e);
}
return Optional.empty();
}
private boolean isPlainText(String mimeType) {
return ArrayUtils.contains(new String[]{"text/html", "text/javascript", "text/css"}, mimeType);
}
UrlRequestJob generateBasicUrlRequestJob(UrlRequest urlRequest, String mimeType, byte[] bytes) {
UrlRequestJob.Options options = UrlRequestJob.Options
.newBuilder(urlRequest.id(), HttpStatus.OK)
.addHttpHeader(HttpHeader.of("Content-Type", mimeType))
.build();
UrlRequestJob urlRequestJob = network.newUrlRequestJob(options);
urlRequestJob.write(bytes);
urlRequestJob.complete();
return urlRequestJob;
}
String getMimeType(String path) {
if (StringUtils.isBlank(path)) {
return "text/html";
}
if (path.endsWith(".html")) {
return "text/html";
}
if (path.endsWith(".css")) {
return "text/css";
}
if (path.endsWith(".js")) {
return "text/javascript";
}
if (path.endsWith(".svg")) {
return "image/svg+xml";
}
if (path.endsWith(".png")) {
return "image/png";
}
if (path.endsWith(".jpeg")) {
return "image/jpeg";
}
if (path.endsWith(".gif")) {
return "image/gif";
}
Path file = new File(path).toPath();
try {
return Files.probeContentType(file);
} catch (IOException e) {
return "text/html";
}
}
}

230
designer-base/src/main/java/com/fr/design/upm/UpmBridge.java

@ -6,6 +6,7 @@ import com.fr.config.ServerPreferenceConfig;
import com.fr.decision.webservice.v10.plugin.helper.category.impl.UpmResourceLoader; import com.fr.decision.webservice.v10.plugin.helper.category.impl.UpmResourceLoader;
import com.fr.design.bridge.exec.JSBridge; import com.fr.design.bridge.exec.JSBridge;
import com.fr.design.bridge.exec.JSCallback; import com.fr.design.bridge.exec.JSCallback;
import com.fr.design.bridge.exec.JSExecutor;
import com.fr.design.extra.PluginOperateUtils; import com.fr.design.extra.PluginOperateUtils;
import com.fr.design.extra.PluginUtils; import com.fr.design.extra.PluginUtils;
import com.fr.design.extra.exe.GetInstalledPluginsExecutor; import com.fr.design.extra.exe.GetInstalledPluginsExecutor;
@ -28,10 +29,8 @@ import com.fr.log.FineLoggerFactory;
import com.fr.plugin.context.PluginMarker; import com.fr.plugin.context.PluginMarker;
import com.fr.stable.ArrayUtils; import com.fr.stable.ArrayUtils;
import com.fr.stable.StringUtils; import com.fr.stable.StringUtils;
import com.teamdev.jxbrowser.chromium.Browser; import com.teamdev.jxbrowser.js.JsAccessible;
import com.teamdev.jxbrowser.chromium.JSArray; import com.teamdev.jxbrowser.js.JsObject;
import com.teamdev.jxbrowser.chromium.JSFunction;
import com.teamdev.jxbrowser.chromium.JSObject;
import javax.swing.*; import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter; import javax.swing.filechooser.FileNameExtensionFilter;
@ -52,42 +51,45 @@ import java.util.concurrent.RunnableFuture;
*/ */
public class UpmBridge { public class UpmBridge {
public static UpmBridge getBridge(Browser browser) { public static UpmBridge getBridge() {
return new UpmBridge(browser); return new UpmBridge();
} }
private JSObject window;
private UpmBridge(Browser browser) { private UpmBridge() {
this.window = browser.executeJavaScriptAndReturnValue("window").asObject();
} }
/** /**
* 更新插件管理中心资源文件这个方法仅仅是为了语义上的作用更新 * 更新插件管理中心资源文件这个方法仅仅是为了语义上的作用更新
*
* @param callback 安装完成后的回调函数 * @param callback 安装完成后的回调函数
*/ */
@JSBridge @JSBridge
public void update(final JSFunction callback) { @JsAccessible
callback.invoke(window, "start", Toolkit.i18nText("Fine-Design_Basic_Update_Plugin_Manager_Download_Start")); public void update(final JsObject callback) {
callback.call(JSExecutor.CALLBACK_FUNCTION_NAME, "start", Toolkit.i18nText("Fine-Design_Basic_Update_Plugin_Manager_Download_Start"));
try { try {
UpmResourceLoader.INSTANCE.download(); UpmResourceLoader.INSTANCE.download();
UpmResourceLoader.INSTANCE.install(); UpmResourceLoader.INSTANCE.install();
callback.invoke(window, "success", Toolkit.i18nText("Fine-Design_Basic_Update_Plugin_Manager_Download_Success")); callback.call(JSExecutor.CALLBACK_FUNCTION_NAME, "success", Toolkit.i18nText("Fine-Design_Basic_Update_Plugin_Manager_Download_Success"));
EventDispatcher.fire(DownloadEvent.UPDATE, "success"); EventDispatcher.fire(DownloadEvent.UPDATE, "success");
} catch (Exception e) { } catch (Exception e) {
FineLoggerFactory.getLogger().error(e.getMessage(), e); FineLoggerFactory.getLogger().error(e.getMessage(), e);
callback.invoke(window, "error", Toolkit.i18nText("Fine-Design_Basic_Update_Plugin_Manager_Download_Error")); callback.call(JSExecutor.CALLBACK_FUNCTION_NAME, "error", Toolkit.i18nText("Fine-Design_Basic_Update_Plugin_Manager_Download_Error"));
} }
} }
/** /**
* 下载并安装插件管理中心的资源文件 * 下载并安装插件管理中心的资源文件
*
* @param callback 安装完成后的回调函数 * @param callback 安装完成后的回调函数
*/ */
@JSBridge @JSBridge
public void startDownload(final JSFunction callback) { @JsAccessible
callback.invoke(window, "start", Toolkit.i18nText("Fine-Design_Basic_Update_Plugin_Manager_Download_Start")); public void startDownload(final JsObject callback) {
new SwingWorker<Void, Void>(){ callback.call(JSExecutor.CALLBACK_FUNCTION_NAME, "start", Toolkit.i18nText("Fine-Design_Basic_Update_Plugin_Manager_Download_Start"));
new SwingWorker<Void, Void>() {
@Override @Override
protected Void doInBackground() throws Exception { protected Void doInBackground() throws Exception {
UpmResourceLoader.INSTANCE.download(); UpmResourceLoader.INSTANCE.download();
@ -99,10 +101,10 @@ public class UpmBridge {
protected void done() { protected void done() {
try { try {
get(); get();
callback.invoke(window, "success", Toolkit.i18nText("Fine-Design_Basic_Update_Plugin_Manager_Download_Success")); callback.call(JSExecutor.CALLBACK_FUNCTION_NAME, "success", Toolkit.i18nText("Fine-Design_Basic_Update_Plugin_Manager_Download_Success"));
EventDispatcher.fire(DownloadEvent.SUCCESS, "success"); EventDispatcher.fire(DownloadEvent.SUCCESS, "success");
} catch (Exception e) { } catch (Exception e) {
callback.invoke(window, "error", Toolkit.i18nText("Fine-Design_Basic_Update_Plugin_Manager_Download_Error")); callback.call(JSExecutor.CALLBACK_FUNCTION_NAME, "error", Toolkit.i18nText("Fine-Design_Basic_Update_Plugin_Manager_Download_Error"));
FineLoggerFactory.getLogger().error(e.getMessage(), e); FineLoggerFactory.getLogger().error(e.getMessage(), e);
EventDispatcher.fire(DownloadEvent.ERROR, "error"); EventDispatcher.fire(DownloadEvent.ERROR, "error");
} }
@ -112,37 +114,44 @@ public class UpmBridge {
/** /**
* 获取upm的版本信息 * 获取upm的版本信息
*
* @return 版本信息 * @return 版本信息
*/ */
@JSBridge @JSBridge
@JsAccessible
public String getVersion() { public String getVersion() {
return ServerPreferenceConfig.getInstance().getOptimizedUPMVersion(); return ServerPreferenceConfig.getInstance().getOptimizedUPMVersion();
} }
@JSBridge @JSBridge
@JsAccessible
public String i18nText(String key) { public String i18nText(String key) {
return Toolkit.i18nText(key); return Toolkit.i18nText(key);
} }
@JSBridge @JSBridge
@JsAccessible
public void closeWindow() { public void closeWindow() {
UpmFinder.closeWindow(); UpmFinder.closeWindow();
} }
@JSBridge @JSBridge
@JsAccessible
public boolean isDesigner() { public boolean isDesigner() {
return true; return true;
} }
@JSBridge @JSBridge
public void getPackInfo(final JSFunction callback) { @JsAccessible
callback.invoke(window, StringUtils.EMPTY); public void getPackInfo(final JsObject callback) {
callback.call(JSExecutor.CALLBACK_FUNCTION_NAME, StringUtils.EMPTY);
} }
@JSBridge @JSBridge
public void getPluginPrefix(final JSFunction callback) { @JsAccessible
UpmTaskWorker<Void> task = new UpmTaskWorker<>(new JSCallback(UpmBrowserExecutor.create(window, callback)), new GetPluginPrefixExecutor()); public void getPluginPrefix(final JsObject callback) {
UpmTaskWorker<Void> task = new UpmTaskWorker<>(new JSCallback(UpmBrowserExecutor.create(callback)), new GetPluginPrefixExecutor());
task.execute(); task.execute();
} }
@ -152,8 +161,9 @@ public class UpmBridge {
* @param callback 回调函数 * @param callback 回调函数
*/ */
@JSBridge @JSBridge
public void getPluginCategories(final JSFunction callback) { @JsAccessible
UpmTaskWorker<Void> task = new UpmTaskWorker<>(new JSCallback(UpmBrowserExecutor.create(window, callback)), new GetPluginCategoriesExecutor()); public void getPluginCategories(final JsObject callback) {
UpmTaskWorker<Void> task = new UpmTaskWorker<>(new JSCallback(UpmBrowserExecutor.create(callback)), new GetPluginCategoriesExecutor());
task.execute(); task.execute();
} }
@ -164,8 +174,9 @@ public class UpmBridge {
* @param callback 回调函数 * @param callback 回调函数
*/ */
@JSBridge @JSBridge
public void getPluginFromStoreNew(String info, final JSFunction callback) { @JsAccessible
UpmTaskWorker<Void> task = new UpmTaskWorker<>(new JSCallback(UpmBrowserExecutor.create(window, callback)), new GetPluginFromStoreExecutor(new JSONObject(info))); public void getPluginFromStoreNew(String info, final JsObject callback) {
UpmTaskWorker<Void> task = new UpmTaskWorker<>(new JSCallback(UpmBrowserExecutor.create(callback)), new GetPluginFromStoreExecutor(new JSONObject(info)));
task.execute(); task.execute();
} }
@ -173,8 +184,9 @@ public class UpmBridge {
* 已安装插件检查更新 * 已安装插件检查更新
*/ */
@JSBridge @JSBridge
public void readUpdateOnline(final JSFunction callback) { @JsAccessible
UpmTaskWorker<Void> task = new UpmTaskWorker<>(new JSCallback(UpmBrowserExecutor.create(window, callback)), new ReadUpdateOnlineExecutor()); public void readUpdateOnline(final JsObject callback) {
UpmTaskWorker<Void> task = new UpmTaskWorker<>(new JSCallback(UpmBrowserExecutor.create(callback)), new ReadUpdateOnlineExecutor());
task.execute(); task.execute();
} }
@ -182,8 +194,9 @@ public class UpmBridge {
* 获取已经安装的插件的数组 * 获取已经安装的插件的数组
*/ */
@JSBridge @JSBridge
public void getInstalledPlugins(final JSFunction callback) { @JsAccessible
UpmTaskWorker<Void> task = new UpmTaskWorker<>(new JSCallback(UpmBrowserExecutor.create(window, callback)), new GetInstalledPluginsExecutor()); public void getInstalledPlugins(final JsObject callback) {
UpmTaskWorker<Void> task = new UpmTaskWorker<>(new JSCallback(UpmBrowserExecutor.create(callback)), new GetInstalledPluginsExecutor());
task.execute(); task.execute();
} }
@ -193,29 +206,36 @@ public class UpmBridge {
* @param pluginIDs 插件集合 * @param pluginIDs 插件集合
*/ */
@JSBridge @JSBridge
public void updatePluginOnline(Object pluginIDs, final JSFunction callback) { @JsAccessible
JSCallback jsCallback = new JSCallback(UpmBrowserExecutor.create(window, callback)); public void updatePluginOnline(JsObject pluginIDs, final JsObject callback) {
JSCallback jsCallback = new JSCallback(UpmBrowserExecutor.create(callback));
List<PluginMarker> pluginMarkerList = new ArrayList<>(); List<PluginMarker> pluginMarkerList = new ArrayList<>();
if (pluginIDs instanceof String) { for (String key : pluginIDs.propertyNames()) {
pluginMarkerList.add(PluginUtils.createPluginMarker(pluginIDs.toString())); pluginIDs.property(key).ifPresent(v -> {
} else if (pluginIDs instanceof JSArray) { pluginMarkerList.add(PluginUtils.createPluginMarker(GeneralUtils.objectToString(v)));
JSArray pluginInfos = (JSArray) pluginIDs; });
for (int i = 0, len = pluginInfos.length(); i < len; i++) {
String value = pluginInfos.get(i).asString().getValue();
pluginMarkerList.add(PluginUtils.createPluginMarker(value));
}
} }
PluginOperateUtils.updatePluginOnline(pluginMarkerList, jsCallback); PluginOperateUtils.updatePluginOnline(pluginMarkerList, jsCallback);
} }
@JSBridge
@JsAccessible
public void updatePluginOnline(String pluginID, final JsObject callback) {
JSCallback jsCallback = new JSCallback(UpmBrowserExecutor.create(callback));
List<PluginMarker> pluginMarkerList = new ArrayList<>();
pluginMarkerList.add(PluginUtils.createPluginMarker(pluginID));
PluginOperateUtils.updatePluginOnline(pluginMarkerList, jsCallback);
}
/** /**
* 搜索在线插件 * 搜索在线插件
* *
* @param keyword 关键字 * @param keyword 关键字
*/ */
@JSBridge @JSBridge
public void searchPlugin(String keyword, final JSFunction callback) { @JsAccessible
UpmTaskWorker<Void> worker = new UpmTaskWorker<>(new JSCallback(UpmBrowserExecutor.create(window, callback)), new SearchOnlineExecutor(keyword)); public void searchPlugin(String keyword, final JsObject callback) {
UpmTaskWorker<Void> worker = new UpmTaskWorker<>(new JSCallback(UpmBrowserExecutor.create(callback)), new SearchOnlineExecutor(keyword));
worker.execute(); worker.execute();
} }
@ -225,8 +245,9 @@ public class UpmBridge {
* @param filePath 插件包的路径 * @param filePath 插件包的路径
*/ */
@JSBridge @JSBridge
public void installPluginFromDisk(final String filePath, final JSFunction callback) { @JsAccessible
JSCallback jsCallback = new JSCallback(UpmBrowserExecutor.create(window, callback)); public void installPluginFromDisk(final String filePath, final JsObject callback) {
JSCallback jsCallback = new JSCallback(UpmBrowserExecutor.create(callback));
File file = new File(filePath); File file = new File(filePath);
PluginOperateUtils.installPluginFromDisk(file, jsCallback); PluginOperateUtils.installPluginFromDisk(file, jsCallback);
} }
@ -237,8 +258,9 @@ public class UpmBridge {
* @param pluginInfo 插件信息 * @param pluginInfo 插件信息
*/ */
@JSBridge @JSBridge
public void uninstallPlugin(final String pluginInfo, final boolean isForce, final JSFunction callback) { @JsAccessible
JSCallback jsCallback = new JSCallback(UpmBrowserExecutor.create(window, callback)); public void uninstallPlugin(final String pluginInfo, final boolean isForce, final JsObject callback) {
JSCallback jsCallback = new JSCallback(UpmBrowserExecutor.create(callback));
PluginOperateUtils.uninstallPlugin(pluginInfo, isForce, jsCallback); PluginOperateUtils.uninstallPlugin(pluginInfo, isForce, jsCallback);
} }
@ -249,8 +271,9 @@ public class UpmBridge {
* @param callback 回调函数 * @param callback 回调函数
*/ */
@JSBridge @JSBridge
public void installPluginOnline(final String pluginInfo, final JSFunction callback) { @JsAccessible
JSCallback jsCallback = new JSCallback(UpmBrowserExecutor.create(window, callback)); public void installPluginOnline(final String pluginInfo, final JsObject callback) {
JSCallback jsCallback = new JSCallback(UpmBrowserExecutor.create(callback));
PluginMarker pluginMarker = PluginUtils.createPluginMarker(pluginInfo); PluginMarker pluginMarker = PluginUtils.createPluginMarker(pluginInfo);
PluginOperateUtils.installPluginOnline(pluginMarker, jsCallback); PluginOperateUtils.installPluginOnline(pluginMarker, jsCallback);
} }
@ -260,8 +283,10 @@ public class UpmBridge {
* *
* @param filePath 插件包的路径 * @param filePath 插件包的路径
*/ */
public void updatePluginFromDisk(String filePath, final JSFunction callback) { @JSBridge
JSCallback jsCallback = new JSCallback(UpmBrowserExecutor.create(window, callback)); @JsAccessible
public void updatePluginFromDisk(String filePath, final JsObject callback) {
JSCallback jsCallback = new JSCallback(UpmBrowserExecutor.create(callback));
File file = new File(filePath); File file = new File(filePath);
PluginOperateUtils.updatePluginFromDisk(file, jsCallback); PluginOperateUtils.updatePluginFromDisk(file, jsCallback);
} }
@ -272,8 +297,9 @@ public class UpmBridge {
* @param pluginID 插件ID * @param pluginID 插件ID
*/ */
@JSBridge @JSBridge
public void setPluginActive(String pluginID, final JSFunction callback) { @JsAccessible
JSCallback jsCallback = new JSCallback(UpmBrowserExecutor.create(window, callback)); public void setPluginActive(String pluginID, final JsObject callback) {
JSCallback jsCallback = new JSCallback(UpmBrowserExecutor.create(callback));
PluginOperateUtils.setPluginActive(pluginID, jsCallback); PluginOperateUtils.setPluginActive(pluginID, jsCallback);
} }
@ -283,6 +309,7 @@ public class UpmBridge {
* @return 选择的文件的路径 * @return 选择的文件的路径
*/ */
@JSBridge @JSBridge
@JsAccessible
public String showFileChooser() { public String showFileChooser() {
return showFileChooserWithFilter(StringUtils.EMPTY, StringUtils.EMPTY); return showFileChooserWithFilter(StringUtils.EMPTY, StringUtils.EMPTY);
} }
@ -296,6 +323,7 @@ public class UpmBridge {
* 这里换用JFileChooser会卡死,不知道为什么 * 这里换用JFileChooser会卡死,不知道为什么
*/ */
@JSBridge @JSBridge
@JsAccessible
public String showFileChooserWithFilter(final String des, final String filter) { public String showFileChooserWithFilter(final String des, final String filter) {
RunnableFuture<String> future = new FutureTask<>(new Callable<String>() { RunnableFuture<String> future = new FutureTask<>(new Callable<String>() {
@Override @Override
@ -318,7 +346,7 @@ public class UpmBridge {
try { try {
return future.get(); return future.get();
} catch (Exception e) { } catch (Exception e) {
FineLoggerFactory.getLogger().error(e.getMessage(), e); FineLoggerFactory.getLogger().error(e.getMessage(), e);
} }
return null; return null;
} }
@ -331,31 +359,60 @@ public class UpmBridge {
* @return 选择的文件的路径 * @return 选择的文件的路径
*/ */
@JSBridge @JSBridge
public String showFileChooserWithFilters(final String des, final Object args) { @JsAccessible
RunnableFuture<String> future = new FutureTask<>(new Callable<String>() { public String showFileChooserWithFilters(final String des, final String args) {
@Override RunnableFuture<String> future = new FutureTask<>(() -> {
public String call() { JFileChooser fileChooser = new JFileChooser();
JFileChooser fileChooser = new JFileChooser(); List<String> filterList = new ArrayList<>();
List<String> filterList = new ArrayList<>(); filterList.add(args);
if (args instanceof String) { String[] filters = filterList.toArray(new String[0]);
filterList.add(GeneralUtils.objectToString(args)); if (ArrayUtils.isNotEmpty(filters)) {
} else if (args instanceof JSArray) { FileNameExtensionFilter filter = new FileNameExtensionFilter(des, UpmUtils.findMatchedExtension(filters));
JSArray array = (JSArray)args; fileChooser.setFileFilter(filter);
for (int i = 0, len = array.length(); i < len; i ++) {
filterList.add(array.get(i).getStringValue());
}
}
String[] filters = filterList.toArray(new String[0]);
if (ArrayUtils.isNotEmpty(filters)) {
FileNameExtensionFilter filter = new FileNameExtensionFilter(des, UpmUtils.findMatchedExtension(filters));
fileChooser.setFileFilter(filter);
}
int result = fileChooser.showOpenDialog(UpmFinder.getDialog());
if (result == JFileChooser.APPROVE_OPTION) {
return fileChooser.getSelectedFile().getAbsolutePath();
}
return null;
} }
int result = fileChooser.showOpenDialog(UpmFinder.getDialog());
if (result == JFileChooser.APPROVE_OPTION) {
return fileChooser.getSelectedFile().getAbsolutePath();
}
return null;
});
SwingUtilities.invokeLater(future);
try {
return future.get();
} catch (Exception e) {
FineLoggerFactory.getLogger().error(e.getMessage(), e);
}
return null;
}
/**
* 选择文件对话框
*
* @param des 过滤文件描述
* @param args 文件的后缀
* @return 选择的文件的路径
*/
@JSBridge
@JsAccessible
public String showFileChooserWithFilters(final String des, final JsObject args) {
RunnableFuture<String> future = new FutureTask<>(() -> {
JFileChooser fileChooser = new JFileChooser();
List<String> filterList = new ArrayList<>();
for (String key : args.propertyNames()) {
args.property(key).ifPresent(v -> {
filterList.add(GeneralUtils.objectToString(v));
});
}
String[] filters = filterList.toArray(new String[0]);
if (ArrayUtils.isNotEmpty(filters)) {
FileNameExtensionFilter filter = new FileNameExtensionFilter(des, UpmUtils.findMatchedExtension(filters));
fileChooser.setFileFilter(filter);
}
int result = fileChooser.showOpenDialog(UpmFinder.getDialog());
if (result == JFileChooser.APPROVE_OPTION) {
return fileChooser.getSelectedFile().getAbsolutePath();
}
return null;
}); });
SwingUtilities.invokeLater(future); SwingUtilities.invokeLater(future);
try { try {
@ -372,7 +429,8 @@ public class UpmBridge {
* 获取系统登录的用户名 * 获取系统登录的用户名
*/ */
@JSBridge @JSBridge
public String getLoginInfo(final JSFunction callback) { @JsAccessible
public String getLoginInfo(final JsObject callback) {
registerLoginInfo(callback); registerLoginInfo(callback);
return MarketConfig.getInstance().getBbsUsername(); return MarketConfig.getInstance().getBbsUsername();
} }
@ -383,8 +441,9 @@ public class UpmBridge {
* @param callback 回调函数 * @param callback 回调函数
*/ */
@JSBridge @JSBridge
public void registerLoginInfo(final JSFunction callback) { @JsAccessible
JSCallback jsCallback = new JSCallback(UpmBrowserExecutor.create(window, callback)); public void registerLoginInfo(final JsObject callback) {
JSCallback jsCallback = new JSCallback(UpmBrowserExecutor.create(callback));
String username = MarketConfig.getInstance().getBbsUsername(); String username = MarketConfig.getInstance().getBbsUsername();
if (StringUtils.isEmpty(username)) { if (StringUtils.isEmpty(username)) {
jsCallback.execute(StringUtils.EMPTY); jsCallback.execute(StringUtils.EMPTY);
@ -404,14 +463,16 @@ public class UpmBridge {
* @param callback 回调函数 * @param callback 回调函数
*/ */
@JSBridge @JSBridge
public void defaultLogin(String username, String password, final JSFunction callback) { @JsAccessible
UpmTaskWorker<Void> worker = new UpmTaskWorker<>(new JSCallback(UpmBrowserExecutor.create(window, callback)), new PluginLoginExecutor(username, password)); public void defaultLogin(String username, String password, final JsObject callback) {
UpmTaskWorker<Void> worker = new UpmTaskWorker<>(new JSCallback(UpmBrowserExecutor.create(callback)), new PluginLoginExecutor(username, password));
worker.execute(); worker.execute();
} }
/** /**
* 清除用户信息 * 清除用户信息
*/ */
@JsAccessible
public void clearUserInfo() { public void clearUserInfo() {
MarketConfig.getInstance().setInShowBBsName(StringUtils.EMPTY); MarketConfig.getInstance().setInShowBBsName(StringUtils.EMPTY);
FinePassportManager.getInstance().logout(); FinePassportManager.getInstance().logout();
@ -422,6 +483,7 @@ public class UpmBridge {
* 打开论坛消息界面 * 打开论坛消息界面
*/ */
@JSBridge @JSBridge
@JsAccessible
public void getPriviteMessage() { public void getPriviteMessage() {
try { try {
String loginUrl = CloudCenter.getInstance().acquireUrlByKind("bbs.default"); String loginUrl = CloudCenter.getInstance().acquireUrlByKind("bbs.default");
@ -435,6 +497,7 @@ public class UpmBridge {
* 忘记密码 * 忘记密码
*/ */
@JSBridge @JSBridge
@JsAccessible
public void forgetHref() { public void forgetHref() {
try { try {
Desktop.getDesktop().browse(new URI(CloudCenter.getInstance().acquireUrlByKind("bbs.reset"))); Desktop.getDesktop().browse(new URI(CloudCenter.getInstance().acquireUrlByKind("bbs.reset")));
@ -447,6 +510,7 @@ public class UpmBridge {
* 立即注册 * 立即注册
*/ */
@JSBridge @JSBridge
@JsAccessible
public void registerHref() { public void registerHref() {
try { try {
Desktop.getDesktop().browse(new URI(CloudCenter.getInstance().acquireUrlByKind("bbs.register"))); Desktop.getDesktop().browse(new URI(CloudCenter.getInstance().acquireUrlByKind("bbs.register")));
@ -457,9 +521,11 @@ public class UpmBridge {
/** /**
* 使用系统浏览器打开网页 * 使用系统浏览器打开网页
*
* @param url 要打开的网页 * @param url 要打开的网页
*/ */
@JSBridge @JSBridge
@JsAccessible
public void openShopUrlAtWebBrowser(String url) { public void openShopUrlAtWebBrowser(String url) {
if (Desktop.isDesktopSupported()) { if (Desktop.isDesktopSupported()) {
try { try {

2
designer-base/src/main/java/com/fr/design/upm/UpmFinder.java

@ -58,7 +58,7 @@ public class UpmFinder {
public static void showUPMDialog() { public static void showUPMDialog() {
boolean flag = true; boolean flag = true;
try { try {
Class.forName("com.teamdev.jxbrowser.chromium.Browser"); Class.forName("com.teamdev.jxbrowser.browser.Browser");
} catch (ClassNotFoundException e) { } catch (ClassNotFoundException e) {
flag = false; flag = false;
} }

15
designer-base/src/main/java/com/fr/design/upm/UpmShowPane.java

@ -6,9 +6,8 @@ import com.fr.design.upm.event.DownloadEvent;
import com.fr.event.Event; import com.fr.event.Event;
import com.fr.event.EventDispatcher; import com.fr.event.EventDispatcher;
import com.fr.event.Listener; import com.fr.event.Listener;
import com.teamdev.jxbrowser.chromium.JSValue; import com.teamdev.jxbrowser.browser.callback.InjectJsCallback;
import com.teamdev.jxbrowser.chromium.events.ScriptContextAdapter; import com.teamdev.jxbrowser.js.JsObject;
import com.teamdev.jxbrowser.chromium.events.ScriptContextEvent;
import java.awt.*; import java.awt.*;
@ -32,12 +31,10 @@ public class UpmShowPane extends BasicPane {
// 先屏蔽掉这个判断,后续可能修改交互 // 先屏蔽掉这个判断,后续可能修改交互
// if (UpmFinder.checkUPMResourcesExist()) { // if (UpmFinder.checkUPMResourcesExist()) {
modernUIPane = new ModernUIPane.Builder<>() modernUIPane = new ModernUIPane.Builder<>()
.prepare(new ScriptContextAdapter() { .prepare(params -> {
@Override JsObject window = params.frame().executeJavaScript("window");
public void onScriptContextCreated(ScriptContextEvent event) { window.putProperty("PluginHelper", UpmBridge.getBridge());
JSValue window = event.getBrowser().executeJavaScriptAndReturnValue("window"); return InjectJsCallback.Response.proceed();
window.asObject().setProperty("PluginHelper", UpmBridge.getBridge(event.getBrowser()));
}
}) })
.withURL(UpmFinder.getMainResourcePath(), UpmUtils.renderMap()) .withURL(UpmFinder.getMainResourcePath(), UpmUtils.renderMap())
.build(); .build();

15
designer-base/src/main/java/com/fr/design/upm/exec/UpmBrowserExecutor.java

@ -1,8 +1,7 @@
package com.fr.design.upm.exec; package com.fr.design.upm.exec;
import com.fr.design.bridge.exec.JSExecutor; import com.fr.design.bridge.exec.JSExecutor;
import com.teamdev.jxbrowser.chromium.JSFunction; import com.teamdev.jxbrowser.js.JsObject;
import com.teamdev.jxbrowser.chromium.JSObject;
/** /**
* @author richie * @author richie
@ -11,20 +10,18 @@ import com.teamdev.jxbrowser.chromium.JSObject;
*/ */
public class UpmBrowserExecutor implements JSExecutor { public class UpmBrowserExecutor implements JSExecutor {
public static UpmBrowserExecutor create(JSObject window, JSFunction callback) { public static UpmBrowserExecutor create(JsObject callback) {
return new UpmBrowserExecutor(window, callback); return new UpmBrowserExecutor(callback);
} }
private JSObject window; private JsObject callback;
private JSFunction callback;
private UpmBrowserExecutor(JSObject window, JSFunction callback) { private UpmBrowserExecutor(JsObject callback) {
this.window = window;
this.callback = callback; this.callback = callback;
} }
@Override @Override
public void executor(String newValue) { public void executor(String newValue) {
callback.invoke(window, newValue); callback.call(JSExecutor.CALLBACK_FUNCTION_NAME, newValue);
} }
} }

4
pom.xml

@ -28,8 +28,8 @@
<artifactId>maven-compiler-plugin</artifactId> <artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version> <version>3.1</version>
<configuration> <configuration>
<source>1.7</source> <source>1.8</source>
<target>1.7</target> <target>1.8</target>
</configuration> </configuration>
</plugin> </plugin>
</plugins> </plugins>

Loading…
Cancel
Save