Example usage for javax.swing SwingWorker SwingWorker

List of usage examples for javax.swing SwingWorker SwingWorker

Introduction

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

Prototype

public SwingWorker() 

Source Link

Document

Constructs this SwingWorker .

Usage

From source file:edu.ku.brc.specify.datamodel.busrules.CollectionBusRules.java

/**
 * //from   w ww . j av  a  2  s  . com
 */
private void addNewCollection() {
    if (!DivisionBusRules.checkForParentSave(formViewObj, Discipline.getClassTableId())) {
        return;
    }

    UIRegistry.loadAndPushResourceBundle("specifydbsetupwiz");

    UIRegistry.writeSimpleGlassPaneMsg("Building Collection...", 20); // I18N
    isOKToCont = true;
    final AppContextMgr acm = AppContextMgr.getInstance();

    final SpecifyDBSetupWizard wizardPanel = new SpecifyDBSetupWizard(
            SpecifyDBSetupWizard.WizardType.Collection, null);

    String msg = UIRegistry.getResourceString("CREATECOLL");
    final CustomDialog dlg = new CustomDialog((Frame) UIRegistry.getMostRecentWindow(), "", true,
            CustomDialog.NONE_BTN, wizardPanel);
    dlg.setCustomTitleBar(msg);
    wizardPanel.setListener(new SpecifyDBSetupWizard.WizardListener() {
        @Override
        public void cancelled() {
            isOKToCont = false;
            dlg.setVisible(false);
        }

        @Override
        public void finished() {
            dlg.setVisible(false);
        }

        @Override
        public void hide() {
            dlg.setVisible(false);
        }

        @Override
        public void panelChanged(String title) {
            dlg.setTitle(title);
        }

        @Override
        public void helpContextChanged(String helpTarget) {

        }
    });
    dlg.createUI();
    dlg.pack();
    UIHelper.centerAndShow(dlg);

    UIRegistry.popResourceBundle();

    if (!isOKToCont) {
        UIRegistry.clearSimpleGlassPaneMsg();
        return;
    }

    wizardPanel.processDataForNonBuild();

    final BuildSampleDatabase bldSampleDB = new BuildSampleDatabase();
    final ProgressFrame progressFrame = bldSampleDB.createProgressFrame(msg); // I18N
    progressFrame.turnOffOverAll();

    progressFrame.setProcess(0, 4);
    progressFrame.setProcessPercent(true);
    progressFrame.getCloseBtn().setVisible(false);
    progressFrame.setAlwaysOnTop(true);
    progressFrame.adjustProgressFrame();

    UIHelper.centerAndShow(progressFrame);

    SwingWorker<Integer, Integer> bldWorker = new SwingWorker<Integer, Integer>() {
        Collection newCollection = null;

        /* (non-Javadoc)
         * @see javax.swing.SwingWorker#doInBackground()
         */
        @Override
        protected Integer doInBackground() throws Exception {
            Session session = null;
            try {
                session = HibernateUtil.getNewSession();
                DataProviderSessionIFace hSession = new HibernateDataProviderSession(session);

                Discipline discipline = (Discipline) formViewObj.getMVParent().getMultiViewParent().getData();
                //Institution    institution      = acm.getClassObject(Institution.class);
                SpecifyUser specifyAdminUser = acm.getClassObject(SpecifyUser.class);
                Agent userAgent = (Agent) hSession
                        .getData("FROM Agent WHERE id = " + Agent.getUserAgent().getId());
                Properties props = wizardPanel.getProps();
                DisciplineType disciplineType = DisciplineType.getByName(discipline.getType());

                discipline = (Discipline) session.merge(discipline);
                specifyAdminUser = (SpecifyUser) hSession
                        .getData("FROM SpecifyUser WHERE id = " + specifyAdminUser.getId());

                bldSampleDB.setSession(session);

                AutoNumberingScheme catNumScheme = bldSampleDB.createAutoNumScheme(props, "catnumfmt",
                        "Catalog Numbering Scheme", CollectionObject.getClassTableId());
                /*AutoNumberingScheme accNumScheme = null;
                        
                if (institution.getIsAccessionsGlobal())
                {
                List<?> list = hSession.getDataList("FROM AutoNumberingScheme WHERE tableNumber = "+Accession.getClassTableId());
                if (list != null && list.size() == 1)
                {
                    accNumScheme = (AutoNumberingScheme)list.get(0);
                }
                } else
                {
                accNumScheme = bldSampleDB.createAutoNumScheme(props, "accnumfmt", "Accession Numbering Scheme", Accession.getClassTableId()); // I18N
                }*/

                newCollection = bldSampleDB.createEmptyCollection(discipline,
                        props.getProperty("collPrefix").toString(), props.getProperty("collName").toString(),
                        userAgent, specifyAdminUser, catNumScheme, disciplineType.isEmbeddedCollecingEvent());

                acm.setClassObject(SpecifyUser.class, specifyAdminUser);
                Agent.setUserAgent(userAgent);

            } catch (Exception ex) {
                ex.printStackTrace();

            } finally {
                if (session != null) {
                    session.close();
                }
            }

            bldSampleDB.setDataType(null);

            return null;
        }

        @Override
        protected void done() {
            super.done();

            progressFrame.setVisible(false);
            progressFrame.dispose();

            if (newCollection != null) {
                List<?> dataItems = null;

                FormViewObj dispFVO = formViewObj.getMVParent().getMultiViewParent()
                        .getCurrentViewAsFormViewObj();
                Discipline discipline = (Discipline) dispFVO.getDataObj();
                DataProviderSessionIFace pSession = null;
                try {
                    pSession = DataProviderFactory.getInstance().createSession();

                    discipline = (Discipline) pSession
                            .getData("FROM Discipline WHERE id = " + discipline.getId());
                    //formViewObj.getMVParent().getMultiViewParent().setData(division);
                    acm.setClassObject(Discipline.class, discipline);

                    dataItems = pSession.getDataList("FROM Discipline");
                    if (dataItems.get(0) instanceof Object[]) {
                        Vector<Object> dataList = new Vector<Object>();
                        for (Object row : dataItems) {
                            Object[] cols = (Object[]) row;
                            dataList.add(cols[0]);
                        }
                        dataItems = dataList;
                    }

                } catch (Exception ex) {
                    System.err.println(ex);
                    ex.printStackTrace();

                } finally {
                    if (pSession != null) {
                        pSession.close();
                    }
                }

                int curInx = dispFVO.getRsController().getCurrentIndex();
                dispFVO.setDataObj(dataItems);
                dispFVO.getRsController().setIndex(curInx);

                //UIRegistry.clearSimpleGlassPaneMsg();

                UIRegistry.showLocalizedMsg("Specify.ABT_EXIT");
                CommandDispatcher.dispatch(new CommandAction(BaseTask.APP_CMD_TYPE, BaseTask.APP_REQ_EXIT));

            } else {
                // error creating
            }
            UIRegistry.clearSimpleGlassPaneMsg();
        }
    };

    bldWorker.execute();

}

