Example usage for javax.swing SwingWorker addPropertyChangeListener

List of usage examples for javax.swing SwingWorker addPropertyChangeListener

Introduction

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

Prototype

public final void addPropertyChangeListener(PropertyChangeListener listener) 

Source Link

Document

Adds a PropertyChangeListener to the listener list.

Usage

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

/**
 * //  w  ww  . j a v  a  2s .  c  o  m
 */
protected void doCreate() {
    if (isOK == null || !isOK) {
        progressBar.setIndeterminate(true);
        progressBar.setVisible(true);

        setUIEnabled(false);

        label.setText(UIRegistry.getResourceString("CONN_DB"));

        testBtn.setVisible(false);

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

                    firePropertyChange(propName, 0, 1);

                    conn = DBConnection.getInstance();

                    AppContextMgr.getInstance().setHasContext(true); // override

                    BuildSampleDatabase bsd = new BuildSampleDatabase();

                    bsd.setSession(HibernateUtil.getCurrentSession());

                    int treeDir = BuildSampleDatabase.getTreeDirForClass(properties, StorageTreeDef.class);

                    isOK = bsd.createEmptyInstitution(properties, false, false, true, treeDir);

                    AppContextMgr.getInstance().setClassObject(DataType.class, bsd.getDataType());

                    HibernateUtil.closeSession();

                    if (!isOK) {
                        errorKey = "BAD_INST";
                        return null;
                    }

                    String userName = properties.getProperty("usrUsername");
                    String password = properties.getProperty("usrPassword");
                    String dbName = properties.getProperty("dbName");

                    firePropertyChange(propName, 0, 2);

                    isOK = tryLogginIn(userName, password, dbName);
                    if (!isOK) {
                        errorKey = "BAD_LOGIN";
                        return null;
                    }

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

                    errorKey = "INST_UNRECOVERABLE";
                }

                return null;
            }

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

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

                setUIEnabled(true);

                updateBtnUI();

                label.setText(UIRegistry.getResourceString(
                        isOK ? "INST_CREATED" : (errorKey != null ? errorKey : "ERR_CRE_INST")));

                if (isOK) {
                    setUIEnabled(false);
                    prevBtn.setEnabled(false);
                }
            }
        };

        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 = "CREATING_INST";
                        break;
                    case 2:
                        key = "LOGIN_USER";
                        break;
                    default:
                        break;
                    }
                    if (key != null) {
                        InstSetupPanel.this.label.setText(UIRegistry.getResourceString(key));
                    }
                }
            }
        });
        worker.execute();
    }
}

From source file:edu.ku.brc.specify.config.FixAttachments.java

/**
 * @param resultsHashMap/* w w  w  .ja v a2 s  . c o m*/
 * @param tableHash
 * @param totalFiles
 */
