Example usage for javax.swing SwingWorker execute

List of usage examples for javax.swing SwingWorker execute

Introduction

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

Prototype

public final void execute() 

Source Link

Document

Schedules this SwingWorker for execution on a worker thread.

Usage

From source file:org.esa.snap.rcp.statistics.ScatterPlotPanel.java

private void compute(final Mask selectedMask) {

    final RasterDataNode raster = getRaster();

    final AttributeDescriptor dataField = scatterPlotModel.dataField;
    if (raster == null || dataField == null) {
        return;//  w w w  .ja  v  a2  s  .co  m
    }

    SwingWorker<ComputedData[], Object> swingWorker = new SwingWorker<ComputedData[], Object>() {

        @Override
        protected ComputedData[] doInBackground() throws Exception {
            SystemUtils.LOG.finest("start computing scatter plot data");

            final List<ComputedData> computedDataList = new ArrayList<>();

            final FeatureCollection<SimpleFeatureType, SimpleFeature> collection = scatterPlotModel.pointDataSource
                    .getFeatureCollection();
            final SimpleFeature[] features = collection.toArray(new SimpleFeature[collection.size()]);

            final int boxSize = scatterPlotModel.boxSize;

            final Rectangle sceneRect = new Rectangle(raster.getRasterWidth(), raster.getRasterHeight());

            final GeoCoding geoCoding = raster.getGeoCoding();
            final AffineTransform imageToModelTransform;
            imageToModelTransform = Product.findImageToModelTransform(geoCoding);
            for (SimpleFeature feature : features) {
                final Point point = (Point) feature.getDefaultGeometryProperty().getValue();
                Point2D modelPos = new Point2D.Float((float) point.getX(), (float) point.getY());
                final Point2D imagePos = imageToModelTransform.inverseTransform(modelPos, null);

                if (!sceneRect.contains(imagePos)) {
                    continue;
                }
                final float imagePosX = (float) imagePos.getX();
                final float imagePosY = (float) imagePos.getY();
                final Rectangle imageRect = sceneRect.intersection(new Rectangle(
                        ((int) imagePosX) - boxSize / 2, ((int) imagePosY) - boxSize / 2, boxSize, boxSize));
                if (imageRect.isEmpty()) {
                    continue;
                }
                final double[] rasterValues = new double[imageRect.width * imageRect.height];
                raster.readPixels(imageRect.x, imageRect.y, imageRect.width, imageRect.height, rasterValues);

                final int[] maskBuffer = new int[imageRect.width * imageRect.height];
                Arrays.fill(maskBuffer, 1);
                if (selectedMask != null) {
                    selectedMask.readPixels(imageRect.x, imageRect.y, imageRect.width, imageRect.height,
                            maskBuffer);
                }

                final int centerIndex = imageRect.width * (imageRect.height / 2) + (imageRect.width / 2);
                if (maskBuffer[centerIndex] == 0) {
                    continue;
                }

                double sum = 0;
                double sumSqr = 0;
                int n = 0;
                boolean valid = false;

                for (int y = 0; y < imageRect.height; y++) {
                    for (int x = 0; x < imageRect.width; x++) {
                        final int index = y * imageRect.height + x;
                        if (raster.isPixelValid(x + imageRect.x, y + imageRect.y) && maskBuffer[index] != 0) {
                            final double rasterValue = rasterValues[index];
                            sum += rasterValue;
                            sumSqr += rasterValue * rasterValue;
                            n++;
                            valid = true;
                        }
                    }
                }

                if (!valid) {
                    continue;
                }

                double rasterMean = sum / n;
                double rasterSigma = n > 1 ? Math.sqrt((sumSqr - (sum * sum) / n) / (n - 1)) : 0.0;

                String localName = dataField.getLocalName();
                Number attribute = (Number) feature.getAttribute(localName);

                final Collection<org.opengis.feature.Property> featureProperties = feature.getProperties();

                final float correlativeData = attribute.floatValue();
                final GeoPos geoPos = new GeoPos();
                if (geoCoding.canGetGeoPos()) {
                    final PixelPos pixelPos = new PixelPos(imagePosX, imagePosY);
                    geoCoding.getGeoPos(pixelPos, geoPos);
                } else {
                    geoPos.setInvalid();
                }
                computedDataList.add(
                        new ComputedData(imagePosX, imagePosY, (float) geoPos.getLat(), (float) geoPos.getLon(),
                                (float) rasterMean, (float) rasterSigma, correlativeData, featureProperties));
            }

            return computedDataList.toArray(new ComputedData[computedDataList.size()]);
        }

        @Override
        public void done() {
            try {
                final ValueAxis xAxis = getPlot().getDomainAxis();
                final ValueAxis yAxis = getPlot().getRangeAxis();

                xAxis.setAutoRange(false);
                yAxis.setAutoRange(false);

                scatterpointsDataset.removeAllSeries();
                acceptableDeviationDataset.removeAllSeries();
                regressionDataset.removeAllSeries();
                getPlot().removeAnnotation(r2Annotation);
                computedDatas = null;

                final ComputedData[] data = get();
                if (data.length == 0) {
                    return;
                }

                computedDatas = data;

                final XYIntervalSeries scatterValues = new XYIntervalSeries(getCorrelativeDataName());
                for (ComputedData computedData : computedDatas) {
                    final float rasterMean = computedData.rasterMean;
                    final float rasterSigma = computedData.rasterSigma;
                    final float correlativeData = computedData.correlativeData;
                    scatterValues.add(correlativeData, correlativeData, correlativeData, rasterMean,
                            rasterMean - rasterSigma, rasterMean + rasterSigma);
                }

                computingData = true;
                scatterpointsDataset.addSeries(scatterValues);

                xAxis.setAutoRange(true);
                yAxis.setAutoRange(true);

                xAxis.setAutoRange(false);
                yAxis.setAutoRange(false);

                xAutoRangeAxisRange = new Range(xAxis.getLowerBound(), xAxis.getUpperBound());
                yAutoRangeAxisRange = new Range(yAxis.getLowerBound(), yAxis.getUpperBound());

                if (xAxisRangeControl.isAutoMinMax()) {
                    xAxisRangeControl.adjustComponents(xAxis, 3);
                } else {
                    xAxisRangeControl.adjustAxis(xAxis, 3);
                }
                if (yAxisRangeControl.isAutoMinMax()) {
                    yAxisRangeControl.adjustComponents(yAxis, 3);
                } else {
                    yAxisRangeControl.adjustAxis(yAxis, 3);
                }

                computeRegressionAndAcceptableDeviationData();
                computingData = false;
            } catch (InterruptedException | CancellationException e) {
                SystemUtils.LOG.log(Level.WARNING, "Failed to compute correlative plot.", e);
                Dialogs.showMessage(CHART_TITLE,
                        "Failed to compute correlative plot.\n" + "Calculation canceled.",
                        JOptionPane.ERROR_MESSAGE, null);
            } catch (ExecutionException e) {
                SystemUtils.LOG.log(Level.WARNING, "Failed to compute correlative plot.", e);
                Dialogs.showMessage(CHART_TITLE, "Failed to compute correlative plot.\n"
                        + "An error occurred:\n" + e.getCause().getMessage(), JOptionPane.ERROR_MESSAGE, null);
            }
        }
    };
    swingWorker.execute();
}