From source file:edu.ku.brc.specify.web.HttpLargeFileTransfer.java

/**
 * @param fileName// w  ww .ja va  2 s  .  c om
 * @param urlStr
 * @param isSiteFile
 * @param propChgListener
 */
public void transferFile(final String fileName, final String urlStr, final boolean isSiteFile,
        final PropertyChangeListener propChgListener) {

    final String prgName = HttpLargeFileTransfer.class.toString();

    final File file = new File(fileName);
    if (file.exists()) {
        final long fileSize = file.length();
        if (fileSize > 0) {
            SwingWorker<Integer, Integer> backupWorker = new SwingWorker<Integer, Integer>() {
                protected String errorMsg = null;
                protected FileInputStream fis = null;
                protected OutputStream fos = null;
                protected int nChunks = 0;

                /* (non-Javadoc)
                 * @see javax.swing.SwingWorker#doInBackground()
                 */
                @Override
                protected Integer doInBackground() throws Exception {
                    try {
                        Thread.sleep(100);
                        fis = new FileInputStream(file);

                        nChunks = (int) (fileSize / MAX_CHUNK_SIZE);
                        if (fileSize % MAX_CHUNK_SIZE > 0) {
                            nChunks++;
                        }

                        byte[] buf = new byte[BUFFER_SIZE];
                        long bytesRemaining = fileSize;

                        String clientID = String.valueOf((long) (Long.MIN_VALUE * Math.random()));

                        URL url = new URL(urlStr);

                        UIRegistry.getStatusBar().setProgressRange(prgName, 0, nChunks);

                        for (int i = 0; i < nChunks; i++) {
                            firePropertyChange(prgName, i - 1, i == nChunks - 1 ? Integer.MAX_VALUE : i);
                            if (i == nChunks - 1) {
                                Thread.sleep(500);
                                int x = 0;
                                x++;
                            }

                            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                            conn.setRequestMethod("PUT");
                            conn.setDoOutput(true);
                            conn.setDoInput(true);
                            conn.setUseCaches(false);

                            int chunkSize = (int) ((bytesRemaining > MAX_CHUNK_SIZE) ? MAX_CHUNK_SIZE
                                    : bytesRemaining);
                            bytesRemaining -= chunkSize;

                            conn.setRequestProperty("Content-Type", "application/octet-stream");
                            conn.setRequestProperty("Content-Length", String.valueOf(chunkSize));

                            conn.setRequestProperty(CLIENT_ID_HEADER, clientID);
                            conn.setRequestProperty(FILE_NAME_HEADER, fileName);
                            conn.setRequestProperty(FILE_CHUNK_COUNT_HEADER, String.valueOf(nChunks));
                            conn.setRequestProperty(FILE_CHUNK_HEADER, String.valueOf(i));
                            conn.setRequestProperty(SERVICE_NUMBER, "10");
                            conn.setRequestProperty(IS_SITE_FILE, Boolean.toString(isSiteFile));

                            fos = conn.getOutputStream();

                            //UIRegistry.getStatusBar().setProgressRange(prgName, 0, (int)((double)chunkSize / BUFFER_SIZE));
                            int cnt = 0;
                            int bytesRead = 0;
                            while (bytesRead < chunkSize) {
                                int read = fis.read(buf);
                                if (read == -1) {
                                    break;

                                } else if (read > 0) {
                                    bytesRead += read;
                                    fos.write(buf, 0, read);
                                }
                                cnt++;
                                //firePropertyChange(prgName, cnt-1, cnt);
                            }
                            fos.close();

                            if (conn.getResponseCode() != HttpServletResponse.SC_OK) {
                                System.err.println(
                                        conn.getResponseMessage() + " " + conn.getResponseCode() + " ");
                                BufferedReader in = new BufferedReader(
                                        new InputStreamReader(conn.getErrorStream()));
                                String line = null;
                                StringBuilder sb = new StringBuilder();
                                while ((line = in.readLine()) != null) {
                                    sb.append(line);
                                    sb.append("\n");
                                }
                                System.out.println(sb.toString());
                                in.close();

                            } else {
                                System.err.println("OK");
                            }
                            //UIRegistry.getStatusBar().setProgressRange(prgName, 0, nChunks);
                            firePropertyChange(prgName, i - 1, i == nChunks - 1 ? Integer.MAX_VALUE : i);
                        }

                    } catch (IOException ex) {
                        errorMsg = ex.toString();
                    }

                    //firePropertyChange(prgName, 0, 100);
                    return null;
                }

                @Override
                protected void done() {
                    super.done();

                    UIRegistry.getStatusBar().setProgressDone(prgName);

                    UIRegistry.clearSimpleGlassPaneMsg();

                    if (StringUtils.isNotEmpty(errorMsg)) {
                        UIRegistry.showError(errorMsg);
                    }

                    if (propChgListener != null) {
                        propChgListener.propertyChange(
                                new PropertyChangeEvent(HttpLargeFileTransfer.this, "Done", 0, 1));
                    }
                }
            };

            final JStatusBar statusBar = UIRegistry.getStatusBar();
            statusBar.setIndeterminate(HttpLargeFileTransfer.class.toString(), true);

            UIRegistry.writeSimpleGlassPaneMsg(getLocalizedMessage("Transmitting..."), 24);

            backupWorker.addPropertyChangeListener(new PropertyChangeListener() {
                public void propertyChange(final PropertyChangeEvent evt) {
                    System.out.println(evt.getPropertyName() + "  " + evt.getNewValue());
                    if (prgName.equals(evt.getPropertyName())) {
                        Integer value = (Integer) evt.getNewValue();
                        if (value == Integer.MAX_VALUE) {
                            statusBar.setIndeterminate(prgName, true);
                            UIRegistry.writeSimpleGlassPaneMsg(
                                    getLocalizedMessage("Transfering data into the database."), 24);

                        } else {
                            statusBar.setValue(prgName, value);
                        }
                    }
                }
            });
            backupWorker.execute();

        } else {
            // file doesn't exist
        }
    } else {
        // file doesn't exist
    }
}