private void doAttachmentRefCleanup(final HashMap<Integer, Vector<Object[]>> resultsHashMap,
        final HashMap<Integer, AttchTableModel> tableHash, final int totalFiles) {
    final int numAttachs = getNumberofBadAttachments();

    final String CNT = "CNT";
    final SwingWorker<Integer, Integer> worker = new SwingWorker<Integer, Integer>() {
        int filesCnt = 0;
        int errs = 0;

        @Override
        protected Integer doInBackground() throws Exception {
            try {
                for (int tblId : resultsHashMap.keySet()) {
                    DBTableInfo ti = DBTableIdMgr.getInstance().getInfoById(tblId);
                    AttchTableModel model = tableHash.get(tblId);
                    for (int r = 0; r < model.getRowCount(); r++) {
                        int attachId = model.getAttachmentId(r);
                        int attachJoinId = model.getAttachmentJoinId(r);

                        String sql = String.format("DELETE FROM %s WHERE %s = %d", ti.getName(),
                                ti.getIdColumnName(), attachJoinId);
                        int rv = BasicSQLUtils.update(sql);
                        if (rv == 1) {
                            rv = BasicSQLUtils
                                    .update("DELETE FROM attachment WHERE AttachmentID = " + attachId);
                            if (rv == 1) {
                                filesCnt++;
                            } else {
                                errs++;
                            }
                        } else {
                            errs++;
                        }

                        firePropertyChange(CNT, 0, (int) ((double) filesCnt / (double) totalFiles * 100.0));
                    }
                }

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

        @Override
        protected void done() {
            UIRegistry.clearSimpleGlassPaneMsg();
            UIRegistry.displayInfoMsgDlg(String.format("Attachments removed: %d / %d", filesCnt, numAttachs));

            if (errs > 0) {
                UIRegistry.displayErrorDlg(
                        String.format("There were %d errors when deleting the attachments.", errs));
            } else {
                if (getNumberofBadAttachments() == 0) {
                    AppPreferences.getGlobalPrefs().putBoolean("CHECK_ATTCH_ERR", false);
                }
            }
            super.done();
        }
    };

    final SimpleGlassPane glassPane = UIRegistry
            .writeSimpleGlassPaneMsg(String.format("Removing %d attachments.", numAttachs), 24);
    glassPane.setProgress(0);

    worker.addPropertyChangeListener(new PropertyChangeListener() {
        public void propertyChange(final PropertyChangeEvent evt) {
            if (CNT.equals(evt.getPropertyName())) {
                glassPane.setProgress((Integer) evt.getNewValue());
            }
        }
    });

    worker.execute();
}

From source file:com.marginallyclever.makelangelo.MainGUI.java

public boolean LoadImage(String filename) {
    // where to save temp output file?
    final String sourceFile = filename;
    final String destinationFile = GetTempDestinationFile();

    LoadImageConverters();/*from   ww w.j  a v a  2s.co m*/
    if (ChooseImageConversionOptions(false) == false)
        return false;

    final ProgressMonitor pm = new ProgressMonitor(null, translator.get("Converting"), "", 0, 100);
    pm.setProgress(0);
    pm.setMillisToPopup(0);

    final SwingWorker<Void, Void> s = new SwingWorker<Void, Void>() {
        @Override
        public Void doInBackground() {
            // read in image
            BufferedImage img;
            try {
                Log("<font color='green'>" + translator.get("Converting") + " " + destinationFile
                        + "</font>\n");
                // convert with style
                img = ImageIO.read(new File(sourceFile));
                int style = GetDrawStyle();
                Filter f = image_converters.get(style);
                TabToLog();
                f.SetParent(this);
                f.SetProgressMonitor(pm);
                f.SetDestinationFile(destinationFile);
                f.Convert(img);
                TabToDraw();
                previewPane.ZoomToFitPaper();
            } catch (IOException e) {
                Log("<font color='red'>" + translator.get("Failed") + e.getLocalizedMessage() + "</font>\n");
                recentFiles.remove(sourceFile);
                updateMenuBar();
            }

            pm.setProgress(100);
            return null;
        }

        @Override
        public void done() {
            pm.close();
            Log("<font color='green'>" + translator.get("Finished") + "</font>\n");
            PlayConversionFinishedSound();
            LoadGCode(destinationFile);
        }
    };

    s.addPropertyChangeListener(new PropertyChangeListener() {
        // Invoked when task's progress property changes.
        public void propertyChange(PropertyChangeEvent evt) {
            if ("progress" == evt.getPropertyName()) {
                int progress = (Integer) evt.getNewValue();
                pm.setProgress(progress);
                String message = String.format("%d%%.\n", progress);
                pm.setNote(message);
                if (s.isDone()) {
                    Log("<font color='green'>" + translator.get("Finished") + "</font>\n");
                } else if (s.isCancelled() || pm.isCanceled()) {
                    if (pm.isCanceled()) {
                        s.cancel(true);
                    }
                    Log("<font color='green'>" + translator.get("Cancelled") + "</font>\n");
                }
            }
        }
    });

    s.execute();

    return true;
}

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

/**
 * @param infileName//from  w  ww  .  j  a v a2  s  .  c  o  m
 * @param outFileName
 * @param changeListener
 * @return
 */
public boolean compressFile(final String infileName, final String outFileName,
        final PropertyChangeListener propChgListener) {
    final File file = new File(infileName);
    if (file.exists()) {
        long fileSize = file.length();
        if (fileSize > 0) {
            SwingWorker<Integer, Integer> backupWorker = new SwingWorker<Integer, Integer>() {
                protected String errorMsg = null;
                protected FileInputStream fis = null;
                protected GZIPOutputStream fos = null;

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

                        long totalSize = file.length();
                        long bytesCnt = 0;

                        FileInputStream fis = new FileInputStream(infileName);
                        GZIPOutputStream fos = new GZIPOutputStream(new FileOutputStream(outFileName));

                        byte[] bytes = new byte[BUFFER_SIZE * 10];

                        while (true) {
                            int len = fis.read(bytes);
                            if (len > 0) {
                                fos.write(bytes, 0, len);
                                bytesCnt += len;
                                firePropertyChange("MEGS", 0,
                                        (int) (((double) bytesCnt / (double) totalSize) * 100.0));
                            } else {
                                break;
                            }
                        }

                        fis.close();
                        fos.close();

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

                    } finally {
                        try {
                            if (fis != null) {
                                fis.close();
                            }
                            if (fos != null) {
                                fos.close();
                            }
                        } catch (IOException ex) {
                            errorMsg = ex.toString();
                        }
                    }
                    firePropertyChange("MEGS", 0, 100);
                    return null;
                }

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

                    UIRegistry.getStatusBar().setProgressDone(HttpLargeFileTransfer.class.toString());

                    //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("Compressing Backup..."), 24);

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

        } else {
            // file doesn't exist
        }
    } else {
        // file doesn't exist
    }
    return false;
}

From source file:edu.ku.brc.specify.config.FixAttachments.java

/**
 * @param resultsHashMap/*from   w w w  . ja  v  a2 s . c  o m*/
 * @param tableHash
 * @param totalFiles
 */
private void reattachFiles(final HashMap<Integer, Vector<Object[]>> resultsHashMap,
        final HashMap<Integer, AttchTableModel> tableHash, final int totalFiles) {
    final String CNT = "CNT";
    final SwingWorker<Integer, Integer> worker = new SwingWorker<Integer, Integer>() {
        int filesCnt = 0;

        @Override
        protected Integer doInBackground() throws Exception {
            DataProviderSessionIFace session = DataProviderFactory.getInstance().createSession();
            if (session != null) {
                try {
                    for (int tblId : resultsHashMap.keySet()) {
                        AttchTableModel model = tableHash.get(tblId);
                        int cnt = 0;
                        for (int r = 0; r < model.getRowCount(); r++) {
                            if (model.isRecoverable(r)) {
                                Thread.sleep(100);

                                session.beginTransaction();
                                Integer attachID = model.getAttachmentId(r);
                                Attachment attachment = session.get(Attachment.class, attachID);
                                AttachmentUtils.getAttachmentManager()
                                        .setStorageLocationIntoAttachment(attachment, false);
                                try {
                                    attachment.storeFile(true); // false means do not display an error dialog
                                    session.saveOrUpdate(attachment);
                                    session.commit();
                                    model.setRecovered(r, true);
                                    filesCnt++;

                                } catch (IOException ex) {
                                    session.rollback();
                                }
                            }
                            cnt++;
                            firePropertyChange(CNT, 0, (int) ((double) cnt / (double) totalFiles * 100.0));
                        }
                    }
                } catch (Exception ex) {
                    session.rollback();

                } finally {
                    session.close();
                }
            }
            return null;
        }

        @Override
        protected void done() {
            UIRegistry.clearSimpleGlassPaneMsg();
            UIRegistry.displayInfoMsgDlg(String.format("Files recovered: %d / %d", filesCnt, totalFiles));

            File file = produceSummaryReport(resultsHashMap, tableHash, totalFiles);
            if (file != null) {
                try {
                    AttachmentUtils.openFile(file);
                } catch (Exception e) {
                }
            }

            if (getNumberofBadAttachments() == 0) {
                AppPreferences.getGlobalPrefs().putBoolean("CHECK_ATTCH_ERR", true);
            }
            super.done();
        }
    };

    final SimpleGlassPane glassPane = UIRegistry
            .writeSimpleGlassPaneMsg(String.format("Recovering %d files.", totalFiles), 24);
    glassPane.setProgress(0);

    worker.addPropertyChangeListener(new PropertyChangeListener() {
        public void propertyChange(final PropertyChangeEvent evt) {
            if (CNT.equals(evt.getPropertyName())) {
                glassPane.setProgress((Integer) evt.getNewValue());
            }
        }
    });

    worker.execute();
}

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

/**
 * /*from w  w  w. ja va  2  s  .c o m*/
 */
protected void createMasterUser() {
    String saUsrNm = ((JTextField) comps.get("saUserName")).getText();
    if (StringUtils.isNotEmpty(saUsrNm) && saUsrNm.equalsIgnoreCase("root")) {
        UIRegistry.showLocalizedError("MASTER_NO_ROOT");
        ((JTextField) comps.get("saUserName")).setText("");
        return;
    }

    if (!checkPermsForMasterUserCreation()) {
        return;
    }

    if (isOK == null || !isOK) {
        progressBar.setIndeterminate(true);
        progressBar.setVisible(true);

        setUIEnabled(false);

        label.setText(UIRegistry.getResourceString("CONN_DB"));

        createMUBtn.setVisible(false);

        SwingWorker<Object, Object> worker = new SwingWorker<Object, Object>() {
            @Override
            protected Object doInBackground() throws Exception {
                MasterUserPanel.this.label.setForeground(Color.BLACK);

                isOK = false;
                if (!isEmbedded) {
                    DBMSUserMgr mgr = DBMSUserMgr.getInstance();

                    String dbUserName = properties.getProperty("dbUserName");
                    String dbPassword = properties.getProperty("dbPassword");
                    String dbName = properties.getProperty("dbName");
                    String hostName = properties.getProperty("hostName");

                    String saUserName = ((JTextField) comps.get("saUserName")).getText();
                    String saPassword = ((JTextField) comps.get("saPassword")).getText();

                    if (mgr.connectToDBMS(dbUserName, dbPassword, hostName)) {

                        if (mgr.doesUserExists(saUserName)) {
                            if (!mgr.setPermissions(saUserName, dbName, DBMSUserMgr.PERM_ALL_BASIC)) {
                                errorKey = "ERR_SET_PERM";
                            } else {
                                isOK = true;
                            }
                        }

                        if (!mgr.doesUserExists(saUserName)) {
                            firePropertyChange(propName, 0, 1);

                            isOK = mgr.createUser(saUserName, saPassword, dbName, DBMSUserMgr.PERM_ALL_BASIC);
                            if (!isOK) {
                                errorKey = "ERR_CRE_MASTER";
                            } else {
                                isOK = true;
                            }
                        }
                    } else {
                        errorKey = "NO_CONN_ROOT";
                        isOK = false;
                    }

                    if (mgr != null) {
                        mgr.close();
                    }
                } else {
                    isOK = true;
                }

                return null;
            }

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

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

                setUIEnabled(true);

                updateBtnUI();

                createMUBtn.setVisible(!isOK);

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

                    SwingUtilities.invokeLater(new Runnable() {
                        @Override
                        public void run() {
                            nextBtn.doClick();
                        }
                    });

                } else {
                    label.setText(UIRegistry.getResourceString(errorKey));
                    UIRegistry.showLocalizedError(errorKey);
                }
            }
        };

        worker.addPropertyChangeListener(new PropertyChangeListener() {
            public void propertyChange(final PropertyChangeEvent evt) {
                if (propName.equals(evt.getPropertyName())) {
                    MasterUserPanel.this.label.setText(UIRegistry.getLocalizedMessage("CREATE_MASTER"));
                }
            }
        });
        worker.execute();
    }
}