From source file:org.esa.beam.visat.toolviews.stat.ScatterPlotPanel.java

private void compute(final Mask selectedMask) {

    final RasterDataNode raster = getRaster();

    final AttributeDescriptor dataField = scatterPlotModel.dataField;
    if (raster == null || dataField == null) {
        return;/* ww  w  . j a  va2s  .com*/
    }

    SwingWorker<ComputedData[], Object> swingWorker = new SwingWorker<ComputedData[], Object>() {

        @Override
        protected ComputedData[] doInBackground() throws Exception {
            BeamLogManager.getSystemLogger().finest("start computing scatter plot data");

            final List<ComputedData> computedDataList = new ArrayList<>();

            final FeatureCollection<SimpleFeatureType, SimpleFeature> collection = scatterPlotModel.pointDataSource
                    .getFeatureCollection();
            final SimpleFeature[] features = collection.toArray(new SimpleFeature[collection.size()]);

            final int boxSize = scatterPlotModel.boxSize;

            final Rectangle sceneRect = new Rectangle(raster.getSceneRasterWidth(),
                    raster.getSceneRasterHeight());

            final GeoCoding geoCoding = raster.getGeoCoding();
            final AffineTransform imageToModelTransform;
            imageToModelTransform = ImageManager.getImageToModelTransform(geoCoding);
            for (SimpleFeature feature : features) {
                final Point point = (Point) feature.getDefaultGeometryProperty().getValue();
                Point2D modelPos = new Point2D.Float((float) point.getX(), (float) point.getY());
                final Point2D imagePos = imageToModelTransform.inverseTransform(modelPos, null);

                if (!sceneRect.contains(imagePos)) {
                    continue;
                }
                final float imagePosX = (float) imagePos.getX();
                final float imagePosY = (float) imagePos.getY();
                final Rectangle imageRect = sceneRect.intersection(new Rectangle(
                        ((int) imagePosX) - boxSize / 2, ((int) imagePosY) - boxSize / 2, boxSize, boxSize));
                if (imageRect.isEmpty()) {
                    continue;
                }
                final double[] rasterValues = new double[imageRect.width * imageRect.height];
                raster.readPixels(imageRect.x, imageRect.y, imageRect.width, imageRect.height, rasterValues);

                final int[] maskBuffer = new int[imageRect.width * imageRect.height];
                Arrays.fill(maskBuffer, 1);
                if (selectedMask != null) {
                    selectedMask.readPixels(imageRect.x, imageRect.y, imageRect.width, imageRect.height,
                            maskBuffer);
                }

                final int centerIndex = imageRect.width * (imageRect.height / 2) + (imageRect.width / 2);
                if (maskBuffer[centerIndex] == 0) {
                    continue;
                }

                double sum = 0;
                double sumSqr = 0;
                int n = 0;
                boolean valid = false;

                for (int y = 0; y < imageRect.height; y++) {
                    for (int x = 0; x < imageRect.width; x++) {
                        final int index = y * imageRect.height + x;
                        if (raster.isPixelValid(x + imageRect.x, y + imageRect.y) && maskBuffer[index] != 0) {
                            final double rasterValue = rasterValues[index];
                            sum += rasterValue;
                            sumSqr += rasterValue * rasterValue;
                            n++;
                            valid = true;
                        }
                    }
                }

                if (!valid) {
                    continue;
                }

                double rasterMean = sum / n;
                double rasterSigma = n > 1 ? Math.sqrt((sumSqr - (sum * sum) / n) / (n - 1)) : 0.0;

                String localName = dataField.getLocalName();
                Number attribute = (Number) feature.getAttribute(localName);

                final Collection<org.opengis.feature.Property> featureProperties = feature.getProperties();

                final float correlativeData = attribute.floatValue();
                final GeoPos geoPos = new GeoPos();
                if (geoCoding.canGetGeoPos()) {
                    final PixelPos pixelPos = new PixelPos(imagePosX, imagePosY);
                    geoCoding.getGeoPos(pixelPos, geoPos);
                } else {
                    geoPos.setInvalid();
                }
                computedDataList.add(new ComputedData(imagePosX, imagePosY, geoPos.getLat(), geoPos.getLon(),
                        (float) rasterMean, (float) rasterSigma, correlativeData, featureProperties));
            }

            return computedDataList.toArray(new ComputedData[computedDataList.size()]);
        }

        @Override
        public void done() {
            try {
                final ValueAxis xAxis = getPlot().getDomainAxis();
                final ValueAxis yAxis = getPlot().getRangeAxis();

                xAxis.setAutoRange(false);
                yAxis.setAutoRange(false);

                scatterpointsDataset.removeAllSeries();
                acceptableDeviationDataset.removeAllSeries();
                regressionDataset.removeAllSeries();
                getPlot().removeAnnotation(r2Annotation);
                computedDatas = null;

                final ComputedData[] data = get();
                if (data.length == 0) {
                    return;
                }

                computedDatas = data;

                final XYIntervalSeries scatterValues = new XYIntervalSeries(getCorrelativeDataName());
                for (ComputedData computedData : computedDatas) {
                    final float rasterMean = computedData.rasterMean;
                    final float rasterSigma = computedData.rasterSigma;
                    final float correlativeData = computedData.correlativeData;
                    scatterValues.add(correlativeData, correlativeData, correlativeData, rasterMean,
                            rasterMean - rasterSigma, rasterMean + rasterSigma);
                }

                computingData = true;
                scatterpointsDataset.addSeries(scatterValues);

                xAxis.setAutoRange(true);
                yAxis.setAutoRange(true);

                xAxis.setAutoRange(false);
                yAxis.setAutoRange(false);

                xAutoRangeAxisRange = new Range(xAxis.getLowerBound(), xAxis.getUpperBound());
                yAutoRangeAxisRange = new Range(yAxis.getLowerBound(), yAxis.getUpperBound());

                if (xAxisRangeControl.isAutoMinMax()) {
                    xAxisRangeControl.adjustComponents(xAxis, 3);
                } else {
                    xAxisRangeControl.adjustAxis(xAxis, 3);
                }
                if (yAxisRangeControl.isAutoMinMax()) {
                    yAxisRangeControl.adjustComponents(yAxis, 3);
                } else {
                    yAxisRangeControl.adjustAxis(yAxis, 3);
                }

                computeRegressionAndAcceptableDeviationData();
                computingData = false;
            } catch (InterruptedException | CancellationException e) {
                BeamLogManager.getSystemLogger().log(Level.WARNING, "Failed to compute correlative plot.", e);
                JOptionPane.showMessageDialog(getParentDialogContentPane(),
                        "Failed to compute correlative plot.\n" + "Calculation canceled.",
                        /*I18N*/
                        CHART_TITLE, /*I18N*/
                        JOptionPane.ERROR_MESSAGE);
            } catch (ExecutionException e) {
                BeamLogManager.getSystemLogger().log(Level.WARNING, "Failed to compute correlative plot.", e);
                JOptionPane.showMessageDialog(getParentDialogContentPane(),
                        "Failed to compute correlative plot.\n" + "An error occurred:\n"
                                + e.getCause().getMessage(),
                        CHART_TITLE, /*I18N*/
                        JOptionPane.ERROR_MESSAGE);
            }
        }
    };
    swingWorker.execute();
}