From source file:com.mirth.connect.client.ui.SettingsPanelResources.java

@Override
public boolean doSave() {
    resetInvalidProperties();//from   ww w.j  a v  a2  s . com
    final String errors = checkProperties().trim();
    if (StringUtils.isNotEmpty(errors)) {
        getFrame().alertError(getFrame(), "Error validating resource settings:\n\n" + errors);
        return false;
    }

    if (!getFrame().alertOption(getFrame(),
            "<html>Libraries associated with any changed resources will be reloaded.<br/>Any channels / connectors using those libraries will be affected.<br/>Also, a maximum of 1000 files may be loaded into a directory<br/>resource, with additional files being skipped.<br/>Are you sure you wish to continue?</html>")) {
        return false;
    }

    updateResource(resourceTable.getSelectedRow());

    final String workingId = getFrame().startWorking("Saving resources...");
    final List<ResourceProperties> resources = new ArrayList<ResourceProperties>();

    for (int row = 0; row < resourceTable.getRowCount(); row++) {
        resources.add((ResourceProperties) resourceTable.getModel().getValueAt(row, PROPERTIES_COLUMN));
    }

    SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() {

        @Override
        public Void doInBackground() throws ClientException {
            getFrame().mirthClient.setResources(resources);
            return null;
        }

        @Override
        public void done() {
            try {
                get();
                setSaveEnabled(false);
            } catch (Throwable t) {
                if (t instanceof ExecutionException) {
                    t = t.getCause();
                }
                getFrame().alertThrowable(getFrame(), t, "Error saving resources: " + t.toString());
            } finally {
                getFrame().stopWorking(workingId);
            }
        }
    };

    worker.execute();

    return true;
}

