List of usage examples for javax.swing ProgressMonitor close
public void close()
From source file:kindleclippings.quizlet.QuizletSync.java
public static void main(String[] args) throws IOException, JSONException, URISyntaxException, InterruptedException, BackingStoreException { ProgressMonitor progress = new ProgressMonitor(null, "QuizletSync", "loading Kindle clippings file", 0, 100);//ww w . j ava 2 s . c o m progress.setMillisToPopup(0); progress.setMillisToDecideToPopup(0); progress.setProgress(0); try { Map<String, List<Clipping>> books = readClippingsFile(); if (books == null) return; if (books.isEmpty()) { JOptionPane.showMessageDialog(null, "no clippings to be uploaded", "QuizletSync", JOptionPane.OK_OPTION); return; } progress.setNote("checking Quizlet account"); progress.setProgress(5); Preferences prefs = getPrefs(); QuizletAPI api = new QuizletAPI(prefs.get("access_token", null)); Collection<TermSet> sets = null; try { progress.setNote("checking Quizlet library"); progress.setProgress(10); sets = api.getSets(prefs.get("user_id", null)); } catch (IOException e) { if (e.toString().contains("401")) { // Not Authorized => Token has been revoked clearPrefs(); prefs = getPrefs(); api = new QuizletAPI(prefs.get("access_token", null)); sets = api.getSets(prefs.get("user_id", null)); } else { throw e; } } progress.setProgress(15); progress.setMaximum(15 + books.size()); progress.setNote("uploading new notes"); Map<String, TermSet> indexedSets = new HashMap<String, TermSet>(sets.size()); for (TermSet t : sets) { indexedSets.put(t.getTitle(), t); } int pro = 15; int createdSets = 0; int createdTerms = 0; int updatedTerms = 0; for (List<Clipping> c : books.values()) { String book = c.get(0).getBook(); progress.setNote(book); progress.setProgress(pro++); TermSet termSet = indexedSets.get(book); if (termSet == null) { if (c.size() < 2) { System.err.println("ignored [" + book + "] (need at least two notes)"); continue; } addSet(api, book, c); createdSets++; createdTerms += c.size(); continue; } // compare against existing terms for (Clipping cl : c) { if (!checkExistingTerm(cl, termSet)) { addTerm(api, termSet, cl); updatedTerms++; } } } progress.setProgress(pro++); if (createdSets == 0 && updatedTerms == 0) { JOptionPane.showMessageDialog(null, "Done.\nNo new data was uploaded", "QuizletSync", JOptionPane.OK_OPTION); } else if (createdSets > 0) { JOptionPane.showMessageDialog(null, String.format( "Done.\nCreated %d new sets with %d cards, and added %d cards to existing sets", createdSets, createdTerms, updatedTerms), "QuizletSync", JOptionPane.OK_OPTION); } else { JOptionPane.showMessageDialog(null, String.format("Done.\nAdded %d cards to existing sets", updatedTerms), "QuizletSync", JOptionPane.OK_OPTION); } } finally { progress.close(); } System.exit(0); }
From source file:kindleclippings.word.QuizletSync.java
public static void main(String[] args) throws IOException, JSONException, URISyntaxException, InterruptedException, BackingStoreException, BadLocationException { JFileChooser fc = new JFileChooser(); fc.setFileFilter(new FileNameExtensionFilter("Word documents", "doc", "rtf", "txt")); fc.setMultiSelectionEnabled(true);/*from w w w . ja v a2 s . c om*/ int result = fc.showOpenDialog(null); if (result != JFileChooser.APPROVE_OPTION) { return; } File[] clf = fc.getSelectedFiles(); if (clf == null || clf.length == 0) return; ProgressMonitor progress = new ProgressMonitor(null, "QuizletSync", "loading notes files", 0, 100); progress.setMillisToPopup(0); progress.setMillisToDecideToPopup(0); progress.setProgress(0); try { progress.setNote("checking Quizlet account"); progress.setProgress(5); Preferences prefs = kindleclippings.quizlet.QuizletSync.getPrefs(); QuizletAPI api = new QuizletAPI(prefs.get("access_token", null)); Collection<TermSet> sets = null; try { progress.setNote("checking Quizlet library"); progress.setProgress(10); sets = api.getSets(prefs.get("user_id", null)); } catch (IOException e) { if (e.toString().contains("401")) { // Not Authorized => Token has been revoked kindleclippings.quizlet.QuizletSync.clearPrefs(); prefs = kindleclippings.quizlet.QuizletSync.getPrefs(); api = new QuizletAPI(prefs.get("access_token", null)); sets = api.getSets(prefs.get("user_id", null)); } else { throw e; } } progress.setProgress(15); progress.setMaximum(15 + clf.length * 10); progress.setNote("uploading new notes"); int pro = 15; int addedSets = 0; int updatedTerms = 0; int updatedSets = 0; for (File f : clf) { progress.setProgress(pro); List<Clipping> clippings = readClippingsFile(f); if (clippings == null) { pro += 10; continue; } if (clippings.isEmpty()) { pro += 10; continue; } if (clippings.size() < 2) { pro += 10; continue; } String book = clippings.get(0).getBook(); progress.setNote(book); TermSet termSet = null; String x = book.toLowerCase().replaceAll("\\W", ""); for (TermSet t : sets) { if (t.getTitle().toLowerCase().replaceAll("\\W", "").equals(x)) { termSet = t; break; } } if (termSet == null) { addSet(api, book, clippings); addedSets++; pro += 10; continue; } // compare against existing terms boolean hasUpdated = false; for (Clipping cl : clippings) { if (!kindleclippings.quizlet.QuizletSync.checkExistingTerm(cl, termSet)) { kindleclippings.quizlet.QuizletSync.addTerm(api, termSet, cl); updatedTerms++; hasUpdated = true; } } pro += 10; if (hasUpdated) updatedSets++; } if (updatedTerms == 0 && addedSets == 0) { JOptionPane.showMessageDialog(null, "Done.\nNo new data was uploaded", "QuizletSync", JOptionPane.OK_OPTION); } else { if (addedSets > 0) { JOptionPane.showMessageDialog(null, String.format("Done.\nCreated %d new sets and added %d cards to %d existing sets", addedSets, updatedSets, updatedTerms), "QuizletSync", JOptionPane.OK_OPTION); } else { JOptionPane.showMessageDialog(null, String.format("Done.\nAdded %d cards to %d existing sets", updatedTerms, updatedSets), "QuizletSync", JOptionPane.OK_OPTION); } } } finally { progress.close(); } System.exit(0); }
From source file:net.ftb.minecraft.MCInstaller.java
public static void setupNewStyle(final String installPath, final ModPack pack, final boolean isLegacy, final LoginResponse RESPONSE) { List<DownloadInfo> assets = gatherAssets(new File(installPath), pack.getMcVersion(Settings.getSettings().getPackVer(pack.getDir())), installPath); if (assets != null && assets.size() > 0) { Logger.logInfo("Checking/Downloading " + assets.size() + " assets, this may take a while..."); final ProgressMonitor prog = new ProgressMonitor(LaunchFrame.getInstance(), "Downloading Files...", "", 0, 100);//from ww w. j a v a 2 s.c om prog.setMaximum(assets.size() * 100); final AssetDownloader downloader = new AssetDownloader(prog, assets) { @Override public void done() { try { prog.close(); if (get()) { Logger.logInfo("Asset downloading complete"); launchMinecraft(installPath, pack, RESPONSE, isLegacy); } else { ErrorUtils.tossError("Error occurred during downloading the assets"); } } catch (CancellationException e) { Logger.logInfo("Asset download interrupted by user"); } catch (Exception e) { ErrorUtils.tossError("Failed to download files.", e); } finally { LaunchFrame.getInstance().getEventBus().post(new EnableObjectsEvent()); } } }; downloader.addPropertyChangeListener(new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent evt) { if (prog.isCanceled()) { downloader.cancel(false); prog.close(); } else if (!downloader.isCancelled()) { if ("ready".equals(evt.getPropertyName())) prog.setProgress(downloader.getReady()); if ("status".equals(evt.getPropertyName())) prog.setNote(downloader.getStatus()); } } }); downloader.execute(); } else if (assets == null) { LaunchFrame.getInstance().getEventBus().post(new EnableObjectsEvent()); } else { launchMinecraft(installPath, pack, RESPONSE, isLegacy); } }
From source file:com.diversityarrays.kdxplore.trialmgr.trait.TraitExplorerPanel.java
private void doImportTraitsFileImpl(File file) { Context context = KDSmartApplication.getInstance(); final ProgressMonitor monitor = new ProgressMonitor(TraitExplorerPanel.this, "Loading", "", 0, 100); ProgressReporter progressReporter = new ProgressReporter() { @Override//from w w w . j a v a2 s . co m public void setProgressNote(String note) { monitor.setNote(note); } @Override public void setProgressMaximum(int max) { monitor.setMaximum(max); } @Override public void setProgressCount(int count) { monitor.setProgress(count); } @Override public void dismissProgress() { monitor.close(); } }; try { Either<ImportError, TraitImportTransactions> either = offlineData.getKdxploreDatabase() .getKDXploreKSmartDatabase().importTraitsFile(context, file, progressReporter); if (either.isLeft()) { ImportError ie = either.left(); MsgBox.error(TraitExplorerPanel.this, ie.getMessage("Import Traits"), "Import Failed"); } else { TraitImportTransactions tit = either.right(); if (!tit.traitsToBeUpdated.isEmpty()) { } refreshTraitsTable(); StringBuilder sb = new StringBuilder("Import Result"); if (tit.nSkipped > 0) { sb.append("\nSkipped ").append(tit.nSkipped); } if (!tit.traitsToBeAdded.isEmpty()) { sb.append("\nAdded: ").append(tit.traitsToBeAdded.size()); } if (!tit.traitsToBeUpdated.isEmpty()) { sb.append("\nUpdated: ").append(tit.traitsToBeUpdated.size()); } MsgBox.info(TraitExplorerPanel.this, sb.toString(), "Import Complete"); } } finally { progressReporter.dismissProgress(); } }
From source file:org.usfirst.frc.team2084.neuralnetwork.HeadingNeuralNetworkTrainer.java
private void trainNetwork() { if (!training) { // Set training flag and disable button training = true;// w ww. jav a2s . c om trainButton.setEnabled(false); final ProgressMonitor progressMonitor = new ProgressMonitor(frame, "Training Network...", "", 0, 100); progressMonitor.setMillisToDecideToPopup(100); progressMonitor.setMillisToPopup(400); @SuppressWarnings("unchecked") final ArrayList<XYDataItem> data = new ArrayList<>(outputGraphDataSeries.getItems()); final int maxProgress = iterations * data.size(); final SwingWorker<Void, Void> trainingWorker = new SwingWorker<Void, Void>() { @Override protected Void doInBackground() throws Exception { // Reset the neural network to default values synchronized (this) { network.reset(); network.setEta(eta); network.setMomentum(momentum); } outer: for (int j = 0; j < iterations; j++) { for (int i = 0; i < data.size(); i++) { if (!isCancelled()) { XYDataItem d = data.get(i); double error = convertAngleToInput(d.getXValue()); double output = d.getYValue(); synchronized (this) { network.feedForward(error); network.backPropagation(output); } int jl = j; int il = i; int progress = (int) (((float) (data.size() * jl + il + 1) / maxProgress) * 100); setProgress(progress); } else { break outer; } } } displayNetwork(); return null; } @Override protected void done() { training = false; trainButton.setEnabled(true); progressMonitor.close(); } }; trainingWorker.addPropertyChangeListener(new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent evt) { if (evt.getPropertyName().equals("progress")) { progressMonitor.setProgress((int) evt.getNewValue()); } if (progressMonitor.isCanceled()) { trainingWorker.cancel(true); } } }); trainingWorker.execute(); } }
From source file:de.cismet.cids.custom.objecteditors.wunda_blau.WebDavPicturePanel.java
/** * DOCUMENT ME!/*w w w. j a v a2s .c om*/ * * @param fileName DOCUMENT ME! * * @return DOCUMENT ME! * * @throws Exception DOCUMENT ME! */ private BufferedImage downloadImageFromWebDAV(final String fileName) throws Exception { final InputStream iStream = webdavHelper.getFileFromWebDAV(fileName, webdavDirectory, getConnectionContext()); try { final ImageInputStream iiStream = ImageIO.createImageInputStream(iStream); final Iterator<ImageReader> itReader = ImageIO.getImageReaders(iiStream); if (itReader.hasNext()) { final ImageReader reader = itReader.next(); final ProgressMonitor monitor = new ProgressMonitor(this, "Bild wird bertragen...", "", 0, 100); // monitor.setMillisToPopup(500); reader.addIIOReadProgressListener(new IIOReadProgressListener() { @Override public void sequenceStarted(final ImageReader source, final int minIndex) { } @Override public void sequenceComplete(final ImageReader source) { } @Override public void imageStarted(final ImageReader source, final int imageIndex) { monitor.setProgress(monitor.getMinimum()); } @Override public void imageProgress(final ImageReader source, final float percentageDone) { if (monitor.isCanceled()) { try { iiStream.close(); } catch (final IOException ex) { // NOP } } else { monitor.setProgress(Math.round(percentageDone)); } } @Override public void imageComplete(final ImageReader source) { monitor.setProgress(monitor.getMaximum()); } @Override public void thumbnailStarted(final ImageReader source, final int imageIndex, final int thumbnailIndex) { } @Override public void thumbnailProgress(final ImageReader source, final float percentageDone) { } @Override public void thumbnailComplete(final ImageReader source) { } @Override public void readAborted(final ImageReader source) { monitor.close(); } }); final ImageReadParam param = reader.getDefaultReadParam(); reader.setInput(iiStream, true, true); final BufferedImage result; try { result = reader.read(0, param); } finally { reader.dispose(); iiStream.close(); } return result; } else { return null; } } finally { IOUtils.closeQuietly(iStream); } }
From source file:com.marginallyclever.makelangelo.MainGUI.java
public boolean LoadImage(String filename) { // where to save temp output file? final String sourceFile = filename; final String destinationFile = GetTempDestinationFile(); LoadImageConverters();/*from w w w. j av a 2 s. c o m*/ if (ChooseImageConversionOptions(false) == false) return false; final ProgressMonitor pm = new ProgressMonitor(null, translator.get("Converting"), "", 0, 100); pm.setProgress(0); pm.setMillisToPopup(0); final SwingWorker<Void, Void> s = new SwingWorker<Void, Void>() { @Override public Void doInBackground() { // read in image BufferedImage img; try { Log("<font color='green'>" + translator.get("Converting") + " " + destinationFile + "</font>\n"); // convert with style img = ImageIO.read(new File(sourceFile)); int style = GetDrawStyle(); Filter f = image_converters.get(style); TabToLog(); f.SetParent(this); f.SetProgressMonitor(pm); f.SetDestinationFile(destinationFile); f.Convert(img); TabToDraw(); previewPane.ZoomToFitPaper(); } catch (IOException e) { Log("<font color='red'>" + translator.get("Failed") + e.getLocalizedMessage() + "</font>\n"); recentFiles.remove(sourceFile); updateMenuBar(); } pm.setProgress(100); return null; } @Override public void done() { pm.close(); Log("<font color='green'>" + translator.get("Finished") + "</font>\n"); PlayConversionFinishedSound(); LoadGCode(destinationFile); } }; s.addPropertyChangeListener(new PropertyChangeListener() { // Invoked when task's progress property changes. public void propertyChange(PropertyChangeEvent evt) { if ("progress" == evt.getPropertyName()) { int progress = (Integer) evt.getNewValue(); pm.setProgress(progress); String message = String.format("%d%%.\n", progress); pm.setNote(message); if (s.isDone()) { Log("<font color='green'>" + translator.get("Finished") + "</font>\n"); } else if (s.isCancelled() || pm.isCanceled()) { if (pm.isCanceled()) { s.cancel(true); } Log("<font color='green'>" + translator.get("Cancelled") + "</font>\n"); } } } }); s.execute(); return true; }
From source file:jamel.gui.JamelWindow.java
/** * Exports a rapport./*from w w w. j a va2 s. co m*/ */ public void exportRapport() { final int max = tabbedPane.getTabCount(); final ProgressMonitor progressMonitor = new ProgressMonitor(this, "Exporting", "", 0, max); progressMonitor.setMillisToDecideToPopup(0); final String rc = System.getProperty("line.separator"); final File outputDirectory = new File("exports/" + this.getTitle() + "-" + (new Date()).getTime()); outputDirectory.mkdir(); try { final FileWriter writer = new FileWriter(new File(outputDirectory, "Rapport.html")); writer.write("<HTML>" + rc); writer.write("<HEAD>"); writer.write("<TITLE>" + this.getTitle() + "</TITLE>" + rc); writer.write("</HEAD>" + rc); writer.write("<BODY>" + rc); writer.write("<H1>" + this.getTitle() + "</H1>" + rc); writer.write("<HR>" + rc); final Date start = viewManager.getStart().getDate(); final Date end = viewManager.getEnd().getDate(); for (int tabIndex = 0; tabIndex < max; tabIndex++) { try { final JPanel currentTab = (JPanel) tabbedPane.getComponentAt(tabIndex); final String tabTitle = tabbedPane.getTitleAt(tabIndex); writer.write("<H2>" + tabTitle + "</H2>" + rc); writer.write("<TABLE>" + rc); final int chartPanelCount = currentTab.getComponentCount(); for (int chartIndex = 0; chartIndex < chartPanelCount; chartIndex++) { if ((chartIndex == 3) | (chartIndex == 6)) writer.write("<TR>" + rc); final ChartPanel aChartPanel = (ChartPanel) currentTab.getComponent(chartIndex); final JamelChart chart = (JamelChart) aChartPanel.getChart(); if (chart != null) { final String chartTitle = chart.getTitle().getText(); if (!chartTitle.equals("Empty")) { try { chart.setTitle(""); chart.setTimeRange(start, end); String imageName = (tabTitle + "-" + chartIndex + "-" + chartTitle + ".png") .replace(" ", "_").replace("&", "and"); ChartUtilities.saveChartAsPNG(new File(outputDirectory, imageName), chart, aChartPanel.getWidth(), aChartPanel.getHeight()); writer.write("<TD><IMG src=\"" + imageName + "\" title=\"" + chartTitle + "\">" + rc); chart.setTitle(chartTitle); } catch (IOException e) { e.printStackTrace(); } } } } writer.write("</TABLE>" + rc); writer.write("<HR>" + rc); } catch (ClassCastException e) { } progressMonitor.setProgress(tabIndex); } writer.write("<H2>Scenario</H2>" + rc); writer.write(this.consoleText.toString()); writer.write("</BODY>" + rc); writer.write("</HTML>" + rc); writer.close(); } catch (IOException e1) { e1.printStackTrace(); } progressMonitor.close(); }
From source file:ca.sqlpower.architect.swingui.SwingUIProjectLoader.java
/** * Saves this project by writing an XML description of it to a temp file, then renaming. * The location of the file is determined by this project's <code>file</code> property. * * @param pm An optional progress monitor which will be initialised then updated * periodically during the save operation. If you use a progress monitor, don't * invoke this method on the AWT event dispatch thread! *///from w w w . j ava 2 s . com public void save(ProgressMonitor pm) throws IOException, SQLObjectException { // write to temp file and then rename (this preserves old project file // when there's problems) if (file.exists() && !file.canWrite()) { // write problems with architect file will muck up the save process throw new SQLObjectException( Messages.getString("SwingUIProject.errorSavingProject", file.getAbsolutePath())); //$NON-NLS-1$ } if (fileVersion != null && !fileVersion.equals(ArchitectVersion.APP_FULL_VERSION.toString())) { String message; try { ArchitectVersion oldFileVersion = new ArchitectVersion(fileVersion); if (oldFileVersion.compareTo(ArchitectVersion.APP_FULL_VERSION) < 0) { message = "Overwriting older file. Older versions may have problems " + "loading the newer file format."; } else { message = "Overwriting newer file. Some data loss from loading may occur."; } } catch (Exception e) { message = "Overwriting file with an invalid version."; } UserPrompter prompter = getSession().createUserPrompter(message + "\nDo you wish to continue?", UserPromptType.BOOLEAN, UserPromptOptions.OK_CANCEL, UserPromptResponse.OK, UserPromptResponse.OK, "OK", "Cancel"); UserPromptResponse response = prompter.promptUser(); if (response.equals(UserPromptResponse.CANCEL)) { return; } } File backupFile = new File(file.getParent(), file.getName() + "~"); //$NON-NLS-1$ // Several places we would check dir perms, but MS-Windows stupidly doesn't let use the // "directory write" attribute for directory writing (but instead overloads // it to mean 'this is a special directory'. File tempFile = null; tempFile = new File(file.getParent(), "tmp___" + file.getName()); //$NON-NLS-1$ String encoding = "UTF-8"; //$NON-NLS-1$ try { // If creating this temp file fails, feed the user back a more explanatory message out = new PrintWriter(tempFile, encoding); } catch (IOException e) { throw new SQLObjectException(Messages.getString("SwingUIProject.cannotCreateOutputFile") + e, e); //$NON-NLS-1$ } progress = 0; this.pm = pm; if (pm != null) { int pmMax = 0; pm.setMinimum(0); if (getSession().isSavingEntireSource()) { pmMax = SQLObjectUtils .countTablesSnapshot((SQLObject) getSession().getDBTree().getModel().getRoot()); } else { pmMax = SQLObjectUtils.countTables((SQLObject) getSession().getDBTree().getModel().getRoot()); } logger.debug("Setting progress monitor maximum to " + pmMax); //$NON-NLS-1$ pm.setMaximum(pmMax); pm.setProgress(progress); pm.setMillisToDecideToPopup(0); } save(out, encoding); // Does ALL the actual I/O out = null; if (pm != null) pm.close(); pm = null; // Do the rename dance. // This is a REALLY bad place for failure (especially if we've made the user wait several hours to save // a large project), so we MUST check failures from renameto (both places!) boolean fstatus = false; fstatus = backupFile.delete(); logger.debug("deleting backup~ file: " + fstatus); //$NON-NLS-1$ // If this is a brand new project, the old file does not yet exist, no point trying to rename it. // But if it already existed, renaming current to backup must succeed, or we give up. if (file.exists()) { fstatus = file.renameTo(backupFile); logger.debug("rename current file to backupFile: " + fstatus); //$NON-NLS-1$ if (!fstatus) { throw new SQLObjectException((Messages.getString("SwingUIProject.couldNotRenameFile", //$NON-NLS-1$ tempFile.toString(), file.toString()))); } } fstatus = tempFile.renameTo(file); if (!fstatus) { throw new SQLObjectException((Messages.getString("SwingUIProject.couldNotRenameTempFile", //$NON-NLS-1$ tempFile.toString(), file.toString()))); } logger.debug("rename tempFile to current file: " + fstatus); //$NON-NLS-1$ fileVersion = ArchitectVersion.APP_FULL_VERSION.toString(); }
From source file:com.monead.semantic.workbench.SemanticWorkbench.java
/** * Expand all the nodes in the tree representation of the model * /*from www. j a v a 2 s . c o m*/ * @return The final status to display */ private String expandAll() { int numNodes; ProgressMonitor progress; boolean canceled; final DefaultMutableTreeNode root = (DefaultMutableTreeNode) ontModelTree.getModel().getRoot(); @SuppressWarnings("rawtypes") final Enumeration enumerateNodes = root.breadthFirstEnumeration(); numNodes = 0; while (enumerateNodes.hasMoreElements()) { enumerateNodes.nextElement(); ++numNodes; } LOGGER.debug("Expanding tree with row count: " + numNodes); progress = new ProgressMonitor(this, "Expanding Tree Nodes", "Starting node expansion", 0, numNodes); setStatus("Expanding all tree nodes"); for (int row = 0; !progress.isCanceled() && row < numNodes; ++row) { progress.setProgress(row); if (row % 1000 == 0) { progress.setNote("Row " + row + " of " + numNodes); } ontModelTree.expandRow(row); } canceled = progress.isCanceled(); progress.close(); ontModelTree.scrollRowToVisible(0); if (!canceled) { // Select the tree view tab SwingUtilities.invokeLater(new Runnable() { public void run() { tabbedPane.setSelectedIndex(TAB_NUMBER_TREE_VIEW); } }); } return canceled ? "Tree node expansion canceled by user" : "Tree nodes expanded"; }