From source file:edu.ku.brc.specify.config.init.DatabasePanel.java

/**
 * /*from   w  ww  . ja  va2s  .com*/
 */
public void createDB() {
    getValues(properties);

    final String databaseName = dbNameTxt.getText();
    final String dbUserName = usernameTxt.getText();
    final String dbPwd = passwordTxt.getText();
    final String hostName = hostNameTxt.getText();

    if (UIRegistry.isMobile()) {
        DBConnection.clearMobileMachineDir();
        File tmpDir = DBConnection.getMobileMachineDir(databaseName);
        UIRegistry.setEmbeddedDBPath(tmpDir.getAbsolutePath());
    }

    final DatabaseDriverInfo driverInfo = (DatabaseDriverInfo) drivers.getSelectedItem();
    String connStrInitial = driverInfo.getConnectionStr(DatabaseDriverInfo.ConnectionType.Open, hostName,
            databaseName, dbUserName, dbPwd, driverInfo.getName());
    //System.err.println(connStrInitial);

    DBConnection.checkForEmbeddedDir(connStrInitial);

    DBConnection.getInstance().setDriverName(driverInfo.getName());
    DBConnection.getInstance().setServerName(hostName);

    VerifyStatus status = verifyDatabase(properties);
    if ((isOK == null || !isOK) && status == VerifyStatus.OK) {
        progressBar.setIndeterminate(true);
        progressBar.setVisible(true);

        label.setText(getResourceString("CONN_DB"));
        createDBBtn.setVisible(false);

        setUIEnabled(false);

        DatabasePanel.this.label.setForeground(Color.BLACK);

        SwingWorker<Object, Object> worker = new SwingWorker<Object, Object>() {
            @Override
            protected Object doInBackground() throws Exception {
                isOK = false;

                DBMSUserMgr mgr = DBMSUserMgr.getInstance();

                List<PermissionInfo> perms = null;

                boolean dbmsOK = false;
                if (driverInfo.isEmbedded()) {
                    if (checkForProcesses) {
                        ProcessListUtil.checkForMySQLProcesses(null);
                        checkForProcesses = false;
                    }

                    if (UIRegistry.isMobile()) {
                        File mobileTmpDir = DBConnection.getMobileMachineDir();
                        if (!mobileTmpDir.exists()) {
                            if (!mobileTmpDir.mkdirs()) {
                                System.err.println(
                                        "Dir[" + mobileTmpDir.getAbsolutePath() + "] didn't get created!");
                                // throw exception
                            }
                            DBConnection.setCopiedToMachineDisk(true);
                        }
                    }

                    String newConnStr = driverInfo.getConnectionStr(DatabaseDriverInfo.ConnectionType.Open,
                            hostName, databaseName, dbUserName, dbPwd, driverInfo.getName());
                    if (driverInfo.isEmbedded()) {
                        //System.err.println(newConnStr);
                        try {
                            Class.forName(driverInfo.getDriverClassName());

                            // This call will create the database if it doesn't exist
                            DBConnection testDB = DBConnection.createInstance(driverInfo.getDriverClassName(),
                                    driverInfo.getDialectClassName(), databaseName, newConnStr, dbUserName,
                                    dbPwd);
                            testDB.getConnection(); // Opens the connection

                            if (testDB != null) {
                                testDB.close();
                            }
                            dbmsOK = true;

                        } catch (Exception ex) {
                            ex.printStackTrace();
                        }
                        DBConnection.getInstance().setDatabaseName(null);
                    }
                } else if (mgr.connectToDBMS(dbUserName, dbPwd, hostName)) {
                    perms = mgr.getPermissionsForCurrentUser();
                    Pair<List<PermissionInfo>, List<PermissionInfo>> missingPerms = PermissionInfo
                            .getMissingPerms(perms, createDBPerms, databaseName);
                    if (missingPerms.getFirst().size() > 0) {
                        final String missingPermStr = PermissionInfo.getMissingPermissionString(mgr,
                                missingPerms.getFirst(), databaseName);
                        SwingUtilities.invokeLater(new Runnable() {

                            /* (non-Javadoc)
                             * @see java.lang.Runnable#run()
                             */
                            @Override
                            public void run() {
                                UIRegistry.showLocalizedError("SEC_MISSING_PERMS", dbUserName, missingPermStr);
                            }

                        });
                        dbmsOK = false;
                    } else {
                        dbmsOK = true;
                    }
                    mgr.close();
                }

                if (dbmsOK) {
                    properties.put(DB_SKIP_CREATE, false);
                    if (perms != null) {
                        properties.put(DBUSERPERMS, perms);
                    }

                    firePropertyChange(PROPNAME, 0, 1);

                    try {
                        SpecifySchemaGenerator.generateSchema(driverInfo, hostName, databaseName, dbUserName,
                                dbPwd); // false means create new database, true means update

                        String connStr = driverInfo.getConnectionStr(DatabaseDriverInfo.ConnectionType.Create,
                                hostName, databaseName);
                        if (connStr == null) {
                            connStr = driverInfo.getConnectionStr(DatabaseDriverInfo.ConnectionType.Open,
                                    hostName, databaseName);
                        }

                        firePropertyChange(PROPNAME, 0, 2);

                        // tryLogin sets up DBConnection
                        if (UIHelper.tryLogin(driverInfo.getDriverClassName(), driverInfo.getDialectClassName(),
                                dbNameTxt.getText(), connStr, dbUserName, dbPwd)) {

                            if (!checkEngineCharSet(properties)) {
                                return false;
                            }
                            isOK = true;

                            firePropertyChange(PROPNAME, 0, 3);

                            Thumbnailer thumb = Thumbnailer.getInstance();
                            File thumbFile = XMLHelper.getConfigDir("thumbnail_generators.xml");
                            thumb.registerThumbnailers(thumbFile);
                            thumb.setQuality(0.5f);
                            thumb.setMaxSize(128, 128);

                            File attLoc = UIRegistry.getAppDataSubDir("AttachmentStorage", true);
                            AttachmentManagerIface attachMgr = new FileStoreAttachmentManager(attLoc);
                            AttachmentUtils.setAttachmentManager(attachMgr);
                            AttachmentUtils.setThumbnailer(thumb);

                        } else {
                            errorKey = "NO_LOGIN_ROOT";
                        }
                    } catch (Exception ex) {
                        errorKey = "DB_UNRECOVERABLE";
                    }
                } else {
                    errorKey = "NO_CONN_ROOT";
                    mgr.close();
                }
                return null;
            }

            /* (non-Javadoc)
             * @see javax.swing.SwingWorker#done()
             */
            @Override
            protected void done() {
                super.done();

                setUIEnabled(true);

                progressBar.setIndeterminate(false);
                progressBar.setVisible(false);

                updateBtnUI();
                createDBBtn.setVisible(!isOK);

                if (isOK) {
                    label.setText(UIRegistry.getResourceString("DB_CREATED"));
                    setUIEnabled(false);

                } else {
                    label.setText(UIRegistry.getResourceString(errorKey != null ? errorKey : "ERR_CRE_DB"));
                    UIRegistry.showLocalizedError(errorKey != null ? errorKey : "ERR_CRE_DB");
                }
            }
        };

        worker.addPropertyChangeListener(new PropertyChangeListener() {
            public void propertyChange(final PropertyChangeEvent evt) {
                if (PROPNAME.equals(evt.getPropertyName())) {
                    String key = null;
                    switch ((Integer) evt.getNewValue()) {
                    case 1:
                        key = "BLD_SCHEMA";
                        break;
                    case 2:
                        key = "DB_FRST_LOGIN";
                        break;
                    case 3:
                        key = "BLD_CACHE";
                        break;
                    default:
                        break;
                    }
                    if (key != null) {
                        DatabasePanel.this.label.setText(UIRegistry.getResourceString(key));
                    }
                }
            }
        });
        worker.execute();

    } else if (status == VerifyStatus.ERROR) {
        errorKey = "NO_LOGIN_ROOT";
        DatabasePanel.this.label.setText(UIRegistry.getResourceString(errorKey));
        DatabasePanel.this.label.setForeground(Color.RED);

        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                UIRegistry.getTopWindow().pack();
            }
        });
    }
}