From source file:com.opendoorlogistics.studio.AppFrame.java

public AppFrame() {

    // create frame with desktop pane
    Container con = getContentPane();
    con.setLayout(new BorderLayout());

    SwingWorker<BufferedImage, BufferedImage> createBackground = new SwingWorker<BufferedImage, BufferedImage>() {

        @Override/* w  w w .j  a va  2 s. com*/
        protected BufferedImage doInBackground() throws Exception {
            // background = new AppBackground().create();
            AppBackground ab = new AppBackground();

            ab.start();
            long lastTime = System.currentTimeMillis();
            int lastRendered = 0;
            while (ab.getNbConsecutiveFails() < 100) {
                ab.doStep();
                long current = System.currentTimeMillis();
                if (current - lastTime > 100 && lastRendered != ab.getNbRendered()) {
                    background = ImageUtils.deepCopy(ab.getImage());
                    publish(background);
                    lastTime = current;
                    lastRendered = ab.getNbRendered();
                }
            }

            ab.finish();

            background = ab.getImage();
            return background;
        }

        @Override
        protected void process(List<BufferedImage> chunks) {
            repaint();
        }

        @Override
        public void done() {
            AppFrame.this.repaint();
        }
    };
    createBackground.execute();

    initWindowPosition();

    registerAppFrameDependentComponents();

    // then create other objects which might use the components
    tables = new DatastoreTablesPanel(this);

    // create scripts panel after registering components
    scriptManager = new ScriptUIManagerImpl(this);
    scriptsPanel = new ScriptsPanel(getApi(), PreferencesManager.getSingleton().getScriptsDirectory(),
            scriptManager);

    // set my icon
    setIconImage(Icons.loadFromStandardPath("App logo.png").getImage());

    // create actions
    fileActions = initFileActions();
    editActions = initEditActions();

    // create left-hand panel with scripts and tables
    splitterTablesScripts = new JSplitPane(JSplitPane.VERTICAL_SPLIT, tables, scriptsPanel);
    splitterTablesScripts.setPreferredSize(new Dimension(200, splitterTablesScripts.getPreferredSize().height));
    splitterTablesScripts.setResizeWeight(0.5);

    // split center part into tables/scripts browser on the left and desktop
    // pane on the right
    desktopScrollPane = new DesktopScrollPane(desktopPane);
    splitterLeftPanelMain = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, splitterTablesScripts,
            desktopScrollPane);
    con.add(splitterLeftPanelMain, BorderLayout.CENTER);

    // add toolbar
    initToolbar(con);

    initMenus();

    // control close operation to stop changed being lost
    setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
    addWindowListener(new WindowAdapter() {
        @Override
        public void windowClosing(WindowEvent e) {
            if (canCloseDatastore()) {
                dispose();
                System.exit(0);
            }
        }
    });

    setVisible(true);
    updateAppearance();

}