From source file:edu.ku.brc.specify.tools.StrLocalizerApp.java

/**
 * //from   w  ww  .j ava2s. com
 */
private void translateNewItems() {

    //writeGlassPaneMsg(getResourceString("StrLocalizerApp.TranslatingNew"), 24);
    final String STATUSBAR_NAME = "STATUS";
    final JStatusBar statusBar = UIRegistry.getStatusBar();
    statusBar.setProgressRange(STATUSBAR_NAME, 0, 100);

    startTransMenuItem.setEnabled(false);
    stopTransMenuItem.setEnabled(true);

    final double total = newKeyList.size();

    SwingWorker<Integer, Integer> translator = new SwingWorker<Integer, Integer>() {
        @Override
        protected Integer doInBackground() throws Exception {
            int count = 0;
            for (String key : newKeyList) {
                StrLocaleEntry entry = srcFile.getItemHash().get(key);
                //if (StringUtils.contains(entry.getSrcStr(), "%") || StringUtils.contains(entry.getSrcStr(), "\n"))
                {
                    String transText = translate(entry.getSrcStr());
                    if (transText != null) {
                        entry.setDstStr(transText);
                        //writeGlassPaneMsg(String.format("%d / %d", count, newKeyList.size()), 18);
                        //System.out.println(String.format("%s - %d / %d", key, count, newKeyList.size()));
                    }
                }

                try {
                    Thread.sleep(100 + (int) (Math.random() * 100.0));
                } catch (InterruptedException ex) {
                }

                setProgress((int) (((double) count / total) * 100.0));
                System.out.println(entry.getSrcStr() + "  " + count);
                //glassPane.setProgress((int)( (100.0 * count) / total));
                count++;

                if (!contTrans.get()) {
                    return null;
                }
            }
            return null;
        }

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

            //statusBar.setIndeterminate(STATUSBAR_NAME, false);
            statusBar.setText("");
            statusBar.setProgressDone(STATUSBAR_NAME);

            UIRegistry.showLocalizedMsg("Done Localizing");

            startTransMenuItem.setEnabled(true);
            stopTransMenuItem.setEnabled(false);

        }
    };

    statusBar.setIndeterminate(STATUSBAR_NAME, true);

    translator.addPropertyChangeListener(new PropertyChangeListener() {
        public void propertyChange(final PropertyChangeEvent evt) {
            //System.out.println(evt.getPropertyName());

            if ("progress".equals(evt.getPropertyName())) {
                statusBar.setText(String.format("%d / 100 ", (Integer) evt.getNewValue()) + "%");
            }
        }
    });
    translator.execute();
}

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