From source file:ca.uviccscu.lp.server.main.ShutdownListener.java

@Override
public void windowClosing(WindowEvent e) {
    if (Shared.hashInProgress) {
        JOptionPane.showMessageDialog(null, "Closing not allowed - stop or finish hashing first!",
                "Hash in progress!", JOptionPane.WARNING_MESSAGE);
    } else {/*from  w ww .  j a  v a2s.c o m*/
        SwingWorker worker = new SwingWorker<Void, Void>() {

            @Override
            public Void doInBackground() {
                try {
                    int ans1 = JOptionPane.showConfirmDialog(null,
                            "Are you sure you want to shutdown? "
                                    + "Clients will switch to passive mode until restarted.",
                            "Confirmation", JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE);
                    if (ans1 == JOptionPane.OK_OPTION) {
                        l.debug("MainFrame window closing requested");
                        MainFrame.lockInterface();
                        MainFrame.setReportingActive();
                        MainFrame.updateTask("Shutting down", true);
                        MainFrame.updateProgressBar(0, 0, 0, "Shutting down settings manager!", true, true);
                        l.trace("Shutting down settings manager and saving session");
                        int ans2 = JOptionPane.showConfirmDialog(null, "Do you want to save the games list",
                                "Save confirmation", JOptionPane.OK_CANCEL_OPTION,
                                JOptionPane.QUESTION_MESSAGE);
                        if (ans2 == JOptionPane.OK_OPTION) {
                            SettingsManager.showSaveSettingsDialog();
                        }
                        SettingsManager.shutdown();
                        l.trace("OK");
                        l.trace("Stopping net manager");
                        MainFrame.updateProgressBar(0, 0, 0, "Shutting down net manager!", true, true);
                        ServerNetManager.shutdown();
                        l.trace("OK");
                        l.trace("Shutting down tracker manager - might have errors here!");
                        MainFrame.updateProgressBar(0, 0, 0, "Shutting down azureus - might take a while!",
                                true, true);
                        //Errors due to Azureus stupid shutdown thread killing routine(see AzureusCoreImpl)
                        //Basically it kills all other threads it doesnt recognise on JVM and then terminates
                        //Not designed to work with other application, and so it also kills the shutdown thread = BAD
                        //Library modified to prevent system shutdown, but exceptions still coming - irrelevant
                        TrackerManager.shutdown();
                        Thread.yield();
                        l.trace("OK");
                        Thread.yield();
                        Thread.sleep(5000);
                        while (!Shared.azShutdownDone) {
                            try {
                                l.trace("Awaiting az shutdown");
                                Thread.sleep(500);
                            } catch (InterruptedException ex) {
                                l.error("Az shutdown monitor interrupted", ex);
                            }
                        }
                        MainFrame.updateProgressBar(0, 0, 0, "Cleaning temporary files - might take a while!",
                                true, true);
                        File f = new File(Shared.workingDirectory);
                        /*
                        //delete until files unlocked or timeout
                        if (!deleteFolder(f, true, 3000, 15000)) {
                        l.trace("Advanced file deletion measures required");
                        releaseLocks();
                        deleteFolder(f, false, 0, 0);
                        //Advanced thread killing, stolen from azureus...except now it kills itself
                        l.error("Delete timeout  - attempting threadicide");
                        l.trace("Starting thread killing");
                        //First kill azureus SM - allows to do whatever we want with threads
                        l.trace("Removed SM");
                        System.setSecurityManager(null);
                        //
                        ThreadGroup tg = Thread.currentThread().getThreadGroup();
                        while (tg.getParent() != null) {
                        tg = tg.getParent();
                        }
                        Thread[] threads = new Thread[tg.activeCount() + 1024];
                        tg.enumerate(threads, true);
                        //VERY BAD WAY TO STOP THREAD BUT NO CHOICE - need to release the file locks
                        for (int i = 0; i < threads.length; i++) {
                        Thread th = threads[i];
                        if (th != null && th != Thread.currentThread() && AEThread2.isOurThread(th)) {
                        l.trace("Stopping " + th.getName());
                        try {
                        th.stop();
                        l.trace("ok");
                        } catch (SecurityException e) {
                        l.trace("Stop vetoed by SM", e);
                        }
                                
                        }
                        }
                        //
                        deleteFolder(f, false, 0, 0);
                        l.error("Trying to stop more threads, list:");
                        //List remaining threads
                        ThreadGroup tg2 = Thread.currentThread().getThreadGroup();
                        while (tg2.getParent() != null) {
                        tg2 = tg2.getParent();
                        }
                        //Object o = new Object();
                        //o.notifyAll();
                        Thread[] threads2 = new Thread[tg2.activeCount() + 1024];
                        tg2.enumerate(threads2, true);
                        //VERY BAD WAY TO STOP THREAD BUT NO CHOICE - need to release the file locks
                        for (int i = 0; i < threads2.length; i++) {
                        Thread th = threads2[i];
                        if (th != null) {
                        l.trace("Have thread: " + th.getName());
                        if (th != null && th != Thread.currentThread() && (AEThread2.isOurThread(th) || isAzThread(th))) {
                        l.trace("Stopping " + th.getName());
                        try {
                        th.stop();
                        l.trace("ok");
                        } catch (SecurityException e) {
                        l.trace("Stop vetoed by SM", e);
                        }
                                
                        }
                        }
                        }
                        try {
                        Utils.cleanupDir();
                        l.trace("OK");
                        } catch (IOException e) {
                        l.trace("Cleaning failed after more thread cleanup", e);
                        Thread.yield();
                        }
                        threadCleanup(f);
                        l.error("Last resort - scheduling delete on JVM exit - might FAIL, CHECK MANUALLY");
                        try {
                        FileUtils.forceDeleteOnExit(f);
                        } catch (IOException iOException) {
                        l.fatal("All delete attempts failed - clean manually");
                        }
                        }
                        File test = new File("C:\\AZTest\\AZ\\logs\\debug_1.log");
                        test.deleteOnExit();
                        try {
                        Thread.sleep(30000);
                        } catch (InterruptedException ex) {
                        java.util.logging.Logger.getLogger(ShutdownListener.class.getName()).log(Level.SEVERE, null, ex);
                        }
                         *
                         */
                        threadReadout();
                        try {
                            Utils.cleanupDir();
                            l.trace("OK");
                        } catch (IOException e) {
                            l.trace("Cleaning failed - expected due to stupid Azureus file lock", e);
                            Thread.yield();
                        }
                        System.exit(0);
                        return null;
                    } else {
                        return null;
                    }
                } catch (Exception ex) {
                    l.fatal("Exception during shutdown!!!", ex);
                    //just end it
                    System.exit(4);
                    return null;
                }
            }
        };
        worker.execute();
    }
}

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