From source file:com.enderville.enderinstaller.ui.Installer.java

private void buildInstallingPane() {

    getNextButton().setEnabled(false);//from   w ww  . j a  v a2  s  .c  o m
    getCancelButton().setEnabled(false);
    getMainPane().removeAll();
    getMainPane().setLayout(new MigLayout(new LC().fill()));
    final JTextArea text = new JTextArea();
    text.setEditable(false);
    getMainPane().add(new JScrollPane(text), new CC().grow().spanY().wrap());
    getMainPane().validate();
    getMainPane().repaint();
    SwingWorker<Object, String> worker = new SwingWorker<Object, String>() {

        @Override
        protected Object doInBackground() throws Exception {
            try {
                List<String> mods = new ArrayList<String>();
                CheckBoxTreeSelectionModel select = getModTree().getCheckBoxTreeSelectionModel();
                TreePath[] paths = select.getSelectionPaths();
                if (paths != null && paths.length > 0) {
                    for (TreePath path : paths) {
                        DefaultMutableTreeNode node = ((DefaultMutableTreeNode) path.getLastPathComponent());
                        String mod = (String) node.getUserObject();
                        if (mod == null) {
                            for (int i = 0; i < node.getChildCount(); i++) {
                                DefaultMutableTreeNode child = (DefaultMutableTreeNode) node.getChildAt(i);
                                mods.add((String) child.getUserObject());
                            }
                        } else {
                            mods.add(mod);
                        }
                    }
                }
                InstallScript.guiInstall(mods, text, getProgressBar());
            } catch (Exception e) {
                LOGGER.error("Error while trying to install mods", e);
                JOptionPane.showMessageDialog(Installer.this,
                        "Unexpected error while installing mods:\n" + e.getMessage(), "Error",
                        JOptionPane.ERROR_MESSAGE);
                setVisible(false);
                dispose();
            }
            return null;
        }

        @Override
        public void done() {
            getNextButton().removeActionListener(Installer.this);
            getNextButton().setText("Done");
            getNextButton().addActionListener(new ActionListener() {

                @Override
                public void actionPerformed(ActionEvent e) {
                    setVisible(false);
                    dispose();
                }
            });
            getNextButton().setEnabled(true);
        }
    };

    worker.execute();
}

From source file:sk.uniza.fri.pds.spotreba.energie.gui.MainGui.java

private void showSpendingStatisticsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_showSpendingStatisticsActionPerformed
    final SpendingStatisticsParameters params = new SpendingStatisticsParameters();
    int option = showUniversalInputDialog(params, "Vvoj spotreby");
    if (option == JOptionPane.OK_OPTION) {
        new SwingWorker<List, RuntimeException>() {
            @Override//from   ww w. j  a v  a  2 s.c om
            protected List doInBackground() throws Exception {
                try {
                    return SeHistoriaService.getInstance().getSpendingStatistics(params);
                } catch (RuntimeException e) {
                    publish(e);
                    return null;
                }
            }

            @Override
            protected void done() {
                try {
                    List<KrokSpotreby> spendingStatistics = get();
                    if (spendingStatistics != null) {
                        final TimeSeries series = new TimeSeries("");
                        final String title = "Vvoj spotreby";
                        for (KrokSpotreby krok : spendingStatistics) {
                            series.add(new Month(krok.getDatumOd()), krok.getSpotreba());
                        }
                        final IntervalXYDataset dataset = (IntervalXYDataset) new TimeSeriesCollection(series);
                        JFreeChart chart = ChartFactory.createXYBarChart(title, // title
                                "", // x-axis label
                                true, // date axis?
                                "", // y-axis label
                                dataset, // data
                                PlotOrientation.VERTICAL, // orientation
                                false, // create legend?
                                true, // generate tooltips?
                                false // generate URLs?
                        );

                        // Set date axis style
                        DateAxis axis = (DateAxis) ((XYPlot) chart.getPlot()).getDomainAxis();
                        axis.setDateFormatOverride(new SimpleDateFormat("yyyy"));
                        DateFormat formatter = new SimpleDateFormat("yyyy");
                        DateTickUnit unit = new DateTickUnit(DateTickUnitType.YEAR, 1, formatter);
                        axis.setTickUnit(unit);
                        JOptionPane.showMessageDialog(null, new ChartPanel(chart));
                    }
                } catch (InterruptedException | ExecutionException ex) {
                    Logger.getLogger(MainGui.class.getName()).log(Level.SEVERE, null, ex);
                }
            }

            @Override
            protected void process(List<RuntimeException> chunks) {
                if (chunks.size() > 0) {
                    showException("Chyba", chunks.get(0));
                }
            }

        }.execute();
    }
}

