From fef8c6686c8c18691f3fa3bb3bb6ae8a8f36efed Mon Sep 17 00:00:00 2001 From: neil <459208047@qq.com> Date: Fri, 26 Apr 2019 15:40:38 +0800 Subject: [PATCH] ct --- .../com/fr/design/DesignerEnvManager.java | 53 +- .../design/actions/file/PreferencePane.java | 120 +-- .../ui/dialog/UpdateMainDialog.java | 825 ++++++++++++++++++ .../main/java/com/fr/design/ui/Assistant.java | 1 + .../com/fr/design/ui/EmbProtocolHandler.java | 34 +- .../java/com/fr/design/ui/ModernUIPane.java | 82 +- .../com/fr/design/ui/InitNameSpace.js | 6 +- .../java/com/fr/design/ui/FineUIDemo.java | 6 +- .../com/fr/design/ui/ModernUIPaneTest.java | 9 +- .../test/resources/com/fr/design/ui/demo.html | 6 + .../mainframe/InformationCollector.java | 282 +++++- .../src/main/java/com/fr/start/Designer.java | 61 +- 12 files changed, 1238 insertions(+), 247 deletions(-) create mode 100644 designer-base/src/main/java/com/fr/design/onlineupdate/ui/dialog/UpdateMainDialog.java diff --git a/designer-base/src/main/java/com/fr/design/DesignerEnvManager.java b/designer-base/src/main/java/com/fr/design/DesignerEnvManager.java index bd464d77e0..66a516554f 100644 --- a/designer-base/src/main/java/com/fr/design/DesignerEnvManager.java +++ b/designer-base/src/main/java/com/fr/design/DesignerEnvManager.java @@ -14,8 +14,6 @@ import com.fr.design.env.DesignerWorkspaceType; import com.fr.design.env.LocalDesignerWorkspaceInfo; import com.fr.design.env.RemoteDesignerWorkspaceInfo; import com.fr.design.file.HistoryTemplateListPane; -import com.fr.design.mainframe.vcs.VcsConfigManager; -import com.fr.design.update.push.DesignerPushUpdateConfigManager; import com.fr.design.style.color.ColorSelectConfigManager; import com.fr.design.utils.DesignUtils; import com.fr.file.FILEFactory; @@ -148,9 +146,6 @@ public class DesignerEnvManager implements XMLReadable, XMLWriter { */ private AlphaFineConfigManager alphaFineConfigManager = new AlphaFineConfigManager(); - private DesignerPushUpdateConfigManager designerPushUpdateConfigManager = DesignerPushUpdateConfigManager.getInstance(); - - private VcsConfigManager vcsConfigManager = VcsConfigManager.getInstance(); public static final String CAS_CERTIFICATE_PATH = "certificatePath"; @@ -182,6 +177,8 @@ public class DesignerEnvManager implements XMLReadable, XMLWriter { public static DesignerEnvManager getEnvManager(boolean needCheckEnv) { if (designerEnvManager == null) { designerEnvManager = new DesignerEnvManager(); + //REPORT-15332有一个国际化调用比较早,需要在这边就设置好locale,由于后台GeneralContext默认是China + GeneralContext.setLocale(designerEnvManager.getLanguage()); try { XMLTools.readFileXML(designerEnvManager, designerEnvManager.getDesignerEnvFile()); } catch (Exception e) { @@ -696,14 +693,6 @@ public class DesignerEnvManager implements XMLReadable, XMLWriter { this.joinProductImprove = joinProductImprove; } - public boolean isAutoPushUpdateEnabled() { - return designerPushUpdateConfigManager.isAutoPushUpdateEnabled(); - } - - public void setAutoPushUpdateEnabled(boolean autoPushUpdateEnabled) { - designerPushUpdateConfigManager.setAutoPushUpdateEnabled(autoPushUpdateEnabled); - } - /** * 是否磁盘空间参数 * @@ -1344,7 +1333,6 @@ public class DesignerEnvManager implements XMLReadable, XMLWriter { } } - private void readJettyPort(XMLableReader reader) { String tmpVal; if ((tmpVal = reader.getElementValue()) != null) { @@ -1489,18 +1477,14 @@ public class DesignerEnvManager implements XMLReadable, XMLWriter { readUUID(reader); } else if ("status".equals(name)) { readActiveStatus(reader); - } else if (ComparatorUtils.equals(CAS_PARAS, name)) { + } else if (CAS_PARAS.equals(name)) { readHttpsParas(reader); - } else if (name.equals("AlphaFineConfigManager")) { + } else if ("AlphaFineConfigManager".equals(name)) { readAlphaFineAttr(reader); - } else if (name.equals("RecentColors")) { + } else if ("RecentColors".equals(name)) { readRecentColor(reader); } else if ("OpenDebug".equals(name)) { readOpenDebug(reader); - } else if (name.equals(DesignerPushUpdateConfigManager.XML_TAG)) { - readDesignerPushUpdateAttr(reader); - } else if (name.equals(vcsConfigManager.XML_TAG)) { - readVcsAttr(reader); } else { readLayout(reader, name); } @@ -1683,14 +1667,6 @@ public class DesignerEnvManager implements XMLReadable, XMLWriter { checkRecentOpenedFileNum(); } - private void readDesignerPushUpdateAttr(XMLableReader reader) { - reader.readXMLObject(designerPushUpdateConfigManager); - } - - private void readVcsAttr(XMLableReader reader) { - reader.readXMLObject(vcsConfigManager); - } - /** * Write XML.
* The method will be invoked when save data to XML file.
@@ -1714,8 +1690,6 @@ public class DesignerEnvManager implements XMLReadable, XMLWriter { writeAlphaFineAttr(writer); writeRecentColor(writer); writeOpenDebug(writer); - writeDesignerPushUpdateAttr(writer); - writeVcsAttr(writer); writer.end(); } @@ -1739,6 +1713,7 @@ public class DesignerEnvManager implements XMLReadable, XMLWriter { } } + //写入uuid private void writeUUID(XMLPrintWriter writer) { writer.startTAG("uuid"); @@ -1954,20 +1929,4 @@ public class DesignerEnvManager implements XMLReadable, XMLWriter { .end(); } - private void writeDesignerPushUpdateAttr(XMLPrintWriter writer) { - this.designerPushUpdateConfigManager.writeXML(writer); - } - - private void writeVcsAttr(XMLPrintWriter writer) { - this.vcsConfigManager.writeXML(writer); - } - - - public VcsConfigManager getVcsConfigManager() { - return vcsConfigManager; - } - - public void setVcsConfigManager(VcsConfigManager vcsConfigManager) { - this.vcsConfigManager = vcsConfigManager; - } } diff --git a/designer-base/src/main/java/com/fr/design/actions/file/PreferencePane.java b/designer-base/src/main/java/com/fr/design/actions/file/PreferencePane.java index 9293500812..ae6ba4c250 100644 --- a/designer-base/src/main/java/com/fr/design/actions/file/PreferencePane.java +++ b/designer-base/src/main/java/com/fr/design/actions/file/PreferencePane.java @@ -2,6 +2,7 @@ package com.fr.design.actions.file; import com.fr.base.BaseUtils; import com.fr.config.Configuration; +import com.fr.config.ServerPreferenceConfig; import com.fr.design.DesignerEnvManager; import com.fr.design.RestartHelper; import com.fr.design.dialog.BasicDialog; @@ -23,9 +24,6 @@ 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.mainframe.vcs.VcsConfigManager; -import com.fr.design.mainframe.vcs.common.VcsHelper; -import com.fr.design.update.push.DesignerPushUpdateManager; import com.fr.design.utils.gui.GUICoreUtils; import com.fr.design.widget.FRWidgetFactory; import com.fr.general.ComparatorUtils; @@ -43,8 +41,6 @@ import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.KeyStroke; import javax.swing.SwingUtilities; -import javax.swing.event.ChangeEvent; -import javax.swing.event.ChangeListener; import java.awt.BorderLayout; import java.awt.Component; import java.awt.Dimension; @@ -122,6 +118,7 @@ public class PreferencePane extends BasicPane { private KeyStroke shortCutKeyStore = null; private UIColorButton gridLineColorTBButton; + private UIColorButton paginationLineColorTBButton; private UICheckBox supportCellEditorDefCheckBox; @@ -136,16 +133,8 @@ public class PreferencePane extends BasicPane { private UICheckBox oracleSpace; private UISpinner cachingTemplateSpinner; private UICheckBox openDebugComboBox; - private UICheckBox joinProductImproveCheckBox; - private UICheckBox autoPushUpdateCheckBox; - - private UICheckBox vcsEnableCheckBox; - private UICheckBox saveCommitCheckBox; - private UICheckBox useIntervalCheckBox; - private IntegerEditor saveIntervalEditor; - private UILabel remindVcsLabel; - - + private UICheckBox useOptimizedUPMCheckbox; + private UICheckBox joinProductImprove; public PreferencePane() { this.initComponents(); @@ -163,11 +152,11 @@ public class PreferencePane extends BasicPane { jtabPane.addTab(com.fr.design.i18n.Toolkit.i18nText("Fine-Design_Basic_Advanced"), advancePane); contentPane.add(jtabPane, BorderLayout.NORTH); + createFunctionPane(generalPane); createEditPane(generalPane); createGuiOfGridPane(generalPane); createColorSettingPane(generalPane); - createVcsSettingPane(generalPane); // ConfPane JPanel confLocationPane = FRGUIPaneFactory.createX_AXISBoxInnerContainer_S_Pane(); @@ -190,14 +179,15 @@ public class PreferencePane extends BasicPane { debuggerPane.add(openDebugComboBox, BorderLayout.CENTER); advancePane.add(debuggerPane); - JPanel improvePane = FRGUIPaneFactory.createVerticalTitledBorderPane(com.fr.design.i18n.Toolkit.i18nText("Fine-Design_Basic_Product_Improve")); - joinProductImproveCheckBox = new UICheckBox(com.fr.design.i18n.Toolkit.i18nText("Fine-Design_Basic_Join_Product_Improve")); - improvePane.add(joinProductImproveCheckBox); + JPanel upmSelectorPane = FRGUIPaneFactory.createTitledBorderPane(com.fr.design.i18n.Toolkit.i18nText("Fine-Design_Basic_Update_Plugin_Manager")); + useOptimizedUPMCheckbox = new UICheckBox(com.fr.design.i18n.Toolkit.i18nText("Fine-Design_Basic_Use_New_Update_Plugin_Manager")); + upmSelectorPane.add(useOptimizedUPMCheckbox); + advancePane.add(upmSelectorPane); - if (DesignerPushUpdateManager.getInstance().isAutoPushUpdateSupported()) { - autoPushUpdateCheckBox = new UICheckBox(com.fr.design.i18n.Toolkit.i18nText("Fine-Design_Automatic_Push_Update")); - improvePane.add(autoPushUpdateCheckBox); - } + + JPanel improvePane = FRGUIPaneFactory.createTitledBorderPane(com.fr.design.i18n.Toolkit.i18nText("Fine-Design_Basic_Product_Improve")); + joinProductImprove = new UICheckBox(com.fr.design.i18n.Toolkit.i18nText("Fine-Design_Basic_Join_Product_Improve")); + improvePane.add(joinProductImprove); JPanel spaceUpPane = FRGUIPaneFactory.createBorderLayout_S_Pane(); spaceUpPane.add(oraclePane, BorderLayout.NORTH); @@ -206,45 +196,6 @@ public class PreferencePane extends BasicPane { advancePane.add(spaceUpPane); } - private void createVcsSettingPane(JPanel generalPane) { - JPanel vcsPane = FRGUIPaneFactory.createVerticalTitledBorderPane(Toolkit.i18nText("Fine-Design_Vcs_Title")); - generalPane.add(vcsPane); - remindVcsLabel = new UILabel(Toolkit.i18nText("Fine-Design_Vcs_Remind")); - remindVcsLabel.setVisible(!VcsHelper.needInit()); - vcsEnableCheckBox = new UICheckBox(Toolkit.i18nText("Fine-Design_Vcs_SaveAuto")); - saveCommitCheckBox = new UICheckBox(Toolkit.i18nText("Fine-Design_Vcs_No_Delete")); - saveIntervalEditor = new IntegerEditor(60); - useIntervalCheckBox = new UICheckBox(); - JPanel enableVcsPanel = new JPanel(FRGUIPaneFactory.createLeftZeroLayout()); - enableVcsPanel.add(vcsEnableCheckBox); - enableVcsPanel.add(remindVcsLabel); - JPanel intervalPanel = new JPanel(FRGUIPaneFactory.createLeftZeroLayout()); - UILabel everyLabel = new UILabel(Toolkit.i18nText("Fine-Design_Vcs_Every")); - UILabel delayLabel = new UILabel(Toolkit.i18nText("Fine-Design_Vcs_Delay")); - intervalPanel.add(useIntervalCheckBox); - intervalPanel.add(everyLabel); - intervalPanel.add(saveIntervalEditor); - intervalPanel.add(delayLabel); - vcsEnableCheckBox.addChangeListener(new ChangeListener() { - @Override - public void stateChanged(ChangeEvent e) { - boolean selected = vcsEnableCheckBox.isSelected(); - if (selected) { - saveCommitCheckBox.setEnabled(true); - saveIntervalEditor.setEnabled(true); - useIntervalCheckBox.setEnabled(true); - } else { - saveCommitCheckBox.setEnabled(false); - saveIntervalEditor.setEnabled(false); - useIntervalCheckBox.setEnabled(false); - } - } - }); - vcsPane.add(enableVcsPanel); - vcsPane.add(intervalPanel); - vcsPane.add(saveCommitCheckBox); - } - private void createFunctionPane(JPanel generalPane) { JPanel functionPane = FRGUIPaneFactory.createTitledBorderPane(com.fr.design.i18n.Toolkit.i18nText("Fine-Design_Basic_Preference_Function")); generalPane.add(functionPane); @@ -594,22 +545,6 @@ public class PreferencePane extends BasicPane { defaultStringToFormulaBox.setEnabled(false); defaultStringToFormulaBox.setSelected(false); } - VcsConfigManager vcsConfigManager = designerEnvManager.getVcsConfigManager(); - if (VcsHelper.needInit()) { - vcsEnableCheckBox.setSelected(vcsConfigManager.isVcsEnable()); - } else { - vcsEnableCheckBox.setEnabled(false); - vcsEnableCheckBox.setSelected(false); - } - if (!vcsEnableCheckBox.isSelected()) { - saveCommitCheckBox.setEnabled(false); - saveIntervalEditor.setEnabled(false); - useIntervalCheckBox.setEnabled(false); - } - - saveIntervalEditor.setValue(vcsConfigManager.getSaveInterval()); - saveCommitCheckBox.setSelected(vcsConfigManager.isSaveCommit()); - useIntervalCheckBox.setSelected(vcsConfigManager.isUseInterval()); supportCellEditorDefCheckBox.setSelected(designerEnvManager.isSupportCellEditorDef()); @@ -631,13 +566,11 @@ public class PreferencePane extends BasicPane { openDebugComboBox.setSelected(designerEnvManager.isOpenDebug()); + useOptimizedUPMCheckbox.setSelected(ServerPreferenceConfig.getInstance().isUseOptimizedUPM()); + this.oracleSpace.setSelected(designerEnvManager.isOracleSystemSpace()); this.cachingTemplateSpinner.setValue(designerEnvManager.getCachingTemplateLimit()); - this.joinProductImproveCheckBox.setSelected(designerEnvManager.isJoinProductImprove()); - - if (this.autoPushUpdateCheckBox != null) { - this.autoPushUpdateCheckBox.setSelected(designerEnvManager.isAutoPushUpdateEnabled()); - } + this.joinProductImprove.setSelected(designerEnvManager.isJoinProductImprove()); } private int chooseCase(int sign) { @@ -698,15 +631,7 @@ public class PreferencePane extends BasicPane { designerEnvManager.setOracleSystemSpace(this.oracleSpace.isSelected()); designerEnvManager.setCachingTemplateLimit((int) this.cachingTemplateSpinner.getValue()); - designerEnvManager.setJoinProductImprove(this.joinProductImproveCheckBox.isSelected()); - VcsConfigManager vcsConfigManager = designerEnvManager.getVcsConfigManager(); - vcsConfigManager.setSaveInterval(this.saveIntervalEditor.getValue()); - vcsConfigManager.setVcsEnable(this.vcsEnableCheckBox.isSelected()); - vcsConfigManager.setSaveCommit(this.saveCommitCheckBox.isSelected()); - vcsConfigManager.setUseInterval(this.useIntervalCheckBox.isSelected()); - if (this.autoPushUpdateCheckBox != null) { - designerEnvManager.setAutoPushUpdateEnabled(this.autoPushUpdateCheckBox.isSelected()); - } + designerEnvManager.setJoinProductImprove(this.joinProductImprove.isSelected()); designerEnvManager.setUndoLimit(maxUndoLimit.getSelectedIndex() * SELECTED_INDEX_5); if (maxUndoLimit.getSelectedIndex() == SELECTED_INDEX_5) { @@ -724,6 +649,17 @@ public class PreferencePane extends BasicPane { return new Class[]{Log4jConfig.class}; } }); + Configurations.update(new Worker() { + @Override + public void run() { + ServerPreferenceConfig.getInstance().setUseOptimizedUPM(useOptimizedUPMCheckbox.isSelected()); + } + + @Override + public Class[] targets() { + return new Class[] {ServerPreferenceConfig.class}; + } + }); } diff --git a/designer-base/src/main/java/com/fr/design/onlineupdate/ui/dialog/UpdateMainDialog.java b/designer-base/src/main/java/com/fr/design/onlineupdate/ui/dialog/UpdateMainDialog.java new file mode 100644 index 0000000000..9438df33be --- /dev/null +++ b/designer-base/src/main/java/com/fr/design/onlineupdate/ui/dialog/UpdateMainDialog.java @@ -0,0 +1,825 @@ +package com.fr.design.onlineupdate.ui.dialog; + +import com.fr.design.RestartHelper; +import com.fr.design.constants.LayoutConstants; +import com.fr.design.dialog.UIDialog; +import com.fr.design.gui.ibutton.UIButton; +import com.fr.design.gui.icontainer.UIScrollPane; +import com.fr.design.gui.ilable.UILabel; +import com.fr.design.gui.itextfield.UITextField; +import com.fr.design.layout.TableLayout; +import com.fr.design.layout.TableLayoutHelper; +import com.fr.design.mainframe.DesignerContext; +import com.fr.design.onlineupdate.actions.FileDownloader; +import com.fr.design.onlineupdate.domain.DownloadItem; +import com.fr.design.onlineupdate.domain.UpdateConstants; +import com.fr.design.onlineupdate.domain.UpdateInfoCachePropertyManager; +import com.fr.design.onlineupdate.factory.DirectoryOperationFactory; +import com.fr.design.onlineupdate.ui.widget.LoadingLabel; +import com.fr.design.onlineupdate.ui.widget.UpdateActionLabel; +import com.fr.design.onlineupdate.ui.widget.UpdateInfoTable; +import com.fr.design.onlineupdate.ui.widget.UpdateInfoTableCellRender; +import com.fr.design.onlineupdate.ui.widget.UpdateInfoTableModel; +import com.fr.design.onlineupdate.ui.widget.UpdateInfoTextAreaCellRender; +import com.fr.design.utils.gui.GUICoreUtils; +import com.fr.general.ComparatorUtils; +import com.fr.general.DateUtils; +import com.fr.general.GeneralContext; +import com.fr.general.GeneralUtils; +import com.fr.general.IOUtils; +import com.fr.general.SiteCenter; +import com.fr.general.http.HttpClient; +import com.fr.json.JSONArray; +import com.fr.json.JSONObject; +import com.fr.log.FineLoggerFactory; +import com.fr.stable.ArrayUtils; +import com.fr.stable.ProductConstants; +import com.fr.stable.StableUtils; +import com.fr.stable.StringUtils; +import com.fr.stable.project.ProjectConstants; +import com.fr.workspace.WorkContext; +import com.sun.java.swing.plaf.motif.MotifProgressBarUI; + +import javax.swing.BorderFactory; +import javax.swing.JPanel; +import javax.swing.JProgressBar; +import javax.swing.RowSorter; +import javax.swing.SortOrder; +import javax.swing.SwingConstants; +import javax.swing.SwingWorker; +import javax.swing.event.DocumentEvent; +import javax.swing.event.DocumentListener; +import javax.swing.table.TableRowSorter; +import java.awt.BorderLayout; +import java.awt.Color; +import java.awt.Component; +import java.awt.Dialog; +import java.awt.Dimension; +import java.awt.Frame; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.io.*; +import java.text.ParsePosition; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Date; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.ExecutionException; + +/** + * Created by XINZAI on 2018/8/21. + */ +public class UpdateMainDialog extends UIDialog { + public static final Dimension DEFAULT = new Dimension(660, 620); + + private static final Dimension PROGRESSBAR = new Dimension(120, 15); + private static final Dimension UPDATE_BUTTON = new Dimension(80, 24); + private static final int UPDATE_PANE_ROW_SIZE = 30; + private static final int UPDATE_CONTENT_PANE_ROW_SIZE = 10; + private static final int UPDATE_CONTENT_PANE_COLUMN_SIZE = 10; + private static final int UPDATE_CONTENT_PANE_LABEL_COLUMN_SIZE = 100; + private static final int SEARCH_PANE_ROW_SIZE = 50; + private static final int SEARCH_PANE_TEXT_COLUMN = 130; + private static final int SEARCH_PANE_COLUMN_GAP = 3; + private static final int UPDATE_INFO_TABLE_HEADER_TIME_WIDTH = 120; + private static final int UPDATE_CONTENT_PANE_BORDER_COLOR = 0xCCCCCC; + private static final int RESTORE_LABEL_COLOR = 0x3384F0; + + private static final String UPDATE_CACHE_STATE_FAIL = "fail"; + private static final String UPDATE_CACHE_STATE_SUCCESS = "success"; + + private static final SimpleDateFormat CHANGELOG_FORMAT = new SimpleDateFormat("M/d/y, h:m:s a", Locale.ENGLISH); + private static final SimpleDateFormat UPDATE_INFO_TABLE_FORMAT = new SimpleDateFormat("yyyy.MM.dd"); + + private Set downloadItems = new HashSet(); + private JSONObject downloadFileConfig; + //最新版本标签 + private LoadingLabel loadingLabel; + //更新按钮 + private UIButton updateButton; + //有新版本提示标签 + private UILabel updateLabel; + + //jar包版本信息面板,包括当前版本和最新版本 + private JPanel jarVersionInfoPane; + //jar包更新信息面板,包括每个版本更新的信息 + private JPanel jarUpdateInfoPane; + //jar包更新操作面板,包括更新重启按钮和进度条 + private JPanel updateActionPane; + //进度条 + private JProgressBar progressBar; + //更新版本提示面板 + private JPanel updateVersionReminderPane; + //jar包版本标签 + private UILabel jarCurrentLabel; + //jar包还原标签 + private UILabel jarRestoreLabel; + //更新信息搜索按钮 + private UIButton searchUpdateInfoBtn; + //搜索更新信息关键词文本框 + private UITextField searchUpdateInfoKeyword; + + private boolean updateSuccessful; + + private UpdateInfoTable updateInfoTable; + + private ArrayList updateInfoList; + + private boolean getUpdateInfoSuccess; + + private UpdateInfoCachePropertyManager cacheProperty; + private String lastUpdateCacheTime; + private String lastUpdateCacheState = UPDATE_CACHE_STATE_FAIL; + + public UpdateMainDialog(Dialog parent) { + super(parent); + initComponents(); + } + + public UpdateMainDialog(Frame parent) { + super(parent); + setModal(true); + initComponents(); + } + + private void initUpdateActionPane() { + double[] rowUpdateSubContentPaneSize = {UPDATE_CONTENT_PANE_ROW_SIZE, TableLayout.PREFERRED, UPDATE_CONTENT_PANE_ROW_SIZE}; + double[] rowUpdateContentPaneSize = {TableLayout.PREFERRED}; + double[] columnUpdateSubContentPaneProgressSize = {TableLayout.FILL, TableLayout.PREFERRED}; + double[] columnUpdateSubContentPaneSize = {UPDATE_CONTENT_PANE_COLUMN_SIZE, TableLayout.FILL, TableLayout.PREFERRED}; + JPanel progressBarPane = new JPanel(new BorderLayout()); + + progressBar = new JProgressBar(); + progressBar.setUI(new MotifProgressBarUI()); + progressBar.setForeground(UpdateConstants.BAR_COLOR); + progressBar.setVisible(false); + progressBar.setStringPainted(true); + progressBar.setPreferredSize(PROGRESSBAR); + + updateLabel = new UILabel(com.fr.design.i18n.Toolkit.i18nText("Fine-Design_Updater_New_Version_Available")); + updateLabel.setHorizontalAlignment(SwingConstants.RIGHT); + updateLabel.setVisible(false); + + progressBarPane.add(GUICoreUtils.createBorderLayoutPane( + progressBar, BorderLayout.CENTER, + updateLabel, BorderLayout.EAST + ), BorderLayout.CENTER); + + updateActionPane = TableLayoutHelper.createCommonTableLayoutPane(new Component[][]{ + new Component[]{new UILabel(), new UILabel(), new UILabel()}, + new Component[]{new UILabel(), initPaneContent(getBackground(), rowUpdateContentPaneSize, columnUpdateSubContentPaneProgressSize, progressBarPane, updateButton), new UILabel()}, + new Component[]{new UILabel(), new UILabel(), new UILabel()} + }, rowUpdateSubContentPaneSize, columnUpdateSubContentPaneSize, LayoutConstants.VGAP_LARGE); + } + + private JPanel initPaneContent(Color color, double[] row, double[] column, Component... var) { + JPanel paneContent = TableLayoutHelper.createTableLayoutPane(new Component[][]{var}, row, column); + paneContent.setBackground(color); + return paneContent; + } + + private void initJarVersionInfoPane() { + double[] rowUpdatePaneSize = {UPDATE_PANE_ROW_SIZE, TableLayout.PREFERRED, TableLayout.PREFERRED}; + double[] columnUpdatePaneSize = {TableLayout.PREFERRED, TableLayout.FILL, TableLayout.PREFERRED}; + double[] rowUpdateContentPaneSize = {TableLayout.PREFERRED}; + double[] columnUpdateContentPaneSize = {TableLayout.PREFERRED, TableLayout.FILL, TableLayout.PREFERRED}; + double[] rowUpdateSubContentPaneSize = {UPDATE_CONTENT_PANE_ROW_SIZE, TableLayout.PREFERRED, TableLayout.PREFERRED, TableLayout.PREFERRED, UPDATE_CONTENT_PANE_ROW_SIZE}; + double[] columnUpdateSubContentPaneSize = {UPDATE_CONTENT_PANE_COLUMN_SIZE, TableLayout.FILL, TableLayout.PREFERRED}; + double[] columnUpdateSubContentPaneLabelSize = {UPDATE_CONTENT_PANE_LABEL_COLUMN_SIZE, TableLayout.PREFERRED}; + + JPanel jarUpdateContentPane = new JPanel(); + jarUpdateContentPane.setLayout(new BorderLayout()); + jarUpdateContentPane.setBorder(BorderFactory.createLineBorder(new Color(UPDATE_CONTENT_PANE_BORDER_COLOR))); + + JPanel jarUpdateContentPane2 = TableLayoutHelper.createCommonTableLayoutPane(new Component[][]{ + new Component[]{new UILabel(), new UILabel(), new UILabel()}, + new Component[]{new UILabel(), updateVersionReminderPane, new UILabel()}, + new Component[]{new UILabel(), initPaneContent(Color.WHITE, rowUpdateContentPaneSize, columnUpdateSubContentPaneLabelSize, new UILabel(com.fr.design.i18n.Toolkit.i18nText("Fine-Design_Updater_JAR_Version")), jarCurrentLabel), new UILabel()}, + new Component[]{new UILabel(), initPaneContent(Color.WHITE, rowUpdateContentPaneSize, columnUpdateSubContentPaneLabelSize, new UILabel(com.fr.design.i18n.Toolkit.i18nText("Fine-Design_Updater_Latest_JAR")), loadingLabel), new UILabel()}, + new Component[]{new UILabel(), new UILabel(), new UILabel()} + }, rowUpdateSubContentPaneSize, columnUpdateSubContentPaneSize, LayoutConstants.VGAP_LARGE); + jarUpdateContentPane2.setBackground(Color.WHITE); + jarUpdateContentPane.add(jarUpdateContentPane2); + jarVersionInfoPane = TableLayoutHelper.createCommonTableLayoutPane(new Component[][]{ + new Component[]{new UILabel(), new UILabel(), new UILabel()}, + new Component[]{new UILabel(), initPaneContent(getBackground(), rowUpdateContentPaneSize, columnUpdateContentPaneSize, new UILabel(com.fr.design.i18n.Toolkit.i18nText("Fine-Design_Updater_JarUpdate")), new UILabel(), jarRestoreLabel), new UILabel()}, + new Component[]{new UILabel(), jarUpdateContentPane, new UILabel()} + }, rowUpdatePaneSize, columnUpdatePaneSize, LayoutConstants.VGAP_LARGE); + } + + private void initJarUpdateInfoPane() { + double[] rowUpdatePaneSize = {SEARCH_PANE_ROW_SIZE, TableLayout.FILL}; + double[] columnUpdatePaneSize = {TableLayout.PREFERRED, TableLayout.FILL, TableLayout.PREFERRED}; + + double[] searchRow = {UPDATE_CONTENT_PANE_ROW_SIZE, TableLayout.PREFERRED, SEARCH_PANE_COLUMN_GAP * 2}; + double[] searchColumn = {TableLayout.FILL, SEARCH_PANE_TEXT_COLUMN, TableLayout.PREFERRED}; + initUpdateInfoSearchPane(); + JPanel searchPane = TableLayoutHelper.createCommonTableLayoutPane(new Component[][]{ + new Component[]{new UILabel(), new UILabel(), new UILabel()}, + new Component[]{new UILabel(), searchUpdateInfoKeyword, searchUpdateInfoBtn}, + new Component[]{new UILabel(), new UILabel(), new UILabel()} + }, searchRow, searchColumn, LayoutConstants.VGAP_LARGE); + + String[] columnNames = {com.fr.design.i18n.Toolkit.i18nText("Fine-Design_Updater_Date"), com.fr.design.i18n.Toolkit.i18nText("Fine-Design_Updater_Content"), com.fr.design.i18n.Toolkit.i18nText("Fine-Design_Updater_SignHeader")}; + initUpdateInfoTable(columnNames); + + UIScrollPane uiScrollPane = new UIScrollPane(updateInfoTable); + jarUpdateInfoPane = TableLayoutHelper.createCommonTableLayoutPane(new Component[][]{ + new Component[]{new UILabel(), searchPane, new UILabel()}, + new Component[]{new UILabel(), uiScrollPane, new UILabel()} + }, rowUpdatePaneSize, columnUpdatePaneSize, LayoutConstants.VGAP_LARGE); + } + + private void initUpdateInfoTable(String[] columnNames) { + int updateTimeColIndex = 0; + int updateTitleColIndex = 1; + int updateSignColIndex = 2; + + updateInfoTable = new UpdateInfoTable(columnNames); + + updateInfoTable.setShowGrid(false); + updateInfoTable.setCellSelectionEnabled(false); + TableRowSorter sorter = new TableRowSorter(updateInfoTable.getDataModel()); + sorter.setSortable(updateTimeColIndex, true); + sorter.setSortable(updateTitleColIndex, false); + sorter.setSortable(updateSignColIndex, false); + updateInfoTable.setRowSorter(sorter); + List sortKeys = new ArrayList(); + sortKeys.add(new RowSorter.SortKey(updateTimeColIndex, SortOrder.DESCENDING)); + sorter.setSortKeys(sortKeys); + + updateInfoTable.getTableHeader().setReorderingAllowed(false); + updateInfoTable.getColumnModel().getColumn(updateTimeColIndex).setMaxWidth(UPDATE_INFO_TABLE_HEADER_TIME_WIDTH); + updateInfoTable.getColumnModel().getColumn(updateTimeColIndex).setMinWidth(UPDATE_INFO_TABLE_HEADER_TIME_WIDTH); + updateInfoTable.getColumnModel().getColumn(updateSignColIndex).setMaxWidth(0); + updateInfoTable.getColumnModel().getColumn(updateSignColIndex).setMinWidth(0); + updateInfoTable.getTableHeader().getColumnModel().getColumn(updateSignColIndex).setMaxWidth(0); + updateInfoTable.getTableHeader().getColumnModel().getColumn(updateSignColIndex).setMinWidth(0); + updateInfoTable.getColumn(com.fr.design.i18n.Toolkit.i18nText("Fine-Design_Updater_Date")).setCellRenderer(new UpdateInfoTableCellRender()); + updateInfoTable.getColumn(com.fr.design.i18n.Toolkit.i18nText("Fine-Design_Updater_Content")).setCellRenderer(new UpdateInfoTextAreaCellRender()); + } + + private void initUpdateInfoSearchPane() { + searchUpdateInfoKeyword = new UITextField(); + searchUpdateInfoKeyword.getDocument().addDocumentListener(new DocumentListener() { + @Override + public void insertUpdate(DocumentEvent e) { + } + + @Override + public void removeUpdate(DocumentEvent e) { + String keyword = searchUpdateInfoKeyword.getText(); + if (ComparatorUtils.equals(keyword, StringUtils.EMPTY) && getUpdateInfoSuccess) { + updateInfoList.clear(); + getUpdateInfo(keyword).execute(); + } + } + + @Override + public void changedUpdate(DocumentEvent e) { + } + }); + searchUpdateInfoBtn = new UIButton(com.fr.design.i18n.Toolkit.i18nText("Fine-Design_Updater_Search")); + searchUpdateInfoBtn.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + if (getUpdateInfoSuccess) { + updateInfoList.clear(); + getUpdateInfo(searchUpdateInfoKeyword.getText()).execute(); + } + } + }); + } + + private void initButtonAndLabel() { + loadingLabel = new LoadingLabel(); + loadingLabel.setText(com.fr.design.i18n.Toolkit.i18nText("Fine-Design_Updater_Checking_Jar_Update")); + updateButton = new UIButton(com.fr.design.i18n.Toolkit.i18nText("Fine-Design_Updater_Update")); + updateButton.setPreferredSize(UPDATE_BUTTON); + updateButton.setEnabled(false); + + double[] rowSize = {TableLayout.PREFERRED}; + + double[] colSize = {UPDATE_CONTENT_PANE_LABEL_COLUMN_SIZE, TableLayout.PREFERRED}; + updateVersionReminderPane = initPaneContent( + Color.WHITE, rowSize, colSize, + new UILabel(com.fr.design.i18n.Toolkit.i18nText("Fine-Design_Updater_Designer_Version")), + new UILabel(UpdateConstants.DEFAULT_APP_NAME + StringUtils.BLANK + ProductConstants.VERSION) + ); + + + jarCurrentLabel = new UILabel(StringUtils.isEmpty(GeneralUtils.readBuildNO()) ? com.fr.design.i18n.Toolkit.i18nText("Fine-Design_Updater_Not_Install_Version") : GeneralUtils.readBuildNO(), SwingConstants.CENTER); + UILabel noJarPreviousRevision = new UILabel(com.fr.design.i18n.Toolkit.i18nText("Fine-Design_Updater_No_Previous_Version")); + UpdateActionLabel jarRestorePreviousRevision = new UpdateActionLabel(com.fr.design.i18n.Toolkit.i18nText("Fine-Design_Updater_Restore"), false); + jarRestorePreviousRevision.setForeground(new Color(RESTORE_LABEL_COLOR)); + jarRestorePreviousRevision.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + RestoreDialog dialog = new RestoreDialog(DesignerContext.getDesignerFrame(), true); + dialog.showDialog(); + } + }); + //choose RestoreLabel to show + boolean isNeedRestore = ArrayUtils.isNotEmpty(DirectoryOperationFactory.listFilteredFiles(StableUtils.getInstallHome(), getBackupDirectory())); + jarRestoreLabel = isNeedRestore ? jarRestorePreviousRevision : noJarPreviousRevision; + } + + private void initComponents() { + JPanel contentPane = (JPanel) getContentPane(); + contentPane.setLayout(new BorderLayout()); + + + initButtonAndLabel(); + + initJarVersionInfoPane(); + initJarUpdateInfoPane(); + initUpdateActionPane(); + + add(jarVersionInfoPane, BorderLayout.NORTH); + + //海外版本不显示更新信息 + if (GeneralContext.getLocale().equals(Locale.CHINA) || GeneralContext.getLocale().equals(Locale.TAIWAN)){ + add(jarUpdateInfoPane, BorderLayout.CENTER); + add(updateActionPane, BorderLayout.SOUTH); + }else { + add(updateActionPane, BorderLayout.CENTER); + } + + addActionListenerForUpdateBtn(); + + new SwingWorker() { + @Override + protected JSONObject doInBackground() throws Exception { + HttpClient hc = new HttpClient(SiteCenter.getInstance().acquireUrlByKind("jar10.update")); + hc.setTimeout(UpdateConstants.CONNECTION_TIMEOUT); + return new JSONObject(hc.getResponseText()); + } + + @Override + protected void done() { + try { + downloadFileConfig = get(); + showDownLoadInfo(); + } catch (InterruptedException e) { + stopLoading(); + } catch (ExecutionException e) { + stopLoading(); + } finally { + getUpdateInfo(StringUtils.EMPTY).execute(); + } + } + }.execute(); + } + + private SwingWorker getUpdateInfo(final String keyword) { + updateInfoList = new ArrayList(); + lastUpdateCacheTime = UpdateConstants.CHANGELOG_X_START; + String cacheConfigPath = getUpdateCacheConfig(); + cacheProperty = new UpdateInfoCachePropertyManager(StableUtils.pathJoin(WorkContext.getCurrent().getPath(), "resources", "offlineres", cacheConfigPath)); + String recordUpdateTime = cacheProperty.readProperty("updateTime"); + if (StringUtils.isNotEmpty(recordUpdateTime)) { + lastUpdateCacheTime = recordUpdateTime; + } + String recordUpdateState = cacheProperty.readProperty("updateState"); + if (StringUtils.isNotEmpty(recordUpdateState)) { + lastUpdateCacheState = recordUpdateState; + } + return new SwingWorker() { + @Override + protected JSONArray doInBackground() { + try { + getUpdateInfoSuccess = false; + //step1:read from cache file + getCachedUpdateInfo(keyword); + //step2:read from website,start from cacheRecordTime + if (downloadFileConfig == null) { + throw new Exception("network error."); + } + HttpClient hc = new HttpClient(SiteCenter.getInstance().acquireUrlByKind("changelog10") + "&start=" + lastUpdateCacheTime + "&end=" + getLatestJARTimeStr()); + hc.asGet(); + hc.setTimeout(UpdateConstants.CONNECTION_TIMEOUT * 2); + String responseText = hc.getResponseText(); + JSONArray array = JSONArray.create(); + //假如返回"-1",说明socket出错了 + if (!ComparatorUtils.equals(responseText, "-1")) { + array = new JSONArray(responseText); + } + hc.release(); + return array; + } catch (Exception e) { + FineLoggerFactory.getLogger().error(e.getMessage()); + } + return JSONArray.create(); + } + + @Override + protected void done() { + try { + JSONArray jsonArray = get(); + //step3:generateInfoTableList + updateInfoTable.getDataModel().populateBean(generateUpdateInfoList(jsonArray, keyword)); + + getUpdateInfoSuccess = true; + //step4:update cache file,start from cacheRecordTime,end latest server jartime + updateCachedInfoFile(jsonArray); + } catch (Exception e) { + getUpdateInfoSuccess = true; + FineLoggerFactory.getLogger().error(e.getMessage()); + } + } + }; + } + + //从文件中读取缓存的更新信息 + private void getCachedUpdateInfo(String keyword) throws Exception { + String cacheInfoPath = getUpdateCacheInfo(); + File cacheFile = new File(StableUtils.pathJoin(WorkContext.getCurrent().getPath(), "resources", "offlineres", cacheInfoPath)); + if (!ComparatorUtils.equals(lastUpdateCacheState, "success")) { + cacheFile.delete(); + return; + } + if (cacheFile.exists()) { + InputStreamReader streamReader = new InputStreamReader(new FileInputStream(cacheFile), "UTF-8"); + BufferedReader br = new BufferedReader(streamReader); + String readStr, updateTimeStr; + + while ((readStr = br.readLine()) != null) { + String[] updateInfo = readStr.split("\\t"); + if (updateInfo.length == 2) { + updateTimeStr = updateInfo[0]; + Date updateTime = CHANGELOG_FORMAT.parse(updateTimeStr); + //形如 Build#release-2018.07.31.03.03.52.80 + String currentNO = GeneralUtils.readBuildNO(); + Date curJarDate = UPDATE_INFO_TABLE_FORMAT.parse(currentNO, new ParsePosition(currentNO.indexOf("-") + 1)); + if (!ComparatorUtils.equals(keyword, StringUtils.EMPTY)) { + if (!containsKeyword(UPDATE_INFO_TABLE_FORMAT.format(updateTime), keyword) && !containsKeyword(updateInfo[1], keyword)) { + continue; + } + } + if (isValidLogInfo(updateInfo[1])) { + updateInfoList.add(new Object[]{UPDATE_INFO_TABLE_FORMAT.format(updateTime), updateInfo[1], updateTime.after(curJarDate)}); + } + } + } + br.close(); + streamReader.close(); + } + } + + private void updateCachedInfoFile(JSONArray jsonArray) throws Exception { + String cacheDirPath = StableUtils.pathJoin(WorkContext.getCurrent().getPath(), "resources", "offlineres"); + File cacheFileDir = new File(cacheDirPath); + if (!StableUtils.mkdirs(cacheFileDir)) { + FineLoggerFactory.getLogger().error("make dir error."); + return; + } + final File cacheFile = new File(StableUtils.pathJoin(cacheDirPath, getUpdateCacheInfo())); + if (!cacheFile.exists()) { + cacheFile.createNewFile(); + lastUpdateCacheTime = UpdateConstants.CHANGELOG_X_START; + lastUpdateCacheState = UPDATE_CACHE_STATE_FAIL; + } + if (downloadFileConfig == null) { + return; + } + String endTime = getLatestJARTimeStr(); + if (endTime.equals(lastUpdateCacheTime) || jsonArray.length() == 0 || ComparatorUtils.compare(endTime, lastUpdateCacheTime) <= 0) { + return; + } + OutputStreamWriter writerStream = new OutputStreamWriter(new FileOutputStream(cacheFile), "UTF-8"); + BufferedWriter bufferWriter = new BufferedWriter(writerStream); + for (int i = 0; i < jsonArray.length(); i++) { + JSONObject jo = (JSONObject) jsonArray.get(i); + bufferWriter.write((String) jo.get("update") + '\t' + jo.get("title")); + bufferWriter.newLine(); + bufferWriter.flush(); + } + bufferWriter.close(); + writerStream.close(); + lastUpdateCacheState = UPDATE_CACHE_STATE_SUCCESS; + lastUpdateCacheTime = endTime; + cacheProperty.updateProperty("updateTime", lastUpdateCacheTime); + cacheProperty.updateProperty("updateState", lastUpdateCacheState); + } + + private ArrayList generateUpdateInfoList(JSONArray jsonArray, String keyword) throws Exception { + for (int i = 0; i < jsonArray.length(); i++) { + JSONObject jo = (JSONObject) jsonArray.get(i); + String updateTitle = (String) jo.get("title"); + String updateTimeStr = (String) jo.get("update"); + Date updateTime = CHANGELOG_FORMAT.parse(updateTimeStr); + //形如 Build#release-2018.07.31.03.03.52.80 + String currentNO = GeneralUtils.readBuildNO(); + Date curJarDate = UPDATE_INFO_TABLE_FORMAT.parse(currentNO, new ParsePosition(currentNO.indexOf("-") + 1)); + if (!ComparatorUtils.equals(keyword, StringUtils.EMPTY)) { + if (!containsKeyword(UPDATE_INFO_TABLE_FORMAT.format(updateTime), keyword) && !containsKeyword(updateTitle, keyword)) { + continue; + } + } + if (isValidLogInfo(updateTitle)) { + updateInfoList.add(new Object[]{UPDATE_INFO_TABLE_FORMAT.format(updateTime), updateTitle, updateTime.after(curJarDate)}); + } + } + return new ArrayList(updateInfoList); + } + + private boolean containsKeyword(String str, String keyword) { + return str.toUpperCase().contains(keyword.toUpperCase()); + } + + private void stopLoading() { + loadingLabel.stopLoading(com.fr.design.i18n.Toolkit.i18nText("Fine-Design_Updater_Connect_VersionUpdateServer_Failed")); + } + + + private void showDownLoadInfo() { + //形如 Build#release-2018.07.31.03.03.52.80 + String buildNO = downloadFileConfig.optString("buildNO"); + Date jarDate = (new SimpleDateFormat("yyyy.MM.dd")).parse(buildNO, new ParsePosition(buildNO.indexOf("-") + 1)); + String serverVersionNO = downloadFileConfig.optString("versionNO"); + String currentVersionNO = ProductConstants.RELEASE_VERSION; + String[] serverVersionSplitStr = serverVersionNO.split("\\."); + String[] currentVersionSplitStr = currentVersionNO.split("\\."); + int index = 0; + int compareResult; + int versionLength = Math.min(serverVersionSplitStr.length, currentVersionSplitStr.length); + + //形如 Build#release-2018.07.31.03.03.52.80 + String currentNO = GeneralUtils.readBuildNO(); + if (!".".equals(StableUtils.getInstallHome())) { + Date currentDate = (new SimpleDateFormat("yyyy.MM.dd")).parse(currentNO, new ParsePosition(currentNO.indexOf("-") + 1)); + if (DateUtils.subtractDate(jarDate, currentDate, DateUtils.DAY) > 0) { + updateButton.setEnabled(true); + updateLabel.setVisible(true); + loadingLabel.stopLoading(buildNO.contains("-") ? buildNO.substring(buildNO.lastIndexOf("-") + 1) : buildNO); + } else { + loadingLabel.stopLoading(com.fr.design.i18n.Toolkit.i18nText("Fine-Design_Updater_Already_Latest_Version")); + } + } else { + updateButton.setEnabled(true); + updateLabel.setVisible(true); + loadingLabel.stopLoading(buildNO.contains("-") ? buildNO.substring(buildNO.lastIndexOf("-") + 1) : buildNO); + } + + while (index < versionLength) { + compareResult = serverVersionSplitStr[index].length() - currentVersionSplitStr[index].length(); + if (0 == compareResult) { + compareResult = serverVersionSplitStr[index].compareTo(currentVersionSplitStr[index]); + if (0 == compareResult) { + ++index; + continue; + } + break; + } + break; + } + + initMapWithInfo(downloadFileConfig); + } + + public void initMapWithInfo(JSONObject result) { + addJarNameToMap(result, "designer"); + addJarNameToMap(result, "server"); + } + + private void addJarNameToMap(JSONObject result, String category) { + JSONArray jsonArray = result.optJSONArray(category); + if (jsonArray != null) { + for (int i = 0, len = jsonArray.length(); i < len; i++) { + JSONObject jo = jsonArray.optJSONObject(i); + String downloadName = jo.optString("name"); + String downloadUrl = jo.optString("url"); + long downloadSize = jo.optLong("size"); + if (ComparatorUtils.equals(category, "server")) { + File currentJAR = new File(StableUtils.pathJoin(WorkContext.getCurrent().getPath(), ProjectConstants.LIB_NAME, downloadName)); + if (currentJAR.exists() && ComparatorUtils.equals(currentJAR.length(), downloadSize)) { + //假如大小一样的jar包就不要下载了 + continue; + } + } + downloadItems.add(new DownloadItem(downloadName, downloadUrl, downloadSize)); + } + } + } + + /** + * jar包更新按钮监听器 + */ + private void addActionListenerForUpdateBtn() { + updateButton.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + if (updateSuccessful) { + RestartHelper.restart(); + } else { + deletePreviousPropertyFile(); + updateButton.setEnabled(false); + progressBar.setVisible(true); + updateLabel.setVisible(false); + + new FileDownloader( + downloadItems.toArray(new DownloadItem[downloadItems.size()]), + StableUtils.pathJoin(StableUtils.getInstallHome(), UpdateConstants.DOWNLOAD_DIR)) { + @Override + protected void process(java.util.List chunks) { + DownloadItem fileInfo = chunks.get(chunks.size() - 1); + progressBar.setString(fileInfo.getName() + " " + fileInfo.getProgressString()); + progressBar.setValue(fileInfo.getProgressValue()); + } + + @Override + public void onDownloadSuccess() { + updateButton.setEnabled(true); + progressBar.setVisible(false); + backup(); + putNewFiles(); + updateSuccessful = true; + updateButton.setText(com.fr.design.i18n.Toolkit.i18nText("Fine-Design_Updater_Restart_Designer")); + } + + @Override + public void onDownloadFailed() { + progressBar.setVisible(false); + } + }.execute(); + } + } + }); + } + + /** + * 确保升级更新之前删除以前的配置文件 + */ + public static void deletePreviousPropertyFile() { + //在进行更新升级之前确保move和delete.properties删除 + File moveFile = new File(RestartHelper.MOVE_FILE); + File delFile = new File(RestartHelper.RECORD_FILE); + if ((moveFile.exists()) && (!moveFile.delete())) { + FineLoggerFactory.getLogger().error(RestartHelper.MOVE_FILE + "delete failed!"); + } + if ((delFile.exists()) && (!delFile.delete())) { + FineLoggerFactory.getLogger().error(RestartHelper.RECORD_FILE + "delete failed!"); + } + } + + /** + * JAR包更新的时候备份老的jar包,包括设计器相关的和服务器相关的几个 + */ + private void backup() { + String installHome = StableUtils.getInstallHome(); + //jar包备份文件的目录为"backup/"+jar包当前版本号 + String todayBackupDir = StableUtils.pathJoin(installHome, getBackupDirectory(), (GeneralUtils.readBuildNO())); + backupFilesFromInstallEnv(installHome, todayBackupDir, getJARList4Server()); + backupFilesFromInstallLib(installHome, todayBackupDir, getJARList4Designer()); + jarCurrentLabel.setText(downloadFileConfig.optString("buildNO")); + } + + private void backupFilesFromInstallEnv(String installHome, String todayBackupDir, List files) { + for (String file : files) { + try { + IOUtils.copy( + new File(StableUtils.pathJoin(installHome, UpdateConstants.APPS_FOLDER_NAME, ProductConstants.getAppFolderName(), ProjectConstants.WEBINF_NAME, ProjectConstants.LIB_NAME, file)), + new File(StableUtils.pathJoin(todayBackupDir))); + } catch (IOException e) { + FineLoggerFactory.getLogger().error(e.getMessage()); + } + } + } + + private void backupFilesFromInstallLib(String installHome, String todayBackupDir, List files) { + for (String file : files) { + try { + IOUtils.copy( + new File(StableUtils.pathJoin(installHome, ProjectConstants.LIB_NAME, file)), + new File(StableUtils.pathJoin(todayBackupDir))); + } catch (IOException e) { + FineLoggerFactory.getLogger().error(e.getMessage()); + } + } + } + + private void putNewFiles() { + Map map = new HashMap(); + java.util.List list = new ArrayList(); + String installHome = StableUtils.getInstallHome(); + putNewFilesToInstallLib(installHome, getDownLoadJAR4Designer(), map, list); + putNewFilesToInstallEnv(installHome, getDownLoadJAR4Server(), map, list); + RestartHelper.saveFilesWhichToMove(map); + RestartHelper.saveFilesWhichToDelete(list.toArray(new String[list.size()])); + } + + private void putNewFilesToInstallLib(String installHome, String[] files, Map map, java.util.List list) { + for (String file : files) { + map.put(StableUtils.pathJoin(installHome, UpdateConstants.DOWNLOAD_DIR, file), + StableUtils.pathJoin(installHome, ProjectConstants.LIB_NAME, file)); + list.add(StableUtils.pathJoin(installHome, ProjectConstants.LIB_NAME, file)); + } + } + + private void putNewFilesToInstallEnv(String installHome, String[] files, Map map, java.util.List list) { + for (String file : files) { + map.put(StableUtils.pathJoin(installHome, UpdateConstants.DOWNLOAD_DIR, file), + StableUtils.pathJoin(installHome, UpdateConstants.APPS_FOLDER_NAME, ProductConstants.getAppFolderName(), ProjectConstants.WEBINF_NAME, ProjectConstants.LIB_NAME, file)); + list.add(StableUtils.pathJoin(installHome, UpdateConstants.APPS_FOLDER_NAME, ProductConstants.getAppFolderName(), ProjectConstants.WEBINF_NAME, ProjectConstants.LIB_NAME, file)); + } + } + + //获取备份目录 + private String getBackupDirectory() { + return UpdateConstants.DESIGNER_BACKUP_DIR; + } + + //获取服务器jar包列表 + private List getJARList4Server() { + return UpdateConstants.JARS_FOR_SERVER_X; + } + + //获取设计器jar包列表 + private List getJARList4Designer() { + return UpdateConstants.JARS_FOR_DESIGNER_X; + } + + //获取服务器jar包下载列表 + private String[] getDownLoadJAR4Server() { + ArrayList jarList = new ArrayList(); + List serverItems = getJARList4Server(); + for (DownloadItem downloadItem : downloadItems) { + String downloadItemName = downloadItem.getName(); + if (serverItems.contains(downloadItemName)) { + jarList.add(downloadItemName); + } + } + return jarList.toArray(new String[jarList.size()]); + } + + //获取设计器jar包下载列表 + private String[] getDownLoadJAR4Designer() { + ArrayList jarList = new ArrayList(); + List designerJarItems = getJARList4Designer(); + for (DownloadItem downloadItem : downloadItems) { + String downloadItemName = downloadItem.getName(); + if (designerJarItems.contains(downloadItemName)) { + jarList.add(downloadItemName); + } + } + return jarList.toArray(new String[jarList.size()]); + } + + //获取更新日志缓存配置文件名 + private String getUpdateCacheConfig() { + return UpdateConstants.UPDATE_CACHE_CONFIG_X; + } + + //获取更新日志缓存内容文件名 + private String getUpdateCacheInfo() { + return UpdateConstants.UPDATE_CACHE_INFO_X; + } + + //获取最新的jar包时间字符串 + private String getLatestJARTimeStr() { + if (downloadFileConfig == null) { + return StringUtils.EMPTY; + } + String buildNO = downloadFileConfig.optString("buildNO"); + Date jarDate = (new SimpleDateFormat("yyyy.MM.dd")).parse(buildNO, new ParsePosition(buildNO.indexOf("-") + 1)); + SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd"); + return df.format(jarDate); + } + + //判断是否是有效的日志内容 + private boolean isValidLogInfo(String logContent) { + String log = logContent.toUpperCase(); + List logType = UpdateConstants.LOG_TYPE; + for (String s : logType) { + if (log.startsWith(s)) { + return true; + } + } + return false; + } + + /** + * 显示窗口 + */ + public void showDialog() { + setSize(DEFAULT); + setTitle(com.fr.design.i18n.Toolkit.i18nText("Fine-Design_Updater_UpdateAndUpgrade")); + GUICoreUtils.centerWindow(this); + setVisible(true); + } + + /** + * 检查有效性 + * + * @throws Exception + */ + @Override + public void checkValid() throws Exception { + + } +} \ No newline at end of file diff --git a/designer-base/src/main/java/com/fr/design/ui/Assistant.java b/designer-base/src/main/java/com/fr/design/ui/Assistant.java index 601f0ac36f..7a51c188c4 100644 --- a/designer-base/src/main/java/com/fr/design/ui/Assistant.java +++ b/designer-base/src/main/java/com/fr/design/ui/Assistant.java @@ -49,5 +49,6 @@ public class Assistant { ProtocolService protocolService = browserContext.getProtocolService(); // 支持读取jar包中文件的自定义协议————emb:/com/fr/design/images/bbs.png protocolService.setProtocolHandler("emb", handler); + //protocolService.setProtocolHandler("file", handler); } } diff --git a/designer-base/src/main/java/com/fr/design/ui/EmbProtocolHandler.java b/designer-base/src/main/java/com/fr/design/ui/EmbProtocolHandler.java index 6636e28744..94456df97f 100644 --- a/designer-base/src/main/java/com/fr/design/ui/EmbProtocolHandler.java +++ b/designer-base/src/main/java/com/fr/design/ui/EmbProtocolHandler.java @@ -1,7 +1,11 @@ package com.fr.design.ui; +import com.fr.base.TemplateUtils; import com.fr.general.IOUtils; import com.fr.stable.StringUtils; +import com.fr.third.org.apache.commons.codec.net.URLCodec; +import com.fr.third.org.apache.commons.io.FileUtils; +import com.fr.third.org.apache.commons.io.FilenameUtils; import com.fr.web.struct.AssembleComponent; import com.fr.web.struct.AtomBuilder; import com.fr.web.struct.PathGroup; @@ -11,7 +15,12 @@ import com.teamdev.jxbrowser.chromium.ProtocolHandler; import com.teamdev.jxbrowser.chromium.URLRequest; import com.teamdev.jxbrowser.chromium.URLResponse; +import java.io.File; +import java.io.FileInputStream; import java.io.InputStream; +import java.io.StringReader; +import java.net.URI; +import java.util.Map; /** * @author richie @@ -21,6 +30,7 @@ import java.io.InputStream; public class EmbProtocolHandler implements ProtocolHandler { private AssembleComponent component; + private Map map; public EmbProtocolHandler() { @@ -30,17 +40,35 @@ public class EmbProtocolHandler implements ProtocolHandler { this.component = component; } + public EmbProtocolHandler(AssembleComponent component, Map map) { + this.component = component; + this.map = map; + } + + public EmbProtocolHandler(Map map) { + this.map = map; + } @Override public URLResponse onRequest(URLRequest req) { try { String path = req.getURL(); - if (path.startsWith("emb:dynamic")) { + if (path.startsWith("file:")) { + String url = new URLCodec().decode(path); + String filePath = TemplateUtils.renderParameter4Tpl(url, map); + File file = new File(URI.create(filePath).getPath()); + InputStream inputStream = new FileInputStream(file); + if (path.endsWith(".svg")) { + System.out.println(path); + } + return Assistant.inputStream2Response(inputStream, "file:///" + file.getAbsolutePath()); + } + else if (path.startsWith("emb:dynamic")) { URLResponse response = new URLResponse(); response.setData(htmlText().getBytes()); response.getHeaders().setHeader("Content-Type", "text/html"); return response; - } else { + } else { int index = path.indexOf("="); if (index > 0) { path = path.substring(index + 1); @@ -51,7 +79,7 @@ public class EmbProtocolHandler implements ProtocolHandler { return Assistant.inputStream2Response(inputStream, path); } } catch (Exception ignore) { - + ignore.printStackTrace(); } return null; } diff --git a/designer-base/src/main/java/com/fr/design/ui/ModernUIPane.java b/designer-base/src/main/java/com/fr/design/ui/ModernUIPane.java index 81f9e051b5..99a4fe97cf 100644 --- a/designer-base/src/main/java/com/fr/design/ui/ModernUIPane.java +++ b/designer-base/src/main/java/com/fr/design/ui/ModernUIPane.java @@ -2,6 +2,10 @@ package com.fr.design.ui; import com.fr.design.DesignerEnvManager; import com.fr.design.dialog.BasicPane; +import com.fr.design.gui.ibutton.UIButton; +import com.fr.design.gui.itoolbar.UIToolbar; +import com.fr.design.i18n.Toolkit; +import com.fr.design.utils.gui.GUICoreUtils; import com.fr.web.struct.AssembleComponent; import com.teamdev.jxbrowser.chromium.Browser; import com.teamdev.jxbrowser.chromium.BrowserPreferences; @@ -14,8 +18,11 @@ import com.teamdev.jxbrowser.chromium.events.ScriptContextEvent; import com.teamdev.jxbrowser.chromium.events.ScriptContextListener; import com.teamdev.jxbrowser.chromium.swing.BrowserView; -import javax.swing.JSplitPane; -import java.awt.BorderLayout; +import javax.swing.*; +import java.awt.*; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.util.Map; /** * @author richie @@ -39,17 +46,29 @@ public class ModernUIPane extends BasicPane { setLayout(new BorderLayout()); BrowserPreferences.setChromiumSwitches("--disable-google-traffic"); if (DesignerEnvManager.getEnvManager().isOpenDebug()) { - JSplitPane splitPane = new JSplitPane(); - add(splitPane, BorderLayout.CENTER); - splitPane.setOrientation(JSplitPane.VERTICAL_SPLIT); - splitPane.setDividerLocation(500); + UIToolbar toolbar = new UIToolbar(); + add(toolbar, BorderLayout.NORTH); + UIButton openDebugButton = new UIButton(Toolkit.i18nText("Fine-Design_Basic_Open_Debug_Window")); + toolbar.add(openDebugButton); + UIButton reloadButton = new UIButton(Toolkit.i18nText("Fine-Design_Basic_Reload")); + toolbar.add(reloadButton); + + openDebugButton.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + showDebuggerDialog(); + } + }); + + reloadButton.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + browser.reloadIgnoringCache(); + } + }); BrowserPreferences.setChromiumSwitches("--remote-debugging-port=9222"); initializeBrowser(); - splitPane.setLeftComponent(new BrowserView(browser)); - Browser debugger = new Browser(); - debugger.loadURL(browser.getRemoteDebuggingURL()); - BrowserView debuggerView = new BrowserView(debugger); - splitPane.setRightComponent(debuggerView); + add(new BrowserView(browser), BorderLayout.CENTER); } else { initializeBrowser(); add(new BrowserView(browser), BorderLayout.CENTER); @@ -57,6 +76,18 @@ public class ModernUIPane extends BasicPane { } } + private void showDebuggerDialog() { + JDialog dialog = new JDialog(SwingUtilities.getWindowAncestor(this)); + Browser debugger = new Browser(); + BrowserView debuggerView = new BrowserView(debugger); + dialog.add(debuggerView, BorderLayout.CENTER); + dialog.setSize(new Dimension(800, 400)); + GUICoreUtils.centerWindow(dialog); + dialog.setVisible(true); + dialog.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); + debugger.loadURL(browser.getRemoteDebuggingURL()); + } + private void initializeBrowser() { browser = new Browser(); // 初始化的时候,就把命名空间对象初始化好,确保window.a.b.c("a.b.c"为命名空间)对象都是初始化过的 @@ -68,6 +99,14 @@ public class ModernUIPane extends BasicPane { }); } + /** + * 转向一个新的地址,相当于重新加载 + * @param url 新的地址 + */ + public void redirect(String url) { + browser.loadURL(url); + } + @Override protected String title4PopupWindow() { return "Modern"; @@ -126,6 +165,16 @@ public class ModernUIPane extends BasicPane { return this; } + /** + * 加载url指向的资源 + * @param url 文件的地址 + */ + public Builder withURL(final String url, Map map) { + Assistant.setEmbProtocolHandler(pane.browser, new EmbProtocolHandler(map)); + pane.browser.loadURL(url); + return this; + } + /** * 加载Atom组件 * @param component Atom组件 @@ -136,6 +185,17 @@ public class ModernUIPane extends BasicPane { return this; } + /** + * 加载Atom组件 + * @param component Atom组件 + */ + public Builder withComponent(AssembleComponent component, Map map) { + Assistant.setEmbProtocolHandler(pane.browser, new EmbProtocolHandler(component, map)); + pane.browser.loadURL("emb:dynamic"); + return this; + } + + /** * 加载html文本内容 * @param html 要加载html文本内容 diff --git a/designer-base/src/main/resources/com/fr/design/ui/InitNameSpace.js b/designer-base/src/main/resources/com/fr/design/ui/InitNameSpace.js index 0274d5fa50..03b2bb32ae 100644 --- a/designer-base/src/main/resources/com/fr/design/ui/InitNameSpace.js +++ b/designer-base/src/main/resources/com/fr/design/ui/InitNameSpace.js @@ -1,6 +1,6 @@ -var arr ="%s".split(".").reverse(); -var create = function (obj, names) { - var name = names.pop(); +let arr ="%s".split(".").reverse(); +let create = function (obj, names) { + let name = names.pop(); if (!name) { return; } diff --git a/designer-base/src/test/java/com/fr/design/ui/FineUIDemo.java b/designer-base/src/test/java/com/fr/design/ui/FineUIDemo.java index c875716a5b..c7dd4b6821 100644 --- a/designer-base/src/test/java/com/fr/design/ui/FineUIDemo.java +++ b/designer-base/src/test/java/com/fr/design/ui/FineUIDemo.java @@ -2,10 +2,8 @@ package com.fr.design.ui; import com.fr.design.DesignerEnvManager; -import javax.swing.JFrame; -import javax.swing.JPanel; -import javax.swing.WindowConstants; -import java.awt.BorderLayout; +import javax.swing.*; +import java.awt.*; /** * @author richie diff --git a/designer-base/src/test/java/com/fr/design/ui/ModernUIPaneTest.java b/designer-base/src/test/java/com/fr/design/ui/ModernUIPaneTest.java index f5c8aaaa92..9676ee998a 100644 --- a/designer-base/src/test/java/com/fr/design/ui/ModernUIPaneTest.java +++ b/designer-base/src/test/java/com/fr/design/ui/ModernUIPaneTest.java @@ -2,13 +2,8 @@ package com.fr.design.ui; import com.fr.design.DesignerEnvManager; -import javax.swing.JButton; -import javax.swing.JFrame; -import javax.swing.JOptionPane; -import javax.swing.JPanel; -import javax.swing.WindowConstants; -import java.awt.BorderLayout; -import java.awt.FlowLayout; +import javax.swing.*; +import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; diff --git a/designer-base/src/test/resources/com/fr/design/ui/demo.html b/designer-base/src/test/resources/com/fr/design/ui/demo.html index 2beae25a78..9e5211c89e 100644 --- a/designer-base/src/test/resources/com/fr/design/ui/demo.html +++ b/designer-base/src/test/resources/com/fr/design/ui/demo.html @@ -10,6 +10,12 @@ return Pool.data; }; +
测试页面,请点击最下面的按钮
diff --git a/designer-realize/src/main/java/com/fr/design/mainframe/InformationCollector.java b/designer-realize/src/main/java/com/fr/design/mainframe/InformationCollector.java index 61f39b81db..8a3f4bb25d 100644 --- a/designer-realize/src/main/java/com/fr/design/mainframe/InformationCollector.java +++ b/designer-realize/src/main/java/com/fr/design/mainframe/InformationCollector.java @@ -7,8 +7,7 @@ import com.fr.base.FRContext; import com.fr.config.MarketConfig; import com.fr.design.DesignerEnvManager; import com.fr.design.mainframe.errorinfo.ErrorInfoUploader; -import com.fr.design.mainframe.messagecollect.impl.FocusPointMessageUploader; -import com.fr.design.mainframe.template.info.TemplateInfoCollector; +import com.fr.design.mainframe.templateinfo.TemplateInfoCollector; import com.fr.general.CloudCenter; import com.fr.general.ComparatorUtils; import com.fr.general.DateUtils; @@ -16,13 +15,20 @@ import com.fr.general.DesUtils; import com.fr.general.GeneralUtils; import com.fr.general.IOUtils; import com.fr.general.http.HttpToolbox; +import com.fr.intelli.record.FocusPoint; +import com.fr.intelli.record.MetricRegistry; import com.fr.json.JSONArray; +import com.fr.json.JSONException; import com.fr.json.JSONObject; import com.fr.log.FineLoggerFactory; import com.fr.stable.EncodeConstants; import com.fr.stable.ProductConstants; import com.fr.stable.StableUtils; import com.fr.stable.StringUtils; +import com.fr.stable.query.QueryFactory; +import com.fr.stable.query.condition.QueryCondition; +import com.fr.stable.query.data.DataList; +import com.fr.stable.query.restriction.RestrictionFactory; import com.fr.stable.xml.XMLPrintWriter; import com.fr.stable.xml.XMLReadable; import com.fr.stable.xml.XMLTools; @@ -47,6 +53,11 @@ import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; +import java.util.Map; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; + /** * @author neil * @@ -70,6 +81,24 @@ public class InformationCollector implements XMLReadable, XMLWriter { private static final String XML_KEY = "ActiveKey"; private static final String XML_OS = "OS"; + public static final String TABLE_NAME = "fr_functionrecord"; + public static final String FUNC_COLUMNNAME = "func"; + public static final String COLUMN_TIME = "time"; + public static final String TABLE_FUNCTION_RECORD = "function.record"; + private static final String ATTR_ID = "id"; + private static final String ATTR_TEXT = "text"; + private static final String ATTR_SOURCE = "source"; + private static final String ATTR_TIME = "time"; + private static final String ATTR_TIMES = "times"; + private static final String ATTR_TITLE = "title"; + private static final String ATTR_USER_NAME = "username"; + private static final String ATTR_UUID = "uuid"; + private static final String ATTR_ITEMS = "items"; + private static final String ATTR_FUNCTION_ARRAY = "functionArray"; + private static final int MAX_EACH_REQUEST_RECORD_COUNT = 200; + private static final int PAGE_SIZE = 200; + private long totalCount = -1; + private static InformationCollector collector; //启动时间与关闭时间列表 @@ -155,12 +184,6 @@ public class InformationCollector implements XMLReadable, XMLWriter { } private void sendUserInfo(){ - long currentTime = new Date().getTime(); - long lastTime = getLastTimeMillis(); - - if (currentTime - lastTime <= DELTA) { - return; - } JSONObject content = getJSONContentAsByte(); String url = CloudCenter.getInstance().acquireUrlByKind("user.info.v10"); boolean success = false; @@ -178,9 +201,135 @@ public class InformationCollector implements XMLReadable, XMLWriter { } } - /** - * 收集开始使用时间,发送信息 - */ + private void sendFunctionsInfo(long currentTime, long lastTime){ + FineLoggerFactory.getLogger().info("Start sent function records to the cloud center..."); + queryAndSendOnePageFunctionContent(currentTime, lastTime, 0); + long page = (totalCount/PAGE_SIZE) + 1; + for(int i=1; i focusPoints = MetricRegistry.getMetric().find(FocusPoint.class,condition); + //第一次查询获取总记录数 + if(page == 0){ + totalCount = focusPoints.getTotalCount(); + } + sendThisPageFunctionContent(focusPoints); + } catch (Exception e) { + FineLoggerFactory.getLogger().error(e.getMessage(), e); + } + } + + private void sendThisPageFunctionContent(DataList focusPoints) { + String url = CloudCenter.getInstance().acquireUrlByKind(TABLE_FUNCTION_RECORD); + try { + JSONObject jsonObject = dealWithSendFunctionContent(focusPoints); + sendFunctionRecord(url, jsonObject); + } catch (JSONException e) { + FineLoggerFactory.getLogger().error(e.getMessage(), e); + } + } + + private JSONObject dealWithSendFunctionContent(DataList focusPoints) throws JSONException { + JSONObject jsonObject = new JSONObject(); + Map map = new HashMap<>(); + if(!focusPoints.isEmpty()){ + DesignerEnvManager envManager = DesignerEnvManager.getEnvManager(); + String bbsUserName = MarketConfig.getInstance().getBbsUsername(); + String uuid = envManager.getUUID(); + jsonObject.put(ATTR_UUID, uuid); + jsonObject.put(ATTR_USER_NAME, bbsUserName); + for(FocusPoint focusPoint : focusPoints.getList()) { + FunctionRecord functionRecord = getOneRecord(focusPoint); + if (map.containsKey(focusPoint.getId())) { + int times = ((FunctionRecord)map.get(focusPoint.getId())).getTimes() + 1; + functionRecord.setTimes(times); + map.put(focusPoint.getId(), functionRecord); + } else { + map.put(focusPoint.getId(), functionRecord); + } + } + jsonObject.put(ATTR_ITEMS, mapToJSONArray(map)); + } + return jsonObject; + } + + private JSONArray mapToJSONArray(Map map) throws JSONException { + JSONArray jsonArray = new JSONArray(); + for(String keys : map.keySet()){ + FunctionRecord functionRecord = (FunctionRecord)map.get(keys); + JSONObject jo = new JSONObject(); + jo.put(ATTR_ID, functionRecord.getId()); + jo.put(ATTR_TEXT, functionRecord.getText()); + jo.put(ATTR_SOURCE, functionRecord.getSource()); + jo.put(ATTR_TIME, functionRecord.getTime()); + jo.put(ATTR_TITLE, functionRecord.getTitle()); + jo.put(ATTR_TIMES, functionRecord.getTimes()); + jsonArray.put(jo); + } + return jsonArray; + } + + private void sendFunctionRecord(String url, JSONObject record) { + boolean success = false; + try { + HashMap para = new HashMap<>(); + para.put("token", SiteCenterToken.generateToken()); + para.put("content", record); + String res = HttpToolbox.post(url, para); + success = ComparatorUtils.equals(new JSONObject(res).get("status"), "success"); + if (success) { + this.lastTime = dateToString(); + } else { + FineLoggerFactory.getLogger().error("Error occured when sent function records to the cloud center."); + } + } catch (Exception e) { + FineLoggerFactory.getLogger().error(e.getMessage(), e); + } + } + + private FunctionRecord getOneRecord(FocusPoint focusPoint) { + FunctionRecord functionRecord = new FunctionRecord(); + functionRecord.setId(focusPoint.getId() == null?StringUtils.EMPTY : focusPoint.getId()); + functionRecord.setText(focusPoint.getText() == null?StringUtils.EMPTY : focusPoint.getText()); + functionRecord.setSource(focusPoint.getSource()); + functionRecord.setTime(focusPoint.getTime().getTime()); + functionRecord.setTitle(focusPoint.getTitle() == null?StringUtils.EMPTY : focusPoint.getTitle()); + functionRecord.setUsername(MarketConfig.getInstance().getBbsUsername() == null?StringUtils.EMPTY : MarketConfig.getInstance().getBbsUsername()); + functionRecord.setUuid(DesignerEnvManager.getEnvManager().getUUID() == null?StringUtils.EMPTY : DesignerEnvManager.getEnvManager().getUUID()); + return functionRecord; + } + + /** + * 收集开始使用时间,发送信息 + */ public void collectStartTime(){ this.current.setStartDate(dateToString()); @@ -192,23 +341,22 @@ public class InformationCollector implements XMLReadable, XMLWriter { return; } - Thread sendThread = new Thread(new Runnable() { - + ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor(); + service.schedule(new Runnable() { @Override public void run() { - try { - //读取XML的5分钟后开始发请求连接服务器. - Thread.sleep(SEND_DELAY); - } catch (InterruptedException e) { - FineLoggerFactory.getLogger().error(e.getMessage(), e); + long currentTime = new Date().getTime(); + long lastTime = getLastTimeMillis(); + if (currentTime - lastTime > DELTA) { + sendUserInfo(); + sendFunctionsInfo(currentTime, lastTime); } - sendUserInfo(); - FocusPointMessageUploader.getInstance().sendToCloudCenter(); + TemplateInfoCollector.getInstance().sendTemplateInfo(); ErrorInfoUploader.getInstance().sendErrorInfo(); } - }); - sendThread.start(); + }, SEND_DELAY, TimeUnit.SECONDS); + } /** @@ -376,4 +524,94 @@ public class InformationCollector implements XMLReadable, XMLWriter { } } + + private class FunctionRecord implements Comparable{ + private String id; + private String text; + private int source; + private long time; + private int times = 1; + private String title; + private String username; + private String uuid; + + public FunctionRecord(){ + + } + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public int getTimes() { + return times; + } + + public void setTimes(int times) { + this.times = times; + } + + public String getText() { + return text; + } + + public void setText(String text) { + this.text = text; + } + + public int getSource() { + return source; + } + + public void setSource(int source) { + this.source = source; + } + + public long getTime() { + return time; + } + + public void setTime(long time) { + this.time = time; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public String getUuid() { + return uuid; + } + + public void setUuid(String uuid) { + this.uuid = uuid; + } + + @Override + public int compareTo(Object o) { + FunctionRecord functionRecord = (FunctionRecord) o; + if(this.getId().equals((functionRecord.getId())) && this.getText().equals(functionRecord.getText()) + && this.getSource() == functionRecord.getSource() && this.getTime() == functionRecord.getTime() + && this.getTitle().equals(functionRecord.getTitle()) && this.getUsername().equals(functionRecord.getUsername()) + && this.getUuid().equals(functionRecord.getUuid())){ + return 0; + } + return 1; + } + } } \ No newline at end of file diff --git a/designer-realize/src/main/java/com/fr/start/Designer.java b/designer-realize/src/main/java/com/fr/start/Designer.java index daf0046d7f..bd872e41ac 100644 --- a/designer-realize/src/main/java/com/fr/start/Designer.java +++ b/designer-realize/src/main/java/com/fr/start/Designer.java @@ -3,7 +3,6 @@ package com.fr.start; import com.fr.base.BaseUtils; import com.fr.base.vcs.DesignerMode; import com.fr.design.DesignerEnvManager; -import com.fr.design.RestartHelper; import com.fr.design.actions.core.ActionFactory; import com.fr.design.actions.file.WebPreviewUtils; import com.fr.design.actions.file.newReport.NewPolyReportAction; @@ -12,7 +11,6 @@ import com.fr.design.actions.server.ServerConfigManagerAction; import com.fr.design.actions.server.StyleListAction; import com.fr.design.actions.server.WidgetManagerAction; import com.fr.design.constants.UIConstants; -import com.fr.design.file.HistoryTemplateListCache; import com.fr.design.file.HistoryTemplateListPane; import com.fr.design.file.MutilTempalteTabPane; import com.fr.design.fun.MenuHandler; @@ -29,14 +27,12 @@ import com.fr.design.mainframe.JWorkBook; import com.fr.design.mainframe.alphafine.component.AlphaFinePane; import com.fr.design.mainframe.bbs.UserInfoLabel; import com.fr.design.mainframe.bbs.UserInfoPane; -import com.fr.design.mainframe.template.info.TemplateInfoCollector; import com.fr.design.mainframe.toolbar.ToolBarMenuDockPlus; import com.fr.design.menu.KeySetUtils; import com.fr.design.menu.MenuDef; import com.fr.design.menu.SeparatorDef; import com.fr.design.menu.ShortCut; import com.fr.design.module.DesignModuleFactory; -import com.fr.design.utils.DesignUtils; import com.fr.design.utils.concurrent.ThreadFactoryBuilder; import com.fr.design.utils.gui.GUICoreUtils; import com.fr.general.ComparatorUtils; @@ -44,17 +40,12 @@ import com.fr.log.FineLoggerFactory; import com.fr.module.Module; import com.fr.module.ModuleContext; import com.fr.runtime.FineRuntime; -import com.fr.stable.BuildContext; -import com.fr.stable.OperatingSystem; import com.fr.stable.ProductConstants; import com.fr.stable.StableUtils; import com.fr.stable.StringUtils; import com.fr.stable.lifecycle.LifecycleFatalError; import com.fr.stable.xml.XMLTools; -import com.fr.start.fx.SplashFx; -import com.fr.start.jni.SplashMac; import com.fr.start.module.StartupArgs; -import com.fr.start.preload.ImagePreLoader; import com.fr.start.server.ServerTray; import com.fr.workspace.WorkContext; @@ -70,8 +61,6 @@ import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import java.util.ArrayList; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadFactory; import java.util.concurrent.ThreadPoolExecutor; @@ -91,10 +80,6 @@ public class Designer extends BaseDesigner { private UIButton redo; private UIPreviewButton run; - public Designer(String[] args) { - super(args); - } - /** * 设计器启动的Main方法 * @@ -104,21 +89,6 @@ public class Designer extends BaseDesigner { //启动运行时 FineRuntime.start(); - BuildContext.setBuildFilePath("/com/fr/stable/build.properties"); - // 如果端口被占用了 说明程序已经运行了一次,也就是说,已经建立一个监听服务器,现在只要给服务器发送命令就好了 - if (DesignUtils.isStarted()) { - DesignUtils.clientSend(args); - FineLoggerFactory.getLogger().error("Designer port not available."); - System.exit(0); - return; - } - RestartHelper.deleteRecordFilesWhenStart(); - - preloadResource(); - - SplashContext.getInstance().registerSplash(createSplash()); - - SplashContext.getInstance().show(); Module designerRoot = ModuleContext.parseRoot("designer-startup.xml"); //传递启动参数 designerRoot.setSingleton(StartupArgs.class, new StartupArgs(args)); @@ -138,34 +108,10 @@ public class Designer extends BaseDesigner { } - private static void preloadResource() { - ExecutorService service = Executors.newCachedThreadPool(); - - service.submit(new Runnable() { - @Override - public void run() { - new ImagePreLoader(); - } - }); - - service.submit(new Runnable() { - @Override - public void run() { - TemplateInfoCollector.getInstance(); - } - }); - service.shutdown(); + public Designer(String[] args) { + super(args); } - private static SplashStrategy createSplash() { - // 这里可以开接口加载自定义启动画面 - if (OperatingSystem.isWindows()) { - return new SplashFx(); - } else if (OperatingSystem.isMacOS()) { - return new SplashMac(); - } - return new SplashFx(); - } /** * 创建新建文件的快捷方式数组。 @@ -269,7 +215,7 @@ public class Designer extends BaseDesigner { saveButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { - JTemplate jt = HistoryTemplateListCache.getInstance().getCurrentEditingTemplate(); + JTemplate jt = HistoryTemplateListPane.getInstance().getCurrentEditingTemplate(); jt.stopEditing(); jt.saveTemplate(); jt.requestFocus(); @@ -278,7 +224,6 @@ public class Designer extends BaseDesigner { return saveButton; } - private UIButton createUndoButton() { undo = new UIButton(BaseUtils.readIcon("/com/fr/design/images/buttonicon/undo.png")); undo.setToolTipText(KeySetUtils.UNDO.getMenuKeySetName());