/**
 * /* w  w  w  .  ja  v  a  2s .com*/
 */
public void doCreateBatchOfColObj(final Pair<String, String> catNumPair) {
    if (catNumPair.getFirst().equals(catNumPair.getSecond())) {
        return;
    }

    DBFieldInfo CatNumFld = DBTableIdMgr.getInstance().getInfoById(CollectionObject.getClassTableId())
            .getFieldByColumnName("CatalogNumber");
    final UIFieldFormatterIFace formatter = CatNumFld.getFormatter();
    if (!formatter.isIncrementer()) {
        //XXX this will have been checked earlier, right?
        UIRegistry.showLocalizedError(NonIncrementingCatNum);
        return;
    }

    final Vector<String> nums = new Vector<String>();
    processBatchContents(catNumPair, false, false, nums);
    SwingWorker<Integer, Integer> worker = new SwingWorker<Integer, Integer>() {
        private Vector<Pair<Integer, String>> objectsAdded = new Vector<Pair<Integer, String>>();
        private Vector<String> objectsNotAdded = new Vector<String>();
        private RecordSet batchRS;
        //private boolean invalidEntry = false;

        /* (non-Javadoc)
         * @see javax.swing.SwingWorker#doInBackground()
         */
        @Override
        protected Integer doInBackground() throws Exception {

            String catNum = catNumPair.getFirst();
            Integer collId = AppContextMgr.getInstance().getClassObject(Collection.class).getId();
            String coIdSql = "select CollectionObjectID from collectionobject where CollectionMemberID = "
                    + collId + " and CatalogNumber = '";
            objectsAdded.add(new Pair<Integer, String>(
                    (Integer) BasicSQLUtils.querySingleObj(coIdSql + catNum + "'"), catNum));

            int cnt = 0;
            CollectionObject co = null;
            //CollectionObject carryForwardCo = (CollectionObject )formViewObj.getDataObj();
            CollectionObject carryForwardCo;
            DataProviderSessionIFace session = DataProviderFactory.getInstance().createSession();
            try {
                carryForwardCo = session.get(CollectionObject.class,
                        ((CollectionObject) formViewObj.getDataObj()).getId());
            } finally {
                session.close();
            }

            Thread.sleep(666); //Perhaps this is unnecessary, but it seems
            //to prevent sporadic "illegal access to loading collection" hibernate errors.
            try {
                for (String currentCat : nums) {
                    try {
                        co = new CollectionObject();
                        co.initialize();

                        //Collection doesn't get set in co.initialize(), or carryForward, but it needs to be set.
                        co.setCollection(AppContextMgr.getInstance().getClassObject(Collection.class));
                        //ditto, but doesn't so much need to be set
                        co.setModifiedByAgent(carryForwardCo.getModifiedByAgent());

                        co.setCatalogNumber(currentCat);
                        formViewObj.setNewObject(co);

                        if (formViewObj.saveObject()) {
                            objectsAdded.add(new Pair<Integer, String>(
                                    (Integer) BasicSQLUtils
                                            .querySingleObj(coIdSql + co.getCatalogNumber() + "'"),
                                    co.getCatalogNumber()));
                        } else {
                            objectsNotAdded.add(formatter.formatToUI(co.getCatalogNumber()).toString());
                        }
                    } catch (Exception ex) {
                        log.error(ex);
                        objectsNotAdded.add(formatter.formatToUI(currentCat) + ": "
                                + (ex.getLocalizedMessage() == null ? "" : ex.getLocalizedMessage()));
                    }
                    cnt++;
                    firePropertyChange(GLASSKEY, 0, cnt);
                }
                firePropertyChange(GLASSKEY, 0, nums.size());

            } catch (Exception ex) {
                edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
                edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(Uploader.class, ex);
            }
            formViewObj.setDataObj(carryForwardCo);
            saveBatchObjectsToRS();
            return objectsAdded.size();
        }

        /**
         * Save the objects added to a Recordset
         */
        protected void saveBatchObjectsToRS() {
            batchRS = new RecordSet();
            batchRS.initialize();
            batchRS.setDbTableId(CollectionObject.getClassTableId());
            String name = getResourceString(BatchRSBaseName) + " " + formatter.formatToUI(catNumPair.getFirst())
                    + "-" + formatter.formatToUI(catNumPair.getSecond());
            if (objectsNotAdded.size() > 0) {
                name += "-" + UIRegistry.getResourceString(IncompleteSaveFlag);
            }
            batchRS.setName(name);
            for (Pair<Integer, String> obj : objectsAdded) {
                batchRS.addItem(obj.getFirst());
            }
            DataProviderSessionIFace session = DataProviderFactory.getInstance().createSession();
            boolean transOpen = false;
            try {
                BusinessRulesIFace busRule = DBTableIdMgr.getInstance().getBusinessRule(RecordSet.class);
                if (busRule != null) {
                    busRule.beforeSave(batchRS, session);
                }
                batchRS.setTimestampCreated(new Timestamp(System.currentTimeMillis()));
                batchRS.setOwner(AppContextMgr.getInstance().getClassObject(SpecifyUser.class));
                session.beginTransaction();
                transOpen = true;
                session.save(batchRS);
                if (busRule != null) {
                    if (!busRule.beforeSaveCommit(batchRS, session)) {
                        session.rollback();
                        throw new Exception("Business rules processing failed");
                    }
                }
                session.commit();
                transOpen = false;
                if (busRule != null) {
                    busRule.afterSaveCommit(batchRS, session);
                }
            } catch (Exception ex) {
                edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
                edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(Uploader.class, ex);
                if (transOpen) {
                    session.rollback();
                }
            }
        }

        /**
         * Add the batch RS to the RecordSetTask UI
         */
        protected void addBatchRSToUI() {
            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    CommandAction cmd = new CommandAction(RecordSetTask.RECORD_SET,
                            RecordSetTask.ADD_TO_NAV_BOX);
                    cmd.setData(batchRS);
                    CommandDispatcher.dispatch(cmd);
                }
            });
        }

        /* (non-Javadoc)
         * @see javax.swing.SwingWorker#done()
         */
        @Override
        protected void done() {
            super.done();
            processingSeries.set(false);
            addBatchRSToUI();
            UIRegistry.clearSimpleGlassPaneMsg();
            if (objectsNotAdded.size() == 0) {
                UIRegistry.displayLocalizedStatusBarText(BatchSaveSuccess,
                        formatter.formatToUI(catNumPair.getFirst()),
                        formatter.formatToUI(catNumPair.getSecond()));
            } else {
                showBatchErrorObjects(objectsNotAdded, BatchSaveErrorsTitle, BatchSaveErrors);
            }
        }
    };

    final SimpleGlassPane gp = UIRegistry.writeSimpleGlassPaneMsg(getI10N("SAVING_BATCH"), 24);
    gp.setProgress(0);
    worker.addPropertyChangeListener(new PropertyChangeListener() {
        public void propertyChange(final PropertyChangeEvent evt) {
            if (GLASSKEY.equals(evt.getPropertyName())) {
                double value = (double) ((Integer) evt.getNewValue()).intValue();
                int percent = (int) (value / ((double) nums.size()) * 100.0);
                gp.setProgress(percent);

            }
        }
    });
    processingSeries.set(true);
    worker.execute();
    //        try {
    //           worker.get();
    //        } catch (Exception ex) {
    //           ex.printStackTrace();
    //        }
}

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();//  w w  w. j a  v  a2s  . c o m

    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:nz.ac.waikato.cms.supernova.gui.Supernova.java