From source file:dbseer.gui.actions.ExplainChartAction.java

private void explain() {
    try {//from  w  w  w  .jav a2s  .  c om
        if (panel.getAnomalyRegion().isEmpty()) {
            JOptionPane.showMessageDialog(null, "Please select an anomaly region.", "Warning",
                    JOptionPane.WARNING_MESSAGE);
            return;
        }

        //         console.setText("Analyzing data for explanation... ");
        DBSeerGUI.explainStatus.setText("Analyzing data for explanation...");

        final StatisticalPackageRunner runner = DBSeerGUI.runner;
        final DBSeerExplainChartPanel explainPanel = this.panel;
        final String causalModelPath = this.causalModelPath;
        final JTextArea console = this.console;
        final ExplainChartAction action = this;

        SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() {
            String normalIdx = "";
            String anomalyIdx = "";

            HashSet<Integer> normalRegion = new HashSet<Integer>();
            HashSet<Integer> anomalyRegion = new HashSet<Integer>();

            @Override
            protected Void doInBackground() throws Exception {
                for (Double d : explainPanel.getNormalRegion()) {
                    normalRegion.add(d.intValue());
                }
                for (Double d : explainPanel.getAnomalyRegion()) {
                    anomalyRegion.add(d.intValue());
                }

                for (Integer i : normalRegion) {
                    normalIdx = normalIdx + i.toString() + " ";
                }
                for (Integer i : anomalyRegion) {
                    anomalyIdx = anomalyIdx + i.toString() + " ";
                }

                runner.eval("normal_idx = [" + normalIdx + "];");
                runner.eval("anomaly_idx = [" + anomalyIdx + "];");
                runner.eval(
                        "[predicates explanations] = explainPerformance(plotter.mv, anomaly_idx, normal_idx, '"
                                + causalModelPath + "', 500, 0.2, 10);");

                return null;
            }

            @Override
            protected void done() {
                try {
                    DBSeerGUI.explainStatus.setText("");
                    printExplanations();
                } catch (Exception e) {
                    JOptionPane.showMessageDialog(null, e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
                    e.printStackTrace();
                }
            }
        };
        worker.execute();
    } catch (Exception e) {
        DBSeerExceptionHandler.handleException(e);
    }
}

From source file:edu.ku.brc.af.core.db.MySQLBackupService.java

/**
 * Does the backup on a SwingWorker Thread.
 * @param isMonthly whether it is a monthly backup
 * @param doSendAppExit requests sending an application exit command when done
 * @return true if the prefs are set up and there were no errors before the SwingWorker thread was started
 *///from w ww.j  a  v  a2s  .c  o m
private boolean doBackUp(final boolean isMonthly, final boolean doSendAppExit,
        final PropertyChangeListener propChgListener) {
    AppPreferences remotePrefs = AppPreferences.getLocalPrefs();

    final String mysqldumpLoc = remotePrefs.get(MYSQLDUMP_LOC, getDefaultMySQLDumpLoc());
    final String backupLoc = remotePrefs.get(MYSQLBCK_LOC, getDefaultBackupLoc());

    if (!(new File(mysqldumpLoc)).exists()) {
        UIRegistry.showLocalizedError("MySQLBackupService.MYSQL_NO_DUMP", mysqldumpLoc);
        if (propChgListener != null) {
            propChgListener.propertyChange(new PropertyChangeEvent(MySQLBackupService.this, ERROR, 0, 1));
        }
        return false;
    }

    File backupDir = new File(backupLoc);
    if (!backupDir.exists()) {
        if (!backupDir.mkdir()) {
            UIRegistry.showLocalizedError("MySQLBackupService.MYSQL_NO_BK_DIR", backupDir.getAbsoluteFile());
            if (propChgListener != null) {
                propChgListener.propertyChange(new PropertyChangeEvent(MySQLBackupService.this, ERROR, 0, 1));
            }
            return false;
        }
    }

    errorMsg = null;

    final String databaseName = DBConnection.getInstance().getDatabaseName();

    getNumberofTables();

    SwingWorker<Integer, Integer> backupWorker = new SwingWorker<Integer, Integer>() {
        protected String fullPath = null;

        /* (non-Javadoc)
         * @see javax.swing.SwingWorker#doInBackground()
         */
        @Override
        protected Integer doInBackground() throws Exception {
            FileOutputStream backupOut = null;
            try {
                Thread.sleep(100);

                // Create output file
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy_MM_dd_kk_mm_ss");
                String fileName = sdf.format(Calendar.getInstance().getTime()) + (isMonthly ? "_monthly" : "")
                        + ".sql";

                fullPath = backupLoc + File.separator + fileName;

                File file = new File(fullPath);
                backupOut = new FileOutputStream(file);

                writeStats(getCollectionStats(getTableNames()), getStatsName(fullPath));

                String userName = DBConnection.getInstance().getUserName();
                String password = DBConnection.getInstance().getPassword();

                if (StringUtils.isEmpty(userName) || StringUtils.isEmpty(password)) {
                    Pair<String, String> up = UserAndMasterPasswordMgr.getInstance().getUserNamePasswordForDB();
                    if (up != null && up.first != null && up.second != null) {
                        userName = up.first;
                        password = up.second;
                    }
                }

                String port = DatabaseDriverInfo.getDriver(DBConnection.getInstance().getDriverName())
                        .getPort();
                String server = DBConnection.getInstance().getServerName();

                Vector<String> args = new Vector<String>();
                args.add(mysqldumpLoc);
                args.add("--user=" + userName);
                args.add("--password=" + password);
                args.add("--host=" + server);
                if (port != null) {
                    args.add("--port=" + port);
                }
                args.add(databaseName);
                Process process = Runtime.getRuntime().exec(args.toArray(new String[0]));

                InputStream input = process.getInputStream();
                byte[] bytes = new byte[8192 * 2];

                double oneMeg = (1024.0 * 1024.0);
                long dspMegs = 0;
                long totalBytes = 0;

                do {
                    int numBytes = input.read(bytes, 0, bytes.length);
                    totalBytes += numBytes;
                    if (numBytes > 0) {
                        long megs = (long) (totalBytes / oneMeg);
                        if (megs != dspMegs) {
                            dspMegs = megs;
                            long megsWithTenths = (long) ((totalBytes * 10.0) / oneMeg);
                            firePropertyChange(MEGS, 0, megsWithTenths);
                        }

                        backupOut.write(bytes, 0, numBytes);

                    } else {
                        break;
                    }

                } while (true);

                StringBuilder sb = new StringBuilder();

                String line;
                BufferedReader errIn = new BufferedReader(new InputStreamReader(process.getErrorStream()));
                while ((line = errIn.readLine()) != null) {
                    //System.err.println(line);
                    if (line.startsWith("ERR") || StringUtils.contains(line, "Got error")) {
                        sb.append(line);
                        sb.append("\n");

                        if (StringUtils.contains(line, "1044") && StringUtils.contains(line, "LOCK TABLES")) {
                            sb.append("\n");
                            sb.append(UIRegistry.getResourceString("MySQLBackupService.LCK_TBL_ERR"));
                            sb.append("\n");
                        }
                    }
                }
                errorMsg = sb.toString();

            } catch (Exception ex) {
                ex.printStackTrace();
                errorMsg = ex.toString();
                UIRegistry.showLocalizedError("MySQLBackupService.EXCP_BK");

            } finally {
                if (backupOut != null) {
                    try {
                        backupOut.flush();
                        backupOut.close();

                    } catch (IOException ex) {
                        ex.printStackTrace();
                        errorMsg = ex.toString();
                    }
                }
            }

            return null;
        }

        @Override
        protected void done() {
            super.done();

            UIRegistry.getStatusBar().setProgressDone(STATUSBAR_NAME);

            UIRegistry.clearSimpleGlassPaneMsg();

            if (StringUtils.isNotEmpty(errorMsg)) {
                UIRegistry.showError(errorMsg);
            }

            if (doSendAppExit) {
                CommandDispatcher.dispatch(new CommandAction("App", "AppReqExit"));
            }

            if (propChgListener != null) {
                propChgListener
                        .propertyChange(new PropertyChangeEvent(MySQLBackupService.this, DONE, null, fullPath));
            }
        }
    };

    final JStatusBar statusBar = UIRegistry.getStatusBar();
    statusBar.setIndeterminate(STATUSBAR_NAME, true);

    UIRegistry.writeSimpleGlassPaneMsg(getLocalizedMessage("MySQLBackupService.BACKINGUP", databaseName), 24);

    backupWorker.addPropertyChangeListener(new PropertyChangeListener() {
        public void propertyChange(final PropertyChangeEvent evt) {
            if (MEGS.equals(evt.getPropertyName())) {
                long value = (Long) evt.getNewValue();
                double val = value / 10.0;
                statusBar.setText(UIRegistry.getLocalizedMessage("MySQLBackupService.BACKUP_MEGS", val));
            }
        }
    });
    backupWorker.execute();

    return true;
}

From source file:edu.ku.brc.specify.tools.schemalocale.SchemaToolsDlg.java

/**
 * /*from w ww .j a  v a 2s . c  o m*/
 */
private void importSchema(final boolean doLocalization) {
    FileDialog fileDlg = new FileDialog((Dialog) null);
    fileDlg.setTitle(getResourceString(doLocalization ? SL_CHS_LOC : SL_CHS_IMP));
    UIHelper.centerAndShow(fileDlg);

    String fileName = fileDlg.getFile();
    if (StringUtils.isNotEmpty(fileName)) {
        String title = getResourceString(doLocalization ? "SL_L10N_SCHEMA" : "SL_IMPORT_SCHEMA");

        final File file = new File(fileDlg.getDirectory() + File.separator + fileName);
        final SimpleGlassPane glassPane = new SimpleGlassPane(title, 18);
        glassPane.setBarHeight(12);
        glassPane.setFillColor(new Color(0, 0, 0, 85));

        setGlassPane(glassPane);
        glassPane.setVisible(true);

        SwingWorker<Integer, Integer> importWorker = new SwingWorker<Integer, Integer>() {
            private boolean isOK = false;

            @Override
            protected Integer doInBackground() throws Exception {
                DataProviderSessionIFace localSession = null;
                try {
                    localSession = DataProviderFactory.getInstance().createSession();

                    localSession.beginTransaction();

                    BuildSampleDatabase bsd = new BuildSampleDatabase();

                    Discipline discipline = localSession.get(Discipline.class,
                            AppContextMgr.getInstance().getClassObject(Discipline.class).getId());

                    isOK = bsd.loadSchemaLocalization(discipline, schemaType, DBTableIdMgr.getInstance(), null, //catFmtName,
                            null, //accFmtName,
                            doLocalization ? UpdateType.eLocalize : UpdateType.eImport, // isDoingUpdate
                            file, // external file
                            glassPane, localSession);
                    if (isOK) {
                        localSession.commit();
                    } else {
                        localSession.rollback();
                    }

                } catch (Exception ex) {
                    ex.printStackTrace();
                    edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(BuildSampleDatabase.class, ex);

                } finally {
                    if (localSession != null) {
                        localSession.close();
                    }
                }

                return null;
            }

            @Override
            protected void done() {
                super.done();

                glassPane.setVisible(false);

                if (isOK) {
                    UIRegistry.showLocalizedMsg("Specify.ABT_EXIT");
                    CommandDispatcher.dispatch(new CommandAction("App", "AppReqExit"));
                }
            }
        };
        importWorker.addPropertyChangeListener(new PropertyChangeListener() {
            public void propertyChange(final PropertyChangeEvent evt) {
                if (evt.getPropertyName().equals("progress")) {
                    glassPane.setProgress((Integer) evt.getNewValue());
                }
            }
        });
        importWorker.execute();
    }
}