Example usage for javax.swing ProgressMonitor ProgressMonitor

List of usage examples for javax.swing ProgressMonitor ProgressMonitor

Introduction

In this page you can find the example usage for javax.swing ProgressMonitor ProgressMonitor.

Prototype

public ProgressMonitor(Component parentComponent, Object message, String note, int min, int max) 

Source Link

Document

Constructs a graphic object that shows progress, typically by filling in a rectangular bar as the process nears completion.

Usage

From source file:Installer.java

public void run() {
    JOptionPane optionPane = new JOptionPane(this, JOptionPane.PLAIN_MESSAGE, JOptionPane.OK_CANCEL_OPTION,
            null, new String[] { "Install", "Cancel" });

    emptyFrame = new Frame("Vivecraft Installer");
    emptyFrame.setUndecorated(true);//  w w  w.j  a va  2  s .  c  om
    emptyFrame.setVisible(true);
    emptyFrame.setLocationRelativeTo(null);
    dialog = optionPane.createDialog(emptyFrame, "Vivecraft Installer");
    dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
    dialog.setVisible(true);
    String str = ((String) optionPane.getValue());
    if (str != null && ((String) optionPane.getValue()).equalsIgnoreCase("Install")) {
        int option = JOptionPane.showOptionDialog(null,
                "Please ensure you have closed the Minecraft launcher before proceeding.\n"
                //"Also, if installing with Forge please ensure you have installed Forge " + FORGE_VERSION + " first.",
                , "Important!", JOptionPane.OK_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE, null, null, null);

        if (option == JOptionPane.OK_OPTION) {
            monitor = new ProgressMonitor(null, "Installing Vivecraft...", "", 0, 100);
            monitor.setMillisToDecideToPopup(0);
            monitor.setMillisToPopup(0);

            task = new InstallTask();
            task.addPropertyChangeListener(this);
            task.execute();
        } else {
            dialog.dispose();
            emptyFrame.dispose();
        }
    } else {
        dialog.dispose();
        emptyFrame.dispose();
    }
}

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 a2s.  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";
}

From source file:v800_trainer.JCicloTronic.java