/**
 * Creates the panel for batch generation.
 *
 * @return      the panel//  w  w  w .j a  v  a2 s  .  c  o m
 */
protected BasePanel createBatchPanel() {
    BasePanel result;
    JPanel params;
    JPanel left1;
    JPanel left2;
    JPanel panel;

    result = new BasePanel(new BorderLayout());
    m_BatchLog = new JTextArea(20, 40);
    m_BatchLog.setFont(Font.decode("Monospaced-PLAIN-12"));
    result.add(new BaseScrollPane(m_BatchLog), BorderLayout.CENTER);

    left1 = new JPanel(new BorderLayout());
    result.add(left1, BorderLayout.WEST);

    // params with height 2
    params = new JPanel(new GridLayout(0, 1));
    left1.add(params, BorderLayout.NORTH);

    m_BatchColors = new ColorTable();
    left1.add(new BaseScrollPane(m_BatchColors), BorderLayout.NORTH);

    // params with height 1
    panel = new JPanel(new BorderLayout());
    left1.add(panel, BorderLayout.CENTER);
    left2 = new JPanel(new BorderLayout());
    panel.add(left2, BorderLayout.NORTH);
    params = new JPanel(new GridLayout(0, 1));
    left2.add(params, BorderLayout.NORTH);

    // background
    m_BatchBackground = new ColorButton(Color.BLACK);
    params.add(createParameter("Background", m_BatchBackground));

    // opacity
    m_BatchOpacity = new JSpinner();
    m_BatchOpacity.setValue(10);
    ((SpinnerNumberModel) m_BatchOpacity.getModel()).setMinimum(0);
    ((SpinnerNumberModel) m_BatchOpacity.getModel()).setMaximum(100);
    ((SpinnerNumberModel) m_BatchOpacity.getModel()).setStepSize(10);
    ((JSpinner.DefaultEditor) m_BatchOpacity.getEditor()).getTextField().setColumns(5);
    params.add(createParameter("Opacity %", m_BatchOpacity));

    // margin
    m_BatchMargin = new JSpinner();
    m_BatchMargin.setValue(20);
    ((SpinnerNumberModel) m_BatchMargin.getModel()).setMinimum(0);
    ((SpinnerNumberModel) m_BatchMargin.getModel()).setMaximum(100);
    ((SpinnerNumberModel) m_BatchMargin.getModel()).setStepSize(10);
    ((JSpinner.DefaultEditor) m_BatchMargin.getEditor()).getTextField().setColumns(5);
    params.add(createParameter("Margin %", m_BatchMargin));

    // width
    m_BatchWidth = new JSpinner();
    m_BatchWidth.setValue(400);
    ((SpinnerNumberModel) m_BatchWidth.getModel()).setMinimum(1);
    ((SpinnerNumberModel) m_BatchWidth.getModel()).setStepSize(100);
    ((JSpinner.DefaultEditor) m_BatchWidth.getEditor()).getTextField().setColumns(5);
    params.add(createParameter("Width", m_BatchWidth));

    // height
    m_BatchHeight = new JSpinner();
    m_BatchHeight.setValue(400);
    ((SpinnerNumberModel) m_BatchHeight.getModel()).setMinimum(1);
    ((SpinnerNumberModel) m_BatchHeight.getModel()).setStepSize(100);
    ((JSpinner.DefaultEditor) m_BatchHeight.getEditor()).getTextField().setColumns(5);
    params.add(createParameter("Height", m_BatchHeight));

    // generator
    m_BatchGenerator = new JComboBox<>(Registry.toStringArray(Registry.getGenerators(), true));
    params.add(createParameter("Generator", m_BatchGenerator));

    // center
    m_BatchCenter = new JComboBox<>(Registry.toStringArray(Registry.getCenters(), true));
    params.add(createParameter("Center", m_BatchCenter));

    // csv
    m_BatchCSV = new FileChooserPanel();
    m_BatchCSV.addChoosableFileFilter(new ExtensionFileFilter("CSV files", "csv"));
    m_BatchCSV.setPreferredSize(new Dimension(170, (int) m_BatchCSV.getPreferredSize().getHeight()));
    params.add(createParameter("CSV", m_BatchCSV));

    // output
    m_BatchOutput = new DirectoryChooserPanel();
    m_BatchOutput.setPreferredSize(new Dimension(170, (int) m_BatchOutput.getPreferredSize().getHeight()));
    params.add(createParameter("Output", m_BatchOutput));

    // generate
    panel = new JPanel(new FlowLayout(FlowLayout.LEFT));
    m_BatchGenerate = new JButton("Generate");
    m_BatchGenerate.addActionListener((ActionEvent e) -> {
        SwingWorker worker = new SwingWorker() {
            @Override
            protected Object doInBackground() throws Exception {
                generateBatchOutput();
                return null;
            }
        };
        worker.execute();
    });
    panel.add(m_BatchGenerate);
    params.add(panel);

    adjustLabels();

    return result;
}