/**
 * /*from www .  j av a2 s . c  o  m*/
 */
@SuppressWarnings("unchecked")
protected void exportSchemaLocales() {
    FileDialog dlg = new FileDialog(((Frame) UIRegistry.getTopWindow()), getResourceString("Save"),
            FileDialog.SAVE);
    dlg.setVisible(true);

    String fileName = dlg.getFile();
    if (fileName != null) {
        final File outFile = new File(dlg.getDirectory() + File.separator + fileName);
        //final File    outFile = new File("xxx.xml");

        final SimpleGlassPane glassPane = new SimpleGlassPane(getResourceString("SL_EXPORT_SCHEMA"), 18);
        glassPane.setBarHeight(12);
        glassPane.setFillColor(new Color(0, 0, 0, 85));

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

        SwingWorker<Integer, Integer> backupWorker = new SwingWorker<Integer, Integer>() {
            @Override
            protected Integer doInBackground() throws Exception {

                DataProviderSessionIFace session = null;
                try {
                    session = DataProviderFactory.getInstance().createSession();

                    int dispId = AppContextMgr.getInstance().getClassObject(Discipline.class).getDisciplineId();
                    String sql = String.format(
                            "FROM SpLocaleContainer WHERE disciplineId = %d AND schemaType = %d", dispId,
                            schemaType);
                    List<SpLocaleContainer> spContainers = (List<SpLocaleContainer>) session.getDataList(sql);
                    try {
                        FileWriter fw = new FileWriter(outFile);

                        //fw.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<vector>\n");
                        fw.write("<vector>\n");

                        BeanWriter beanWriter = new BeanWriter(fw);
                        XMLIntrospector introspector = beanWriter.getXMLIntrospector();
                        introspector.getConfiguration().setWrapCollectionsInElement(true);
                        beanWriter.getBindingConfiguration().setMapIDs(false);
                        beanWriter.setWriteEmptyElements(false);

                        beanWriter.enablePrettyPrint();

                        double step = 100.0 / (double) spContainers.size();
                        double total = 0.0;
                        for (SpLocaleContainer container : spContainers) {
                            // force Load of lazy collections
                            container.getDescs().size();
                            container.getNames().size();

                            // Leaving this Code as an example of specifying the bewtixt file.
                            /*InputStream inputStream = Specify.class.getResourceAsStream("datamodel/SpLocaleContainer.betwixt");
                            //InputStream inputStream = Specify.class.getResourceAsStream("/edu/ku/brc/specify/tools/schemalocale/SpLocaleContainer.betwixt");
                            InputSource inputSrc    = new InputSource(inputStream); 
                            beanWriter.write(container, inputSrc);
                            inputStream.close(); */

                            beanWriter.write(container);

                            total += step;
                            firePropertyChange("progress", 0, (int) total);
                        }

                        fw.write("</vector>\n");
                        fw.close();

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

                } catch (Exception e) {
                    edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
                    edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(SchemaLocalizerDlg.class, e);
                    e.printStackTrace();

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

                return null;
            }

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

                glassPane.setVisible(false);
            }
        };

        backupWorker.addPropertyChangeListener(new PropertyChangeListener() {
            public void propertyChange(final PropertyChangeEvent evt) {
                if (evt.getPropertyName().equals("progress")) {
                    glassPane.setProgress((Integer) evt.getNewValue());
                }
            }
        });
        backupWorker.execute();
    }
}

From source file:edu.ku.brc.specify.tasks.subpane.images.ImagesPane.java

/**
 * //from www. j  a  va  2  s  . c  om
 */
private void searchForRecordSetAttachments() {
    final String MEGS = "MEGS";
    final String STATUSBAR_NAME = "ImageSearchStatusBar";

    rowsVector.clear();
    items = recordSet.getOrderedItems();

    final int numItems = items.size();

    SwingWorker<Integer, Integer> backupWorker = new SwingWorker<Integer, Integer>() {
        @Override
        protected Integer doInBackground() throws Exception {
            final DBTableInfo ti = DBTableIdMgr.getInstance().getInfoById(recordSet.getDbTableId());

            boolean isAttachmentTableItself = ti.getTableId() == Attachment.getClassTableId();

            String sql;
            if (!isAttachmentTableItself) {
                sql = "SELECT a.AttachmentID, a.TableID, a.Title, a.AttachmentLocation, a.MimeType FROM attachment a "
                        + "INNER JOIN %sattachment coa ON a.AttachmentID = coa.AttachmentID "
                        + "WHERE coa.%s IN (%s) %s ORDER BY FIELD(%s, %s)";
            } else {
                sql = "SELECT a.AttachmentID, a.TableID, a.Title, a.AttachmentLocation, a.MimeType FROM attachment a "
                        + "WHERE AttachmentID IN (%s) ORDER BY FIELD(a.AttachmentID, %s)";
            }

            int batchSize = 500;
            int attchIndex = 0;
            int batches = (numItems / batchSize) + (numItems % batchSize == 0 ? 0 : 1);
            if (numItems < batchSize) {
                batchSize = numItems;
            }

            Statement stmt = null;
            try {
                stmt = DBConnection.getInstance().getConnection().createStatement();

                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < batches; i++) {
                    firePropertyChange(MEGS, 0, i + 1);
                    sb.setLength(0);
                    for (int j = 0; j < batchSize && attchIndex < numItems; j++) {
                        RecordSetItemIFace rsi = items.get(attchIndex++);
                        if (j > 0)
                            sb.append(',');
                        sb.append(rsi.getRecordId().toString());
                    }

                    String filter = getFilterString();
                    if (StringUtils.isNotEmpty(filter)) {
                        filter = " AND " + filter;
                    }

                    String fullSQL;
                    if (!isAttachmentTableItself) {
                        fullSQL = String.format(sql, ti.getName(), ti.getIdColumnName(), sb.toString(), filter,
                                ti.getIdColumnName(), sb.toString());
                    } else {
                        fullSQL = String.format(sql, sb.toString(), filter, sb.toString());
                    }
                    log.debug(fullSQL);
                    ResultSet rs = stmt.executeQuery(fullSQL);
                    while (rs.next()) {
                        ImageDataItem imgDataItem = new ImageDataItem(rs.getInt(1), rs.getInt(2),
                                rs.getString(3), rs.getString(4), rs.getString(5));
                        rowsVector.add(imgDataItem);
                    }
                    rs.close();
                }

            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    if (stmt != null)
                        stmt.close();
                } catch (Exception e) {
                }
            }
            return null;
        }

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

            getStatusBar().setProgressDone(STATUSBAR_NAME);
            clearSimpleGlassPaneMsg();

            if (rowsVector != null && rowsVector.size() > 0) {
                gridPanel.setItemList(rowsVector);
                JScrollPane sb = new JScrollPane(gridPanel, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
                        JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
                add(sb, BorderLayout.CENTER);

                ((AttachmentsTask) task).attachmentSearchDone(ImagesPane.this);

            } else {
                ((AttachmentsTask) task).attachmentSearchDone(null);
                writeTimedSimpleGlassPaneMsg(getNotFoundMessage());
            }
        }
    };

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

    writeSimpleGlassPaneMsg(getResourceString("ATTCH_SEARCH_IMGS"), 24);

    backupWorker.addPropertyChangeListener(new PropertyChangeListener() {
        public void propertyChange(final PropertyChangeEvent evt) {
            if (MEGS.equals(evt.getPropertyName())) {
                Integer value = (Integer) evt.getNewValue();
                int val = (int) (((double) value / (double) numItems) * 100.0);
                statusBar.setText(Integer.toString(val));//getLocalizedMessage("MySQLBackupService.BACKUP_MEGS", val));
            }
        }
    });
    backupWorker.execute();
}

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

/**
 * @param fileName/*from   w  w  w.  j  av  a2s.  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
    }
}