private void jMenuOpenallActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuOpenallActionPerformed
    // Add your handling code here:

    int i;/*from  w w w  . ja  v a2 s  .  com*/
    StringBuffer Buffer = new StringBuffer();
    String[] liste = new String[1];
    byte Data[] = new byte[81930];
    File path = new File(Properties.getProperty("data.dir"));
    File Datei;

    FileFilter directoryFilter = new FileFilter() {
        public boolean accept(File file) {
            return file.isDirectory();
        }

        public String getDescription() {
            return "";
        };
    };

    chooser.setCurrentDirectory(
            new java.io.File(Properties.getProperty("import.dir", Properties.getProperty("data.dir"))));
    chooser.setDialogType(JFileChooser.OPEN_DIALOG);
    ExampleFileFilter filtera = new ExampleFileFilter();
    ExampleFileFilter filterb = new ExampleFileFilter();
    ExampleFileFilter filterc = new ExampleFileFilter();
    ExampleFileFilter filterd = new ExampleFileFilter();
    ExampleFileFilter filtere = new ExampleFileFilter();

    filtera.addExtension("dat");
    filtera.setDescription("HAC Rohdaten");
    filterb.addExtension("tur");
    filterb.setDescription("Hactronic Dateien");
    filterc.addExtension("hrm");
    filterc.setDescription("Polar Daten");
    filterd.addExtension("");
    filterd.setDescription("Polar V800 Verzeichnis");
    filtere.addExtension("csv");
    filtere.setDescription("Polar V800 CSV Flow export");

    chooser.resetChoosableFileFilters();
    chooser.addChoosableFileFilter(filtera);
    chooser.addChoosableFileFilter(filterb);
    chooser.addChoosableFileFilter(filterc);
    chooser.addChoosableFileFilter(filterd);
    chooser.addChoosableFileFilter(filtere);
    chooser.setFileFilter(filtere);

    chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);

    int returnVal = chooser.showDialog(this, null);
    if (returnVal == JFileChooser.APPROVE_OPTION) {

        if (chooser.getSelectedFile().getName().endsWith(".dat")) {
            path = new File(chooser.getCurrentDirectory().getPath());
        } else {
            path = new File(chooser.getSelectedFile().getPath());
        }

        if (chooser.getFileFilter().equals(filtera)) {
            liste = path.list(new DirFilter(".dat"));
        }
        if (chooser.getFileFilter().equals(filterb)) {
            liste = path.list(new DirFilter(".tur"));
        }
        if (chooser.getFileFilter().equals(filterc)) {
            liste = path.list(new DirFilter(".hrm"));
        }
        if (chooser.getFileFilter().equals(filtere)) {
            liste = path.list(new DirFilter(".csv"));
        }

        if (chooser.getFileFilter().equals(filterd)) {

            File[] files = path.listFiles();
            ArrayList<String> pathliste = new ArrayList();
            for (File file : files) {
                try {
                    if (file.isDirectory()) {
                        pathliste.add(file.getCanonicalPath());
                    }
                } catch (Exception e) {
                }
            }

            Thread thread = new Thread(new Runnable() {

                public void run() {
                    setCursor(new Cursor(Cursor.WAIT_CURSOR));
                    pm = new ProgressMonitor(JCicloTronic.this, "Importiere...", "", 0, 100);
                    pm.setMillisToPopup(1);

                    v800export V800_export = new v800export();
                    V800_export.export_sessions(JCicloTronic.this, pathliste);
                    pm.close();
                    ChangeModel();
                    setCursor(new Cursor(Cursor.DEFAULT_CURSOR));

                    try {

                        Thread.sleep(100);
                    } catch (Exception e) {
                        if (Thread.interrupted()) {
                            return;
                        }
                    }
                }

            });

            thread.start();

            return;

        }

        //alle auer V800 Dateien importieren
        if (liste == null) {
            JOptionPane.showMessageDialog(null, "Keine Rohdaten-Files gefunden!", "Achtung!",
                    JOptionPane.ERROR_MESSAGE);
            return;
        }
        final String[] liste_final = liste.clone();
        final File path_final = path;

        Thread thread = new Thread(new Runnable() {

            public void run() {
                File Datei;
                byte Data[] = new byte[81930];

                setCursor(new Cursor(Cursor.WAIT_CURSOR));
                pm = new ProgressMonitor(JCicloTronic.this, "Importiere...", "", 0, 100);
                pm.setMillisToPopup(1);

                for (int i = 0; i < liste_final.length; i++) {
                    pm.setProgress((int) 100.0 * i / liste_final.length);
                    pm.setNote(liste_final[i]);

                    try {
                        Eingabedatei = new java.io.FileInputStream(path_final.getPath()
                                + SystemProperties.getProperty("file.separator") + liste_final[i]);

                        try {
                            Datei = new File(path_final.getPath()
                                    + SystemProperties.getProperty("file.separator") + liste_final[i]);
                            Data = new byte[(int) Datei.length()];
                            //                        Eingabedatei.read()

                            Eingabedatei.read(Data);
                            Eingabedatei.close();
                            if (chooser.getFileFilter().equals(filtera)) {
                                ExtractTour(Data);
                            }
                            if (chooser.getFileFilter().equals(filterb)) {
                                ExtractHactronicFile(Data);
                            }
                            if (chooser.getFileFilter().equals(filterc)) {
                                ExtractPolarFile(Data);
                            }
                            if (chooser.getFileFilter().equals(filtere)) {
                                ExtractCSV(Data);
                            }

                        } catch (IOException e) {
                            JOptionPane.showMessageDialog(null, "IO-Fehler bei Datenlesen", "Achtung!",
                                    JOptionPane.ERROR_MESSAGE);
                        }

                    } catch (FileNotFoundException e) {
                        JOptionPane.showMessageDialog(null,
                                "IO-Fehler bei " + path_final.getPath()
                                        + SystemProperties.getProperty("file.separator") + liste_final[i],
                                "Achtung!", JOptionPane.ERROR_MESSAGE);

                    }

                }
                pm.close();
                JOptionPane.showMessageDialog(null, "Daten  Ende", "Achtung!", JOptionPane.ERROR_MESSAGE);

                Properties.setProperty("import.dir", chooser.getCurrentDirectory().getPath());

                ChangeModel();
                setCursor(new Cursor(Cursor.DEFAULT_CURSOR));

                try {

                    Thread.sleep(100);
                } catch (Exception e) {
                    if (Thread.interrupted()) {
                        return;
                    }
                }
            }

        });

        thread.start();

    }
}

From source file:v800_trainer.JCicloTronic.java

