From d247e8b74a30babafdf0e2c63027c5e3be13d1e0 Mon Sep 17 00:00:00 2001 From: hzzz Date: Fri, 25 May 2018 09:25:11 +0800 Subject: [PATCH 1/9] env.. --- .../src/com/fr/design/DesignerEnvManager.java | 39 +- .../design/actions/file/SwitchExistEnv.java | 13 +- .../com/fr/design/file/FileOperations.java | 18 +- .../design/file/HistoryTemplateListPane.java | 4 +- .../com/fr/design/file/TemplateTreePane.java | 12 +- .../fr/design/mainframe/DesignerFrame.java | 115 ++- .../DesignerFrameFileDealerPane.java | 54 +- .../com/fr/design/mainframe/TemplatePane.java | 718 +++++++++++++----- .../loghandler/DesignerLogHandler.java | 25 +- .../src/com/fr/design/utils/DesignUtils.java | 111 +-- designer-base/src/com/fr/env/EnvListPane.java | 524 ++++++++++++- designer-base/src/com/fr/env/RemoteEnv.java | 488 ++++++------ designer-base/src/com/fr/env/SignIn.java | 2 +- 13 files changed, 1494 insertions(+), 629 deletions(-) diff --git a/designer-base/src/com/fr/design/DesignerEnvManager.java b/designer-base/src/com/fr/design/DesignerEnvManager.java index f372c9ef7..111e4f625 100644 --- a/designer-base/src/com/fr/design/DesignerEnvManager.java +++ b/designer-base/src/com/fr/design/DesignerEnvManager.java @@ -61,6 +61,7 @@ public class DesignerEnvManager implements XMLReadable, XMLWriter { private static final int MAX_SHOW_NUM = 10; private static final String VERSION_80 = "80"; + private static final int CACHINGTEMPLATE_LIMIT = 5; private static DesignerEnvManager designerEnvManager; // gui. private String activationKey = null; @@ -99,6 +100,7 @@ public class DesignerEnvManager implements XMLReadable, XMLWriter { private int language; //2014-8-26默认显示全部, 因为以前的版本, 虽然是false, 实际上是显示所有表, 因此这边要兼容 private boolean useOracleSystemSpace = true; + private int cachingTemplateLimit = CACHINGTEMPLATE_LIMIT; private boolean autoBackUp = true; private int undoLimit = 5; private short pageLengthUnit = Constants.UNIT_MM; @@ -146,6 +148,7 @@ public class DesignerEnvManager implements XMLReadable, XMLWriter { private boolean isHttps = false; private static List mapWorkerList = new ArrayList(); + private boolean imageCompress = false;//图片压缩 /** * DesignerEnvManager. @@ -244,7 +247,8 @@ public class DesignerEnvManager implements XMLReadable, XMLWriter { // 写文件的LogLocation String logLocation = DesignerEnvManager.getEnvManager().getLogLocation(); - if (logLocation != null) { + //Mac下8.0,9.0 选项-日志设置为空时在根目录下检测文件存在会抛无权限,这里应该设个默认值比较好吧 + if (StringUtils.isNotEmpty(logLocation)) { try { Calendar calender = GregorianCalendar.getInstance(); calender.setTimeInMillis(System.currentTimeMillis()); @@ -631,6 +635,21 @@ public class DesignerEnvManager implements XMLReadable, XMLWriter { this.useOracleSystemSpace = displayOracleSystem; } + /** + * 配置最大缓存模板个数 + */ + public void setCachingTemplateLimit(int cachingTemplateLimit) { + this.cachingTemplateLimit = cachingTemplateLimit; + } + + + /** + * 获取最大缓存模板个数 + */ + public int getCachingTemplateLimit() { + return this.cachingTemplateLimit; + } + /** * 是否加入产品改良 * @@ -1394,7 +1413,9 @@ public class DesignerEnvManager implements XMLReadable, XMLWriter { this.setMaxNumberOrPreviewRow(reader.getAttrAsInt("maxNumberOrPreviewRow", 200)); this.setOracleSystemSpace(reader.getAttrAsBoolean("useOracleSystemSpace", true)); + this.setCachingTemplateLimit(reader.getAttrAsInt("cachingTemplateLimit", CACHINGTEMPLATE_LIMIT)); this.setJoinProductImprove(reader.getAttrAsBoolean("joinProductImprove", true)); + this.setImageCompress(reader.getAttrAsBoolean("imageCompress", true)); this.setAutoBackUp(reader.getAttrAsBoolean("autoBackUp", true)); this.setTemplateTreePaneExpanded(reader.getAttrAsBoolean("templateTreePaneExpanded", false)); // peter:读取webinfLocation @@ -1614,9 +1635,15 @@ public class DesignerEnvManager implements XMLReadable, XMLWriter { if (!this.isOracleSystemSpace()) { writer.attr("useOracleSystemSpace", this.isOracleSystemSpace()); } + if (this.getCachingTemplateLimit() >= 0) { + writer.attr("cachingTemplateLimit", this.getCachingTemplateLimit()); + } if (!this.isJoinProductImprove()) { writer.attr("joinProductImprove", this.isJoinProductImprove()); } + if (!this.isImageCompress()) { + writer.attr("imageCompress", this.isImageCompress()); + } if (!this.isAutoBackUp()) { writer.attr("autoBackUp", this.isAutoBackUp()); } @@ -1790,4 +1817,12 @@ public class DesignerEnvManager implements XMLReadable, XMLWriter { public void setAlphaFineConfigManager(AlphaFineConfigManager alphaFineConfigManager) { this.alphaFineConfigManager = alphaFineConfigManager; } -} \ No newline at end of file + + public boolean isImageCompress() { + return imageCompress; + } + + public void setImageCompress(boolean imageCompress) { + this.imageCompress = imageCompress; + } +} diff --git a/designer-base/src/com/fr/design/actions/file/SwitchExistEnv.java b/designer-base/src/com/fr/design/actions/file/SwitchExistEnv.java index 57574ae25..ea709385f 100644 --- a/designer-base/src/com/fr/design/actions/file/SwitchExistEnv.java +++ b/designer-base/src/com/fr/design/actions/file/SwitchExistEnv.java @@ -36,6 +36,9 @@ import java.util.logging.Level; public class SwitchExistEnv extends MenuDef { + // 标志开始切换环境 + private static boolean isSwitching = false; + public SwitchExistEnv() { this.setMenuKeySet(KeySetUtils.SWITCH_ENV); this.setName(getMenuKeySet().getMenuName()); @@ -101,6 +104,7 @@ public class SwitchExistEnv extends MenuDef { * @param e 事件 */ public void actionPerformed(ActionEvent e) { + isSwitching = true; DesignerEnvManager envManager = DesignerEnvManager.getEnvManager(); Env selectedEnv = envManager.getEnv(this.getName()); try { @@ -117,13 +121,18 @@ public class SwitchExistEnv extends MenuDef { return; } SignIn.signIn(selectedEnv); - HistoryTemplateListPane.getInstance().getCurrentEditingTemplate().refreshToolArea(); fireDSChanged(); } catch (Exception em) { FRContext.getLogger().error(em.getMessage(), em); JOptionPane.showMessageDialog(DesignerContext.getDesignerFrame(), Inter.getLocText(new String[]{"M-SwitchWorkspace", "Failed"})); TemplatePane.getInstance().editItems(); + } finally { + isSwitching = false; } } } -} \ No newline at end of file + + public static boolean isSwitching() { + return isSwitching; + } +} diff --git a/designer-base/src/com/fr/design/file/FileOperations.java b/designer-base/src/com/fr/design/file/FileOperations.java index 34b86cbc6..390a28e0c 100644 --- a/designer-base/src/com/fr/design/file/FileOperations.java +++ b/designer-base/src/com/fr/design/file/FileOperations.java @@ -5,34 +5,34 @@ public interface FileOperations { /** *打开选中的报表文件 */ - public void openSelectedReport(); + public void openSelectedReport(); /** *打开文件夹 */ - public void openContainerFolder(); + public void openContainerFolder(); /** *刷新 */ - public void refresh(); + public void refresh(); /** *删除文件 */ - public void deleteFile(); + public void deleteFile(); /** *加上文件锁 */ - public void lockFile(); + public void lockFile(); /** *文件解锁 */ - public void unLockFile(); + public void unLockFile(); - public String getSelectedTemplatePath(); + public String getSelectedTemplatePath(); /** *文件名是否存在 @@ -41,5 +41,5 @@ public interface FileOperations { * @param suffix 后缀名 * @return 是否存在 */ - public boolean isNameAlreadyExist(String newName, String oldName, String suffix); -} \ No newline at end of file + public boolean isNameAlreadyExist(String newName, String oldName, String suffix); +} diff --git a/designer-base/src/com/fr/design/file/HistoryTemplateListPane.java b/designer-base/src/com/fr/design/file/HistoryTemplateListPane.java index dfd1f123f..deda53953 100644 --- a/designer-base/src/com/fr/design/file/HistoryTemplateListPane.java +++ b/designer-base/src/com/fr/design/file/HistoryTemplateListPane.java @@ -38,7 +38,7 @@ import com.fr.design.utils.gui.GUIPaintUtils; public class HistoryTemplateListPane extends JPanel implements FileOperations, CallbackEvent { //最大保存内存中面板数,为0时关闭优化内存 - private static final int DEAD_LINE = 5; + private static final int DEAD_LINE = DesignerEnvManager.getEnvManager().getCachingTemplateLimit(); private static final int LIST_BORDER = 4; private List> historyList; private JTemplate editingTemplate; @@ -438,4 +438,4 @@ public class HistoryTemplateListPane extends JPanel implements FileOperations, C return isNameAreadyExist; } -} \ No newline at end of file +} diff --git a/designer-base/src/com/fr/design/file/TemplateTreePane.java b/designer-base/src/com/fr/design/file/TemplateTreePane.java index 9061521a4..969a66f32 100644 --- a/designer-base/src/com/fr/design/file/TemplateTreePane.java +++ b/designer-base/src/com/fr/design/file/TemplateTreePane.java @@ -26,11 +26,7 @@ import com.sun.jna.platform.FileUtils; import javax.swing.*; import javax.swing.tree.DefaultMutableTreeNode; import java.awt.*; -import java.awt.event.KeyEvent; -import java.awt.event.KeyListener; -import java.awt.event.MouseAdapter; -import java.awt.event.MouseEvent; -import java.awt.event.MouseListener; +import java.awt.event.*; import java.io.File; import java.io.IOException; import java.util.ArrayList; @@ -143,7 +139,7 @@ public class TemplateTreePane extends JPanel implements FileOperations { public void openContainerFolder() { FileNode fn = TemplateTreePane.this.reportletsTree.getSelectedFileNode(); LocalEnv localEnv = (LocalEnv) FRContext.getCurrentEnv(); - String filePath = StableUtils.pathJoin(localEnv.path, fn.getEnvPath()); + String filePath = StableUtils.pathJoin(new String[]{localEnv.path, fn.getEnvPath()}); filePath = filePath.substring(0, filePath.lastIndexOf(CoreConstants.SEPARATOR)); try { Desktop.getDesktop().open(new File(filePath)); @@ -319,8 +315,6 @@ public class TemplateTreePane extends JPanel implements FileOperations { if (fileUtils.hasTrash()) { try { fileUtils.moveToTrash(new File[]{new File(StableUtils.pathJoin(nodeFile.getEnvPath(), nodeFile.getPath()))}); - //todo 走下这个流程,否则集群下其它节点无法同步删除 - FRContext.getCurrentEnv().deleteFile(nodeFile.getPath()); } catch (IOException e) { FRLogger.getLogger().info(e.getMessage()); FRContext.getCurrentEnv().deleteFile(nodeFile.getPath()); @@ -331,4 +325,4 @@ public class TemplateTreePane extends JPanel implements FileOperations { } } -} \ No newline at end of file +} diff --git a/designer-base/src/com/fr/design/mainframe/DesignerFrame.java b/designer-base/src/com/fr/design/mainframe/DesignerFrame.java index 41d755905..06911ee1d 100644 --- a/designer-base/src/com/fr/design/mainframe/DesignerFrame.java +++ b/designer-base/src/com/fr/design/mainframe/DesignerFrame.java @@ -6,17 +6,26 @@ package com.fr.design.mainframe; import com.fr.base.BaseUtils; import com.fr.base.Env; import com.fr.base.FRContext; +import com.fr.base.vcs.DesignerMode; import com.fr.design.DesignModelAdapter; import com.fr.design.DesignState; import com.fr.design.DesignerEnvManager; import com.fr.design.ExtraDesignClassManager; +import com.fr.design.actions.core.ActionFactory; +import com.fr.design.actions.file.SwitchExistEnv; import com.fr.design.constants.UIConstants; import com.fr.design.data.DesignTableDataManager; import com.fr.design.data.datapane.TableDataTreePane; +import com.fr.design.event.DesignerOpenedListener; import com.fr.design.event.TargetModifiedEvent; import com.fr.design.event.TargetModifiedListener; -import com.fr.design.file.*; +import com.fr.design.file.HistoryTemplateListPane; +import com.fr.design.file.MutilTempalteTabPane; +import com.fr.design.file.NewTemplatePane; +import com.fr.design.file.SaveSomeTemplatePane; +import com.fr.design.file.TemplateTreePane; import com.fr.design.fun.TitlePlaceProcessor; +import com.fr.design.fun.impl.AbstractTemplateTreeShortCutProvider; import com.fr.design.gui.ibutton.UIButton; import com.fr.design.gui.imenu.UIMenuHighLight; import com.fr.design.gui.iscrollbar.UIScrollBar; @@ -26,6 +35,7 @@ import com.fr.design.mainframe.loghandler.LogMessageBar; import com.fr.design.mainframe.toolbar.ToolBarMenuDock; import com.fr.design.mainframe.toolbar.ToolBarMenuDockPlus; import com.fr.design.menu.MenuManager; +import com.fr.design.menu.ShortCut; import com.fr.design.utils.DesignUtils; import com.fr.design.utils.gui.GUICoreUtils; import com.fr.file.FILE; @@ -54,14 +64,27 @@ import javax.swing.border.MatteBorder; import java.awt.*; import java.awt.datatransfer.DataFlavor; import java.awt.datatransfer.Transferable; -import java.awt.dnd.*; -import java.awt.event.*; +import java.awt.dnd.DnDConstants; +import java.awt.dnd.DropTarget; +import java.awt.dnd.DropTargetDragEvent; +import java.awt.dnd.DropTargetDropEvent; +import java.awt.dnd.DropTargetEvent; +import java.awt.dnd.DropTargetListener; +import java.awt.event.ComponentAdapter; +import java.awt.event.ComponentEvent; +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; +import java.awt.event.MouseListener; +import java.awt.event.WindowAdapter; +import java.awt.event.WindowEvent; +import java.awt.event.WindowListener; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; +import java.util.Set; import java.util.logging.Level; public class DesignerFrame extends JFrame implements JTemplateActionListener, TargetModifiedListener { @@ -74,7 +97,12 @@ public class DesignerFrame extends JFrame implements JTemplateActionListener, Ta private static final Integer TOP_LAYER = new Integer((200)); private static java.util.List> appList = new java.util.ArrayList>(); - private ToolBarMenuDock ad; + private List designerOpenedListenerList = new ArrayList<>(); + + //顶部日志+登陆按钮 + private static final JPanel northEastPane = FRGUIPaneFactory.createBorderLayout_S_Pane(); + + private static ToolBarMenuDock ad; private DesktopCardPane centerTemplateCardPane; @@ -158,8 +186,8 @@ public class DesignerFrame extends JFrame implements JTemplateActionListener, Ta } public void mouseReleased(MouseEvent e) { - if (BaseUtils.isAuthorityEditing()) { - BaseUtils.setAuthorityEditing(false); + if (DesignerMode.isAuthorityEditing()) { + DesignerMode.setMode(DesignerMode.NORMARL); WestRegionContainerPane.getInstance().replaceDownPane( TableDataTreePane.getInstance(DesignModelAdapter.getCurrentModelAdapter())); HistoryTemplateListPane.getInstance().getCurrentEditingTemplate().refreshEastPropertiesPane(); @@ -235,7 +263,7 @@ public class DesignerFrame extends JFrame implements JTemplateActionListener, Ta this.addComponentListener(new ComponentAdapter() { public void componentResized(ComponentEvent e) { reCalculateFrameSize(); - if (BaseUtils.isAuthorityEditing()) { + if (DesignerMode.isAuthorityEditing()) { doResize(); } } @@ -266,6 +294,22 @@ public class DesignerFrame extends JFrame implements JTemplateActionListener, Ta } } + /** + * 注册"设计器初始化完成"的监听 + */ + public void addDesignerOpenedListener(DesignerOpenedListener listener) { + designerOpenedListenerList.add(listener); + } + + /** + * 触发"设计器初始化完成"事件 + */ + public void fireDesignerOpened() { + for (DesignerOpenedListener listener : designerOpenedListenerList) { + listener.designerOpened(); + } + } + protected DesktopCardPane getCenterTemplateCardPane() { return centerTemplateCardPane; } @@ -276,41 +320,39 @@ public class DesignerFrame extends JFrame implements JTemplateActionListener, Ta protected void initMenuPane() { menuPane = FRGUIPaneFactory.createBorderLayout_S_Pane(); menuPane.add(new UIMenuHighLight(), BorderLayout.SOUTH); - menuPane.add(initNorthEastPane(ad), BorderLayout.EAST); + menuPane.add(initNorthEastPane(), BorderLayout.EAST); basePane.add(menuPane, BorderLayout.NORTH); this.resetToolkitByPlus(null); } /** - * @param ad * @return */ - protected JPanel initNorthEastPane(final ToolBarMenuDock ad) { + protected JPanel initNorthEastPane() { //hugh: private修改为protected方便oem的时候修改右上的组件构成 - //顶部日志+登陆按钮 - final JPanel northEastPane = FRGUIPaneFactory.createBorderLayout_S_Pane(); + //优先级为-1,保证最后全面刷新一次 GeneralContext.listenPluginRunningChanged(new PluginEventListener(-1) { @Override public void on(PluginEvent event) { - refreshNorthEastPane(northEastPane, ad); + refreshNorthEastPane(); DesignUtils.refreshDesignerFrame(FRContext.getCurrentEnv()); } }, new PluginFilter() { @Override public boolean accept(PluginContext context) { - - return context.contain(PluginModule.ExtraDesign); + return !SwitchExistEnv.isSwitching() + && context.contain(PluginModule.ExtraDesign); } }); - refreshNorthEastPane(northEastPane, ad); + refreshNorthEastPane(); return northEastPane; } - private void refreshNorthEastPane(JPanel northEastPane, ToolBarMenuDock ad) { + public static void refreshNorthEastPane() { northEastPane.removeAll(); northEastPane.setLayout(new FlowLayout(FlowLayout.RIGHT, 0, 0)); northEastPane.add(LogMessageBar.getInstance()); @@ -415,7 +457,7 @@ public class DesignerFrame extends JFrame implements JTemplateActionListener, Ta * 刷新 */ public void refreshDottedLine() { - if (BaseUtils.isAuthorityEditing()) { + if (DesignerMode.isAuthorityEditing()) { populateAuthorityArea(); populateCloseButton(); addDottedLine(); @@ -474,7 +516,7 @@ public class DesignerFrame extends JFrame implements JTemplateActionListener, Ta for (int i = 0; i < fixButtons.length; i++) { combineUp.add(fixButtons[i]); } - if (!BaseUtils.isAuthorityEditing()) { + if (!DesignerMode.isAuthorityEditing()) { combineUp.addSeparator(new Dimension(2, 16)); if (toolbar4Form != null) { for (int i = 0; i < toolbar4Form.length; i++) { @@ -585,7 +627,16 @@ public class DesignerFrame extends JFrame implements JTemplateActionListener, Ta */ public void needToAddAuhtorityPaint() { - newWorkBookPane.setButtonGray(BaseUtils.isAuthorityEditing()); + newWorkBookPane.setButtonGray(DesignerMode.isAuthorityEditing()); + + // 进入或退出权限编辑模式,通知插件 + Set extraShortCuts = ExtraDesignClassManager.getInstance().getExtraShortCuts(); + for (ShortCut shortCut : extraShortCuts) { + if (shortCut instanceof AbstractTemplateTreeShortCutProvider) { + ((AbstractTemplateTreeShortCutProvider) shortCut).notifyFromAuhtorityChange(DesignerMode.isAuthorityEditing()); + } + } + } /** @@ -665,13 +716,16 @@ public class DesignerFrame extends JFrame implements JTemplateActionListener, Ta * @param env 环境 */ public void refreshEnv(Env env) { - this.setTitle(); DesignerFrameFileDealerPane.getInstance().refreshDockingView(); TableDataTreePane.getInstance(DesignModelAdapter.getCurrentModelAdapter()); TemplateTreePane.getInstance().refreshDockingView(); DesignTableDataManager.clearGlobalDs(); EastRegionContainerPane.getInstance().refreshDownPane(); + JTemplate template = HistoryTemplateListPane.getInstance().getCurrentEditingTemplate(); + if (template != null) { + template.refreshToolArea(); + } } /** @@ -734,6 +788,8 @@ public class DesignerFrame extends JFrame implements JTemplateActionListener, Ta * @param jt 添加的模板. */ public void addAndActivateJTemplate(JTemplate jt) { + //释放模板对象 + ActionFactory.editorRelease(); if (jt == null || jt.getEditingFILE() == null) { return; } @@ -750,6 +806,8 @@ public class DesignerFrame extends JFrame implements JTemplateActionListener, Ta * @param jt 模板 */ public void activateJTemplate(JTemplate jt) { + //释放模板对象 + ActionFactory.editorRelease(); if (jt == null || jt.getEditingFILE() == null) { return; } @@ -855,13 +913,16 @@ public class DesignerFrame extends JFrame implements JTemplateActionListener, Ta String fileExtention = fileName.substring(indexOfLastDot + 1); for (int i = 0, len = appList.size(); i < len; i++) { App app = appList.get(i); - String[] defaultAppExtentions = app.defaultExtensions(); + String[] defaultAppExtentions = app.defaultExtentions(); boolean opened = false; for (int j = 0; j < defaultAppExtentions.length; j++) { if (defaultAppExtentions[j].equalsIgnoreCase(fileExtention)) { - // 不要catch - JTemplate jt = app.openTemplate(tplFile); - + JTemplate jt = null; + try { + jt = app.openTemplate(tplFile); + } catch (Exception e) { + FRLogger.getLogger().error(e.getMessage(), e); + } if (jt == null) { return; } @@ -908,8 +969,6 @@ public class DesignerFrame extends JFrame implements JTemplateActionListener, Ta } else { this.addAndActivateJTemplate(jt); } - //REPORT-5084:激活后刷新一下右側面板 - jt.refreshEastPropertiesPane(); } /** @@ -1021,4 +1080,4 @@ public class DesignerFrame extends JFrame implements JTemplateActionListener, Ta } } -} \ No newline at end of file +} diff --git a/designer-base/src/com/fr/design/mainframe/DesignerFrameFileDealerPane.java b/designer-base/src/com/fr/design/mainframe/DesignerFrameFileDealerPane.java index 5e68607b1..e5cfdfa69 100644 --- a/designer-base/src/com/fr/design/mainframe/DesignerFrameFileDealerPane.java +++ b/designer-base/src/com/fr/design/mainframe/DesignerFrameFileDealerPane.java @@ -2,6 +2,7 @@ package com.fr.design.mainframe; import com.fr.base.BaseUtils; import com.fr.base.FRContext; +import com.fr.base.vcs.DesignerMode; import com.fr.design.DesignModelAdapter; import com.fr.design.DesignerEnvManager; import com.fr.design.ExtraDesignClassManager; @@ -10,7 +11,11 @@ import com.fr.design.constants.UIConstants; import com.fr.design.data.DesignTableDataManager; import com.fr.design.data.datapane.TableDataTreePane; import com.fr.design.data.tabledata.ResponseDataSourceChange; -import com.fr.design.file.*; +import com.fr.design.file.FileOperations; +import com.fr.design.file.FileToolbarStateChangeListener; +import com.fr.design.file.HistoryTemplateListPane; +import com.fr.design.file.MutilTempalteTabPane; +import com.fr.design.file.TemplateTreePane; import com.fr.design.gui.ibutton.UIButton; import com.fr.design.gui.ilable.UILabel; import com.fr.design.gui.imenu.UIMenuHighLight; @@ -28,7 +33,6 @@ import com.fr.file.FileNodeFILE; import com.fr.file.filetree.FileNode; import com.fr.general.ComparatorUtils; import com.fr.general.Inter; -import com.fr.io.utils.ResourceIOUtils; import com.fr.stable.CoreConstants; import com.fr.stable.StableUtils; import com.fr.stable.project.ProjectConstants; @@ -42,6 +46,7 @@ import java.awt.event.ActionListener; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.io.File; +import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import java.util.Set; @@ -52,6 +57,11 @@ public class DesignerFrameFileDealerPane extends JPanel implements FileToolbarSt private CardLayout card; private JPanel cardPane; + private java.util.List otherToobarStateChangeListeners= new ArrayList<>(); + + public FileOperations getSelectedOperation() { + return selectedOperation; + } private FileOperations selectedOperation; private UIToolbar toolBar; @@ -110,7 +120,7 @@ public class DesignerFrameFileDealerPane extends JPanel implements FileToolbarSt HistoryTemplateListPane.getInstance().setCurrentEditingTemplate(jt); //处理自动新建的模板 MutilTempalteTabPane.getInstance().doWithtemTemplate(); - if (BaseUtils.isAuthorityEditing()) { + if (DesignerMode.isAuthorityEditing()) { RolesAlreadyEditedPane.getInstance().refreshDockingView(); } @@ -134,7 +144,7 @@ public class DesignerFrameFileDealerPane extends JPanel implements FileToolbarSt } toolbarDef.addShortCut(delFileAction); Set extraShortCuts = ExtraDesignClassManager.getInstance().getExtraShortCuts(); - for (ShortCut shortCut : extraShortCuts){ + for (ShortCut shortCut : extraShortCuts) { toolbarDef.addShortCut(shortCut); } @@ -160,8 +170,9 @@ public class DesignerFrameFileDealerPane extends JPanel implements FileToolbarSt } /** - * 响应数据集改变 - * @param map 改变名字的数据集 + * 响应数据集改变 + * + * @param map 改变名字的数据集 */ public void fireDSChanged(Map map) { DesignTableDataManager.fireDSChanged(map); @@ -212,6 +223,21 @@ public class DesignerFrameFileDealerPane extends JPanel implements FileToolbarSt public void actionPerformed(ActionEvent evt) { selectedOperation.refresh(); stateChange(); + + } + } + + public void addToobarStateChangeListener(FileToolbarStateChangeListener toobarStateChangeListener) { + this.otherToobarStateChangeListeners.add(toobarStateChangeListener); + } + + public void removeToobarStateChangeListener(FileToolbarStateChangeListener toobarStateChangeListener) { + this.otherToobarStateChangeListeners.remove(toobarStateChangeListener); + } + + private void otherStateChange() { + for (FileToolbarStateChangeListener toobarStateChangeListener : otherToobarStateChangeListeners) { + toobarStateChangeListener.stateChange(); } } @@ -295,8 +321,8 @@ public class DesignerFrameFileDealerPane extends JPanel implements FileToolbarSt openReportAction.setEnabled(false); } FileNode node = TemplateTreePane.getInstance().getTemplateFileTree().getSelectedFileNode(); - if (selectedOperation.getSelectedTemplatePath() != null){ - if (node.getLock() != null && !ComparatorUtils.equals(node.getUserID(),node.getLock())){ + if (selectedOperation.getSelectedTemplatePath() != null) { + if (node.getLock() != null && !ComparatorUtils.equals(node.getUserID(), node.getLock())) { delFileAction.setEnabled(false); } else { delFileAction.setEnabled(true); @@ -329,6 +355,7 @@ public class DesignerFrameFileDealerPane extends JPanel implements FileToolbarSt delFileAction.setEnabled(true); } + otherStateChange(); } /** @@ -383,8 +410,8 @@ public class DesignerFrameFileDealerPane extends JPanel implements FileToolbarSt return; } - final FileNodeFILE nodeFile = new FileNodeFILE(new FileNode(StableUtils.pathJoin(ProjectConstants.REPORTLETS_NAME, reportPath), false)); - final String path = nodeFile.getPath(); + final FileNodeFILE nodeFile = new FileNodeFILE(new FileNode(StableUtils.pathJoin(new String[]{ProjectConstants.REPORTLETS_NAME, reportPath}), false)); + final String path = StableUtils.pathJoin(new String[]{nodeFile.getEnvPath(), nodeFile.getPath()}); oldName = nodeFile.getName(); suffix = oldName.substring(oldName.lastIndexOf(CoreConstants.DOT), oldName.length()); oldName = oldName.replaceAll(suffix, ""); @@ -477,9 +504,8 @@ public class DesignerFrameFileDealerPane extends JPanel implements FileToolbarSt String newPath = path.replace(nodeFile.getName(), userInput + suffix); renameTemplateInMemory(nodeFile, userInput + suffix, oldName + suffix); DesignerEnvManager.getEnvManager().replaceRecentOpenedFilePath(oldPath, newPath.replaceAll("/", "\\\\")); - - //模版重命名 - ResourceIOUtils.renameTo(path, newPath); + File newFile = new File(newPath); + new File(path).renameTo(newFile); selectedOperation.refresh(); DesignerContext.getDesignerFrame().setTitle(); jd.dispose(); @@ -569,4 +595,4 @@ public class DesignerFrameFileDealerPane extends JPanel implements FileToolbarSt return null; } -} \ No newline at end of file +} diff --git a/designer-base/src/com/fr/design/mainframe/TemplatePane.java b/designer-base/src/com/fr/design/mainframe/TemplatePane.java index 0aa0258a9..e5cfdfa69 100644 --- a/designer-base/src/com/fr/design/mainframe/TemplatePane.java +++ b/designer-base/src/com/fr/design/mainframe/TemplatePane.java @@ -1,278 +1,598 @@ package com.fr.design.mainframe; import com.fr.base.BaseUtils; -import com.fr.base.Env; -import com.fr.dav.LocalEnv; +import com.fr.base.FRContext; +import com.fr.base.vcs.DesignerMode; import com.fr.design.DesignModelAdapter; import com.fr.design.DesignerEnvManager; -import com.fr.design.dialog.BasicDialog; -import com.fr.design.dialog.DialogActionAdapter; -import com.fr.design.dialog.InformationWarnPane; +import com.fr.design.ExtraDesignClassManager; +import com.fr.design.actions.UpdateAction; +import com.fr.design.constants.UIConstants; +import com.fr.design.data.DesignTableDataManager; +import com.fr.design.data.datapane.TableDataTreePane; +import com.fr.design.data.tabledata.ResponseDataSourceChange; +import com.fr.design.file.FileOperations; +import com.fr.design.file.FileToolbarStateChangeListener; import com.fr.design.file.HistoryTemplateListPane; +import com.fr.design.file.MutilTempalteTabPane; import com.fr.design.file.TemplateTreePane; import com.fr.design.gui.ibutton.UIButton; import com.fr.design.gui.ilable.UILabel; -import com.fr.env.EnvListPane; -import com.fr.env.RemoteEnv; -import com.fr.env.SignIn; +import com.fr.design.gui.imenu.UIMenuHighLight; +import com.fr.design.gui.itextfield.UITextField; +import com.fr.design.gui.itoolbar.UIToolbar; +import com.fr.design.gui.itree.filetree.TemplateFileTree; +import com.fr.design.layout.FRGUIPaneFactory; +import com.fr.design.menu.KeySetUtils; +import com.fr.design.menu.ShortCut; +import com.fr.design.menu.ToolBarDef; +import com.fr.design.roleAuthority.RolesAlreadyEditedPane; +import com.fr.design.utils.gui.GUICoreUtils; +import com.fr.file.FILE; +import com.fr.file.FileNodeFILE; +import com.fr.file.filetree.FileNode; import com.fr.general.ComparatorUtils; -import com.fr.general.GeneralContext; import com.fr.general.Inter; -import com.fr.stable.EnvChangedListener; -import com.fr.stable.ProductConstants; -import com.fr.stable.StringUtils; +import com.fr.stable.CoreConstants; +import com.fr.stable.StableUtils; +import com.fr.stable.project.ProjectConstants; import javax.swing.*; +import javax.swing.event.DocumentEvent; +import javax.swing.event.DocumentListener; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; -import java.awt.event.MouseEvent; -import java.awt.event.MouseListener; +import java.awt.event.KeyAdapter; +import java.awt.event.KeyEvent; +import java.io.File; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Map; +import java.util.Set; -//TODO: august TemplatePane和TemplateTreePane最好合并成一个类 -public class TemplatePane extends JPanel implements MouseListener { - private static final long NUM = 1L; - private static int NUM200 = 200; +public class DesignerFrameFileDealerPane extends JPanel implements FileToolbarStateChangeListener, ResponseDataSourceChange { + private static final String FILE = "file"; + private static DesignerFrameFileDealerPane THIS; - public static TemplatePane getInstance() { - return HOLDER.singleton; + private CardLayout card; + private JPanel cardPane; + private java.util.List otherToobarStateChangeListeners= new ArrayList<>(); + + public FileOperations getSelectedOperation() { + return selectedOperation; } - private static class HOLDER { - private static TemplatePane singleton = new TemplatePane(); + private FileOperations selectedOperation; + private UIToolbar toolBar; + + private OpenReportAction openReportAction = new OpenReportAction(); + private RefreshTreeAction refreshTreeAction = new RefreshTreeAction(); + private OpenFolderAction openFolderAction = new OpenFolderAction(); + private RenameAction renameAction = new RenameAction(); + private DelFileAction delFileAction = new DelFileAction(); + + + /** + * 刷新 + */ + public void refresh() { + selectedOperation.refresh(); } - private static final long serialVersionUID = 2108412478281713143L; - public static final int HEIGHT = 23;// 最好和日志的高度统一 用同一个变量 - private static javax.swing.Icon leftIcon = BaseUtils.readIcon("/com/fr/design/images/docking/left.png"); - ; - private static javax.swing.Icon rightIcon = BaseUtils.readIcon("/com/fr/design/images/docking/right.png"); - ; - private boolean isExpanded = false; - private UIButton editButton; - private UILabel envLabel; - - private TemplatePane() { - super(); - this.initComponents(); - this.setFocusable(true); - this.addMouseListener(this); - isExpanded = DesignerEnvManager.getEnvManager().isTemplateTreePaneExpanded(); - // TemplateTreePane.getInstance().setVisible(isExpanded); - TemplateTreePane.getInstance().setVisible(true); + public static final DesignerFrameFileDealerPane getInstance() { + if (THIS == null) { + THIS = new DesignerFrameFileDealerPane(); + } + return THIS; } - private void initComponents() { - GeneralContext.addEnvChangedListener(new EnvChangedListener() { - public void envChanged() { - setJLabel(DesignerEnvManager.getEnvManager().getCurEnvName()); - } - }); - this.setLayout(new BorderLayout(25, 0)); - editButton = new UIButton(BaseUtils.readIcon("/com/fr/design/images/control/control-center2.png")) { - private static final long serialVersionUID = NUM; - - @Override - public Point getToolTipLocation(MouseEvent event) { - return new Point(25, 2); - } - }; - editButton.setOpaque(false); - editButton.setBorder(BorderFactory.createEmptyBorder(2, 0, 0, 10)); - editButton.setMargin(null); - editButton.setCursor(new Cursor(Cursor.HAND_CURSOR)); - editButton.setToolTipText(Inter.getLocText("Env-Configure_Workspace")); - this.add(new UILabel(" "), BorderLayout.WEST); - this.add(editButton, BorderLayout.EAST); - editButton.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent evt) { - editItems(); - } - }); - envLabel = new UILabel(); - envLabel.setForeground(new Color(102, 102, 102)); - setJLabel(DesignerEnvManager.getEnvManager().getCurEnvName()); - this.add(envLabel, BorderLayout.CENTER); + private DesignerFrameFileDealerPane() { + setLayout(new BorderLayout()); + toolBar = ToolBarDef.createJToolBar(); + toolBar.setBorder(BorderFactory.createMatteBorder(0, 0, 1, 0, UIConstants.TOOLBAR_BORDER_COLOR)); + toolBar.setBorderPainted(true); + JPanel tooBarPane = FRGUIPaneFactory.createBorderLayout_S_Pane(); + JPanel parent = new JPanel(new BorderLayout()); + parent.add(toolBar, BorderLayout.CENTER); + parent.setBorder(BorderFactory.createEmptyBorder(3, 0, 4, 0)); + tooBarPane.add(parent, BorderLayout.CENTER); + tooBarPane.add(new UIMenuHighLight(), BorderLayout.SOUTH); + + add(tooBarPane, BorderLayout.NORTH); + cardPane = new JPanel(card = new CardLayout()); + cardPane.add(TemplateTreePane.getInstance(), FILE); + + selectedOperation = TemplateTreePane.getInstance(); + card.show(cardPane, FILE); + + TemplateTreePane.getInstance().setToobarStateChangeListener(this); + + add(cardPane, BorderLayout.CENTER); + stateChange(); + } + + + public final void setCurrentEditingTemplate(JTemplate jt) { + DesignModelAdapter.setCurrentModelAdapter(jt == null ? null : jt.getModel()); + fireDSChanged(); + TableDataTreePane.getInstance(DesignModelAdapter.getCurrentModelAdapter()); + HistoryTemplateListPane.getInstance().setCurrentEditingTemplate(jt); + //处理自动新建的模板 + MutilTempalteTabPane.getInstance().doWithtemTemplate(); + if (DesignerMode.isAuthorityEditing()) { + RolesAlreadyEditedPane.getInstance().refreshDockingView(); + } + + jt.setComposite(); + jt.refreshToolArea(); + jt.fireJTemplateOpened(); + jt.requestFocus(); + jt.revert(); + + FRContext.getLogger().info("\"" + jt.getEditingFILE().getName() + "\"" + Inter.getLocText("LOG-Has_Been_Openned") + "!"); } /** - * 是否可扩展 - * @return 同上 + * 刷新菜单 */ - public boolean IsExpanded() { - return this.isExpanded; + public void refreshDockingView() { + ToolBarDef toolbarDef = new ToolBarDef(); + toolbarDef.addShortCut(openReportAction, refreshTreeAction); + if (FRContext.getCurrentEnv().isSupportLocalFileOperate()) { + toolbarDef.addShortCut(openFolderAction, renameAction); + } + toolbarDef.addShortCut(delFileAction); + Set extraShortCuts = ExtraDesignClassManager.getInstance().getExtraShortCuts(); + for (ShortCut shortCut : extraShortCuts) { + toolbarDef.addShortCut(shortCut); + } + + toolbarDef.updateToolBar(toolBar); + refreshActions(); } - public void setExpand(boolean b) { - this.isExpanded = b; + + private void refreshActions() { + openReportAction.setEnabled(false); + refreshTreeAction.setEnabled(true); + openFolderAction.setEnabled(false); + renameAction.setEnabled(false); + delFileAction.setEnabled(false); this.repaint(); } - private boolean envListOkAction(EnvListPane envListPane) { - String selectedName = envListPane.updateEnvManager(); - DesignerEnvManager envManager = DesignerEnvManager.getEnvManager(); - Env selectedEnv = envManager.getEnv(selectedName); - GeneralContext.fireEnvWillChangeListener(); - try { - //如果是远程的还要先测试下,如果失败就不切换 - if (selectedEnv instanceof RemoteEnv) { - if (!((RemoteEnv) selectedEnv).testServerConnection()) { - JOptionPane.showMessageDialog(DesignerContext.getDesignerFrame(), Inter.getLocText(new String[]{"M-SwitchWorkspace", "Failed"})); - return false; - } else { - String remoteVersion = selectedEnv.getDesignerVersion(); - if (StringUtils.isBlank(remoteVersion) || ComparatorUtils.compare(remoteVersion, ProductConstants.DESIGNER_VERSION) < 0) { - String infor = Inter.getLocText("Server-version-tip"); - String moreInfo = Inter.getLocText("Server-version-tip-moreInfo"); - new InformationWarnPane(infor, moreInfo, Inter.getLocText("Tooltips")).show(); - return false; - } - } - } - SignIn.signIn(selectedEnv); - JTemplate template = HistoryTemplateListPane.getInstance().getCurrentEditingTemplate(); - if (template != null) { - template.refreshToolArea(); - } - setJLabel(selectedName); - } catch (Exception e) { - JOptionPane.showMessageDialog(DesignerContext.getDesignerFrame(), Inter.getLocText(new String[]{"M-SwitchWorkspace", "Failed"})); - return false; - } - TemplateTreePane.getInstance().refreshDockingView(); - DesignModelAdapter model = DesignModelAdapter.getCurrentModelAdapter(); - if (model != null) { - model.envChanged(); - } - return true; + /** + * 响应数据集改变 + */ + public void fireDSChanged() { + fireDSChanged(new HashMap()); } /** - * 编辑items + * 响应数据集改变 + * + * @param map 改变名字的数据集 */ - public void editItems() { - final EnvListPane envListPane = new EnvListPane(); - final BasicDialog envListDialog = envListPane.showWindow(SwingUtilities.getWindowAncestor(DesignerContext.getDesignerFrame())); - - envListPane.populateEnvManager(envLabel.getText()); - envListDialog.addDialogActionListener(new DialogActionAdapter() { - public void doOk() { - envListOkAction(envListPane); - } + public void fireDSChanged(Map map) { + DesignTableDataManager.fireDSChanged(map); + } + + + /* + * Open Report Action + */ + private class OpenReportAction extends UpdateAction { + + public OpenReportAction() { + this.setName(KeySetUtils.OPEN_TEMPLATE.getMenuKeySetName()); + this.setSmallIcon(BaseUtils.readIcon("/com/fr/design/images/buttonicon/open.png")); + } + + @Override + public void actionPerformed(ActionEvent evt) { + selectedOperation.openSelectedReport(); + } - public void doCancel() { - envListDialog.setVisible(false); - } - }); - envListDialog.setVisible(true); } - private void setJLabel(String name) { - if (DesignerEnvManager.getEnvManager().getEnv(name) instanceof LocalEnv) { - envLabel.setIcon(BaseUtils.readIcon("com/fr/design/images/data/bind/localconnect.png")); + private class OpenFolderAction extends UpdateAction { + + public OpenFolderAction() { + this.setName(Inter.getLocText("FR-Designer_Show_in_Containing_Folder")); + this.setSmallIcon(BaseUtils.readIcon("/com/fr/design/images/m_file/view_folder.png")); + } - } else if (DesignerEnvManager.getEnvManager().getEnv(name) instanceof RemoteEnv) { - envLabel.setIcon(BaseUtils.readIcon("com/fr/design/images/data/bind/distanceconnect.png")); + @Override + public void actionPerformed(ActionEvent evt) { + selectedOperation.openContainerFolder(); } - envLabel.setText(name); - envLabel.repaint(); } - @Override - public Dimension getPreferredSize() { - return new Dimension(250, HEIGHT); + /* + * 刷新ReportletsTree + */ + private class RefreshTreeAction extends UpdateAction { + + public RefreshTreeAction() { + this.setName(Inter.getLocText("FR-Designer_Refresh")); + this.setSmallIcon(UIConstants.REFRESH_ICON); + } + + @Override + public void actionPerformed(ActionEvent evt) { + selectedOperation.refresh(); + stateChange(); + + } } - @Override - public void paintComponent(Graphics g) { - super.paintComponent(g); - paintBackgroundIcon(g); + public void addToobarStateChangeListener(FileToolbarStateChangeListener toobarStateChangeListener) { + this.otherToobarStateChangeListeners.add(toobarStateChangeListener); } - private void paintBackgroundIcon(Graphics g) { - int w = this.getWidth(); - int h = this.getHeight(); - Graphics2D g2d = (Graphics2D) g; - Color lightColor = new Color(226, 230, 234); - Color darkColor = new Color(183, 188, 195); - GradientPaint gp = new GradientPaint(1, 1, lightColor, 1, h - 1, darkColor); - g2d.setPaint(gp); - g2d.fillRect(1, 1, w - 2, h - 1); - g2d.setColor(lightColor); - g2d.drawLine(0, 2, 0, h - 1); - g2d.setColor(darkColor); - g2d.drawLine(w - 1, 2, w - 1, h - 1); - Icon icon = !isExpanded ? leftIcon : rightIcon; - icon.paintIcon(this, g2d, 4, 4); + public void removeToobarStateChangeListener(FileToolbarStateChangeListener toobarStateChangeListener) { + this.otherToobarStateChangeListeners.remove(toobarStateChangeListener); + } + private void otherStateChange() { + for (FileToolbarStateChangeListener toobarStateChangeListener : otherToobarStateChangeListeners) { + toobarStateChangeListener.stateChange(); + } } - /** - * 鼠标点击 - * @param e 事件 + /* + * 重命名文件 */ - @Override - public void mouseClicked(MouseEvent e) { + private class RenameAction extends UpdateAction { + + public RenameAction() { + this.setName(Inter.getLocText("FR-Designer_Rename")); + this.setSmallIcon(BaseUtils.readIcon("/com/fr/design/images/data/source/rename.png")); + } + + @Override + public void actionPerformed(ActionEvent evt) { + new RenameDialog(); + MutilTempalteTabPane.getInstance().repaint(); + } + } - /** - * 鼠标按下 - * @param e 事件 + /* + * 删除指定文件 */ - @Override - public void mousePressed(MouseEvent e) { - if (e.getX() < NUM200) { - isExpanded = !isExpanded; - TemplateTreePane.getInstance().setVisible(isExpanded); - this.setExpand(isExpanded); - DesignerEnvManager.getEnvManager().setTemplateTreePaneExpanded(isExpanded); + private class DelFileAction extends UpdateAction { + + public DelFileAction() { + this.setName(Inter.getLocText("FR-Designer_Remove")); + this.setSmallIcon(BaseUtils.readIcon("/com/fr/design/images/data/source/delete.png")); + } + + @Override + public void actionPerformed(ActionEvent evt) { + selectedOperation.deleteFile(); } } - /** - * 鼠标放开 - * @param e 事件 + /* + * 加锁 */ - @Override - public void mouseReleased(MouseEvent e) { + private class GetLockAction extends UpdateAction { + + public GetLockAction() { + this.setName(Inter.getLocText("FR-Designer_Get_Lock")); + this.setSmallIcon(BaseUtils.readIcon("/com/fr/design/images/control/lock.png")); + } + + @Override + public void actionPerformed(ActionEvent evt) { + selectedOperation.lockFile(); + } + } + + /* + * 解锁 + */ + private class ReleaseLockAction extends UpdateAction { + + public ReleaseLockAction() { + this.setName(Inter.getLocText("FR-Designer_Release_Lock")); + this.setSmallIcon(BaseUtils.readIcon("/com/fr/design/images/control/unlock.png")); + } + + @Override + public void actionPerformed(ActionEvent evt) { + selectedOperation.unLockFile(); + } } /** - * 鼠标进入 - * @param e 事件 + * 按钮状态改变 */ @Override - public void mouseEntered(MouseEvent e) { + public void stateChange() { + //当前环境为远程环境时 + if (FRContext.getCurrentEnv() != null) { + if (!FRContext.getCurrentEnv().isSupportLocalFileOperate()) { + if (selectedOperation.getSelectedTemplatePath() != null) { + openReportAction.setEnabled(true); + } else { + openReportAction.setEnabled(false); + } + FileNode node = TemplateTreePane.getInstance().getTemplateFileTree().getSelectedFileNode(); + if (selectedOperation.getSelectedTemplatePath() != null) { + if (node.getLock() != null && !ComparatorUtils.equals(node.getUserID(), node.getLock())) { + delFileAction.setEnabled(false); + } else { + delFileAction.setEnabled(true); + } + } else { + delFileAction.setEnabled(false); + } + } else { + //当前环境为本地环境时 + if (selectedOperation.getSelectedTemplatePath() != null) { + openReportAction.setEnabled(true); + renameAction.setEnabled(true); + delFileAction.setEnabled(true); + } else { + openReportAction.setEnabled(false); + renameAction.setEnabled(false); + delFileAction.setEnabled(false); + } + openFolderAction.setEnabled(containsFolderNums() + seletedTemplateNums() != 0); + } + refreshTreeAction.setEnabled(true); + } + if (containsFolderNums() > 0 && (containsFolderNums() + seletedTemplateNums() > 1)) { + refreshActions(); + } else if (containsFolderNums() == 0 && seletedTemplateNums() > 1) { + openReportAction.setEnabled(false); + refreshTreeAction.setEnabled(true); + openFolderAction.setEnabled(false); + renameAction.setEnabled(false); + delFileAction.setEnabled(true); + } + + otherStateChange(); } /** - * 鼠标离开 - * @param e 事件 + * 是否包含文件夹 + * + * @return */ - @Override - public void mouseExited(MouseEvent e) { + + private int containsFolderNums() { + TemplateFileTree fileTree = TemplateTreePane.getInstance().getTemplateFileTree(); + if (fileTree.getSelectionPaths() == null) { + return 0; + } + + //选择的包含文件和文件夹的数目 + if (fileTree.getSelectionPaths().length == 0) { + return 0; + } + //所有的num减去模板的num,得到文件夹的num + return fileTree.getSelectionPaths().length - fileTree.getSelectedTemplatePaths().length; } /** - * 处理异常 + * 是否选择了多个模板 + * + * @return */ - public void dealEvnExceptionWhenStartDesigner() { - final EnvListPane envListPane = new EnvListPane(); - envListPane.populateEnvManager(envLabel.getText()); - BasicDialog envListDialog = envListPane.showWindow(SwingUtilities.getWindowAncestor(DesignerContext.getDesignerFrame())); - envListDialog.addDialogActionListener(new DialogActionAdapter() { - public void doOk() { - if (!envListOkAction(envListPane)) { - System.exit(0); + private int seletedTemplateNums() { + TemplateFileTree fileTree = TemplateTreePane.getInstance().getTemplateFileTree(); + if (fileTree.getSelectionPaths() == null) { + return 0; + } + + return fileTree.getSelectedTemplatePaths().length; + } + + + // js: 重命名对话框,模仿Eclipse的重命名,支持快捷键F2,Enter,ESC + private class RenameDialog { + + private UITextField jt; + private String userInput; + private String oldName; + private UILabel hintsLabel; + private UIButton confirmButton; + private JDialog jd; + private String suffix; + + public RenameDialog() { + final String reportPath = selectedOperation.getSelectedTemplatePath(); + if (reportPath == null) { + return; + } + + final FileNodeFILE nodeFile = new FileNodeFILE(new FileNode(StableUtils.pathJoin(new String[]{ProjectConstants.REPORTLETS_NAME, reportPath}), false)); + final String path = StableUtils.pathJoin(new String[]{nodeFile.getEnvPath(), nodeFile.getPath()}); + oldName = nodeFile.getName(); + suffix = oldName.substring(oldName.lastIndexOf(CoreConstants.DOT), oldName.length()); + oldName = oldName.replaceAll(suffix, ""); + + jd = new JDialog(); + jd.setLayout(new GridLayout(2, 2)); + jd.setModal(true); + UILabel newNameLabel = new UILabel(Inter.getLocText("FR-Designer_Enter-New-FileName")); + newNameLabel.setMinimumSize(new Dimension(150, 27)); + newNameLabel.setHorizontalAlignment(SwingConstants.RIGHT); + jt = new UITextField(oldName); + jt.getDocument().addDocumentListener(getdoDocumentListener()); + jt.selectAll(); + jt.setPreferredSize(new Dimension(150, 20)); + + JPanel newNamePanel = new JPanel(); + newNamePanel.setLayout(new BoxLayout(newNamePanel, BoxLayout.X_AXIS)); + newNamePanel.add(Box.createHorizontalGlue()); + newNamePanel.add(newNameLabel); + newNamePanel.add(Box.createHorizontalStrut(5)); + jd.add(newNamePanel); + + JPanel jtPanel = new JPanel(); + jtPanel.setLayout(new BoxLayout(jtPanel, BoxLayout.Y_AXIS)); + JPanel containJt = new JPanel(new BorderLayout()); + containJt.add(jt, BorderLayout.WEST); + containJt.setMaximumSize(new Dimension(200, 20)); + jtPanel.add(Box.createVerticalGlue()); + jtPanel.add(containJt); + jtPanel.add(Box.createVerticalGlue()); + jd.add(jtPanel); + + addUITextFieldListener(nodeFile, path); + + hintsLabel = new UILabel(); + hintsLabel.setBounds(20, 50, 250, 30); + hintsLabel.setMaximumSize(new Dimension(200, 30)); + hintsLabel.setHorizontalAlignment(SwingConstants.RIGHT); + hintsLabel.setForeground(Color.RED); + hintsLabel.setVisible(false); + + confirmButton = new UIButton(Inter.getLocText("FR-Designer_Confirm")); + confirmButton.setPreferredSize(new Dimension(80, 25)); + confirmButton.setMinimumSize(new Dimension(80, 25)); + confirmButton.setMaximumSize(new Dimension(80, 25)); + confirmButton.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + confirmClose(nodeFile, path); } + }); + UIButton cancelButton = new UIButton(Inter.getLocText("FR-Designer_Cancel")); + cancelButton.setPreferredSize(new Dimension(80, 25)); + cancelButton.setMinimumSize(new Dimension(80, 25)); + cancelButton.setMaximumSize(new Dimension(80, 25)); + + cancelButton.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + jd.dispose(); + } + }); + + JPanel hintsPanel = new JPanel(); + hintsPanel.setLayout(new BorderLayout()); + hintsPanel.add(hintsLabel, BorderLayout.EAST); + jd.add(hintsLabel); + + JPanel btPanel = new JPanel(new BorderLayout()); + btPanel.setLayout(new BoxLayout(btPanel, BoxLayout.X_AXIS)); + btPanel.add(Box.createHorizontalGlue()); + btPanel.add(confirmButton); + btPanel.add(Box.createHorizontalStrut(5)); + btPanel.add(cancelButton); + btPanel.add(Box.createHorizontalStrut(20)); + jd.add(btPanel); + + jd.setSize(380, 200); + jd.setTitle(Inter.getLocText("FR-Designer_Rename")); + jd.setResizable(false); + jd.setAlwaysOnTop(true); + jd.setIconImage(BaseUtils.readImage("/com/fr/base/images/oem/logo.png")); + jd.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); + GUICoreUtils.centerWindow(jd); + jd.setVisible(true); + } + + public void confirmClose(FileNodeFILE nodeFile, String path) { + userInput = userInput == null ? oldName : userInput; + String oldPath = path.replaceAll("/", "\\\\"); + String newPath = path.replace(nodeFile.getName(), userInput + suffix); + renameTemplateInMemory(nodeFile, userInput + suffix, oldName + suffix); + DesignerEnvManager.getEnvManager().replaceRecentOpenedFilePath(oldPath, newPath.replaceAll("/", "\\\\")); + File newFile = new File(newPath); + new File(path).renameTo(newFile); + selectedOperation.refresh(); + DesignerContext.getDesignerFrame().setTitle(); + jd.dispose(); + } + + private void renameTemplateInMemory(FILE tplFile, String newName, String oldName) { + JTemplate dPane = getSpecialTemplateByFILE(tplFile); + if (dPane == null) { + return; + } + FILE renameFile = dPane.getEditingFILE(); + renameFile.setPath(renameFile.getPath().replace(oldName, newName)); + } + + // 增加enter以及esc快捷键的支持 + public void addUITextFieldListener(final FileNodeFILE nodeFile, final String path) { + + jt.addKeyListener(new KeyAdapter() { + public void keyPressed(KeyEvent e) { + if (e.getKeyCode() == KeyEvent.VK_ESCAPE) { + jd.dispose(); + } + } + }); + + jt.addKeyListener(new KeyAdapter() { + public void keyPressed(KeyEvent e) { + if (e.getKeyCode() == KeyEvent.VK_ENTER) { + if (confirmButton.isEnabled()) { + confirmClose(nodeFile, path); + } + } + } + }); + + } + + // UITextField的输入监听 + public DocumentListener getdoDocumentListener() { + DocumentListener dl = new DocumentListener() { + + public void changedUpdate(DocumentEvent e) { + isNameAlreadyExist(); + } + + public void insertUpdate(DocumentEvent e) { + isNameAlreadyExist(); + } + + public void removeUpdate(DocumentEvent e) { + isNameAlreadyExist(); + } + }; + + return dl; + } + + private void isNameAlreadyExist() { + userInput = jt.getText().trim(); + if (selectedOperation.isNameAlreadyExist(userInput, oldName, suffix)) { + jt.selectAll(); + // 如果文件名已存在,则灰掉确认按钮 + hintsLabel.setText(Inter.getLocText(new String[]{"Utils-File_name", "Already_exists"}, new String[]{userInput})); + hintsLabel.setVisible(true); + confirmButton.setEnabled(false); + } else { + hintsLabel.setVisible(false); + confirmButton.setEnabled(true); } + } + } - public void doCancel() { - System.exit(0); + /** + * @param tplFile + * @return 内存中的template重命名一下 + */ + private JTemplate getSpecialTemplateByFILE(FILE tplFile) { + HistoryTemplateListPane historyHandle = HistoryTemplateListPane.getInstance(); + if (ComparatorUtils.equals(historyHandle.getCurrentEditingTemplate().getEditingFILE(), tplFile)) { + return historyHandle.getCurrentEditingTemplate(); + } + for (int i = 0; i < historyHandle.getHistoryCount(); i++) { + if (ComparatorUtils.equals(historyHandle.get(i).getEditingFILE(), tplFile)) { + return historyHandle.get(i); } - }); - envListDialog.setVisible(true); + } + return null; } -} \ No newline at end of file +} diff --git a/designer-base/src/com/fr/design/mainframe/loghandler/DesignerLogHandler.java b/designer-base/src/com/fr/design/mainframe/loghandler/DesignerLogHandler.java index 7be558aca..b718760ed 100644 --- a/designer-base/src/com/fr/design/mainframe/loghandler/DesignerLogHandler.java +++ b/designer-base/src/com/fr/design/mainframe/loghandler/DesignerLogHandler.java @@ -1,7 +1,7 @@ package com.fr.design.mainframe.loghandler; import com.fr.base.BaseUtils; -import com.fr.base.ServerConfig; +import com.fr.base.ConfigManager; import com.fr.base.FRContext; import com.fr.design.gui.icontainer.UIScrollPane; import com.fr.design.gui.imenu.UIMenuItem; @@ -11,17 +11,28 @@ import com.fr.general.FRLogLevel; import com.fr.general.FRLogger; import com.fr.general.GeneralContext; import com.fr.general.Inter; +import com.fr.general.LogRecordTime; import com.fr.log.LogHandler; import com.fr.stable.EnvChangedListener; import com.fr.stable.xml.LogRecordTimeProvider; -import javax.swing.*; +import javax.swing.AbstractAction; +import javax.swing.ActionMap; +import javax.swing.InputMap; +import javax.swing.JCheckBoxMenuItem; +import javax.swing.JComponent; +import javax.swing.JPanel; +import javax.swing.JPopupMenu; +import javax.swing.JTextPane; +import javax.swing.KeyStroke; import javax.swing.text.BadLocationException; import javax.swing.text.DefaultEditorKit; import javax.swing.text.Document; import javax.swing.text.SimpleAttributeSet; import javax.swing.text.StyleConstants; -import java.awt.*; +import java.awt.BorderLayout; +import java.awt.Color; +import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ItemEvent; @@ -119,7 +130,7 @@ public class DesignerLogHandler { @Override public void actionPerformed(ActionEvent e) { JPopupMenu showsetPopup = new JPopupMenu(); - int logLevelvalue = ServerConfig.getInstance().getServerLogLevel().intValue(); + int logLevelvalue = ConfigManager.getProviderInstance().getServerLogLevel().intValue(); if (logLevelvalue <= INFO_INT) { showsetPopup.add(showInfo); showsetPopup.add(showError); @@ -149,6 +160,10 @@ public class DesignerLogHandler { logHandlerArea.printStackTrace(message, level, date); } + public void printRemoteLog(LogRecordTime logRecordTime) { + logHandlerArea.printStackTrace(logRecordTime); + } + private class LogHandlerArea extends JPanel { private static final long serialVersionUID = 8215630927304621660L; @@ -341,4 +356,4 @@ public class DesignerLogHandler { }; } -} \ No newline at end of file +} diff --git a/designer-base/src/com/fr/design/utils/DesignUtils.java b/designer-base/src/com/fr/design/utils/DesignUtils.java index 469e7fd1a..4ee3ff9c0 100644 --- a/designer-base/src/com/fr/design/utils/DesignUtils.java +++ b/designer-base/src/com/fr/design/utils/DesignUtils.java @@ -1,12 +1,6 @@ package com.fr.design.utils; -import com.fr.base.BaseUtils; -import com.fr.base.ServerConfig; -import com.fr.base.Env; -import com.fr.base.EnvException; -import com.fr.base.FRContext; -import com.fr.base.FeedBackInfo; -import com.fr.base.Utils; +import com.fr.base.*; import com.fr.base.remote.RemoteDeziConstants; import com.fr.dav.DavXMLUtils; import com.fr.dav.LocalEnv; @@ -15,39 +9,18 @@ import com.fr.design.ExtraDesignClassManager; import com.fr.design.fun.DesignerEnvProcessor; import com.fr.design.gui.UILookAndFeel; import com.fr.design.mainframe.DesignerContext; +import com.fr.design.mainframe.DesignerFrame; import com.fr.env.RemoteEnv; import com.fr.file.FileFILE; -import com.fr.general.ComparatorUtils; -import com.fr.general.FRFont; -import com.fr.general.FRLogger; -import com.fr.general.GeneralContext; -import com.fr.general.Inter; +import com.fr.general.*; import com.fr.general.http.HttpClient; -import com.fr.stable.ArrayUtils; -import com.fr.stable.CodeUtils; -import com.fr.stable.EncodeConstants; -import com.fr.stable.StableUtils; -import com.fr.stable.StringUtils; +import com.fr.stable.*; import com.fr.start.StartServer; import javax.swing.*; import java.awt.*; -import java.io.BufferedReader; -import java.io.BufferedWriter; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.OutputStreamWriter; -import java.io.PrintWriter; -import java.io.UnsupportedEncodingException; -import java.net.HttpURLConnection; -import java.net.ServerSocket; -import java.net.Socket; -import java.net.URI; -import java.net.URLEncoder; +import java.io.*; +import java.net.*; import java.util.Calendar; import java.util.Enumeration; import java.util.Locale; @@ -209,18 +182,18 @@ public class DesignUtils { // 更新CurrentEnv于FRContext & DesignerEnvManager FRContext.setCurrentEnv(env); - + DesignerFrame.refreshNorthEastPane(); refreshDesignerFrame(env); // 当换了运行环境,重置服务器,让它下次预览时重启 if (env instanceof LocalEnv && !ComparatorUtils.equals(env.getPath(), oldEnvPath)) { StartServer.currentEnvChanged(); } } - + public static void refreshDesignerFrame(Env env) { - + final Env run_env = env; - + // 刷新DesignerFrame里面的面板 SwingUtilities.invokeLater(new Runnable() { @@ -233,7 +206,7 @@ public class DesignUtils { } }); } - + /** * p:初始化look and feel, 把一切放到这个里面.可以让多个地方调用. */ @@ -256,15 +229,15 @@ public class DesignUtils { } } } - + private static boolean isTextField(String key){ - return key.startsWith("TextField.") || key.startsWith("PasswordField."); + return key.startsWith("TextField.") || key.startsWith("PasswordField."); } - + private static FRFont getCurrentLocaleFont(){ FRFont guiFRFont; Locale defaultLocale = Locale.getDefault(); - + if (isDisplaySimSun(defaultLocale)) { guiFRFont = getNamedFont("SimSun"); } else if(isDisplayDialog(defaultLocale)) { @@ -272,57 +245,50 @@ public class DesignUtils { } else { guiFRFont = getNamedFont("Tahoma"); } - + //先初始化的设计器locale, 后初始化lookandfeel.如果顺序改了, 这边也要调整. Locale designerLocale = FRContext.getLocale(); String file = Inter.getLocText("FR-Designer_File"); char displayChar = file.charAt(0); if (!guiFRFont.canDisplay(displayChar)) { - //如果不能用默认的语言显示字体, 比如想在英文系统里用中文设计器 - //默认语言(中文:宋体, 英文:Tahoma, 其他:Dialog) - guiFRFont = getNamedFont("SimSun"); - if (!guiFRFont.canDisplay(displayChar)) { + //如果不能用默认的语言显示字体, 比如想在英文系统里用中文设计器 + //默认语言(中文:宋体, 英文:Tahoma, 其他:Dialog) + guiFRFont = getNamedFont("SimSun"); + if (!guiFRFont.canDisplay(displayChar)) { //比如想在中文或英文系统里用韩文设计器 guiFRFont = getNamedFont("Dialog"); if(!guiFRFont.canDisplay(displayChar)) { FRContext.getLogger().error(Inter.getLocText("FR-Base_SimSun_Not_Found")); } - } - } - + } + } + return guiFRFont; } - + private static FRFont getNamedFont(String name){ - return FRFont.getInstance(name, Font.PLAIN, 12); + return FRFont.getInstance(name, Font.PLAIN, 12); } - + private static boolean isDisplaySimSun(Locale defaultLocale){ - return ComparatorUtils.equals(defaultLocale, Locale.SIMPLIFIED_CHINESE); + return ComparatorUtils.equals(defaultLocale, Locale.SIMPLIFIED_CHINESE); } - + private static boolean isDisplayDialog(Locale defaultLocale){ - return ComparatorUtils.equals(defaultLocale, Locale.TRADITIONAL_CHINESE) - || ComparatorUtils.equals(defaultLocale, Locale.JAPANESE) - || ComparatorUtils.equals(defaultLocale, Locale.JAPAN) + return ComparatorUtils.equals(defaultLocale, Locale.TRADITIONAL_CHINESE) + || ComparatorUtils.equals(defaultLocale, Locale.JAPANESE) + || ComparatorUtils.equals(defaultLocale, Locale.JAPAN) || ComparatorUtils.equals(defaultLocale, Locale.KOREAN) || ComparatorUtils.equals(defaultLocale, Locale.KOREA); } - /** - * 访问服务器环境-空参数 - */ - public static void visitEnvServer() { - visitEnvServerByParameters(StringUtils.EMPTY, new String[] {}, new String[] {}); - } - /** * 访问服务器环境 * * @param names 参数名字 * @param values 参数值 */ - public static void visitEnvServerByParameters(String baseRoute, String[] names, String[] values) { + public static void visitEnvServerByParameters(String[] names, String[] values) { int len = Math.min(ArrayUtils.getLength(names), ArrayUtils.getLength(values)); String[] segs = new String[len]; for (int i = 0; i < len; i++) { @@ -353,8 +319,7 @@ public class DesignUtils { } else { try { String web = GeneralContext.getCurrentAppNameOfEnv(); - String url = "http://localhost:" + DesignerEnvManager.getEnvManager().getJettyServerPort() - + "/" + web + "/" + ServerConfig.getInstance().getServletName() + baseRoute + String url = "http://localhost:" + DesignerEnvManager.getEnvManager().getJettyServerPort() + "/" + web + "/" + ConfigManager.getProviderInstance().getServletMapping() + postfixOfUri; StartServer.browserURLWithLocalEnv(url); } catch (Throwable e) { @@ -474,10 +439,10 @@ public class DesignUtils { private static InputStream postBytes2ServerB(byte[] bytes) throws Exception { - HttpClient client = new HttpClient("http://114.215.175.35:8080/WebReport/product_advice.jsp"); + HttpClient client = new HttpClient("http://114.215.175.35:8080/WebReport/product_advice.jsp"); client.asGet(); - client.setContent(bytes); - return execute4InputStream(client); + client.setContent(bytes); + return execute4InputStream(client); } @@ -487,7 +452,7 @@ public class DesignUtils { private static ByteArrayInputStream execute4InputStream(HttpClient client) throws Exception { int statusCode = client.getResponseCode(); if(statusCode != HttpURLConnection.HTTP_OK){ - throw new EnvException("Method failed: " + statusCode); + throw new EnvException("Method failed: " + statusCode); } InputStream in = client.getResponseStream(); if (in == null) { @@ -519,4 +484,4 @@ public class DesignUtils { } -} \ No newline at end of file +} diff --git a/designer-base/src/com/fr/env/EnvListPane.java b/designer-base/src/com/fr/env/EnvListPane.java index 4165bf9bc..d1d794f8d 100644 --- a/designer-base/src/com/fr/env/EnvListPane.java +++ b/designer-base/src/com/fr/env/EnvListPane.java @@ -1,33 +1,73 @@ package com.fr.env; +import java.awt.BorderLayout; +import java.awt.Color; +import java.awt.Component; +import java.awt.Dimension; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.KeyEvent; +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; +import java.io.File; +import java.util.*; + +import javax.swing.BorderFactory; + +import com.fr.design.gui.ilable.UILabel; + +import javax.swing.JFileChooser; +import javax.swing.JOptionPane; +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import javax.swing.JTextPane; +import javax.swing.JToolBar; +import javax.swing.SwingUtilities; +import javax.swing.ToolTipManager; +import javax.swing.event.DocumentEvent; +import javax.swing.event.DocumentListener; +import javax.swing.event.TreeSelectionEvent; +import javax.swing.event.TreeSelectionListener; +import javax.swing.text.AttributeSet; +import javax.swing.text.BadLocationException; +import javax.swing.text.SimpleAttributeSet; +import javax.swing.text.StyleConstants; + +import com.fr.base.BaseUtils; import com.fr.base.Env; +import com.fr.base.FRContext; +import com.fr.general.NameObject; import com.fr.dav.LocalEnv; import com.fr.design.DesignerEnvManager; +import com.fr.design.beans.BasicBeanPane; +import com.fr.design.dialog.InformationWarnPane; import com.fr.design.gui.controlpane.JListControlPane; import com.fr.design.gui.controlpane.NameObjectCreator; import com.fr.design.gui.controlpane.NameableCreator; +import com.fr.design.gui.ipasswordfield.UIPassWordField; +import com.fr.design.gui.itree.filetree.JFileTree; +import com.fr.design.gui.ibutton.UIButton; +import com.fr.design.gui.icheckbox.UICheckBox; +import com.fr.design.gui.itextarea.UITextArea; +import com.fr.design.gui.itextfield.UITextField; +import com.fr.design.layout.FRGUIPaneFactory; +import com.fr.design.layout.TableLayout; +import com.fr.design.layout.TableLayoutHelper; +import com.fr.design.mainframe.DesignerContext; +import com.fr.design.scrollruler.ModLineBorder; +import com.fr.file.filter.OnlyShowDirectoryFileFilter; import com.fr.general.ComparatorUtils; import com.fr.general.Inter; -import com.fr.general.NameObject; import com.fr.stable.Nameable; +import com.fr.stable.ProductConstants; import com.fr.stable.StringUtils; import com.fr.stable.core.PropertyChangeAdapter; +import com.fr.third.org.hibernate.boot.jaxb.SourceType; -import javax.swing.JOptionPane; -import javax.swing.SwingUtilities; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Iterator; -import java.util.List; - -/** - * @author yaohwu - */ public class EnvListPane extends JListControlPane { public EnvListPane() { super(); addEditingListner(new PropertyChangeAdapter() { - @Override public void propertyChange() { String tempName = getEditingName(); String[] allListNames = nameableList.getAllNames(); @@ -46,6 +86,7 @@ public class EnvListPane extends JListControlPane { nameableList.stopEditing(); JOptionPane.showMessageDialog(SwingUtilities.getWindowAncestor(EnvListPane.this), Inter.getLocText(waning, sign)); setWarnigText(editingIndex); + return; } } }); @@ -56,7 +97,6 @@ public class EnvListPane extends JListControlPane { * * @return 返回添加按钮的NameableCreator */ - @Override public NameableCreator[] createNameableCreators() { NameableCreator local = new NameObjectCreator(Inter.getLocText("Env-Local_Directory"), "com/fr/design/images/data/bind/localconnect.png", LocalEnv.class, LocalEnvPane.class); @@ -78,13 +118,14 @@ public class EnvListPane extends JListControlPane { public void populateEnvManager(String selectedEnv) { DesignerEnvManager mgr = DesignerEnvManager.getEnvManager(); Iterator nameIt = mgr.getEnvNameIterator(); - List nameObjectList = new ArrayList<>(); + List nameObjectList = new ArrayList(); + nameIt.hasNext(); while (nameIt.hasNext()) { String name = nameIt.next(); nameObjectList.add(new NameObject(name, mgr.getEnv(name))); } - this.populate(nameObjectList.toArray(new NameObject[0])); + this.populate(nameObjectList.toArray(new NameObject[nameObjectList.size()])); if (StringUtils.isBlank(selectedEnv)) { selectedEnv = mgr.getCurEnvName(); @@ -102,10 +143,457 @@ public class EnvListPane extends JListControlPane { DesignerEnvManager mgr = DesignerEnvManager.getEnvManager(); mgr.clearAllEnv(); Nameable[] res = this.update(); - for (Nameable re : res) { - NameObject nameObject = (NameObject) re; + NameObject[] envNameObjectArray = new NameObject[res.length]; + java.util.Arrays.asList(res).toArray(envNameObjectArray); + for (int i = 0; i < envNameObjectArray.length; i++) { + NameObject nameObject = envNameObjectArray[i]; mgr.putEnv(nameObject.getName(), (Env) nameObject.getObject()); } + return this.getSelectedName(); } -} \ No newline at end of file + + public static class LocalEnvPane extends BasicBeanPane { + + private UITextField pathTextField; + private JFileTree localEnvTree; + + public LocalEnvPane() { + this.setLayout(FRGUIPaneFactory.createM_BorderLayout()); + + // northPane + JPanel northPane = FRGUIPaneFactory.createBorderLayout_S_Pane(); + this.add(northPane, BorderLayout.NORTH); + + northPane.add(new UILabel(Inter.getLocText("Location") + ":"), BorderLayout.WEST); + northPane.add(pathTextField = new UITextField(), BorderLayout.CENTER); + + // 删除选择文件按钮 添加JFileTree + + // centerPane + JPanel centerPane = FRGUIPaneFactory.createBorderLayout_S_Pane(); + this.add(centerPane, BorderLayout.CENTER); + + // 添加JFileTree + localEnvTree = new JFileTree(); + JScrollPane localEnvPane = new JScrollPane(localEnvTree); + centerPane.add(localEnvPane, BorderLayout.CENTER); + + // 设置根路径File 和 文件过滤类型 + localEnvTree.setFileFilter(new OnlyShowDirectoryFileFilter()); + localEnvTree.setRootFiles(File.listRoots()); + localEnvTree.addTreeSelectionListener(new TreeSelectionListener() { + + @Override + public void valueChanged(TreeSelectionEvent e) { + pathTextField.setText(localEnvTree.getSelectedFile().getPath()); + } + }); + + UITextArea description = new UITextArea(); + centerPane.add(description, BorderLayout.SOUTH); + description.setText(Inter.getLocText("Env-Des1")); + description.setEditable(false); + } + + @Override + protected String title4PopupWindow() { + return Inter.getLocText("Location"); + } + + @Override + public LocalEnv updateBean() { + String path = pathTextField.getText(); + return LocalEnv.createEnv(path); + } + + public String getPath() { + return pathTextField.getText(); + } + + @Override + public void populateBean(LocalEnv ob) { + if (StringUtils.isBlank(ob.getPath())) { + return; + } + pathTextField.setText(ob.getPath()); + + final File tmpFile = new File(ob.getPath()); + localEnvTree.selectFile(tmpFile); + localEnvTree.setEnabled(true); + } + } + + public static class RemoteEnvPane extends BasicBeanPane { + public static final int HTTPS_HOST_INDEX = 8; + public static final int HTTP_HOST_INDEX = 7; + + private UICheckBox httpsCheckBox = new UICheckBox(Inter.getLocText("FR-Designer_Https_Enable")); + private UITextField servletPathField = new UITextField(); + private UITextField hostNameField = new UITextField(); + private UITextField portNameField = new UITextField(); + private UITextField webApplyField = new UITextField(); + private UITextField servletField = new UITextField(); + private UITextField userTextField = new UITextField(); + private UIPassWordField passwordTextField = new UIPassWordField(); + private UITextField certificatePath = new UITextField(); + private UIPassWordField certificatePass = new UIPassWordField(); + private UIButton chooseDirBtn = new UIButton("..."); + private String envPath; + private String hint; + + // 各种参数面板 + private JPanel northPane; + // 提示面板 + private JPanel previewPane; + // 面板的所有组件 + private Component[][] coms; + DocumentListener docListener = new DocumentListener() { + + @Override + public void changedUpdate(DocumentEvent e) { + showServletPathField(httpsCheckBox.isSelected()); + } + + @Override + public void insertUpdate(DocumentEvent e) { + showServletPathField(httpsCheckBox.isSelected()); + } + + @Override + public void removeUpdate(DocumentEvent e) { + showServletPathField(httpsCheckBox.isSelected()); + } + }; + + private void setHttpsState(boolean enable){ + chooseDirBtn.setEnabled(enable); + DesignerEnvManager.getEnvManager().setHttps(enable); + } + + public RemoteEnvPane() { + this.setBorder(BorderFactory.createTitledBorder(new ModLineBorder(ModLineBorder.TOP), Inter.getLocText("Config_Servlet"))); + this.setLayout(FRGUIPaneFactory.createM_BorderLayout()); + // 位置 + JPanel servletPathPane = FRGUIPaneFactory.createRightFlowInnerContainer_S_Pane(); + servletPathPane.add(new UILabel(Inter.getLocText("Server_Path") + ":")); + servletPathField.setEditable(false); + + hostNameField.getDocument().addDocumentListener(docListener); + portNameField.getDocument().addDocumentListener(docListener); + webApplyField.getDocument().addDocumentListener(docListener); + servletField.getDocument().addDocumentListener(docListener); + + // 主机名 + JPanel servletNamePane = FRGUIPaneFactory.createRightFlowInnerContainer_S_Pane(); + servletNamePane.add(new UILabel(Inter.getLocText("Host_Name") + "/IP" + ":")); + // 端口 + JPanel portNamePane = FRGUIPaneFactory.createRightFlowInnerContainer_S_Pane(); + portNamePane.add(new UILabel(Inter.getLocText("Port") + ":")); + // web应用 + JPanel webApplyPane = FRGUIPaneFactory.createRightFlowInnerContainer_S_Pane(); + webApplyPane.add(new UILabel(Inter.getLocText("Web_Apply") + ":")); + // servlet + JPanel servletPane = FRGUIPaneFactory.createRightFlowInnerContainer_S_Pane(); + servletPane.add(new UILabel("Servlet" + ":")); + // 用户名 + JPanel userNamePane = FRGUIPaneFactory.createRightFlowInnerContainer_S_Pane(); + userNamePane.add(new UILabel(Inter.getLocText("Username") + ":")); + // 密码 + JPanel passWordPane = FRGUIPaneFactory.createRightFlowInnerContainer_S_Pane(); + passWordPane.add(new UILabel(Inter.getLocText("Password") + ":")); + // https证书路径 + JPanel certificatePathPane = FRGUIPaneFactory.createRightFlowInnerContainer_S_Pane(); + certificatePathPane.add(new UILabel(Inter.getLocText("FR-Designer_Certificate_Path")+ ":")); + // https秘钥 + JPanel certificatePassPane = FRGUIPaneFactory.createRightFlowInnerContainer_S_Pane(); + certificatePassPane.add(new UILabel(Inter.getLocText("FR-Designer_Certificate_Pass") + ":")); + + //输入密码的时候检测下大写锁定 + passwordTextField.addMouseListener(new MouseAdapter() { + public void mouseEntered(MouseEvent e) { + if (java.awt.Toolkit.getDefaultToolkit().getLockingKeyState(KeyEvent.VK_CAPS_LOCK)) { + hint = Inter.getLocText("CapsLock"); + } else { + hint = null; + } + ToolTipManager.sharedInstance().setInitialDelay(100); + passwordTextField.setToolTipText(hint); + } + }); + + coms = new Component[][]{ + new Component[]{initHttpsCheckBoxPane(),new UILabel()}, + new Component[]{servletPathPane, initServletNameToolBar()}, + new Component[]{servletNamePane, hostNameField}, + new Component[]{portNamePane, portNameField}, + new Component[]{webApplyPane, webApplyField}, + new Component[]{servletPane, servletField}, + new Component[]{userNamePane, userTextField}, + new Component[]{passWordPane, passwordTextField}, + new Component[]{certificatePathPane,initHttpsPane()}, + new Component[]{certificatePassPane,certificatePass} + }; + + setHttpsState(httpsCheckBox.isSelected()); + initNorthPane(true); + initCenterPane(); + this.add(northPane, BorderLayout.NORTH); + this.add(previewPane, BorderLayout.CENTER); + } + + private JToolBar initServletNameToolBar(){ + JToolBar servletNameToolBar = new JToolBar(); + + servletNameToolBar.setFloatable(false); + servletNameToolBar.setLayout(FRGUIPaneFactory.createBorderLayout()); + + servletNameToolBar.add(this.servletPathField); + UIButton testConnctionButton = new UIButton(BaseUtils.readIcon("/com/fr/design/images/m_web/cache.png")); + testConnctionButton.setToolTipText(Inter.getLocText("Datasource-Test_Connection")); + servletNameToolBar.add(testConnctionButton, BorderLayout.EAST); + + testConnctionButton.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent ev) { + if (testConnection()) { + JOptionPane.showMessageDialog(SwingUtilities.getWindowAncestor(RemoteEnvPane.this), Inter.getLocText("Datasource-Connection_successfully")); + } + } + }); + + return servletNameToolBar; + } + + private void initCenterPane(){ + // centerPane + previewPane = FRGUIPaneFactory.createBorderLayout_S_Pane(); + previewPane.setBorder(BorderFactory.createTitledBorder(new ModLineBorder(ModLineBorder.TOP), Inter.getLocText("Note"))); + + JTextPane previewTextArea = new JTextPane(); + + // e:当行的长度大于所分配的宽度时,将换行. +// previewTextArea.setLineWrap(true); + previewTextArea.setEditable(false); + previewTextArea.setText(Inter.getLocText("Env-Des2")); + try { + previewTextArea.getDocument().insertString(previewTextArea.getText().length(), Inter.getLocText("Env_Des"), this.getRedSytleAttribute()); + previewTextArea.getDocument().insertString(previewTextArea.getText().length(), "\n" + Inter.getLocText("FR-Designer_Env_Des_Https"), this.getRedSytleAttribute()); + } catch (BadLocationException e) { + FRContext.getLogger().error(e.getMessage(), e); + } + previewPane.add(new JScrollPane(previewTextArea), BorderLayout.CENTER); + } + + @Override + protected String title4PopupWindow() { + return "Remote"; + } + + private JPanel initHttpsPane(){ + JPanel httpsPane = FRGUIPaneFactory.createRightFlowInnerContainer_S_Pane(); + httpsPane.setLayout(FRGUIPaneFactory.createBorderLayout()); + httpsPane.add(certificatePath,BorderLayout.CENTER); + httpsPane.add(chooseDirBtn, BorderLayout.EAST); + chooseDirBtn.setPreferredSize(new Dimension(25, 25)); + chooseDirBtn.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent evt) { + JFileChooser fileChooser = new JFileChooser(); + fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY); + int saveValue = fileChooser.showOpenDialog(DesignerContext.getDesignerFrame()); + if (saveValue == JFileChooser.APPROVE_OPTION) { + File selectedFile = fileChooser.getSelectedFile(); + certificatePath.setText(selectedFile.getAbsolutePath()); + } + } + }); + return httpsPane; + } + + private JPanel initHttpsCheckBoxPane(){ + JPanel checkBoxPane = FRGUIPaneFactory.createRightFlowInnerContainer_S_Pane(); + checkBoxPane.add(httpsCheckBox); + httpsCheckBox.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + boolean isHttps = httpsCheckBox.isSelected(); + DesignerEnvManager manager = DesignerEnvManager.getEnvManager(); + manager.setHttps(isHttps); + setHttpsState(isHttps); + updateNorthPane(isHttps); + } + }); + return checkBoxPane; + } + + private void setHttpsParas(){ + System.setProperty("javax.net.ssl.trustStore", this.certificatePath.getText()); + System.setProperty("javax.net.ssl.trustStorePassword", new String(this.certificatePass.getPassword())); + DesignerEnvManager manager = DesignerEnvManager.getEnvManager(); + manager.setCertificatePath(this.certificatePath.getText()); + manager.setCertificatePass(new String(this.certificatePass.getPassword())); + manager.setHttps(this.httpsCheckBox.isSelected()); + } + + private boolean testConnection() { + RemoteEnv env = new RemoteEnv(); + String url = servletPathField.getText(); + env.setPath(url); + env.setUser(userTextField.getText()); + env.setPassword(new String(passwordTextField.getPassword())); + boolean connect = false; + try { + if (!StringUtils.isBlank(servletPathField.getText().trim())) { + if(url.startsWith("https:") && !this.httpsCheckBox.isSelected()){ + JOptionPane.showMessageDialog(this, Inter.getLocText("Datasource-Connection_failed")); + return false; + } + if(url.startsWith("https:")){ + setHttpsParas(); + } + connect = env.testConnectionWithOutRegisteServer(this); + } + } catch (Exception e) { + JOptionPane.showMessageDialog(this, Inter.getLocText("Datasource-Connection_failed")); + FRContext.getLogger().error(e.getMessage(), e); + } + if (connect) { + try { + String remoteVersion = env.getDesignerVersion(); + if (StringUtils.isBlank(remoteVersion) || ComparatorUtils.compare(remoteVersion, ProductConstants.DESIGNER_VERSION) < 0) { + String infor = Inter.getLocText("Server-version-tip") + "。"; + String moreInfo = Inter.getLocText("Server-version-tip-moreInfo") + "。"; + new InformationWarnPane(infor, moreInfo, Inter.getLocText("Tooltips")).show(); + return false; + } + } catch (Exception e) { + FRContext.getLogger().error(e.getMessage(), e); + } + + } + + return connect; + } + + private AttributeSet getRedSytleAttribute() { + SimpleAttributeSet ds = new SimpleAttributeSet(); + StyleConstants.setForeground(ds, Color.red); + return ds; + } + + /** + * 显示show the content of serverPathFiled + * @param isHttps 是否启用https + */ + public void showServletPathField(boolean isHttps) { + String s = StringUtils.isBlank(webApplyField.getText()) ? "" : "/", t = StringUtils.isBlank(servletField.getText()) ? "" : "/", colon = StringUtils.isBlank(portNameField.getText()) ? "" + : ":"; + String prefix = isHttps ? "https://" : "http://"; + servletPathField.setText(prefix + hostNameField.getText() + colon + portNameField.getText() + s + webApplyField.getText() + t + servletField.getText()); + } + + @Override + public void populateBean(RemoteEnv ob) { + envPath = ob.getPath(); + boolean isHttps = false; + if(envPath != null){ + isHttps = envPath.startsWith("https"); + httpsCheckBox.setSelected(isHttps); + setHttpsState(isHttps); + } + updateNorthPane(isHttps); + if (envPath == null || ComparatorUtils.equals(envPath, StringUtils.EMPTY)) { + this.hostNameField.setText(StringUtils.EMPTY); + this.portNameField.setText(StringUtils.EMPTY); + this.webApplyField.setText(StringUtils.EMPTY); + this.servletField.setText(StringUtils.EMPTY); + this.servletPathField.setText(StringUtils.EMPTY); + this.httpsCheckBox.setSelected(false); + } else { + DesignerEnvManager manager = DesignerEnvManager.getEnvManager(); + this.certificatePath.setText(manager.getCertificatePath()); + this.certificatePass.setText(manager.getCertificatePass()); + // 第二次出现":"的地方,port位置起始点 + int secondTime = envPath.indexOf(":", envPath.indexOf(":") + 1); + // 第三次出现"/"的地方 + int thirdTime = envPath.indexOf("/", secondTime + 1); + // 最后出现"/"的地方 + int lastTime = envPath.lastIndexOf("/"); + String hostName = isHttps ? envPath.substring(HTTPS_HOST_INDEX, secondTime) : envPath.substring(HTTP_HOST_INDEX, secondTime); + this.hostNameField.setText(hostName); + if (thirdTime < 0) { + this.portNameField.setText(envPath.substring(secondTime + 1)); + this.webApplyField.setText(StringUtils.EMPTY); + } else { + this.portNameField.setText(envPath.substring(secondTime + 1, thirdTime)); + if (thirdTime == lastTime) { + this.webApplyField.setText(StringUtils.EMPTY); + } else { + this.webApplyField.setText(envPath.substring(thirdTime + 1, lastTime)); + } + this.servletField.setText(envPath.substring(lastTime + 1)); + } + this.servletPathField.setText(envPath); + } + + this.userTextField.setText(ob.getUser() == null ? StringUtils.EMPTY : ob.getUser()); + + this.passwordTextField.setText(ob.getPassword() == null ? StringUtils.EMPTY : ob.getPassword()); + } + + private void initNorthPane(boolean isHttps){ + double p = TableLayout.PREFERRED; + double f = TableLayout.FILL; + double[] rowSize; + double[] size = {p,p,p,p,p,p,p,p}; + double[] httpsSize = {p,p,p,p,p,p,p,p,p,p}; + if(isHttps){ + rowSize = httpsSize; + }else{ + rowSize = size; + } + double[] columnSize = {p, f}; + northPane = TableLayoutHelper.createTableLayoutPane(coms, rowSize, columnSize); + } + + private void updateNorthPane(boolean isHttps){ + this.removeAll(); + initNorthPane(isHttps); + this.add(northPane, BorderLayout.NORTH); + this.add(previewPane,BorderLayout.CENTER); + this.revalidate(); + this.doLayout(); + this.repaint(); + } + + @Override + public RemoteEnv updateBean() { + String hostName = this.hostNameField.getText(); +// String port = this.portNameField.getText(); + String webApply = this.webApplyField.getText(); + String servlet = this.servletField.getText(); + String path = this.servletPathField.getText(); + String user = this.userTextField.getText(); + String password = new String(this.passwordTextField.getPassword()); + if (isAllEmpty(new String[]{hostName, webApply, servlet})) { + path = StringUtils.EMPTY; + } + + return new RemoteEnv(path, user, password); + } + + private boolean isAllEmpty(String[] strs) { + for (int i = 0; i < strs.length; i++) { + if (StringUtils.isNotEmpty(strs[i])) { + return false; + } + } + return true; + } + } + + public static void main(String[] args) { + Byte[] a = new Byte[1]; + System.out.println(a.getClass()); + } +} diff --git a/designer-base/src/com/fr/env/RemoteEnv.java b/designer-base/src/com/fr/env/RemoteEnv.java index c1533aca5..ed43bc2da 100644 --- a/designer-base/src/com/fr/env/RemoteEnv.java +++ b/designer-base/src/com/fr/env/RemoteEnv.java @@ -1,6 +1,13 @@ package com.fr.env; -import com.fr.base.*; +import com.fr.base.AbstractEnv; +import com.fr.base.EnvException; +import com.fr.base.FRContext; +import com.fr.base.ModifiedTable; +import com.fr.base.Parameter; +import com.fr.base.StoreProcedureParameter; +import com.fr.base.TableData; +import com.fr.base.Utils; import com.fr.base.remote.RemoteDeziConstants; import com.fr.data.TableDataSource; import com.fr.data.core.DataCoreUtils; @@ -18,21 +25,31 @@ import com.fr.design.file.HistoryTemplateListPane; import com.fr.design.fun.DesignerEnvProcessor; import com.fr.design.mainframe.DesignerContext; import com.fr.design.mainframe.DesignerFrameFileDealerPane; +import com.fr.design.mainframe.loghandler.DesignerLogHandler; import com.fr.file.CacheManager; -import com.fr.file.ConnectionConfig; -import com.fr.file.TableDataConfig; +import com.fr.file.DatasourceManager; +import com.fr.file.DatasourceManagerProvider; import com.fr.file.filetree.FileNode; -import com.fr.general.*; +import com.fr.general.ComparatorUtils; +import com.fr.general.FRLogger; +import com.fr.general.IOUtils; +import com.fr.general.Inter; +import com.fr.general.LogRecordTime; +import com.fr.general.LogUtils; import com.fr.general.http.HttpClient; -import com.fr.io.utils.ResourceIOUtils; import com.fr.json.JSONArray; import com.fr.json.JSONException; import com.fr.json.JSONObject; import com.fr.license.function.VT4FR; import com.fr.regist.License; -import com.fr.report.DesignAuthority; import com.fr.share.ShareConstants; -import com.fr.stable.*; +import com.fr.stable.ArrayUtils; +import com.fr.stable.EncodeConstants; +import com.fr.stable.JavaCompileInfo; +import com.fr.stable.ProductConstants; +import com.fr.stable.StableUtils; +import com.fr.stable.StringUtils; +import com.fr.stable.SvgProvider; import com.fr.stable.file.XMLFileManagerProvider; import com.fr.stable.project.ProjectConstants; import com.fr.stable.xml.XMLPrintWriter; @@ -41,25 +58,42 @@ import com.fr.stable.xml.XMLableReader; import com.fr.web.ResourceConstants; import javax.swing.*; -import javax.xml.transform.*; +import javax.xml.transform.Source; +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerConfigurationException; +import javax.xml.transform.TransformerException; +import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import java.awt.*; -import java.io.*; +import java.io.BufferedReader; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.FilenameFilter; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.OutputStream; +import java.io.OutputStreamWriter; +import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.NoRouteToHostException; import java.net.Socket; import java.net.URLEncoder; -import java.util.*; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; import java.util.List; +import java.util.Map; import java.util.Timer; +import java.util.TimerTask; import java.util.logging.Level; import java.util.regex.Pattern; -/** - * @author null - */ -public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurable { +public class RemoteEnv extends AbstractEnv { private static final int TIME_OUT = 30 * 1000; private static final int PLAIN_SOCKET_PORT = 80; private static final int SSL_PORT = 443; @@ -69,7 +103,7 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl private static final String CERT_KEY = "javax.net.ssl.trustStore"; private static final String PWD_KEY = "javax.net.ssl.trustStorePassword"; private static final String HTTPS_PREFIX = "https:"; - private final static String[] FILE_TYPE = {"cptx", "cpt", "frm", "form", "cht", "chart"}; + private final static String[] FILE_TYPE = {"cpt", "frm", "form", "cht", "chart"}; private String path; private String user; private String password; @@ -79,7 +113,7 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl private int licNotSupport = 0; private boolean isRoot = false; private Timer logTimer = null; - private static ThreadLocal threadLocal = new ThreadLocal<>(); + private static ThreadLocal threadLocal = new ThreadLocal(); private boolean isReadTimeOut = false; private String buildFilePath; @@ -109,7 +143,6 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl /** * 当前设计环境的用户名,用于远程设计 */ - @Override public String getUser() { return user; } @@ -123,11 +156,7 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl return password; } - /** - * 修复密码中包含特殊字符,无法登录的问题 - * - * @return - */ + // 修复密码中包含特殊字符,无法登录的问题 private String getEncodedPassword() { try { return URLEncoder.encode(password, "UTF-8"); @@ -187,39 +216,31 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl /** * 根据nameValuePairs,也就是参数对,生成PostMethod */ - private HttpClient createHttpMethod(HashMap para, boolean isSignIn) throws EnvException { + private HttpClient createHttpMethod(HashMap para, boolean isSignIn) throws EnvException, UnsupportedEncodingException { String methodPath = this.path; if (!isSignIn) { methodPath = methodPath + "?id=" + createUserID(); } - HttpClient client = new HttpClient(methodPath, para); - /* - todo post 方法好象过去不了 - 但是get方法也会有一些url参数问题,尤其是图表部分 - 比如: - op=fr_remote_design&cmd=design_get_plugin_service_data&serviceID=plugin.phantomjs&req= - */ - client.asGet(); - return client; + return new HttpClient(methodPath, para); } /** * 根据nameValuePairs,也就是参数对,生成PostMethod,不同之处在于,参数拼在path后面,不是method.addParameters */ - private HttpClient createHttpMethod2(HashMap para) throws EnvException, UnsupportedEncodingException { + private HttpClient createHttpMethod2(HashMap para) throws EnvException { String methodPath = path + '?' + "id=" + createUserID(); - return new HttpClient(methodPath); + return new HttpClient(methodPath, para, true); } - /* - * Read the response body. - * 拿出InputStream中所有的Byte,转换成ByteArrayInputStream的形式返回 - * - * 这样做的目的是确保method.releaseConnection - * - * TODO 但如果不做method.releaseConnection,有多大危害呢?不确定... - */ + /* + * Read the response body. + * 拿出InputStream中所有的Byte,转换成ByteArrayInputStream的形式返回 + * + * 这样做的目的是确保method.releaseConnection + * + * TODO 但如果不做method.releaseConnection,有多大危害呢?不确定... + */ /** * execute method之后,取返回的inputstream @@ -255,6 +276,7 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl } else if (ComparatorUtils.equals(message, RemoteDeziConstants.FILE_LOCKED)) { JOptionPane.showMessageDialog(null, Inter.getLocText("FR-Remote_File_is_Locked")); return null; + } else if (message.startsWith(RemoteDeziConstants.RUNTIME_ERROR_PREFIX)) { } return new ByteArrayInputStream(bytes); } finally { @@ -341,7 +363,6 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl * @return 链接是否成功 * @throws Exception 异常 */ - @Override public boolean testServerConnectionWithOutShowMessagePane() throws Exception { return testConnection(false, true, DesignerContext.getDesignerFrame()); } @@ -361,7 +382,7 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl private boolean testConnection(boolean needMessage, boolean isRegisteServer, Component parentComponent) throws Exception { extraChangeEnvPara(); - HashMap para = new HashMap<>(); + HashMap para = new HashMap(); para.put("op", "fr_remote_design"); para.put("cmd", "test_server_connection"); para.put("user", user); @@ -376,11 +397,7 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl String res = stream2String(execute4InputStream(client)); if (res == null) { if (needMessage) { - JOptionPane.showMessageDialog( - parentComponent, - Inter.getLocText("Datasource-Connection_failed"), - UIManager.getString("OptionPane.messageDialogTitle", parentComponent.getLocale()), - JOptionPane.ERROR_MESSAGE); + JOptionPane.showMessageDialog(parentComponent, Inter.getLocText("Datasource-Connection_failed")); } return false; } else if (ComparatorUtils.equals(res, "true")) { @@ -390,33 +407,22 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl } return true; } else if (ComparatorUtils.equals(res, "invalid username or password.")) { - JOptionPane.showMessageDialog( - parentComponent, - Inter.getLocText(new String[]{"Datasource-Connection_failed", "Registration-User_Name", "Password", "Error"}, new String[]{",", "", "", "!"}), - Inter.getLocText("FR-Server-All_Error"), - JOptionPane.ERROR_MESSAGE); + JOptionPane.showMessageDialog(parentComponent, + Inter.getLocText(new String[]{"Datasource-Connection_failed", "Registration-User_Name", "Password", "Error"}, new String[]{",", "", "", "!"}) + , Inter.getLocText("FR-Server-All_Error"), JOptionPane.ERROR_MESSAGE); return false; } else if (res.contains("RegistEditionException")) { if (needMessage) { - JOptionPane.showMessageDialog( - parentComponent, - Inter.getLocText(new String[]{"Datasource-Connection_failed", "Version-does-not-support"}, new String[]{",", "!"}), - UIManager.getString("OptionPane.messageDialogTitle", parentComponent.getLocale()), - JOptionPane.ERROR_MESSAGE - ); + JOptionPane.showMessageDialog(parentComponent, Inter.getLocText(new String[]{"Datasource-Connection_failed", "Version-does-not-support"}, new String[]{",", "!"})); } else { - FRContext.getLogger().info(Inter.getLocText(new String[]{"Datasource-Connection_failed", "Version-does-not-support"}, new String[]{",", "!"})); + FRLogger.getLogger().info(Inter.getLocText(new String[]{"Datasource-Connection_failed", "Version-does-not-support"}, new String[]{",", "!"})); } return false; } else if (ComparatorUtils.equals(res, "war not support remote design.")) { if (needMessage) { - JOptionPane.showMessageDialog( - parentComponent, - Inter.getLocText(new String[]{"Datasource-Connection_failed", "NS-war-remote"}, new String[]{",", "!"}), - UIManager.getString("OptionPane.messageDialogTitle", parentComponent.getLocale()), - JOptionPane.ERROR_MESSAGE); + JOptionPane.showMessageDialog(parentComponent, Inter.getLocText(new String[]{"Datasource-Connection_failed", "NS-war-remote"}, new String[]{",", "!"})); } else { - FRContext.getLogger().info(Inter.getLocText(new String[]{"Datasource-Connection_failed", "NS-war-remote"}, new String[]{",", "!"})); + FRLogger.getLogger().info(Inter.getLocText(new String[]{"Datasource-Connection_failed", "NS-war-remote"}, new String[]{",", "!"})); } return false; } else { @@ -444,17 +450,17 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl try { SignIn.signIn(this); } catch (Exception e) { - FRContext.getLogger().error(e.getMessage()); + FRLogger.getLogger().error(e.getMessage()); } } /** * 心跳访问,用来更新当前用户的访问时间 * - * @throws Exception e + * @throws Exception */ public void heartBeatConnection() throws Exception { - HashMap para = new HashMap<>(); + HashMap para = new HashMap(); para.put("op", "fr_remote_design"); para.put("cmd", "heart_beat"); para.put("user", user); @@ -471,7 +477,7 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl // DesignerFrameFileDealerPane.getInstance().refresh(); // } // } catch (Exception e) { -// FRContext.getLogger().error(e.getMessage()); +// FRLogger.getLogger().error(e.getMessage()); // } } @@ -480,7 +486,6 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl * * @return 描述环境名字的字符串 */ - @Override public String getEnvDescription() { return Inter.getLocText("Env-Remote_Server"); } @@ -488,7 +493,6 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl /** * 登录,返回userID */ - @Override public void signIn() throws Exception { if (clock != null && clock.connected) { return; @@ -499,7 +503,7 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl } clearUserID(); startLogTimer(); - HashMap para = new HashMap<>(); + HashMap para = new HashMap(); para.put("op", "fr_remote_design"); para.put("cmd", "r_sign_in"); para.put("user", user); @@ -520,7 +524,6 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl } timer = new Timer(); timer.schedule(new TimerTask() { - @Override public void run() { try { RemoteEnv.this.setThreadLocal("HEART_BEAT"); @@ -540,13 +543,12 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl logTimer = new Timer(); logTimer.schedule(new TimerTask() { - @Override public void run() { try { RemoteEnv.this.setThreadLocal("LOG_MESSAGE"); FRContext.getCurrentEnv().printLogMessage(); } catch (Exception e) { - FRContext.getLogger().info(e.getMessage()); + FRLogger.getLogger().info(e.getMessage()); } } }, 10000, 10000); @@ -563,9 +565,8 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl * 根据userID sign out * * @return 成功签出返回true - * @throws Exception e + * @throws Exception */ - @Override public boolean signOut() throws Exception { if (userID == null) { return true; @@ -576,7 +577,7 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl // richer:把轮训使用的定时器也去掉 timer.cancel(); - HashMap para = new HashMap<>(); + HashMap para = new HashMap(); para.put("op", "fr_remote_design"); para.put("cmd", "r_sign_out"); para.put("id", userID); @@ -593,7 +594,7 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl try { resJSON = stream2String(execute4InputStream(client)); } catch (Exception e) { - FRContext.getLogger().error(e.getMessage()); + FRLogger.getLogger().error(e.getMessage()); } if (resJSON == null) { @@ -640,7 +641,7 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl } JSONArray ja = new JSONArray(filePathes); - HashMap para = new HashMap<>(); + HashMap para = new HashMap(); para.put("op", "fr_remote_design"); para.put("cmd", cmd); para.put("pathes", ja.toString()); @@ -662,7 +663,7 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl * * @param filePathes 文件路径 * @return 成功解锁返回true - * @throws Exception e + * @throws Exception */ public boolean releaseLock(String[] filePathes) throws Exception { return doLockOperation(filePathes, "design_release_lock"); @@ -680,7 +681,7 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl return false; } - HashMap para = new HashMap<>(); + HashMap para = new HashMap(); para.put("op", "fr_remote_design"); para.put("cmd", "design_report_exist"); para.put("report_path", reportPath); @@ -695,11 +696,11 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl * 解锁当前模板,用于远程设计。当远程设计某张模板 时,在解锁之前改模板处于锁定状态 * * @param tplPath 路径 - * @throws Exception e + * @throws Exception */ @Override public void unlockTemplate(String tplPath) throws Exception { - HashMap para = new HashMap<>(); + HashMap para = new HashMap(); para.put("op", "fr_remote_design"); para.put("cmd", "design_close_report"); para.put(RemoteDeziConstants.TEMPLATE_PATH, tplPath); @@ -748,9 +749,8 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl /** * 刷新数出流,并提交 * - * @throws IOException e + * @throws IOException */ - @Override public void flush() throws IOException { super.flush(); post2Server(); @@ -760,9 +760,10 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl * 将指定字节写入输入流数组 * * @param b 写入的字节 + * @throws IOException */ @Override - public void write(int b) { + public void write(int b) throws IOException { out.write(b); } @@ -783,7 +784,7 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl // 把database写成xml文件到out DavXMLUtils.writeXMLFileDatabaseConnection(database, out); - HashMap para = new HashMap<>(); + HashMap para = new HashMap(); para.put("op", "fr_remote_design"); para.put("cmd", "design_test_con"); @@ -796,18 +797,6 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl return Boolean.valueOf(IOUtils.inputStream2String(input, EncodeConstants.ENCODING_UTF_8)); } - @Override - public boolean updateAuthorities(DesignAuthority[] authorities) throws Exception { - return RemoteEnvUtils.updateAuthorities(authorities, this); - } - - @Override - public DesignAuthority[] getAuthorities() { - - return RemoteEnvUtils.getAuthorities(this); - - } - /** * ben:取schema */ @@ -816,7 +805,7 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl ByteArrayOutputStream out = new ByteArrayOutputStream(); DavXMLUtils.writeXMLFileDatabaseConnection(database, out); - HashMap para = new HashMap<>(); + HashMap para = new HashMap(); para.put("op", "fr_remote_design"); para.put("cmd", "design_get_schema"); InputStream input = postBytes2ServerB(out.toByteArray(), para); @@ -833,7 +822,7 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl public TableProcedure[] getTableProcedure(com.fr.data.impl.Connection database, String type, String schema) throws Exception { ByteArrayOutputStream out = new ByteArrayOutputStream(); DavXMLUtils.writeXMLFileDatabaseConnection(database, out); - HashMap para = new HashMap<>(); + HashMap para = new HashMap(); para.put("op", "fr_remote_design"); para.put("cmd", "design_get_tables"); para.put("__type__", type); @@ -845,7 +834,6 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl return DavXMLUtils.readXMLSQLTables(input); } - @Override public List getProcedures(com.fr.data.impl.Connection datasource, String[] schemas, boolean isOracle, boolean isOracleSysSpace) throws Exception { HashMap schemaTableProcedureMap = new HashMap(); List sqlTableObjs = new ArrayList(); @@ -878,11 +866,11 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl * * @param folderPath 文件名 * @return 成功创建返回true - * @throws Exception e + * @throws Exception */ @Override public boolean createFolder(String folderPath) throws Exception { - HashMap para = new HashMap<>(); + HashMap para = new HashMap(); para.put("op", "fr_remote_design"); para.put("cmd", "design_create_folder"); para.put("folder_path", folderPath); @@ -902,11 +890,10 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl * * @param filePath :目标文件相对路径 * @return 成功新建返回true - * @throws Exception e + * @throws Exception */ - @Override public boolean createFile(String filePath) throws Exception { - HashMap para = new HashMap<>(); + HashMap para = new HashMap(); para.put("op", "fr_remote_design"); para.put("cmd", "design_create_file"); para.put("file_path", filePath); @@ -921,9 +908,8 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl return Boolean.valueOf(IOUtils.inputStream2String(input, EncodeConstants.ENCODING_UTF_8)); } - @Override public boolean renameFile(String newPath, String oldPath) throws Exception { - HashMap para = new HashMap<>(); + HashMap para = new HashMap(); para.put("op", "fr_remote_design"); para.put("cmd", "design_rename_file"); para.put("newPath", newPath); @@ -944,7 +930,7 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl * * @param filePath :目标文件相对路径 * @return 文件是否存在 - * @throws Exception e + * @throws Exception */ @Override public boolean fileExists(String filePath) throws Exception { @@ -952,7 +938,7 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl return false; } - HashMap para = new HashMap<>(); + HashMap para = new HashMap(); para.put("op", "fr_remote_design"); para.put("cmd", "design_file_exists"); para.put("file_path", filePath); @@ -972,15 +958,14 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl * * @param filePath 文件路径 * @return 文件被锁住了,返回true - * @throws Exception e + * @throws Exception */ - @Override public boolean fileLocked(String filePath) throws Exception { if (filePath == null) { return false; } - HashMap para = new HashMap<>(); + HashMap para = new HashMap(); para.put("op", "fr_remote_design"); para.put("cmd", "design_file_locked"); para.put("file_path", filePath); @@ -1001,7 +986,6 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl * * @param env 用户环境 */ - @Override public void registerUserEnv(UserBaseEnv env) { } @@ -1009,7 +993,6 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl * 用于检测用户环境 * ,启动定时器 */ - @Override public void startUserCheckTimer() { } @@ -1026,13 +1009,12 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl * @param filePath 文件地址 * @return 删除成功返回true */ - @Override public boolean deleteFile(String filePath) { if (filePath == null) { return false; } try { - HashMap para = new HashMap<>(); + HashMap para = new HashMap(); para.put("op", "fr_remote_design"); para.put("cmd", "delete_file"); para.put("file_path", filePath); @@ -1046,7 +1028,7 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl return Boolean.valueOf(IOUtils.inputStream2String(input, EncodeConstants.ENCODING_UTF_8)); } catch (Exception e) { - FRContext.getLogger().error(e.getMessage()); + FRLogger.getLogger().error(e.getMessage()); } return false; } @@ -1057,10 +1039,10 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl * @param key 键值 * @param value 值 * @return 如果写入成功,返回true - * @throws Exception e + * @throws Exception */ public boolean writePrivilegeMap(String key, String value) throws Exception { - HashMap para = new HashMap<>(); + HashMap para = new HashMap(); para.put("op", "fr_remote_design"); para.put("cmd", "write_privilege_map"); para.put("current_user", this.user); @@ -1068,8 +1050,7 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl para.put("key", key); para.put("value", value); - //jim :加上user,远程设计点击预览时传递用户角色信息 - HttpClient client = createHttpMethod(para); + HttpClient client = createHttpMethod(para); //jim :加上user,远程设计点击预览时传递用户角色信息 InputStream input = execute4InputStream(client); if (input == null) { @@ -1082,12 +1063,11 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl /** * DataSource中去除当前角色没有权限访问的数据源 */ - @Override public void removeNoPrivilegeConnection() { - TableDataConfig dm = TableDataConfig.getInstance(); + DatasourceManagerProvider dm = DatasourceManager.getProviderInstance(); try { - HashMap para = new HashMap<>(); + HashMap para = new HashMap(); para.put("op", "fs_remote_design"); para.put("cmd", "env_get_role"); para.put("currentUsername", this.getUser()); @@ -1096,11 +1076,11 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl HttpClient client = createHttpMethod(para); InputStream input = execute4InputStream(client); JSONArray ja = new JSONArray(stream2String(input)); - ArrayList toBeRemoveTDName = new ArrayList<>(); + ArrayList toBeRemoveTDName = new ArrayList(); for (int i = 0; i < ja.length(); i++) { String toBeRemoveConnName = (String) ((JSONObject) ja.get(i)).get("name"); - ConnectionConfig.getInstance().removeConnection(toBeRemoveConnName); - Iterator it = dm.getTableDatas().keySet().iterator(); + dm.removeConnection(toBeRemoveConnName); + Iterator it = dm.getTableDataNameIterator(); while (it.hasNext()) { String tdName = (String) it.next(); TableData td = dm.getTableData(tdName); @@ -1121,7 +1101,7 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl * * @param rootFilePath 指定目录 * @return WEB-INF目录下指定路径的文件夹与文件 - * @throws Exception e + * @throws Exception */ @Override public FileNode[] listFile(String rootFilePath) throws Exception { @@ -1133,7 +1113,7 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl * * @param rootFilePath 指定目录 * @return WEB-INF上层目录下指定路径的文件夹与文件 - * @throws Exception e + * @throws Exception */ @Override public FileNode[] listReportPathFile(String rootFilePath) throws Exception { @@ -1143,7 +1123,7 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl private FileNode[] listFile(String rootFilePath, boolean isWebReport) throws Exception { FileNode[] fileNodes; - HashMap para = new HashMap<>(); + HashMap para = new HashMap(); para.put("op", "fs_remote_design"); para.put("cmd", "design_list_file"); para.put("file_path", rootFilePath); @@ -1160,7 +1140,7 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl // 远程环境下左侧目录树暂不需要打开xlsx,xls文件 fileNodes = DavXMLUtils.readXMLFileNodes(input); - ArrayList al = new ArrayList<>(); + ArrayList al = new ArrayList(); for (int i = 0; i < fileNodes.length; i++) { al.add(fileNodes[i]); } @@ -1179,9 +1159,9 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl * * @param rootFilePath 指定目录 * @return 列出目标目录下所有cpt文件或文件夹 + * @throws Exception */ - @Override - public FileNode[] listCpt(String rootFilePath) { + public FileNode[] listCpt(String rootFilePath) throws Exception { return listCpt(rootFilePath, false); } @@ -1191,11 +1171,10 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl * @param rootFilePath 指定目录 * @param recurse 是否递归查找其子目录 * @return 列出目标目录下所有cpt文件或文件夹 - * @throws Exception e + * @throws Exception */ - @Override public FileNode[] listCpt(String rootFilePath, boolean recurse) { - List fileNodeList = new ArrayList<>(); + List fileNodeList = new ArrayList(); try { listAll(rootFilePath, fileNodeList, new String[]{"cpt"}, recurse); } catch (Exception e) { @@ -1235,14 +1214,13 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl * @return 数据集的参数 * @throws Exception 获取参数失败则抛出此异常 */ - @Override public Parameter[] getTableDataParameters(TableData tableData) throws Exception { ByteArrayOutputStream out = new ByteArrayOutputStream(); - //把tableData写成xml文件到out +// 把tableData写成xml文件到out DavXMLUtils.writeXMLFileTableData(tableData, out); - HashMap para = new HashMap<>(); + HashMap para = new HashMap(); para.put("op", "fr_remote_design"); para.put("cmd", "design_td_pars"); InputStream input = postBytes2ServerB(out.toByteArray(), para); @@ -1261,13 +1239,12 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl * @return 返回存储过程中的所有参数组成的数组 * @throws Exception 如果获取参数失败则抛出此异常 */ - @Override public Parameter[] getStoreProcedureParameters(StoreProcedure storeProcedure) throws Exception { ByteArrayOutputStream out = new ByteArrayOutputStream(); // 把tableData写成xml文件到out DavXMLUtils.writeXMLFileStoreProcedureAndSource(storeProcedure, out); - HashMap para = new HashMap<>(); + HashMap para = new HashMap(); para.put("op", "fr_remote_design"); para.put("cmd", "design_sp_pars"); InputStream input = postBytes2ServerB(out.toByteArray(), para); @@ -1292,7 +1269,6 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl * @return 实际的二维数据集 * @throws Exception 如果生成数据失败则抛出此异常 */ - @Override public EmbeddedTableData previewTableData(TableDataSource dataSource, Object tableData, java.util.Map parameterMap, int rowCount) throws Exception { ByteArrayOutputStream out = new ByteArrayOutputStream(); @@ -1302,7 +1278,7 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl // 把parameterMap转成JSON格式的字符串 JSONObject jo = new JSONObject(parameterMap); String jsonParameter = jo.toString(); - HashMap para = new HashMap<>(); + HashMap para = new HashMap(); para.put("op", "fr_remote_design"); para.put("cmd", "design_preview_td"); para.put("pars", jsonParameter); @@ -1328,7 +1304,6 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl * @return 实际的二位数据条 * @throws Exception 异常 */ - @Override public Object previewTableData(Object tableData, java.util.Map parameterMap, int start, int end, String[] cols, int[] colIdx) throws Exception { return previewTableData(tableData, parameterMap, -1); } @@ -1348,13 +1323,6 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl */ public InputStream postBytes2ServerB(byte[] bytes, HashMap para) throws Exception { HttpClient client = createHttpMethod2(para); - /* - todo post 方法好象过去不了 - 但是get方法也会有一些url参数问题,尤其是图表部分 - 比如: - op=fr_remote_design&cmd=design_get_plugin_service_data&serviceID=plugin.phantomjs&req= - */ -// client.asGet(); client.setContent(bytes); return execute4InputStream(client); } @@ -1364,7 +1332,6 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl * The method will be invoked when read data from XML file.
* May override the method to read the data that you saved. */ - @Override public void readXML(XMLableReader reader) { if (reader.isChildNode()) { String tmpVal; @@ -1389,7 +1356,6 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl * * @param writer the PrintWriter. */ - @Override public void writeXML(XMLPrintWriter writer) { writer.startTAG("DIR").attr("path", this.path).attr("user", this.user).attr("password", this.password).end(); } @@ -1468,7 +1434,7 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl if (StringUtils.isBlank(remoteVersion) || ComparatorUtils.compare(remoteVersion, ProductConstants.DESIGNER_VERSION) < 0) { String infor = Inter.getLocText("FR-Server_Version_Tip"); String moreInfo = Inter.getLocText("FR-Server_Version_Tip_MoreInfo"); - FRContext.getLogger().log(Level.WARNING, infor); + FRLogger.getLogger().log(Level.WARNING, infor); new InformationWarnPane(infor, moreInfo, Inter.getLocText("FR-Designer_Tooltips")).show(); return; } @@ -1491,10 +1457,8 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl Pattern pattern = Pattern.compile("[/:]+"); String[] strs = pattern.split(remoteEnv.path); - //host,如:192.168.100.195 - String shost = strs[1]; - //端口,如:8080 - int sport = Integer.parseInt(strs[2]); + String shost = strs[1];//host,如:192.168.100.195 + int sport = Integer.parseInt(strs[2]);//端口,如:8080 Socket socket = new Socket(shost, sport); //OOBBINLINE:是否支持发送一个字节的TCP紧急数据,false表示服务器不用处理这个数据 @@ -1509,7 +1473,7 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl * * @param resourceName 配置文件的名字,如datasource.xml * @return 输入流 - * @throws Exception e + * @throws Exception */ @Override public InputStream readResource(String resourceName) throws Exception { @@ -1523,14 +1487,18 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl * @param path 制定路径,是基于报表目录下resource文件夹路径 * @return 读到的文件 */ - @Override - public String[] readPathSvgFiles(String path) { - String cataloguePath = StableUtils.pathJoin(CacheManager.getProviderInstance().getCacheDirectory().getPath(), SvgProvider.SERVER, path); + public File[] readPathSvgFiles(String path) { + String cataloguePath = StableUtils.pathJoin(new String[]{CacheManager.getProviderInstance().getCacheDirectory().getPath(), SvgProvider.SERVER, path}); + //检查缓存文件保存的目录下serversvgs文件夹是否存在 ,先用来暂存服务器读过来的svg文件 + File catalogue = new File(cataloguePath); + if (!catalogue.exists()) { + catalogue.mkdirs(); + } - ArrayList fileArray = new ArrayList<>(); + ArrayList fileArray = new ArrayList<>(); try { - HashMap para = new HashMap<>(); + HashMap para = new HashMap(); para.put("op", "fr_remote_design"); para.put("cmd", "design_read_svgfile"); para.put("resourcePath", path); @@ -1544,17 +1512,17 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl JSONObject jsonObject = (JSONObject) ja.get(i); String svgFileName = (String) jsonObject.get("svgfileName"); String svgfileContent = (String) jsonObject.get("svgfileContent"); - - String file = StableUtils.pathJoin(cataloguePath, svgFileName); + File file = new File(StableUtils.pathJoin(new String[]{cataloguePath, svgFileName})); InputStream in = new ByteArrayInputStream(svgfileContent.getBytes(EncodeConstants.ENCODING_UTF_8)); - ResourceIOUtils.write(file, in); + FileOutputStream out = new FileOutputStream(file); + IOUtils.copyBinaryTo(in, out); fileArray.add(file); } } catch (Exception e) { FRContext.getLogger().error(e.getMessage()); } - return fileArray.toArray(new String[fileArray.size()]); + return fileArray.toArray(new File[fileArray.size()]); } @@ -1565,12 +1533,11 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl * @return 是否写入成功 * @throws Exception 异常 */ - @Override public boolean writeSvgFile(SvgProvider svgFile) throws Exception { testServerConnection(); - HashMap para = new HashMap<>(); - para.put("op", "svgrelate"); + HashMap para = new HashMap(); + para.put("op", "svginit"); para.put("cmd", "design_save_svg"); para.put("filePath", svgFile.getFilePath()); para.put("current_uid", this.createUserID()); @@ -1622,7 +1589,7 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl public boolean writeResource(XMLFileManagerProvider mgr) throws Exception { testServerConnection(); - HashMap para = new HashMap<>(); + HashMap para = new HashMap(); para.put("op", "fr_remote_design"); para.put("cmd", "design_save_resource"); para.put("resource", mgr.fileName()); @@ -1657,10 +1624,9 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl * @param prefix 当前Env下得工程分类,如reportlets,lib等 * @return InputStream 输入流 */ - @Override public InputStream readBean(String beanPath, String prefix) throws Exception { - HashMap para = new HashMap<>(); + HashMap para = new HashMap(); para.put("op", "fs_remote_design"); para.put("cmd", "design_open"); para.put(RemoteDeziConstants.PREFXI, prefix); @@ -1679,9 +1645,9 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl * @param prefix 当前Env下得工程分类,如reportlets,lib等 * @return OutputStream 输出流 */ - @Override - public OutputStream writeBean(String beanPath, String prefix) { - HashMap para = new HashMap<>(); + public OutputStream writeBean(String beanPath, String prefix) + throws Exception { + HashMap para = new HashMap(); para.put("op", "fs_remote_design"); para.put("cmd", "design_save_report"); para.put(RemoteDeziConstants.PREFXI, prefix); @@ -1699,7 +1665,7 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl */ @Override public String[] getColumns(String selectedName, String schema, String tableName) throws Exception { - HashMap para = new HashMap<>(); + HashMap para = new HashMap(); para.put("op", "fr_remote_design"); para.put("cmd", "design_columns"); para.put("dsName", selectedName); @@ -1730,7 +1696,7 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl @Override public String getProcedureText(String connectionName, String databaseName) throws Exception { - HashMap para = new HashMap<>(); + HashMap para = new HashMap(); para.put("op", "fr_remote_design"); para.put("cmd", "design_get_procedure_text"); para.put("procedure_name", databaseName); @@ -1747,7 +1713,7 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl @Override public StoreProcedureParameter[] getStoreProcedureDeclarationParameters(String connectionName, String databaseName, String parameterDefaultValue) throws Exception { ByteArrayOutputStream out = new ByteArrayOutputStream(); - HashMap para = new HashMap<>(); + HashMap para = new HashMap(); para.put("op", "fr_remote_design"); para.put("cmd", "design_get_sp_parameters"); para.put("__name__", databaseName); @@ -1764,10 +1730,9 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl /** * 获取datasource.xml文件的修改表 */ - @Override public ModifiedTable getDataSourceModifiedTables(String type) { try { - HashMap para = new HashMap<>(); + HashMap para = new HashMap(); para.put("op", "fr_remote_design"); para.put("cmd", "get_datasource_modified_tables"); para.put("type", type); @@ -1792,7 +1757,6 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl * @param type 操作类型,是数据连接还是服务器数据集 * @return 写入成功返回true */ - @Override public boolean writeDataSourceModifiedTables(ModifiedTable modifiedTable, String type) { ByteArrayOutputStream out = new ByteArrayOutputStream(); @@ -1800,7 +1764,7 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl // 把tableData写成xml文件到out DavXMLUtils.writeXMLModifiedTables(modifiedTable, out); try { - HashMap para = new HashMap<>(); + HashMap para = new HashMap(); para.put("op", "fr_remote_design"); para.put("cmd", "update_modifytable_to_server"); para.put("type", type); @@ -1820,7 +1784,7 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl public String[] getProcedureColumns(StoreProcedure storeProcedure, java.util.Map parameterMap) throws Exception { String[] columns; - HashMap para = new HashMap<>(); + HashMap para = new HashMap(); para.put("op", "fr_remote_design"); para.put("cmd", "list_sp"); HttpClient client = createHttpMethod(para); @@ -1834,15 +1798,17 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl columns = DavXMLUtils.readXMLSPColumns(input); return columns; } catch (Exception e) { - FRContext.getLogger().error(e.getMessage()); + FRLogger.getLogger().error(e.getMessage()); } return new String[0]; } + ; + public String[] getProcedureColumns(String name) throws Exception { String[] columns; - HashMap para = new HashMap<>(); + HashMap para = new HashMap(); para.put("op", "fr_remote_design"); para.put("cmd", "list_sp_columns_name"); para.put("name", name); @@ -1855,7 +1821,7 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl columns = DavXMLUtils.readXMLSPColumns(input); return columns; } catch (Exception e) { - FRContext.getLogger().error(e.getMessage()); + FRLogger.getLogger().error(e.getMessage()); } return new String[0]; @@ -1866,10 +1832,9 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl * * @throws Exception */ - @Override public void printLogMessage() throws Exception { ByteArrayOutputStream out = new ByteArrayOutputStream(); - HashMap para = new HashMap<>(); + HashMap para = new HashMap(); para.put("op", "fr_remote_design"); para.put("cmd", "get_log_message"); @@ -1879,16 +1844,17 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl } LogRecordTime[] records = LogUtils.readXMLLogRecords(input); for (LogRecordTime logRecordTime : records) { - //TODO + DesignerLogHandler.getInstance().printRemoteLog(logRecordTime); } } - @Override public String getUserID() { return userID; } + //TODO: + /** * 预览存储过程 * @@ -1909,7 +1875,7 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl String jsonParameter = jo.toString(); try { - HashMap para = new HashMap<>(); + HashMap para = new HashMap(); para.put("op", "fr_remote_design"); para.put("cmd", "list_sp"); para.put("pars", jsonParameter); @@ -1933,13 +1899,12 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl } catch (Exception e) { - FRContext.getLogger().error(e.getMessage()); + FRLogger.getLogger().error(e.getMessage()); } return new ProcedureDataModel[0]; } - @Override public String getAppName() { return "WebReport"; } @@ -1951,11 +1916,10 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl * @return 是返回true * @throws Exception */ - @Override public boolean isOracle(Connection database) throws Exception { ByteArrayOutputStream out = new ByteArrayOutputStream(); DavXMLUtils.writeXMLFileDatabaseConnection(database, out); - HashMap para = new HashMap<>(); + HashMap para = new HashMap(); para.put("op", "fr_remote_design"); para.put("cmd", "design_get_isOracle"); InputStream input = postBytes2ServerB(out.toByteArray(), para); @@ -1965,7 +1929,6 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl return DavXMLUtils.readXMLBoolean(input); } - @Override public String[] getSupportedTypes() { return FILE_TYPE; } @@ -1975,7 +1938,6 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl * * @return 不支持返回false */ - @Override public boolean isSupportLocalFileOperate() { return false; } @@ -1986,11 +1948,10 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl * @param path 路径 * @return 有权限则返回true */ - @Override public boolean hasFileFolderAllow(String path) { HttpClient client = null; try { - HashMap para = new HashMap<>(); + HashMap para = new HashMap(); para.put("op", "fs_remote_design"); para.put("cmd", "design_filefolder_allow"); para.put("current_uid", this.createUserID()); @@ -2004,7 +1965,7 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl } return Boolean.valueOf(IOUtils.inputStream2String(input, EncodeConstants.ENCODING_UTF_8)); } catch (Exception e) { - FRContext.getLogger().error(e.getMessage()); + FRLogger.getLogger().error(e.getMessage()); return false; } @@ -2015,7 +1976,6 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl * * @return 是则返回true */ - @Override public boolean isRoot() { return isRoot; } @@ -2032,7 +1992,7 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl @Override public String getDesignerVersion() throws Exception { - HashMap para = new HashMap<>(); + HashMap para = new HashMap(); para.put("op", "fr_remote_design"); para.put("cmd", "design_get_designer_version"); para.put("user", user); @@ -2042,12 +2002,11 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl try { return stream2String(execute4InputStream(client)); } catch (Exception e) { - FRContext.getLogger().error(e.getMessage()); + FRLogger.getLogger().error(e.getMessage()); } return null; } - @Override public InputStream getDataSourceInputStream(String filePath) throws Exception { return readBean(filePath, "datasource"); } @@ -2057,7 +2016,7 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl public ArrayList getAllRole4Privilege(boolean isFS) { ArrayList allRoleList = new ArrayList(); try { - HashMap para = new HashMap<>(); + HashMap para = new HashMap(); para.put("op", "fr_remote_design"); para.put("cmd", "get_all_role"); para.put("isFS", String.valueOf(isFS)); @@ -2089,7 +2048,6 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl /** * 获取当前env的build文件路径 */ - @Override public String getBuildFilePath() { return StringUtils.isEmpty(buildFilePath) ? ResourceConstants.BUILD_PATH : buildFilePath; } @@ -2097,7 +2055,6 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl /** * 设置当前env的build文件路径 */ - @Override public void setBuildFilePath(String buildFilePath) { this.buildFilePath = buildFilePath; } @@ -2108,9 +2065,8 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl * @param sourceText 源代码 * @return 编译信息,有可能是成功信息,也有可能是出错或者警告信息 */ - @Override public JavaCompileInfo compilerSourceCode(String sourceText) throws Exception { - HashMap para = new HashMap<>(); + HashMap para = new HashMap(); para.put("op", "fr_remote_design"); para.put("cmd", "design_compile_source_code"); InputStream in = postBytes2ServerB(sourceText.getBytes(EncodeConstants.ENCODING_UTF_8), para); @@ -2129,69 +2085,70 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl @Override public String pluginServiceAction(String serviceID, String req) throws Exception { - HashMap para = new HashMap<>(); + HashMap para = new HashMap(); para.put("op", "fr_remote_design"); para.put("cmd", "design_get_plugin_service_data"); para.put("serviceID", serviceID); para.put("req", req); - //jim :加上user,远程设计点击预览时传递用户角色信息 - HttpClient client = createHttpMethod(para); + HttpClient client = createHttpMethod(para); //jim :加上user,远程设计点击预览时传递用户角色信息 InputStream inputStream = execute4InputStream(client); return IOUtils.inputStream2String(inputStream); } /** * 远程不启动,使用虚拟服务 - *

* - * @param serviceID serviceID + * @param serviceID */ @Override public void pluginServiceStart(String serviceID) { } @Override - public String[] loadREUFile() { - ResourceIOUtils.delete(StableUtils.pathJoin( - CacheManager.getProviderInstance().getCacheDirectory().getAbsolutePath(), - ShareConstants.DIR_SHARE_CACHE)); - - String zipFilePath = null; + public File[] loadREUFile() throws Exception { + File target = new File(CacheManager.getProviderInstance().getCacheDirectory(), + ShareConstants.DIR_SHARE_CACHE); + StableUtils.deleteFile(target); + StableUtils.mkdirs(target); + File cacheDir = null; + File zip = null; + OutputStream out = null; try { - HashMap para = new HashMap<>(); + HashMap para = new HashMap(); para.put("op", "fr_remote_design"); para.put("cmd", "design_read_reufile"); para.put("current_uid", this.createUserID()); para.put("currentUsername", this.getUser()); HttpClient client = createHttpMethod(para); - //拿到服务端传过来的整个共享文件夹的压缩文件的文件流 - InputStream input = client.getResponseStream(); - - zipFilePath = StableUtils.pathJoin(CacheManager.getProviderInstance().getCacheDirectory().getAbsolutePath(), "share.zip"); - String cacheDir = StableUtils.pathJoin(CacheManager.getProviderInstance().getCacheDirectory().getAbsolutePath(), ShareConstants.DIR_SHARE_CACHE); - - ResourceIOUtils.write(zipFilePath, input); - ResourceIOUtils.unzip(zipFilePath, cacheDir, EncodeConstants.ENCODING_GBK); - - - return ResourceIOUtils.listWithFullPath(cacheDir, new Filter() { - @Override - public boolean accept(String s) { - return s.endsWith(ProjectConstants.REU); - } - }); + InputStream input = client.getResponseStream();//拿到服务端传过来的整个共享文件夹的压缩文件的文件流 + zip = new File(StableUtils.pathJoin(CacheManager.getProviderInstance().getCacheDirectory().getAbsolutePath()), "share.zip"); + cacheDir = new File(StableUtils.pathJoin(CacheManager.getProviderInstance().getCacheDirectory().getAbsolutePath()), ShareConstants.DIR_SHARE_CACHE); + StableUtils.deleteFile(cacheDir); + StableUtils.mkdirs(cacheDir); + StableUtils.makesureFileExist(zip); + out = new FileOutputStream(zip); + IOUtils.copyBinaryTo(input, out);//放到本地缓存目录下 + + IOUtils.unzip(zip, cacheDir.getAbsolutePath(), EncodeConstants.ENCODING_GBK);//先解压到临时目录 + if (cacheDir.exists() && cacheDir.isDirectory()) { + return cacheDir.listFiles(new FilenameFilter() { + public boolean accept(File file, String s) { + return s.endsWith("reu"); + } + }); + } } catch (Exception e) { FRContext.getLogger().error(e.getMessage()); } finally { - - if (zipFilePath != null) { - ResourceIOUtils.delete(zipFilePath); + if (out != null) { + out.flush(); + out.close(); } + StableUtils.deleteFile(zip); } - - return new String[0]; + return new File[0]; } @Override @@ -2204,7 +2161,7 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl String shareXMLName = StableUtils.pathJoin(tempFile.getAbsolutePath(), ShareConstants.NAME_XML_MODULE); String helpXMLName = StableUtils.pathJoin(tempFile.getAbsolutePath(), ShareConstants.NAME_XML_HELP); try { - HashMap para = new HashMap<>(); + HashMap para = new HashMap(); para.put("op", "fr_remote_design"); para.put("cmd", "design_install_reufile"); para.put("current_uid", this.createUserID()); @@ -2231,7 +2188,7 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl return true; } try { - HashMap para = new HashMap<>(); + HashMap para = new HashMap(); para.put("op", "fr_remote_design"); para.put("cmd", "design_remove_reufile"); para.put("current_uid", this.createUserID()); @@ -2248,22 +2205,9 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl @Override public String getSharePath() { - try { - HashMap para = new HashMap<>(); - para.put("op", "fr_remote_design"); - para.put("cmd", "design_get_share_path"); - para.put("current_uid", this.createUserID()); - para.put("currentUsername", this.getUser()); - - HttpClient client = createHttpMethod(para); - InputStream input = execute4InputStream(client); - return stream2String(input); - } catch (Exception e) { - return StringUtils.EMPTY; - } + return StringUtils.EMPTY; } - @Override public void doWhenServerShutDown() { } @@ -2284,7 +2228,7 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl public JSONArray getPluginStatus() { try { - HashMap para = new HashMap<>(); + HashMap para = new HashMap(); para.put("op", "plugin"); para.put("cmd", "get_status"); para.put("current_uid", this.createUserID()); @@ -2297,4 +2241,14 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl return JSONArray.create(); } } -} \ No newline at end of file + + public String post(HashMap para, boolean isSignIn) { + try { + HttpClient client = createHttpMethod(para, isSignIn); + return stream2String(execute4InputStream(client)); + } catch (Exception e) { + FRContext.getLogger().error(e.getMessage()); + return StringUtils.EMPTY; + } + } +} diff --git a/designer-base/src/com/fr/env/SignIn.java b/designer-base/src/com/fr/env/SignIn.java index a5f2860ec..8cb021a82 100644 --- a/designer-base/src/com/fr/env/SignIn.java +++ b/designer-base/src/com/fr/env/SignIn.java @@ -40,4 +40,4 @@ public class SignIn { FRContext.getLogger().error(e.getMessage(), e); } } -} \ No newline at end of file +} From b9b023752ec3e6cd6bdc5a88ee135fc6121bee16 Mon Sep 17 00:00:00 2001 From: hzzz Date: Fri, 25 May 2018 15:32:42 +0800 Subject: [PATCH 2/9] merge --- .../src/com/fr/design/DesignerEnvManager.java | 194 +- .../design/actions/file/SwitchExistEnv.java | 40 +- .../com/fr/design/file/FileOperations.java | 18 +- .../design/file/HistoryTemplateListPane.java | 4 +- .../com/fr/design/file/TemplateTreePane.java | 57 +- .../fr/design/mainframe/DesignerFrame.java | 123 +- .../DesignerFrameFileDealerPane.java | 86 +- .../com/fr/design/mainframe/TemplatePane.java | 719 ++----- .../loghandler/DesignerLogHandler.java | 20 +- .../src/com/fr/design/utils/DesignUtils.java | 111 +- designer-base/src/com/fr/env/EnvListPane.java | 527 +---- .../src/com/fr/env/LocalEnvPane.java | 9 +- designer-base/src/com/fr/env/RemoteEnv.java | 1697 ++--------------- .../src/com/fr/env/RemoteEnvPane.java | 5 +- designer-base/src/com/fr/env/SignIn.java | 64 +- .../src/com/fr/start/server/FRTomcat.java | 8 +- .../src/com/fr/start/Designer4Debug.java | 6 +- 17 files changed, 753 insertions(+), 2935 deletions(-) diff --git a/designer-base/src/com/fr/design/DesignerEnvManager.java b/designer-base/src/com/fr/design/DesignerEnvManager.java index 111e4f625..fcc4c2b26 100644 --- a/designer-base/src/com/fr/design/DesignerEnvManager.java +++ b/designer-base/src/com/fr/design/DesignerEnvManager.java @@ -4,9 +4,12 @@ package com.fr.design; import com.fr.base.BaseXMLUtils; -import com.fr.base.Env; import com.fr.base.FRContext; import com.fr.base.Utils; +import com.fr.base.env.resource.EnvConfigUtils; +import com.fr.base.env.resource.LocalEnvConfig; +import com.fr.base.env.resource.RemoteEnvConfig; +import com.fr.core.env.EnvConfig; import com.fr.dav.LocalEnv; import com.fr.design.actions.help.alphafine.AlphaFineConfigManager; import com.fr.design.constants.UIConstants; @@ -61,7 +64,6 @@ public class DesignerEnvManager implements XMLReadable, XMLWriter { private static final int MAX_SHOW_NUM = 10; private static final String VERSION_80 = "80"; - private static final int CACHINGTEMPLATE_LIMIT = 5; private static DesignerEnvManager designerEnvManager; // gui. private String activationKey = null; @@ -73,7 +75,7 @@ public class DesignerEnvManager implements XMLReadable, XMLWriter { private boolean showPaintToolBar = true; private int maxNumberOrPreviewRow = 200; // name和Env的键值对 - private Map nameEnvMap = new ListMap(); + private Map nameEnvMap = new ListMap(); // marks: 当前报表服务器名字 private String curEnvName = null; private boolean showProjectPane = true; @@ -100,7 +102,6 @@ public class DesignerEnvManager implements XMLReadable, XMLWriter { private int language; //2014-8-26默认显示全部, 因为以前的版本, 虽然是false, 实际上是显示所有表, 因此这边要兼容 private boolean useOracleSystemSpace = true; - private int cachingTemplateLimit = CACHINGTEMPLATE_LIMIT; private boolean autoBackUp = true; private int undoLimit = 5; private short pageLengthUnit = Constants.UNIT_MM; @@ -148,7 +149,6 @@ public class DesignerEnvManager implements XMLReadable, XMLWriter { private boolean isHttps = false; private static List mapWorkerList = new ArrayList(); - private boolean imageCompress = false;//图片压缩 /** * DesignerEnvManager. @@ -194,7 +194,7 @@ public class DesignerEnvManager implements XMLReadable, XMLWriter { if (installHome != null) { String name = Inter.getLocText("FR-Engine_DEFAULT"); String envPath = StableUtils.pathJoin(new String[]{installHome, ProjectConstants.WEBAPP_NAME, ProjectConstants.WEBINF_NAME}); - designerEnvManager.putEnv(name, LocalEnv.createEnv(envPath)); + designerEnvManager.putEnv(name, new LocalEnvConfig(envPath)); designerEnvManager.setCurEnvName(name); } } @@ -247,8 +247,7 @@ public class DesignerEnvManager implements XMLReadable, XMLWriter { // 写文件的LogLocation String logLocation = DesignerEnvManager.getEnvManager().getLogLocation(); - //Mac下8.0,9.0 选项-日志设置为空时在根目录下检测文件存在会抛无权限,这里应该设个默认值比较好吧 - if (StringUtils.isNotEmpty(logLocation)) { + if (logLocation != null) { try { Calendar calender = GregorianCalendar.getInstance(); calender.setTimeInMillis(System.currentTimeMillis()); @@ -327,7 +326,7 @@ public class DesignerEnvManager implements XMLReadable, XMLWriter { FRContext.getLogger().error(e.getMessage(), e); } // 清空前一个版本中的工作目录和最近打开 - nameEnvMap = new ListMap(); + nameEnvMap = new ListMap(); recentOpenedFilePathList = new ArrayList(); curEnvName = null; designerEnvManager.saveXMLFile(); @@ -474,7 +473,7 @@ public class DesignerEnvManager implements XMLReadable, XMLWriter { * @return 是默认则返回true */ public boolean isCurrentEnvDefault() { - Env currentEnv = this.getEnv(curEnvName); + EnvConfig currentEnv = this.getEnv(curEnvName); String defaultEnvPath = StableUtils.pathJoin(new String[]{StableUtils.getInstallHome(), ProjectConstants.WEBAPP_NAME, ProjectConstants.WEBINF_NAME}); return ComparatorUtils.equals(new File(defaultEnvPath).getPath(), currentEnv.getPath()); } @@ -482,21 +481,19 @@ public class DesignerEnvManager implements XMLReadable, XMLWriter { /** * 返回默认环境 */ - public Env getDefaultEnv() { + public EnvConfig getDefaultEnv() { String installHome = StableUtils.getInstallHome(); - String defaultenvPath = StableUtils.pathJoin(new String[]{installHome, ProjectConstants.WEBAPP_NAME, ProjectConstants.WEBINF_NAME}); + String defaultenvPath = StableUtils.pathJoin(installHome, ProjectConstants.WEBAPP_NAME, ProjectConstants.WEBINF_NAME); defaultenvPath = new File(defaultenvPath).getPath(); - if (nameEnvMap.size() >= 0) { - Iterator> entryIt = nameEnvMap.entrySet().iterator(); - while (entryIt.hasNext()) { - Entry entry = entryIt.next(); - Env env = entry.getValue(); - if (ComparatorUtils.equals(defaultenvPath, env.getPath())) { - return env; - } + Iterator> entryIt = nameEnvMap.entrySet().iterator(); + while (entryIt.hasNext()) { + Entry entry = entryIt.next(); + EnvConfig env = entry.getValue(); + if (ComparatorUtils.equals(defaultenvPath, env.getPath())) { + return env; } } - Env newDefaultEnv = LocalEnv.createEnv(defaultenvPath); + EnvConfig newDefaultEnv = new LocalEnvConfig(defaultenvPath); this.putEnv(Inter.getLocText(new String[]{"Default", "Utils-Report_Runtime_Env"}), newDefaultEnv); return newDefaultEnv; } @@ -509,10 +506,10 @@ public class DesignerEnvManager implements XMLReadable, XMLWriter { String defaultenvPath = StableUtils.pathJoin(new String[]{installHome, ProjectConstants.WEBAPP_NAME, ProjectConstants.WEBINF_NAME}); defaultenvPath = new File(defaultenvPath).getPath(); if (nameEnvMap.size() >= 0) { - Iterator> entryIt = nameEnvMap.entrySet().iterator(); + Iterator> entryIt = nameEnvMap.entrySet().iterator(); while (entryIt.hasNext()) { - Entry entry = entryIt.next(); - Env env = entry.getValue(); + Entry entry = entryIt.next(); + EnvConfig env = entry.getValue(); if (ComparatorUtils.equals(defaultenvPath, env.getPath())) { return entry.getKey(); } @@ -635,21 +632,6 @@ public class DesignerEnvManager implements XMLReadable, XMLWriter { this.useOracleSystemSpace = displayOracleSystem; } - /** - * 配置最大缓存模板个数 - */ - public void setCachingTemplateLimit(int cachingTemplateLimit) { - this.cachingTemplateLimit = cachingTemplateLimit; - } - - - /** - * 获取最大缓存模板个数 - */ - public int getCachingTemplateLimit() { - return this.cachingTemplateLimit; - } - /** * 是否加入产品改良 * @@ -699,7 +681,7 @@ public class DesignerEnvManager implements XMLReadable, XMLWriter { /** * 根据名称返回环境 */ - public Env getEnv(String name) { + public EnvConfig getEnv(String name) { return this.nameEnvMap.get(name); } @@ -709,7 +691,7 @@ public class DesignerEnvManager implements XMLReadable, XMLWriter { * @param name 名称 * @param env 对应的环境 */ - public void putEnv(String name, Env env) { + public void putEnv(String name, EnvConfig env) { this.nameEnvMap.put(name, env); } @@ -1413,16 +1395,14 @@ public class DesignerEnvManager implements XMLReadable, XMLWriter { this.setMaxNumberOrPreviewRow(reader.getAttrAsInt("maxNumberOrPreviewRow", 200)); this.setOracleSystemSpace(reader.getAttrAsBoolean("useOracleSystemSpace", true)); - this.setCachingTemplateLimit(reader.getAttrAsInt("cachingTemplateLimit", CACHINGTEMPLATE_LIMIT)); this.setJoinProductImprove(reader.getAttrAsBoolean("joinProductImprove", true)); - this.setImageCompress(reader.getAttrAsBoolean("imageCompress", true)); this.setAutoBackUp(reader.getAttrAsBoolean("autoBackUp", true)); this.setTemplateTreePaneExpanded(reader.getAttrAsBoolean("templateTreePaneExpanded", false)); // peter:读取webinfLocation if ((tmpVal = reader.getAttrAsString("webinfLocation", null)) != null) { // marks:兼容6.1的 // marks:设置默认的目录. - Env reportServer = LocalEnv.createEnv(tmpVal); + EnvConfig reportServer = new LocalEnvConfig(tmpVal); String curReportServerName = Inter.getLocText("Server-Embedded_Server"); this.putEnv(curReportServerName, reportServer); @@ -1479,7 +1459,7 @@ public class DesignerEnvManager implements XMLReadable, XMLWriter { // marks:获取名字 String reportServerName = reader.getAttrAsString("name", null); - Env env = readEnv(reader); + EnvConfig env = readEnv(reader); if (env == null) { return; } @@ -1605,7 +1585,7 @@ public class DesignerEnvManager implements XMLReadable, XMLWriter { Iterator nameIt = this.getEnvNameIterator(); while (nameIt.hasNext()) { String envName = nameIt.next(); - Env env = this.getEnv(envName); + EnvConfig env = this.getEnv(envName); writeEnv(writer, envName, env); } @@ -1635,15 +1615,9 @@ public class DesignerEnvManager implements XMLReadable, XMLWriter { if (!this.isOracleSystemSpace()) { writer.attr("useOracleSystemSpace", this.isOracleSystemSpace()); } - if (this.getCachingTemplateLimit() >= 0) { - writer.attr("cachingTemplateLimit", this.getCachingTemplateLimit()); - } if (!this.isJoinProductImprove()) { writer.attr("joinProductImprove", this.isJoinProductImprove()); } - if (!this.isImageCompress()) { - writer.attr("imageCompress", this.isImageCompress()); - } if (!this.isAutoBackUp()) { writer.attr("autoBackUp", this.isAutoBackUp()); } @@ -1770,44 +1744,44 @@ public class DesignerEnvManager implements XMLReadable, XMLWriter { } /* - * 写Env为xml - */ - private static void writeEnv(XMLPrintWriter writer, String name, Env env) { + * 写Env为xml + */ + private static void writeEnv(XMLPrintWriter writer, String name, EnvConfig env) { if (env == null) { return; } - writer.startTAG("Env"); + writer.startTAG("EnvConfig"); writer.classAttr(env.getClass()); writer.attr("name", name); - env.writeXML(writer); - + EnvConfigXMLAdapter xmlAdapter = env instanceof RemoteEnvConfig + ? new RemoteEnvConfigXMLAdapter() + : new LocalEnvConfigXMLAdapter(); + xmlAdapter.fromEnvConfig(env).writeXML(writer); writer.end(); } /* - * 从xml读Env - */ - private static Env readEnv(XMLableReader reader) { - Env env = null; - + * 从xml读Env + */ + private static EnvConfig readEnv(XMLableReader reader) { + EnvConfigXMLAdapter xmlAdapter = null; String tmpVal; //temp value if ((tmpVal = reader.getAttrAsString("class", null)) != null) { - if (tmpVal.endsWith(".LocalEnv")) { - env = LocalEnv.createEnv(); - } else if (tmpVal.endsWith(".RemoteEnv")) { - env = new RemoteEnv(); + if (tmpVal.contains(".LocalEnv")) { + xmlAdapter = new LocalEnvConfigXMLAdapter(); + } else if (tmpVal.contains(".RemoteEnv")) { + xmlAdapter = new RemoteEnvConfigXMLAdapter(); } } - if (env == null) { - return env; + if (xmlAdapter == null) { + return null; } - reader.readXMLObject(env); - - return env; + reader.readXMLObject(xmlAdapter); + return xmlAdapter.toEnvConfig(); } public AlphaFineConfigManager getAlphaFineConfigManager() { @@ -1818,11 +1792,77 @@ public class DesignerEnvManager implements XMLReadable, XMLWriter { this.alphaFineConfigManager = alphaFineConfigManager; } - public boolean isImageCompress() { - return imageCompress; + private interface EnvConfigXMLAdapter extends XMLReadable, XMLWriter { + EnvConfig toEnvConfig(); + + EnvConfigXMLAdapter fromEnvConfig(EnvConfig envConfig); } - public void setImageCompress(boolean imageCompress) { - this.imageCompress = imageCompress; + private static class LocalEnvConfigXMLAdapter implements EnvConfigXMLAdapter { + private String path; + + public void readXML(XMLableReader reader) { + if (reader.isChildNode()) { + if ("DIR".equals(reader.getTagName())) { + this.path = reader.getElementValue(); + } + } + } + + public void writeXML(XMLPrintWriter writer) { + writer.startTAG("DIR").textNode(this.path).end(); + } + + public EnvConfig toEnvConfig() { + return new LocalEnvConfig(path); + } + + public EnvConfigXMLAdapter fromEnvConfig(EnvConfig envConfig) { + this.path = envConfig.getPath(); + return this; + } + + } + + private static class RemoteEnvConfigXMLAdapter implements EnvConfigXMLAdapter { + private String path; + private String username; + private String password; + + public void readXML(XMLableReader reader) { + if (reader.isChildNode()) { + String tmpVal; + if ("DIR".equals(reader.getTagName())) { + if ((tmpVal = reader.getAttrAsString("path", null)) != null) { + this.path = tmpVal; + } + if ((tmpVal = reader.getAttrAsString("user", null)) != null) { + this.username = tmpVal; + } + if ((tmpVal = reader.getAttrAsString("password", null)) != null) { + this.password = tmpVal; + } + } + } + } + + public void writeXML(XMLPrintWriter writer) { + writer.startTAG("DIR") + .attr("path", this.path) + .attr("user", this.username) + .attr("password", this.password) + .end(); + } + + public EnvConfig toEnvConfig() { + return new RemoteEnvConfig(path, username, password); + } + + public EnvConfigXMLAdapter fromEnvConfig(EnvConfig envConfig) { + this.path = envConfig.getPath(); + this.username = EnvConfigUtils.getUsername(envConfig); + this.password = EnvConfigUtils.getPassword(envConfig); + return this; + } } -} +} \ No newline at end of file diff --git a/designer-base/src/com/fr/design/actions/file/SwitchExistEnv.java b/designer-base/src/com/fr/design/actions/file/SwitchExistEnv.java index ea709385f..2da352c83 100644 --- a/designer-base/src/com/fr/design/actions/file/SwitchExistEnv.java +++ b/designer-base/src/com/fr/design/actions/file/SwitchExistEnv.java @@ -3,6 +3,9 @@ package com.fr.design.actions.file; import com.fr.base.BaseUtils; import com.fr.base.Env; import com.fr.base.FRContext; +import com.fr.base.env.resource.LocalEnvConfig; +import com.fr.base.env.resource.RemoteEnvConfig; +import com.fr.core.env.EnvConfig; import com.fr.dav.LocalEnv; import com.fr.design.DesignerEnvManager; import com.fr.design.actions.UpdateAction; @@ -36,9 +39,6 @@ import java.util.logging.Level; public class SwitchExistEnv extends MenuDef { - // 标志开始切换环境 - private static boolean isSwitching = false; - public SwitchExistEnv() { this.setMenuKeySet(KeySetUtils.SWITCH_ENV); this.setName(getMenuKeySet().getMenuName()); @@ -74,10 +74,10 @@ public class SwitchExistEnv extends MenuDef { public GetExistEnvAction(String envName) { this.setName(envName); - Env env = DesignerEnvManager.getEnvManager().getEnv(envName); - if (env instanceof LocalEnv) { + EnvConfig env = DesignerEnvManager.getEnvManager().getEnv(envName); + if (env instanceof LocalEnvConfig) { this.setSmallIcon(BaseUtils.readIcon("com/fr/design/images/data/bind/localconnect.png")); - } else if (env instanceof RemoteEnv) { + } else if (env instanceof RemoteEnvConfig) { this.setSmallIcon(BaseUtils.readIcon("com/fr/design/images/data/bind/distanceconnect.png")); } } @@ -104,35 +104,29 @@ public class SwitchExistEnv extends MenuDef { * @param e 事件 */ public void actionPerformed(ActionEvent e) { - isSwitching = true; DesignerEnvManager envManager = DesignerEnvManager.getEnvManager(); - Env selectedEnv = envManager.getEnv(this.getName()); + EnvConfig selectedEnv = envManager.getEnv(this.getName()); try { if (selectedEnv instanceof RemoteEnv && !((RemoteEnv) selectedEnv).testServerConnection()) { JOptionPane.showMessageDialog(DesignerContext.getDesignerFrame(), Inter.getLocText(new String[]{"M-SwitchWorkspace", "Failed"})); return; } - String remoteVersion = selectedEnv.getDesignerVersion(); - if (StringUtils.isBlank(remoteVersion) || ComparatorUtils.compare(remoteVersion, ProductConstants.DESIGNER_VERSION) < 0) { - String infor = Inter.getLocText("Server-version-tip"); - String moreInfo = Inter.getLocText("Server-version-tip-moreInfo"); - FRLogger.getLogger().log(Level.WARNING, infor); - new InformationWarnPane(infor, moreInfo, Inter.getLocText("Tooltips")).show(); - return; - } +// String remoteVersion = selectedEnv.getDesignerVersion(); +// if (StringUtils.isBlank(remoteVersion) || ComparatorUtils.compare(remoteVersion, ProductConstants.DESIGNER_VERSION) < 0) { +// String infor = Inter.getLocText("Server-version-tip"); +// String moreInfo = Inter.getLocText("Server-version-tip-moreInfo"); +// FRLogger.getLogger().log(Level.WARNING, infor); +// new InformationWarnPane(infor, moreInfo, Inter.getLocText("Tooltips")).show(); +// return; +// } SignIn.signIn(selectedEnv); + HistoryTemplateListPane.getInstance().getCurrentEditingTemplate().refreshToolArea(); fireDSChanged(); } catch (Exception em) { FRContext.getLogger().error(em.getMessage(), em); JOptionPane.showMessageDialog(DesignerContext.getDesignerFrame(), Inter.getLocText(new String[]{"M-SwitchWorkspace", "Failed"})); TemplatePane.getInstance().editItems(); - } finally { - isSwitching = false; } } } - - public static boolean isSwitching() { - return isSwitching; - } -} +} \ No newline at end of file diff --git a/designer-base/src/com/fr/design/file/FileOperations.java b/designer-base/src/com/fr/design/file/FileOperations.java index 390a28e0c..34b86cbc6 100644 --- a/designer-base/src/com/fr/design/file/FileOperations.java +++ b/designer-base/src/com/fr/design/file/FileOperations.java @@ -5,34 +5,34 @@ public interface FileOperations { /** *打开选中的报表文件 */ - public void openSelectedReport(); + public void openSelectedReport(); /** *打开文件夹 */ - public void openContainerFolder(); + public void openContainerFolder(); /** *刷新 */ - public void refresh(); + public void refresh(); /** *删除文件 */ - public void deleteFile(); + public void deleteFile(); /** *加上文件锁 */ - public void lockFile(); + public void lockFile(); /** *文件解锁 */ - public void unLockFile(); + public void unLockFile(); - public String getSelectedTemplatePath(); + public String getSelectedTemplatePath(); /** *文件名是否存在 @@ -41,5 +41,5 @@ public interface FileOperations { * @param suffix 后缀名 * @return 是否存在 */ - public boolean isNameAlreadyExist(String newName, String oldName, String suffix); -} + public boolean isNameAlreadyExist(String newName, String oldName, String suffix); +} \ No newline at end of file diff --git a/designer-base/src/com/fr/design/file/HistoryTemplateListPane.java b/designer-base/src/com/fr/design/file/HistoryTemplateListPane.java index deda53953..dfd1f123f 100644 --- a/designer-base/src/com/fr/design/file/HistoryTemplateListPane.java +++ b/designer-base/src/com/fr/design/file/HistoryTemplateListPane.java @@ -38,7 +38,7 @@ import com.fr.design.utils.gui.GUIPaintUtils; public class HistoryTemplateListPane extends JPanel implements FileOperations, CallbackEvent { //最大保存内存中面板数,为0时关闭优化内存 - private static final int DEAD_LINE = DesignerEnvManager.getEnvManager().getCachingTemplateLimit(); + private static final int DEAD_LINE = 5; private static final int LIST_BORDER = 4; private List> historyList; private JTemplate editingTemplate; @@ -438,4 +438,4 @@ public class HistoryTemplateListPane extends JPanel implements FileOperations, C return isNameAreadyExist; } -} +} \ No newline at end of file diff --git a/designer-base/src/com/fr/design/file/TemplateTreePane.java b/designer-base/src/com/fr/design/file/TemplateTreePane.java index 969a66f32..a52e42389 100644 --- a/designer-base/src/com/fr/design/file/TemplateTreePane.java +++ b/designer-base/src/com/fr/design/file/TemplateTreePane.java @@ -26,7 +26,11 @@ import com.sun.jna.platform.FileUtils; import javax.swing.*; import javax.swing.tree.DefaultMutableTreeNode; import java.awt.*; -import java.awt.event.*; +import java.awt.event.KeyEvent; +import java.awt.event.KeyListener; +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; +import java.awt.event.MouseListener; import java.io.File; import java.io.IOException; import java.util.ArrayList; @@ -139,7 +143,7 @@ public class TemplateTreePane extends JPanel implements FileOperations { public void openContainerFolder() { FileNode fn = TemplateTreePane.this.reportletsTree.getSelectedFileNode(); LocalEnv localEnv = (LocalEnv) FRContext.getCurrentEnv(); - String filePath = StableUtils.pathJoin(new String[]{localEnv.path, fn.getEnvPath()}); + String filePath = StableUtils.pathJoin(localEnv.getPath(), fn.getEnvPath()); filePath = filePath.substring(0, filePath.lastIndexOf(CoreConstants.SEPARATOR)); try { Desktop.getDesktop().open(new File(filePath)); @@ -189,6 +193,16 @@ public class TemplateTreePane extends JPanel implements FileOperations { reportletsTree.refresh(); } + @Override + public void lockFile() { + throw new UnsupportedOperationException("unsupport now"); + } + + @Override + public void unLockFile() { + throw new UnsupportedOperationException("unsupport now"); + } + private void deleteHistory(String fileName) { int index = HistoryTemplateListPane.getInstance().contains(fileName); int size = HistoryTemplateListPane.getInstance().getHistoryCount(); @@ -214,41 +228,6 @@ public class TemplateTreePane extends JPanel implements FileOperations { MutilTempalteTabPane.getInstance().repaint(); } - /** - * 加上文件锁 - */ - public void lockFile() { - FileNode fn = reportletsTree.getSelectedFileNode(); - RemoteEnv remoteEnv = (RemoteEnv) FRContext.getCurrentEnv(); - if (fn == null) { - return; - } - try { - remoteEnv.getLock(new String[]{fn.getEnvPath()}); - } catch (Exception e) { - FRContext.getLogger().error(e.getMessage(), e); - JOptionPane.showMessageDialog(DesignerContext.getDesignerFrame(), e.getMessage()); - } - reportletsTree.refresh(); - } - - /** - * 文件解锁 - */ - public void unLockFile() { - FileNode fn = reportletsTree.getSelectedFileNode(); - if (fn == null) { - return; - } - RemoteEnv remoteEnv = (RemoteEnv) FRContext.getCurrentEnv(); - try { - remoteEnv.releaseLock(new String[]{fn.getEnvPath()}); - } catch (Exception e) { - FRContext.getLogger().error(e.getMessage(), e); - JOptionPane.showMessageDialog(DesignerContext.getDesignerFrame(), e.getMessage()); - } - reportletsTree.refresh(); - } public String getSelectedTemplatePath() { return reportletsTree.getSelectedTemplatePath(); @@ -315,6 +294,8 @@ public class TemplateTreePane extends JPanel implements FileOperations { if (fileUtils.hasTrash()) { try { fileUtils.moveToTrash(new File[]{new File(StableUtils.pathJoin(nodeFile.getEnvPath(), nodeFile.getPath()))}); + //todo 走下这个流程,否则集群下其它节点无法同步删除 + FRContext.getCurrentEnv().deleteFile(nodeFile.getPath()); } catch (IOException e) { FRLogger.getLogger().info(e.getMessage()); FRContext.getCurrentEnv().deleteFile(nodeFile.getPath()); @@ -325,4 +306,4 @@ public class TemplateTreePane extends JPanel implements FileOperations { } } -} +} \ No newline at end of file diff --git a/designer-base/src/com/fr/design/mainframe/DesignerFrame.java b/designer-base/src/com/fr/design/mainframe/DesignerFrame.java index 06911ee1d..f00a0830e 100644 --- a/designer-base/src/com/fr/design/mainframe/DesignerFrame.java +++ b/designer-base/src/com/fr/design/mainframe/DesignerFrame.java @@ -6,26 +6,19 @@ package com.fr.design.mainframe; import com.fr.base.BaseUtils; import com.fr.base.Env; import com.fr.base.FRContext; -import com.fr.base.vcs.DesignerMode; +import com.fr.base.env.resource.EnvConfigUtils; +import com.fr.core.env.EnvConfig; import com.fr.design.DesignModelAdapter; import com.fr.design.DesignState; import com.fr.design.DesignerEnvManager; import com.fr.design.ExtraDesignClassManager; -import com.fr.design.actions.core.ActionFactory; -import com.fr.design.actions.file.SwitchExistEnv; import com.fr.design.constants.UIConstants; import com.fr.design.data.DesignTableDataManager; import com.fr.design.data.datapane.TableDataTreePane; -import com.fr.design.event.DesignerOpenedListener; import com.fr.design.event.TargetModifiedEvent; import com.fr.design.event.TargetModifiedListener; -import com.fr.design.file.HistoryTemplateListPane; -import com.fr.design.file.MutilTempalteTabPane; -import com.fr.design.file.NewTemplatePane; -import com.fr.design.file.SaveSomeTemplatePane; -import com.fr.design.file.TemplateTreePane; +import com.fr.design.file.*; import com.fr.design.fun.TitlePlaceProcessor; -import com.fr.design.fun.impl.AbstractTemplateTreeShortCutProvider; import com.fr.design.gui.ibutton.UIButton; import com.fr.design.gui.imenu.UIMenuHighLight; import com.fr.design.gui.iscrollbar.UIScrollBar; @@ -35,7 +28,6 @@ import com.fr.design.mainframe.loghandler.LogMessageBar; import com.fr.design.mainframe.toolbar.ToolBarMenuDock; import com.fr.design.mainframe.toolbar.ToolBarMenuDockPlus; import com.fr.design.menu.MenuManager; -import com.fr.design.menu.ShortCut; import com.fr.design.utils.DesignUtils; import com.fr.design.utils.gui.GUICoreUtils; import com.fr.file.FILE; @@ -64,27 +56,14 @@ import javax.swing.border.MatteBorder; import java.awt.*; import java.awt.datatransfer.DataFlavor; import java.awt.datatransfer.Transferable; -import java.awt.dnd.DnDConstants; -import java.awt.dnd.DropTarget; -import java.awt.dnd.DropTargetDragEvent; -import java.awt.dnd.DropTargetDropEvent; -import java.awt.dnd.DropTargetEvent; -import java.awt.dnd.DropTargetListener; -import java.awt.event.ComponentAdapter; -import java.awt.event.ComponentEvent; -import java.awt.event.MouseAdapter; -import java.awt.event.MouseEvent; -import java.awt.event.MouseListener; -import java.awt.event.WindowAdapter; -import java.awt.event.WindowEvent; -import java.awt.event.WindowListener; +import java.awt.dnd.*; +import java.awt.event.*; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; -import java.util.Set; import java.util.logging.Level; public class DesignerFrame extends JFrame implements JTemplateActionListener, TargetModifiedListener { @@ -97,12 +76,7 @@ public class DesignerFrame extends JFrame implements JTemplateActionListener, Ta private static final Integer TOP_LAYER = new Integer((200)); private static java.util.List> appList = new java.util.ArrayList>(); - private List designerOpenedListenerList = new ArrayList<>(); - - //顶部日志+登陆按钮 - private static final JPanel northEastPane = FRGUIPaneFactory.createBorderLayout_S_Pane(); - - private static ToolBarMenuDock ad; + private ToolBarMenuDock ad; private DesktopCardPane centerTemplateCardPane; @@ -186,8 +160,8 @@ public class DesignerFrame extends JFrame implements JTemplateActionListener, Ta } public void mouseReleased(MouseEvent e) { - if (DesignerMode.isAuthorityEditing()) { - DesignerMode.setMode(DesignerMode.NORMARL); + if (BaseUtils.isAuthorityEditing()) { + BaseUtils.setAuthorityEditing(false); WestRegionContainerPane.getInstance().replaceDownPane( TableDataTreePane.getInstance(DesignModelAdapter.getCurrentModelAdapter())); HistoryTemplateListPane.getInstance().getCurrentEditingTemplate().refreshEastPropertiesPane(); @@ -263,7 +237,7 @@ public class DesignerFrame extends JFrame implements JTemplateActionListener, Ta this.addComponentListener(new ComponentAdapter() { public void componentResized(ComponentEvent e) { reCalculateFrameSize(); - if (DesignerMode.isAuthorityEditing()) { + if (BaseUtils.isAuthorityEditing()) { doResize(); } } @@ -294,22 +268,6 @@ public class DesignerFrame extends JFrame implements JTemplateActionListener, Ta } } - /** - * 注册"设计器初始化完成"的监听 - */ - public void addDesignerOpenedListener(DesignerOpenedListener listener) { - designerOpenedListenerList.add(listener); - } - - /** - * 触发"设计器初始化完成"事件 - */ - public void fireDesignerOpened() { - for (DesignerOpenedListener listener : designerOpenedListenerList) { - listener.designerOpened(); - } - } - protected DesktopCardPane getCenterTemplateCardPane() { return centerTemplateCardPane; } @@ -320,39 +278,41 @@ public class DesignerFrame extends JFrame implements JTemplateActionListener, Ta protected void initMenuPane() { menuPane = FRGUIPaneFactory.createBorderLayout_S_Pane(); menuPane.add(new UIMenuHighLight(), BorderLayout.SOUTH); - menuPane.add(initNorthEastPane(), BorderLayout.EAST); + menuPane.add(initNorthEastPane(ad), BorderLayout.EAST); basePane.add(menuPane, BorderLayout.NORTH); this.resetToolkitByPlus(null); } /** + * @param ad * @return */ - protected JPanel initNorthEastPane() { + protected JPanel initNorthEastPane(final ToolBarMenuDock ad) { //hugh: private修改为protected方便oem的时候修改右上的组件构成 - + //顶部日志+登陆按钮 + final JPanel northEastPane = FRGUIPaneFactory.createBorderLayout_S_Pane(); //优先级为-1,保证最后全面刷新一次 GeneralContext.listenPluginRunningChanged(new PluginEventListener(-1) { @Override public void on(PluginEvent event) { - refreshNorthEastPane(); + refreshNorthEastPane(northEastPane, ad); DesignUtils.refreshDesignerFrame(FRContext.getCurrentEnv()); } }, new PluginFilter() { @Override public boolean accept(PluginContext context) { - return !SwitchExistEnv.isSwitching() - && context.contain(PluginModule.ExtraDesign); + + return context.contain(PluginModule.ExtraDesign); } }); - refreshNorthEastPane(); + refreshNorthEastPane(northEastPane, ad); return northEastPane; } - public static void refreshNorthEastPane() { + private void refreshNorthEastPane(JPanel northEastPane, ToolBarMenuDock ad) { northEastPane.removeAll(); northEastPane.setLayout(new FlowLayout(FlowLayout.RIGHT, 0, 0)); northEastPane.add(LogMessageBar.getInstance()); @@ -457,7 +417,7 @@ public class DesignerFrame extends JFrame implements JTemplateActionListener, Ta * 刷新 */ public void refreshDottedLine() { - if (DesignerMode.isAuthorityEditing()) { + if (BaseUtils.isAuthorityEditing()) { populateAuthorityArea(); populateCloseButton(); addDottedLine(); @@ -516,7 +476,7 @@ public class DesignerFrame extends JFrame implements JTemplateActionListener, Ta for (int i = 0; i < fixButtons.length; i++) { combineUp.add(fixButtons[i]); } - if (!DesignerMode.isAuthorityEditing()) { + if (!BaseUtils.isAuthorityEditing()) { combineUp.addSeparator(new Dimension(2, 16)); if (toolbar4Form != null) { for (int i = 0; i < toolbar4Form.length; i++) { @@ -627,16 +587,7 @@ public class DesignerFrame extends JFrame implements JTemplateActionListener, Ta */ public void needToAddAuhtorityPaint() { - newWorkBookPane.setButtonGray(DesignerMode.isAuthorityEditing()); - - // 进入或退出权限编辑模式,通知插件 - Set extraShortCuts = ExtraDesignClassManager.getInstance().getExtraShortCuts(); - for (ShortCut shortCut : extraShortCuts) { - if (shortCut instanceof AbstractTemplateTreeShortCutProvider) { - ((AbstractTemplateTreeShortCutProvider) shortCut).notifyFromAuhtorityChange(DesignerMode.isAuthorityEditing()); - } - } - + newWorkBookPane.setButtonGray(BaseUtils.isAuthorityEditing()); } /** @@ -660,10 +611,10 @@ public class DesignerFrame extends JFrame implements JTemplateActionListener, Ta defaultTitleSB.append(ProductConstants.BRANCH); // james:标识登录的用户和登录的ENV String envName = DesignerEnvManager.getEnvManager().getCurEnvName(); - Env env = DesignerEnvManager.getEnvManager().getEnv(envName); + EnvConfig env = DesignerEnvManager.getEnvManager().getEnv(envName); if (env != null) { - defaultTitleSB.append(env.getUser()).append('@').append(envName).append('['); - defaultTitleSB.append(env.getEnvDescription()); + defaultTitleSB.append(EnvConfigUtils.getUsername(env)).append('@').append(envName).append('['); + defaultTitleSB.append(Inter.getLocText("Env-Remote_Server")); defaultTitleSB.append(']'); if (editingTemplate != null) { String path = editingTemplate.getEditingFILE().getPath(); @@ -716,16 +667,13 @@ public class DesignerFrame extends JFrame implements JTemplateActionListener, Ta * @param env 环境 */ public void refreshEnv(Env env) { + this.setTitle(); DesignerFrameFileDealerPane.getInstance().refreshDockingView(); TableDataTreePane.getInstance(DesignModelAdapter.getCurrentModelAdapter()); TemplateTreePane.getInstance().refreshDockingView(); DesignTableDataManager.clearGlobalDs(); EastRegionContainerPane.getInstance().refreshDownPane(); - JTemplate template = HistoryTemplateListPane.getInstance().getCurrentEditingTemplate(); - if (template != null) { - template.refreshToolArea(); - } } /** @@ -788,8 +736,6 @@ public class DesignerFrame extends JFrame implements JTemplateActionListener, Ta * @param jt 添加的模板. */ public void addAndActivateJTemplate(JTemplate jt) { - //释放模板对象 - ActionFactory.editorRelease(); if (jt == null || jt.getEditingFILE() == null) { return; } @@ -806,8 +752,6 @@ public class DesignerFrame extends JFrame implements JTemplateActionListener, Ta * @param jt 模板 */ public void activateJTemplate(JTemplate jt) { - //释放模板对象 - ActionFactory.editorRelease(); if (jt == null || jt.getEditingFILE() == null) { return; } @@ -913,16 +857,13 @@ public class DesignerFrame extends JFrame implements JTemplateActionListener, Ta String fileExtention = fileName.substring(indexOfLastDot + 1); for (int i = 0, len = appList.size(); i < len; i++) { App app = appList.get(i); - String[] defaultAppExtentions = app.defaultExtentions(); + String[] defaultAppExtentions = app.defaultExtensions(); boolean opened = false; for (int j = 0; j < defaultAppExtentions.length; j++) { if (defaultAppExtentions[j].equalsIgnoreCase(fileExtention)) { - JTemplate jt = null; - try { - jt = app.openTemplate(tplFile); - } catch (Exception e) { - FRLogger.getLogger().error(e.getMessage(), e); - } + // 不要catch + JTemplate jt = app.openTemplate(tplFile); + if (jt == null) { return; } @@ -969,6 +910,8 @@ public class DesignerFrame extends JFrame implements JTemplateActionListener, Ta } else { this.addAndActivateJTemplate(jt); } + //REPORT-5084:激活后刷新一下右側面板 + jt.refreshEastPropertiesPane(); } /** @@ -1080,4 +1023,4 @@ public class DesignerFrame extends JFrame implements JTemplateActionListener, Ta } } -} +} \ No newline at end of file diff --git a/designer-base/src/com/fr/design/mainframe/DesignerFrameFileDealerPane.java b/designer-base/src/com/fr/design/mainframe/DesignerFrameFileDealerPane.java index e5cfdfa69..af03db3fe 100644 --- a/designer-base/src/com/fr/design/mainframe/DesignerFrameFileDealerPane.java +++ b/designer-base/src/com/fr/design/mainframe/DesignerFrameFileDealerPane.java @@ -2,7 +2,6 @@ package com.fr.design.mainframe; import com.fr.base.BaseUtils; import com.fr.base.FRContext; -import com.fr.base.vcs.DesignerMode; import com.fr.design.DesignModelAdapter; import com.fr.design.DesignerEnvManager; import com.fr.design.ExtraDesignClassManager; @@ -11,11 +10,7 @@ import com.fr.design.constants.UIConstants; import com.fr.design.data.DesignTableDataManager; import com.fr.design.data.datapane.TableDataTreePane; import com.fr.design.data.tabledata.ResponseDataSourceChange; -import com.fr.design.file.FileOperations; -import com.fr.design.file.FileToolbarStateChangeListener; -import com.fr.design.file.HistoryTemplateListPane; -import com.fr.design.file.MutilTempalteTabPane; -import com.fr.design.file.TemplateTreePane; +import com.fr.design.file.*; import com.fr.design.gui.ibutton.UIButton; import com.fr.design.gui.ilable.UILabel; import com.fr.design.gui.imenu.UIMenuHighLight; @@ -33,6 +28,7 @@ import com.fr.file.FileNodeFILE; import com.fr.file.filetree.FileNode; import com.fr.general.ComparatorUtils; import com.fr.general.Inter; +import com.fr.io.utils.ResourceIOUtils; import com.fr.stable.CoreConstants; import com.fr.stable.StableUtils; import com.fr.stable.project.ProjectConstants; @@ -46,7 +42,6 @@ import java.awt.event.ActionListener; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.io.File; -import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import java.util.Set; @@ -57,11 +52,6 @@ public class DesignerFrameFileDealerPane extends JPanel implements FileToolbarSt private CardLayout card; private JPanel cardPane; - private java.util.List otherToobarStateChangeListeners= new ArrayList<>(); - - public FileOperations getSelectedOperation() { - return selectedOperation; - } private FileOperations selectedOperation; private UIToolbar toolBar; @@ -120,7 +110,7 @@ public class DesignerFrameFileDealerPane extends JPanel implements FileToolbarSt HistoryTemplateListPane.getInstance().setCurrentEditingTemplate(jt); //处理自动新建的模板 MutilTempalteTabPane.getInstance().doWithtemTemplate(); - if (DesignerMode.isAuthorityEditing()) { + if (BaseUtils.isAuthorityEditing()) { RolesAlreadyEditedPane.getInstance().refreshDockingView(); } @@ -144,7 +134,7 @@ public class DesignerFrameFileDealerPane extends JPanel implements FileToolbarSt } toolbarDef.addShortCut(delFileAction); Set extraShortCuts = ExtraDesignClassManager.getInstance().getExtraShortCuts(); - for (ShortCut shortCut : extraShortCuts) { + for (ShortCut shortCut : extraShortCuts){ toolbarDef.addShortCut(shortCut); } @@ -170,9 +160,8 @@ public class DesignerFrameFileDealerPane extends JPanel implements FileToolbarSt } /** - * 响应数据集改变 - * - * @param map 改变名字的数据集 + * 响应数据集改变 + * @param map 改变名字的数据集 */ public void fireDSChanged(Map map) { DesignTableDataManager.fireDSChanged(map); @@ -223,21 +212,6 @@ public class DesignerFrameFileDealerPane extends JPanel implements FileToolbarSt public void actionPerformed(ActionEvent evt) { selectedOperation.refresh(); stateChange(); - - } - } - - public void addToobarStateChangeListener(FileToolbarStateChangeListener toobarStateChangeListener) { - this.otherToobarStateChangeListeners.add(toobarStateChangeListener); - } - - public void removeToobarStateChangeListener(FileToolbarStateChangeListener toobarStateChangeListener) { - this.otherToobarStateChangeListeners.remove(toobarStateChangeListener); - } - - private void otherStateChange() { - for (FileToolbarStateChangeListener toobarStateChangeListener : otherToobarStateChangeListeners) { - toobarStateChangeListener.stateChange(); } } @@ -275,38 +249,6 @@ public class DesignerFrameFileDealerPane extends JPanel implements FileToolbarSt } } - /* - * 加锁 - */ - private class GetLockAction extends UpdateAction { - - public GetLockAction() { - this.setName(Inter.getLocText("FR-Designer_Get_Lock")); - this.setSmallIcon(BaseUtils.readIcon("/com/fr/design/images/control/lock.png")); - } - - @Override - public void actionPerformed(ActionEvent evt) { - selectedOperation.lockFile(); - } - } - - /* - * 解锁 - */ - private class ReleaseLockAction extends UpdateAction { - - public ReleaseLockAction() { - this.setName(Inter.getLocText("FR-Designer_Release_Lock")); - this.setSmallIcon(BaseUtils.readIcon("/com/fr/design/images/control/unlock.png")); - } - - @Override - public void actionPerformed(ActionEvent evt) { - selectedOperation.unLockFile(); - } - } - /** * 按钮状态改变 */ @@ -321,8 +263,8 @@ public class DesignerFrameFileDealerPane extends JPanel implements FileToolbarSt openReportAction.setEnabled(false); } FileNode node = TemplateTreePane.getInstance().getTemplateFileTree().getSelectedFileNode(); - if (selectedOperation.getSelectedTemplatePath() != null) { - if (node.getLock() != null && !ComparatorUtils.equals(node.getUserID(), node.getLock())) { + if (selectedOperation.getSelectedTemplatePath() != null){ + if (node.getLock() != null && !ComparatorUtils.equals(node.getUserID(),node.getLock())){ delFileAction.setEnabled(false); } else { delFileAction.setEnabled(true); @@ -355,7 +297,6 @@ public class DesignerFrameFileDealerPane extends JPanel implements FileToolbarSt delFileAction.setEnabled(true); } - otherStateChange(); } /** @@ -410,8 +351,8 @@ public class DesignerFrameFileDealerPane extends JPanel implements FileToolbarSt return; } - final FileNodeFILE nodeFile = new FileNodeFILE(new FileNode(StableUtils.pathJoin(new String[]{ProjectConstants.REPORTLETS_NAME, reportPath}), false)); - final String path = StableUtils.pathJoin(new String[]{nodeFile.getEnvPath(), nodeFile.getPath()}); + final FileNodeFILE nodeFile = new FileNodeFILE(new FileNode(StableUtils.pathJoin(ProjectConstants.REPORTLETS_NAME, reportPath), false)); + final String path = nodeFile.getPath(); oldName = nodeFile.getName(); suffix = oldName.substring(oldName.lastIndexOf(CoreConstants.DOT), oldName.length()); oldName = oldName.replaceAll(suffix, ""); @@ -504,8 +445,9 @@ public class DesignerFrameFileDealerPane extends JPanel implements FileToolbarSt String newPath = path.replace(nodeFile.getName(), userInput + suffix); renameTemplateInMemory(nodeFile, userInput + suffix, oldName + suffix); DesignerEnvManager.getEnvManager().replaceRecentOpenedFilePath(oldPath, newPath.replaceAll("/", "\\\\")); - File newFile = new File(newPath); - new File(path).renameTo(newFile); + + //模版重命名 + ResourceIOUtils.renameTo(path, newPath); selectedOperation.refresh(); DesignerContext.getDesignerFrame().setTitle(); jd.dispose(); @@ -595,4 +537,4 @@ public class DesignerFrameFileDealerPane extends JPanel implements FileToolbarSt return null; } -} +} \ No newline at end of file diff --git a/designer-base/src/com/fr/design/mainframe/TemplatePane.java b/designer-base/src/com/fr/design/mainframe/TemplatePane.java index e5cfdfa69..f95e0aee4 100644 --- a/designer-base/src/com/fr/design/mainframe/TemplatePane.java +++ b/designer-base/src/com/fr/design/mainframe/TemplatePane.java @@ -1,598 +1,279 @@ package com.fr.design.mainframe; import com.fr.base.BaseUtils; -import com.fr.base.FRContext; -import com.fr.base.vcs.DesignerMode; +import com.fr.base.Env; +import com.fr.core.env.EnvConfig; +import com.fr.dav.LocalEnv; import com.fr.design.DesignModelAdapter; import com.fr.design.DesignerEnvManager; -import com.fr.design.ExtraDesignClassManager; -import com.fr.design.actions.UpdateAction; -import com.fr.design.constants.UIConstants; -import com.fr.design.data.DesignTableDataManager; -import com.fr.design.data.datapane.TableDataTreePane; -import com.fr.design.data.tabledata.ResponseDataSourceChange; -import com.fr.design.file.FileOperations; -import com.fr.design.file.FileToolbarStateChangeListener; +import com.fr.design.dialog.BasicDialog; +import com.fr.design.dialog.DialogActionAdapter; +import com.fr.design.dialog.InformationWarnPane; import com.fr.design.file.HistoryTemplateListPane; -import com.fr.design.file.MutilTempalteTabPane; import com.fr.design.file.TemplateTreePane; import com.fr.design.gui.ibutton.UIButton; import com.fr.design.gui.ilable.UILabel; -import com.fr.design.gui.imenu.UIMenuHighLight; -import com.fr.design.gui.itextfield.UITextField; -import com.fr.design.gui.itoolbar.UIToolbar; -import com.fr.design.gui.itree.filetree.TemplateFileTree; -import com.fr.design.layout.FRGUIPaneFactory; -import com.fr.design.menu.KeySetUtils; -import com.fr.design.menu.ShortCut; -import com.fr.design.menu.ToolBarDef; -import com.fr.design.roleAuthority.RolesAlreadyEditedPane; -import com.fr.design.utils.gui.GUICoreUtils; -import com.fr.file.FILE; -import com.fr.file.FileNodeFILE; -import com.fr.file.filetree.FileNode; +import com.fr.env.EnvListPane; +import com.fr.env.RemoteEnv; +import com.fr.env.SignIn; import com.fr.general.ComparatorUtils; +import com.fr.general.GeneralContext; import com.fr.general.Inter; -import com.fr.stable.CoreConstants; -import com.fr.stable.StableUtils; -import com.fr.stable.project.ProjectConstants; +import com.fr.stable.EnvChangedListener; +import com.fr.stable.ProductConstants; +import com.fr.stable.StringUtils; import javax.swing.*; -import javax.swing.event.DocumentEvent; -import javax.swing.event.DocumentListener; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; -import java.awt.event.KeyAdapter; -import java.awt.event.KeyEvent; -import java.io.File; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Map; -import java.util.Set; +import java.awt.event.MouseEvent; +import java.awt.event.MouseListener; -public class DesignerFrameFileDealerPane extends JPanel implements FileToolbarStateChangeListener, ResponseDataSourceChange { - private static final String FILE = "file"; - private static DesignerFrameFileDealerPane THIS; +//TODO: august TemplatePane和TemplateTreePane最好合并成一个类 +public class TemplatePane extends JPanel implements MouseListener { + private static final long NUM = 1L; + private static int NUM200 = 200; - private CardLayout card; - private JPanel cardPane; - private java.util.List otherToobarStateChangeListeners= new ArrayList<>(); - - public FileOperations getSelectedOperation() { - return selectedOperation; + public static TemplatePane getInstance() { + return HOLDER.singleton; } - private FileOperations selectedOperation; - private UIToolbar toolBar; - - private OpenReportAction openReportAction = new OpenReportAction(); - private RefreshTreeAction refreshTreeAction = new RefreshTreeAction(); - private OpenFolderAction openFolderAction = new OpenFolderAction(); - private RenameAction renameAction = new RenameAction(); - private DelFileAction delFileAction = new DelFileAction(); - - - /** - * 刷新 - */ - public void refresh() { - selectedOperation.refresh(); - } - - public static final DesignerFrameFileDealerPane getInstance() { - if (THIS == null) { - THIS = new DesignerFrameFileDealerPane(); - } - return THIS; + private static class HOLDER { + private static TemplatePane singleton = new TemplatePane(); } - private DesignerFrameFileDealerPane() { - setLayout(new BorderLayout()); - toolBar = ToolBarDef.createJToolBar(); - toolBar.setBorder(BorderFactory.createMatteBorder(0, 0, 1, 0, UIConstants.TOOLBAR_BORDER_COLOR)); - toolBar.setBorderPainted(true); - JPanel tooBarPane = FRGUIPaneFactory.createBorderLayout_S_Pane(); - JPanel parent = new JPanel(new BorderLayout()); - parent.add(toolBar, BorderLayout.CENTER); - parent.setBorder(BorderFactory.createEmptyBorder(3, 0, 4, 0)); - tooBarPane.add(parent, BorderLayout.CENTER); - tooBarPane.add(new UIMenuHighLight(), BorderLayout.SOUTH); - - add(tooBarPane, BorderLayout.NORTH); - cardPane = new JPanel(card = new CardLayout()); - cardPane.add(TemplateTreePane.getInstance(), FILE); - - selectedOperation = TemplateTreePane.getInstance(); - card.show(cardPane, FILE); - - TemplateTreePane.getInstance().setToobarStateChangeListener(this); - - add(cardPane, BorderLayout.CENTER); - stateChange(); + private static final long serialVersionUID = 2108412478281713143L; + public static final int HEIGHT = 23;// 最好和日志的高度统一 用同一个变量 + private static javax.swing.Icon leftIcon = BaseUtils.readIcon("/com/fr/design/images/docking/left.png"); + ; + private static javax.swing.Icon rightIcon = BaseUtils.readIcon("/com/fr/design/images/docking/right.png"); + ; + private boolean isExpanded = false; + private UIButton editButton; + private UILabel envLabel; + + private TemplatePane() { + super(); + this.initComponents(); + this.setFocusable(true); + this.addMouseListener(this); + isExpanded = DesignerEnvManager.getEnvManager().isTemplateTreePaneExpanded(); + // TemplateTreePane.getInstance().setVisible(isExpanded); + TemplateTreePane.getInstance().setVisible(true); } - - public final void setCurrentEditingTemplate(JTemplate jt) { - DesignModelAdapter.setCurrentModelAdapter(jt == null ? null : jt.getModel()); - fireDSChanged(); - TableDataTreePane.getInstance(DesignModelAdapter.getCurrentModelAdapter()); - HistoryTemplateListPane.getInstance().setCurrentEditingTemplate(jt); - //处理自动新建的模板 - MutilTempalteTabPane.getInstance().doWithtemTemplate(); - if (DesignerMode.isAuthorityEditing()) { - RolesAlreadyEditedPane.getInstance().refreshDockingView(); - } - - jt.setComposite(); - jt.refreshToolArea(); - jt.fireJTemplateOpened(); - jt.requestFocus(); - jt.revert(); - - FRContext.getLogger().info("\"" + jt.getEditingFILE().getName() + "\"" + Inter.getLocText("LOG-Has_Been_Openned") + "!"); + private void initComponents() { + GeneralContext.addEnvChangedListener(new EnvChangedListener() { + public void envChanged() { + setJLabel(DesignerEnvManager.getEnvManager().getCurEnvName()); + } + }); + this.setLayout(new BorderLayout(25, 0)); + editButton = new UIButton(BaseUtils.readIcon("/com/fr/design/images/control/control-center2.png")) { + private static final long serialVersionUID = NUM; + + @Override + public Point getToolTipLocation(MouseEvent event) { + return new Point(25, 2); + } + }; + editButton.setOpaque(false); + editButton.setBorder(BorderFactory.createEmptyBorder(2, 0, 0, 10)); + editButton.setMargin(null); + editButton.setCursor(new Cursor(Cursor.HAND_CURSOR)); + editButton.setToolTipText(Inter.getLocText("Env-Configure_Workspace")); + this.add(new UILabel(" "), BorderLayout.WEST); + this.add(editButton, BorderLayout.EAST); + editButton.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent evt) { + editItems(); + } + }); + envLabel = new UILabel(); + envLabel.setForeground(new Color(102, 102, 102)); + setJLabel(DesignerEnvManager.getEnvManager().getCurEnvName()); + this.add(envLabel, BorderLayout.CENTER); } /** - * 刷新菜单 + * 是否可扩展 + * @return 同上 */ - public void refreshDockingView() { - ToolBarDef toolbarDef = new ToolBarDef(); - toolbarDef.addShortCut(openReportAction, refreshTreeAction); - if (FRContext.getCurrentEnv().isSupportLocalFileOperate()) { - toolbarDef.addShortCut(openFolderAction, renameAction); - } - toolbarDef.addShortCut(delFileAction); - Set extraShortCuts = ExtraDesignClassManager.getInstance().getExtraShortCuts(); - for (ShortCut shortCut : extraShortCuts) { - toolbarDef.addShortCut(shortCut); - } - - toolbarDef.updateToolBar(toolBar); - refreshActions(); + public boolean IsExpanded() { + return this.isExpanded; } - - private void refreshActions() { - openReportAction.setEnabled(false); - refreshTreeAction.setEnabled(true); - openFolderAction.setEnabled(false); - renameAction.setEnabled(false); - delFileAction.setEnabled(false); + public void setExpand(boolean b) { + this.isExpanded = b; this.repaint(); } - /** - * 响应数据集改变 - */ - public void fireDSChanged() { - fireDSChanged(new HashMap()); - } - - /** - * 响应数据集改变 - * - * @param map 改变名字的数据集 - */ - public void fireDSChanged(Map map) { - DesignTableDataManager.fireDSChanged(map); - } - - - /* - * Open Report Action - */ - private class OpenReportAction extends UpdateAction { - - public OpenReportAction() { - this.setName(KeySetUtils.OPEN_TEMPLATE.getMenuKeySetName()); - this.setSmallIcon(BaseUtils.readIcon("/com/fr/design/images/buttonicon/open.png")); - } - - @Override - public void actionPerformed(ActionEvent evt) { - selectedOperation.openSelectedReport(); - } - - } - - private class OpenFolderAction extends UpdateAction { - - public OpenFolderAction() { - this.setName(Inter.getLocText("FR-Designer_Show_in_Containing_Folder")); - this.setSmallIcon(BaseUtils.readIcon("/com/fr/design/images/m_file/view_folder.png")); + private boolean envListOkAction(EnvListPane envListPane) { + String selectedName = envListPane.updateEnvManager(); + DesignerEnvManager envManager = DesignerEnvManager.getEnvManager(); + EnvConfig selectedEnv = envManager.getEnv(selectedName); + GeneralContext.fireEnvWillChangeListener(); + try { + //如果是远程的还要先测试下,如果失败就不切换 + if (selectedEnv instanceof RemoteEnv) { + if (!((RemoteEnv) selectedEnv).testServerConnection()) { + JOptionPane.showMessageDialog(DesignerContext.getDesignerFrame(), Inter.getLocText(new String[]{"M-SwitchWorkspace", "Failed"})); + return false; + } else { +// String remoteVersion = selectedEnv.getDesignerVersion(); +// if (StringUtils.isBlank(remoteVersion) || ComparatorUtils.compare(remoteVersion, ProductConstants.DESIGNER_VERSION) < 0) { +// String infor = Inter.getLocText("Server-version-tip"); +// String moreInfo = Inter.getLocText("Server-version-tip-moreInfo"); +// new InformationWarnPane(infor, moreInfo, Inter.getLocText("Tooltips")).show(); +// return false; +// } + } + } + SignIn.signIn(selectedEnv); + JTemplate template = HistoryTemplateListPane.getInstance().getCurrentEditingTemplate(); + if (template != null) { + template.refreshToolArea(); + } + setJLabel(selectedName); + } catch (Exception e) { + JOptionPane.showMessageDialog(DesignerContext.getDesignerFrame(), Inter.getLocText(new String[]{"M-SwitchWorkspace", "Failed"})); + return false; } - - @Override - public void actionPerformed(ActionEvent evt) { - selectedOperation.openContainerFolder(); + TemplateTreePane.getInstance().refreshDockingView(); + DesignModelAdapter model = DesignModelAdapter.getCurrentModelAdapter(); + if (model != null) { + model.envChanged(); } + return true; } - /* - * 刷新ReportletsTree + /** + * 编辑items */ - private class RefreshTreeAction extends UpdateAction { + public void editItems() { + final EnvListPane envListPane = new EnvListPane(); + final BasicDialog envListDialog = envListPane.showWindow(SwingUtilities.getWindowAncestor(DesignerContext.getDesignerFrame())); + + envListPane.populateEnvManager(envLabel.getText()); + envListDialog.addDialogActionListener(new DialogActionAdapter() { + public void doOk() { + envListOkAction(envListPane); + } - public RefreshTreeAction() { - this.setName(Inter.getLocText("FR-Designer_Refresh")); - this.setSmallIcon(UIConstants.REFRESH_ICON); - } + public void doCancel() { + envListDialog.setVisible(false); + } + }); + envListDialog.setVisible(true); + } - @Override - public void actionPerformed(ActionEvent evt) { - selectedOperation.refresh(); - stateChange(); + private void setJLabel(String name) { + if (DesignerEnvManager.getEnvManager().getEnv(name) instanceof LocalEnv) { + envLabel.setIcon(BaseUtils.readIcon("com/fr/design/images/data/bind/localconnect.png")); + } else if (DesignerEnvManager.getEnvManager().getEnv(name) instanceof RemoteEnv) { + envLabel.setIcon(BaseUtils.readIcon("com/fr/design/images/data/bind/distanceconnect.png")); } + envLabel.setText(name); + envLabel.repaint(); } - public void addToobarStateChangeListener(FileToolbarStateChangeListener toobarStateChangeListener) { - this.otherToobarStateChangeListeners.add(toobarStateChangeListener); - } - - public void removeToobarStateChangeListener(FileToolbarStateChangeListener toobarStateChangeListener) { - this.otherToobarStateChangeListeners.remove(toobarStateChangeListener); + @Override + public Dimension getPreferredSize() { + return new Dimension(250, HEIGHT); } - private void otherStateChange() { - for (FileToolbarStateChangeListener toobarStateChangeListener : otherToobarStateChangeListeners) { - toobarStateChangeListener.stateChange(); - } + @Override + public void paintComponent(Graphics g) { + super.paintComponent(g); + paintBackgroundIcon(g); } - /* - * 重命名文件 - */ - private class RenameAction extends UpdateAction { - - public RenameAction() { - this.setName(Inter.getLocText("FR-Designer_Rename")); - this.setSmallIcon(BaseUtils.readIcon("/com/fr/design/images/data/source/rename.png")); - } - - @Override - public void actionPerformed(ActionEvent evt) { - new RenameDialog(); - MutilTempalteTabPane.getInstance().repaint(); - } + private void paintBackgroundIcon(Graphics g) { + int w = this.getWidth(); + int h = this.getHeight(); + Graphics2D g2d = (Graphics2D) g; + Color lightColor = new Color(226, 230, 234); + Color darkColor = new Color(183, 188, 195); + GradientPaint gp = new GradientPaint(1, 1, lightColor, 1, h - 1, darkColor); + g2d.setPaint(gp); + g2d.fillRect(1, 1, w - 2, h - 1); + g2d.setColor(lightColor); + g2d.drawLine(0, 2, 0, h - 1); + g2d.setColor(darkColor); + g2d.drawLine(w - 1, 2, w - 1, h - 1); + Icon icon = !isExpanded ? leftIcon : rightIcon; + icon.paintIcon(this, g2d, 4, 4); } - /* - * 删除指定文件 + /** + * 鼠标点击 + * @param e 事件 */ - private class DelFileAction extends UpdateAction { - - public DelFileAction() { - this.setName(Inter.getLocText("FR-Designer_Remove")); - this.setSmallIcon(BaseUtils.readIcon("/com/fr/design/images/data/source/delete.png")); - } - - @Override - public void actionPerformed(ActionEvent evt) { - selectedOperation.deleteFile(); - } + @Override + public void mouseClicked(MouseEvent e) { } - /* - * 加锁 + /** + * 鼠标按下 + * @param e 事件 */ - private class GetLockAction extends UpdateAction { - - public GetLockAction() { - this.setName(Inter.getLocText("FR-Designer_Get_Lock")); - this.setSmallIcon(BaseUtils.readIcon("/com/fr/design/images/control/lock.png")); - } - - @Override - public void actionPerformed(ActionEvent evt) { - selectedOperation.lockFile(); + @Override + public void mousePressed(MouseEvent e) { + if (e.getX() < NUM200) { + isExpanded = !isExpanded; + TemplateTreePane.getInstance().setVisible(isExpanded); + this.setExpand(isExpanded); + DesignerEnvManager.getEnvManager().setTemplateTreePaneExpanded(isExpanded); } } - /* - * 解锁 + /** + * 鼠标放开 + * @param e 事件 */ - private class ReleaseLockAction extends UpdateAction { - - public ReleaseLockAction() { - this.setName(Inter.getLocText("FR-Designer_Release_Lock")); - this.setSmallIcon(BaseUtils.readIcon("/com/fr/design/images/control/unlock.png")); - } - - @Override - public void actionPerformed(ActionEvent evt) { - selectedOperation.unLockFile(); - } + @Override + public void mouseReleased(MouseEvent e) { } /** - * 按钮状态改变 + * 鼠标进入 + * @param e 事件 */ @Override - public void stateChange() { - //当前环境为远程环境时 - if (FRContext.getCurrentEnv() != null) { - if (!FRContext.getCurrentEnv().isSupportLocalFileOperate()) { - if (selectedOperation.getSelectedTemplatePath() != null) { - openReportAction.setEnabled(true); - } else { - openReportAction.setEnabled(false); - } - FileNode node = TemplateTreePane.getInstance().getTemplateFileTree().getSelectedFileNode(); - if (selectedOperation.getSelectedTemplatePath() != null) { - if (node.getLock() != null && !ComparatorUtils.equals(node.getUserID(), node.getLock())) { - delFileAction.setEnabled(false); - } else { - delFileAction.setEnabled(true); - } - } else { - delFileAction.setEnabled(false); - } - } else { - //当前环境为本地环境时 - if (selectedOperation.getSelectedTemplatePath() != null) { - openReportAction.setEnabled(true); - renameAction.setEnabled(true); - delFileAction.setEnabled(true); - } else { - openReportAction.setEnabled(false); - renameAction.setEnabled(false); - delFileAction.setEnabled(false); - } - openFolderAction.setEnabled(containsFolderNums() + seletedTemplateNums() != 0); - } - refreshTreeAction.setEnabled(true); - } - if (containsFolderNums() > 0 && (containsFolderNums() + seletedTemplateNums() > 1)) { - refreshActions(); - } else if (containsFolderNums() == 0 && seletedTemplateNums() > 1) { - openReportAction.setEnabled(false); - refreshTreeAction.setEnabled(true); - openFolderAction.setEnabled(false); - renameAction.setEnabled(false); - delFileAction.setEnabled(true); - } - - otherStateChange(); + public void mouseEntered(MouseEvent e) { } /** - * 是否包含文件夹 - * - * @return + * 鼠标离开 + * @param e 事件 */ - - private int containsFolderNums() { - TemplateFileTree fileTree = TemplateTreePane.getInstance().getTemplateFileTree(); - if (fileTree.getSelectionPaths() == null) { - return 0; - } - - //选择的包含文件和文件夹的数目 - if (fileTree.getSelectionPaths().length == 0) { - return 0; - } - //所有的num减去模板的num,得到文件夹的num - return fileTree.getSelectionPaths().length - fileTree.getSelectedTemplatePaths().length; + @Override + public void mouseExited(MouseEvent e) { } /** - * 是否选择了多个模板 - * - * @return + * 处理异常 */ - private int seletedTemplateNums() { - TemplateFileTree fileTree = TemplateTreePane.getInstance().getTemplateFileTree(); - if (fileTree.getSelectionPaths() == null) { - return 0; - } - - return fileTree.getSelectedTemplatePaths().length; - } - - - // js: 重命名对话框,模仿Eclipse的重命名,支持快捷键F2,Enter,ESC - private class RenameDialog { - - private UITextField jt; - private String userInput; - private String oldName; - private UILabel hintsLabel; - private UIButton confirmButton; - private JDialog jd; - private String suffix; - - public RenameDialog() { - final String reportPath = selectedOperation.getSelectedTemplatePath(); - if (reportPath == null) { - return; - } - - final FileNodeFILE nodeFile = new FileNodeFILE(new FileNode(StableUtils.pathJoin(new String[]{ProjectConstants.REPORTLETS_NAME, reportPath}), false)); - final String path = StableUtils.pathJoin(new String[]{nodeFile.getEnvPath(), nodeFile.getPath()}); - oldName = nodeFile.getName(); - suffix = oldName.substring(oldName.lastIndexOf(CoreConstants.DOT), oldName.length()); - oldName = oldName.replaceAll(suffix, ""); - - jd = new JDialog(); - jd.setLayout(new GridLayout(2, 2)); - jd.setModal(true); - UILabel newNameLabel = new UILabel(Inter.getLocText("FR-Designer_Enter-New-FileName")); - newNameLabel.setMinimumSize(new Dimension(150, 27)); - newNameLabel.setHorizontalAlignment(SwingConstants.RIGHT); - jt = new UITextField(oldName); - jt.getDocument().addDocumentListener(getdoDocumentListener()); - jt.selectAll(); - jt.setPreferredSize(new Dimension(150, 20)); - - JPanel newNamePanel = new JPanel(); - newNamePanel.setLayout(new BoxLayout(newNamePanel, BoxLayout.X_AXIS)); - newNamePanel.add(Box.createHorizontalGlue()); - newNamePanel.add(newNameLabel); - newNamePanel.add(Box.createHorizontalStrut(5)); - jd.add(newNamePanel); - - JPanel jtPanel = new JPanel(); - jtPanel.setLayout(new BoxLayout(jtPanel, BoxLayout.Y_AXIS)); - JPanel containJt = new JPanel(new BorderLayout()); - containJt.add(jt, BorderLayout.WEST); - containJt.setMaximumSize(new Dimension(200, 20)); - jtPanel.add(Box.createVerticalGlue()); - jtPanel.add(containJt); - jtPanel.add(Box.createVerticalGlue()); - jd.add(jtPanel); - - addUITextFieldListener(nodeFile, path); - - hintsLabel = new UILabel(); - hintsLabel.setBounds(20, 50, 250, 30); - hintsLabel.setMaximumSize(new Dimension(200, 30)); - hintsLabel.setHorizontalAlignment(SwingConstants.RIGHT); - hintsLabel.setForeground(Color.RED); - hintsLabel.setVisible(false); - - confirmButton = new UIButton(Inter.getLocText("FR-Designer_Confirm")); - confirmButton.setPreferredSize(new Dimension(80, 25)); - confirmButton.setMinimumSize(new Dimension(80, 25)); - confirmButton.setMaximumSize(new Dimension(80, 25)); - confirmButton.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent e) { - confirmClose(nodeFile, path); + public void dealEvnExceptionWhenStartDesigner() { + final EnvListPane envListPane = new EnvListPane(); + envListPane.populateEnvManager(envLabel.getText()); + BasicDialog envListDialog = envListPane.showWindow(SwingUtilities.getWindowAncestor(DesignerContext.getDesignerFrame())); + envListDialog.addDialogActionListener(new DialogActionAdapter() { + public void doOk() { + if (!envListOkAction(envListPane)) { + System.exit(0); } - }); - - UIButton cancelButton = new UIButton(Inter.getLocText("FR-Designer_Cancel")); - cancelButton.setPreferredSize(new Dimension(80, 25)); - cancelButton.setMinimumSize(new Dimension(80, 25)); - cancelButton.setMaximumSize(new Dimension(80, 25)); - - cancelButton.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent e) { - jd.dispose(); - } - }); - - JPanel hintsPanel = new JPanel(); - hintsPanel.setLayout(new BorderLayout()); - hintsPanel.add(hintsLabel, BorderLayout.EAST); - jd.add(hintsLabel); - - JPanel btPanel = new JPanel(new BorderLayout()); - btPanel.setLayout(new BoxLayout(btPanel, BoxLayout.X_AXIS)); - btPanel.add(Box.createHorizontalGlue()); - btPanel.add(confirmButton); - btPanel.add(Box.createHorizontalStrut(5)); - btPanel.add(cancelButton); - btPanel.add(Box.createHorizontalStrut(20)); - jd.add(btPanel); - - jd.setSize(380, 200); - jd.setTitle(Inter.getLocText("FR-Designer_Rename")); - jd.setResizable(false); - jd.setAlwaysOnTop(true); - jd.setIconImage(BaseUtils.readImage("/com/fr/base/images/oem/logo.png")); - jd.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); - GUICoreUtils.centerWindow(jd); - jd.setVisible(true); - } - - public void confirmClose(FileNodeFILE nodeFile, String path) { - userInput = userInput == null ? oldName : userInput; - String oldPath = path.replaceAll("/", "\\\\"); - String newPath = path.replace(nodeFile.getName(), userInput + suffix); - renameTemplateInMemory(nodeFile, userInput + suffix, oldName + suffix); - DesignerEnvManager.getEnvManager().replaceRecentOpenedFilePath(oldPath, newPath.replaceAll("/", "\\\\")); - File newFile = new File(newPath); - new File(path).renameTo(newFile); - selectedOperation.refresh(); - DesignerContext.getDesignerFrame().setTitle(); - jd.dispose(); - } - private void renameTemplateInMemory(FILE tplFile, String newName, String oldName) { - JTemplate dPane = getSpecialTemplateByFILE(tplFile); - if (dPane == null) { - return; } - FILE renameFile = dPane.getEditingFILE(); - renameFile.setPath(renameFile.getPath().replace(oldName, newName)); - } - - // 增加enter以及esc快捷键的支持 - public void addUITextFieldListener(final FileNodeFILE nodeFile, final String path) { - - jt.addKeyListener(new KeyAdapter() { - public void keyPressed(KeyEvent e) { - if (e.getKeyCode() == KeyEvent.VK_ESCAPE) { - jd.dispose(); - } - } - }); - - jt.addKeyListener(new KeyAdapter() { - public void keyPressed(KeyEvent e) { - if (e.getKeyCode() == KeyEvent.VK_ENTER) { - if (confirmButton.isEnabled()) { - confirmClose(nodeFile, path); - } - } - } - }); - - } - // UITextField的输入监听 - public DocumentListener getdoDocumentListener() { - DocumentListener dl = new DocumentListener() { - - public void changedUpdate(DocumentEvent e) { - isNameAlreadyExist(); - } - - public void insertUpdate(DocumentEvent e) { - isNameAlreadyExist(); - } - - public void removeUpdate(DocumentEvent e) { - isNameAlreadyExist(); - } - }; - - return dl; - } - - private void isNameAlreadyExist() { - userInput = jt.getText().trim(); - if (selectedOperation.isNameAlreadyExist(userInput, oldName, suffix)) { - jt.selectAll(); - // 如果文件名已存在,则灰掉确认按钮 - hintsLabel.setText(Inter.getLocText(new String[]{"Utils-File_name", "Already_exists"}, new String[]{userInput})); - hintsLabel.setVisible(true); - confirmButton.setEnabled(false); - } else { - hintsLabel.setVisible(false); - confirmButton.setEnabled(true); + public void doCancel() { + System.exit(0); } - } - } - - /** - * @param tplFile - * @return 内存中的template重命名一下 - */ - private JTemplate getSpecialTemplateByFILE(FILE tplFile) { - HistoryTemplateListPane historyHandle = HistoryTemplateListPane.getInstance(); - if (ComparatorUtils.equals(historyHandle.getCurrentEditingTemplate().getEditingFILE(), tplFile)) { - return historyHandle.getCurrentEditingTemplate(); - } - for (int i = 0; i < historyHandle.getHistoryCount(); i++) { - if (ComparatorUtils.equals(historyHandle.get(i).getEditingFILE(), tplFile)) { - return historyHandle.get(i); - } - } - return null; + }); + envListDialog.setVisible(true); } -} +} \ No newline at end of file diff --git a/designer-base/src/com/fr/design/mainframe/loghandler/DesignerLogHandler.java b/designer-base/src/com/fr/design/mainframe/loghandler/DesignerLogHandler.java index b718760ed..9a5effae4 100644 --- a/designer-base/src/com/fr/design/mainframe/loghandler/DesignerLogHandler.java +++ b/designer-base/src/com/fr/design/mainframe/loghandler/DesignerLogHandler.java @@ -1,7 +1,7 @@ package com.fr.design.mainframe.loghandler; import com.fr.base.BaseUtils; -import com.fr.base.ConfigManager; +import com.fr.base.ServerConfig; import com.fr.base.FRContext; import com.fr.design.gui.icontainer.UIScrollPane; import com.fr.design.gui.imenu.UIMenuItem; @@ -16,23 +16,13 @@ import com.fr.log.LogHandler; import com.fr.stable.EnvChangedListener; import com.fr.stable.xml.LogRecordTimeProvider; -import javax.swing.AbstractAction; -import javax.swing.ActionMap; -import javax.swing.InputMap; -import javax.swing.JCheckBoxMenuItem; -import javax.swing.JComponent; -import javax.swing.JPanel; -import javax.swing.JPopupMenu; -import javax.swing.JTextPane; -import javax.swing.KeyStroke; +import javax.swing.*; import javax.swing.text.BadLocationException; import javax.swing.text.DefaultEditorKit; import javax.swing.text.Document; import javax.swing.text.SimpleAttributeSet; import javax.swing.text.StyleConstants; -import java.awt.BorderLayout; -import java.awt.Color; -import java.awt.Dimension; +import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ItemEvent; @@ -130,7 +120,7 @@ public class DesignerLogHandler { @Override public void actionPerformed(ActionEvent e) { JPopupMenu showsetPopup = new JPopupMenu(); - int logLevelvalue = ConfigManager.getProviderInstance().getServerLogLevel().intValue(); + int logLevelvalue = ServerConfig.getInstance().getServerLogLevel().intValue(); if (logLevelvalue <= INFO_INT) { showsetPopup.add(showInfo); showsetPopup.add(showError); @@ -356,4 +346,4 @@ public class DesignerLogHandler { }; } -} +} \ No newline at end of file diff --git a/designer-base/src/com/fr/design/utils/DesignUtils.java b/designer-base/src/com/fr/design/utils/DesignUtils.java index 4ee3ff9c0..469e7fd1a 100644 --- a/designer-base/src/com/fr/design/utils/DesignUtils.java +++ b/designer-base/src/com/fr/design/utils/DesignUtils.java @@ -1,6 +1,12 @@ package com.fr.design.utils; -import com.fr.base.*; +import com.fr.base.BaseUtils; +import com.fr.base.ServerConfig; +import com.fr.base.Env; +import com.fr.base.EnvException; +import com.fr.base.FRContext; +import com.fr.base.FeedBackInfo; +import com.fr.base.Utils; import com.fr.base.remote.RemoteDeziConstants; import com.fr.dav.DavXMLUtils; import com.fr.dav.LocalEnv; @@ -9,18 +15,39 @@ import com.fr.design.ExtraDesignClassManager; import com.fr.design.fun.DesignerEnvProcessor; import com.fr.design.gui.UILookAndFeel; import com.fr.design.mainframe.DesignerContext; -import com.fr.design.mainframe.DesignerFrame; import com.fr.env.RemoteEnv; import com.fr.file.FileFILE; -import com.fr.general.*; +import com.fr.general.ComparatorUtils; +import com.fr.general.FRFont; +import com.fr.general.FRLogger; +import com.fr.general.GeneralContext; +import com.fr.general.Inter; import com.fr.general.http.HttpClient; -import com.fr.stable.*; +import com.fr.stable.ArrayUtils; +import com.fr.stable.CodeUtils; +import com.fr.stable.EncodeConstants; +import com.fr.stable.StableUtils; +import com.fr.stable.StringUtils; import com.fr.start.StartServer; import javax.swing.*; import java.awt.*; -import java.io.*; -import java.net.*; +import java.io.BufferedReader; +import java.io.BufferedWriter; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.OutputStreamWriter; +import java.io.PrintWriter; +import java.io.UnsupportedEncodingException; +import java.net.HttpURLConnection; +import java.net.ServerSocket; +import java.net.Socket; +import java.net.URI; +import java.net.URLEncoder; import java.util.Calendar; import java.util.Enumeration; import java.util.Locale; @@ -182,18 +209,18 @@ public class DesignUtils { // 更新CurrentEnv于FRContext & DesignerEnvManager FRContext.setCurrentEnv(env); - DesignerFrame.refreshNorthEastPane(); + refreshDesignerFrame(env); // 当换了运行环境,重置服务器,让它下次预览时重启 if (env instanceof LocalEnv && !ComparatorUtils.equals(env.getPath(), oldEnvPath)) { StartServer.currentEnvChanged(); } } - + public static void refreshDesignerFrame(Env env) { - + final Env run_env = env; - + // 刷新DesignerFrame里面的面板 SwingUtilities.invokeLater(new Runnable() { @@ -206,7 +233,7 @@ public class DesignUtils { } }); } - + /** * p:初始化look and feel, 把一切放到这个里面.可以让多个地方调用. */ @@ -229,15 +256,15 @@ public class DesignUtils { } } } - + private static boolean isTextField(String key){ - return key.startsWith("TextField.") || key.startsWith("PasswordField."); + return key.startsWith("TextField.") || key.startsWith("PasswordField."); } - + private static FRFont getCurrentLocaleFont(){ FRFont guiFRFont; Locale defaultLocale = Locale.getDefault(); - + if (isDisplaySimSun(defaultLocale)) { guiFRFont = getNamedFont("SimSun"); } else if(isDisplayDialog(defaultLocale)) { @@ -245,50 +272,57 @@ public class DesignUtils { } else { guiFRFont = getNamedFont("Tahoma"); } - + //先初始化的设计器locale, 后初始化lookandfeel.如果顺序改了, 这边也要调整. Locale designerLocale = FRContext.getLocale(); String file = Inter.getLocText("FR-Designer_File"); char displayChar = file.charAt(0); if (!guiFRFont.canDisplay(displayChar)) { - //如果不能用默认的语言显示字体, 比如想在英文系统里用中文设计器 - //默认语言(中文:宋体, 英文:Tahoma, 其他:Dialog) - guiFRFont = getNamedFont("SimSun"); - if (!guiFRFont.canDisplay(displayChar)) { + //如果不能用默认的语言显示字体, 比如想在英文系统里用中文设计器 + //默认语言(中文:宋体, 英文:Tahoma, 其他:Dialog) + guiFRFont = getNamedFont("SimSun"); + if (!guiFRFont.canDisplay(displayChar)) { //比如想在中文或英文系统里用韩文设计器 guiFRFont = getNamedFont("Dialog"); if(!guiFRFont.canDisplay(displayChar)) { FRContext.getLogger().error(Inter.getLocText("FR-Base_SimSun_Not_Found")); } - } - } - + } + } + return guiFRFont; } - + private static FRFont getNamedFont(String name){ - return FRFont.getInstance(name, Font.PLAIN, 12); + return FRFont.getInstance(name, Font.PLAIN, 12); } - + private static boolean isDisplaySimSun(Locale defaultLocale){ - return ComparatorUtils.equals(defaultLocale, Locale.SIMPLIFIED_CHINESE); + return ComparatorUtils.equals(defaultLocale, Locale.SIMPLIFIED_CHINESE); } - + private static boolean isDisplayDialog(Locale defaultLocale){ - return ComparatorUtils.equals(defaultLocale, Locale.TRADITIONAL_CHINESE) - || ComparatorUtils.equals(defaultLocale, Locale.JAPANESE) - || ComparatorUtils.equals(defaultLocale, Locale.JAPAN) + return ComparatorUtils.equals(defaultLocale, Locale.TRADITIONAL_CHINESE) + || ComparatorUtils.equals(defaultLocale, Locale.JAPANESE) + || ComparatorUtils.equals(defaultLocale, Locale.JAPAN) || ComparatorUtils.equals(defaultLocale, Locale.KOREAN) || ComparatorUtils.equals(defaultLocale, Locale.KOREA); } + /** + * 访问服务器环境-空参数 + */ + public static void visitEnvServer() { + visitEnvServerByParameters(StringUtils.EMPTY, new String[] {}, new String[] {}); + } + /** * 访问服务器环境 * * @param names 参数名字 * @param values 参数值 */ - public static void visitEnvServerByParameters(String[] names, String[] values) { + public static void visitEnvServerByParameters(String baseRoute, String[] names, String[] values) { int len = Math.min(ArrayUtils.getLength(names), ArrayUtils.getLength(values)); String[] segs = new String[len]; for (int i = 0; i < len; i++) { @@ -319,7 +353,8 @@ public class DesignUtils { } else { try { String web = GeneralContext.getCurrentAppNameOfEnv(); - String url = "http://localhost:" + DesignerEnvManager.getEnvManager().getJettyServerPort() + "/" + web + "/" + ConfigManager.getProviderInstance().getServletMapping() + String url = "http://localhost:" + DesignerEnvManager.getEnvManager().getJettyServerPort() + + "/" + web + "/" + ServerConfig.getInstance().getServletName() + baseRoute + postfixOfUri; StartServer.browserURLWithLocalEnv(url); } catch (Throwable e) { @@ -439,10 +474,10 @@ public class DesignUtils { private static InputStream postBytes2ServerB(byte[] bytes) throws Exception { - HttpClient client = new HttpClient("http://114.215.175.35:8080/WebReport/product_advice.jsp"); + HttpClient client = new HttpClient("http://114.215.175.35:8080/WebReport/product_advice.jsp"); client.asGet(); - client.setContent(bytes); - return execute4InputStream(client); + client.setContent(bytes); + return execute4InputStream(client); } @@ -452,7 +487,7 @@ public class DesignUtils { private static ByteArrayInputStream execute4InputStream(HttpClient client) throws Exception { int statusCode = client.getResponseCode(); if(statusCode != HttpURLConnection.HTTP_OK){ - throw new EnvException("Method failed: " + statusCode); + throw new EnvException("Method failed: " + statusCode); } InputStream in = client.getResponseStream(); if (in == null) { @@ -484,4 +519,4 @@ public class DesignUtils { } -} +} \ No newline at end of file diff --git a/designer-base/src/com/fr/env/EnvListPane.java b/designer-base/src/com/fr/env/EnvListPane.java index d1d794f8d..951f6cdda 100644 --- a/designer-base/src/com/fr/env/EnvListPane.java +++ b/designer-base/src/com/fr/env/EnvListPane.java @@ -1,73 +1,34 @@ package com.fr.env; -import java.awt.BorderLayout; -import java.awt.Color; -import java.awt.Component; -import java.awt.Dimension; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.KeyEvent; -import java.awt.event.MouseAdapter; -import java.awt.event.MouseEvent; -import java.io.File; -import java.util.*; - -import javax.swing.BorderFactory; - -import com.fr.design.gui.ilable.UILabel; - -import javax.swing.JFileChooser; -import javax.swing.JOptionPane; -import javax.swing.JPanel; -import javax.swing.JScrollPane; -import javax.swing.JTextPane; -import javax.swing.JToolBar; -import javax.swing.SwingUtilities; -import javax.swing.ToolTipManager; -import javax.swing.event.DocumentEvent; -import javax.swing.event.DocumentListener; -import javax.swing.event.TreeSelectionEvent; -import javax.swing.event.TreeSelectionListener; -import javax.swing.text.AttributeSet; -import javax.swing.text.BadLocationException; -import javax.swing.text.SimpleAttributeSet; -import javax.swing.text.StyleConstants; - -import com.fr.base.BaseUtils; import com.fr.base.Env; -import com.fr.base.FRContext; -import com.fr.general.NameObject; +import com.fr.core.env.EnvConfig; import com.fr.dav.LocalEnv; import com.fr.design.DesignerEnvManager; -import com.fr.design.beans.BasicBeanPane; -import com.fr.design.dialog.InformationWarnPane; import com.fr.design.gui.controlpane.JListControlPane; import com.fr.design.gui.controlpane.NameObjectCreator; import com.fr.design.gui.controlpane.NameableCreator; -import com.fr.design.gui.ipasswordfield.UIPassWordField; -import com.fr.design.gui.itree.filetree.JFileTree; -import com.fr.design.gui.ibutton.UIButton; -import com.fr.design.gui.icheckbox.UICheckBox; -import com.fr.design.gui.itextarea.UITextArea; -import com.fr.design.gui.itextfield.UITextField; -import com.fr.design.layout.FRGUIPaneFactory; -import com.fr.design.layout.TableLayout; -import com.fr.design.layout.TableLayoutHelper; -import com.fr.design.mainframe.DesignerContext; -import com.fr.design.scrollruler.ModLineBorder; -import com.fr.file.filter.OnlyShowDirectoryFileFilter; import com.fr.general.ComparatorUtils; import com.fr.general.Inter; +import com.fr.general.NameObject; import com.fr.stable.Nameable; -import com.fr.stable.ProductConstants; import com.fr.stable.StringUtils; import com.fr.stable.core.PropertyChangeAdapter; -import com.fr.third.org.hibernate.boot.jaxb.SourceType; +import javax.swing.JOptionPane; +import javax.swing.SwingUtilities; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Iterator; +import java.util.List; + +/** + * @author yaohwu + */ public class EnvListPane extends JListControlPane { public EnvListPane() { super(); addEditingListner(new PropertyChangeAdapter() { + @Override public void propertyChange() { String tempName = getEditingName(); String[] allListNames = nameableList.getAllNames(); @@ -86,7 +47,6 @@ public class EnvListPane extends JListControlPane { nameableList.stopEditing(); JOptionPane.showMessageDialog(SwingUtilities.getWindowAncestor(EnvListPane.this), Inter.getLocText(waning, sign)); setWarnigText(editingIndex); - return; } } }); @@ -97,6 +57,7 @@ public class EnvListPane extends JListControlPane { * * @return 返回添加按钮的NameableCreator */ + @Override public NameableCreator[] createNameableCreators() { NameableCreator local = new NameObjectCreator(Inter.getLocText("Env-Local_Directory"), "com/fr/design/images/data/bind/localconnect.png", LocalEnv.class, LocalEnvPane.class); @@ -118,14 +79,13 @@ public class EnvListPane extends JListControlPane { public void populateEnvManager(String selectedEnv) { DesignerEnvManager mgr = DesignerEnvManager.getEnvManager(); Iterator nameIt = mgr.getEnvNameIterator(); - List nameObjectList = new ArrayList(); - nameIt.hasNext(); + List nameObjectList = new ArrayList<>(); while (nameIt.hasNext()) { String name = nameIt.next(); nameObjectList.add(new NameObject(name, mgr.getEnv(name))); } - this.populate(nameObjectList.toArray(new NameObject[nameObjectList.size()])); + this.populate(nameObjectList.toArray(new NameObject[0])); if (StringUtils.isBlank(selectedEnv)) { selectedEnv = mgr.getCurEnvName(); @@ -143,457 +103,10 @@ public class EnvListPane extends JListControlPane { DesignerEnvManager mgr = DesignerEnvManager.getEnvManager(); mgr.clearAllEnv(); Nameable[] res = this.update(); - NameObject[] envNameObjectArray = new NameObject[res.length]; - java.util.Arrays.asList(res).toArray(envNameObjectArray); - for (int i = 0; i < envNameObjectArray.length; i++) { - NameObject nameObject = envNameObjectArray[i]; - mgr.putEnv(nameObject.getName(), (Env) nameObject.getObject()); + for (Nameable re : res) { + NameObject nameObject = (NameObject) re; + mgr.putEnv(nameObject.getName(), (EnvConfig) nameObject.getObject()); } - return this.getSelectedName(); } - - public static class LocalEnvPane extends BasicBeanPane { - - private UITextField pathTextField; - private JFileTree localEnvTree; - - public LocalEnvPane() { - this.setLayout(FRGUIPaneFactory.createM_BorderLayout()); - - // northPane - JPanel northPane = FRGUIPaneFactory.createBorderLayout_S_Pane(); - this.add(northPane, BorderLayout.NORTH); - - northPane.add(new UILabel(Inter.getLocText("Location") + ":"), BorderLayout.WEST); - northPane.add(pathTextField = new UITextField(), BorderLayout.CENTER); - - // 删除选择文件按钮 添加JFileTree - - // centerPane - JPanel centerPane = FRGUIPaneFactory.createBorderLayout_S_Pane(); - this.add(centerPane, BorderLayout.CENTER); - - // 添加JFileTree - localEnvTree = new JFileTree(); - JScrollPane localEnvPane = new JScrollPane(localEnvTree); - centerPane.add(localEnvPane, BorderLayout.CENTER); - - // 设置根路径File 和 文件过滤类型 - localEnvTree.setFileFilter(new OnlyShowDirectoryFileFilter()); - localEnvTree.setRootFiles(File.listRoots()); - localEnvTree.addTreeSelectionListener(new TreeSelectionListener() { - - @Override - public void valueChanged(TreeSelectionEvent e) { - pathTextField.setText(localEnvTree.getSelectedFile().getPath()); - } - }); - - UITextArea description = new UITextArea(); - centerPane.add(description, BorderLayout.SOUTH); - description.setText(Inter.getLocText("Env-Des1")); - description.setEditable(false); - } - - @Override - protected String title4PopupWindow() { - return Inter.getLocText("Location"); - } - - @Override - public LocalEnv updateBean() { - String path = pathTextField.getText(); - return LocalEnv.createEnv(path); - } - - public String getPath() { - return pathTextField.getText(); - } - - @Override - public void populateBean(LocalEnv ob) { - if (StringUtils.isBlank(ob.getPath())) { - return; - } - pathTextField.setText(ob.getPath()); - - final File tmpFile = new File(ob.getPath()); - localEnvTree.selectFile(tmpFile); - localEnvTree.setEnabled(true); - } - } - - public static class RemoteEnvPane extends BasicBeanPane { - public static final int HTTPS_HOST_INDEX = 8; - public static final int HTTP_HOST_INDEX = 7; - - private UICheckBox httpsCheckBox = new UICheckBox(Inter.getLocText("FR-Designer_Https_Enable")); - private UITextField servletPathField = new UITextField(); - private UITextField hostNameField = new UITextField(); - private UITextField portNameField = new UITextField(); - private UITextField webApplyField = new UITextField(); - private UITextField servletField = new UITextField(); - private UITextField userTextField = new UITextField(); - private UIPassWordField passwordTextField = new UIPassWordField(); - private UITextField certificatePath = new UITextField(); - private UIPassWordField certificatePass = new UIPassWordField(); - private UIButton chooseDirBtn = new UIButton("..."); - private String envPath; - private String hint; - - // 各种参数面板 - private JPanel northPane; - // 提示面板 - private JPanel previewPane; - // 面板的所有组件 - private Component[][] coms; - DocumentListener docListener = new DocumentListener() { - - @Override - public void changedUpdate(DocumentEvent e) { - showServletPathField(httpsCheckBox.isSelected()); - } - - @Override - public void insertUpdate(DocumentEvent e) { - showServletPathField(httpsCheckBox.isSelected()); - } - - @Override - public void removeUpdate(DocumentEvent e) { - showServletPathField(httpsCheckBox.isSelected()); - } - }; - - private void setHttpsState(boolean enable){ - chooseDirBtn.setEnabled(enable); - DesignerEnvManager.getEnvManager().setHttps(enable); - } - - public RemoteEnvPane() { - this.setBorder(BorderFactory.createTitledBorder(new ModLineBorder(ModLineBorder.TOP), Inter.getLocText("Config_Servlet"))); - this.setLayout(FRGUIPaneFactory.createM_BorderLayout()); - // 位置 - JPanel servletPathPane = FRGUIPaneFactory.createRightFlowInnerContainer_S_Pane(); - servletPathPane.add(new UILabel(Inter.getLocText("Server_Path") + ":")); - servletPathField.setEditable(false); - - hostNameField.getDocument().addDocumentListener(docListener); - portNameField.getDocument().addDocumentListener(docListener); - webApplyField.getDocument().addDocumentListener(docListener); - servletField.getDocument().addDocumentListener(docListener); - - // 主机名 - JPanel servletNamePane = FRGUIPaneFactory.createRightFlowInnerContainer_S_Pane(); - servletNamePane.add(new UILabel(Inter.getLocText("Host_Name") + "/IP" + ":")); - // 端口 - JPanel portNamePane = FRGUIPaneFactory.createRightFlowInnerContainer_S_Pane(); - portNamePane.add(new UILabel(Inter.getLocText("Port") + ":")); - // web应用 - JPanel webApplyPane = FRGUIPaneFactory.createRightFlowInnerContainer_S_Pane(); - webApplyPane.add(new UILabel(Inter.getLocText("Web_Apply") + ":")); - // servlet - JPanel servletPane = FRGUIPaneFactory.createRightFlowInnerContainer_S_Pane(); - servletPane.add(new UILabel("Servlet" + ":")); - // 用户名 - JPanel userNamePane = FRGUIPaneFactory.createRightFlowInnerContainer_S_Pane(); - userNamePane.add(new UILabel(Inter.getLocText("Username") + ":")); - // 密码 - JPanel passWordPane = FRGUIPaneFactory.createRightFlowInnerContainer_S_Pane(); - passWordPane.add(new UILabel(Inter.getLocText("Password") + ":")); - // https证书路径 - JPanel certificatePathPane = FRGUIPaneFactory.createRightFlowInnerContainer_S_Pane(); - certificatePathPane.add(new UILabel(Inter.getLocText("FR-Designer_Certificate_Path")+ ":")); - // https秘钥 - JPanel certificatePassPane = FRGUIPaneFactory.createRightFlowInnerContainer_S_Pane(); - certificatePassPane.add(new UILabel(Inter.getLocText("FR-Designer_Certificate_Pass") + ":")); - - //输入密码的时候检测下大写锁定 - passwordTextField.addMouseListener(new MouseAdapter() { - public void mouseEntered(MouseEvent e) { - if (java.awt.Toolkit.getDefaultToolkit().getLockingKeyState(KeyEvent.VK_CAPS_LOCK)) { - hint = Inter.getLocText("CapsLock"); - } else { - hint = null; - } - ToolTipManager.sharedInstance().setInitialDelay(100); - passwordTextField.setToolTipText(hint); - } - }); - - coms = new Component[][]{ - new Component[]{initHttpsCheckBoxPane(),new UILabel()}, - new Component[]{servletPathPane, initServletNameToolBar()}, - new Component[]{servletNamePane, hostNameField}, - new Component[]{portNamePane, portNameField}, - new Component[]{webApplyPane, webApplyField}, - new Component[]{servletPane, servletField}, - new Component[]{userNamePane, userTextField}, - new Component[]{passWordPane, passwordTextField}, - new Component[]{certificatePathPane,initHttpsPane()}, - new Component[]{certificatePassPane,certificatePass} - }; - - setHttpsState(httpsCheckBox.isSelected()); - initNorthPane(true); - initCenterPane(); - this.add(northPane, BorderLayout.NORTH); - this.add(previewPane, BorderLayout.CENTER); - } - - private JToolBar initServletNameToolBar(){ - JToolBar servletNameToolBar = new JToolBar(); - - servletNameToolBar.setFloatable(false); - servletNameToolBar.setLayout(FRGUIPaneFactory.createBorderLayout()); - - servletNameToolBar.add(this.servletPathField); - UIButton testConnctionButton = new UIButton(BaseUtils.readIcon("/com/fr/design/images/m_web/cache.png")); - testConnctionButton.setToolTipText(Inter.getLocText("Datasource-Test_Connection")); - servletNameToolBar.add(testConnctionButton, BorderLayout.EAST); - - testConnctionButton.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent ev) { - if (testConnection()) { - JOptionPane.showMessageDialog(SwingUtilities.getWindowAncestor(RemoteEnvPane.this), Inter.getLocText("Datasource-Connection_successfully")); - } - } - }); - - return servletNameToolBar; - } - - private void initCenterPane(){ - // centerPane - previewPane = FRGUIPaneFactory.createBorderLayout_S_Pane(); - previewPane.setBorder(BorderFactory.createTitledBorder(new ModLineBorder(ModLineBorder.TOP), Inter.getLocText("Note"))); - - JTextPane previewTextArea = new JTextPane(); - - // e:当行的长度大于所分配的宽度时,将换行. -// previewTextArea.setLineWrap(true); - previewTextArea.setEditable(false); - previewTextArea.setText(Inter.getLocText("Env-Des2")); - try { - previewTextArea.getDocument().insertString(previewTextArea.getText().length(), Inter.getLocText("Env_Des"), this.getRedSytleAttribute()); - previewTextArea.getDocument().insertString(previewTextArea.getText().length(), "\n" + Inter.getLocText("FR-Designer_Env_Des_Https"), this.getRedSytleAttribute()); - } catch (BadLocationException e) { - FRContext.getLogger().error(e.getMessage(), e); - } - previewPane.add(new JScrollPane(previewTextArea), BorderLayout.CENTER); - } - - @Override - protected String title4PopupWindow() { - return "Remote"; - } - - private JPanel initHttpsPane(){ - JPanel httpsPane = FRGUIPaneFactory.createRightFlowInnerContainer_S_Pane(); - httpsPane.setLayout(FRGUIPaneFactory.createBorderLayout()); - httpsPane.add(certificatePath,BorderLayout.CENTER); - httpsPane.add(chooseDirBtn, BorderLayout.EAST); - chooseDirBtn.setPreferredSize(new Dimension(25, 25)); - chooseDirBtn.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent evt) { - JFileChooser fileChooser = new JFileChooser(); - fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY); - int saveValue = fileChooser.showOpenDialog(DesignerContext.getDesignerFrame()); - if (saveValue == JFileChooser.APPROVE_OPTION) { - File selectedFile = fileChooser.getSelectedFile(); - certificatePath.setText(selectedFile.getAbsolutePath()); - } - } - }); - return httpsPane; - } - - private JPanel initHttpsCheckBoxPane(){ - JPanel checkBoxPane = FRGUIPaneFactory.createRightFlowInnerContainer_S_Pane(); - checkBoxPane.add(httpsCheckBox); - httpsCheckBox.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - boolean isHttps = httpsCheckBox.isSelected(); - DesignerEnvManager manager = DesignerEnvManager.getEnvManager(); - manager.setHttps(isHttps); - setHttpsState(isHttps); - updateNorthPane(isHttps); - } - }); - return checkBoxPane; - } - - private void setHttpsParas(){ - System.setProperty("javax.net.ssl.trustStore", this.certificatePath.getText()); - System.setProperty("javax.net.ssl.trustStorePassword", new String(this.certificatePass.getPassword())); - DesignerEnvManager manager = DesignerEnvManager.getEnvManager(); - manager.setCertificatePath(this.certificatePath.getText()); - manager.setCertificatePass(new String(this.certificatePass.getPassword())); - manager.setHttps(this.httpsCheckBox.isSelected()); - } - - private boolean testConnection() { - RemoteEnv env = new RemoteEnv(); - String url = servletPathField.getText(); - env.setPath(url); - env.setUser(userTextField.getText()); - env.setPassword(new String(passwordTextField.getPassword())); - boolean connect = false; - try { - if (!StringUtils.isBlank(servletPathField.getText().trim())) { - if(url.startsWith("https:") && !this.httpsCheckBox.isSelected()){ - JOptionPane.showMessageDialog(this, Inter.getLocText("Datasource-Connection_failed")); - return false; - } - if(url.startsWith("https:")){ - setHttpsParas(); - } - connect = env.testConnectionWithOutRegisteServer(this); - } - } catch (Exception e) { - JOptionPane.showMessageDialog(this, Inter.getLocText("Datasource-Connection_failed")); - FRContext.getLogger().error(e.getMessage(), e); - } - if (connect) { - try { - String remoteVersion = env.getDesignerVersion(); - if (StringUtils.isBlank(remoteVersion) || ComparatorUtils.compare(remoteVersion, ProductConstants.DESIGNER_VERSION) < 0) { - String infor = Inter.getLocText("Server-version-tip") + "。"; - String moreInfo = Inter.getLocText("Server-version-tip-moreInfo") + "。"; - new InformationWarnPane(infor, moreInfo, Inter.getLocText("Tooltips")).show(); - return false; - } - } catch (Exception e) { - FRContext.getLogger().error(e.getMessage(), e); - } - - } - - return connect; - } - - private AttributeSet getRedSytleAttribute() { - SimpleAttributeSet ds = new SimpleAttributeSet(); - StyleConstants.setForeground(ds, Color.red); - return ds; - } - - /** - * 显示show the content of serverPathFiled - * @param isHttps 是否启用https - */ - public void showServletPathField(boolean isHttps) { - String s = StringUtils.isBlank(webApplyField.getText()) ? "" : "/", t = StringUtils.isBlank(servletField.getText()) ? "" : "/", colon = StringUtils.isBlank(portNameField.getText()) ? "" - : ":"; - String prefix = isHttps ? "https://" : "http://"; - servletPathField.setText(prefix + hostNameField.getText() + colon + portNameField.getText() + s + webApplyField.getText() + t + servletField.getText()); - } - - @Override - public void populateBean(RemoteEnv ob) { - envPath = ob.getPath(); - boolean isHttps = false; - if(envPath != null){ - isHttps = envPath.startsWith("https"); - httpsCheckBox.setSelected(isHttps); - setHttpsState(isHttps); - } - updateNorthPane(isHttps); - if (envPath == null || ComparatorUtils.equals(envPath, StringUtils.EMPTY)) { - this.hostNameField.setText(StringUtils.EMPTY); - this.portNameField.setText(StringUtils.EMPTY); - this.webApplyField.setText(StringUtils.EMPTY); - this.servletField.setText(StringUtils.EMPTY); - this.servletPathField.setText(StringUtils.EMPTY); - this.httpsCheckBox.setSelected(false); - } else { - DesignerEnvManager manager = DesignerEnvManager.getEnvManager(); - this.certificatePath.setText(manager.getCertificatePath()); - this.certificatePass.setText(manager.getCertificatePass()); - // 第二次出现":"的地方,port位置起始点 - int secondTime = envPath.indexOf(":", envPath.indexOf(":") + 1); - // 第三次出现"/"的地方 - int thirdTime = envPath.indexOf("/", secondTime + 1); - // 最后出现"/"的地方 - int lastTime = envPath.lastIndexOf("/"); - String hostName = isHttps ? envPath.substring(HTTPS_HOST_INDEX, secondTime) : envPath.substring(HTTP_HOST_INDEX, secondTime); - this.hostNameField.setText(hostName); - if (thirdTime < 0) { - this.portNameField.setText(envPath.substring(secondTime + 1)); - this.webApplyField.setText(StringUtils.EMPTY); - } else { - this.portNameField.setText(envPath.substring(secondTime + 1, thirdTime)); - if (thirdTime == lastTime) { - this.webApplyField.setText(StringUtils.EMPTY); - } else { - this.webApplyField.setText(envPath.substring(thirdTime + 1, lastTime)); - } - this.servletField.setText(envPath.substring(lastTime + 1)); - } - this.servletPathField.setText(envPath); - } - - this.userTextField.setText(ob.getUser() == null ? StringUtils.EMPTY : ob.getUser()); - - this.passwordTextField.setText(ob.getPassword() == null ? StringUtils.EMPTY : ob.getPassword()); - } - - private void initNorthPane(boolean isHttps){ - double p = TableLayout.PREFERRED; - double f = TableLayout.FILL; - double[] rowSize; - double[] size = {p,p,p,p,p,p,p,p}; - double[] httpsSize = {p,p,p,p,p,p,p,p,p,p}; - if(isHttps){ - rowSize = httpsSize; - }else{ - rowSize = size; - } - double[] columnSize = {p, f}; - northPane = TableLayoutHelper.createTableLayoutPane(coms, rowSize, columnSize); - } - - private void updateNorthPane(boolean isHttps){ - this.removeAll(); - initNorthPane(isHttps); - this.add(northPane, BorderLayout.NORTH); - this.add(previewPane,BorderLayout.CENTER); - this.revalidate(); - this.doLayout(); - this.repaint(); - } - - @Override - public RemoteEnv updateBean() { - String hostName = this.hostNameField.getText(); -// String port = this.portNameField.getText(); - String webApply = this.webApplyField.getText(); - String servlet = this.servletField.getText(); - String path = this.servletPathField.getText(); - String user = this.userTextField.getText(); - String password = new String(this.passwordTextField.getPassword()); - if (isAllEmpty(new String[]{hostName, webApply, servlet})) { - path = StringUtils.EMPTY; - } - - return new RemoteEnv(path, user, password); - } - - private boolean isAllEmpty(String[] strs) { - for (int i = 0; i < strs.length; i++) { - if (StringUtils.isNotEmpty(strs[i])) { - return false; - } - } - return true; - } - } - - public static void main(String[] args) { - Byte[] a = new Byte[1]; - System.out.println(a.getClass()); - } -} +} \ No newline at end of file diff --git a/designer-base/src/com/fr/env/LocalEnvPane.java b/designer-base/src/com/fr/env/LocalEnvPane.java index 1ee7a25ff..d2719636d 100644 --- a/designer-base/src/com/fr/env/LocalEnvPane.java +++ b/designer-base/src/com/fr/env/LocalEnvPane.java @@ -1,5 +1,6 @@ package com.fr.env; +import com.fr.base.env.resource.LocalEnvConfig; import com.fr.dav.LocalEnv; import com.fr.design.beans.BasicBeanPane; import com.fr.design.gui.ilable.UILabel; @@ -21,7 +22,7 @@ import java.io.File; /** * @author yaohwu */ -public class LocalEnvPane extends BasicBeanPane { +public class LocalEnvPane extends BasicBeanPane { private UITextField pathTextField; private JFileTree localEnvTree; @@ -70,9 +71,9 @@ public class LocalEnvPane extends BasicBeanPane { } @Override - public LocalEnv updateBean() { + public LocalEnvConfig updateBean() { String path = pathTextField.getText(); - return LocalEnv.createEnv(path); + return new LocalEnvConfig(path); } public String getPath() { @@ -80,7 +81,7 @@ public class LocalEnvPane extends BasicBeanPane { } @Override - public void populateBean(LocalEnv ob) { + public void populateBean(LocalEnvConfig ob) { if (StringUtils.isBlank(ob.getPath())) { return; } diff --git a/designer-base/src/com/fr/env/RemoteEnv.java b/designer-base/src/com/fr/env/RemoteEnv.java index ed43bc2da..6cb776a40 100644 --- a/designer-base/src/com/fr/env/RemoteEnv.java +++ b/designer-base/src/com/fr/env/RemoteEnv.java @@ -3,61 +3,42 @@ package com.fr.env; import com.fr.base.AbstractEnv; import com.fr.base.EnvException; import com.fr.base.FRContext; -import com.fr.base.ModifiedTable; -import com.fr.base.Parameter; -import com.fr.base.StoreProcedureParameter; import com.fr.base.TableData; import com.fr.base.Utils; +import com.fr.base.env.EnvContext; +import com.fr.base.env.resource.RemoteEnvConfig; import com.fr.base.remote.RemoteDeziConstants; import com.fr.data.TableDataSource; -import com.fr.data.core.DataCoreUtils; -import com.fr.data.core.db.TableProcedure; -import com.fr.data.impl.Connection; import com.fr.data.impl.EmbeddedTableData; -import com.fr.data.impl.storeproc.ProcedureDataModel; -import com.fr.data.impl.storeproc.StoreProcedure; import com.fr.dav.DavXMLUtils; -import com.fr.dav.UserBaseEnv; import com.fr.design.DesignerEnvManager; -import com.fr.design.ExtraDesignClassManager; -import com.fr.design.dialog.InformationWarnPane; -import com.fr.design.file.HistoryTemplateListPane; -import com.fr.design.fun.DesignerEnvProcessor; -import com.fr.design.mainframe.DesignerContext; -import com.fr.design.mainframe.DesignerFrameFileDealerPane; -import com.fr.design.mainframe.loghandler.DesignerLogHandler; import com.fr.file.CacheManager; -import com.fr.file.DatasourceManager; -import com.fr.file.DatasourceManagerProvider; +import com.fr.file.ConnectionConfig; +import com.fr.file.TableDataConfig; import com.fr.file.filetree.FileNode; import com.fr.general.ComparatorUtils; -import com.fr.general.FRLogger; import com.fr.general.IOUtils; import com.fr.general.Inter; import com.fr.general.LogRecordTime; import com.fr.general.LogUtils; import com.fr.general.http.HttpClient; +import com.fr.io.utils.ResourceIOUtils; import com.fr.json.JSONArray; -import com.fr.json.JSONException; import com.fr.json.JSONObject; -import com.fr.license.function.VT4FR; -import com.fr.regist.License; +import com.fr.report.DesignAuthority; import com.fr.share.ShareConstants; -import com.fr.stable.ArrayUtils; import com.fr.stable.EncodeConstants; +import com.fr.stable.Filter; import com.fr.stable.JavaCompileInfo; -import com.fr.stable.ProductConstants; import com.fr.stable.StableUtils; import com.fr.stable.StringUtils; import com.fr.stable.SvgProvider; import com.fr.stable.file.XMLFileManagerProvider; import com.fr.stable.project.ProjectConstants; -import com.fr.stable.xml.XMLPrintWriter; import com.fr.stable.xml.XMLTools; -import com.fr.stable.xml.XMLableReader; import com.fr.web.ResourceConstants; -import javax.swing.*; +import javax.swing.JOptionPane; import javax.xml.transform.Source; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; @@ -65,14 +46,12 @@ import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; -import java.awt.*; +import java.awt.Component; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.FilenameFilter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; @@ -80,52 +59,25 @@ import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; -import java.net.NoRouteToHostException; -import java.net.Socket; -import java.net.URLEncoder; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; -import java.util.Timer; -import java.util.TimerTask; -import java.util.logging.Level; -import java.util.regex.Pattern; - -public class RemoteEnv extends AbstractEnv { - private static final int TIME_OUT = 30 * 1000; - private static final int PLAIN_SOCKET_PORT = 80; - private static final int SSL_PORT = 443; - private static final int MAX_PER_ROUTE = 20; - private static final int MAX_TOTAL = 100; - private static final String REMOTE_PLUGIN = "remote_plugin.info"; + +/** + * @author null + */ +public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurable { private static final String CERT_KEY = "javax.net.ssl.trustStore"; private static final String PWD_KEY = "javax.net.ssl.trustStorePassword"; private static final String HTTPS_PREFIX = "https:"; - private final static String[] FILE_TYPE = {"cpt", "frm", "form", "cht", "chart"}; - private String path; - private String user; - private String password; - private Clock clock = null; - private String userID; - private Timer timer; - private int licNotSupport = 0; - private boolean isRoot = false; - private Timer logTimer = null; - private static ThreadLocal threadLocal = new ThreadLocal(); - private boolean isReadTimeOut = false; + private final static String[] FILE_TYPE = {"cptx", "cpt", "frm", "form", "cht", "chart"}; private String buildFilePath; - - public RemoteEnv() { - this.clock = new Clock(this); - } + private final RemoteEnvConfig env; public RemoteEnv(String path, String userName, String password) { - this(); - this.path = path; - this.user = userName; - this.password = password; + env = new RemoteEnvConfig(path, userName, password); } /** @@ -133,81 +85,22 @@ public class RemoteEnv extends AbstractEnv { */ @Override public String getPath() { - return this.path; - } - - public void setPath(String s) { - this.path = s; + return env.getPath(); } /** * 当前设计环境的用户名,用于远程设计 */ + @Override public String getUser() { - return user; + return env.getUsername(); } - public void setUser(String user) { - this.user = user; - clearUserID(); - } public String getPassword() { - return password; - } - - // 修复密码中包含特殊字符,无法登录的问题 - private String getEncodedPassword() { - try { - return URLEncoder.encode(password, "UTF-8"); - } catch (UnsupportedEncodingException e) { - return password; - } - } - - public void setPassword(String password) { - this.password = password; - clearUserID(); - } - - public Clock getClock() { - return this.clock; + return env.getPassword(); } - public void setClock(Clock clock) { - this.clock = clock; - } - - private void clearUserID() { - this.userID = null; - } - - public void setThreadLocal(String value) { - synchronized (this) { - threadLocal.set(value); - } - - } - - public String getThreadLocal() { - return threadLocal.get(); - } - - /** - * 所有与服务器端交互前,都要调用这个方法生成UserID - */ - private String createUserID() throws EnvException { - // 如果登录之后userID还是null - if (this.userID == null) { - if (!VT4FR.RemoteDesign.support() && licNotSupport <= 0) { - licNotSupport++; - JOptionPane.showMessageDialog(null, Inter.getLocText("FR-Lic_does_not_Support_Remote")); - } - throw new EnvException(Inter.getLocText("Env-Invalid_User_and_Password")); - } - - return this.userID; - } private HttpClient createHttpMethod(HashMap para) throws EnvException, UnsupportedEncodingException { return createHttpMethod(para, false); @@ -216,31 +109,43 @@ public class RemoteEnv extends AbstractEnv { /** * 根据nameValuePairs,也就是参数对,生成PostMethod */ - private HttpClient createHttpMethod(HashMap para, boolean isSignIn) throws EnvException, UnsupportedEncodingException { - String methodPath = this.path; + private HttpClient createHttpMethod(HashMap para, boolean isSignIn) throws EnvException { + String methodPath = getPath(); if (!isSignIn) { - methodPath = methodPath + "?id=" + createUserID(); - } - return new HttpClient(methodPath, para); + methodPath = methodPath + "?id=" + EnvContext.currentToken(); + } + HttpClient client = new HttpClient(methodPath, para); + /* + todo post 方法好象过去不了 + 但是get方法也会有一些url参数问题,尤其是图表部分 + 比如: + op=fr_remote_design&cmd=design_get_plugin_service_data&serviceID=plugin.phantomjs&req= + */ + client.asGet(); + return client; } /** * 根据nameValuePairs,也就是参数对,生成PostMethod,不同之处在于,参数拼在path后面,不是method.addParameters */ - private HttpClient createHttpMethod2(HashMap para) throws EnvException { - String methodPath = path + '?' + "id=" + createUserID(); - return new HttpClient(methodPath, para, true); + private HttpClient createHttpMethod2(HashMap para) throws EnvException, UnsupportedEncodingException { + String methodPath = getPath() + '?' + "id=" + createUserID(); + return new HttpClient(methodPath); + } + + private String createUserID() { + return EnvContext.currentToken(); } - /* - * Read the response body. - * 拿出InputStream中所有的Byte,转换成ByteArrayInputStream的形式返回 - * - * 这样做的目的是确保method.releaseConnection - * - * TODO 但如果不做method.releaseConnection,有多大危害呢?不确定... - */ + /* + * Read the response body. + * 拿出InputStream中所有的Byte,转换成ByteArrayInputStream的形式返回 + * + * 这样做的目的是确保method.releaseConnection + * + * TODO 但如果不做method.releaseConnection,有多大危害呢?不确定... + */ /** * execute method之后,取返回的inputstream @@ -276,7 +181,6 @@ public class RemoteEnv extends AbstractEnv { } else if (ComparatorUtils.equals(message, RemoteDeziConstants.FILE_LOCKED)) { JOptionPane.showMessageDialog(null, Inter.getLocText("FR-Remote_File_is_Locked")); return null; - } else if (message.startsWith(RemoteDeziConstants.RUNTIME_ERROR_PREFIX)) { } return new ByteArrayInputStream(bytes); } finally { @@ -288,17 +192,6 @@ public class RemoteEnv extends AbstractEnv { } } - private void doWithTimeOutException() { - boolean isNotNeedTip = ComparatorUtils.equals(getThreadLocal(), "HEART_BEAT") || ComparatorUtils.equals(getThreadLocal(), "LOG_MESSAGE"); - if (!isReadTimeOut && !isNotNeedTip) { - isReadTimeOut = true; - JOptionPane.showMessageDialog(DesignerContext.getDesignerFrame(), Inter.getLocText(new String[]{"Data", "read_time_out"})); - isReadTimeOut = false; - } - FRContext.getLogger().info("Connection reset "); - } - - /** * nameValuePairs,这个参数要接着this.path,拼成一个URL,否则服务器端req.getParameter是无法得到的 * @@ -347,371 +240,38 @@ public class RemoteEnv extends AbstractEnv { return sb.toString(); } - /** - * 测试连接服务器 - * - * @return 测试连接成功返回true - * @throws Exception 异常 - */ public boolean testServerConnection() throws Exception { - return testConnection(true, true, DesignerContext.getDesignerFrame()); + throw new UnsupportedOperationException("unsupport now"); +// return testConnection(true, true, DesignerContext.getDesignerFrame()); } - /** - * 测试当前配置是否正确 - * - * @return 链接是否成功 - * @throws Exception 异常 - */ + @Override public boolean testServerConnectionWithOutShowMessagePane() throws Exception { - return testConnection(false, true, DesignerContext.getDesignerFrame()); + throw new UnsupportedOperationException("unsupport now"); } - /** - * 主要用于在环境配置面板中的测试连接按钮时,不要注册进远程环境 - * - * @param messageParentPane 弹框的依赖的面板 - * @return 是否测试连接成功 - * @throws Exception 异常 - */ public boolean testConnectionWithOutRegisteServer(Component messageParentPane) throws Exception { - return testConnection(true, false, messageParentPane); - } - - - private boolean testConnection(boolean needMessage, boolean isRegisteServer, Component parentComponent) throws Exception { - extraChangeEnvPara(); - - HashMap para = new HashMap(); - para.put("op", "fr_remote_design"); - para.put("cmd", "test_server_connection"); - para.put("user", user); - para.put("password", getEncodedPassword()); - - if (path.startsWith("https") && (!DesignerEnvManager.getEnvManager().isHttps())) { - return false; - } - - HttpClient client = createHttpMethod(para, true); - - String res = stream2String(execute4InputStream(client)); - if (res == null) { - if (needMessage) { - JOptionPane.showMessageDialog(parentComponent, Inter.getLocText("Datasource-Connection_failed")); - } - return false; - } else if (ComparatorUtils.equals(res, "true")) { - if (!clock.connected && isRegisteServer) { - //服务器中断又重新启动之后,重新向远程服务器注册 - register2Server(); - } - return true; - } else if (ComparatorUtils.equals(res, "invalid username or password.")) { - JOptionPane.showMessageDialog(parentComponent, - Inter.getLocText(new String[]{"Datasource-Connection_failed", "Registration-User_Name", "Password", "Error"}, new String[]{",", "", "", "!"}) - , Inter.getLocText("FR-Server-All_Error"), JOptionPane.ERROR_MESSAGE); - return false; - } else if (res.contains("RegistEditionException")) { - if (needMessage) { - JOptionPane.showMessageDialog(parentComponent, Inter.getLocText(new String[]{"Datasource-Connection_failed", "Version-does-not-support"}, new String[]{",", "!"})); - } else { - FRLogger.getLogger().info(Inter.getLocText(new String[]{"Datasource-Connection_failed", "Version-does-not-support"}, new String[]{",", "!"})); - } - return false; - } else if (ComparatorUtils.equals(res, "war not support remote design.")) { - if (needMessage) { - JOptionPane.showMessageDialog(parentComponent, Inter.getLocText(new String[]{"Datasource-Connection_failed", "NS-war-remote"}, new String[]{",", "!"})); - } else { - FRLogger.getLogger().info(Inter.getLocText(new String[]{"Datasource-Connection_failed", "NS-war-remote"}, new String[]{",", "!"})); - } - return false; - } else { - throw new EnvException(res); - } - } - - private void extraChangeEnvPara() { - //在env连接之前, 加载一下不依赖env的插件. 看看需不需要改变参数. - DesignerEnvProcessor envProcessor = ExtraDesignClassManager.getInstance().getSingle(DesignerEnvProcessor.XML_TAG); - if (envProcessor != null) { - this.path = envProcessor.changeEnvPathBeforeConnect(user, password, path); - } + throw new UnsupportedOperationException("unsupport now"); } private void setHttpsParas() { - if (path.startsWith(HTTPS_PREFIX) && System.getProperty(CERT_KEY) == null) { + if (getPath().startsWith(HTTPS_PREFIX) && System.getProperty(CERT_KEY) == null) { DesignerEnvManager envManager = DesignerEnvManager.getEnvManager(); System.setProperty(CERT_KEY, envManager.getCertificatePath()); System.setProperty(PWD_KEY, envManager.getCertificatePass()); } } - private void register2Server() { - try { - SignIn.signIn(this); - } catch (Exception e) { - FRLogger.getLogger().error(e.getMessage()); - } - } - - /** - * 心跳访问,用来更新当前用户的访问时间 - * - * @throws Exception - */ - public void heartBeatConnection() throws Exception { - HashMap para = new HashMap(); - para.put("op", "fr_remote_design"); - para.put("cmd", "heart_beat"); - para.put("user", user); - - HttpClient client = createHttpMethod(para); - execute4InputStream(client); - - //这做法不好, 30秒刷一次, 刷新的时候会重新构建树, 构建完会把子节点都收缩起来, 效果太差. - //为什么不保存刷新前树的伸缩状态, 因为刷新后的树和刷新前的树的结构未必是一致的. - - //服务器通知客户端更新左上角文件树面板 -// try { -// if (ComparatorUtils.equals(stream2String(execute4InputStream(method)), "true")) { -// DesignerFrameFileDealerPane.getInstance().refresh(); -// } -// } catch (Exception e) { -// FRLogger.getLogger().error(e.getMessage()); -// } - } - /** * 返回描述该运行环境的名字 * * @return 描述环境名字的字符串 */ + @Override public String getEnvDescription() { return Inter.getLocText("Env-Remote_Server"); } - /** - * 登录,返回userID - */ - public void signIn() throws Exception { - if (clock != null && clock.connected) { - return; - } - String remoteVersion = getDesignerVersion(); - if (StringUtils.isBlank(remoteVersion) || ComparatorUtils.compare(remoteVersion, ProductConstants.DESIGNER_VERSION) < 0) { - throw new Exception("version not match"); - } - clearUserID(); - startLogTimer(); - HashMap para = new HashMap(); - para.put("op", "fr_remote_design"); - para.put("cmd", "r_sign_in"); - para.put("user", user); - para.put("password", getEncodedPassword()); - - simulaRPC(para, true); - - //neil:调用Clock方法,10秒向服务器发送一个字节,确保没掉线 - if (clock == null) { - Clock clock = new Clock(this); - setClock(clock); - } - clock.start(); - - // 远程登录的心跳访问, 防止设计器强制关闭而没有Logout - if (timer != null) { - timer.cancel(); - } - timer = new Timer(); - timer.schedule(new TimerTask() { - public void run() { - try { - RemoteEnv.this.setThreadLocal("HEART_BEAT"); - RemoteEnv.this.heartBeatConnection(); - } catch (Exception e) { - FRContext.getLogger().error("Server may be disconnected.", e); - } - } - }, RemoteDeziConstants.HEARTBEAT_DELAY, RemoteDeziConstants.HEARTBEAT_DELAY); - } - - - private void startLogTimer() { - if (logTimer != null) { - logTimer.cancel(); - } - - logTimer = new Timer(); - logTimer.schedule(new TimerTask() { - public void run() { - try { - RemoteEnv.this.setThreadLocal("LOG_MESSAGE"); - FRContext.getCurrentEnv().printLogMessage(); - } catch (Exception e) { - FRLogger.getLogger().info(e.getMessage()); - } - } - }, 10000, 10000); - } - - private void stopLogTimer() { - if (logTimer != null) { - logTimer.cancel(); - logTimer = null; - } - } - - /** - * 根据userID sign out - * - * @return 成功签出返回true - * @throws Exception - */ - public boolean signOut() throws Exception { - if (userID == null) { - return true; - } - stopLogTimer(); - // richer:登出的时候就把定时发送的时钟停掉 - clock.stop(); - // richer:把轮训使用的定时器也去掉 - timer.cancel(); - - HashMap para = new HashMap(); - para.put("op", "fr_remote_design"); - para.put("cmd", "r_sign_out"); - para.put("id", userID); - - return simulaRPC(para, false - ); - } - - protected boolean simulaRPC(HashMap para, boolean isSignIn) throws Exception { - HttpClient client = createHttpMethod(para, isSignIn); - - // execute method取到input stream再转成String - String resJSON = null; - try { - resJSON = stream2String(execute4InputStream(client)); - } catch (Exception e) { - FRLogger.getLogger().error(e.getMessage()); - } - - if (resJSON == null) { - return false; - } - if (resJSON.contains("RegistEditionException")) { - JOptionPane.showMessageDialog(null, Inter.getLocText("FR-Lic_does_not_Support_Remote")); - return false; - } - try { - JSONObject jo = new JSONObject(resJSON); - - if (isSignIn) { - if (jo.has("id")) { - userID = jo.getString("id"); - } - if (jo.has("isRoot")) { - isRoot = jo.getBoolean("isRoot"); - } - - if (userID != null) { - return true; - } - } else { - if (jo.has("res")) { - return jo.getBoolean("res"); - } - } - String exception = jo.getString("exp"); - if (exception != null) { - throw new EnvException(exception); - } - } catch (JSONException je) { - // 返回的resJSON不是JSON格式的,那就直接返回resJSON作为userID - return true; - } - - return true; - } - - protected boolean doLockOperation(String[] filePathes, String cmd) throws Exception { - if (filePathes == null || filePathes.length == 0) { - return true; - } - - JSONArray ja = new JSONArray(filePathes); - HashMap para = new HashMap(); - para.put("op", "fr_remote_design"); - para.put("cmd", cmd); - para.put("pathes", ja.toString()); - - return simulaRPC(para, false); - } - - /** - * 取路径filePath下面文件的lock - *

- * 处于同一个原子操作,要么拿到所有的锁,要么一个锁也没有拿到 - */ - public boolean getLock(String[] filePathes) throws Exception { - return doLockOperation(filePathes, "design_get_lock"); - } - - /** - * 解锁文件 - * - * @param filePathes 文件路径 - * @return 成功解锁返回true - * @throws Exception - */ - public boolean releaseLock(String[] filePathes) throws Exception { - return doLockOperation(filePathes, "design_release_lock"); - } - - /** - * 当前Env下,tplPath目录下是否存在模板 - * - * @param reportPath 路径 - * @return 是否存在 - */ - @Override - public boolean isTemplateExist(String reportPath) throws Exception { - if (reportPath == null) { - return false; - } - - HashMap para = new HashMap(); - para.put("op", "fr_remote_design"); - para.put("cmd", "design_report_exist"); - para.put("report_path", reportPath); - - HttpClient client = createHttpMethod(para); - InputStream input = execute4InputStream(client); - - return ComparatorUtils.equals(stream2String(input), "true"); - } - - /** - * 解锁当前模板,用于远程设计。当远程设计某张模板 时,在解锁之前改模板处于锁定状态 - * - * @param tplPath 路径 - * @throws Exception - */ - @Override - public void unlockTemplate(String tplPath) throws Exception { - HashMap para = new HashMap(); - para.put("op", "fr_remote_design"); - para.put("cmd", "design_close_report"); - para.put(RemoteDeziConstants.TEMPLATE_PATH, tplPath); - HttpClient client = createHttpMethod(para); - - InputStream input = execute4InputStream(client); - String info = Utils.inputStream2String(input, EncodeConstants.ENCODING_UTF_8); - - FRContext.getLogger().error(info); - } - public class Bytes2ServerOutputStream extends OutputStream { private ByteArrayOutputStream out = new ByteArrayOutputStream(); private HashMap nameValuePairs; @@ -749,8 +309,9 @@ public class RemoteEnv extends AbstractEnv { /** * 刷新数出流,并提交 * - * @throws IOException + * @throws IOException e */ + @Override public void flush() throws IOException { super.flush(); post2Server(); @@ -760,121 +321,42 @@ public class RemoteEnv extends AbstractEnv { * 将指定字节写入输入流数组 * * @param b 写入的字节 - * @throws IOException */ @Override - public void write(int b) throws IOException { + public void write(int b) { out.write(b); } } - /** - * 测试数据连接是否能够正确的连接上 - * - * @param database 数据连接 - * @return 如果能正确的连接到数据库则返回true - * @throws Exception 无法正确连接到数据库则抛出此异常 - * TODO alex_ENV 个人以为,这里应该是测试所有Connection的连接,所以Connection与TableData接口的关联需要思考 - */ - @Override - public boolean testConnection(com.fr.data.impl.Connection database) throws Exception { - ByteArrayOutputStream out = new ByteArrayOutputStream(); - - // 把database写成xml文件到out - DavXMLUtils.writeXMLFileDatabaseConnection(database, out); - - HashMap para = new HashMap(); - para.put("op", "fr_remote_design"); - para.put("cmd", "design_test_con"); - - InputStream input = postBytes2ServerB(out.toByteArray(), para); - - if (input == null) { - return false; - } - - return Boolean.valueOf(IOUtils.inputStream2String(input, EncodeConstants.ENCODING_UTF_8)); - } - - /** - * ben:取schema - */ @Override - public String[] getTableSchema(com.fr.data.impl.Connection database) throws Exception { - ByteArrayOutputStream out = new ByteArrayOutputStream(); - - DavXMLUtils.writeXMLFileDatabaseConnection(database, out); - HashMap para = new HashMap(); - para.put("op", "fr_remote_design"); - para.put("cmd", "design_get_schema"); - InputStream input = postBytes2ServerB(out.toByteArray(), para); - if (input == null) { - return null; - } - return DavXMLUtils.readXMLFileSchema(input); + public boolean updateAuthorities(DesignAuthority[] authorities) throws Exception { + return RemoteEnvUtils.updateAuthorities(authorities, this); } - /** - * b:分别取Table,View,Procedure,实际应用时更有意义 - */ @Override - public TableProcedure[] getTableProcedure(com.fr.data.impl.Connection database, String type, String schema) throws Exception { - ByteArrayOutputStream out = new ByteArrayOutputStream(); - DavXMLUtils.writeXMLFileDatabaseConnection(database, out); - HashMap para = new HashMap(); - para.put("op", "fr_remote_design"); - para.put("cmd", "design_get_tables"); - para.put("__type__", type); - para.put("__dbschema__", schema); - InputStream input = postBytes2ServerB(out.toByteArray(), para); - if (input == null) { - return new TableProcedure[0]; - } - return DavXMLUtils.readXMLSQLTables(input); - } - - public List getProcedures(com.fr.data.impl.Connection datasource, String[] schemas, boolean isOracle, boolean isOracleSysSpace) throws Exception { - HashMap schemaTableProcedureMap = new HashMap(); - List sqlTableObjs = new ArrayList(); - TableProcedure[] sqlTableObj = null; - int len = schemas.length; - if (len > 0) { - for (int i = 0; i < len; i++) { - String schema = schemas[i]; - sqlTableObj = this.getTableProcedure(datasource, TableProcedure.PROCEDURE, schema); - if (sqlTableObj == null) { - sqlTableObj = new TableProcedure[0]; - } - sqlTableObjs.add(sqlTableObj); - schemaTableProcedureMap.put(schema, sqlTableObj); - } - } else { - sqlTableObj = this.getTableProcedure(datasource, TableProcedure.PROCEDURE, null); - if (sqlTableObj == null) { - sqlTableObj = new TableProcedure[0]; - } - sqlTableObjs.add(sqlTableObj); - schemaTableProcedureMap.put(null, sqlTableObj); - } - DataCoreUtils.putProcedureMap(datasource, schemaTableProcedureMap); - return sqlTableObjs; + public DesignAuthority[] getAuthorities() { + return RemoteEnvUtils.getAuthorities(this); } /** - * 在当前路径下新建文件夹 + * 远程设计器设计时,假如开了权限就不可预览了。这边放一个全局的map来开后门 * - * @param folderPath 文件名 - * @return 成功创建返回true - * @throws Exception + * @param key 键值 + * @param value 值 + * @return 如果写入成功,返回true + * @throws Exception e */ - @Override - public boolean createFolder(String folderPath) throws Exception { - HashMap para = new HashMap(); + public boolean writePrivilegeMap(String key, String value) throws Exception { + HashMap para = new HashMap<>(); para.put("op", "fr_remote_design"); - para.put("cmd", "design_create_folder"); - para.put("folder_path", folderPath); + para.put("cmd", "write_privilege_map"); + para.put("current_user", getUser()); + para.put("current_password", this.getPassword()); + para.put("key", key); + para.put("value", value); + //jim :加上user,远程设计点击预览时传递用户角色信息 HttpClient client = createHttpMethod(para); InputStream input = execute4InputStream(client); @@ -886,188 +368,14 @@ public class RemoteEnv extends AbstractEnv { } /** - * 新建一个文件 - * - * @param filePath :目标文件相对路径 - * @return 成功新建返回true - * @throws Exception + * DataSource中去除当前角色没有权限访问的数据源 */ - public boolean createFile(String filePath) throws Exception { - HashMap para = new HashMap(); - para.put("op", "fr_remote_design"); - para.put("cmd", "design_create_file"); - para.put("file_path", filePath); + @Override + public void removeNoPrivilegeConnection() { + TableDataConfig dm = TableDataConfig.getInstance(); - HttpClient client = createHttpMethod(para); - InputStream input = execute4InputStream(client); - - if (input == null) { - return false; - } - - return Boolean.valueOf(IOUtils.inputStream2String(input, EncodeConstants.ENCODING_UTF_8)); - } - - public boolean renameFile(String newPath, String oldPath) throws Exception { - HashMap para = new HashMap(); - para.put("op", "fr_remote_design"); - para.put("cmd", "design_rename_file"); - para.put("newPath", newPath); - para.put("oldPath", oldPath); - - HttpClient client = createHttpMethod(para); - InputStream input = execute4InputStream(client); - - if (input == null) { - return false; - } - - return Boolean.valueOf(IOUtils.inputStream2String(input, EncodeConstants.ENCODING_UTF_8)); - } - - /** - * 判断文件是否存在 - * - * @param filePath :目标文件相对路径 - * @return 文件是否存在 - * @throws Exception - */ - @Override - public boolean fileExists(String filePath) throws Exception { - if (filePath == null) { - return false; - } - - HashMap para = new HashMap(); - para.put("op", "fr_remote_design"); - para.put("cmd", "design_file_exists"); - para.put("file_path", filePath); - - HttpClient client = createHttpMethod(para); - InputStream input = execute4InputStream(client); - - if (input == null) { - return false; - } - - return Boolean.valueOf(IOUtils.inputStream2String(input, EncodeConstants.ENCODING_UTF_8)); - } - - /** - * 判断文件是否锁住 - * - * @param filePath 文件路径 - * @return 文件被锁住了,返回true - * @throws Exception - */ - public boolean fileLocked(String filePath) throws Exception { - if (filePath == null) { - return false; - } - - HashMap para = new HashMap(); - para.put("op", "fr_remote_design"); - para.put("cmd", "design_file_locked"); - para.put("file_path", filePath); - - HttpClient client = createHttpMethod(para); - InputStream input = execute4InputStream(client); - - if (input == null) { - return false; - } - - return Boolean.valueOf(IOUtils.inputStream2String(input, EncodeConstants.ENCODING_UTF_8)); - } - - - /** - * 注册环境,用于检测是否启动定时器,主要用于本地环境来监测远程 - * - * @param env 用户环境 - */ - public void registerUserEnv(UserBaseEnv env) { - } - - /** - * 用于检测用户环境 - * ,启动定时器 - */ - public void startUserCheckTimer() { - } - - - /** - * 停止定时器 - */ - public void stopUserCheckTimer() { - } - - /** - * 删除文件 - * - * @param filePath 文件地址 - * @return 删除成功返回true - */ - public boolean deleteFile(String filePath) { - if (filePath == null) { - return false; - } try { - HashMap para = new HashMap(); - para.put("op", "fr_remote_design"); - para.put("cmd", "delete_file"); - para.put("file_path", filePath); - - HttpClient client = createHttpMethod(para); - InputStream input = execute4InputStream(client); - - if (input == null) { - return false; - } - - return Boolean.valueOf(IOUtils.inputStream2String(input, EncodeConstants.ENCODING_UTF_8)); - } catch (Exception e) { - FRLogger.getLogger().error(e.getMessage()); - } - return false; - } - - /** - * 远程设计器设计时,假如开了权限就不可预览了。这边放一个全局的map来开后门 - * - * @param key 键值 - * @param value 值 - * @return 如果写入成功,返回true - * @throws Exception - */ - public boolean writePrivilegeMap(String key, String value) throws Exception { - HashMap para = new HashMap(); - para.put("op", "fr_remote_design"); - para.put("cmd", "write_privilege_map"); - para.put("current_user", this.user); - para.put("current_password", this.password); - para.put("key", key); - para.put("value", value); - - HttpClient client = createHttpMethod(para); //jim :加上user,远程设计点击预览时传递用户角色信息 - InputStream input = execute4InputStream(client); - - if (input == null) { - return false; - } - - return Boolean.valueOf(IOUtils.inputStream2String(input, EncodeConstants.ENCODING_UTF_8)); - } - - /** - * DataSource中去除当前角色没有权限访问的数据源 - */ - public void removeNoPrivilegeConnection() { - DatasourceManagerProvider dm = DatasourceManager.getProviderInstance(); - - try { - HashMap para = new HashMap(); + HashMap para = new HashMap<>(); para.put("op", "fs_remote_design"); para.put("cmd", "env_get_role"); para.put("currentUsername", this.getUser()); @@ -1076,11 +384,11 @@ public class RemoteEnv extends AbstractEnv { HttpClient client = createHttpMethod(para); InputStream input = execute4InputStream(client); JSONArray ja = new JSONArray(stream2String(input)); - ArrayList toBeRemoveTDName = new ArrayList(); + ArrayList toBeRemoveTDName = new ArrayList<>(); for (int i = 0; i < ja.length(); i++) { String toBeRemoveConnName = (String) ((JSONObject) ja.get(i)).get("name"); - dm.removeConnection(toBeRemoveConnName); - Iterator it = dm.getTableDataNameIterator(); + ConnectionConfig.getInstance().removeConnection(toBeRemoveConnName); + Iterator it = dm.getTableDatas().keySet().iterator(); while (it.hasNext()) { String tdName = (String) it.next(); TableData td = dm.getTableData(tdName); @@ -1096,165 +404,6 @@ public class RemoteEnv extends AbstractEnv { } } - /** - * 列出WEB-INF目录下指定路径的文件夹与文件 - * - * @param rootFilePath 指定目录 - * @return WEB-INF目录下指定路径的文件夹与文件 - * @throws Exception - */ - @Override - public FileNode[] listFile(String rootFilePath) throws Exception { - return listFile(rootFilePath, false); - } - - /** - * 列出WEB-INF上层目录下指定路径的文件夹与文件 - * - * @param rootFilePath 指定目录 - * @return WEB-INF上层目录下指定路径的文件夹与文件 - * @throws Exception - */ - @Override - public FileNode[] listReportPathFile(String rootFilePath) throws Exception { - return listFile(rootFilePath, true); - } - - private FileNode[] listFile(String rootFilePath, boolean isWebReport) throws Exception { - FileNode[] fileNodes; - - HashMap para = new HashMap(); - para.put("op", "fs_remote_design"); - para.put("cmd", "design_list_file"); - para.put("file_path", rootFilePath); - para.put("currentUserName", this.getUser()); - para.put("currentUserId", this.createUserID()); - para.put("isWebReport", isWebReport ? "true" : "false"); - - HttpClient client = createHttpMethod(para); - InputStream input = execute4InputStream(client); - - if (input == null) { - return new FileNode[0]; - } - - // 远程环境下左侧目录树暂不需要打开xlsx,xls文件 - fileNodes = DavXMLUtils.readXMLFileNodes(input); - ArrayList al = new ArrayList(); - for (int i = 0; i < fileNodes.length; i++) { - al.add(fileNodes[i]); - } - - FileNode[] fileNodes2 = new FileNode[al.size()]; - for (int i = 0; i < al.size(); i++) { - fileNodes2[i] = al.get(i); - } - - return fileNodes2; - } - - - /** - * 列出目标目录下所有cpt文件或文件夹 - * - * @param rootFilePath 指定目录 - * @return 列出目标目录下所有cpt文件或文件夹 - * @throws Exception - */ - public FileNode[] listCpt(String rootFilePath) throws Exception { - return listCpt(rootFilePath, false); - } - - /** - * 列出目标目录下所有cpt文件或文件夹 - * - * @param rootFilePath 指定目录 - * @param recurse 是否递归查找其子目录 - * @return 列出目标目录下所有cpt文件或文件夹 - * @throws Exception - */ - public FileNode[] listCpt(String rootFilePath, boolean recurse) { - List fileNodeList = new ArrayList(); - try { - listAll(rootFilePath, fileNodeList, new String[]{"cpt"}, recurse); - } catch (Exception e) { - FRContext.getLogger().error(e.getMessage(), e); - } - return fileNodeList.toArray(new FileNode[fileNodeList.size()]); - } - - private void listAll(String rootFilePath, List nodeList, String[] fileTypes, boolean recurse) throws Exception { - FileNode[] fns = listFile(rootFilePath); - for (FileNode fileNode : fns) { - if (isAcceptFileType(fileNode, fileTypes)) { - nodeList.add(fileNode); - } else if (fileNode.isDirectory()) { - if (recurse) { - listAll(rootFilePath + File.separator + fileNode.getName(), nodeList, fileTypes, true); - } else { - nodeList.add(fileNode); - } - } - } - } - - private boolean isAcceptFileType(FileNode fileNode, String[] fileTypes) { - for (String fileType : fileTypes) { - if (fileNode.isFileType(fileType)) { - return true; - } - } - return false; - } - - /** - * 获取指定数据集的参数 - * - * @param tableData 数据集 - * @return 数据集的参数 - * @throws Exception 获取参数失败则抛出此异常 - */ - public Parameter[] getTableDataParameters(TableData tableData) throws Exception { - ByteArrayOutputStream out = new ByteArrayOutputStream(); - -// 把tableData写成xml文件到out - DavXMLUtils.writeXMLFileTableData(tableData, out); - - HashMap para = new HashMap(); - para.put("op", "fr_remote_design"); - para.put("cmd", "design_td_pars"); - InputStream input = postBytes2ServerB(out.toByteArray(), para); - - if (input == null) { - return new Parameter[0]; - } - return DavXMLUtils.readXMLParameters(input); - } - - - /** - * 获取存储过程中的参数 - * - * @param storeProcedure 存储过程 - * @return 返回存储过程中的所有参数组成的数组 - * @throws Exception 如果获取参数失败则抛出此异常 - */ - public Parameter[] getStoreProcedureParameters(StoreProcedure storeProcedure) throws Exception { - ByteArrayOutputStream out = new ByteArrayOutputStream(); - - // 把tableData写成xml文件到out - DavXMLUtils.writeXMLFileStoreProcedureAndSource(storeProcedure, out); - HashMap para = new HashMap(); - para.put("op", "fr_remote_design"); - para.put("cmd", "design_sp_pars"); - InputStream input = postBytes2ServerB(out.toByteArray(), para); - - if (input == null) { - return new Parameter[0]; - } - return DavXMLUtils.readXMLParameters(input); - } - @Override public EmbeddedTableData previewTableData(Object tableData, Map parameterMap, int rowCount) throws Exception { return previewTableData(null, tableData, parameterMap, rowCount); @@ -1269,6 +418,7 @@ public class RemoteEnv extends AbstractEnv { * @return 实际的二维数据集 * @throws Exception 如果生成数据失败则抛出此异常 */ + @Override public EmbeddedTableData previewTableData(TableDataSource dataSource, Object tableData, java.util.Map parameterMap, int rowCount) throws Exception { ByteArrayOutputStream out = new ByteArrayOutputStream(); @@ -1278,7 +428,7 @@ public class RemoteEnv extends AbstractEnv { // 把parameterMap转成JSON格式的字符串 JSONObject jo = new JSONObject(parameterMap); String jsonParameter = jo.toString(); - HashMap para = new HashMap(); + HashMap para = new HashMap<>(); para.put("op", "fr_remote_design"); para.put("cmd", "design_preview_td"); para.put("pars", jsonParameter); @@ -1298,186 +448,41 @@ public class RemoteEnv extends AbstractEnv { * @param tableData 带参数的数据集 * @param parameterMap 参数键值对 * @param start 开始 - * @param end 结尾 - * @param cols 列名 - * @param colIdx 列序号 - * @return 实际的二位数据条 - * @throws Exception 异常 - */ - public Object previewTableData(Object tableData, java.util.Map parameterMap, int start, int end, String[] cols, int[] colIdx) throws Exception { - return previewTableData(tableData, parameterMap, -1); - } - - @Override - public Object previewTableData(TableDataSource dataSource, Object tableData, Map parameterMap, int start, int end, String[] cols, int[] colIdx) throws Exception { - return previewTableData(dataSource, tableData, parameterMap, -1); - } - - /** - * nameValuePairs,这个参数要接着this.path,拼成一个URL,否则服务器端req.getParameter是无法得到的 - * - * @param bytes 数据 - * @param para 参数 - * @return 从服务器端得到InputStream - * @throws Exception 异常 - */ - public InputStream postBytes2ServerB(byte[] bytes, HashMap para) throws Exception { - HttpClient client = createHttpMethod2(para); - client.setContent(bytes); - return execute4InputStream(client); - } - - /** - * Read XML.
- * The method will be invoked when read data from XML file.
- * May override the method to read the data that you saved. - */ - public void readXML(XMLableReader reader) { - if (reader.isChildNode()) { - String tmpVal; - if ("DIR".equals(reader.getTagName())) { - if ((tmpVal = reader.getAttrAsString("path", null)) != null) { - this.path = tmpVal; - } - if ((tmpVal = reader.getAttrAsString("user", null)) != null) { - this.user = tmpVal; - } - if ((tmpVal = reader.getAttrAsString("password", null)) != null) { - this.password = tmpVal; - } - } - } - } - - /** - * Write XML.
- * The method will be invoked when save data to XML file.
- * May override the method to save your own data. - * - * @param writer the PrintWriter. - */ - public void writeXML(XMLPrintWriter writer) { - writer.startTAG("DIR").attr("path", this.path).attr("user", this.user).attr("password", this.password).end(); - } - - - public static class Clock { - - private static final long CONNECT_INTERVAL = 3000L; - private boolean connected = false; - - private RemoteEnv remoteEnv; - - public Clock(RemoteEnv remoteEnv) { - this.remoteEnv = remoteEnv; - } - - /** - * 开始连接 - */ - public void start() { - if (connected) { - return; - } - connected = true; - - new Thread(new Runnable() { - @Override - public void run() { - // richie:连续三次尝试连接都没有响应才判定为丢失连接 - while (connected) { - try { - attemptConnect(); - } catch (Exception ex) { - try { - attemptConnect(); - } catch (Exception ee) { - try { - attemptConnect(); - } catch (Exception exc) { - stop(); - if (exc instanceof NoRouteToHostException) { - //网络问题导致的连接中断 - if (JOptionPane.showConfirmDialog(null, Inter.getLocText("FR-Remote_Connect2Server_Again"), UIManager.getString("OptionPane.titleText"), JOptionPane.YES_NO_OPTION) - == JOptionPane.OK_OPTION) { - //调用重新连接服务器的方法 - connectedAgain(); - } - } else { - //服务器关闭引起的连接中断 - if (JOptionPane.showConfirmDialog(null, Inter.getLocText("FR-Remote_Re_Connect_to_Server"), UIManager.getString("OptionPane.titleText"), JOptionPane.YES_NO_OPTION) - == JOptionPane.OK_OPTION) { - //调用重新连接服务器的方法 - connectedAgain(); - } - } - } - } - } - } - } - }).start(); - } - - /** - * 服务器连接中断后重新连接 - */ - private void connectedAgain() { - try { - if (!remoteEnv.testServerConnectionWithOutShowMessagePane()) { - JOptionPane.showMessageDialog(DesignerContext.getDesignerFrame(), Inter.getLocText(new String[]{"Datasource-Connection_failed", "check_communication"}, - new String[]{",", "!"})); - DesignerFrameFileDealerPane.getInstance().refresh(); - return; - } - String remoteVersion = remoteEnv.getDesignerVersion(); - if (StringUtils.isBlank(remoteVersion) || ComparatorUtils.compare(remoteVersion, ProductConstants.DESIGNER_VERSION) < 0) { - String infor = Inter.getLocText("FR-Server_Version_Tip"); - String moreInfo = Inter.getLocText("FR-Server_Version_Tip_MoreInfo"); - FRLogger.getLogger().log(Level.WARNING, infor); - new InformationWarnPane(infor, moreInfo, Inter.getLocText("FR-Designer_Tooltips")).show(); - return; - } - SignIn.signIn(remoteEnv); - HistoryTemplateListPane.getInstance().getCurrentEditingTemplate().refreshToolArea(); - } catch (Exception em) { - FRContext.getLogger().error(em.getMessage(), em); - } - } - - /** - * 停止连接 - */ - public void stop() { - connected = false; - } - - private void attemptConnect() throws Exception { - Thread.sleep(CONNECT_INTERVAL); - Pattern pattern = Pattern.compile("[/:]+"); - String[] strs = pattern.split(remoteEnv.path); - - String shost = strs[1];//host,如:192.168.100.195 - int sport = Integer.parseInt(strs[2]);//端口,如:8080 + * @param end 结尾 + * @param cols 列名 + * @param colIdx 列序号 + * @return 实际的二位数据条 + * @throws Exception 异常 + */ + @Override + public Object previewTableData(Object tableData, java.util.Map parameterMap, int start, int end, String[] cols, int[] colIdx) throws Exception { + return previewTableData(tableData, parameterMap, -1); + } - Socket socket = new Socket(shost, sport); - //OOBBINLINE:是否支持发送一个字节的TCP紧急数据,false表示服务器不用处理这个数据 - socket.setOOBInline(false); - socket.sendUrgentData(0xFF); - socket.close(); - } + @Override + public Object previewTableData(TableDataSource dataSource, Object tableData, Map parameterMap, int start, int end, String[] cols, int[] colIdx) throws Exception { + return previewTableData(dataSource, tableData, parameterMap, -1); } /** - * 读报表运行环境所需的配置文件,如datasource.xml, config.xml,这些文件都保存在WEB-INF/resources目录下面 + * nameValuePairs,这个参数要接着this.path,拼成一个URL,否则服务器端req.getParameter是无法得到的 * - * @param resourceName 配置文件的名字,如datasource.xml - * @return 输入流 - * @throws Exception + * @param bytes 数据 + * @param para 参数 + * @return 从服务器端得到InputStream + * @throws Exception 异常 */ - @Override - public InputStream readResource(String resourceName) throws Exception { - return readBean(resourceName, ProjectConstants.RESOURCES_NAME); + public InputStream postBytes2ServerB(byte[] bytes, HashMap para) throws Exception { + HttpClient client = createHttpMethod2(para); + /* + todo post 方法好象过去不了 + 但是get方法也会有一些url参数问题,尤其是图表部分 + 比如: + op=fr_remote_design&cmd=design_get_plugin_service_data&serviceID=plugin.phantomjs&req= + */ +// client.asGet(); + client.setContent(bytes); + return execute4InputStream(client); } @@ -1487,18 +492,14 @@ public class RemoteEnv extends AbstractEnv { * @param path 制定路径,是基于报表目录下resource文件夹路径 * @return 读到的文件 */ - public File[] readPathSvgFiles(String path) { - String cataloguePath = StableUtils.pathJoin(new String[]{CacheManager.getProviderInstance().getCacheDirectory().getPath(), SvgProvider.SERVER, path}); + @Override + public String[] readPathSvgFiles(String path) { + String cataloguePath = StableUtils.pathJoin(CacheManager.getProviderInstance().getCacheDirectory().getPath(), SvgProvider.SERVER, path); - //检查缓存文件保存的目录下serversvgs文件夹是否存在 ,先用来暂存服务器读过来的svg文件 - File catalogue = new File(cataloguePath); - if (!catalogue.exists()) { - catalogue.mkdirs(); - } - ArrayList fileArray = new ArrayList<>(); + ArrayList fileArray = new ArrayList<>(); try { - HashMap para = new HashMap(); + HashMap para = new HashMap<>(); para.put("op", "fr_remote_design"); para.put("cmd", "design_read_svgfile"); para.put("resourcePath", path); @@ -1512,17 +513,17 @@ public class RemoteEnv extends AbstractEnv { JSONObject jsonObject = (JSONObject) ja.get(i); String svgFileName = (String) jsonObject.get("svgfileName"); String svgfileContent = (String) jsonObject.get("svgfileContent"); - File file = new File(StableUtils.pathJoin(new String[]{cataloguePath, svgFileName})); + + String file = StableUtils.pathJoin(cataloguePath, svgFileName); InputStream in = new ByteArrayInputStream(svgfileContent.getBytes(EncodeConstants.ENCODING_UTF_8)); - FileOutputStream out = new FileOutputStream(file); - IOUtils.copyBinaryTo(in, out); + ResourceIOUtils.write(file, in); fileArray.add(file); } } catch (Exception e) { FRContext.getLogger().error(e.getMessage()); } - return fileArray.toArray(new File[fileArray.size()]); + return fileArray.toArray(new String[fileArray.size()]); } @@ -1533,11 +534,12 @@ public class RemoteEnv extends AbstractEnv { * @return 是否写入成功 * @throws Exception 异常 */ + @Override public boolean writeSvgFile(SvgProvider svgFile) throws Exception { testServerConnection(); - HashMap para = new HashMap(); - para.put("op", "svginit"); + HashMap para = new HashMap<>(); + para.put("op", "svgrelate"); para.put("cmd", "design_save_svg"); para.put("filePath", svgFile.getFilePath()); para.put("current_uid", this.createUserID()); @@ -1589,7 +591,7 @@ public class RemoteEnv extends AbstractEnv { public boolean writeResource(XMLFileManagerProvider mgr) throws Exception { testServerConnection(); - HashMap para = new HashMap(); + HashMap para = new HashMap<>(); para.put("op", "fr_remote_design"); para.put("cmd", "design_save_resource"); para.put("resource", mgr.fileName()); @@ -1624,9 +626,10 @@ public class RemoteEnv extends AbstractEnv { * @param prefix 当前Env下得工程分类,如reportlets,lib等 * @return InputStream 输入流 */ + @Override public InputStream readBean(String beanPath, String prefix) throws Exception { - HashMap para = new HashMap(); + HashMap para = new HashMap<>(); para.put("op", "fs_remote_design"); para.put("cmd", "design_open"); para.put(RemoteDeziConstants.PREFXI, prefix); @@ -1645,9 +648,9 @@ public class RemoteEnv extends AbstractEnv { * @param prefix 当前Env下得工程分类,如reportlets,lib等 * @return OutputStream 输出流 */ - public OutputStream writeBean(String beanPath, String prefix) - throws Exception { - HashMap para = new HashMap(); + @Override + public OutputStream writeBean(String beanPath, String prefix) { + HashMap para = new HashMap<>(); para.put("op", "fs_remote_design"); para.put("cmd", "design_save_report"); para.put(RemoteDeziConstants.PREFXI, prefix); @@ -1656,185 +659,21 @@ public class RemoteEnv extends AbstractEnv { return new Bytes2ServerOutputStream(para); } - /** - * 返回数据库表的列名 - * - * @param selectedName 所选择数据库名 - * @param schema 数据库模式,用于存储过程 - * @param tableName 所选择数据库名 - */ - @Override - public String[] getColumns(String selectedName, String schema, String tableName) throws Exception { - HashMap para = new HashMap(); - para.put("op", "fr_remote_design"); - para.put("cmd", "design_columns"); - para.put("dsName", selectedName); - para.put("schema", schema); - para.put("tableName", tableName); - - HttpClient client = createHttpMethod2(para); - InputStream input = execute4InputStream(client); - - if (input == null) { - return null; - } - - String colums = stream2String(input); - if (StringUtils.isEmpty(colums)) { - return null; - } - return colums.split("\\."); - } - - /** - * 返回模板文件路径 - */ @Override public String getWebReportPath() { return getPath().substring(0, getPath().lastIndexOf("/")); } - @Override - public String getProcedureText(String connectionName, String databaseName) throws Exception { - HashMap para = new HashMap(); - para.put("op", "fr_remote_design"); - para.put("cmd", "design_get_procedure_text"); - para.put("procedure_name", databaseName); - para.put("connectionName", connectionName); - - ByteArrayOutputStream out = new ByteArrayOutputStream(); - InputStream input = postBytes2ServerB(out.toByteArray(), para); - if (input == null) { - return StringUtils.EMPTY; - } - return DavXMLUtils.readXMLProcedureText(input); - } - - @Override - public StoreProcedureParameter[] getStoreProcedureDeclarationParameters(String connectionName, String databaseName, String parameterDefaultValue) throws Exception { - ByteArrayOutputStream out = new ByteArrayOutputStream(); - HashMap para = new HashMap(); - para.put("op", "fr_remote_design"); - para.put("cmd", "design_get_sp_parameters"); - para.put("__name__", databaseName); - para.put("__default_value__", parameterDefaultValue); - para.put("connectionName", connectionName); - - InputStream input = postBytes2ServerB(out.toByteArray(), para); - if (input == null) { - return new StoreProcedureParameter[0]; - } - return DavXMLUtils.readXMLStoreProcedureParameters(input); - } - - /** - * 获取datasource.xml文件的修改表 - */ - public ModifiedTable getDataSourceModifiedTables(String type) { - try { - HashMap para = new HashMap(); - para.put("op", "fr_remote_design"); - para.put("cmd", "get_datasource_modified_tables"); - para.put("type", type); - - HttpClient client = createHttpMethod(para); - InputStream input = execute4InputStream(client); - if (input == null) { - return new ModifiedTable(); - } - return DavXMLUtils.readXMLModifiedTables(input); - } catch (Exception e) { - FRContext.getLogger().error(e.getMessage()); - } - return new ModifiedTable(); - } - - - /** - * 写修改表 - * - * @param modifiedTable 修改表 - * @param type 操作类型,是数据连接还是服务器数据集 - * @return 写入成功返回true - */ - public boolean writeDataSourceModifiedTables(ModifiedTable modifiedTable, String type) { - - ByteArrayOutputStream out = new ByteArrayOutputStream(); - - // 把tableData写成xml文件到out - DavXMLUtils.writeXMLModifiedTables(modifiedTable, out); - try { - HashMap para = new HashMap(); - para.put("op", "fr_remote_design"); - para.put("cmd", "update_modifytable_to_server"); - para.put("type", type); - - InputStream input = postBytes2ServerB(out.toByteArray(), para); - - if (input == null) { - return false; - } - - return Boolean.valueOf(IOUtils.inputStream2String(input, EncodeConstants.ENCODING_UTF_8)); - } catch (Exception e) { - FRContext.getLogger().error(e.getMessage()); - } - return false; - } - - public String[] getProcedureColumns(StoreProcedure storeProcedure, java.util.Map parameterMap) throws Exception { - String[] columns; - HashMap para = new HashMap(); - para.put("op", "fr_remote_design"); - para.put("cmd", "list_sp"); - HttpClient client = createHttpMethod(para); - try { - InputStream input = execute4InputStream(client); - - if (input == null) { - return ArrayUtils.EMPTY_STRING_ARRAY; - } - - columns = DavXMLUtils.readXMLSPColumns(input); - return columns; - } catch (Exception e) { - FRLogger.getLogger().error(e.getMessage()); - } - - return new String[0]; - } - - ; - - public String[] getProcedureColumns(String name) throws Exception { - String[] columns; - HashMap para = new HashMap(); - para.put("op", "fr_remote_design"); - para.put("cmd", "list_sp_columns_name"); - para.put("name", name); - HttpClient client = createHttpMethod(para); - try { - InputStream input = execute4InputStream(client); - if (input == null) { - return ArrayUtils.EMPTY_STRING_ARRAY; - } - columns = DavXMLUtils.readXMLSPColumns(input); - return columns; - } catch (Exception e) { - FRLogger.getLogger().error(e.getMessage()); - } - return new String[0]; - - } /** * 输出日志信息 * * @throws Exception */ + @Override public void printLogMessage() throws Exception { ByteArrayOutputStream out = new ByteArrayOutputStream(); - HashMap para = new HashMap(); + HashMap para = new HashMap<>(); para.put("op", "fr_remote_design"); para.put("cmd", "get_log_message"); @@ -1844,114 +683,27 @@ public class RemoteEnv extends AbstractEnv { } LogRecordTime[] records = LogUtils.readXMLLogRecords(input); for (LogRecordTime logRecordTime : records) { - DesignerLogHandler.getInstance().printRemoteLog(logRecordTime); + //TODO } } - public String getUserID() { - return userID; - } - - //TODO: - - /** - * 预览存储过程 - * - * @param storeProcedure 存储过程 - * @param parameterMap 参数map - * @param rowCount 行数 - * @return 返回取到的存储过程 - */ @Override - public ProcedureDataModel[] previewProcedureDataModel(StoreProcedure storeProcedure, Map parameterMap, int rowCount) { - ByteArrayOutputStream out = new ByteArrayOutputStream(); - - // 把tableData写成xml文件到out - DavXMLUtils.writeXMLFileStoreProcedureAndSource(storeProcedure, out); - - // 把parameterMap转成JSON格式的字符串 - JSONObject jo = new JSONObject(parameterMap); - String jsonParameter = jo.toString(); - - try { - HashMap para = new HashMap(); - para.put("op", "fr_remote_design"); - para.put("cmd", "list_sp"); - para.put("pars", jsonParameter); - - InputStream input = postBytes2ServerB(out.toByteArray(), para); - if (input == null) { - return null; - } - - TableData[] tableDatas = DavXMLUtils.readXMLTableDataArray(input); - if (tableDatas == null || tableDatas.length == 0) { - return new ProcedureDataModel[0]; - } - ProcedureDataModel[] procedureDataModels = new ProcedureDataModel[tableDatas.length]; - for (int i = 0; i < tableDatas.length; i++) { - if (tableDatas[i] instanceof EmbeddedTableData) { - procedureDataModels[i] = ((EmbeddedTableData) tableDatas[i]).trans2ProcedureDataModel(); - } - } - return procedureDataModels; - - - } catch (Exception e) { - FRLogger.getLogger().error(e.getMessage()); - } - return new ProcedureDataModel[0]; - } - - - public String getAppName() { - return "WebReport"; - } - - /** - * 是否为Oracle数据连接 - * - * @param database 数据连接 - * @return 是返回true - * @throws Exception - */ - public boolean isOracle(Connection database) throws Exception { - ByteArrayOutputStream out = new ByteArrayOutputStream(); - DavXMLUtils.writeXMLFileDatabaseConnection(database, out); - HashMap para = new HashMap(); - para.put("op", "fr_remote_design"); - para.put("cmd", "design_get_isOracle"); - InputStream input = postBytes2ServerB(out.toByteArray(), para); - if (input == null) { - return true; - } - return DavXMLUtils.readXMLBoolean(input); - } - public String[] getSupportedTypes() { return FILE_TYPE; } - /** - * 在模板面板中是否支持增加打开所在文件夹、重命名、删除三个工具栏选项 - * - * @return 不支持返回false - */ - public boolean isSupportLocalFileOperate() { - return false; - } - /** * 判断是否有文件夹权限 * * @param path 路径 * @return 有权限则返回true */ + @Override public boolean hasFileFolderAllow(String path) { HttpClient client = null; try { - HashMap para = new HashMap(); + HashMap para = new HashMap<>(); para.put("op", "fs_remote_design"); para.put("cmd", "design_filefolder_allow"); para.put("current_uid", this.createUserID()); @@ -1965,48 +717,13 @@ public class RemoteEnv extends AbstractEnv { } return Boolean.valueOf(IOUtils.inputStream2String(input, EncodeConstants.ENCODING_UTF_8)); } catch (Exception e) { - FRLogger.getLogger().error(e.getMessage()); + FRContext.getLogger().error(e.getMessage()); return false; } } - /** - * 是否是管理员身份 - * - * @return 是则返回true - */ - public boolean isRoot() { - return isRoot; - } - - /** - * 是否为压缩包部署 - * - * @return 是则返回true - */ - @Override - public boolean isPackDeploy() { - return false; - } - @Override - public String getDesignerVersion() throws Exception { - HashMap para = new HashMap(); - para.put("op", "fr_remote_design"); - para.put("cmd", "design_get_designer_version"); - para.put("user", user); - para.put("password", getEncodedPassword()); - - HttpClient client = createHttpMethod(para, true); - try { - return stream2String(execute4InputStream(client)); - } catch (Exception e) { - FRLogger.getLogger().error(e.getMessage()); - } - return null; - } - public InputStream getDataSourceInputStream(String filePath) throws Exception { return readBean(filePath, "datasource"); } @@ -2016,7 +733,7 @@ public class RemoteEnv extends AbstractEnv { public ArrayList getAllRole4Privilege(boolean isFS) { ArrayList allRoleList = new ArrayList(); try { - HashMap para = new HashMap(); + HashMap para = new HashMap<>(); para.put("op", "fr_remote_design"); para.put("cmd", "get_all_role"); para.put("isFS", String.valueOf(isFS)); @@ -2034,20 +751,10 @@ public class RemoteEnv extends AbstractEnv { return allRoleList; } - @Override - public String getLicName() { - return License.FILE_NAME; - } - - @Override - public void setLicName(String licName) { - //do nth - } - - /** * 获取当前env的build文件路径 */ + @Override public String getBuildFilePath() { return StringUtils.isEmpty(buildFilePath) ? ResourceConstants.BUILD_PATH : buildFilePath; } @@ -2055,6 +762,7 @@ public class RemoteEnv extends AbstractEnv { /** * 设置当前env的build文件路径 */ + @Override public void setBuildFilePath(String buildFilePath) { this.buildFilePath = buildFilePath; } @@ -2065,8 +773,9 @@ public class RemoteEnv extends AbstractEnv { * @param sourceText 源代码 * @return 编译信息,有可能是成功信息,也有可能是出错或者警告信息 */ + @Override public JavaCompileInfo compilerSourceCode(String sourceText) throws Exception { - HashMap para = new HashMap(); + HashMap para = new HashMap<>(); para.put("op", "fr_remote_design"); para.put("cmd", "design_compile_source_code"); InputStream in = postBytes2ServerB(sourceText.getBytes(EncodeConstants.ENCODING_UTF_8), para); @@ -2085,70 +794,69 @@ public class RemoteEnv extends AbstractEnv { @Override public String pluginServiceAction(String serviceID, String req) throws Exception { - HashMap para = new HashMap(); + HashMap para = new HashMap<>(); para.put("op", "fr_remote_design"); para.put("cmd", "design_get_plugin_service_data"); para.put("serviceID", serviceID); para.put("req", req); - HttpClient client = createHttpMethod(para); //jim :加上user,远程设计点击预览时传递用户角色信息 + //jim :加上user,远程设计点击预览时传递用户角色信息 + HttpClient client = createHttpMethod(para); InputStream inputStream = execute4InputStream(client); return IOUtils.inputStream2String(inputStream); } /** * 远程不启动,使用虚拟服务 + *

* - * @param serviceID + * @param serviceID serviceID */ @Override public void pluginServiceStart(String serviceID) { } @Override - public File[] loadREUFile() throws Exception { - File target = new File(CacheManager.getProviderInstance().getCacheDirectory(), - ShareConstants.DIR_SHARE_CACHE); - StableUtils.deleteFile(target); - StableUtils.mkdirs(target); - File cacheDir = null; - File zip = null; - OutputStream out = null; + public String[] loadREUFile() { + ResourceIOUtils.delete(StableUtils.pathJoin( + CacheManager.getProviderInstance().getCacheDirectory().getAbsolutePath(), + ShareConstants.DIR_SHARE_CACHE)); + + String zipFilePath = null; try { - HashMap para = new HashMap(); + HashMap para = new HashMap<>(); para.put("op", "fr_remote_design"); para.put("cmd", "design_read_reufile"); para.put("current_uid", this.createUserID()); para.put("currentUsername", this.getUser()); HttpClient client = createHttpMethod(para); - InputStream input = client.getResponseStream();//拿到服务端传过来的整个共享文件夹的压缩文件的文件流 - zip = new File(StableUtils.pathJoin(CacheManager.getProviderInstance().getCacheDirectory().getAbsolutePath()), "share.zip"); - cacheDir = new File(StableUtils.pathJoin(CacheManager.getProviderInstance().getCacheDirectory().getAbsolutePath()), ShareConstants.DIR_SHARE_CACHE); - StableUtils.deleteFile(cacheDir); - StableUtils.mkdirs(cacheDir); - StableUtils.makesureFileExist(zip); - out = new FileOutputStream(zip); - IOUtils.copyBinaryTo(input, out);//放到本地缓存目录下 - - IOUtils.unzip(zip, cacheDir.getAbsolutePath(), EncodeConstants.ENCODING_GBK);//先解压到临时目录 - if (cacheDir.exists() && cacheDir.isDirectory()) { - return cacheDir.listFiles(new FilenameFilter() { - public boolean accept(File file, String s) { - return s.endsWith("reu"); - } - }); - } + //拿到服务端传过来的整个共享文件夹的压缩文件的文件流 + InputStream input = client.getResponseStream(); + + zipFilePath = StableUtils.pathJoin(CacheManager.getProviderInstance().getCacheDirectory().getAbsolutePath(), "share.zip"); + String cacheDir = StableUtils.pathJoin(CacheManager.getProviderInstance().getCacheDirectory().getAbsolutePath(), ShareConstants.DIR_SHARE_CACHE); + + ResourceIOUtils.write(zipFilePath, input); + ResourceIOUtils.unzip(zipFilePath, cacheDir, EncodeConstants.ENCODING_GBK); + + + return ResourceIOUtils.listWithFullPath(cacheDir, new Filter() { + @Override + public boolean accept(String s) { + return s.endsWith(ProjectConstants.REU); + } + }); } catch (Exception e) { FRContext.getLogger().error(e.getMessage()); } finally { - if (out != null) { - out.flush(); - out.close(); + + if (zipFilePath != null) { + ResourceIOUtils.delete(zipFilePath); } - StableUtils.deleteFile(zip); } - return new File[0]; + + return new String[0]; } @Override @@ -2161,7 +869,7 @@ public class RemoteEnv extends AbstractEnv { String shareXMLName = StableUtils.pathJoin(tempFile.getAbsolutePath(), ShareConstants.NAME_XML_MODULE); String helpXMLName = StableUtils.pathJoin(tempFile.getAbsolutePath(), ShareConstants.NAME_XML_HELP); try { - HashMap para = new HashMap(); + HashMap para = new HashMap<>(); para.put("op", "fr_remote_design"); para.put("cmd", "design_install_reufile"); para.put("current_uid", this.createUserID()); @@ -2188,7 +896,7 @@ public class RemoteEnv extends AbstractEnv { return true; } try { - HashMap para = new HashMap(); + HashMap para = new HashMap<>(); para.put("op", "fr_remote_design"); para.put("cmd", "design_remove_reufile"); para.put("current_uid", this.createUserID()); @@ -2205,50 +913,25 @@ public class RemoteEnv extends AbstractEnv { @Override public String getSharePath() { - return StringUtils.EMPTY; - } - - public void doWhenServerShutDown() { - - } - - @Override - public boolean isLocalEnv() { - - return false; - } - - @Override - public boolean hasPluginServiceStarted(String key) { - - return true; - } - - @Override - public JSONArray getPluginStatus() { - try { - HashMap para = new HashMap(); - para.put("op", "plugin"); - para.put("cmd", "get_status"); + HashMap para = new HashMap<>(); + para.put("op", "fr_remote_design"); + para.put("cmd", "design_get_share_path"); para.put("current_uid", this.createUserID()); para.put("currentUsername", this.getUser()); HttpClient client = createHttpMethod(para); InputStream input = execute4InputStream(client); - return new JSONArray(stream2String(input)); + return stream2String(input); } catch (Exception e) { - return JSONArray.create(); + return StringUtils.EMPTY; } } - public String post(HashMap para, boolean isSignIn) { - try { - HttpClient client = createHttpMethod(para, isSignIn); - return stream2String(execute4InputStream(client)); - } catch (Exception e) { - FRContext.getLogger().error(e.getMessage()); - return StringUtils.EMPTY; - } + + @Override + public boolean hasPluginServiceStarted(String key) { + + return true; } -} +} \ No newline at end of file diff --git a/designer-base/src/com/fr/env/RemoteEnvPane.java b/designer-base/src/com/fr/env/RemoteEnvPane.java index 12fb4d2b4..77ae0b451 100644 --- a/designer-base/src/com/fr/env/RemoteEnvPane.java +++ b/designer-base/src/com/fr/env/RemoteEnvPane.java @@ -465,11 +465,8 @@ public class RemoteEnvPane extends BasicBeanPane { } private boolean testConnection() { - RemoteEnv env = new RemoteEnv(); String url = remoteEnvURL.getURL(); - env.setPath(url); - env.setUser(usernameInput.getText()); - env.setPassword(new String(passwordInput.getPassword())); + RemoteEnv env = new RemoteEnv(url, usernameInput.getText(), new String(passwordInput.getPassword())); boolean connect = false; try { if (StringUtils.isNotEmpty(url)) { diff --git a/designer-base/src/com/fr/env/SignIn.java b/designer-base/src/com/fr/env/SignIn.java index 8cb021a82..f876302ba 100644 --- a/designer-base/src/com/fr/env/SignIn.java +++ b/designer-base/src/com/fr/env/SignIn.java @@ -1,43 +1,61 @@ package com.fr.env; -import com.fr.base.Env; import com.fr.base.FRContext; +import com.fr.base.env.EnvContext; +import com.fr.base.env.resource.EnvConfigUtils; +import com.fr.base.env.resource.RemoteEnvConfig; +import com.fr.core.env.EnvConfig; +import com.fr.core.env.EnvEvents; +import com.fr.dav.LocalEnv; import com.fr.design.utils.DesignUtils; +import com.fr.event.Event; +import com.fr.event.EventDispatcher; +import com.fr.event.Listener; +import com.fr.event.Null; import com.fr.general.ComparatorUtils; -import com.fr.general.env.EnvContext; +import com.fr.general.Inter; + +import javax.swing.JOptionPane; +import javax.swing.UIManager; public class SignIn { - public static Env lastSelectedEnv;// 记录最后登录的Env + + static { + EventDispatcher.listen(EnvEvents.CONNECTION_ERROR, new Listener() { + @Override + public void on(Event event, Null param) { + if (JOptionPane.showConfirmDialog(null, Inter.getLocText("FR-Remote_Connect2Server_Again"), UIManager.getString("OptionPane.titleText"), JOptionPane.YES_NO_OPTION) + == JOptionPane.OK_OPTION) { + try { + EnvContext.signIn(EnvContext.currentEnv()); + } catch (Exception e) { + FRContext.getLogger().error(e.getMessage()); + } + } + } + }); + } /** * 注册入环境 * @param selectedEnv 选择的环境 * @throws Exception 异常 */ - public static void signIn(Env selectedEnv) throws Exception { - boolean validServer; - signOutOldEnv(selectedEnv); - selectedEnv.signIn(); - validServer = true; - if (validServer) { - DesignUtils.switchToEnv(selectedEnv); - lastSelectedEnv = selectedEnv; + public static void signIn(EnvConfig selectedEnv) throws Exception { + if (EnvContext.currentEnv() != null && !ComparatorUtils.equals(EnvContext.currentEnv(), selectedEnv)) { + EnvContext.signOut(); } + EnvContext.signIn(selectedEnv); + DesignUtils.switchToEnv(trans(selectedEnv)); } - private static void signOutOldEnv(Env newEnv) { - // 环境相同直接返回,避免浪费过多时间 - if (lastSelectedEnv == null || ComparatorUtils.equals(lastSelectedEnv, newEnv)) { - return; - } - try { - EnvContext.fireBeforeSignOut(); - lastSelectedEnv.signOut(); - EnvContext.fireAfterSignOut(); - } catch (Exception e) { - FRContext.getLogger().error(e.getMessage(), e); + private static com.fr.base.Env trans(EnvConfig env) { + if (env instanceof RemoteEnvConfig) { + return new RemoteEnv(env.getPath(), EnvConfigUtils.getUsername(env), EnvConfigUtils.getPassword(env)); + } else { + return new LocalEnv(); } } -} +} \ No newline at end of file diff --git a/designer-base/src/com/fr/start/server/FRTomcat.java b/designer-base/src/com/fr/start/server/FRTomcat.java index 46c529697..b7519b98a 100644 --- a/designer-base/src/com/fr/start/server/FRTomcat.java +++ b/designer-base/src/com/fr/start/server/FRTomcat.java @@ -20,9 +20,9 @@ public class FRTomcat extends Tomcat{ public Context addWebapp(String contextPath, String docBase) throws ServletException { - silence(host, contextPath); + silence(getHost(), contextPath); - Context ctx = createContext(host, contextPath); + Context ctx = createContext(getHost(), contextPath); if (ctx instanceof StandardContext) { ((StandardContext)ctx).setDelegate(true); } @@ -37,10 +37,10 @@ public class FRTomcat extends Tomcat{ ctxCfg.setDefaultWebXml(noDefaultWebXmlPath()); - if (host == null) { + if (getHost() == null) { getHost().addChild(ctx); } else { - host.addChild(ctx); + getHost().addChild(ctx); } return ctx; diff --git a/designer-realize/src/com/fr/start/Designer4Debug.java b/designer-realize/src/com/fr/start/Designer4Debug.java index 0786fee6f..6448b70bc 100644 --- a/designer-realize/src/com/fr/start/Designer4Debug.java +++ b/designer-realize/src/com/fr/start/Designer4Debug.java @@ -5,7 +5,7 @@ package com.fr.start; */ public class Designer4Debug { - public static void main(String... args) { - org.swingexplorer.Launcher.main(new String[]{"com.fr.start.Designer"}); - } +// public static void main(String... args) { +// org.swingexplorer.Launcher.main(new String[]{"com.fr.start.Designer"}); +// } } From 39a1bcb6a245735b22ab2c05f55728ecea43a297 Mon Sep 17 00:00:00 2001 From: hzzz Date: Fri, 25 May 2018 15:32:50 +0800 Subject: [PATCH 3/9] merge --- .../loghandler/socketio/DesignerSocketIO.java | 90 +++++++++++++++++++ 1 file changed, 90 insertions(+) create mode 100644 designer-base/src/com/fr/design/mainframe/loghandler/socketio/DesignerSocketIO.java diff --git a/designer-base/src/com/fr/design/mainframe/loghandler/socketio/DesignerSocketIO.java b/designer-base/src/com/fr/design/mainframe/loghandler/socketio/DesignerSocketIO.java new file mode 100644 index 000000000..2444ae3d1 --- /dev/null +++ b/designer-base/src/com/fr/design/mainframe/loghandler/socketio/DesignerSocketIO.java @@ -0,0 +1,90 @@ +package com.fr.design.mainframe.loghandler.socketio; + +import com.fr.base.env.EnvContext; +import com.fr.base.env.resource.LocalEnvConfig; +import com.fr.core.env.EnvConfig; +import com.fr.core.env.EnvConstants; +import com.fr.core.env.EnvEvents; +import com.fr.decision.webservice.utils.DecisionServiceConstants; +import com.fr.design.mainframe.loghandler.DesignerLogHandler; +import com.fr.event.Event; +import com.fr.event.EventDispatcher; +import com.fr.event.Listener; +import com.fr.event.Null; +import com.fr.general.LogRecordTime; +import com.fr.general.LogUtils; +import com.fr.log.FineLoggerFactory; +import com.fr.third.guava.base.Optional; +import com.fr.web.WebSocketConfig; +import io.socket.client.IO; +import io.socket.client.Socket; +import io.socket.emitter.Emitter; + +import java.io.ByteArrayInputStream; +import java.net.URI; +import java.net.URL; + +public class DesignerSocketIO { + + private static Optional socketIO = Optional.absent(); + + private static final Emitter.Listener printLog = new Emitter.Listener() { + @Override + public void call(Object... objects) { + //TODO 这里要测试一下类型 + String object = (String) objects[0]; + try { + LogRecordTime[] logRecordTimes = LogUtils.readXMLLogRecords(new ByteArrayInputStream(object.getBytes())); + for (LogRecordTime logRecordTime : logRecordTimes) { + DesignerLogHandler.getInstance().printRemoteLog(logRecordTime); + } + } catch (Exception e) { + FineLoggerFactory.getLogger().error(e.getMessage(), e); + } + } + }; + + static { + EventDispatcher.listen(EnvEvents.AFTER_SIGN_OUT, new Listener() { + @Override + public void on(Event event, Null param) { + if (socketIO.isPresent()) { + socketIO.get().close(); + socketIO = Optional.absent(); + } + } + }); + EventDispatcher.listen(EnvEvents.AFTER_SIGN_IN, new Listener() { + @Override + public void on(Event event, Null param) { + updateSocket(); + } + }); + } + + public static void init() { + updateSocket(); + } + + private static void updateSocket() { + EnvConfig env = EnvContext.currentEnv(); + if (env instanceof LocalEnvConfig) { + return; + } + + try { + String uri = String.format("http://%s:%s/%s?%s=%s", + new URL(env.getPath()).getHost(), + WebSocketConfig.getInstance().getPort(), + EnvConstants.WS_NAMESPACE, + DecisionServiceConstants.WEB_SOCKET_TOKEN_NAME, + EnvContext.currentToken()); + + socketIO = Optional.of(IO.socket(new URI(uri))); + socketIO.get().on(EnvConstants.WS_LOGRECORD, printLog); + socketIO.get().connect(); + } catch (Exception e) { + FineLoggerFactory.getLogger().error(e.getMessage(), e); + } + } +} \ No newline at end of file From d6258df530d13ffe36dbd04efa64b0b76f184fcf Mon Sep 17 00:00:00 2001 From: hzzz Date: Fri, 25 May 2018 17:01:09 +0800 Subject: [PATCH 4/9] start designer socket client --- .../src/com/fr/start/module/DesignerModuleActivator.java | 3 +++ 1 file changed, 3 insertions(+) diff --git a/designer-realize/src/com/fr/start/module/DesignerModuleActivator.java b/designer-realize/src/com/fr/start/module/DesignerModuleActivator.java index 7a8becd11..b6abbdf85 100644 --- a/designer-realize/src/com/fr/start/module/DesignerModuleActivator.java +++ b/designer-realize/src/com/fr/start/module/DesignerModuleActivator.java @@ -1,5 +1,6 @@ package com.fr.start.module; +import com.fr.design.mainframe.loghandler.socketio.DesignerSocketIO; import com.fr.design.module.DesignerModule; import com.fr.general.ModuleContext; import com.fr.locale.InterMutableKey; @@ -20,6 +21,8 @@ public class DesignerModuleActivator extends Activator implements Prepare { ModuleContext.registerModuleListener(getModule().upFindSingleton(ModuleListener.class)); ModuleContext.startModule(DesignerModule.class.getName()); ModuleContext.clearModuleListener(); + + DesignerSocketIO.init(); } @Override From a1fdd0b66ec6477ef8cece6d5225b1c859ae964e Mon Sep 17 00:00:00 2001 From: hzzz Date: Tue, 29 May 2018 15:36:16 +0800 Subject: [PATCH 5/9] merge --- .../loghandler/socketio/DesignerSocketIO.java | 4 +- .../RemoteDesignAuthorityManagerAction.java | 7 +- .../src/com/fr/design/utils/DesignUtils.java | 105 +- .../fr/env/DesignAuthorityConfigurable.java | 2 +- designer-base/src/com/fr/env/RemoteEnv.java | 1350 ++++++++++++++++- .../src/com/fr/env/RemoteEnvUtils.java | 2 +- designer-base/src/com/fr/env/SignIn.java | 2 +- .../AccessibleBodyWatermarkEditor.java | 8 + .../actions/report/ReportWatermarkAction.java | 8 + 9 files changed, 1369 insertions(+), 119 deletions(-) diff --git a/designer-base/src/com/fr/design/mainframe/loghandler/socketio/DesignerSocketIO.java b/designer-base/src/com/fr/design/mainframe/loghandler/socketio/DesignerSocketIO.java index 2444ae3d1..14be4cfb1 100644 --- a/designer-base/src/com/fr/design/mainframe/loghandler/socketio/DesignerSocketIO.java +++ b/designer-base/src/com/fr/design/mainframe/loghandler/socketio/DesignerSocketIO.java @@ -47,7 +47,7 @@ public class DesignerSocketIO { static { EventDispatcher.listen(EnvEvents.AFTER_SIGN_OUT, new Listener() { @Override - public void on(Event event, Null param) { + public void on(Event event, Null param) { if (socketIO.isPresent()) { socketIO.get().close(); socketIO = Optional.absent(); @@ -56,7 +56,7 @@ public class DesignerSocketIO { }); EventDispatcher.listen(EnvEvents.AFTER_SIGN_IN, new Listener() { @Override - public void on(Event event, Null param) { + public void on(Event event, Null param) { updateSocket(); } }); diff --git a/designer-base/src/com/fr/design/remote/action/RemoteDesignAuthorityManagerAction.java b/designer-base/src/com/fr/design/remote/action/RemoteDesignAuthorityManagerAction.java index 39d5921d6..da2122cb4 100644 --- a/designer-base/src/com/fr/design/remote/action/RemoteDesignAuthorityManagerAction.java +++ b/designer-base/src/com/fr/design/remote/action/RemoteDesignAuthorityManagerAction.java @@ -48,11 +48,8 @@ public class RemoteDesignAuthorityManagerAction extends UpdateAction { public void doOk() { DesignAuthority[] authorities = managerPane.update(); if (!FRContext.getCurrentEnv().isLocalEnv()) { - try { - ((RemoteEnv) FRContext.getCurrentEnv()).updateAuthorities(authorities); - } catch (Exception exception) { - FRContext.getLogger().error(exception.getMessage()); - } + boolean success = ((RemoteEnv) FRContext.getCurrentEnv()).updateAuthorities(authorities); + FRContext.getLogger().info("update remote design authority: " + success); } } diff --git a/designer-base/src/com/fr/design/utils/DesignUtils.java b/designer-base/src/com/fr/design/utils/DesignUtils.java index 469e7fd1a..25be2df48 100644 --- a/designer-base/src/com/fr/design/utils/DesignUtils.java +++ b/designer-base/src/com/fr/design/utils/DesignUtils.java @@ -1,11 +1,11 @@ package com.fr.design.utils; import com.fr.base.BaseUtils; -import com.fr.base.ServerConfig; import com.fr.base.Env; import com.fr.base.EnvException; import com.fr.base.FRContext; import com.fr.base.FeedBackInfo; +import com.fr.base.ServerConfig; import com.fr.base.Utils; import com.fr.base.remote.RemoteDeziConstants; import com.fr.dav.DavXMLUtils; @@ -23,6 +23,7 @@ import com.fr.general.FRLogger; import com.fr.general.GeneralContext; import com.fr.general.Inter; import com.fr.general.http.HttpClient; +import com.fr.security.JwtUtils; import com.fr.stable.ArrayUtils; import com.fr.stable.CodeUtils; import com.fr.stable.EncodeConstants; @@ -30,8 +31,11 @@ import com.fr.stable.StableUtils; import com.fr.stable.StringUtils; import com.fr.start.StartServer; -import javax.swing.*; -import java.awt.*; +import javax.swing.JOptionPane; +import javax.swing.SwingUtilities; +import javax.swing.UIManager; +import java.awt.Desktop; +import java.awt.Font; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.ByteArrayInputStream; @@ -74,7 +78,8 @@ public class DesignUtils { /** * 通过端口是否被占用判断设计器有没有启动 - * s + * s + * * @return 启动了返回true */ public static boolean isStarted() { @@ -120,11 +125,12 @@ public class DesignUtils { } /** - *建立监听端口 - * @param startPort 端口 - * @param suffixs 文件后缀 + * 建立监听端口 + * + * @param startPort 端口 + * @param suffixs 文件后缀 */ - public static void creatListeningServer(final int startPort,final String[] suffixs) { + public static void creatListeningServer(final int startPort, final String[] suffixs) { Thread serverSocketThread = new Thread() { public void run() { ServerSocket serverSocket = null; @@ -146,7 +152,7 @@ public class DesignUtils { String path = f.getAbsolutePath(); boolean isMatch = false; - for(int i= 0; i threadLocal = new ThreadLocal<>(); + private boolean isReadTimeOut = false; private String buildFilePath; - private final RemoteEnvConfig env; + + public RemoteEnv() { + this.clock = new Clock(this); + } public RemoteEnv(String path, String userName, String password) { - env = new RemoteEnvConfig(path, userName, password); + this(); + this.path = path; + this.user = userName; + this.password = password; } /** @@ -85,7 +105,11 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl */ @Override public String getPath() { - return env.getPath(); + return this.path; + } + + public void setPath(String s) { + this.path = s; } /** @@ -93,16 +117,76 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl */ @Override public String getUser() { - return env.getUsername(); + return user; } + public void setUser(String user) { + this.user = user; + clearUserID(); + } public String getPassword() { - return env.getPassword(); + return password; } + /** + * 修复密码中包含特殊字符,无法登录的问题 + * + * @return + */ + private String getEncodedPassword() { + try { + return URLEncoder.encode(password, "UTF-8"); + } catch (UnsupportedEncodingException e) { + return password; + } + } + + public void setPassword(String password) { + this.password = password; + clearUserID(); + } - private HttpClient createHttpMethod(HashMap para) throws EnvException, UnsupportedEncodingException { + public Clock getClock() { + return this.clock; + } + + public void setClock(Clock clock) { + this.clock = clock; + } + + private void clearUserID() { + this.userID = null; + } + + public void setThreadLocal(String value) { + synchronized (this) { + threadLocal.set(value); + } + + } + + public String getThreadLocal() { + return threadLocal.get(); + } + + /** + * 所有与服务器端交互前,都要调用这个方法生成UserID + */ + private String createUserID() throws EnvException { + // 如果登录之后userID还是null + if (this.userID == null) { + if (!VT4FR.RemoteDesign.support() && licNotSupport <= 0) { + licNotSupport++; + JOptionPane.showMessageDialog(null, Inter.getLocText("FR-Lic_does_not_Support_Remote")); + } + throw new EnvException(Inter.getLocText("Env-Invalid_User_and_Password")); + } + + return this.userID; + } + + private HttpClient createHttpMethod(HashMap para) throws EnvException { return createHttpMethod(para, false); } @@ -110,9 +194,9 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl * 根据nameValuePairs,也就是参数对,生成PostMethod */ private HttpClient createHttpMethod(HashMap para, boolean isSignIn) throws EnvException { - String methodPath = getPath(); + String methodPath = this.path; if (!isSignIn) { - methodPath = methodPath + "?id=" + EnvContext.currentToken(); + methodPath = methodPath + "?id=" + createUserID(); } HttpClient client = new HttpClient(methodPath, para); /* @@ -129,14 +213,10 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl * 根据nameValuePairs,也就是参数对,生成PostMethod,不同之处在于,参数拼在path后面,不是method.addParameters */ private HttpClient createHttpMethod2(HashMap para) throws EnvException, UnsupportedEncodingException { - String methodPath = getPath() + '?' + "id=" + createUserID(); + String methodPath = path + '?' + "id=" + createUserID(); return new HttpClient(methodPath); } - private String createUserID() { - return EnvContext.currentToken(); - } - /* * Read the response body. @@ -192,6 +272,17 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl } } + private void doWithTimeOutException() { + boolean isNotNeedTip = ComparatorUtils.equals(getThreadLocal(), "HEART_BEAT") || ComparatorUtils.equals(getThreadLocal(), "LOG_MESSAGE"); + if (!isReadTimeOut && !isNotNeedTip) { + isReadTimeOut = true; + JOptionPane.showMessageDialog(DesignerContext.getDesignerFrame(), Inter.getLocText(new String[]{"Data", "read_time_out"})); + isReadTimeOut = false; + } + FRContext.getLogger().info("Connection reset "); + } + + /** * nameValuePairs,这个参数要接着this.path,拼成一个URL,否则服务器端req.getParameter是无法得到的 * @@ -240,28 +331,127 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl return sb.toString(); } + /** + * 测试连接服务器 + * + * @return 测试连接成功返回true + * @throws Exception 异常 + */ public boolean testServerConnection() throws Exception { - throw new UnsupportedOperationException("unsupport now"); -// return testConnection(true, true, DesignerContext.getDesignerFrame()); + return testConnection(true, true, DesignerContext.getDesignerFrame()); } + /** + * 测试当前配置是否正确 + * + * @return 链接是否成功 + * @throws Exception 异常 + */ @Override public boolean testServerConnectionWithOutShowMessagePane() throws Exception { - throw new UnsupportedOperationException("unsupport now"); + return testConnection(false, true, DesignerContext.getDesignerFrame()); } + /** + * 主要用于在环境配置面板中的测试连接按钮时,不要注册进远程环境 + * + * @param messageParentPane 弹框的依赖的面板 + * @return 是否测试连接成功 + * @throws Exception 异常 + */ public boolean testConnectionWithOutRegisteServer(Component messageParentPane) throws Exception { - throw new UnsupportedOperationException("unsupport now"); + return testConnection(true, false, messageParentPane); + } + + + private boolean testConnection(boolean needMessage, boolean isRegisteServer, Component parentComponent) throws Exception { + checkArgument(parentComponent instanceof Component, "parentComponent should be a java.awt.component"); + Component component = parentComponent; + String url = String.format("%s/connection", EnvConstants.toDecisionPath(getPath())); + ImmutableMap params = ImmutableMap.of( + "version", (Object) ProductConstants.DESIGNER_VERSION + ); + ImmutableMap headers = ImmutableMap.of( + EnvConstants.USERNAME, getUser(), + EnvConstants.PWD, getPassword()); + String res = HttpToolbox.post(url, params, headers); + if (res == null) { + if (needMessage) { + JOptionPane.showMessageDialog(component, Inter.getLocText("Datasource-Connection_failed")); + } + return false; + } else if (ComparatorUtils.equals(res, "true")) { + return true; + } else { + if (ComparatorUtils.equals(res, EnvConstants.AUTH_ERROR)) { + JOptionPane.showMessageDialog(component, + Inter.getLocText(new String[]{"Datasource-Connection_failed", "Registration-User_Name", "Password", "Error"}, new String[]{",", "", "", "!"}) + , Inter.getLocText("FR-Server-All_Error"), JOptionPane.ERROR_MESSAGE); + return false; + } else { + if (ComparatorUtils.equals(res, EnvConstants.WAR_ERROR)) { + if (needMessage) { + JOptionPane.showMessageDialog(component, Inter.getLocText(new String[]{"Datasource-Connection_failed", "NS-war-remote"}, new String[]{",", "!"})); + } else { + FineLoggerFactory.getLogger().info(Inter.getLocText(new String[]{"Datasource-Connection_failed", "NS-war-remote"}, new String[]{",", "!"})); + } + return false; + } else { + if (needMessage) { + JOptionPane.showMessageDialog(component, Inter.getLocText(new String[]{"Datasource-Connection_failed", "Version-does-not-support"}, new String[]{",", "!"})); + } else { + FineLoggerFactory.getLogger().info(Inter.getLocText(new String[]{"Datasource-Connection_failed", "Version-does-not-support"}, new String[]{",", "!"})); + } + return false; + } + } + } + } + + private void extraChangeEnvPara() { + //在env连接之前, 加载一下不依赖env的插件. 看看需不需要改变参数. + DesignerEnvProcessor envProcessor = ExtraDesignClassManager.getInstance().getSingle(DesignerEnvProcessor.XML_TAG); + if (envProcessor != null) { + this.path = envProcessor.changeEnvPathBeforeConnect(user, password, path); + } } private void setHttpsParas() { - if (getPath().startsWith(HTTPS_PREFIX) && System.getProperty(CERT_KEY) == null) { + if (path.startsWith(HTTPS_PREFIX) && System.getProperty(CERT_KEY) == null) { DesignerEnvManager envManager = DesignerEnvManager.getEnvManager(); System.setProperty(CERT_KEY, envManager.getCertificatePath()); System.setProperty(PWD_KEY, envManager.getCertificatePass()); } } + + /** + * 心跳访问,用来更新当前用户的访问时间 + * + * @throws Exception e + */ + public void heartBeatConnection() throws Exception { + HashMap para = new HashMap<>(); + para.put("op", "fr_remote_design"); + para.put("cmd", "heart_beat"); + para.put("user", user); + + HttpClient client = createHttpMethod(para); + execute4InputStream(client); + + //这做法不好, 30秒刷一次, 刷新的时候会重新构建树, 构建完会把子节点都收缩起来, 效果太差. + //为什么不保存刷新前树的伸缩状态, 因为刷新后的树和刷新前的树的结构未必是一致的. + + //服务器通知客户端更新左上角文件树面板 +// try { +// if (ComparatorUtils.equals(stream2String(execute4InputStream(method)), "true")) { +// DesignerFrameFileDealerPane.getInstance().refresh(); +// } +// } catch (Exception e) { +// FRContext.getLogger().error(e.getMessage()); +// } + } + /** * 返回描述该运行环境的名字 * @@ -272,6 +462,193 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl return Inter.getLocText("Env-Remote_Server"); } + /** + * 登录,返回userID + */ + @Override + public void signIn() throws Exception { + throw new UnsupportedOperationException("unsupport now"); + } + + + private void startLogTimer() { + if (logTimer != null) { + logTimer.cancel(); + } + + logTimer = new Timer(); + logTimer.schedule(new TimerTask() { + @Override + public void run() { + try { + RemoteEnv.this.setThreadLocal("LOG_MESSAGE"); + FRContext.getCurrentEnv().printLogMessage(); + } catch (Exception e) { + FRContext.getLogger().info(e.getMessage()); + } + } + }, 10000, 10000); + } + + private void stopLogTimer() { + if (logTimer != null) { + logTimer.cancel(); + logTimer = null; + } + } + + /** + * 根据userID sign out + * + * @return 成功签出返回true + * @throws Exception e + */ + @Override + public boolean signOut() throws Exception { + if (userID == null) { + return true; + } + stopLogTimer(); + // richer:登出的时候就把定时发送的时钟停掉 + clock.stop(); + // richer:把轮训使用的定时器也去掉 + timer.cancel(); + + HashMap para = new HashMap<>(); + para.put("op", "fr_remote_design"); + para.put("cmd", "r_sign_out"); + para.put("id", userID); + + return simulaRPC(para, false + ); + } + + protected boolean simulaRPC(HashMap para, boolean isSignIn) throws Exception { + HttpClient client = createHttpMethod(para, isSignIn); + + // execute method取到input stream再转成String + String resJSON = null; + try { + resJSON = stream2String(execute4InputStream(client)); + } catch (Exception e) { + FRContext.getLogger().error(e.getMessage()); + } + + if (resJSON == null) { + return false; + } + if (resJSON.contains("RegistEditionException")) { + JOptionPane.showMessageDialog(null, Inter.getLocText("FR-Lic_does_not_Support_Remote")); + return false; + } + try { + JSONObject jo = new JSONObject(resJSON); + + if (isSignIn) { + if (jo.has("id")) { + userID = jo.getString("id"); + } + if (jo.has("isRoot")) { + isRoot = jo.getBoolean("isRoot"); + } + + if (userID != null) { + return true; + } + } else { + if (jo.has("res")) { + return jo.getBoolean("res"); + } + } + String exception = jo.getString("exp"); + if (exception != null) { + throw new EnvException(exception); + } + } catch (JSONException je) { + // 返回的resJSON不是JSON格式的,那就直接返回resJSON作为userID + return true; + } + + return true; + } + + protected boolean doLockOperation(String[] filePathes, String cmd) throws Exception { + if (filePathes == null || filePathes.length == 0) { + return true; + } + + JSONArray ja = new JSONArray(filePathes); + HashMap para = new HashMap<>(); + para.put("op", "fr_remote_design"); + para.put("cmd", cmd); + para.put("pathes", ja.toString()); + + return simulaRPC(para, false); + } + + /** + * 取路径filePath下面文件的lock + *

+ * 处于同一个原子操作,要么拿到所有的锁,要么一个锁也没有拿到 + */ + public boolean getLock(String[] filePathes) throws Exception { + return doLockOperation(filePathes, "design_get_lock"); + } + + /** + * 解锁文件 + * + * @param filePathes 文件路径 + * @return 成功解锁返回true + * @throws Exception e + */ + public boolean releaseLock(String[] filePathes) throws Exception { + return doLockOperation(filePathes, "design_release_lock"); + } + + /** + * 当前Env下,tplPath目录下是否存在模板 + * + * @param reportPath 路径 + * @return 是否存在 + */ + @Override + public boolean isTemplateExist(String reportPath) throws Exception { + if (reportPath == null) { + return false; + } + + HashMap para = new HashMap<>(); + para.put("op", "fr_remote_design"); + para.put("cmd", "design_report_exist"); + para.put("report_path", reportPath); + + HttpClient client = createHttpMethod(para); + InputStream input = execute4InputStream(client); + + return ComparatorUtils.equals(stream2String(input), "true"); + } + + /** + * 解锁当前模板,用于远程设计。当远程设计某张模板 时,在解锁之前改模板处于锁定状态 + * + * @param tplPath 路径 + * @throws Exception e + */ + @Override + public void unlockTemplate(String tplPath) throws Exception { + HashMap para = new HashMap<>(); + para.put("op", "fr_remote_design"); + para.put("cmd", "design_close_report"); + para.put(RemoteDeziConstants.TEMPLATE_PATH, tplPath); + HttpClient client = createHttpMethod(para); + + InputStream input = execute4InputStream(client); + String info = Utils.inputStream2String(input, EncodeConstants.ENCODING_UTF_8); + + FRContext.getLogger().error(info); + } + public class Bytes2ServerOutputStream extends OutputStream { private ByteArrayOutputStream out = new ByteArrayOutputStream(); private HashMap nameValuePairs; @@ -329,14 +706,287 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl } } + /** + * 测试数据连接是否能够正确的连接上 + * + * @param database 数据连接 + * @return 如果能正确的连接到数据库则返回true + * @throws Exception 无法正确连接到数据库则抛出此异常 + * TODO alex_ENV 个人以为,这里应该是测试所有Connection的连接,所以Connection与TableData接口的关联需要思考 + */ + @Override + public boolean testConnection(com.fr.data.impl.Connection database) throws Exception { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + + // 把database写成xml文件到out + DavXMLUtils.writeXMLFileDatabaseConnection(database, out); + + HashMap para = new HashMap<>(); + para.put("op", "fr_remote_design"); + para.put("cmd", "design_test_con"); + + InputStream input = postBytes2ServerB(out.toByteArray(), para); + + if (input == null) { + return false; + } + + return Boolean.valueOf(IOUtils.inputStream2String(input, EncodeConstants.ENCODING_UTF_8)); + } + @Override - public boolean updateAuthorities(DesignAuthority[] authorities) throws Exception { + public boolean updateAuthorities(DesignAuthority[] authorities) { return RemoteEnvUtils.updateAuthorities(authorities, this); } @Override public DesignAuthority[] getAuthorities() { + return RemoteEnvUtils.getAuthorities(this); + + } + + /** + * ben:取schema + */ + @Override + public String[] getTableSchema(com.fr.data.impl.Connection database) throws Exception { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + + DavXMLUtils.writeXMLFileDatabaseConnection(database, out); + HashMap para = new HashMap<>(); + para.put("op", "fr_remote_design"); + para.put("cmd", "design_get_schema"); + InputStream input = postBytes2ServerB(out.toByteArray(), para); + if (input == null) { + return null; + } + return DavXMLUtils.readXMLFileSchema(input); + } + + /** + * b:分别取Table,View,Procedure,实际应用时更有意义 + */ + @Override + public TableProcedure[] getTableProcedure(com.fr.data.impl.Connection database, String type, String schema) throws Exception { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + DavXMLUtils.writeXMLFileDatabaseConnection(database, out); + HashMap para = new HashMap<>(); + para.put("op", "fr_remote_design"); + para.put("cmd", "design_get_tables"); + para.put("__type__", type); + para.put("__dbschema__", schema); + InputStream input = postBytes2ServerB(out.toByteArray(), para); + if (input == null) { + return new TableProcedure[0]; + } + return DavXMLUtils.readXMLSQLTables(input); + } + + @Override + public List getProcedures(com.fr.data.impl.Connection datasource, String[] schemas, boolean isOracle, boolean isOracleSysSpace) throws Exception { + HashMap schemaTableProcedureMap = new HashMap(); + List sqlTableObjs = new ArrayList(); + TableProcedure[] sqlTableObj = null; + int len = schemas.length; + if (len > 0) { + for (int i = 0; i < len; i++) { + String schema = schemas[i]; + sqlTableObj = this.getTableProcedure(datasource, TableProcedure.PROCEDURE, schema); + if (sqlTableObj == null) { + sqlTableObj = new TableProcedure[0]; + } + sqlTableObjs.add(sqlTableObj); + schemaTableProcedureMap.put(schema, sqlTableObj); + } + } else { + sqlTableObj = this.getTableProcedure(datasource, TableProcedure.PROCEDURE, null); + if (sqlTableObj == null) { + sqlTableObj = new TableProcedure[0]; + } + sqlTableObjs.add(sqlTableObj); + schemaTableProcedureMap.put(null, sqlTableObj); + } + DataCoreUtils.putProcedureMap(datasource, schemaTableProcedureMap); + return sqlTableObjs; + } + + /** + * 在当前路径下新建文件夹 + * + * @param folderPath 文件名 + * @return 成功创建返回true + * @throws Exception e + */ + @Override + public boolean createFolder(String folderPath) throws Exception { + HashMap para = new HashMap<>(); + para.put("op", "fr_remote_design"); + para.put("cmd", "design_create_folder"); + para.put("folder_path", folderPath); + + HttpClient client = createHttpMethod(para); + InputStream input = execute4InputStream(client); + + if (input == null) { + return false; + } + + return Boolean.valueOf(IOUtils.inputStream2String(input, EncodeConstants.ENCODING_UTF_8)); + } + + /** + * 新建一个文件 + * + * @param filePath :目标文件相对路径 + * @return 成功新建返回true + * @throws Exception e + */ + @Override + public boolean createFile(String filePath) throws Exception { + HashMap para = new HashMap<>(); + para.put("op", "fr_remote_design"); + para.put("cmd", "design_create_file"); + para.put("file_path", filePath); + + HttpClient client = createHttpMethod(para); + InputStream input = execute4InputStream(client); + + if (input == null) { + return false; + } + + return Boolean.valueOf(IOUtils.inputStream2String(input, EncodeConstants.ENCODING_UTF_8)); + } + + @Override + public boolean renameFile(String newPath, String oldPath) throws Exception { + HashMap para = new HashMap<>(); + para.put("op", "fr_remote_design"); + para.put("cmd", "design_rename_file"); + para.put("newPath", newPath); + para.put("oldPath", oldPath); + + HttpClient client = createHttpMethod(para); + InputStream input = execute4InputStream(client); + + if (input == null) { + return false; + } + + return Boolean.valueOf(IOUtils.inputStream2String(input, EncodeConstants.ENCODING_UTF_8)); + } + + /** + * 判断文件是否存在 + * + * @param filePath :目标文件相对路径 + * @return 文件是否存在 + * @throws Exception e + */ + @Override + public boolean fileExists(String filePath) throws Exception { + if (filePath == null) { + return false; + } + + HashMap para = new HashMap<>(); + para.put("op", "fr_remote_design"); + para.put("cmd", "design_file_exists"); + para.put("file_path", filePath); + + HttpClient client = createHttpMethod(para); + InputStream input = execute4InputStream(client); + + if (input == null) { + return false; + } + + return Boolean.valueOf(IOUtils.inputStream2String(input, EncodeConstants.ENCODING_UTF_8)); + } + + /** + * 判断文件是否锁住 + * + * @param filePath 文件路径 + * @return 文件被锁住了,返回true + * @throws Exception e + */ + @Override + public boolean fileLocked(String filePath) throws Exception { + if (filePath == null) { + return false; + } + + HashMap para = new HashMap<>(); + para.put("op", "fr_remote_design"); + para.put("cmd", "design_file_locked"); + para.put("file_path", filePath); + + HttpClient client = createHttpMethod(para); + InputStream input = execute4InputStream(client); + + if (input == null) { + return false; + } + + return Boolean.valueOf(IOUtils.inputStream2String(input, EncodeConstants.ENCODING_UTF_8)); + } + + + /** + * 注册环境,用于检测是否启动定时器,主要用于本地环境来监测远程 + * + * @param env 用户环境 + */ + @Override + public void registerUserEnv(UserBaseEnv env) { + } + + /** + * 用于检测用户环境 + * ,启动定时器 + */ + @Override + public void startUserCheckTimer() { + } + + + /** + * 停止定时器 + */ + public void stopUserCheckTimer() { + } + + /** + * 删除文件 + * + * @param filePath 文件地址 + * @return 删除成功返回true + */ + @Override + public boolean deleteFile(String filePath) { + if (filePath == null) { + return false; + } + try { + HashMap para = new HashMap<>(); + para.put("op", "fr_remote_design"); + para.put("cmd", "delete_file"); + para.put("file_path", filePath); + + HttpClient client = createHttpMethod(para); + InputStream input = execute4InputStream(client); + + if (input == null) { + return false; + } + + return Boolean.valueOf(IOUtils.inputStream2String(input, EncodeConstants.ENCODING_UTF_8)); + } catch (Exception e) { + FRContext.getLogger().error(e.getMessage()); + } + return false; } /** @@ -351,8 +1001,8 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl HashMap para = new HashMap<>(); para.put("op", "fr_remote_design"); para.put("cmd", "write_privilege_map"); - para.put("current_user", getUser()); - para.put("current_password", this.getPassword()); + para.put("current_user", this.user); + para.put("current_password", this.password); para.put("key", key); para.put("value", value); @@ -404,6 +1054,168 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl } } + /** + * 列出WEB-INF目录下指定路径的文件夹与文件 + * + * @param rootFilePath 指定目录 + * @return WEB-INF目录下指定路径的文件夹与文件 + * @throws Exception e + */ + @Override + public FileNode[] listFile(String rootFilePath) throws Exception { + return listFile(rootFilePath, false); + } + + /** + * 列出WEB-INF上层目录下指定路径的文件夹与文件 + * + * @param rootFilePath 指定目录 + * @return WEB-INF上层目录下指定路径的文件夹与文件 + * @throws Exception e + */ + @Override + public FileNode[] listReportPathFile(String rootFilePath) throws Exception { + return listFile(rootFilePath, true); + } + + private FileNode[] listFile(String rootFilePath, boolean isWebReport) throws Exception { + FileNode[] fileNodes; + + HashMap para = new HashMap<>(); + para.put("op", "fs_remote_design"); + para.put("cmd", "design_list_file"); + para.put("file_path", rootFilePath); + para.put("currentUserName", this.getUser()); + para.put("currentUserId", this.createUserID()); + para.put("isWebReport", isWebReport ? "true" : "false"); + + HttpClient client = createHttpMethod(para); + InputStream input = execute4InputStream(client); + + if (input == null) { + return new FileNode[0]; + } + + // 远程环境下左侧目录树暂不需要打开xlsx,xls文件 + fileNodes = DavXMLUtils.readXMLFileNodes(input); + ArrayList al = new ArrayList<>(); + for (int i = 0; i < fileNodes.length; i++) { + al.add(fileNodes[i]); + } + + FileNode[] fileNodes2 = new FileNode[al.size()]; + for (int i = 0; i < al.size(); i++) { + fileNodes2[i] = al.get(i); + } + + return fileNodes2; + } + + + /** + * 列出目标目录下所有cpt文件或文件夹 + * + * @param rootFilePath 指定目录 + * @return 列出目标目录下所有cpt文件或文件夹 + */ + @Override + public FileNode[] listCpt(String rootFilePath) { + return listCpt(rootFilePath, false); + } + + /** + * 列出目标目录下所有cpt文件或文件夹 + * + * @param rootFilePath 指定目录 + * @param recurse 是否递归查找其子目录 + * @return 列出目标目录下所有cpt文件或文件夹 + * @throws Exception e + */ + @Override + public FileNode[] listCpt(String rootFilePath, boolean recurse) { + List fileNodeList = new ArrayList<>(); + try { + listAll(rootFilePath, fileNodeList, new String[]{"cpt"}, recurse); + } catch (Exception e) { + FRContext.getLogger().error(e.getMessage(), e); + } + return fileNodeList.toArray(new FileNode[fileNodeList.size()]); + } + + private void listAll(String rootFilePath, List nodeList, String[] fileTypes, boolean recurse) throws Exception { + FileNode[] fns = listFile(rootFilePath); + for (FileNode fileNode : fns) { + if (isAcceptFileType(fileNode, fileTypes)) { + nodeList.add(fileNode); + } else if (fileNode.isDirectory()) { + if (recurse) { + listAll(rootFilePath + File.separator + fileNode.getName(), nodeList, fileTypes, true); + } else { + nodeList.add(fileNode); + } + } + } + } + + private boolean isAcceptFileType(FileNode fileNode, String[] fileTypes) { + for (String fileType : fileTypes) { + if (fileNode.isFileType(fileType)) { + return true; + } + } + return false; + } + + /** + * 获取指定数据集的参数 + * + * @param tableData 数据集 + * @return 数据集的参数 + * @throws Exception 获取参数失败则抛出此异常 + */ + @Override + public Parameter[] getTableDataParameters(TableData tableData) throws Exception { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + + //把tableData写成xml文件到out + DavXMLUtils.writeXMLFileTableData(tableData, out); + + HashMap para = new HashMap<>(); + para.put("op", "fr_remote_design"); + para.put("cmd", "design_td_pars"); + InputStream input = postBytes2ServerB(out.toByteArray(), para); + + if (input == null) { + return new Parameter[0]; + } + return DavXMLUtils.readXMLParameters(input); + } + + + /** + * 获取存储过程中的参数 + * + * @param storeProcedure 存储过程 + * @return 返回存储过程中的所有参数组成的数组 + * @throws Exception 如果获取参数失败则抛出此异常 + */ + @Override + public Parameter[] getStoreProcedureParameters(StoreProcedure storeProcedure) throws Exception { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + + // 把tableData写成xml文件到out + DavXMLUtils.writeXMLFileStoreProcedureAndSource(storeProcedure, out); + HashMap para = new HashMap<>(); + para.put("op", "fr_remote_design"); + para.put("cmd", "design_sp_pars"); + InputStream input = postBytes2ServerB(out.toByteArray(), para); + + if (input == null) { + return new Parameter[0]; + } + return DavXMLUtils.readXMLParameters(input); + } + @Override public EmbeddedTableData previewTableData(Object tableData, Map parameterMap, int rowCount) throws Exception { return previewTableData(null, tableData, parameterMap, rowCount); @@ -485,6 +1297,90 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl return execute4InputStream(client); } + /** + * Read XML.
+ * The method will be invoked when read data from XML file.
+ * May override the method to read the data that you saved. + */ + @Override + public void readXML(XMLableReader reader) { + if (reader.isChildNode()) { + String tmpVal; + if ("DIR".equals(reader.getTagName())) { + if ((tmpVal = reader.getAttrAsString("path", null)) != null) { + this.path = tmpVal; + } + if ((tmpVal = reader.getAttrAsString("user", null)) != null) { + this.user = tmpVal; + } + if ((tmpVal = reader.getAttrAsString("password", null)) != null) { + this.password = tmpVal; + } + } + } + } + + /** + * Write XML.
+ * The method will be invoked when save data to XML file.
+ * May override the method to save your own data. + * + * @param writer the PrintWriter. + */ + @Override + public void writeXML(XMLPrintWriter writer) { + writer.startTAG("DIR").attr("path", this.path).attr("user", this.user).attr("password", this.password).end(); + } + + + public static class Clock { + + private static final long CONNECT_INTERVAL = 3000L; + private boolean connected = false; + + private RemoteEnv remoteEnv; + + public Clock(RemoteEnv remoteEnv) { + this.remoteEnv = remoteEnv; + } + + /** + * 停止连接 + */ + public void stop() { + connected = false; + } + + private void attemptConnect() throws Exception { + Thread.sleep(CONNECT_INTERVAL); + Pattern pattern = Pattern.compile("[/:]+"); + String[] strs = pattern.split(remoteEnv.path); + + //host,如:192.168.100.195 + String shost = strs[1]; + //端口,如:8080 + int sport = Integer.parseInt(strs[2]); + + Socket socket = new Socket(shost, sport); + //OOBBINLINE:是否支持发送一个字节的TCP紧急数据,false表示服务器不用处理这个数据 + socket.setOOBInline(false); + socket.sendUrgentData(0xFF); + socket.close(); + } + } + + /** + * 读报表运行环境所需的配置文件,如datasource.xml, config.xml,这些文件都保存在WEB-INF/resources目录下面 + * + * @param resourceName 配置文件的名字,如datasource.xml + * @return 输入流 + * @throws Exception e + */ + @Override + public InputStream readResource(String resourceName) throws Exception { + return readBean(resourceName, ProjectConstants.RESOURCES_NAME); + } + /** * 读取路径下的svg文件 @@ -659,11 +1555,176 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl return new Bytes2ServerOutputStream(para); } + /** + * 返回数据库表的列名 + * + * @param selectedName 所选择数据库名 + * @param schema 数据库模式,用于存储过程 + * @param tableName 所选择数据库名 + */ + @Override + public String[] getColumns(String selectedName, String schema, String tableName) throws Exception { + HashMap para = new HashMap<>(); + para.put("op", "fr_remote_design"); + para.put("cmd", "design_columns"); + para.put("dsName", selectedName); + para.put("schema", schema); + para.put("tableName", tableName); + + HttpClient client = createHttpMethod2(para); + InputStream input = execute4InputStream(client); + + if (input == null) { + return null; + } + + String colums = stream2String(input); + if (StringUtils.isEmpty(colums)) { + return null; + } + return colums.split("\\."); + } + + /** + * 返回模板文件路径 + */ @Override public String getWebReportPath() { return getPath().substring(0, getPath().lastIndexOf("/")); } + @Override + public String getProcedureText(String connectionName, String databaseName) throws Exception { + HashMap para = new HashMap<>(); + para.put("op", "fr_remote_design"); + para.put("cmd", "design_get_procedure_text"); + para.put("procedure_name", databaseName); + para.put("connectionName", connectionName); + + ByteArrayOutputStream out = new ByteArrayOutputStream(); + InputStream input = postBytes2ServerB(out.toByteArray(), para); + if (input == null) { + return StringUtils.EMPTY; + } + return DavXMLUtils.readXMLProcedureText(input); + } + + @Override + public StoreProcedureParameter[] getStoreProcedureDeclarationParameters(String connectionName, String databaseName, String parameterDefaultValue) throws Exception { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + HashMap para = new HashMap<>(); + para.put("op", "fr_remote_design"); + para.put("cmd", "design_get_sp_parameters"); + para.put("__name__", databaseName); + para.put("__default_value__", parameterDefaultValue); + para.put("connectionName", connectionName); + + InputStream input = postBytes2ServerB(out.toByteArray(), para); + if (input == null) { + return new StoreProcedureParameter[0]; + } + return DavXMLUtils.readXMLStoreProcedureParameters(input); + } + + /** + * 获取datasource.xml文件的修改表 + */ + @Override + public ModifiedTable getDataSourceModifiedTables(String type) { + try { + HashMap para = new HashMap<>(); + para.put("op", "fr_remote_design"); + para.put("cmd", "get_datasource_modified_tables"); + para.put("type", type); + + HttpClient client = createHttpMethod(para); + InputStream input = execute4InputStream(client); + if (input == null) { + return new ModifiedTable(); + } + return DavXMLUtils.readXMLModifiedTables(input); + } catch (Exception e) { + FRContext.getLogger().error(e.getMessage()); + } + return new ModifiedTable(); + } + + + /** + * 写修改表 + * + * @param modifiedTable 修改表 + * @param type 操作类型,是数据连接还是服务器数据集 + * @return 写入成功返回true + */ + @Override + public boolean writeDataSourceModifiedTables(ModifiedTable modifiedTable, String type) { + + ByteArrayOutputStream out = new ByteArrayOutputStream(); + + // 把tableData写成xml文件到out + DavXMLUtils.writeXMLModifiedTables(modifiedTable, out); + try { + HashMap para = new HashMap<>(); + para.put("op", "fr_remote_design"); + para.put("cmd", "update_modifytable_to_server"); + para.put("type", type); + + InputStream input = postBytes2ServerB(out.toByteArray(), para); + + if (input == null) { + return false; + } + + return Boolean.valueOf(IOUtils.inputStream2String(input, EncodeConstants.ENCODING_UTF_8)); + } catch (Exception e) { + FRContext.getLogger().error(e.getMessage()); + } + return false; + } + + public String[] getProcedureColumns(StoreProcedure storeProcedure, java.util.Map parameterMap) throws Exception { + String[] columns; + HashMap para = new HashMap<>(); + para.put("op", "fr_remote_design"); + para.put("cmd", "list_sp"); + HttpClient client = createHttpMethod(para); + try { + InputStream input = execute4InputStream(client); + + if (input == null) { + return ArrayUtils.EMPTY_STRING_ARRAY; + } + + columns = DavXMLUtils.readXMLSPColumns(input); + return columns; + } catch (Exception e) { + FRContext.getLogger().error(e.getMessage()); + } + + return new String[0]; + } + + public String[] getProcedureColumns(String name) throws Exception { + String[] columns; + HashMap para = new HashMap<>(); + para.put("op", "fr_remote_design"); + para.put("cmd", "list_sp_columns_name"); + para.put("name", name); + HttpClient client = createHttpMethod(para); + try { + InputStream input = execute4InputStream(client); + if (input == null) { + return ArrayUtils.EMPTY_STRING_ARRAY; + } + columns = DavXMLUtils.readXMLSPColumns(input); + return columns; + } catch (Exception e) { + FRContext.getLogger().error(e.getMessage()); + } + return new String[0]; + + } /** * 输出日志信息 @@ -687,12 +1748,103 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl } } + @Override + public String getUserID() { + return userID; + } + + + /** + * 预览存储过程 + * + * @param storeProcedure 存储过程 + * @param parameterMap 参数map + * @param rowCount 行数 + * @return 返回取到的存储过程 + */ + @Override + public ProcedureDataModel[] previewProcedureDataModel(StoreProcedure storeProcedure, Map parameterMap, int rowCount) { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + + // 把tableData写成xml文件到out + DavXMLUtils.writeXMLFileStoreProcedureAndSource(storeProcedure, out); + + // 把parameterMap转成JSON格式的字符串 + JSONObject jo = new JSONObject(parameterMap); + String jsonParameter = jo.toString(); + + try { + HashMap para = new HashMap<>(); + para.put("op", "fr_remote_design"); + para.put("cmd", "list_sp"); + para.put("pars", jsonParameter); + + InputStream input = postBytes2ServerB(out.toByteArray(), para); + if (input == null) { + return null; + } + + TableData[] tableDatas = DavXMLUtils.readXMLTableDataArray(input); + if (tableDatas == null || tableDatas.length == 0) { + return new ProcedureDataModel[0]; + } + ProcedureDataModel[] procedureDataModels = new ProcedureDataModel[tableDatas.length]; + for (int i = 0; i < tableDatas.length; i++) { + if (tableDatas[i] instanceof EmbeddedTableData) { + procedureDataModels[i] = ((EmbeddedTableData) tableDatas[i]).trans2ProcedureDataModel(); + } + } + return procedureDataModels; + + + } catch (Exception e) { + FRContext.getLogger().error(e.getMessage()); + } + return new ProcedureDataModel[0]; + } + + + @Override + public String getAppName() { + return "WebReport"; + } + + /** + * 是否为Oracle数据连接 + * + * @param database 数据连接 + * @return 是返回true + * @throws Exception + */ + @Override + public boolean isOracle(Connection database) throws Exception { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + DavXMLUtils.writeXMLFileDatabaseConnection(database, out); + HashMap para = new HashMap<>(); + para.put("op", "fr_remote_design"); + para.put("cmd", "design_get_isOracle"); + InputStream input = postBytes2ServerB(out.toByteArray(), para); + if (input == null) { + return true; + } + return DavXMLUtils.readXMLBoolean(input); + } @Override public String[] getSupportedTypes() { return FILE_TYPE; } + /** + * 在模板面板中是否支持增加打开所在文件夹、重命名、删除三个工具栏选项 + * + * @return 不支持返回false + */ + @Override + public boolean isSupportLocalFileOperate() { + return false; + } + /** * 判断是否有文件夹权限 * @@ -723,6 +1875,43 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl } + /** + * 是否是管理员身份 + * + * @return 是则返回true + */ + @Override + public boolean isRoot() { + return isRoot; + } + + /** + * 是否为压缩包部署 + * + * @return 是则返回true + */ + @Override + public boolean isPackDeploy() { + return false; + } + + @Override + public String getDesignerVersion() throws Exception { + HashMap para = new HashMap<>(); + para.put("op", "fr_remote_design"); + para.put("cmd", "design_get_designer_version"); + para.put("user", user); + para.put("password", getEncodedPassword()); + + HttpClient client = createHttpMethod(para, true); + try { + return stream2String(execute4InputStream(client)); + } catch (Exception e) { + FRContext.getLogger().error(e.getMessage()); + } + return null; + } + @Override public InputStream getDataSourceInputStream(String filePath) throws Exception { return readBean(filePath, "datasource"); @@ -751,6 +1940,17 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl return allRoleList; } + @Override + public String getLicName() { + return License.FILE_NAME; + } + + @Override + public void setLicName(String licName) { + //do nth + } + + /** * 获取当前env的build文件路径 */ @@ -928,10 +2128,38 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl } } + @Override + public void doWhenServerShutDown() { + + } + + @Override + public boolean isLocalEnv() { + + return false; + } @Override public boolean hasPluginServiceStarted(String key) { return true; } + + @Override + public JSONArray getPluginStatus() { + + try { + HashMap para = new HashMap<>(); + para.put("op", "plugin"); + para.put("cmd", "get_status"); + para.put("current_uid", this.createUserID()); + para.put("currentUsername", this.getUser()); + + HttpClient client = createHttpMethod(para); + InputStream input = execute4InputStream(client); + return new JSONArray(stream2String(input)); + } catch (Exception e) { + return JSONArray.create(); + } + } } \ No newline at end of file diff --git a/designer-base/src/com/fr/env/RemoteEnvUtils.java b/designer-base/src/com/fr/env/RemoteEnvUtils.java index d22150bd8..5580222be 100644 --- a/designer-base/src/com/fr/env/RemoteEnvUtils.java +++ b/designer-base/src/com/fr/env/RemoteEnvUtils.java @@ -3,6 +3,7 @@ package com.fr.env; import com.fr.base.FRContext; import com.fr.general.IOUtils; import com.fr.report.DesignAuthority; +import com.fr.report.util.AuthorityXMLUtils; import com.fr.stable.EncodeConstants; import com.fr.third.org.apache.http.HttpEntity; import com.fr.third.org.apache.http.client.methods.CloseableHttpResponse; @@ -13,7 +14,6 @@ import com.fr.third.org.apache.http.entity.InputStreamEntity; import com.fr.third.org.apache.http.impl.client.CloseableHttpClient; import com.fr.third.org.apache.http.impl.client.HttpClients; import com.fr.third.org.apache.http.util.EntityUtils; -import com.fr.web.utils.AuthorityXMLUtils; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; diff --git a/designer-base/src/com/fr/env/SignIn.java b/designer-base/src/com/fr/env/SignIn.java index f876302ba..09ba8c911 100644 --- a/designer-base/src/com/fr/env/SignIn.java +++ b/designer-base/src/com/fr/env/SignIn.java @@ -25,7 +25,7 @@ public class SignIn { static { EventDispatcher.listen(EnvEvents.CONNECTION_ERROR, new Listener() { @Override - public void on(Event event, Null param) { + public void on(Event event, Null param) { if (JOptionPane.showConfirmDialog(null, Inter.getLocText("FR-Remote_Connect2Server_Again"), UIManager.getString("OptionPane.titleText"), JOptionPane.YES_NO_OPTION) == JOptionPane.OK_OPTION) { try { diff --git a/designer-form/src/com/fr/design/mainframe/widget/accessibles/AccessibleBodyWatermarkEditor.java b/designer-form/src/com/fr/design/mainframe/widget/accessibles/AccessibleBodyWatermarkEditor.java index 863dd1b95..a3cd042fa 100644 --- a/designer-form/src/com/fr/design/mainframe/widget/accessibles/AccessibleBodyWatermarkEditor.java +++ b/designer-form/src/com/fr/design/mainframe/widget/accessibles/AccessibleBodyWatermarkEditor.java @@ -7,6 +7,9 @@ import com.fr.design.mainframe.widget.editors.ITextComponent; import com.fr.design.mainframe.widget.renderer.WatermarkRenderer; import com.fr.design.mainframe.widget.wrappers.WatermarkWrapper; import com.fr.design.report.WatermarkPane; +import com.fr.plugin.ExtraClassManager; +import com.fr.stable.ReportFunctionProcessor; +import com.fr.stable.fun.FunctionProcessor; import javax.swing.SwingUtilities; import java.awt.Dimension; @@ -40,6 +43,11 @@ public class AccessibleBodyWatermarkEditor extends UneditableAccessibleEditor { public void doOk() { setValue(watermarkPane.update()); fireStateChanged(); + // 功能点 + FunctionProcessor processor = ExtraClassManager.getInstance().getFunctionProcessor(); + if (processor != null) { + processor.recordFunction(ReportFunctionProcessor.WATERMARK); + } } }); watermarkPane.populate((WatermarkAttr) getValue()); diff --git a/designer-realize/src/com/fr/design/actions/report/ReportWatermarkAction.java b/designer-realize/src/com/fr/design/actions/report/ReportWatermarkAction.java index ebe0b4ed1..d74d1698a 100644 --- a/designer-realize/src/com/fr/design/actions/report/ReportWatermarkAction.java +++ b/designer-realize/src/com/fr/design/actions/report/ReportWatermarkAction.java @@ -9,7 +9,10 @@ import com.fr.design.mainframe.JWorkBook; import com.fr.design.menu.KeySetUtils; import com.fr.design.report.WatermarkPane; import com.fr.main.impl.WorkBook; +import com.fr.plugin.ExtraClassManager; import com.fr.report.core.ReportUtils; +import com.fr.stable.ReportFunctionProcessor; +import com.fr.stable.fun.FunctionProcessor; import java.awt.event.ActionEvent; @@ -42,6 +45,11 @@ public class ReportWatermarkAction extends JWorkBookAction { public void doOk() { wbTpl.addAttrMark(watermarkPane.update()); jwb.fireTargetModified(); + // 功能点 + FunctionProcessor processor = ExtraClassManager.getInstance().getFunctionProcessor(); + if (processor != null) { + processor.recordFunction(ReportFunctionProcessor.WATERMARK); + } } }).setVisible(true); } From cd26cd96bc66400882086564c39a20dfb47ceda4 Mon Sep 17 00:00:00 2001 From: hzzz Date: Tue, 29 May 2018 18:46:27 +0800 Subject: [PATCH 6/9] merge --- .../src/com/fr/design/DesignerEnvManager.java | 2 +- designer-base/src/com/fr/env/EnvListPane.java | 6 +- designer-base/src/com/fr/env/RemoteEnv.java | 1245 +---------------- .../src/com/fr/env/RemoteEnvPane.java | 17 +- 4 files changed, 72 insertions(+), 1198 deletions(-) diff --git a/designer-base/src/com/fr/design/DesignerEnvManager.java b/designer-base/src/com/fr/design/DesignerEnvManager.java index fcc4c2b26..8d6cbafed 100644 --- a/designer-base/src/com/fr/design/DesignerEnvManager.java +++ b/designer-base/src/com/fr/design/DesignerEnvManager.java @@ -1455,7 +1455,7 @@ public class DesignerEnvManager implements XMLReadable, XMLWriter { } if (reader.isChildNode()) { - if (reader.getTagName().equals("Env")) { // description. + if (reader.getTagName().contains("Env")) { // description. // marks:获取名字 String reportServerName = reader.getAttrAsString("name", null); diff --git a/designer-base/src/com/fr/env/EnvListPane.java b/designer-base/src/com/fr/env/EnvListPane.java index 951f6cdda..9e1677ba3 100644 --- a/designer-base/src/com/fr/env/EnvListPane.java +++ b/designer-base/src/com/fr/env/EnvListPane.java @@ -1,6 +1,8 @@ package com.fr.env; import com.fr.base.Env; +import com.fr.base.env.resource.LocalEnvConfig; +import com.fr.base.env.resource.RemoteEnvConfig; import com.fr.core.env.EnvConfig; import com.fr.dav.LocalEnv; import com.fr.design.DesignerEnvManager; @@ -60,9 +62,9 @@ public class EnvListPane extends JListControlPane { @Override public NameableCreator[] createNameableCreators() { NameableCreator local = new NameObjectCreator(Inter.getLocText("Env-Local_Directory"), "com/fr/design/images/data/bind/localconnect.png", - LocalEnv.class, LocalEnvPane.class); + LocalEnvConfig.class, LocalEnvPane.class); NameableCreator remote = new NameObjectCreator(Inter.getLocText("Env-Remote_Server"), "com/fr/design/images/data/bind/distanceconnect.png", - RemoteEnv.class, RemoteEnvPane.class); + RemoteEnvConfig.class, RemoteEnvPane.class); return new NameableCreator[]{local, remote}; } diff --git a/designer-base/src/com/fr/env/RemoteEnv.java b/designer-base/src/com/fr/env/RemoteEnv.java index d541afe4c..b09f1cb98 100644 --- a/designer-base/src/com/fr/env/RemoteEnv.java +++ b/designer-base/src/com/fr/env/RemoteEnv.java @@ -1,64 +1,74 @@ package com.fr.env; -import com.fr.base.*; +import com.fr.base.AbstractEnv; +import com.fr.base.EnvException; +import com.fr.base.FRContext; +import com.fr.base.TableData; +import com.fr.base.Utils; +import com.fr.base.env.EnvContext; +import com.fr.base.env.resource.RemoteEnvConfig; import com.fr.base.remote.RemoteDeziConstants; import com.fr.core.env.EnvConstants; import com.fr.data.TableDataSource; -import com.fr.data.core.DataCoreUtils; -import com.fr.data.core.db.TableProcedure; -import com.fr.data.impl.Connection; import com.fr.data.impl.EmbeddedTableData; -import com.fr.data.impl.storeproc.ProcedureDataModel; -import com.fr.data.impl.storeproc.StoreProcedure; import com.fr.dav.DavXMLUtils; -import com.fr.dav.UserBaseEnv; import com.fr.design.DesignerEnvManager; import com.fr.design.ExtraDesignClassManager; -import com.fr.design.dialog.InformationWarnPane; -import com.fr.design.file.HistoryTemplateListPane; import com.fr.design.fun.DesignerEnvProcessor; import com.fr.design.mainframe.DesignerContext; -import com.fr.design.mainframe.DesignerFrameFileDealerPane; import com.fr.file.CacheManager; import com.fr.file.ConnectionConfig; import com.fr.file.TableDataConfig; -import com.fr.file.filetree.FileNode; -import com.fr.general.*; +import com.fr.general.ComparatorUtils; +import com.fr.general.IOUtils; +import com.fr.general.Inter; import com.fr.general.http.HttpClient; import com.fr.general.http.HttpToolbox; import com.fr.io.utils.ResourceIOUtils; import com.fr.json.JSONArray; import com.fr.json.JSONException; import com.fr.json.JSONObject; -import com.fr.license.function.VT4FR; import com.fr.log.FineLoggerFactory; -import com.fr.regist.License; import com.fr.report.DesignAuthority; import com.fr.share.ShareConstants; -import com.fr.stable.*; +import com.fr.stable.EncodeConstants; +import com.fr.stable.Filter; +import com.fr.stable.JavaCompileInfo; +import com.fr.stable.ProductConstants; +import com.fr.stable.StableUtils; +import com.fr.stable.StringUtils; +import com.fr.stable.SvgProvider; import com.fr.stable.file.XMLFileManagerProvider; import com.fr.stable.project.ProjectConstants; -import com.fr.stable.xml.XMLPrintWriter; import com.fr.stable.xml.XMLTools; -import com.fr.stable.xml.XMLableReader; import com.fr.third.guava.collect.ImmutableMap; import com.fr.web.ResourceConstants; -import javax.swing.*; -import javax.xml.transform.*; +import javax.swing.JOptionPane; +import javax.xml.transform.Source; +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerConfigurationException; +import javax.xml.transform.TransformerException; +import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; -import java.awt.*; -import java.io.*; +import java.awt.Component; +import java.io.BufferedReader; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.OutputStream; +import java.io.OutputStreamWriter; +import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; -import java.net.NoRouteToHostException; -import java.net.Socket; -import java.net.URLEncoder; -import java.util.*; -import java.util.List; -import java.util.Timer; -import java.util.logging.Level; -import java.util.regex.Pattern; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; import static com.fr.third.guava.base.Preconditions.checkArgument; @@ -66,38 +76,20 @@ import static com.fr.third.guava.base.Preconditions.checkArgument; * @author null */ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurable { - private static final int TIME_OUT = 30 * 1000; - private static final int PLAIN_SOCKET_PORT = 80; - private static final int SSL_PORT = 443; - private static final int MAX_PER_ROUTE = 20; - private static final int MAX_TOTAL = 100; - private static final String REMOTE_PLUGIN = "remote_plugin.info"; + private static final String CERT_KEY = "javax.net.ssl.trustStore"; private static final String PWD_KEY = "javax.net.ssl.trustStorePassword"; private static final String HTTPS_PREFIX = "https:"; private final static String[] FILE_TYPE = {"cptx", "cpt", "frm", "form", "cht", "chart"}; private String path; - private String user; - private String password; - private Clock clock = null; private String userID; - private Timer timer; - private int licNotSupport = 0; - private boolean isRoot = false; - private Timer logTimer = null; - private static ThreadLocal threadLocal = new ThreadLocal<>(); private boolean isReadTimeOut = false; private String buildFilePath; + private RemoteEnvConfig env; - public RemoteEnv() { - this.clock = new Clock(this); - } public RemoteEnv(String path, String userName, String password) { - this(); - this.path = path; - this.user = userName; - this.password = password; + env = new RemoteEnvConfig(path, userName, password); } /** @@ -105,85 +97,24 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl */ @Override public String getPath() { - return this.path; - } - - public void setPath(String s) { - this.path = s; + return env.getPath(); } - /** - * 当前设计环境的用户名,用于远程设计 - */ @Override public String getUser() { - return user; + return env.getUsername(); } - public void setUser(String user) { - this.user = user; - clearUserID(); - } public String getPassword() { - return password; - } - - /** - * 修复密码中包含特殊字符,无法登录的问题 - * - * @return - */ - private String getEncodedPassword() { - try { - return URLEncoder.encode(password, "UTF-8"); - } catch (UnsupportedEncodingException e) { - return password; - } - } - - public void setPassword(String password) { - this.password = password; - clearUserID(); - } - - public Clock getClock() { - return this.clock; - } - - public void setClock(Clock clock) { - this.clock = clock; - } - - private void clearUserID() { - this.userID = null; - } - - public void setThreadLocal(String value) { - synchronized (this) { - threadLocal.set(value); - } - - } - - public String getThreadLocal() { - return threadLocal.get(); + return env.getPassword(); } /** * 所有与服务器端交互前,都要调用这个方法生成UserID */ - private String createUserID() throws EnvException { - // 如果登录之后userID还是null - if (this.userID == null) { - if (!VT4FR.RemoteDesign.support() && licNotSupport <= 0) { - licNotSupport++; - JOptionPane.showMessageDialog(null, Inter.getLocText("FR-Lic_does_not_Support_Remote")); - } - throw new EnvException(Inter.getLocText("Env-Invalid_User_and_Password")); - } - - return this.userID; + private String createUserID() { + return EnvContext.currentToken(); } private HttpClient createHttpMethod(HashMap para) throws EnvException { @@ -272,15 +203,6 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl } } - private void doWithTimeOutException() { - boolean isNotNeedTip = ComparatorUtils.equals(getThreadLocal(), "HEART_BEAT") || ComparatorUtils.equals(getThreadLocal(), "LOG_MESSAGE"); - if (!isReadTimeOut && !isNotNeedTip) { - isReadTimeOut = true; - JOptionPane.showMessageDialog(DesignerContext.getDesignerFrame(), Inter.getLocText(new String[]{"Data", "read_time_out"})); - isReadTimeOut = false; - } - FRContext.getLogger().info("Connection reset "); - } /** @@ -408,13 +330,7 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl } } - private void extraChangeEnvPara() { - //在env连接之前, 加载一下不依赖env的插件. 看看需不需要改变参数. - DesignerEnvProcessor envProcessor = ExtraDesignClassManager.getInstance().getSingle(DesignerEnvProcessor.XML_TAG); - if (envProcessor != null) { - this.path = envProcessor.changeEnvPathBeforeConnect(user, password, path); - } - } + private void setHttpsParas() { if (path.startsWith(HTTPS_PREFIX) && System.getProperty(CERT_KEY) == null) { @@ -425,32 +341,7 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl } - /** - * 心跳访问,用来更新当前用户的访问时间 - * - * @throws Exception e - */ - public void heartBeatConnection() throws Exception { - HashMap para = new HashMap<>(); - para.put("op", "fr_remote_design"); - para.put("cmd", "heart_beat"); - para.put("user", user); - - HttpClient client = createHttpMethod(para); - execute4InputStream(client); - //这做法不好, 30秒刷一次, 刷新的时候会重新构建树, 构建完会把子节点都收缩起来, 效果太差. - //为什么不保存刷新前树的伸缩状态, 因为刷新后的树和刷新前的树的结构未必是一致的. - - //服务器通知客户端更新左上角文件树面板 -// try { -// if (ComparatorUtils.equals(stream2String(execute4InputStream(method)), "true")) { -// DesignerFrameFileDealerPane.getInstance().refresh(); -// } -// } catch (Exception e) { -// FRContext.getLogger().error(e.getMessage()); -// } - } /** * 返回描述该运行环境的名字 @@ -471,184 +362,6 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl } - private void startLogTimer() { - if (logTimer != null) { - logTimer.cancel(); - } - - logTimer = new Timer(); - logTimer.schedule(new TimerTask() { - @Override - public void run() { - try { - RemoteEnv.this.setThreadLocal("LOG_MESSAGE"); - FRContext.getCurrentEnv().printLogMessage(); - } catch (Exception e) { - FRContext.getLogger().info(e.getMessage()); - } - } - }, 10000, 10000); - } - - private void stopLogTimer() { - if (logTimer != null) { - logTimer.cancel(); - logTimer = null; - } - } - - /** - * 根据userID sign out - * - * @return 成功签出返回true - * @throws Exception e - */ - @Override - public boolean signOut() throws Exception { - if (userID == null) { - return true; - } - stopLogTimer(); - // richer:登出的时候就把定时发送的时钟停掉 - clock.stop(); - // richer:把轮训使用的定时器也去掉 - timer.cancel(); - - HashMap para = new HashMap<>(); - para.put("op", "fr_remote_design"); - para.put("cmd", "r_sign_out"); - para.put("id", userID); - - return simulaRPC(para, false - ); - } - - protected boolean simulaRPC(HashMap para, boolean isSignIn) throws Exception { - HttpClient client = createHttpMethod(para, isSignIn); - - // execute method取到input stream再转成String - String resJSON = null; - try { - resJSON = stream2String(execute4InputStream(client)); - } catch (Exception e) { - FRContext.getLogger().error(e.getMessage()); - } - - if (resJSON == null) { - return false; - } - if (resJSON.contains("RegistEditionException")) { - JOptionPane.showMessageDialog(null, Inter.getLocText("FR-Lic_does_not_Support_Remote")); - return false; - } - try { - JSONObject jo = new JSONObject(resJSON); - - if (isSignIn) { - if (jo.has("id")) { - userID = jo.getString("id"); - } - if (jo.has("isRoot")) { - isRoot = jo.getBoolean("isRoot"); - } - - if (userID != null) { - return true; - } - } else { - if (jo.has("res")) { - return jo.getBoolean("res"); - } - } - String exception = jo.getString("exp"); - if (exception != null) { - throw new EnvException(exception); - } - } catch (JSONException je) { - // 返回的resJSON不是JSON格式的,那就直接返回resJSON作为userID - return true; - } - - return true; - } - - protected boolean doLockOperation(String[] filePathes, String cmd) throws Exception { - if (filePathes == null || filePathes.length == 0) { - return true; - } - - JSONArray ja = new JSONArray(filePathes); - HashMap para = new HashMap<>(); - para.put("op", "fr_remote_design"); - para.put("cmd", cmd); - para.put("pathes", ja.toString()); - - return simulaRPC(para, false); - } - - /** - * 取路径filePath下面文件的lock - *

- * 处于同一个原子操作,要么拿到所有的锁,要么一个锁也没有拿到 - */ - public boolean getLock(String[] filePathes) throws Exception { - return doLockOperation(filePathes, "design_get_lock"); - } - - /** - * 解锁文件 - * - * @param filePathes 文件路径 - * @return 成功解锁返回true - * @throws Exception e - */ - public boolean releaseLock(String[] filePathes) throws Exception { - return doLockOperation(filePathes, "design_release_lock"); - } - - /** - * 当前Env下,tplPath目录下是否存在模板 - * - * @param reportPath 路径 - * @return 是否存在 - */ - @Override - public boolean isTemplateExist(String reportPath) throws Exception { - if (reportPath == null) { - return false; - } - - HashMap para = new HashMap<>(); - para.put("op", "fr_remote_design"); - para.put("cmd", "design_report_exist"); - para.put("report_path", reportPath); - - HttpClient client = createHttpMethod(para); - InputStream input = execute4InputStream(client); - - return ComparatorUtils.equals(stream2String(input), "true"); - } - - /** - * 解锁当前模板,用于远程设计。当远程设计某张模板 时,在解锁之前改模板处于锁定状态 - * - * @param tplPath 路径 - * @throws Exception e - */ - @Override - public void unlockTemplate(String tplPath) throws Exception { - HashMap para = new HashMap<>(); - para.put("op", "fr_remote_design"); - para.put("cmd", "design_close_report"); - para.put(RemoteDeziConstants.TEMPLATE_PATH, tplPath); - HttpClient client = createHttpMethod(para); - - InputStream input = execute4InputStream(client); - String info = Utils.inputStream2String(input, EncodeConstants.ENCODING_UTF_8); - - FRContext.getLogger().error(info); - } - public class Bytes2ServerOutputStream extends OutputStream { private ByteArrayOutputStream out = new ByteArrayOutputStream(); private HashMap nameValuePairs; @@ -706,36 +419,9 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl } } - /** - * 测试数据连接是否能够正确的连接上 - * - * @param database 数据连接 - * @return 如果能正确的连接到数据库则返回true - * @throws Exception 无法正确连接到数据库则抛出此异常 - * TODO alex_ENV 个人以为,这里应该是测试所有Connection的连接,所以Connection与TableData接口的关联需要思考 - */ - @Override - public boolean testConnection(com.fr.data.impl.Connection database) throws Exception { - ByteArrayOutputStream out = new ByteArrayOutputStream(); - - // 把database写成xml文件到out - DavXMLUtils.writeXMLFileDatabaseConnection(database, out); - - HashMap para = new HashMap<>(); - para.put("op", "fr_remote_design"); - para.put("cmd", "design_test_con"); - - InputStream input = postBytes2ServerB(out.toByteArray(), para); - - if (input == null) { - return false; - } - - return Boolean.valueOf(IOUtils.inputStream2String(input, EncodeConstants.ENCODING_UTF_8)); - } @Override - public boolean updateAuthorities(DesignAuthority[] authorities) { + public boolean updateAuthorities(DesignAuthority[] authorities) { return RemoteEnvUtils.updateAuthorities(authorities, this); } @@ -746,248 +432,6 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl } - /** - * ben:取schema - */ - @Override - public String[] getTableSchema(com.fr.data.impl.Connection database) throws Exception { - ByteArrayOutputStream out = new ByteArrayOutputStream(); - - DavXMLUtils.writeXMLFileDatabaseConnection(database, out); - HashMap para = new HashMap<>(); - para.put("op", "fr_remote_design"); - para.put("cmd", "design_get_schema"); - InputStream input = postBytes2ServerB(out.toByteArray(), para); - if (input == null) { - return null; - } - return DavXMLUtils.readXMLFileSchema(input); - } - - /** - * b:分别取Table,View,Procedure,实际应用时更有意义 - */ - @Override - public TableProcedure[] getTableProcedure(com.fr.data.impl.Connection database, String type, String schema) throws Exception { - ByteArrayOutputStream out = new ByteArrayOutputStream(); - DavXMLUtils.writeXMLFileDatabaseConnection(database, out); - HashMap para = new HashMap<>(); - para.put("op", "fr_remote_design"); - para.put("cmd", "design_get_tables"); - para.put("__type__", type); - para.put("__dbschema__", schema); - InputStream input = postBytes2ServerB(out.toByteArray(), para); - if (input == null) { - return new TableProcedure[0]; - } - return DavXMLUtils.readXMLSQLTables(input); - } - - @Override - public List getProcedures(com.fr.data.impl.Connection datasource, String[] schemas, boolean isOracle, boolean isOracleSysSpace) throws Exception { - HashMap schemaTableProcedureMap = new HashMap(); - List sqlTableObjs = new ArrayList(); - TableProcedure[] sqlTableObj = null; - int len = schemas.length; - if (len > 0) { - for (int i = 0; i < len; i++) { - String schema = schemas[i]; - sqlTableObj = this.getTableProcedure(datasource, TableProcedure.PROCEDURE, schema); - if (sqlTableObj == null) { - sqlTableObj = new TableProcedure[0]; - } - sqlTableObjs.add(sqlTableObj); - schemaTableProcedureMap.put(schema, sqlTableObj); - } - } else { - sqlTableObj = this.getTableProcedure(datasource, TableProcedure.PROCEDURE, null); - if (sqlTableObj == null) { - sqlTableObj = new TableProcedure[0]; - } - sqlTableObjs.add(sqlTableObj); - schemaTableProcedureMap.put(null, sqlTableObj); - } - DataCoreUtils.putProcedureMap(datasource, schemaTableProcedureMap); - return sqlTableObjs; - } - - /** - * 在当前路径下新建文件夹 - * - * @param folderPath 文件名 - * @return 成功创建返回true - * @throws Exception e - */ - @Override - public boolean createFolder(String folderPath) throws Exception { - HashMap para = new HashMap<>(); - para.put("op", "fr_remote_design"); - para.put("cmd", "design_create_folder"); - para.put("folder_path", folderPath); - - HttpClient client = createHttpMethod(para); - InputStream input = execute4InputStream(client); - - if (input == null) { - return false; - } - - return Boolean.valueOf(IOUtils.inputStream2String(input, EncodeConstants.ENCODING_UTF_8)); - } - - /** - * 新建一个文件 - * - * @param filePath :目标文件相对路径 - * @return 成功新建返回true - * @throws Exception e - */ - @Override - public boolean createFile(String filePath) throws Exception { - HashMap para = new HashMap<>(); - para.put("op", "fr_remote_design"); - para.put("cmd", "design_create_file"); - para.put("file_path", filePath); - - HttpClient client = createHttpMethod(para); - InputStream input = execute4InputStream(client); - - if (input == null) { - return false; - } - - return Boolean.valueOf(IOUtils.inputStream2String(input, EncodeConstants.ENCODING_UTF_8)); - } - - @Override - public boolean renameFile(String newPath, String oldPath) throws Exception { - HashMap para = new HashMap<>(); - para.put("op", "fr_remote_design"); - para.put("cmd", "design_rename_file"); - para.put("newPath", newPath); - para.put("oldPath", oldPath); - - HttpClient client = createHttpMethod(para); - InputStream input = execute4InputStream(client); - - if (input == null) { - return false; - } - - return Boolean.valueOf(IOUtils.inputStream2String(input, EncodeConstants.ENCODING_UTF_8)); - } - - /** - * 判断文件是否存在 - * - * @param filePath :目标文件相对路径 - * @return 文件是否存在 - * @throws Exception e - */ - @Override - public boolean fileExists(String filePath) throws Exception { - if (filePath == null) { - return false; - } - - HashMap para = new HashMap<>(); - para.put("op", "fr_remote_design"); - para.put("cmd", "design_file_exists"); - para.put("file_path", filePath); - - HttpClient client = createHttpMethod(para); - InputStream input = execute4InputStream(client); - - if (input == null) { - return false; - } - - return Boolean.valueOf(IOUtils.inputStream2String(input, EncodeConstants.ENCODING_UTF_8)); - } - - /** - * 判断文件是否锁住 - * - * @param filePath 文件路径 - * @return 文件被锁住了,返回true - * @throws Exception e - */ - @Override - public boolean fileLocked(String filePath) throws Exception { - if (filePath == null) { - return false; - } - - HashMap para = new HashMap<>(); - para.put("op", "fr_remote_design"); - para.put("cmd", "design_file_locked"); - para.put("file_path", filePath); - - HttpClient client = createHttpMethod(para); - InputStream input = execute4InputStream(client); - - if (input == null) { - return false; - } - - return Boolean.valueOf(IOUtils.inputStream2String(input, EncodeConstants.ENCODING_UTF_8)); - } - - - /** - * 注册环境,用于检测是否启动定时器,主要用于本地环境来监测远程 - * - * @param env 用户环境 - */ - @Override - public void registerUserEnv(UserBaseEnv env) { - } - - /** - * 用于检测用户环境 - * ,启动定时器 - */ - @Override - public void startUserCheckTimer() { - } - - - /** - * 停止定时器 - */ - public void stopUserCheckTimer() { - } - - /** - * 删除文件 - * - * @param filePath 文件地址 - * @return 删除成功返回true - */ - @Override - public boolean deleteFile(String filePath) { - if (filePath == null) { - return false; - } - try { - HashMap para = new HashMap<>(); - para.put("op", "fr_remote_design"); - para.put("cmd", "delete_file"); - para.put("file_path", filePath); - - HttpClient client = createHttpMethod(para); - InputStream input = execute4InputStream(client); - - if (input == null) { - return false; - } - - return Boolean.valueOf(IOUtils.inputStream2String(input, EncodeConstants.ENCODING_UTF_8)); - } catch (Exception e) { - FRContext.getLogger().error(e.getMessage()); - } - return false; - } /** * 远程设计器设计时,假如开了权限就不可预览了。这边放一个全局的map来开后门 @@ -1001,8 +445,8 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl HashMap para = new HashMap<>(); para.put("op", "fr_remote_design"); para.put("cmd", "write_privilege_map"); - para.put("current_user", this.user); - para.put("current_password", this.password); + para.put("current_user", getUser()); + para.put("current_password", getPassword()); para.put("key", key); para.put("value", value); @@ -1048,174 +492,13 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl for (int i = 0; i < toBeRemoveTDName.size(); i++) { dm.removeTableData(toBeRemoveTDName.get(i)); - } - } catch (Exception e) { - FRContext.getLogger().error(e.getMessage()); - } - } - - /** - * 列出WEB-INF目录下指定路径的文件夹与文件 - * - * @param rootFilePath 指定目录 - * @return WEB-INF目录下指定路径的文件夹与文件 - * @throws Exception e - */ - @Override - public FileNode[] listFile(String rootFilePath) throws Exception { - return listFile(rootFilePath, false); - } - - /** - * 列出WEB-INF上层目录下指定路径的文件夹与文件 - * - * @param rootFilePath 指定目录 - * @return WEB-INF上层目录下指定路径的文件夹与文件 - * @throws Exception e - */ - @Override - public FileNode[] listReportPathFile(String rootFilePath) throws Exception { - return listFile(rootFilePath, true); - } - - private FileNode[] listFile(String rootFilePath, boolean isWebReport) throws Exception { - FileNode[] fileNodes; - - HashMap para = new HashMap<>(); - para.put("op", "fs_remote_design"); - para.put("cmd", "design_list_file"); - para.put("file_path", rootFilePath); - para.put("currentUserName", this.getUser()); - para.put("currentUserId", this.createUserID()); - para.put("isWebReport", isWebReport ? "true" : "false"); - - HttpClient client = createHttpMethod(para); - InputStream input = execute4InputStream(client); - - if (input == null) { - return new FileNode[0]; - } - - // 远程环境下左侧目录树暂不需要打开xlsx,xls文件 - fileNodes = DavXMLUtils.readXMLFileNodes(input); - ArrayList al = new ArrayList<>(); - for (int i = 0; i < fileNodes.length; i++) { - al.add(fileNodes[i]); - } - - FileNode[] fileNodes2 = new FileNode[al.size()]; - for (int i = 0; i < al.size(); i++) { - fileNodes2[i] = al.get(i); - } - - return fileNodes2; - } - - - /** - * 列出目标目录下所有cpt文件或文件夹 - * - * @param rootFilePath 指定目录 - * @return 列出目标目录下所有cpt文件或文件夹 - */ - @Override - public FileNode[] listCpt(String rootFilePath) { - return listCpt(rootFilePath, false); - } - - /** - * 列出目标目录下所有cpt文件或文件夹 - * - * @param rootFilePath 指定目录 - * @param recurse 是否递归查找其子目录 - * @return 列出目标目录下所有cpt文件或文件夹 - * @throws Exception e - */ - @Override - public FileNode[] listCpt(String rootFilePath, boolean recurse) { - List fileNodeList = new ArrayList<>(); - try { - listAll(rootFilePath, fileNodeList, new String[]{"cpt"}, recurse); - } catch (Exception e) { - FRContext.getLogger().error(e.getMessage(), e); - } - return fileNodeList.toArray(new FileNode[fileNodeList.size()]); - } - - private void listAll(String rootFilePath, List nodeList, String[] fileTypes, boolean recurse) throws Exception { - FileNode[] fns = listFile(rootFilePath); - for (FileNode fileNode : fns) { - if (isAcceptFileType(fileNode, fileTypes)) { - nodeList.add(fileNode); - } else if (fileNode.isDirectory()) { - if (recurse) { - listAll(rootFilePath + File.separator + fileNode.getName(), nodeList, fileTypes, true); - } else { - nodeList.add(fileNode); - } - } - } - } - - private boolean isAcceptFileType(FileNode fileNode, String[] fileTypes) { - for (String fileType : fileTypes) { - if (fileNode.isFileType(fileType)) { - return true; - } - } - return false; - } - - /** - * 获取指定数据集的参数 - * - * @param tableData 数据集 - * @return 数据集的参数 - * @throws Exception 获取参数失败则抛出此异常 - */ - @Override - public Parameter[] getTableDataParameters(TableData tableData) throws Exception { - ByteArrayOutputStream out = new ByteArrayOutputStream(); - - //把tableData写成xml文件到out - DavXMLUtils.writeXMLFileTableData(tableData, out); - - HashMap para = new HashMap<>(); - para.put("op", "fr_remote_design"); - para.put("cmd", "design_td_pars"); - InputStream input = postBytes2ServerB(out.toByteArray(), para); - - if (input == null) { - return new Parameter[0]; - } - return DavXMLUtils.readXMLParameters(input); - } - - - /** - * 获取存储过程中的参数 - * - * @param storeProcedure 存储过程 - * @return 返回存储过程中的所有参数组成的数组 - * @throws Exception 如果获取参数失败则抛出此异常 - */ - @Override - public Parameter[] getStoreProcedureParameters(StoreProcedure storeProcedure) throws Exception { - ByteArrayOutputStream out = new ByteArrayOutputStream(); - - // 把tableData写成xml文件到out - DavXMLUtils.writeXMLFileStoreProcedureAndSource(storeProcedure, out); - HashMap para = new HashMap<>(); - para.put("op", "fr_remote_design"); - para.put("cmd", "design_sp_pars"); - InputStream input = postBytes2ServerB(out.toByteArray(), para); - - if (input == null) { - return new Parameter[0]; + } + } catch (Exception e) { + FRContext.getLogger().error(e.getMessage()); } - return DavXMLUtils.readXMLParameters(input); } + @Override public EmbeddedTableData previewTableData(Object tableData, Map parameterMap, int rowCount) throws Exception { return previewTableData(null, tableData, parameterMap, rowCount); @@ -1297,90 +580,6 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl return execute4InputStream(client); } - /** - * Read XML.
- * The method will be invoked when read data from XML file.
- * May override the method to read the data that you saved. - */ - @Override - public void readXML(XMLableReader reader) { - if (reader.isChildNode()) { - String tmpVal; - if ("DIR".equals(reader.getTagName())) { - if ((tmpVal = reader.getAttrAsString("path", null)) != null) { - this.path = tmpVal; - } - if ((tmpVal = reader.getAttrAsString("user", null)) != null) { - this.user = tmpVal; - } - if ((tmpVal = reader.getAttrAsString("password", null)) != null) { - this.password = tmpVal; - } - } - } - } - - /** - * Write XML.
- * The method will be invoked when save data to XML file.
- * May override the method to save your own data. - * - * @param writer the PrintWriter. - */ - @Override - public void writeXML(XMLPrintWriter writer) { - writer.startTAG("DIR").attr("path", this.path).attr("user", this.user).attr("password", this.password).end(); - } - - - public static class Clock { - - private static final long CONNECT_INTERVAL = 3000L; - private boolean connected = false; - - private RemoteEnv remoteEnv; - - public Clock(RemoteEnv remoteEnv) { - this.remoteEnv = remoteEnv; - } - - /** - * 停止连接 - */ - public void stop() { - connected = false; - } - - private void attemptConnect() throws Exception { - Thread.sleep(CONNECT_INTERVAL); - Pattern pattern = Pattern.compile("[/:]+"); - String[] strs = pattern.split(remoteEnv.path); - - //host,如:192.168.100.195 - String shost = strs[1]; - //端口,如:8080 - int sport = Integer.parseInt(strs[2]); - - Socket socket = new Socket(shost, sport); - //OOBBINLINE:是否支持发送一个字节的TCP紧急数据,false表示服务器不用处理这个数据 - socket.setOOBInline(false); - socket.sendUrgentData(0xFF); - socket.close(); - } - } - - /** - * 读报表运行环境所需的配置文件,如datasource.xml, config.xml,这些文件都保存在WEB-INF/resources目录下面 - * - * @param resourceName 配置文件的名字,如datasource.xml - * @return 输入流 - * @throws Exception e - */ - @Override - public InputStream readResource(String resourceName) throws Exception { - return readBean(resourceName, ProjectConstants.RESOURCES_NAME); - } - /** * 读取路径下的svg文件 @@ -1555,35 +754,6 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl return new Bytes2ServerOutputStream(para); } - /** - * 返回数据库表的列名 - * - * @param selectedName 所选择数据库名 - * @param schema 数据库模式,用于存储过程 - * @param tableName 所选择数据库名 - */ - @Override - public String[] getColumns(String selectedName, String schema, String tableName) throws Exception { - HashMap para = new HashMap<>(); - para.put("op", "fr_remote_design"); - para.put("cmd", "design_columns"); - para.put("dsName", selectedName); - para.put("schema", schema); - para.put("tableName", tableName); - - HttpClient client = createHttpMethod2(para); - InputStream input = execute4InputStream(client); - - if (input == null) { - return null; - } - - String colums = stream2String(input); - if (StringUtils.isEmpty(colums)) { - return null; - } - return colums.split("\\."); - } /** * 返回模板文件路径 @@ -1593,139 +763,6 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl return getPath().substring(0, getPath().lastIndexOf("/")); } - @Override - public String getProcedureText(String connectionName, String databaseName) throws Exception { - HashMap para = new HashMap<>(); - para.put("op", "fr_remote_design"); - para.put("cmd", "design_get_procedure_text"); - para.put("procedure_name", databaseName); - para.put("connectionName", connectionName); - - ByteArrayOutputStream out = new ByteArrayOutputStream(); - InputStream input = postBytes2ServerB(out.toByteArray(), para); - if (input == null) { - return StringUtils.EMPTY; - } - return DavXMLUtils.readXMLProcedureText(input); - } - - @Override - public StoreProcedureParameter[] getStoreProcedureDeclarationParameters(String connectionName, String databaseName, String parameterDefaultValue) throws Exception { - ByteArrayOutputStream out = new ByteArrayOutputStream(); - HashMap para = new HashMap<>(); - para.put("op", "fr_remote_design"); - para.put("cmd", "design_get_sp_parameters"); - para.put("__name__", databaseName); - para.put("__default_value__", parameterDefaultValue); - para.put("connectionName", connectionName); - - InputStream input = postBytes2ServerB(out.toByteArray(), para); - if (input == null) { - return new StoreProcedureParameter[0]; - } - return DavXMLUtils.readXMLStoreProcedureParameters(input); - } - - /** - * 获取datasource.xml文件的修改表 - */ - @Override - public ModifiedTable getDataSourceModifiedTables(String type) { - try { - HashMap para = new HashMap<>(); - para.put("op", "fr_remote_design"); - para.put("cmd", "get_datasource_modified_tables"); - para.put("type", type); - - HttpClient client = createHttpMethod(para); - InputStream input = execute4InputStream(client); - if (input == null) { - return new ModifiedTable(); - } - return DavXMLUtils.readXMLModifiedTables(input); - } catch (Exception e) { - FRContext.getLogger().error(e.getMessage()); - } - return new ModifiedTable(); - } - - - /** - * 写修改表 - * - * @param modifiedTable 修改表 - * @param type 操作类型,是数据连接还是服务器数据集 - * @return 写入成功返回true - */ - @Override - public boolean writeDataSourceModifiedTables(ModifiedTable modifiedTable, String type) { - - ByteArrayOutputStream out = new ByteArrayOutputStream(); - - // 把tableData写成xml文件到out - DavXMLUtils.writeXMLModifiedTables(modifiedTable, out); - try { - HashMap para = new HashMap<>(); - para.put("op", "fr_remote_design"); - para.put("cmd", "update_modifytable_to_server"); - para.put("type", type); - - InputStream input = postBytes2ServerB(out.toByteArray(), para); - - if (input == null) { - return false; - } - - return Boolean.valueOf(IOUtils.inputStream2String(input, EncodeConstants.ENCODING_UTF_8)); - } catch (Exception e) { - FRContext.getLogger().error(e.getMessage()); - } - return false; - } - - public String[] getProcedureColumns(StoreProcedure storeProcedure, java.util.Map parameterMap) throws Exception { - String[] columns; - HashMap para = new HashMap<>(); - para.put("op", "fr_remote_design"); - para.put("cmd", "list_sp"); - HttpClient client = createHttpMethod(para); - try { - InputStream input = execute4InputStream(client); - - if (input == null) { - return ArrayUtils.EMPTY_STRING_ARRAY; - } - - columns = DavXMLUtils.readXMLSPColumns(input); - return columns; - } catch (Exception e) { - FRContext.getLogger().error(e.getMessage()); - } - - return new String[0]; - } - - public String[] getProcedureColumns(String name) throws Exception { - String[] columns; - HashMap para = new HashMap<>(); - para.put("op", "fr_remote_design"); - para.put("cmd", "list_sp_columns_name"); - para.put("name", name); - HttpClient client = createHttpMethod(para); - try { - InputStream input = execute4InputStream(client); - if (input == null) { - return ArrayUtils.EMPTY_STRING_ARRAY; - } - columns = DavXMLUtils.readXMLSPColumns(input); - return columns; - } catch (Exception e) { - FRContext.getLogger().error(e.getMessage()); - } - return new String[0]; - - } - /** * 输出日志信息 * @@ -1733,19 +770,7 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl */ @Override public void printLogMessage() throws Exception { - ByteArrayOutputStream out = new ByteArrayOutputStream(); - HashMap para = new HashMap<>(); - para.put("op", "fr_remote_design"); - para.put("cmd", "get_log_message"); - - InputStream input = postBytes2ServerB(out.toByteArray(), para); - if (input == null) { - return; - } - LogRecordTime[] records = LogUtils.readXMLLogRecords(input); - for (LogRecordTime logRecordTime : records) { - //TODO - } + throw new UnsupportedOperationException("unsupport now"); } @Override @@ -1754,96 +779,11 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl } - /** - * 预览存储过程 - * - * @param storeProcedure 存储过程 - * @param parameterMap 参数map - * @param rowCount 行数 - * @return 返回取到的存储过程 - */ - @Override - public ProcedureDataModel[] previewProcedureDataModel(StoreProcedure storeProcedure, Map parameterMap, int rowCount) { - ByteArrayOutputStream out = new ByteArrayOutputStream(); - - // 把tableData写成xml文件到out - DavXMLUtils.writeXMLFileStoreProcedureAndSource(storeProcedure, out); - - // 把parameterMap转成JSON格式的字符串 - JSONObject jo = new JSONObject(parameterMap); - String jsonParameter = jo.toString(); - - try { - HashMap para = new HashMap<>(); - para.put("op", "fr_remote_design"); - para.put("cmd", "list_sp"); - para.put("pars", jsonParameter); - - InputStream input = postBytes2ServerB(out.toByteArray(), para); - if (input == null) { - return null; - } - - TableData[] tableDatas = DavXMLUtils.readXMLTableDataArray(input); - if (tableDatas == null || tableDatas.length == 0) { - return new ProcedureDataModel[0]; - } - ProcedureDataModel[] procedureDataModels = new ProcedureDataModel[tableDatas.length]; - for (int i = 0; i < tableDatas.length; i++) { - if (tableDatas[i] instanceof EmbeddedTableData) { - procedureDataModels[i] = ((EmbeddedTableData) tableDatas[i]).trans2ProcedureDataModel(); - } - } - return procedureDataModels; - - - } catch (Exception e) { - FRContext.getLogger().error(e.getMessage()); - } - return new ProcedureDataModel[0]; - } - - - @Override - public String getAppName() { - return "WebReport"; - } - - /** - * 是否为Oracle数据连接 - * - * @param database 数据连接 - * @return 是返回true - * @throws Exception - */ - @Override - public boolean isOracle(Connection database) throws Exception { - ByteArrayOutputStream out = new ByteArrayOutputStream(); - DavXMLUtils.writeXMLFileDatabaseConnection(database, out); - HashMap para = new HashMap<>(); - para.put("op", "fr_remote_design"); - para.put("cmd", "design_get_isOracle"); - InputStream input = postBytes2ServerB(out.toByteArray(), para); - if (input == null) { - return true; - } - return DavXMLUtils.readXMLBoolean(input); - } - @Override public String[] getSupportedTypes() { return FILE_TYPE; } - /** - * 在模板面板中是否支持增加打开所在文件夹、重命名、删除三个工具栏选项 - * - * @return 不支持返回false - */ - @Override - public boolean isSupportLocalFileOperate() { - return false; - } /** * 判断是否有文件夹权限 @@ -1875,42 +815,6 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl } - /** - * 是否是管理员身份 - * - * @return 是则返回true - */ - @Override - public boolean isRoot() { - return isRoot; - } - - /** - * 是否为压缩包部署 - * - * @return 是则返回true - */ - @Override - public boolean isPackDeploy() { - return false; - } - - @Override - public String getDesignerVersion() throws Exception { - HashMap para = new HashMap<>(); - para.put("op", "fr_remote_design"); - para.put("cmd", "design_get_designer_version"); - para.put("user", user); - para.put("password", getEncodedPassword()); - - HttpClient client = createHttpMethod(para, true); - try { - return stream2String(execute4InputStream(client)); - } catch (Exception e) { - FRContext.getLogger().error(e.getMessage()); - } - return null; - } @Override public InputStream getDataSourceInputStream(String filePath) throws Exception { @@ -1940,16 +844,6 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl return allRoleList; } - @Override - public String getLicName() { - return License.FILE_NAME; - } - - @Override - public void setLicName(String licName) { - //do nth - } - /** * 获取当前env的build文件路径 @@ -2128,16 +1022,6 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl } } - @Override - public void doWhenServerShutDown() { - - } - - @Override - public boolean isLocalEnv() { - - return false; - } @Override public boolean hasPluginServiceStarted(String key) { @@ -2145,21 +1029,4 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl return true; } - @Override - public JSONArray getPluginStatus() { - - try { - HashMap para = new HashMap<>(); - para.put("op", "plugin"); - para.put("cmd", "get_status"); - para.put("current_uid", this.createUserID()); - para.put("currentUsername", this.getUser()); - - HttpClient client = createHttpMethod(para); - InputStream input = execute4InputStream(client); - return new JSONArray(stream2String(input)); - } catch (Exception e) { - return JSONArray.create(); - } - } } \ No newline at end of file diff --git a/designer-base/src/com/fr/env/RemoteEnvPane.java b/designer-base/src/com/fr/env/RemoteEnvPane.java index 77ae0b451..20ca4715a 100644 --- a/designer-base/src/com/fr/env/RemoteEnvPane.java +++ b/designer-base/src/com/fr/env/RemoteEnvPane.java @@ -1,6 +1,8 @@ package com.fr.env; import com.fr.base.FRContext; +import com.fr.base.env.resource.EnvConfigUtils; +import com.fr.base.env.resource.RemoteEnvConfig; import com.fr.design.DesignerEnvManager; import com.fr.design.beans.BasicBeanPane; import com.fr.design.border.UITitledBorder; @@ -49,7 +51,7 @@ import static com.fr.design.layout.TableLayout.PREFERRED; /** * @author yaohwu */ -public class RemoteEnvPane extends BasicBeanPane { +public class RemoteEnvPane extends BasicBeanPane { private static final Color TIPS_FONT_COLOR = new Color(0x8f8f92); @@ -100,7 +102,7 @@ public class RemoteEnvPane extends BasicBeanPane { /** * 主机位置 */ - private RemoteEnvURL remoteEnvURL; + private RemoteEnvURL remoteEnvURL = new RemoteEnvURL(""); /** * https 配置面板 */ @@ -151,6 +153,7 @@ public class RemoteEnvPane extends BasicBeanPane { @Override public void removeUpdate(DocumentEvent e) { + actionURLInputChange(); } @@ -250,7 +253,7 @@ public class RemoteEnvPane extends BasicBeanPane { } @Override - public void populateBean(RemoteEnv ob) { + public void populateBean(RemoteEnvConfig ob) { if (StringUtils.isEmpty(ob.getPath())) { remoteEnvURL = RemoteEnvURL.createDefaultURL(); @@ -265,18 +268,20 @@ public class RemoteEnvPane extends BasicBeanPane { fileChooserButton.setEnabled(remoteEnvURL.getHttps()); updateHttpsConfigPanel(); - this.usernameInput.setText(ob.getUser() == null ? StringUtils.EMPTY : ob.getUser()); + String username = EnvConfigUtils.getUsername(ob); + String pwd = EnvConfigUtils.getPassword(ob); + this.usernameInput.setText(username == null ? StringUtils.EMPTY : pwd); this.passwordInput.setText(ob.getPassword() == null ? StringUtils.EMPTY : ob.getPassword()); } @Override - public RemoteEnv updateBean() { + public RemoteEnvConfig updateBean() { String path = remoteEnvURL.getURL(); String user = this.usernameInput.getText(); String password = new String(this.passwordInput.getPassword()); - return new RemoteEnv(path, user, password); + return new RemoteEnvConfig(path, user, password); } @Override From 55b20fe0a68bfe838884883901d82f23cf68e53b Mon Sep 17 00:00:00 2001 From: hzzz Date: Tue, 29 May 2018 20:29:42 +0800 Subject: [PATCH 7/9] merge --- designer-base/src/com/fr/env/RemoteEnv.java | 11 ++++------- 1 file changed, 4 insertions(+), 7 deletions(-) diff --git a/designer-base/src/com/fr/env/RemoteEnv.java b/designer-base/src/com/fr/env/RemoteEnv.java index b09f1cb98..74995cf1d 100644 --- a/designer-base/src/com/fr/env/RemoteEnv.java +++ b/designer-base/src/com/fr/env/RemoteEnv.java @@ -81,9 +81,6 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl private static final String PWD_KEY = "javax.net.ssl.trustStorePassword"; private static final String HTTPS_PREFIX = "https:"; private final static String[] FILE_TYPE = {"cptx", "cpt", "frm", "form", "cht", "chart"}; - private String path; - private String userID; - private boolean isReadTimeOut = false; private String buildFilePath; private RemoteEnvConfig env; @@ -125,7 +122,7 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl * 根据nameValuePairs,也就是参数对,生成PostMethod */ private HttpClient createHttpMethod(HashMap para, boolean isSignIn) throws EnvException { - String methodPath = this.path; + String methodPath = getPath(); if (!isSignIn) { methodPath = methodPath + "?id=" + createUserID(); } @@ -144,7 +141,7 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl * 根据nameValuePairs,也就是参数对,生成PostMethod,不同之处在于,参数拼在path后面,不是method.addParameters */ private HttpClient createHttpMethod2(HashMap para) throws EnvException, UnsupportedEncodingException { - String methodPath = path + '?' + "id=" + createUserID(); + String methodPath = getPath() + '?' + "id=" + createUserID(); return new HttpClient(methodPath); } @@ -333,7 +330,7 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl private void setHttpsParas() { - if (path.startsWith(HTTPS_PREFIX) && System.getProperty(CERT_KEY) == null) { + if (getPath().startsWith(HTTPS_PREFIX) && System.getProperty(CERT_KEY) == null) { DesignerEnvManager envManager = DesignerEnvManager.getEnvManager(); System.setProperty(CERT_KEY, envManager.getCertificatePath()); System.setProperty(PWD_KEY, envManager.getCertificatePass()); @@ -775,7 +772,7 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl @Override public String getUserID() { - return userID; + return EnvContext.currentToken(); } From e9cec1e07394b7bca227996d343428c993de762f Mon Sep 17 00:00:00 2001 From: hzzz Date: Wed, 30 May 2018 16:32:11 +0800 Subject: [PATCH 8/9] merge --- .../loghandler/socketio/DesignerSocketIO.java | 6 +- designer-base/src/com/fr/env/RemoteEnv.java | 377 ++++++++++-------- .../src/com/fr/env/RemoteEnvUtils.java | 165 ++++++-- 3 files changed, 325 insertions(+), 223 deletions(-) diff --git a/designer-base/src/com/fr/design/mainframe/loghandler/socketio/DesignerSocketIO.java b/designer-base/src/com/fr/design/mainframe/loghandler/socketio/DesignerSocketIO.java index 14be4cfb1..7e3746089 100644 --- a/designer-base/src/com/fr/design/mainframe/loghandler/socketio/DesignerSocketIO.java +++ b/designer-base/src/com/fr/design/mainframe/loghandler/socketio/DesignerSocketIO.java @@ -31,10 +31,8 @@ public class DesignerSocketIO { private static final Emitter.Listener printLog = new Emitter.Listener() { @Override public void call(Object... objects) { - //TODO 这里要测试一下类型 - String object = (String) objects[0]; try { - LogRecordTime[] logRecordTimes = LogUtils.readXMLLogRecords(new ByteArrayInputStream(object.getBytes())); + LogRecordTime[] logRecordTimes = LogUtils.readXMLLogRecords(new ByteArrayInputStream((byte[]) objects[0])); for (LogRecordTime logRecordTime : logRecordTimes) { DesignerLogHandler.getInstance().printRemoteLog(logRecordTime); } @@ -73,7 +71,7 @@ public class DesignerSocketIO { } try { - String uri = String.format("http://%s:%s/%s?%s=%s", + String uri = String.format("http://%s:%s%s?%s=%s", new URL(env.getPath()).getHost(), WebSocketConfig.getInstance().getPort(), EnvConstants.WS_NAMESPACE, diff --git a/designer-base/src/com/fr/env/RemoteEnv.java b/designer-base/src/com/fr/env/RemoteEnv.java index 74995cf1d..373b15f48 100644 --- a/designer-base/src/com/fr/env/RemoteEnv.java +++ b/designer-base/src/com/fr/env/RemoteEnv.java @@ -3,6 +3,9 @@ package com.fr.env; import com.fr.base.AbstractEnv; import com.fr.base.EnvException; import com.fr.base.FRContext; +import com.fr.base.ModifiedTable; +import com.fr.base.Parameter; +import com.fr.base.StoreProcedureParameter; import com.fr.base.TableData; import com.fr.base.Utils; import com.fr.base.env.EnvContext; @@ -10,27 +13,42 @@ import com.fr.base.env.resource.RemoteEnvConfig; import com.fr.base.remote.RemoteDeziConstants; import com.fr.core.env.EnvConstants; import com.fr.data.TableDataSource; +import com.fr.data.core.DataCoreUtils; +import com.fr.data.core.db.TableProcedure; +import com.fr.data.impl.Connection; import com.fr.data.impl.EmbeddedTableData; +import com.fr.data.impl.storeproc.ProcedureDataModel; +import com.fr.data.impl.storeproc.StoreProcedure; import com.fr.dav.DavXMLUtils; +import com.fr.dav.UserBaseEnv; import com.fr.design.DesignerEnvManager; import com.fr.design.ExtraDesignClassManager; +import com.fr.design.dialog.InformationWarnPane; +import com.fr.design.file.HistoryTemplateListPane; import com.fr.design.fun.DesignerEnvProcessor; import com.fr.design.mainframe.DesignerContext; +import com.fr.design.mainframe.DesignerFrameFileDealerPane; import com.fr.file.CacheManager; import com.fr.file.ConnectionConfig; import com.fr.file.TableDataConfig; +import com.fr.file.filetree.FileNode; +import com.fr.general.CommonIOUtils; import com.fr.general.ComparatorUtils; import com.fr.general.IOUtils; import com.fr.general.Inter; -import com.fr.general.http.HttpClient; +import com.fr.general.LogRecordTime; +import com.fr.general.LogUtils; import com.fr.general.http.HttpToolbox; import com.fr.io.utils.ResourceIOUtils; import com.fr.json.JSONArray; import com.fr.json.JSONException; import com.fr.json.JSONObject; +import com.fr.license.function.VT4FR; import com.fr.log.FineLoggerFactory; +import com.fr.regist.License; import com.fr.report.DesignAuthority; import com.fr.share.ShareConstants; +import com.fr.stable.ArrayUtils; import com.fr.stable.EncodeConstants; import com.fr.stable.Filter; import com.fr.stable.JavaCompileInfo; @@ -40,11 +58,15 @@ import com.fr.stable.StringUtils; import com.fr.stable.SvgProvider; import com.fr.stable.file.XMLFileManagerProvider; import com.fr.stable.project.ProjectConstants; +import com.fr.stable.xml.XMLPrintWriter; import com.fr.stable.xml.XMLTools; +import com.fr.stable.xml.XMLableReader; import com.fr.third.guava.collect.ImmutableMap; import com.fr.web.ResourceConstants; +import com.fr.report.util.AuthorityXMLUtils; import javax.swing.JOptionPane; +import javax.swing.UIManager; import javax.xml.transform.Source; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; @@ -64,11 +86,18 @@ import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.UnsupportedEncodingException; -import java.net.HttpURLConnection; +import java.net.NoRouteToHostException; +import java.net.Socket; +import java.net.URLEncoder; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; +import java.util.List; import java.util.Map; +import java.util.Timer; +import java.util.TimerTask; +import java.util.logging.Level; +import java.util.regex.Pattern; import static com.fr.third.guava.base.Preconditions.checkArgument; @@ -76,7 +105,6 @@ import static com.fr.third.guava.base.Preconditions.checkArgument; * @author null */ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurable { - private static final String CERT_KEY = "javax.net.ssl.trustStore"; private static final String PWD_KEY = "javax.net.ssl.trustStorePassword"; private static final String HTTPS_PREFIX = "https:"; @@ -89,9 +117,6 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl env = new RemoteEnvConfig(path, userName, password); } - /** - * 返回env配置路径 - */ @Override public String getPath() { return env.getPath(); @@ -102,82 +127,25 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl return env.getUsername(); } - public String getPassword() { return env.getPassword(); } - /** - * 所有与服务器端交互前,都要调用这个方法生成UserID - */ - private String createUserID() { + @Override + public String getUserID() { return EnvContext.currentToken(); } - private HttpClient createHttpMethod(HashMap para) throws EnvException { - return createHttpMethod(para, false); - } - - /** - * 根据nameValuePairs,也就是参数对,生成PostMethod - */ - private HttpClient createHttpMethod(HashMap para, boolean isSignIn) throws EnvException { - String methodPath = getPath(); - if (!isSignIn) { - methodPath = methodPath + "?id=" + createUserID(); - } - HttpClient client = new HttpClient(methodPath, para); - /* - todo post 方法好象过去不了 - 但是get方法也会有一些url参数问题,尤其是图表部分 - 比如: - op=fr_remote_design&cmd=design_get_plugin_service_data&serviceID=plugin.phantomjs&req= - */ - client.asGet(); - return client; - } - - /** - * 根据nameValuePairs,也就是参数对,生成PostMethod,不同之处在于,参数拼在path后面,不是method.addParameters - */ - private HttpClient createHttpMethod2(HashMap para) throws EnvException, UnsupportedEncodingException { - String methodPath = getPath() + '?' + "id=" + createUserID(); - return new HttpClient(methodPath); - } - - - /* - * Read the response body. - * 拿出InputStream中所有的Byte,转换成ByteArrayInputStream的形式返回 - * - * 这样做的目的是确保method.releaseConnection - * - * TODO 但如果不做method.releaseConnection,有多大危害呢?不确定... - */ - /** - * execute method之后,取返回的inputstream + * execute method之后,取返回的 InputStream */ - private ByteArrayInputStream execute4InputStream(HttpClient client) throws Exception { - setHttpsParas(); - try { - int statusCode = client.getResponseCode(); - if (statusCode != HttpURLConnection.HTTP_OK) { - //数据加载太多,屏蔽掉 - //doWithTimeOutException(); - throw new EnvException("Method failed: " + statusCode); - } - } catch (Exception e) { - FRContext.getLogger().info("Connection reset "); - } - InputStream in = client.getResponseStream(); + private InputStream filterInputStream(InputStream in) throws Exception { if (in == null) { return null; } ByteArrayOutputStream out = new ByteArrayOutputStream(); try { - Utils.copyBinaryTo(in, out); - + IOUtils.copyBinaryTo(in, out); // 看一下传过来的byte[]是不是DesignProcessor.INVALID,如果是的话,就抛Exception byte[] bytes = out.toByteArray(); // carl:格式一致传中文 @@ -195,7 +163,6 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl synchronized (this) { in.close(); out.close(); - client.release(); } } } @@ -210,10 +177,7 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl * @throws Exception 异常 */ private boolean postBytes2Server(byte[] bytes, HashMap para) throws Exception { - HttpClient client = createHttpMethod2(para); - client.setContent(bytes); - execute4InputStream(client); - + filterInputStream(RemoteEnvUtils.simulateRPCByHttpPost(bytes, para, false, this)); return true; } @@ -227,27 +191,13 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl if (in == null) { return null; } - BufferedReader br; + String result = null; try { - br = new BufferedReader(new InputStreamReader(in, EncodeConstants.ENCODING_UTF_8)); + result = CommonIOUtils.inputStream2String(in, EncodeConstants.ENCODING_UTF_8); } catch (UnsupportedEncodingException e) { - br = new BufferedReader(new InputStreamReader(in)); - } - StringBuilder sb = new StringBuilder(); - String line; - - try { - while ((line = br.readLine()) != null) { - if (sb.length() > 0) { - sb.append('\n'); - } - sb.append(line); - } - } catch (IOException e) { FRContext.getLogger().error(e.getMessage(), e); } - - return sb.toString(); + return result; } /** @@ -328,8 +278,7 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl } - - private void setHttpsParas() { + private void refreshHttpSProperty() { if (getPath().startsWith(HTTPS_PREFIX) && System.getProperty(CERT_KEY) == null) { DesignerEnvManager envManager = DesignerEnvManager.getEnvManager(); System.setProperty(CERT_KEY, envManager.getCertificatePath()); @@ -338,7 +287,11 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl } - + /** + * 心跳访问,用来更新当前用户的访问时间 + * + * @throws Exception e + */ /** * 返回描述该运行环境的名字 @@ -350,15 +303,6 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl return Inter.getLocText("Env-Remote_Server"); } - /** - * 登录,返回userID - */ - @Override - public void signIn() throws Exception { - throw new UnsupportedOperationException("unsupport now"); - } - - public class Bytes2ServerOutputStream extends OutputStream { private ByteArrayOutputStream out = new ByteArrayOutputStream(); private HashMap nameValuePairs; @@ -416,20 +360,35 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl } } - @Override public boolean updateAuthorities(DesignAuthority[] authorities) { - return RemoteEnvUtils.updateAuthorities(authorities, this); + refreshHttpSProperty(); + String res = null; + try { + InputStream inputStream = RemoteEnvUtils.updateAuthorities(authorities, this); + inputStream = filterInputStream(inputStream); + res = IOUtils.inputStream2String(inputStream, EncodeConstants.ENCODING_UTF_8); + } catch (Exception e) { + FRContext.getLogger().error(e.getMessage()); + } + return StringUtils.isNotEmpty(res) && Boolean.valueOf(res); } @Override public DesignAuthority[] getAuthorities() { - - return RemoteEnvUtils.getAuthorities(this); - + refreshHttpSProperty(); + DesignAuthority[] authorities = new DesignAuthority[0]; + try { + InputStream inputStream = RemoteEnvUtils.getAuthorities(this); + inputStream = filterInputStream(inputStream); + authorities = AuthorityXMLUtils.readDesignAuthoritiesXML(inputStream); + return authorities; + } catch (Exception e) { + FRContext.getLogger().error(e.getMessage()); + } + return authorities; } - /** * 远程设计器设计时,假如开了权限就不可预览了。这边放一个全局的map来开后门 * @@ -439,6 +398,7 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl * @throws Exception e */ public boolean writePrivilegeMap(String key, String value) throws Exception { + refreshHttpSProperty(); HashMap para = new HashMap<>(); para.put("op", "fr_remote_design"); para.put("cmd", "write_privilege_map"); @@ -448,8 +408,9 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl para.put("value", value); //jim :加上user,远程设计点击预览时传递用户角色信息 - HttpClient client = createHttpMethod(para); - InputStream input = execute4InputStream(client); + InputStream input = filterInputStream( + RemoteEnvUtils.simulateRPCByHttpGet(para, false, this) + ); if (input == null) { return false; @@ -463,6 +424,7 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl */ @Override public void removeNoPrivilegeConnection() { + refreshHttpSProperty(); TableDataConfig dm = TableDataConfig.getInstance(); try { @@ -472,8 +434,9 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl para.put("currentUsername", this.getUser()); para.put("currentPwd", this.getPassword()); - HttpClient client = createHttpMethod(para); - InputStream input = execute4InputStream(client); + InputStream input = filterInputStream( + RemoteEnvUtils.simulateRPCByHttpGet(para, false, this) + ); JSONArray ja = new JSONArray(stream2String(input)); ArrayList toBeRemoveTDName = new ArrayList<>(); for (int i = 0; i < ja.length(); i++) { @@ -495,7 +458,6 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl } } - @Override public EmbeddedTableData previewTableData(Object tableData, Map parameterMap, int rowCount) throws Exception { return previewTableData(null, tableData, parameterMap, rowCount); @@ -565,16 +527,8 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl * @throws Exception 异常 */ public InputStream postBytes2ServerB(byte[] bytes, HashMap para) throws Exception { - HttpClient client = createHttpMethod2(para); - /* - todo post 方法好象过去不了 - 但是get方法也会有一些url参数问题,尤其是图表部分 - 比如: - op=fr_remote_design&cmd=design_get_plugin_service_data&serviceID=plugin.phantomjs&req= - */ -// client.asGet(); - client.setContent(bytes); - return execute4InputStream(client); + refreshHttpSProperty(); + return filterInputStream(RemoteEnvUtils.simulateRPCByHttpPost(bytes, para, false, this)); } @@ -586,28 +540,29 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl */ @Override public String[] readPathSvgFiles(String path) { + refreshHttpSProperty(); String cataloguePath = StableUtils.pathJoin(CacheManager.getProviderInstance().getCacheDirectory().getPath(), SvgProvider.SERVER, path); - ArrayList fileArray = new ArrayList<>(); try { HashMap para = new HashMap<>(); para.put("op", "fr_remote_design"); para.put("cmd", "design_read_svgfile"); para.put("resourcePath", path); - para.put("current_uid", this.createUserID()); + para.put("current_uid", this.getUserID()); para.put("currentUsername", this.getUser()); - HttpClient client = createHttpMethod(para); - InputStream input = execute4InputStream(client); + InputStream input = filterInputStream( + RemoteEnvUtils.simulateRPCByHttpGet(para, false, this) + ); JSONArray ja = new JSONArray(stream2String(input)); for (int i = 0; i < ja.length(); i++) { JSONObject jsonObject = (JSONObject) ja.get(i); String svgFileName = (String) jsonObject.get("svgfileName"); - String svgfileContent = (String) jsonObject.get("svgfileContent"); + String svgFileContent = (String) jsonObject.get("svgfileContent"); String file = StableUtils.pathJoin(cataloguePath, svgFileName); - InputStream in = new ByteArrayInputStream(svgfileContent.getBytes(EncodeConstants.ENCODING_UTF_8)); + InputStream in = new ByteArrayInputStream(svgFileContent.getBytes(EncodeConstants.ENCODING_UTF_8)); ResourceIOUtils.write(file, in); fileArray.add(file); } @@ -615,7 +570,7 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl FRContext.getLogger().error(e.getMessage()); } - return fileArray.toArray(new String[fileArray.size()]); + return fileArray.toArray(new String[0]); } @@ -634,7 +589,7 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl para.put("op", "svgrelate"); para.put("cmd", "design_save_svg"); para.put("filePath", svgFile.getFilePath()); - para.put("current_uid", this.createUserID()); + para.put("current_uid", this.getUserID()); para.put("currentUsername", this.getUser()); // 通过ByteArrayOutputStream将svg写成字节流 @@ -657,9 +612,9 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl } try { - HttpClient client = createHttpMethod2(out.getNameValuePairs()); - client.setContent(out.getOut().toByteArray()); - String res = stream2String(execute4InputStream(client)); + String res = stream2String(filterInputStream( + RemoteEnvUtils.simulateRPCByHttpPost(out.getOut().toByteArray(), out.nameValuePairs, false, this) + )); if (StringUtils.isNotEmpty(res)) { JOptionPane.showMessageDialog(null, Inter.getLocText("FR-Already_exist") + res); return false; @@ -688,7 +643,7 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl para.put("cmd", "design_save_resource"); para.put("resource", mgr.fileName()); para.put("class_name", mgr.getClass().getName()); - para.put("current_uid", this.createUserID()); + para.put("current_uid", this.getUserID()); para.put("currentUsername", this.getUser()); // alex:通过ByteArrayOutputStream将mgr写成字节流 @@ -696,9 +651,11 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl XMLTools.writeOutputStreamXML(mgr, out); try { - HttpClient client = createHttpMethod2(out.getNameValuePairs()); - client.setContent(out.getOut().toByteArray()); - String res = stream2String(execute4InputStream(client)); + String res = stream2String( + filterInputStream( + RemoteEnvUtils.simulateRPCByHttpPost(out.getOut().toByteArray(), out.nameValuePairs, false, this) + ) + ); if (StringUtils.isNotEmpty(res)) { JOptionPane.showMessageDialog(null, Inter.getLocText("FR-Already_exist") + res); return false; @@ -721,16 +678,14 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl @Override public InputStream readBean(String beanPath, String prefix) throws Exception { + refreshHttpSProperty(); HashMap para = new HashMap<>(); para.put("op", "fs_remote_design"); para.put("cmd", "design_open"); para.put(RemoteDeziConstants.PREFXI, prefix); para.put("resource", beanPath); - HttpClient client = createHttpMethod(para); - // return Utils.toZipIn(execute4InputStream(method)); - //Utils.toZipIn这边有bug,远程连接的时候datasource.xml不能读取,先还原了 - return execute4InputStream(client); + return filterInputStream(RemoteEnvUtils.simulateRPCByHttpGet(para, false, this)); } /** @@ -751,7 +706,6 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl return new Bytes2ServerOutputStream(para); } - /** * 返回模板文件路径 */ @@ -760,22 +714,72 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl return getPath().substring(0, getPath().lastIndexOf("/")); } + public String[] getProcedureColumns(StoreProcedure storeProcedure, Map parameterMap) throws Exception { + refreshHttpSProperty(); + String[] columns; + HashMap para = new HashMap<>(); + para.put("op", "fr_remote_design"); + para.put("cmd", "list_sp"); + try { + InputStream input = filterInputStream( + RemoteEnvUtils.simulateRPCByHttpGet(para, false, this) + ); + + if (input == null) { + return ArrayUtils.EMPTY_STRING_ARRAY; + } + + columns = DavXMLUtils.readXMLSPColumns(input); + return columns; + } catch (Exception e) { + FRContext.getLogger().error(e.getMessage()); + } + + return new String[0]; + } + + public String[] getProcedureColumns(String name) throws Exception { + refreshHttpSProperty(); + String[] columns; + HashMap para = new HashMap<>(); + para.put("op", "fr_remote_design"); + para.put("cmd", "list_sp_columns_name"); + para.put("name", name); + try { + InputStream input = filterInputStream( + RemoteEnvUtils.simulateRPCByHttpGet(para, false, this) + ); + if (input == null) { + return ArrayUtils.EMPTY_STRING_ARRAY; + } + columns = DavXMLUtils.readXMLSPColumns(input); + return columns; + } catch (Exception e) { + FRContext.getLogger().error(e.getMessage()); + } + return new String[0]; + + } + /** * 输出日志信息 * - * @throws Exception + * @throws Exception e */ @Override public void printLogMessage() throws Exception { - throw new UnsupportedOperationException("unsupport now"); - } + ByteArrayOutputStream out = new ByteArrayOutputStream(); + HashMap para = new HashMap<>(); + para.put("op", "fr_remote_design"); + para.put("cmd", "get_log_message"); - @Override - public String getUserID() { - return EnvContext.currentToken(); + InputStream input = postBytes2ServerB(out.toByteArray(), para); + if (input == null) { + return; + } + LogRecordTime[] records = LogUtils.readXMLLogRecords(input); } - @Override public String[] getSupportedTypes() { return FILE_TYPE; @@ -790,16 +794,17 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl */ @Override public boolean hasFileFolderAllow(String path) { - HttpClient client = null; + refreshHttpSProperty(); try { HashMap para = new HashMap<>(); para.put("op", "fs_remote_design"); para.put("cmd", "design_filefolder_allow"); - para.put("current_uid", this.createUserID()); + para.put("current_uid", this.getUserID()); para.put(RemoteDeziConstants.TEMPLATE_PATH, path); - client = createHttpMethod(para); - InputStream input = execute4InputStream(client); + InputStream input = filterInputStream( + RemoteEnvUtils.simulateRPCByHttpGet(para, false, this) + ); if (input == null) { return false; @@ -812,7 +817,6 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl } - @Override public InputStream getDataSourceInputStream(String filePath) throws Exception { return readBean(filePath, "datasource"); @@ -821,15 +825,17 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl @Override public ArrayList getAllRole4Privilege(boolean isFS) { - ArrayList allRoleList = new ArrayList(); + refreshHttpSProperty(); + ArrayList allRoleList = new ArrayList<>(); try { HashMap para = new HashMap<>(); para.put("op", "fr_remote_design"); para.put("cmd", "get_all_role"); para.put("isFS", String.valueOf(isFS)); - HttpClient client = createHttpMethod(para); - InputStream input = execute4InputStream(client); + InputStream input = filterInputStream( + RemoteEnvUtils.simulateRPCByHttpGet(para, false, this) + ); JSONArray ja = new JSONArray(stream2String(input)); for (int i = 0; i < ja.length(); i++) { String roleName = (String) ((JSONObject) ja.get(i)).get("name"); @@ -842,6 +848,7 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl } + /** * 获取当前env的build文件路径 */ @@ -885,14 +892,16 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl @Override public String pluginServiceAction(String serviceID, String req) throws Exception { + refreshHttpSProperty(); HashMap para = new HashMap<>(); para.put("op", "fr_remote_design"); para.put("cmd", "design_get_plugin_service_data"); para.put("serviceID", serviceID); para.put("req", req); //jim :加上user,远程设计点击预览时传递用户角色信息 - HttpClient client = createHttpMethod(para); - InputStream inputStream = execute4InputStream(client); + InputStream inputStream = filterInputStream( + RemoteEnvUtils.simulateRPCByHttpPost(para, false, this) + ); return IOUtils.inputStream2String(inputStream); } @@ -908,6 +917,7 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl @Override public String[] loadREUFile() { + refreshHttpSProperty(); ResourceIOUtils.delete(StableUtils.pathJoin( CacheManager.getProviderInstance().getCacheDirectory().getAbsolutePath(), ShareConstants.DIR_SHARE_CACHE)); @@ -917,12 +927,11 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl HashMap para = new HashMap<>(); para.put("op", "fr_remote_design"); para.put("cmd", "design_read_reufile"); - para.put("current_uid", this.createUserID()); + para.put("current_uid", this.getUserID()); para.put("currentUsername", this.getUser()); - HttpClient client = createHttpMethod(para); //拿到服务端传过来的整个共享文件夹的压缩文件的文件流 - InputStream input = client.getResponseStream(); + InputStream input = RemoteEnvUtils.simulateRPCByHttpGet(para, false, this); zipFilePath = StableUtils.pathJoin(CacheManager.getProviderInstance().getCacheDirectory().getAbsolutePath(), "share.zip"); String cacheDir = StableUtils.pathJoin(CacheManager.getProviderInstance().getCacheDirectory().getAbsolutePath(), ShareConstants.DIR_SHARE_CACHE); @@ -952,6 +961,7 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl @Override public boolean installREUFile(File reuFile) { + refreshHttpSProperty(); if (reuFile == null) { return false; } @@ -963,18 +973,27 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl HashMap para = new HashMap<>(); para.put("op", "fr_remote_design"); para.put("cmd", "design_install_reufile"); - para.put("current_uid", this.createUserID()); + para.put("current_uid", this.getUserID()); para.put("currentUsername", this.getUser()); para.put("reuFileName", reuFile.getName()); - HttpClient client = createHttpMethod(para); - client.setContent(IOUtils.inputStream2Bytes(new FileInputStream(new File(shareXMLName)))); - InputStream input = execute4InputStream(client); - client.release(); + InputStream input = filterInputStream( + RemoteEnvUtils.simulateRPCByHttpPost( + IOUtils.inputStream2Bytes( + new FileInputStream(new File(shareXMLName)) + ) + , para, + false, + this) + ); para.put("isComplete", "true"); - HttpClient client1 = createHttpMethod(para); - client1.setContent(IOUtils.inputStream2Bytes(new FileInputStream(new File(helpXMLName)))); - InputStream input1 = execute4InputStream(client1); + InputStream input1 = filterInputStream(RemoteEnvUtils.simulateRPCByHttpPost( + IOUtils.inputStream2Bytes( + new FileInputStream(new File(helpXMLName)) + ) + , para, + false, + this)); return ComparatorUtils.equals(stream2String(input), "true") && ComparatorUtils.equals(stream2String(input1), "true"); } catch (Exception e) { return false; @@ -983,6 +1002,7 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl @Override public boolean removeREUFilesByName(String fileName) { + refreshHttpSProperty(); if (StringUtils.isEmpty(fileName)) { return true; } @@ -990,12 +1010,13 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl HashMap para = new HashMap<>(); para.put("op", "fr_remote_design"); para.put("cmd", "design_remove_reufile"); - para.put("current_uid", this.createUserID()); + para.put("current_uid", this.getUserID()); para.put("currentUsername", this.getUser()); para.put("reuFileName", fileName); - HttpClient client = createHttpMethod(para); - InputStream input = execute4InputStream(client); + InputStream input = filterInputStream( + RemoteEnvUtils.simulateRPCByHttpGet(para, false, this) + ); return ComparatorUtils.equals(stream2String(input), "true"); } catch (Exception e) { return false; @@ -1004,15 +1025,17 @@ public class RemoteEnv extends AbstractEnv implements DesignAuthorityConfigurabl @Override public String getSharePath() { + refreshHttpSProperty(); try { HashMap para = new HashMap<>(); para.put("op", "fr_remote_design"); para.put("cmd", "design_get_share_path"); - para.put("current_uid", this.createUserID()); + para.put("current_uid", this.getUserID()); para.put("currentUsername", this.getUser()); - HttpClient client = createHttpMethod(para); - InputStream input = execute4InputStream(client); + InputStream input = filterInputStream( + RemoteEnvUtils.simulateRPCByHttpGet(para, false, this) + ); return stream2String(input); } catch (Exception e) { return StringUtils.EMPTY; diff --git a/designer-base/src/com/fr/env/RemoteEnvUtils.java b/designer-base/src/com/fr/env/RemoteEnvUtils.java index 5580222be..cf6b2d657 100644 --- a/designer-base/src/com/fr/env/RemoteEnvUtils.java +++ b/designer-base/src/com/fr/env/RemoteEnvUtils.java @@ -1,86 +1,167 @@ package com.fr.env; +import com.fr.base.EnvException; import com.fr.base.FRContext; -import com.fr.general.IOUtils; import com.fr.report.DesignAuthority; import com.fr.report.util.AuthorityXMLUtils; import com.fr.stable.EncodeConstants; -import com.fr.third.org.apache.http.HttpEntity; -import com.fr.third.org.apache.http.client.methods.CloseableHttpResponse; +import com.fr.third.org.apache.commons.io.IOUtils; +import com.fr.third.org.apache.http.HttpResponse; +import com.fr.third.org.apache.http.HttpStatus; +import com.fr.third.org.apache.http.client.ClientProtocolException; +import com.fr.third.org.apache.http.client.ResponseHandler; import com.fr.third.org.apache.http.client.methods.HttpUriRequest; import com.fr.third.org.apache.http.client.methods.RequestBuilder; import com.fr.third.org.apache.http.entity.ContentType; import com.fr.third.org.apache.http.entity.InputStreamEntity; import com.fr.third.org.apache.http.impl.client.CloseableHttpClient; import com.fr.third.org.apache.http.impl.client.HttpClients; -import com.fr.third.org.apache.http.util.EntityUtils; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; +import java.io.InputStream; +import java.net.URLEncoder; +import java.util.Map; public class RemoteEnvUtils { private RemoteEnvUtils() { } - public static boolean updateAuthorities(DesignAuthority[] authorities, RemoteEnv env) { + private static ResponseHandler responseHandler = new ResponseHandler() { + @Override + public InputStream handleResponse(HttpResponse response) throws IOException { + int statusCode = response.getStatusLine().getStatusCode(); + if (statusCode != HttpStatus.SC_OK) { + throw new ClientProtocolException("Method failed: " + response.getStatusLine().toString()); + } + InputStream in = response.getEntity().getContent(); + if (in == null) { + return null; + } + // 读取并返回 + ByteArrayOutputStream out = new ByteArrayOutputStream(); + IOUtils.copy(in, out); + return new ByteArrayInputStream(out.toByteArray()); + } + }; + + public static InputStream simulateRPCByHttpPost(byte[] bytes, Map parameters, boolean isSignIn, RemoteEnv env) throws EnvException { String path = env.getPath(); - String userID = env.getUserID(); + RequestBuilder builder = RequestBuilder.post(path); - String res = null; - CloseableHttpClient httpClient = HttpClients.createDefault(); + InputStream inputStream = null; - ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + for (Map.Entry entry : parameters.entrySet()) { + builder.addParameter(entry.getKey(), entry.getValue()); + } + if (!isSignIn) { + builder.addParameter("id", env.getUserID()); + } + InputStreamEntity reqEntity = new InputStreamEntity(new ByteArrayInputStream(bytes)); - AuthorityXMLUtils.writeDesignAuthoritiesXML(authorities, outputStream); + try (CloseableHttpClient httpClient = HttpClients.createSystem()) { + HttpUriRequest request = builder + .setEntity(reqEntity) + .build(); + inputStream = httpClient.execute(request, responseHandler); + } catch (IOException e) { + FRContext.getLogger().error(e.getMessage()); + } + return inputStream; + } + public static InputStream simulateRPCByHttpPost(Map parameters, boolean isSignIn, RemoteEnv env) throws EnvException { + String path = env.getPath(); + RequestBuilder builder = RequestBuilder.post(path); - InputStreamEntity reqEntity = new InputStreamEntity(new ByteArrayInputStream(outputStream.toByteArray()), ContentType.TEXT_XML); + InputStream inputStream = null; + + for (Map.Entry entry : parameters.entrySet()) { + builder.addParameter(entry.getKey(), entry.getValue()); + } + if (!isSignIn) { + builder.addParameter("id", env.getUserID()); + } - HttpUriRequest request = RequestBuilder.post(path) - .addParameter("id", userID) - .addParameter("op", "remote_design_authority") - .addParameter("cmd", "update_authorities") - .setEntity(reqEntity) - .build(); - - try { - CloseableHttpResponse response = httpClient.execute(request); - HttpEntity entity = response.getEntity(); - res = IOUtils.inputStream2String(entity.getContent(), EncodeConstants.ENCODING_UTF_8); - EntityUtils.consume(entity); + try (CloseableHttpClient httpClient = HttpClients.createSystem()) { + HttpUriRequest request = builder + .build(); + inputStream = httpClient.execute(request, responseHandler); } catch (IOException e) { FRContext.getLogger().error(e.getMessage()); } + return inputStream; + } + + public static InputStream simulateRPCByHttpGet(Map parameters, boolean isSignIn, RemoteEnv env) throws EnvException { + String path = env.getPath(); + RequestBuilder builder = RequestBuilder.get(path); - return res != null && Boolean.valueOf(res); + InputStream inputStream = null; + for (Map.Entry entry : parameters.entrySet()) { + builder.addParameter(entry.getKey(), entry.getValue()); + } + if (!isSignIn) { + builder.addParameter("id", env.getUserID()); + } + try (CloseableHttpClient httpClient = HttpClients.createSystem()) { + HttpUriRequest request = builder.build(); + inputStream = httpClient.execute(request, responseHandler); + + } catch (IOException e) { + FRContext.getLogger().error(e.getMessage()); + } + return inputStream; } - public static DesignAuthority[] getAuthorities(RemoteEnv env) { + + public static InputStream updateAuthorities(DesignAuthority[] authorities, RemoteEnv env) { String path = env.getPath(); + // 远程设计临时用户id String userID = env.getUserID(); - DesignAuthority[] authorities = null; - CloseableHttpClient httpClient = HttpClients.createDefault(); - - HttpUriRequest request = RequestBuilder.get(path) - .addParameter("id", userID) - .addParameter("op", "remote_design_authority") - .addParameter("cmd", "get_authorities") - .build(); - - try { - CloseableHttpResponse response = httpClient.execute(request); - HttpEntity entity = response.getEntity(); - - authorities = AuthorityXMLUtils.readDesignAuthoritiesXML(entity.getContent()); - EntityUtils.consume(entity); - } catch (Exception e) { + InputStream inputStream = null; + + ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + AuthorityXMLUtils.writeDesignAuthoritiesXML(authorities, outputStream); + InputStreamEntity reqEntity = new InputStreamEntity(new ByteArrayInputStream(outputStream.toByteArray()), ContentType.TEXT_XML); + + try (CloseableHttpClient httpClient = HttpClients.createSystem()) { + HttpUriRequest request = RequestBuilder.post(path) + .addParameter("id", userID) + .addParameter("op", "remote_design_authority") + .addParameter("cmd", "update_authorities") + .setEntity(reqEntity) + .build(); + inputStream = httpClient.execute(request, responseHandler); + } catch (IOException e) { FRContext.getLogger().error(e.getMessage()); } - return authorities; + return inputStream; + + } + + public static InputStream getAuthorities(RemoteEnv env) throws EnvException { + String path = env.getPath(); + // 远程设计临时用户id + String userID = env.getUserID(); + InputStream inputStream = null; + + try (CloseableHttpClient httpClient = HttpClients.createSystem();) { + HttpUriRequest request = RequestBuilder.get(path) + .addParameter("id", userID) + .addParameter("op", "remote_design_authority") + .addParameter("cmd", "get_authorities") + .build(); + inputStream = httpClient.execute(request, responseHandler); + } catch (IOException e) { + FRContext.getLogger().error(e.getMessage()); + } + return inputStream; } + } From 3838b06108bc132d2508c5bfb8023872cc9f7e40 Mon Sep 17 00:00:00 2001 From: hzzz Date: Wed, 30 May 2018 17:26:34 +0800 Subject: [PATCH 9/9] check --- .../src/com/fr/design/DesignerEnvManager.java | 2 - .../design/actions/file/SwitchExistEnv.java | 18 +------- .../com/fr/design/mainframe/TemplatePane.java | 43 ++++++++++++++----- designer-base/src/com/fr/env/EnvListPane.java | 2 - .../src/com/fr/start/server/FRTomcat.java | 8 ++-- .../src/com/fr/start/Designer4Debug.java | 6 +-- 6 files changed, 40 insertions(+), 39 deletions(-) diff --git a/designer-base/src/com/fr/design/DesignerEnvManager.java b/designer-base/src/com/fr/design/DesignerEnvManager.java index 8d6cbafed..c4266cf15 100644 --- a/designer-base/src/com/fr/design/DesignerEnvManager.java +++ b/designer-base/src/com/fr/design/DesignerEnvManager.java @@ -10,10 +10,8 @@ import com.fr.base.env.resource.EnvConfigUtils; import com.fr.base.env.resource.LocalEnvConfig; import com.fr.base.env.resource.RemoteEnvConfig; import com.fr.core.env.EnvConfig; -import com.fr.dav.LocalEnv; import com.fr.design.actions.help.alphafine.AlphaFineConfigManager; import com.fr.design.constants.UIConstants; -import com.fr.env.RemoteEnv; import com.fr.env.SignIn; import com.fr.file.FILEFactory; import com.fr.general.ComparatorUtils; diff --git a/designer-base/src/com/fr/design/actions/file/SwitchExistEnv.java b/designer-base/src/com/fr/design/actions/file/SwitchExistEnv.java index 2da352c83..602f440d9 100644 --- a/designer-base/src/com/fr/design/actions/file/SwitchExistEnv.java +++ b/designer-base/src/com/fr/design/actions/file/SwitchExistEnv.java @@ -1,17 +1,14 @@ package com.fr.design.actions.file; import com.fr.base.BaseUtils; -import com.fr.base.Env; import com.fr.base.FRContext; import com.fr.base.env.resource.LocalEnvConfig; import com.fr.base.env.resource.RemoteEnvConfig; import com.fr.core.env.EnvConfig; -import com.fr.dav.LocalEnv; import com.fr.design.DesignerEnvManager; import com.fr.design.actions.UpdateAction; import com.fr.design.data.DesignTableDataManager; import com.fr.design.data.tabledata.ResponseDataSourceChange; -import com.fr.design.dialog.InformationWarnPane; import com.fr.design.file.HistoryTemplateListPane; import com.fr.design.mainframe.DesignerContext; import com.fr.design.mainframe.JTemplate; @@ -21,20 +18,15 @@ import com.fr.design.menu.MenuDef; import com.fr.design.menu.SeparatorDef; import com.fr.env.RemoteEnv; import com.fr.env.SignIn; -import com.fr.general.ComparatorUtils; -import com.fr.general.FRLogger; import com.fr.general.GeneralContext; import com.fr.general.Inter; import com.fr.stable.EnvChangedListener; -import com.fr.stable.ProductConstants; -import com.fr.stable.StringUtils; -import javax.swing.*; +import javax.swing.JOptionPane; import java.awt.event.ActionEvent; import java.util.HashMap; import java.util.Iterator; import java.util.Map; -import java.util.logging.Level; public class SwitchExistEnv extends MenuDef { @@ -111,14 +103,6 @@ public class SwitchExistEnv extends MenuDef { JOptionPane.showMessageDialog(DesignerContext.getDesignerFrame(), Inter.getLocText(new String[]{"M-SwitchWorkspace", "Failed"})); return; } -// String remoteVersion = selectedEnv.getDesignerVersion(); -// if (StringUtils.isBlank(remoteVersion) || ComparatorUtils.compare(remoteVersion, ProductConstants.DESIGNER_VERSION) < 0) { -// String infor = Inter.getLocText("Server-version-tip"); -// String moreInfo = Inter.getLocText("Server-version-tip-moreInfo"); -// FRLogger.getLogger().log(Level.WARNING, infor); -// new InformationWarnPane(infor, moreInfo, Inter.getLocText("Tooltips")).show(); -// return; -// } SignIn.signIn(selectedEnv); HistoryTemplateListPane.getInstance().getCurrentEditingTemplate().refreshToolArea(); fireDSChanged(); diff --git a/designer-base/src/com/fr/design/mainframe/TemplatePane.java b/designer-base/src/com/fr/design/mainframe/TemplatePane.java index f95e0aee4..8d128ce5e 100644 --- a/designer-base/src/com/fr/design/mainframe/TemplatePane.java +++ b/designer-base/src/com/fr/design/mainframe/TemplatePane.java @@ -1,7 +1,6 @@ package com.fr.design.mainframe; import com.fr.base.BaseUtils; -import com.fr.base.Env; import com.fr.core.env.EnvConfig; import com.fr.dav.LocalEnv; import com.fr.design.DesignModelAdapter; @@ -23,8 +22,19 @@ import com.fr.stable.EnvChangedListener; import com.fr.stable.ProductConstants; import com.fr.stable.StringUtils; -import javax.swing.*; -import java.awt.*; +import javax.swing.BorderFactory; +import javax.swing.Icon; +import javax.swing.JOptionPane; +import javax.swing.JPanel; +import javax.swing.SwingUtilities; +import java.awt.BorderLayout; +import java.awt.Color; +import java.awt.Cursor; +import java.awt.Dimension; +import java.awt.GradientPaint; +import java.awt.Graphics; +import java.awt.Graphics2D; +import java.awt.Point; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseEvent; @@ -98,6 +108,7 @@ public class TemplatePane extends JPanel implements MouseListener { /** * 是否可扩展 + * * @return 同上 */ public boolean IsExpanded() { @@ -121,13 +132,13 @@ public class TemplatePane extends JPanel implements MouseListener { JOptionPane.showMessageDialog(DesignerContext.getDesignerFrame(), Inter.getLocText(new String[]{"M-SwitchWorkspace", "Failed"})); return false; } else { -// String remoteVersion = selectedEnv.getDesignerVersion(); -// if (StringUtils.isBlank(remoteVersion) || ComparatorUtils.compare(remoteVersion, ProductConstants.DESIGNER_VERSION) < 0) { -// String infor = Inter.getLocText("Server-version-tip"); -// String moreInfo = Inter.getLocText("Server-version-tip-moreInfo"); -// new InformationWarnPane(infor, moreInfo, Inter.getLocText("Tooltips")).show(); -// return false; -// } + String remoteVersion = getDesignerVersion(selectedEnv); + if (StringUtils.isBlank(remoteVersion) || ComparatorUtils.compare(remoteVersion, ProductConstants.DESIGNER_VERSION) < 0) { + String infor = Inter.getLocText("Server-version-tip"); + String moreInfo = Inter.getLocText("Server-version-tip-moreInfo"); + new InformationWarnPane(infor, moreInfo, Inter.getLocText("Tooltips")).show(); + return false; + } } } SignIn.signIn(selectedEnv); @@ -148,6 +159,11 @@ public class TemplatePane extends JPanel implements MouseListener { return true; } + private String getDesignerVersion(EnvConfig selectedEnv) { +// return selectedEnv.getDesignerVersion(); + throw new UnsupportedOperationException("unsupport now"); + } + /** * 编辑items */ @@ -162,7 +178,7 @@ public class TemplatePane extends JPanel implements MouseListener { } public void doCancel() { - envListDialog.setVisible(false); + envListDialog.setVisible(false); } }); envListDialog.setVisible(true); @@ -210,6 +226,7 @@ public class TemplatePane extends JPanel implements MouseListener { /** * 鼠标点击 + * * @param e 事件 */ @Override @@ -218,6 +235,7 @@ public class TemplatePane extends JPanel implements MouseListener { /** * 鼠标按下 + * * @param e 事件 */ @Override @@ -232,6 +250,7 @@ public class TemplatePane extends JPanel implements MouseListener { /** * 鼠标放开 + * * @param e 事件 */ @Override @@ -240,6 +259,7 @@ public class TemplatePane extends JPanel implements MouseListener { /** * 鼠标进入 + * * @param e 事件 */ @Override @@ -248,6 +268,7 @@ public class TemplatePane extends JPanel implements MouseListener { /** * 鼠标离开 + * * @param e 事件 */ @Override diff --git a/designer-base/src/com/fr/env/EnvListPane.java b/designer-base/src/com/fr/env/EnvListPane.java index 9e1677ba3..b7f3b29ed 100644 --- a/designer-base/src/com/fr/env/EnvListPane.java +++ b/designer-base/src/com/fr/env/EnvListPane.java @@ -1,10 +1,8 @@ package com.fr.env; -import com.fr.base.Env; import com.fr.base.env.resource.LocalEnvConfig; import com.fr.base.env.resource.RemoteEnvConfig; import com.fr.core.env.EnvConfig; -import com.fr.dav.LocalEnv; import com.fr.design.DesignerEnvManager; import com.fr.design.gui.controlpane.JListControlPane; import com.fr.design.gui.controlpane.NameObjectCreator; diff --git a/designer-base/src/com/fr/start/server/FRTomcat.java b/designer-base/src/com/fr/start/server/FRTomcat.java index b7519b98a..46c529697 100644 --- a/designer-base/src/com/fr/start/server/FRTomcat.java +++ b/designer-base/src/com/fr/start/server/FRTomcat.java @@ -20,9 +20,9 @@ public class FRTomcat extends Tomcat{ public Context addWebapp(String contextPath, String docBase) throws ServletException { - silence(getHost(), contextPath); + silence(host, contextPath); - Context ctx = createContext(getHost(), contextPath); + Context ctx = createContext(host, contextPath); if (ctx instanceof StandardContext) { ((StandardContext)ctx).setDelegate(true); } @@ -37,10 +37,10 @@ public class FRTomcat extends Tomcat{ ctxCfg.setDefaultWebXml(noDefaultWebXmlPath()); - if (getHost() == null) { + if (host == null) { getHost().addChild(ctx); } else { - getHost().addChild(ctx); + host.addChild(ctx); } return ctx; diff --git a/designer-realize/src/com/fr/start/Designer4Debug.java b/designer-realize/src/com/fr/start/Designer4Debug.java index 6448b70bc..0786fee6f 100644 --- a/designer-realize/src/com/fr/start/Designer4Debug.java +++ b/designer-realize/src/com/fr/start/Designer4Debug.java @@ -5,7 +5,7 @@ package com.fr.start; */ public class Designer4Debug { -// public static void main(String... args) { -// org.swingexplorer.Launcher.main(new String[]{"com.fr.start.Designer"}); -// } + public static void main(String... args) { + org.swingexplorer.Launcher.main(new String[]{"com.fr.start.Designer"}); + } }