From source file:op.allowance.PnlAllowance.java

private void reloadDisplay() {
    /***/*from w  w  w.  ja  va  2  s .c o  m*/
     *               _                 _ ____  _           _
     *      _ __ ___| | ___   __ _  __| |  _ \(_)___ _ __ | | __ _ _   _
     *     | '__/ _ \ |/ _ \ / _` |/ _` | | | | / __| '_ \| |/ _` | | | |
     *     | | |  __/ | (_) | (_| | (_| | |_| | \__ \ |_) | | (_| | |_| |
     *     |_|  \___|_|\___/ \__,_|\__,_|____/|_|___/ .__/|_|\__,_|\__, |
     *                                              |_|            |___/
     */

    final boolean withworker = false;
    cpsCash.removeAll();
    cashmap.clear();
    cpMap.clear();
    contentmap.clear();
    carrySums.clear();
    minmax.clear();

    if (withworker) {

        OPDE.getMainframe().setBlocked(true);
        OPDE.getDisplayManager()
                .setProgressBarMessage(new DisplayMessage(SYSTools.xx("misc.msg.wait"), -1, 100));

        SwingWorker worker = new SwingWorker() {

            @Override
            protected Object doInBackground() throws Exception {
                int progress = 0;
                OPDE.getDisplayManager().setProgressBarMessage(
                        new DisplayMessage(SYSTools.xx("misc.msg.wait"), progress, lstResidents.size()));

                for (Resident resident : lstResidents) {
                    progress++;
                    createCP4(resident);
                    OPDE.getDisplayManager().setProgressBarMessage(
                            new DisplayMessage(SYSTools.xx("misc.msg.wait"), progress, lstResidents.size()));
                }
                return null;
            }

            @Override
            protected void done() {
                OPDE.getDisplayManager().setMainMessage(SYSTools.xx(internalClassID));
                buildPanel();
                OPDE.getDisplayManager().setProgressBarMessage(null);
                OPDE.getMainframe().setBlocked(false);
            }
        };
        worker.execute();

    } else {

        for (Resident resident : lstResidents) {
            createCP4(resident);
        }

        OPDE.getDisplayManager().setMainMessage(SYSTools.xx(internalClassID));

        //            if (currentResident != null) {
        //                OPDE.getDisplayManager().setMainMessage(ResidentTools.getLabelText(currentResident));
        //            } else {
        //                OPDE.getDisplayManager().setMainMessage(SYSTools.xx(internalClassID));
        //            }
        buildPanel();
    }

}

From source file:op.care.bhp.PnlBHP.java

private void reloadDisplay() {
    /***/*from w ww.  j a va  2 s .  co  m*/
     *               _                 _ ____  _           _
     *      _ __ ___| | ___   __ _  __| |  _ \(_)___ _ __ | | __ _ _   _
     *     | '__/ _ \ |/ _ \ / _` |/ _` | | | | / __| '_ \| |/ _` | | | |
     *     | | |  __/ | (_) | (_| | (_| | |_| | \__ \ |_) | | (_| | |_| |
     *     |_|  \___|_|\___/ \__,_|\__,_|____/|_|___/ .__/|_|\__,_|\__, |
     *                                              |_|            |___/
     */
    initPhase = true;

    final boolean withworker = true;
    if (withworker) {

        OPDE.getMainframe().setBlocked(true);
        OPDE.getDisplayManager()
                .setProgressBarMessage(new DisplayMessage(SYSTools.xx("misc.msg.wait"), -1, 100));

        synchronized (mapPrescription2Stock) {
            SYSTools.clear(mapPrescription2Stock);
        }
        synchronized (mapBHP2Pane) {
            SYSTools.clear(mapBHP2Pane);
        }

        synchronized (mapShift2BHP) {
            if (mapShift2BHP != null) {
                for (Byte key : mapShift2BHP.keySet()) {
                    mapShift2BHP.get(key).clear();
                }
                mapShift2BHP.clear();
            }
        }
        synchronized (mapShift2Pane) {
            if (mapShift2Pane != null) {
                for (Byte key : mapShift2Pane.keySet()) {
                    mapShift2Pane.get(key).removeAll();
                }
                mapShift2Pane.clear();
            }
        }

        SwingWorker worker = new SwingWorker() {

            @Override
            protected Object doInBackground() throws Exception {

                try {

                    int progress = 0;
                    OPDE.getDisplayManager()
                            .setProgressBarMessage(new DisplayMessage(SYSTools.xx("misc.msg.wait"), -1, 100));

                    synchronized (mapShift2BHP) {
                        for (BHP bhp : BHPTools.getBHPs(resident, jdcDatum.getDate())) {
                            if (!mapShift2BHP.containsKey(bhp.getShift())) {
                                mapShift2BHP.put(bhp.getShift(), new ArrayList<BHP>());
                            }
                            mapShift2BHP.get(bhp.getShift()).add(bhp);
                        }

                        if (!mapShift2BHP.containsKey(BHPTools.SHIFT_ON_DEMAND)) {
                            mapShift2BHP.put(BHPTools.SHIFT_ON_DEMAND, new ArrayList<BHP>());
                        }
                        mapShift2BHP.get(BHPTools.SHIFT_ON_DEMAND)
                                .addAll(BHPTools.getBHPsOnDemand(resident, jdcDatum.getDate()));
                        if (!mapShift2BHP.containsKey(BHPTools.SHIFT_OUTCOMES)) {
                            mapShift2BHP.put(BHPTools.SHIFT_OUTCOMES, new ArrayList<BHP>());
                        }
                        mapShift2BHP.get(BHPTools.SHIFT_OUTCOMES)
                                .addAll(BHPTools.getOutcomeBHPs(resident, new LocalDate(jdcDatum.getDate())));
                    }

                    synchronized (mapShift2Pane) {
                        for (Byte shift : new Byte[] { BHPTools.SHIFT_ON_DEMAND, BHPTools.SHIFT_OUTCOMES,
                                BHPTools.SHIFT_VERY_EARLY, BHPTools.SHIFT_EARLY, BHPTools.SHIFT_LATE,
                                BHPTools.SHIFT_VERY_LATE }) {
                            mapShift2Pane.put(shift, createCP4(shift));
                            try {
                                mapShift2Pane.get(shift)
                                        .setCollapsed(shift == BHPTools.SHIFT_ON_DEMAND
                                                || shift == BHPTools.SHIFT_OUTCOMES
                                                || shift != SYSCalendar.whatShiftIs(new Date()));
                            } catch (PropertyVetoException e) {
                                OPDE.debug(e);
                            }
                            progress += 20;
                            OPDE.getDisplayManager().setProgressBarMessage(
                                    new DisplayMessage(SYSTools.xx("misc.msg.wait"), progress, 100));
                        }
                    }
                } catch (Exception exc) {
                    OPDE.fatal(exc);
                }

                return null;
            }

            @Override
            protected void done() {
                buildPanel(true);
                initPhase = false;
                OPDE.getDisplayManager().setProgressBarMessage(null);
                OPDE.getMainframe().setBlocked(false);
            }
        };
        worker.execute();

    } else {

        mapBHP2Pane.clear();
        if (mapShift2BHP != null) {
            for (Byte key : mapShift2BHP.keySet()) {
                mapShift2BHP.get(key).clear();
            }
            mapShift2BHP.clear();
        }
        if (mapShift2Pane != null) {
            for (Byte key : mapShift2Pane.keySet()) {
                mapShift2Pane.get(key).removeAll();
            }
            mapShift2Pane.clear();
        }

        for (BHP bhp : BHPTools.getBHPs(resident, jdcDatum.getDate())) {
            if (!mapShift2BHP.containsKey(bhp.getShift())) {
                mapShift2BHP.put(bhp.getShift(), new ArrayList<BHP>());
            }
            mapShift2BHP.get(bhp.getShift()).add(bhp);
        }

        if (!mapShift2BHP.containsKey(BHPTools.SHIFT_ON_DEMAND)) {
            mapShift2BHP.put(BHPTools.SHIFT_ON_DEMAND, new ArrayList<BHP>());
        }
        mapShift2BHP.get(BHPTools.SHIFT_ON_DEMAND)
                .addAll(BHPTools.getBHPsOnDemand(resident, jdcDatum.getDate()));
        if (!mapShift2BHP.containsKey(BHPTools.SHIFT_OUTCOMES)) {
            mapShift2BHP.put(BHPTools.SHIFT_OUTCOMES, new ArrayList<BHP>());
        }
        mapShift2BHP.get(BHPTools.SHIFT_OUTCOMES)
                .addAll(BHPTools.getOutcomeBHPs(resident, new LocalDate(jdcDatum.getDate())));

        for (Byte shift : new Byte[] { BHPTools.SHIFT_ON_DEMAND, BHPTools.SHIFT_OUTCOMES,
                BHPTools.SHIFT_VERY_EARLY, BHPTools.SHIFT_EARLY, BHPTools.SHIFT_LATE,
                BHPTools.SHIFT_VERY_LATE }) {
            mapShift2Pane.put(shift, createCP4(shift));
            try {
                mapShift2Pane.get(shift).setCollapsed(shift == BHPTools.SHIFT_ON_DEMAND
                        || shift == BHPTools.SHIFT_OUTCOMES || shift != SYSCalendar.whatShiftIs(new Date()));
            } catch (PropertyVetoException e) {
                OPDE.debug(e);
            }
        }

        buildPanel(true);

    }
    initPhase = false;
}

From source file:op.care.dfn.PnlDFN.java

private void reloadDisplay() {
    /***/*from w ww  .ja v  a2s .com*/
     *               _                 _ ____  _           _
     *      _ __ ___| | ___   __ _  __| |  _ \(_)___ _ __ | | __ _ _   _
     *     | '__/ _ \ |/ _ \ / _` |/ _` | | | | / __| '_ \| |/ _` | | | |
     *     | | |  __/ | (_) | (_| | (_| | |_| | \__ \ |_) | | (_| | |_| |
     *     |_|  \___|_|\___/ \__,_|\__,_|____/|_|___/ .__/|_|\__,_|\__, |
     *                                              |_|            |___/
     */
    initPhase = true;
    synchronized (mapDFN2Pane) {
        SYSTools.clear(mapDFN2Pane);
    }

    synchronized (mapShift2DFN) {
        for (Byte key : mapShift2DFN.keySet()) {
            mapShift2DFN.get(key).clear();
        }
    }

    synchronized (mapShift2Pane) {
        for (Byte key : mapShift2Pane.keySet()) {
            mapShift2Pane.get(key).removeAll();
        }
        mapShift2Pane.clear();
    }

    final boolean withworker = true;
    if (withworker) {

        OPDE.getMainframe().setBlocked(true);
        OPDE.getDisplayManager()
                .setProgressBarMessage(new DisplayMessage(SYSTools.xx("misc.msg.wait"), -1, 100));

        cpDFN.removeAll();

        SwingWorker worker = new SwingWorker() {

            @Override
            protected Object doInBackground() throws Exception {

                int progress = 0;
                OPDE.getDisplayManager()
                        .setProgressBarMessage(new DisplayMessage(SYSTools.xx("misc.msg.wait"), progress, 100));

                ArrayList<DFN> listDFNs = DFNTools.getDFNs(resident, jdcDate.getDate());

                synchronized (mapShift2DFN) {
                    for (DFN dfn : listDFNs) {
                        mapShift2DFN.get(dfn.getShift()).add(dfn);
                    }
                }

                // now build the CollapsiblePanes
                for (Byte shift : new Byte[] { DFNTools.SHIFT_ON_DEMAND, DFNTools.SHIFT_VERY_EARLY,
                        DFNTools.SHIFT_EARLY, DFNTools.SHIFT_LATE, DFNTools.SHIFT_VERY_LATE }) {
                    CollapsiblePane cp = createCP4(shift);
                    synchronized (mapShift2Pane) {
                        mapShift2Pane.put(shift, cp);
                        try {
                            mapShift2Pane.get(shift).setCollapsed(shift == DFNTools.SHIFT_ON_DEMAND
                                    || shift != SYSCalendar.whatShiftIs(new Date()));
                        } catch (PropertyVetoException e) {
                            OPDE.debug(e);
                        }
                        progress += 20;
                        OPDE.getDisplayManager().setProgressBarMessage(
                                new DisplayMessage(SYSTools.xx("misc.msg.wait"), progress, 100));
                    }
                }
                return null;
            }

            @Override
            protected void done() {
                buildPanel(true);
                initPhase = false;
                OPDE.getDisplayManager().setProgressBarMessage(null);
                OPDE.getMainframe().setBlocked(false);
                OPDE.getDisplayManager().addSubMessage(
                        new DisplayMessage(DateFormat.getDateInstance().format(jdcDate.getDate())));
            }
        };
        worker.execute();

    } else {
        //           buildPanel(true);
    }
    initPhase = false;
}