private void jMenu_V800_LadenMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jMenu_V800_LadenMouseClicked

    V800_Download_Training V800_read = new V800_Download_Training();
    if (!V800_read.start(this))
        return;//  w w  w . j a va 2s .  co m
    setCursor(new Cursor(Cursor.WAIT_CURSOR));
    ArrayList<String> sessions = V800_read.get_all_sessions();
    ArrayList<String> NewData = new ArrayList();

    for (int i = 0; i < sessions.size(); i++) {

        String Name = sessions.get(i).replace("/", "");
        Name = Properties.getProperty("data.dir", Properties.getProperty("working.dir"))
                + SystemProperties.getProperty("file.separator") + Name.substring(0, Name.length() - 2)
                + "_Tour.cfg";

        File file = new File(Name);

        if ((file.exists() != true || Integer.parseInt(Properties.getProperty("Daten ueberschreiben")) == 1)) {
            NewData.add(sessions.get(i));
        }

    }

    Thread thread = new Thread(new Runnable() {

        public void run() {
            setCursor(new Cursor(Cursor.WAIT_CURSOR));
            pm = new ProgressMonitor(JCicloTronic.this, "Download...", "", 0, 100);
            pm.setMillisToPopup(0);
            pm.setMillisToDecideToPopup(0);

            ArrayList<String> PathList = V800_read.get_sessions(NewData);

            V800_read.stop();
            //    V800_read = null;

            pm.close();

            v800export V800_export = new v800export();

            pm = new ProgressMonitor(JCicloTronic.this, "Importiere...", "", 0, 100);
            pm.setMillisToPopup(0);
            pm.setMillisToDecideToPopup(0);

            V800_export.export_sessions(JCicloTronic.this, PathList);

            pm.close();
            ChangeModel();

            try {

                Thread.sleep(100);
            } catch (Exception e) {
                if (Thread.interrupted()) {
                    return;
                }
            }
        }

    });

    thread.start();

    ChangeModel();
    setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
}

From source file:com.monead.semantic.workbench.SemanticWorkbench.java

/**
 * Add the classes to the tree view/*from   w ww .  j a v  a 2s  . co m*/
 * 
 * @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.monead.semantic.workbench.SemanticWorkbench.java

/**
 * Load the provided file as an ontology replacing any assertions currently
 * in the assertions text area./*from   ww w  . j a  va  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:oct.analysis.application.dat.OCTAnalysisManager.java

/**
 * This method will take care of interacting with the user in determining
 * where the fovea is within the OCT. It first lets the user inspect the
 * automatically identified locations where the fovea may be and then choose
 * the selection that is at the fovea. If none of the automated findings are
 * at the fovea the user has the option to manual specify it's location.
 * Finally, the chosen X coordinate (within the OCT) of the fovea is set in
 * the manager and can be obtained via the getFoveaCenterXPosition getter.
 *
 * @param fullAutoMode find the fovea automatically without user input when
 * true, otherwise find the fovea in semi-automatic mode involving user
 * interaction/*  w w  w  .  j a v  a 2s  .  co  m*/
 */
public void findCenterOfFovea(boolean fullAutoMode) throws InterruptedException, ExecutionException {
    //disable clicking other components while processing by enabling glass pane
    JFrame topFrame = (JFrame) SwingUtilities.getWindowAncestor(imgPanel);
    Component glassPane = topFrame.getGlassPane();
    glassPane.setVisible(true);

    //monitor progress of finding the fovea
    ProgressMonitor pm = new ProgressMonitor(imgPanel, "Analyzing OCT for fovea...", "", 0, 100);
    pm.setMillisToDecideToPopup(0);
    pm.setMillisToPopup(100);
    pm.setProgress(0);
    FoveaFindingTask fvtask = new FoveaFindingTask(!fullAutoMode, glassPane);
    fvtask.addPropertyChangeListener((PropertyChangeEvent evt) -> {
        if ("progress".equals(evt.getPropertyName())) {
            int progress1 = (Integer) evt.getNewValue();
            pm.setProgress(progress1);
        }
    });
    fvtask.execute();
}

From source file:org.archiviststoolkit.mydomain.DomainAccessObjectImpl.java

/**
 * Add a group of instances./*  ww  w.  j av a  2 s .  c  o m*/
 *
 * @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.
 * /*ww w  .ja v a  2s.c o m*/
 * @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./*  w w  w  .  j a  v a2  s  .c  o m*/
 * 
 * @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();
}