List of usage examples for javax.swing SwingWorker SwingWorker
public SwingWorker()
From source file:org.ut.biolab.medsavant.client.region.RegionWizard.java
private AbstractWizardPage getGenesPage() { return new DefaultWizardPage(PAGENAME_GENES) { private static final int GENE_SELECTION_PANE_WIDTH = 350; private JPanel leftSide; private GeneSelectionPanel geneManiaResultsPanel; private Set<String> geneManiaGeneNames = null; {// w w w . j av a 2 s .c o m selectedGenesPanel = new GeneSelectionPanel(true, true); sourceGenesPanel = new GeneSelectionPanel(true, true); geneManiaResultsPanel = new GeneSelectionPanel(true, true) { @Override protected void dragAndDropAddGenes(Set<Gene> geneSet) { Set<Object> genesToMoveToGeneManiaPanel = new HashSet<Object>(geneManiaGeneNames); genesToMoveToGeneManiaPanel.retainAll(selectedGenesPanel.getSelectedKeys()); selectedGenesPanel.copyItems(geneManiaResultsPanel, genesToMoveToGeneManiaPanel); selectedGenesPanel.moveSelectedItems(sourceGenesPanel); } @Override protected void dragAndDropRemoveKeys(Set<Object> keySet) { Set<Object> keys = geneManiaResultsPanel.getSelectedKeys(); geneManiaResultsPanel.removeRows(keys); sourceGenesPanel.removeRows(keys); } }; geneManiaResultsPanel.setOddRowColor(new Color(242, 249, 245)); runGeneManiaButton = new JButton("Run GeneMANIA"); runGeneManiaButton.setEnabled(!DirectorySettings.isGeneManiaInstalled()); ListSelectionListener selectionListener = new ListSelectionListener() { @Override public void valueChanged(ListSelectionEvent lse) { int numSel = sourceGenesPanel.getNumSelected() + selectedGenesPanel.getNumSelected(); if (geneManiaGeneNames != null) { numSel += geneManiaResultsPanel.getNumSelected(); } if (GenemaniaInfoRetriever.isGeneManiaDownloading()) { runGeneManiaButton.setEnabled(false); } else { runGeneManiaButton.setEnabled(numSel > 0 || !DirectorySettings.isGeneManiaInstalled()); } } }; sourceGenesPanel.getTable().getSelectionModel().addListSelectionListener(selectionListener); selectedGenesPanel.getTable().getSelectionModel().addListSelectionListener(selectionListener); selectedGenesPanel.getTable().getModel().addTableModelListener(new TableModelListener() { @Override public void tableChanged(TableModelEvent tme) { if (selectedGenesPanel.getData().length > 0) { fireButtonEvent(ButtonEvent.ENABLE_BUTTON, ButtonNames.NEXT); } else { fireButtonEvent(ButtonEvent.DISABLE_BUTTON, ButtonNames.NEXT); } } }); selectedGenesPanel.setPreferredSize( new Dimension(GENE_SELECTION_PANE_WIDTH, selectedGenesPanel.getPreferredSize().height)); final JPanel outerLeftSide = new JPanel(); outerLeftSide.setLayout(new BoxLayout(outerLeftSide, BoxLayout.X_AXIS)); leftSide = new JPanel(); leftSide.setLayout(new BoxLayout(leftSide, BoxLayout.Y_AXIS)); leftSide.add(sourceGenesPanel); outerLeftSide.add(leftSide); final JPanel bg = new JPanel(); bg.setLayout(new BoxLayout(bg, BoxLayout.Y_AXIS)); JButton addButton = new JButton("Add "); JButton removeButton = new JButton("? Remove"); sourceGenesPanel.getTable().addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent me) { if (me.getClickCount() == 2) { sourceGenesPanel.moveSelectedItems(selectedGenesPanel); } } }); selectedGenesPanel.getTable().addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent me) { if (me.getClickCount() == 2) { if (geneManiaGeneNames != null) { Set<Object> genesToMoveToGeneManiaPanel = new HashSet<Object>(geneManiaGeneNames); genesToMoveToGeneManiaPanel.retainAll(selectedGenesPanel.getSelectedKeys()); selectedGenesPanel.copyItems(geneManiaResultsPanel, genesToMoveToGeneManiaPanel); } selectedGenesPanel.moveSelectedItems(sourceGenesPanel); } } }); geneManiaResultsPanel.getTable().addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent me) { if (me.getClickCount() == 2) { Set<Object> keys = geneManiaResultsPanel.getSelectedKeys(); geneManiaResultsPanel.moveSelectedItems(selectedGenesPanel); sourceGenesPanel.moveItems(selectedGenesPanel, keys); } } }); addButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent ae) { if (geneManiaGeneNames != null) { Set<Object> keys = geneManiaResultsPanel.getSelectedKeys(); geneManiaResultsPanel.moveSelectedItems(selectedGenesPanel); sourceGenesPanel.moveItems(selectedGenesPanel, keys); } else { sourceGenesPanel.moveSelectedItems(selectedGenesPanel); } } }); removeButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent ae) { if (geneManiaGeneNames != null) { Set<Object> genesToMoveToGeneManiaPanel = new HashSet<Object>(geneManiaGeneNames); genesToMoveToGeneManiaPanel.retainAll(selectedGenesPanel.getSelectedKeys()); selectedGenesPanel.copyItems(geneManiaResultsPanel, genesToMoveToGeneManiaPanel); } selectedGenesPanel.moveSelectedItems(sourceGenesPanel); } }); bg.add(Box.createVerticalGlue()); bg.add(addButton); bg.add(removeButton); bg.add(Box.createVerticalGlue()); outerLeftSide.add(bg); JPanel rightSide = new JPanel(); rightSide.setLayout(new BoxLayout(rightSide, BoxLayout.Y_AXIS)); rightSide.add(selectedGenesPanel); rightSide.add(runGeneManiaButton); final JSplitPane hsplitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, outerLeftSide, rightSide); hsplitPane.setResizeWeight(1); addComponent(hsplitPane, true); if (!DirectorySettings.isGeneManiaInstalled()) { runGeneManiaButton.setText("Download GeneMANIA"); if (GenemaniaInfoRetriever.isGeneManiaDownloading()) { runGeneManiaButton.setEnabled(false); registerDownloadListener(); } } runGeneManiaButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent ae) { if (!DirectorySettings.isGeneManiaInstalled()) { int response = DialogUtils.askYesNo("Download GeneMANIA?", "GeneMANIA is not yet installed. Do you want to download and install it now?"); try { if (response == DialogUtils.OK) { runGeneManiaButton.setText("Run GeneMANIA"); runGeneManiaButton.setEnabled(false); registerDownloadListener(); /* DownloadTask dt = GenemaniaInfoRetriever.getGeneManiaDownloadTask(); dt.addPropertyChangeListener(new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent evt) { if (evt.getPropertyName().equals("downloadState")) { DownloadTask.DownloadState ds = (DownloadTask.DownloadState) evt.getNewValue(); if (ds == DownloadTask.DownloadState.CANCELLED || ds == DownloadTask.DownloadState.FINISHED) { runGeneManiaButton.setEnabled( (selectedGenesPanel.getNumSelected() + sourceGenesPanel.getNumSelected()) > 0); } } } }); */ GenemaniaInfoRetriever.getGeneManiaDownloadTask().execute(); } } catch (IOException e) { DialogUtils.displayMessage("Error downloading GeneMANIA files"); LOG.error(e); } } else { final List<String> selectedGenes = new LinkedList<String>(); for (Gene g : selectedGenesPanel.getSelectedGenes()) { selectedGenes.add(g.getName()); } for (Gene g : sourceGenesPanel.getSelectedGenes()) { selectedGenes.add(g.getName()); } if (geneManiaGeneNames != null) { for (Gene g : geneManiaResultsPanel.getSelectedGenes()) { selectedGenes.add(g.getName()); } } final JButton closeGeneManiaButton = new JButton("? Close GeneMANIA results"); closeGeneManiaButton.setEnabled(false); final JPanel geneManiaContainingPanel = new JPanel(); geneManiaContainingPanel .setLayout(new BoxLayout(geneManiaContainingPanel, BoxLayout.Y_AXIS)); final SwingWorker geneManiaWorker = new SwingWorker() { private List<Object[]> results; @Override public void done() { Object[][] newdata = new Object[results.size()][4]; results.toArray(newdata); geneManiaResultsPanel.updateData(newdata); geneManiaResultsPanel.updateView(); geneManiaContainingPanel.removeAll(); geneManiaContainingPanel.add(geneManiaResultsPanel); geneManiaContainingPanel.revalidate(); geneManiaContainingPanel.repaint(); closeGeneManiaButton.setEnabled(true); } @Override public Object doInBackground() { try { GenemaniaInfoRetriever genemania = new GenemaniaInfoRetriever(); genemania.setGenes(selectedGenes); List<String> geneNameList = genemania.getRelatedGeneNamesByScore(); geneManiaGeneNames = new HashSet<String>(); geneManiaGeneNames.addAll(geneNameList); LOG.debug("Found " + geneNameList.size() + " related genes"); results = new ArrayList<Object[]>(geneNameList.size()); int i = 0; for (String gene : geneNameList) { if (isCancelled()) { return null; } Gene g = GeneSetFetcher.getInstance().getGeneDictionary().get(gene); if (g == null) { LOG.warn("No gene found for " + gene); } else if (!selectedGenesPanel.hasKey(g.getName())) { results.add(new Object[] { g.getName(), g.getChrom(), g.getStart(), g.getEnd() }); } } } catch (IOException e) { LOG.error(e); } catch (ApplicationException e) { LOG.error(e); } catch (DataStoreException e) { LOG.error(e); } catch (NoRelatedGenesInfoException e) { LOG.error(e); } return null; } }; leftSide.removeAll(); closeGeneManiaButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent ae) { try { geneManiaWorker.cancel(true); } catch (Exception e) { //genemania throws exceptions when cancelled } leftSide.removeAll(); leftSide.add(sourceGenesPanel); leftSide.validate(); leftSide.repaint(); geneManiaGeneNames = null; } }); JPanel closeButtonPanel = new JPanel(); closeButtonPanel.setLayout(new BoxLayout(closeButtonPanel, BoxLayout.X_AXIS)); closeButtonPanel.add(closeGeneManiaButton); closeButtonPanel.add(Box.createHorizontalGlue()); leftSide.add(closeButtonPanel); geneManiaContainingPanel.add(new WaitPanel("Querying GeneMANIA for related genes")); leftSide.add(geneManiaContainingPanel); leftSide.validate(); leftSide.repaint(); geneManiaWorker.execute(); } //end else }//end actionPerformed });//end ActionListener } @Override public void setupWizardButtons() { fireButtonEvent(ButtonEvent.HIDE_BUTTON, ButtonNames.FINISH); fireButtonEvent(ButtonEvent.SHOW_BUTTON, ButtonNames.BACK); if (selectedGenesPanel.getNumSelected() > 0) { fireButtonEvent(ButtonEvent.ENABLE_BUTTON, ButtonNames.NEXT); } else { fireButtonEvent(ButtonEvent.DISABLE_BUTTON, ButtonNames.NEXT); } } }; }
From source file:org.ut.biolab.medsavant.client.util.MedSavantWorker.java
/** * @param pageName which view created this worker *///from w ww . j a v a2 s . c o m public MedSavantWorker(String pageName) { this.pageName = pageName; ThreadController.getInstance().addWorker(pageName, this); final MedSavantWorker instance = this; swingWorker = new SwingWorker<T, Object>() { @Override public void done() { instance.done(); } @Override protected T doInBackground() throws Exception { return (T) instance.doInBackground(); } }; }
From source file:org.yccheok.jstock.gui.analysis.WizardDownloadIndicatorJPanel.java
private SwingWorker<Void, Status> getDownloadIndicatorTask() { SwingWorker<Void, Status> worker = new SwingWorker<Void, Status>() { @Override// www .j a v a 2 s . c o m protected void done() { // Inform wizard. WizardDownloadIndicatorJPanel.this.observable.setChanged(); WizardDownloadIndicatorJPanel.this.observable.notifyObservers(); } @Override protected void process(java.util.List<Status> statuses) { for (Status status : statuses) { writeToMemoryLog(status.message); jLabel1.setText(status.message); jLabel2.setIcon(status.icon); if (status.icon == Icons.ERROR || status.icon == Icons.WARNING) { jLabel1.setForeground(Color.RED); jLabel3.setVisible(true); } else { jLabel1.setForeground(Color.BLUE); jLabel3.setVisible(false); } } } @Override protected Void doInBackground() { if (isCancelled()) { return null; } memoryLog.clear(); final int expected = indicatorDownloadInfos.size(); int actual = 0; for (IndicatorDownloadManager.Info info : indicatorDownloadInfos) { final String message0 = MessageFormat.format( GUIBundle.getString("WizardDownloadlIndicatorJPanel_DownloadingIndicator_template..."), info.projectName); publish(Status.newInstance(message0, Icons.BUSY)); final File temp = Utils.downloadAsTempFile(info.fileURL.toString()); if (temp == null) { final String fail_message0 = MessageFormat.format( GUIBundle .getString("WizardDownloadlIndicatorJPanel_DownloadIndicatorFail_template"), info.projectName); publish(Status.newInstance(fail_message0, Icons.BUSY)); continue; } // Check for zipfile check sum. final String message1 = MessageFormat.format( GUIBundle.getString("WizardDownloadlIndicatorJPanel_CheckingCheckSum_template..."), info.projectName); publish(Status.newInstance(message1, Icons.BUSY)); final long checksum = org.yccheok.jstock.analysis.Utils.getChecksum(temp); if (checksum != info.checksum) { final String fail_message1 = MessageFormat.format( GUIBundle.getString("WizardDownloadlIndicatorJPanel_CheckCheckSumFail_template"), info.projectName); publish(Status.newInstance(fail_message1, Icons.BUSY)); continue; } if (isCancelled()) { // Early return. return null; } // Install. final String message2 = MessageFormat.format( GUIBundle.getString("WizardDownloadlIndicatorJPanel_InstallingIndicator_template..."), info.projectName); publish(Status.newInstance(message2, Icons.BUSY)); if (indicatorProjectManager.install(temp)) { actual++; } else { final String fail_message2 = MessageFormat.format( GUIBundle.getString("WizardDownloadlIndicatorJPanel_InstallIndicatorFail_template"), info.projectName); publish(Status.newInstance(fail_message2, Icons.BUSY)); } } final String message = MessageFormat.format( GUIBundle.getString( "WizardDownloadlIndicatorJPanel_NOutOfMIndicatorsInstalledSuccessfully_template"), actual, expected); if (actual == expected) { publish(Status.newInstance(message, Icons.OK)); } else { if (actual > 0) { publish(Status.newInstance(message, Icons.WARNING)); } else { publish(Status.newInstance(message, Icons.ERROR)); } } return null; } }; return worker; }
From source file:org.yccheok.jstock.gui.analysis.WizardSelectIndicatorJPanel.java
private SwingWorker<IndicatorDownloadManager, Void> getIndicatorDownloadManagerTask() { SwingWorker<IndicatorDownloadManager, Void> worker = new SwingWorker<IndicatorDownloadManager, Void>() { @Override//from w w w . ja v a2 s .c om protected void done() { // The done Method: When you are informed that the SwingWorker // is done via a property change or via the SwingWorker object's // done method, you need to be aware that the get methods can // throw a CancellationException. A CancellationException is a // RuntimeException, which means you do not need to declare it // thrown and you do not need to catch it. Instead, you should // test the SwingWorker using the isCancelled method before you // use the get method. if (this.isCancelled()) { // Cancelled by user explicitly. Do not perform any GUI update. // No pop-up message. WizardSelectIndicatorJPanel.this.indicatorDownloadManager = null; return; } try { WizardSelectIndicatorJPanel.this.indicatorDownloadManager = get(); } catch (InterruptedException ex) { log.error(null, ex); } catch (ExecutionException ex) { log.error(null, ex); } catch (CancellationException ex) { // Some developers suggest to catch this exception, instead of // checking on isCancelled. As I am not confident by merely // isCancelled check can prevent CancellationException (What // if cancellation is happen just after isCancelled check?), // I will apply both techniques. log.error(null, ex); } updateGUIState(); } @Override protected IndicatorDownloadManager doInBackground() { if (isCancelled()) { return null; } final String location = IndicatorDownloadManager.getIndicatorDownloadManagerDescriptionFileLocation( indicatorProjectManager.getPreferredOperatorIndicatorType()); final Utils.InputStreamAndMethod inputStreamAndMethod = Utils .getResponseBodyAsStreamBasedOnProxyAuthOption(location); if (inputStreamAndMethod.inputStream == null) { inputStreamAndMethod.method.releaseConnection(); return null; } // Why we design method parameter to accept Reader instead of // InputStream? // This is because if we construct Reader within fromXML, we will // have to close the Reader within fromXML. This will close the // InputStream implicitly as well. This is not what we want. We // want the caller to close InputStream explicitly. final Reader reader = new InputStreamReader(inputStreamAndMethod.inputStream, Charset.forName("UTF-8")); final IndicatorDownloadManager _indicatorDownloadManager = Utils .fromXML(IndicatorDownloadManager.class, reader); org.yccheok.jstock.file.Utils.close(reader); org.yccheok.jstock.file.Utils.close(inputStreamAndMethod.inputStream); inputStreamAndMethod.method.releaseConnection(); if (_indicatorDownloadManager == null) { return null; } // Perform simple validation. for (int i = 0; i < _indicatorDownloadManager.size(); i++) { if (_indicatorDownloadManager.get(i).type != indicatorProjectManager .getPreferredOperatorIndicatorType()) { return null; } } for (int i = 0; i < _indicatorDownloadManager.size(); i++) { final IndicatorDownloadManager.Info info = _indicatorDownloadManager.get(i); final URL descriptionURL = info.descriptionURL; final String respond = Utils .getResponseBodyAsStringBasedOnProxyAuthOption(descriptionURL.toString()); if (respond != null) { if (respond.contains(Utils.getJStockUUID())) { htmlDescriptionMap.put(info.projectName, respond); } } } return _indicatorDownloadManager; } }; return worker; }
From source file:org.yccheok.jstock.gui.JStock.java
public void saveToCloud() { jMenu3.setEnabled(false);/* w w w. j av a 2 s . c o m*/ SwingWorker swingWorker = new SwingWorker<Pair<Pair<Credential, String>, Boolean>, Void>() { @Override protected Pair<Pair<Credential, String>, Boolean> doInBackground() throws Exception { final Pair<Pair<Credential, String>, Boolean> pair = org.yccheok.jstock.google.Utils .authorizeDrive(); return pair; } @Override public void done() { jMenu3.setEnabled(true); Pair<Pair<Credential, String>, Boolean> pair = null; try { pair = this.get(); } catch (InterruptedException ex) { JOptionPane.showMessageDialog(JStock.this, ex.getMessage(), GUIBundle.getString("SaveToCloudJDialog_Title"), JOptionPane.ERROR_MESSAGE); log.error(null, ex); } catch (ExecutionException ex) { org.yccheok.jstock.google.Utils.logoutDrive(); JOptionPane.showMessageDialog(JStock.this, ex.getMessage(), GUIBundle.getString("SaveToCloudJDialog_Title"), JOptionPane.ERROR_MESSAGE); log.error(null, ex); } if (pair == null) { return; } SaveToCloudJDialog saveToCloudJDialog = new SaveToCloudJDialog(JStock.this, true, pair.first, pair.second); saveToCloudJDialog.setVisible(true); } }; swingWorker.execute(); }
From source file:org.yccheok.jstock.gui.JStock.java
public void loadFromCloud() { jMenu3.setEnabled(false);/*from ww w . j av a2s . c om*/ SwingWorker swingWorker = new SwingWorker<Pair<Pair<Credential, String>, Boolean>, Void>() { @Override protected Pair<Pair<Credential, String>, Boolean> doInBackground() throws Exception { final Pair<Pair<Credential, String>, Boolean> pair = org.yccheok.jstock.google.Utils .authorizeDrive(); if (pair == null) { return null; } return pair; } @Override public void done() { jMenu3.setEnabled(true); Pair<Pair<Credential, String>, Boolean> pair = null; try { pair = this.get(); } catch (InterruptedException ex) { JOptionPane.showMessageDialog(JStock.this, ex.getMessage(), GUIBundle.getString("LoadFromCloudJDialog_Title"), JOptionPane.ERROR_MESSAGE); log.error(null, ex); } catch (ExecutionException ex) { org.yccheok.jstock.google.Utils.logoutDrive(); JOptionPane.showMessageDialog(JStock.this, ex.getMessage(), GUIBundle.getString("LoadFromCloudJDialog_Title"), JOptionPane.ERROR_MESSAGE); log.error(null, ex); } if (pair == null) { return; } LoadFromCloudJDialog loadFromCloudJDialog = new LoadFromCloudJDialog(JStock.this, true, pair.first, pair.second); loadFromCloudJDialog.setVisible(true); } }; swingWorker.execute(); }
From source file:org.yccheok.jstock.gui.LoadFromCloudJDialog.java
private SwingWorker<JStockOptions, Status> getLoadFromCloudTask() { SwingWorker<JStockOptions, Status> worker = new SwingWorker<JStockOptions, Status>() { @Override/*from ww w. j a v a 2 s. com*/ protected void done() { JStockOptions result = null; // Some developers suggest to catch this exception, instead of // checking on isCancelled. As I am not confident by merely // isCancelled check can prevent CancellationException (What // if cancellation is happen just after isCancelled check?), // I will apply both techniques. if (this.isCancelled() == false) { try { result = this.get(); } catch (InterruptedException ex) { log.error(null, ex); } catch (ExecutionException ex) { log.error(null, ex); } catch (CancellationException ex) { log.error(null, ex); } } jButton1.setEnabled(true); jButton3.setEnabled(true); if (result != null) { JStock.instance().reloadAfterDownloadFromCloud(result); JOptionPane.showMessageDialog(LoadFromCloudJDialog.this, GUIBundle.getString("LoadFromCloudJDialog_Success")); setVisible(false); dispose(); } } @Override protected void process(java.util.List<Status> statuses) { for (Status status : statuses) { writeToMemoryLog(status.message); jLabel3.setText(status.message); jLabel4.setIcon(status.icon); jLabel3.setVisible(true); jLabel4.setVisible(true); if (status.icon == Icons.ERROR || status.icon == Icons.WARNING) { jLabel3.setForeground(Color.RED); jLabel5.setVisible(true); } else { jLabel3.setForeground(Color.BLUE); jLabel5.setVisible(false); } } } // Unlike Android, we don't mutate old JStockOptions first. Instead, // we return JStockOptions to UI thread. This allow JStock.java make // look n feel decision, based on old JStockOptions. @Override protected JStockOptions doInBackground() { if (isCancelled()) { return null; } memoryLog.clear(); publish(Status.newInstance(GUIBundle.getString("LoadFromCloudJDialog_LoadingFromCloud..."), Icons.BUSY)); Utils.CloudFile cloudFile = Utils.loadFromGoogleDrive(credentialEx.first); if (cloudFile == null) { // Perhaps we should load from legacy cloud server, and help // user to perform migration to Google Doc server. cloudFile = Utils.loadFromLegacyGoogleDrive(credentialEx.first); if (cloudFile == null) { publish(Status.newInstance(GUIBundle.getString("LoadFromCloudJDialog_LoadingFromCloudFail"), Icons.ERROR)); return null; } else { Utils.saveToGoogleDrive(credentialEx.first, cloudFile.file); } } /* Check for checksum. */ if (cloudFile.checksum != org.yccheok.jstock.analysis.Utils.getChecksum(cloudFile.file)) { publish(Status.newInstance(GUIBundle.getString("LoadFromCloudJDialog_CheckingCheckSumFail"), Icons.ERROR)); return null; } /* Check for date. */ final long today = new Date().getTime(); final long milli_seconds_in_a_day = 1000 * 24 * 60 * 60; if ((today / milli_seconds_in_a_day) != (cloudFile.date / milli_seconds_in_a_day)) { DateFormat dateFormat = DateFormat.getDateInstance(); final String message = MessageFormat.format( MessagesBundle .getString("question_message_overwrite_your_data_by_cloud_data_at_template"), dateFormat.format(cloudFile.date)); final int result = JOptionPane.showConfirmDialog(LoadFromCloudJDialog.this, message, MessagesBundle.getString("question_title_overwrite_your_data_by_cloud_data_at"), JOptionPane.YES_NO_OPTION); if (result != JOptionPane.YES_OPTION) { publish(Status.newInstance( GUIBundle.getString("LoadFromCloudJDialog_UserRefuseToOverwriteWithOldData"), Icons.ERROR)); return null; } } /* Check for version. */ if (Utils.isCloudFileCompatible(cloudFile.version) == false) { final String message = MessageFormat.format( GUIBundle.getString("LoadFromCloudJDialog_VersionNotCompatible_template"), cloudFile.version); publish(Status.newInstance(message, Icons.ERROR)); return null; } // Place isCancelled check after time consuming operation. // Not the best way, but perhaps the easiest way to cancel // the operation. if (isCancelled()) { return null; } publish(Status.newInstance(GUIBundle.getString("LoadFromCloudJDialog_ExtractingData..."), Icons.BUSY)); boolean status = Utils.extractZipFile(cloudFile.file, true); // Place isCancelled check after time consuming operation. // Not the best way, but perhaps the easiest way to cancel // the operation. if (isCancelled()) { return null; } if (false == status) { publish(Status.newInstance(GUIBundle.getString("LoadFromCloudJDialog_ExtractingDataFail"), Icons.ERROR)); return null; } final File f = new File(org.yccheok.jstock.gui.Utils.getUserDataDirectory() + "config" + File.separator + "options.xml"); final JStockOptions jStockOptions = Utils.fromXML(JStockOptions.class, f); if (jStockOptions == null) { publish(Status.newInstance(GUIBundle.getString("LoadFromCloudJDialog_ExtractingDataFail"), Icons.ERROR)); return null; } // json from Android might contain latest configuration. loadBrokingFirmsFromJson(jStockOptions); publish(Status.newInstance(GUIBundle.getString("LoadFromCloudJDialog_Success"), Icons.OK)); return jStockOptions; } }; return worker; }
From source file:org.yccheok.jstock.gui.OptionsAlertJPanel.java
private void signIn() { jCheckBox2.setEnabled(false);//from ww w . j ava2 s .c o m SwingWorker swingWorker = new SwingWorker<Pair<Pair<Credential, String>, Boolean>, Void>() { @Override protected Pair<Pair<Credential, String>, Boolean> doInBackground() throws Exception { final Pair<Pair<Credential, String>, Boolean> pair = org.yccheok.jstock.google.Utils .authorizeGmail(); return pair; } @Override public void done() { Pair<Pair<Credential, String>, Boolean> pair = null; try { pair = this.get(); } catch (InterruptedException ex) { JOptionPane.showMessageDialog(OptionsAlertJPanel.this, ex.getMessage(), GUIBundle.getString("OptionsAlertJPanel_Alert"), JOptionPane.ERROR_MESSAGE); log.error(null, ex); } catch (ExecutionException ex) { Throwable throwable = ex.getCause(); if (throwable instanceof com.google.api.client.googleapis.json.GoogleJsonResponseException) { com.google.api.client.googleapis.json.GoogleJsonResponseException ge = (com.google.api.client.googleapis.json.GoogleJsonResponseException) throwable; for (GoogleJsonError.ErrorInfo errorInfo : ge.getDetails().getErrors()) { if ("insufficientPermissions".equals(errorInfo.getReason())) { org.yccheok.jstock.google.Utils.logoutGmail(); break; } } } JOptionPane.showMessageDialog(OptionsAlertJPanel.this, ex.getMessage(), GUIBundle.getString("OptionsAlertJPanel_Alert"), JOptionPane.ERROR_MESSAGE); log.error(null, ex); } if (pair != null) { credentialEx = pair.first; } else { jCheckBox2.setSelected(false); JStock.instance().getJStockOptions().setSendEmail(jCheckBox2.isSelected()); } updateGUIState(); } }; swingWorker.execute(); }
From source file:org.yccheok.jstock.gui.OptionsAlertJPanel.java
private void initCredentialEx() { SwingWorker swingWorker = new SwingWorker<Pair<Credential, String>, Void>() { @Override/*from w ww . ja v a 2s . c om*/ protected Pair<Credential, String> doInBackground() throws Exception { final Pair<Credential, String> pair = org.yccheok.jstock.google.Utils.authorizeGmailOffline(); return pair; } @Override public void done() { Pair<Credential, String> pair = null; try { pair = this.get(); } catch (InterruptedException ex) { log.error(null, ex); } catch (ExecutionException ex) { Throwable throwable = ex.getCause(); if (throwable instanceof com.google.api.client.googleapis.json.GoogleJsonResponseException) { com.google.api.client.googleapis.json.GoogleJsonResponseException ge = (com.google.api.client.googleapis.json.GoogleJsonResponseException) throwable; for (GoogleJsonError.ErrorInfo errorInfo : ge.getDetails().getErrors()) { if ("insufficientPermissions".equals(errorInfo.getReason())) { org.yccheok.jstock.google.Utils.logoutGmail(); break; } } } log.error(null, ex); } if (pair != null) { credentialEx = pair; jCheckBox2.setSelected(JStock.instance().getJStockOptions().isSendEmail()); } updateGUIState(); } }; swingWorker.execute(); }
From source file:org.yccheok.jstock.gui.OptionsAlertJPanel.java
/** * Get Swing worker thread which performs email testing task. * @return Swing wroker thread which performs email testing task *///from ww w. j ava2 s . c o m private SwingWorker getTestEmailSwingWorker() { SwingWorker worker = new SwingWorker<Boolean, Void>() { @Override public Boolean doInBackground() { boolean status = true; Pair<Credential, String> credentialEx = OptionsAlertJPanel.this.credentialEx; if (credentialEx == null) { status = false; } else { final String ccEmail = jTextField1.getText().trim(); final String title = MessagesBundle .getString("info_message_congratulation_email_alert_system_is_working"); final String message = MessagesBundle .getString("info_message_congratulation_email_alert_system_is_working"); try { GoogleMail.Send(ccEmail, title, message); } catch (Exception ex) { log.error(null, ex); status = false; } } return status; } @Override public void done() { // The done Method: When you are informed that the SwingWorker // is done via a property change or via the SwingWorker object's // done method, you need to be aware that the get methods can // throw a CancellationException. A CancellationException is a // RuntimeException, which means you do not need to declare it // thrown and you do not need to catch it. Instead, you should // test the SwingWorker using the isCancelled method before you // use the get method. if (this.isCancelled()) { // Cancelled by user explicitly. Do not perform any GUI update. // No pop-up message. return; } Boolean status = null; try { status = get(); } catch (InterruptedException ex) { log.error(null, ex); } catch (ExecutionException ex) { log.error(null, ex); } catch (CancellationException ex) { // Some developers suggest to catch this exception, instead of // checking on isCancelled. As I am not confident by merely // isCancelled check can prevent CancellationException (What // if cancellation is happen just after isCancelled check?), // I will apply both techniques. log.error(null, ex); } OptionsAlertJPanel.this.updateGUIState(); if (status == null || status == false) { JOptionPane.showMessageDialog(OptionsAlertJPanel.this, MessagesBundle.getString("error_message_error_in_sending_email"), MessagesBundle.getString("error_title_error_in_sending_email"), JOptionPane.ERROR_MESSAGE); } else { JOptionPane.showMessageDialog(OptionsAlertJPanel.this, MessagesBundle.getString("info_message_email_alert_system_is_working"), MessagesBundle.getString("info_title_email_alert_system_is_working"), JOptionPane.INFORMATION_MESSAGE); } } }; return worker; }