List of usage examples for javax.swing ProgressMonitor close
public void close()
From source file:com.monead.semantic.workbench.SemanticWorkbench.java
/** * Add the classes to the tree view// w w w . jav a 2s. com * * @see #addIndividualsToTree(OntClass, DefaultMutableTreeNode, * ProgressMonitor) * * @param classesNode * The classes parent node in the tree * @param maxIndividualsPerClass * The maximum number of individuals to display in each class * @param messagePrefix * Prefix for display messages */ private void addClassesToTree(DefaultMutableTreeNode classesNode, int maxIndividualsPerClass, String messagePrefix) { ProgressMonitor progress = null; DefaultMutableTreeNode oneClassNode; List<OntClass> ontClasses; ExtendedIterator<OntClass> classesIterator; int classNumber; try { classesIterator = ontModel.listClasses(); setStatus(messagePrefix + "... obtaining the list of classes"); if (LOGGER.isTraceEnabled()) { LOGGER.trace("List of classes built"); } ontClasses = new ArrayList<OntClass>(); while (classesIterator.hasNext()) { ontClasses.add(classesIterator.next()); } progress = new ProgressMonitor(this, "Create the model tree view", "Setting up the class list", 0, ontClasses.size()); Collections.sort(ontClasses, new OntClassComparator()); if (LOGGER.isTraceEnabled()) { LOGGER.trace("List of classes sorted. Num classes:" + ontClasses.size()); } classNumber = 0; for (OntClass ontClass : ontClasses) { setStatus(messagePrefix + " for class " + ontClass); if (MemoryWarningSystem.hasLatestAvailableTenuredGenAfterCollectionChanged(this) && MemoryWarningSystem .getLatestAvailableTenuredGenAfterCollection() < MINIMUM_BYTES_REQUIRED_FOR_TREE_BUILD) { throw new IllegalStateException( "Insufficient memory available to complete building the tree (class iteration)"); } if (progress.isCanceled()) { throw new RuntimeException("Tree model creation canceled by user"); } progress.setNote(ontClass.toString()); progress.setProgress(++classNumber); // Check whether class is to be skipped if (LOGGER.isTraceEnabled()) { LOGGER.trace("Check if class to be skipped: " + ontClass.getURI()); for (String skipClass : classesToSkipInTree.keySet()) { LOGGER.trace("Class to skip: " + skipClass + " equal? " + (skipClass.equals(ontClass.getURI()))); } } if (filterEnableFilters.isSelected() && classesToSkipInTree.get(ontClass.getURI()) != null) { LOGGER.debug("Class to be skipped: " + ontClass.getURI()); continue; } if (ontClass.isAnon()) { // Show anonymous classes based on configuration if (filterShowAnonymousNodes.isSelected()) { oneClassNode = new DefaultMutableTreeNode( new WrapperClass(ontClass.getId().getLabelString(), "[Anonymous class]", true)); } else { LOGGER.debug("Skip anonymous class: " + ontClass.getId().getLabelString()); continue; } } else { oneClassNode = new DefaultMutableTreeNode(new WrapperClass(ontClass.getLocalName(), ontClass.getURI(), showFqnInTree.isSelected())); LOGGER.debug("Add class node: " + ontClass.getLocalName() + " (" + ontClass.getURI() + ")"); } classesNode.add(oneClassNode); addIndividualsToTree(ontClass, oneClassNode, maxIndividualsPerClass, progress); } } finally { if (progress != null) { progress.close(); } } }
From source file:com.marginallyclever.makelangelo.MainGUI.java
protected boolean LoadDXF(String filename) { if (ChooseImageConversionOptions(true) == false) return false; // where to save temp output file? final String destinationFile = GetTempDestinationFile(); final String srcFile = filename; TabToLog();//from ww w . j av a2 s . c om 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>() { public boolean ok = false; @SuppressWarnings("unchecked") @Override public Void doInBackground() { Log("<font color='green'>" + translator.get("Converting") + " " + destinationFile + "</font>\n"); Parser parser = ParserBuilder.createDefaultParser(); double dxf_x2 = 0; double dxf_y2 = 0; OutputStreamWriter out = null; try { out = new OutputStreamWriter(new FileOutputStream(destinationFile), "UTF-8"); DrawingTool tool = machineConfiguration.GetCurrentTool(); out.write(machineConfiguration.GetConfigLine() + ";\n"); out.write(machineConfiguration.GetBobbinLine() + ";\n"); out.write("G00 G90;\n"); tool.WriteChangeTo(out); tool.WriteOff(out); parser.parse(srcFile, DXFParser.DEFAULT_ENCODING); DXFDocument doc = parser.getDocument(); Bounds b = doc.getBounds(); double width = b.getMaximumX() - b.getMinimumX(); double height = b.getMaximumY() - b.getMinimumY(); double cx = (b.getMaximumX() + b.getMinimumX()) / 2.0f; double cy = (b.getMaximumY() + b.getMinimumY()) / 2.0f; double sy = machineConfiguration.GetPaperHeight() * 10 / height; double sx = machineConfiguration.GetPaperWidth() * 10 / width; double scale = (sx < sy ? sx : sy) * machineConfiguration.paper_margin; sx = scale * (machineConfiguration.reverseForGlass ? -1 : 1); // count all entities in all layers Iterator<DXFLayer> layer_iter = (Iterator<DXFLayer>) doc.getDXFLayerIterator(); int entity_total = 0; int entity_count = 0; while (layer_iter.hasNext()) { DXFLayer layer = (DXFLayer) layer_iter.next(); Log("<font color='yellow'>Found layer " + layer.getName() + "</font>\n"); Iterator<String> entity_iter = (Iterator<String>) layer.getDXFEntityTypeIterator(); while (entity_iter.hasNext()) { String entity_type = (String) entity_iter.next(); List<DXFEntity> entity_list = (List<DXFEntity>) layer.getDXFEntities(entity_type); Log("<font color='yellow'>+ Found " + entity_list.size() + " of type " + entity_type + "</font>\n"); entity_total += entity_list.size(); } } // set the progress meter pm.setMinimum(0); pm.setMaximum(entity_total); // convert each entity layer_iter = doc.getDXFLayerIterator(); while (layer_iter.hasNext()) { DXFLayer layer = (DXFLayer) layer_iter.next(); Iterator<String> entity_type_iter = (Iterator<String>) layer.getDXFEntityTypeIterator(); while (entity_type_iter.hasNext()) { String entity_type = (String) entity_type_iter.next(); List<DXFEntity> entity_list = layer.getDXFEntities(entity_type); if (entity_type.equals(DXFConstants.ENTITY_TYPE_LINE)) { for (int i = 0; i < entity_list.size(); ++i) { pm.setProgress(entity_count++); DXFLine entity = (DXFLine) entity_list.get(i); Point start = entity.getStartPoint(); Point end = entity.getEndPoint(); double x = (start.getX() - cx) * sx; double y = (start.getY() - cy) * sy; double x2 = (end.getX() - cx) * sx; double y2 = (end.getY() - cy) * sy; // is it worth drawing this line? double dx = x2 - x; double dy = y2 - y; if (dx * dx + dy * dy < tool.GetDiameter() / 2.0) { continue; } dx = dxf_x2 - x; dy = dxf_y2 - y; if (dx * dx + dy * dy > tool.GetDiameter() / 2.0) { if (tool.DrawIsOn()) { tool.WriteOff(out); } tool.WriteMoveTo(out, (float) x, (float) y); } if (tool.DrawIsOff()) { tool.WriteOn(out); } tool.WriteMoveTo(out, (float) x2, (float) y2); dxf_x2 = x2; dxf_y2 = y2; } } else if (entity_type.equals(DXFConstants.ENTITY_TYPE_SPLINE)) { for (int i = 0; i < entity_list.size(); ++i) { pm.setProgress(entity_count++); DXFSpline entity = (DXFSpline) entity_list.get(i); entity.setLineWeight(30); DXFPolyline polyLine = DXFSplineConverter.toDXFPolyline(entity); boolean first = true; for (int j = 0; j < polyLine.getVertexCount(); ++j) { DXFVertex v = polyLine.getVertex(j); double x = (v.getX() - cx) * sx; double y = (v.getY() - cy) * sy; double dx = dxf_x2 - x; double dy = dxf_y2 - y; if (first == true) { first = false; if (dx * dx + dy * dy > tool.GetDiameter() / 2.0) { // line does not start at last tool location, lift and move. if (tool.DrawIsOn()) { tool.WriteOff(out); } tool.WriteMoveTo(out, (float) x, (float) y); } // else line starts right here, do nothing. } else { // not the first point, draw. if (tool.DrawIsOff()) tool.WriteOn(out); if (j < polyLine.getVertexCount() - 1 && dx * dx + dy * dy < tool.GetDiameter() / 2.0) continue; // less than 1mm movement? Skip it. tool.WriteMoveTo(out, (float) x, (float) y); } dxf_x2 = x; dxf_y2 = y; } } } else if (entity_type.equals(DXFConstants.ENTITY_TYPE_POLYLINE)) { for (int i = 0; i < entity_list.size(); ++i) { pm.setProgress(entity_count++); DXFPolyline entity = (DXFPolyline) entity_list.get(i); boolean first = true; for (int j = 0; j < entity.getVertexCount(); ++j) { DXFVertex v = entity.getVertex(j); double x = (v.getX() - cx) * sx; double y = (v.getY() - cy) * sy; double dx = dxf_x2 - x; double dy = dxf_y2 - y; if (first == true) { first = false; if (dx * dx + dy * dy > tool.GetDiameter() / 2.0) { // line does not start at last tool location, lift and move. if (tool.DrawIsOn()) { tool.WriteOff(out); } tool.WriteMoveTo(out, (float) x, (float) y); } // else line starts right here, do nothing. } else { // not the first point, draw. if (tool.DrawIsOff()) tool.WriteOn(out); if (j < entity.getVertexCount() - 1 && dx * dx + dy * dy < tool.GetDiameter() / 2.0) continue; // less than 1mm movement? Skip it. tool.WriteMoveTo(out, (float) x, (float) y); } dxf_x2 = x; dxf_y2 = y; } } } } } // entities finished. Close up file. tool.WriteOff(out); tool.WriteMoveTo(out, 0, 0); ok = true; } catch (IOException e) { e.printStackTrace(); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { try { if (out != null) out.close(); } catch (IOException e) { e.printStackTrace(); } } pm.setProgress(100); return null; } @Override public void done() { pm.close(); Log("<font color='green'>" + translator.get("Finished") + "</font>\n"); PlayConversionFinishedSound(); if (ok) { LoadGCode(destinationFile); TabToDraw(); } Halt(); } }; 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:com.monead.semantic.workbench.SemanticWorkbench.java
/** * Load the provided file as an ontology replacing any assertions currently * in the assertions text area.//from w ww . ja v a 2 s.c o m * * @return The message to be presented on the status line */ private String loadOntologyFile() { final int chunkSize = 32000; StringBuilder allData; char[] chunk; long totalBytesRead = 0; int chunksRead = 0; int maxChunks; int bytesRead = -1; ProgressMonitor monitor = null; Reader reader = null; String message; boolean loadCanceled = false; if (rdfFileSource.isFile()) { lastDirectoryUsed = rdfFileSource.getBackingFile().getParentFile(); } assertionsInput.setText(""); invalidateModel(false); allData = new StringBuilder(); chunk = new char[chunkSize]; setStatus("Loading file " + rdfFileSource.getAbsolutePath()); if (rdfFileSource.length() > 0 && rdfFileSource.length() < MAX_ASSERTION_BYTES_TO_LOAD_INTO_TEXT_AREA) { maxChunks = (int) (rdfFileSource.length() / chunkSize); } else { maxChunks = (int) (MAX_ASSERTION_BYTES_TO_LOAD_INTO_TEXT_AREA / chunkSize); } if (rdfFileSource.length() % chunkSize > 0) { ++maxChunks; } // Assume the file can be loaded hasIncompleteAssertionsInput = false; monitor = new ProgressMonitor(this, "Loading assertions from " + rdfFileSource.getName(), "0 bytes read", 0, maxChunks); try { reader = new InputStreamReader(rdfFileSource.getInputStream()); while (!loadCanceled && (rdfFileSource.isUrl() || chunksRead < maxChunks) && (bytesRead = reader.read(chunk)) > -1) { totalBytesRead += bytesRead; chunksRead = (int) (totalBytesRead / chunk.length); if (chunksRead < maxChunks) { allData.append(chunk, 0, bytesRead); } if (chunksRead >= maxChunks) { monitor.setMaximum(chunksRead + 1); } monitor.setProgress(chunksRead); monitor.setNote("Read " + INTEGER_COMMA_FORMAT.format(totalBytesRead) + (rdfFileSource.isFile() ? " of " + INTEGER_COMMA_FORMAT.format(rdfFileSource.length()) : " bytes") + (chunksRead >= maxChunks ? " (Determining total file size)" : "")); loadCanceled = monitor.isCanceled(); } if (!loadCanceled && rdfFileSource.isUrl()) { rdfFileSource.setLength(totalBytesRead); } if (!loadCanceled && rdfFileSource.length() > MAX_ASSERTION_BYTES_TO_LOAD_INTO_TEXT_AREA) { // The entire file was not loaded hasIncompleteAssertionsInput = true; } if (hasIncompleteAssertionsInput) { StringBuilder warningMessage; warningMessage = new StringBuilder(); warningMessage.append("The file is too large to display. However the entire file will be loaded\n"); warningMessage.append("into the model when it is built.\n\nDisplay size limit (bytes): "); warningMessage.append(INTEGER_COMMA_FORMAT.format(MAX_ASSERTION_BYTES_TO_LOAD_INTO_TEXT_AREA)); if (rdfFileSource.isFile()) { warningMessage.append("\nFile size (bytes):"); warningMessage.append(INTEGER_COMMA_FORMAT.format(rdfFileSource.length())); } warningMessage.append("\n\n"); warningMessage.append("Note that the assersions text area will not permit editing\n"); warningMessage.append("of the partially loaded file and the 'save assertions' menu\n"); warningMessage.append("option will be disabled. These limitations are enabled\n"); warningMessage.append("to prevent the accidental loss of information from the\n"); warningMessage.append("source assertions file."); JOptionPane.showMessageDialog(this, warningMessage.toString(), "Max Display Size Reached", JOptionPane.WARNING_MESSAGE); // Add text to the assertions text area to highlight the fact that the // entire file was not loaded into the text area allData.insert(0, "# First " + INTEGER_COMMA_FORMAT.format(MAX_ASSERTION_BYTES_TO_LOAD_INTO_TEXT_AREA) + " of " + INTEGER_COMMA_FORMAT.format(rdfFileSource.length()) + " bytes displayed\n\n"); allData.insert(0, "# INCOMPLETE VERSION of the file: " + rdfFileSource.getAbsolutePath() + "\n"); allData.append("\n\n# INCOMPLETE VERSION of the file: " + rdfFileSource.getAbsolutePath() + "\n"); allData.append("# First " + INTEGER_COMMA_FORMAT.format(MAX_ASSERTION_BYTES_TO_LOAD_INTO_TEXT_AREA) + " of " + INTEGER_COMMA_FORMAT.format(rdfFileSource.length()) + " bytes displayed\n"); } // Set the loaded assertions into the text area, cleaning up Windows \r\n // endings, if found if (!loadCanceled) { assertionsInput.setText(allData.toString().replaceAll("\r\n", "\n")); assertionsInput.setSelectionEnd(0); assertionsInput.setSelectionStart(0); assertionsInput.moveCaretPosition(0); assertionsInput.scrollRectToVisible(new Rectangle(0, 0, 1, 1)); message = "Loaded file" + (hasIncompleteAssertionsInput ? " (incomplete)" : "") + ": " + rdfFileSource.getName(); addRecentAssertedTriplesFile(rdfFileSource); // Select the assertions tab SwingUtilities.invokeLater(new Runnable() { public void run() { tabbedPane.setSelectedIndex(TAB_NUMBER_ASSERTIONS); setFocusOnCorrectTextArea(); } }); } else { message = "Assertions file load canceled by user"; } } catch (Throwable throwable) { setStatus("Unable to load file: " + rdfFileSource.getName()); JOptionPane.showMessageDialog(this, "Error: Unable to read file\n\n" + rdfFileSource.getAbsolutePath() + "\n\n" + throwable.getMessage(), "Error Reading File", JOptionPane.ERROR_MESSAGE); LOGGER.error("Unable to load the file: " + rdfFileSource.getAbsolutePath(), throwable); message = "Unable to load the file: " + rdfFileSource.getAbsolutePath(); } finally { if (reader != null) { try { reader.close(); } catch (Throwable throwable) { LOGGER.error("Unable to close input file", throwable); } } if (monitor != null) { monitor.close(); } } return message; }
From source file:org.archiviststoolkit.mydomain.DomainAccessObjectImpl.java
/** * Add a group of instances.//from www.j a va2s . c om * * @param collection the objects to add * @throws PersistenceException fails if we cannot persist the instance */ public final void addGroup(final Collection collection, Component parent) throws PersistenceException { Session session = SessionFactory.getInstance() .openSession(new AuditInterceptor(ApplicationFrame.getInstance().getCurrentUser())); DomainObject domainObject = null; try { Iterator iterator = collection.iterator(); int numberOfRecords = collection.size(); ProgressMonitor monitor = new ProgressMonitor(parent, "Saving Records", null, 0, numberOfRecords); int count = 0; while (iterator.hasNext()) { domainObject = (DomainObject) iterator.next(); updateClassSpecific(domainObject, session); session.saveOrUpdate(domainObject); monitor.setProgress(count++); } monitor.close(); session.flush(); session.connection().commit(); } catch (HibernateException hibernateException) { throw new PersistenceException("failed to add, class: " + this.getClass() + " object: " + domainObject, hibernateException); } catch (Exception sqlException) { throw new PersistenceException("failed to add, class: " + this.getClass() + " object: " + domainObject, sqlException); } // HibernateUtil.closeSession(); SessionFactory.getInstance().closeSession(session); this.notifyListeners(new DomainAccessEvent(DomainAccessEvent.INSERTGROUP, collection)); }
From source file:org.ecoinformatics.seek.ecogrid.quicksearch.GetMetadataAction.java
/** * Invoked when an action occurs. It will transfer the original metadata * into a html file. The namespace will be the key to find stylesheet. If no * sytlesheet found, metadata will be null. * //from w ww. j a v a2 s .c om * @param e * ActionEvent */ public void actionPerformed(ActionEvent e) { super.actionPerformed(e); NamedObj object = getTarget(); if (object instanceof ResultRecord) { this.item = (ResultRecord) object; } if (item == null) { JOptionPane.showMessageDialog(null, "There is no metadata associated with this component."); return; } ProgressMonitor progressMonitor = new ProgressMonitor(null, "Acquiring Metadata ", "", 0, 5); progressMonitor.setMillisToDecideToPopup(100); progressMonitor.setMillisToPopup(10); progressMonitor.setProgress(0); this.metadataSource = item.getFullRecord(); progressMonitor.setProgress(1); this.nameSpace = item.getNamespace(); progressMonitor.setProgress(2); this.htmlFileName = item.getRecordId(); //System.out.println("the html file name is ====== "+htmlFileName); progressMonitor.setProgress(3); if (configuration == null) { configuration = getConfiguration(); } if (metadataSource != null && nameSpace != null && htmlFileName != null && configuration != null) { if (htmlFileName.endsWith(XMLFILEEXTENSION)) { htmlFileName = htmlFileName + HTMLFILEEXTENSION; } try { progressMonitor.setProgress(4); metadata = StaticUtil.getMetadataHTMLurl(metadataSource, nameSpace, htmlFileName); //System.out.println("before open html page"); configuration.openModel(null, metadata, metadata.toExternalForm()); progressMonitor.setProgress(5); //System.out.println("after open html page"); progressMonitor.close(); } catch (Exception ee) { log.debug("The error to get metadata html ", ee); } } }
From source file:org.madeirahs.editor.ui.SubviewUI.java
/** * Constructs a new Submissions viewing UI. It is recommended that you call * this from the UI thread.//from w w w . jav a 2 s . c om * * @param owner * @param prov */ public SubviewUI(MainUI owner, final FTPProvider prov) { super(owner, "Database Submissions"); parent = owner; this.prov = prov; final SubviewUI inst = this; list = new JList(); list.setBorder(new EmptyBorder(5, 5, 5, 5)); btns = new JPanel(); ((FlowLayout) btns.getLayout()).setAlignment(FlowLayout.RIGHT); load = new JButton("Load"); load.addActionListener(new LoadListener()); accept = new JButton("Accept"); accept.addActionListener(new AcceptListener()); remove = new JButton("Remove"); remove.addActionListener(new RemoveListener()); btns.add(load); btns.add(accept); btns.add(remove); add(BorderLayout.CENTER, list); add(BorderLayout.SOUTH, btns); setDefaultCloseOperation(DO_NOTHING_ON_CLOSE); addWindowListener(new OnCloseDialog()); setSize(300, 300); setLocationRelativeTo(parent); new Thread(new Runnable() { @Override public void run() { try { ProgressMonitor prog = new ProgressMonitor(inst, "Retrieving Database", "", 0, 101); prog.setMillisToDecideToPopup(0); prog.setMillisToPopup(0); dbi = Database.getInstance(ServerFTP.dbDir, prov, prog); prog.close(); try { loadListData(); } catch (IllegalServerStateException e) { e.printStackTrace(); JOptionPane.showMessageDialog(null, "Server communication error. Please contact server admin.\n" + e.toString(), "Bad Response", JOptionPane.ERROR_MESSAGE); } SwingUtilities.invokeLater(new Runnable() { @Override public void run() { list.validate(); } }); } catch (ClassCastException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); JOptionPane.showMessageDialog(parent, "Error downloading database:\n" + e.toString(), "I/O Error", JOptionPane.ERROR_MESSAGE); } catch (ClassNotFoundException e) { e.printStackTrace(); } } }).start(); }
From source file:org.mbari.aved.ui.classifier.knowledgebase.SearchableConceptTreePanel.java
/** * Perfroms the database lookup of all matching Concepts. * @param text/*from www . j a va 2s .co m*/ * @param useGlobSearch */ private void loadNodes(final String text, final boolean useGlobSearch) { Collection matches = null; try { if (useGlobSearch) { if (!cachedGlobSearches.contains(text)) { matches = LWConceptNameDAO.getInstance().findNamesBySubString(text); cachedGlobSearches.add(text); cachedWordSearches.add(text); } } else { if (!cachedWordSearches.contains(text)) { matches = LWConceptNameDAO.getInstance().findNamesStartingWith(text); cachedWordSearches.add(text); } } } catch (DAOException e) { if (log.isErrorEnabled()) { log.error("Database lookup of " + text + " failed", e); } } /* * If we loaded the matched names from the database then we need * to open the Concept such that it gets cached under the root * concept. */ if (matches != null) { final ProgressMonitor progressMonitor = new ProgressMonitor(AppFrameDispatcher.getFrame(), "Loading search results for '" + text + "'", "", 0, matches.size()); int n = 0; for (Iterator i = matches.iterator(); i.hasNext();) { n++; final IConceptName cn = (IConceptName) i.next(); progressMonitor.setProgress(n); progressMonitor.setNote("Loading '" + cn.getName() + "'"); /* * Have to open the node in a seperate thread for the * progress monitor to update. Here we're using foxtrot. */ Worker.post(new Job() { public Object run() { openNode((Concept) cn.getConcept()); return null; } }); } progressMonitor.close(); } }
From source file:plugin.notes.gui.NotesView.java
/** * Opens a .gmn file// www. j av a 2 s. c o m * *@param notesFile .gmn file to open */ private void openGMN(File notesFile) { try { Object obj = notesTree.getLastSelectedPathComponent(); if (obj instanceof NotesTreeNode) { NotesTreeNode node = (NotesTreeNode) obj; if (node != root) { int choice = JOptionPane.showConfirmDialog(this, "Importing note " + notesFile.getName() + " into a node other then root, Continue?", "Importing to a node other then root", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE); if (choice == JOptionPane.NO_OPTION) { return; } } InputStream in = new BufferedInputStream(new FileInputStream(notesFile)); ZipInputStream zin = new ZipInputStream(in); ZipEntry e; ProgressMonitor pm = new ProgressMonitor(GMGenSystem.inst, "Reading Notes Export", "Reading", 1, 1000); int progress = 1; while ((e = zin.getNextEntry()) != null) { unzip(zin, e.getName(), node.getDir()); progress++; if (progress > 99) { progress = 99; } pm.setProgress(progress); } zin.close(); pm.close(); } } catch (IOException e) { JOptionPane.showMessageDialog(this, "Error Reading File" + notesFile.getName()); Logging.errorPrint("Error Reading File" + notesFile.getName()); Logging.errorPrint(e.getMessage(), e); } }
From source file:plugin.notes.gui.NotesView.java
/** * Writes out a GMN file//from www. j a v a2 s .com * *@param exportFile file to export to *@param node node to export *@exception IOException file write failed for some reason */ private void writeNotesFile(File exportFile, NotesTreeNode node) throws IOException { File dir = node.getDir(); ZipOutputStream out = new ZipOutputStream(new FileOutputStream(exportFile)); int max = fileCount(dir); ProgressMonitor pm = new ProgressMonitor(GMGenSystem.inst, "Writing out Notes Export", "Writing", 0, max); try { writeNotesDir(out, dir, dir, pm, 0); } // Always close the streams, even if exceptions were thrown finally { try { out.close(); } catch (IOException e) { //TODO: Should this really be ignored? } } pm.close(); }
From source file:richtercloud.document.scanner.gui.MainPanel.java
/** * * @param images images to be transformed into a {@link OCRSelectPanelPanel} * or {@code null} indicating that no scan data was persisted when opening a * persisted entry/*www.j a v a 2 s . c o m*/ * @param documentFile The {@link File} the document is stored in. * {@code null} indicates that the document has not been saved yet (e.g. if * the {@link OCRSelectComponent} represents scan data). * @throws DocumentAddException */ public void addDocument(final List<BufferedImage> images, final File documentFile, final Object entityToEdit) throws DocumentAddException { if (ADD_DOCUMENT_ASYNC) { final ProgressMonitor progressMonitor = new ProgressMonitor(this, //parent "Generating new document tab", //message null, //note 0, //min 100 //max ); progressMonitor.setMillisToPopup(0); progressMonitor.setMillisToDecideToPopup(0); final SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() { private OCRSelectComponent createdOCRSelectComponentScrollPane; @Override protected Void doInBackground() throws Exception { try { this.createdOCRSelectComponentScrollPane = addDocumentRoutine(images, documentFile, entityToEdit, progressMonitor); } catch (Exception ex) { ex.printStackTrace(); } return null; } @Override protected void done() { progressMonitor.close(); addDocumentDone(this.createdOCRSelectComponentScrollPane); } }; worker.execute(); progressMonitor.setProgress(1); //ProgressMonitor dialog blocks until SwingWorker.done //is invoked } else { OCRSelectComponent oCRSelectComponentScrollPane = addDocumentRoutine(images, documentFile, entityToEdit, null //progressMonitor ); addDocumentDone(oCRSelectComponentScrollPane); } }