Search in sources :

Example 11 with SwingWorker

use of javax.swing.SwingWorker in project sic by belluccifranco.

the class CajasGUI method buscar.

private void buscar() {
    cambiarEstadoEnabled(false);
    pb_barra.setIndeterminate(true);
    SwingWorker<List<Caja>, Void> worker = new SwingWorker<List<Caja>, Void>() {

        @Override
        protected List<Caja> doInBackground() throws Exception {
            String criteria = "/cajas/busqueda/criteria?";
            if (chk_Fecha.isSelected()) {
                criteria += "desde=" + dc_FechaDesde.getDate().getTime() + "&hasta=" + dc_FechaHasta.getDate().getTime();
            }
            if (chk_Usuario.isSelected()) {
                criteria += "&idUsuario=" + ((Usuario) cmb_Usuarios.getSelectedItem()).getId_Usuario();
            }
            criteria += "&idEmpresa=" + EmpresaActiva.getInstance().getEmpresa().getId_Empresa();
            cajas = new ArrayList(Arrays.asList(RestClient.getRestTemplate().getForObject(criteria, Caja[].class)));
            cargarResultadosAlTable();
            cambiarEstadoEnabled(true);
            return cajas;
        }

        @Override
        protected void done() {
            pb_barra.setIndeterminate(false);
            try {
                if (get().isEmpty()) {
                    JOptionPane.showInternalMessageDialog(getParent(), ResourceBundle.getBundle("Mensajes").getString("mensaje_busqueda_sin_resultados"), "Aviso", JOptionPane.INFORMATION_MESSAGE);
                }
            } catch (InterruptedException ex) {
                String msjError = "La tarea que se estaba realizando fue interrumpida. Intente nuevamente.";
                LOGGER.error(msjError + " - " + ex.getMessage());
                JOptionPane.showInternalMessageDialog(getParent(), msjError, "Error", JOptionPane.ERROR_MESSAGE);
            } catch (ExecutionException ex) {
                if (ex.getCause() instanceof RestClientResponseException) {
                    JOptionPane.showMessageDialog(getParent(), ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
                } else if (ex.getCause() instanceof ResourceAccessException) {
                    LOGGER.error(ex.getMessage());
                    JOptionPane.showMessageDialog(getParent(), ResourceBundle.getBundle("Mensajes").getString("mensaje_error_conexion"), "Error", JOptionPane.ERROR_MESSAGE);
                } else {
                    String msjError = "Se produjo un error en la ejecuciĆ³n de la tarea solicitada. Intente nuevamente.";
                    LOGGER.error(msjError + " - " + ex.getMessage());
                    JOptionPane.showInternalMessageDialog(getParent(), msjError, "Error", JOptionPane.ERROR_MESSAGE);
                }
                cambiarEstadoEnabled(true);
            }
        }
    };
    worker.execute();
}
Also used : Usuario(sic.modelo.Usuario) ArrayList(java.util.ArrayList) SwingWorker(javax.swing.SwingWorker) Caja(sic.modelo.Caja) EstadoCaja(sic.modelo.EstadoCaja) ArrayList(java.util.ArrayList) List(java.util.List) RestClientResponseException(org.springframework.web.client.RestClientResponseException) ExecutionException(java.util.concurrent.ExecutionException) ResourceAccessException(org.springframework.web.client.ResourceAccessException)

Example 12 with SwingWorker

use of javax.swing.SwingWorker in project beast-mcmc by beast-dev.

the class MainFrame method generateNumberOfSimulations.

// END: doExport
// threading, UI, exceptions handling
private void generateNumberOfSimulations(final File outFile) {
    setBusy();
    SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() {

        ArrayList<TreeModel> simulatedTreeModelList = new ArrayList<TreeModel>();

        // Executed in background thread
        public Void doInBackground() {
            try {
                if (BeagleSequenceSimulatorApp.VERBOSE) {
                    Utils.printPartitionDataList(dataList);
                    System.out.println();
                }
                long startingSeed = dataList.startingSeed;
                for (int i = 0; i < dataList.simulationsCount; i++) {
                    String fullPath = Utils.getMultipleWritePath(outFile, dataList.outputFormat.toString().toLowerCase(), i);
                    PrintWriter writer = new PrintWriter(new FileWriter(fullPath));
                    ArrayList<Partition> partitionsList = new ArrayList<Partition>();
                    for (PartitionData data : dataList) {
                        if (data.record == null) {
                            writer.close();
                            throw new RuntimeException("Set data in Partitions tab for " + (partitionsList.size() + 1) + " partition.");
                        } else {
                            TreeModel treeModel = data.createTreeModel();
                            simulatedTreeModelList.add(treeModel);
                            // create partition
                            Partition partition = new Partition(//
                            treeModel, //
                            data.createBranchModel(), //
                            data.createSiteRateModel(), //
                            data.createClockRateModel(), //
                            data.createFrequencyModel(), // from
                            data.from - 1, // to
                            data.to - 1, // every
                            data.every);
                            if (data.ancestralSequenceString != null) {
                                partition.setRootSequence(data.createAncestralSequence());
                            }
                            partitionsList.add(partition);
                        }
                    }
                    if (dataList.setSeed) {
                        MathUtils.setSeed(startingSeed);
                        startingSeed += 1;
                    }
                    beagleSequenceSimulator = new BeagleSequenceSimulator(partitionsList);
                    SimpleAlignment alignment = beagleSequenceSimulator.simulate(dataList.useParallel, dataList.outputAncestralSequences);
                    alignment.setOutputType(dataList.outputFormat);
                    //                        if (dataList.outputFormat == SimpleAlignment.OutputType.NEXUS) {
                    //                            alignment.setOutputType(dataList.outputFormat);
                    //                        } else if(dataList.outputFormat == SimpleAlignment.OutputType.XML) {
                    //                        	alignment.setOutputType(dataList.outputFormat);
                    //                        }else {
                    //                        	//
                    //                        }
                    writer.println(alignment.toString());
                    writer.close();
                }
            // END: simulationsCount loop
            } catch (Exception e) {
                Utils.handleException(e);
                setStatus("Exception occured.");
                setIdle();
            }
            return null;
        }

        // END: doInBackground
        // Executed in event dispatch thread
        public void done() {
            //            	LinkedHashMap<Integer, LinkedHashMap<NodeRef, int[]>> partitionSequencesMap = beagleSequenceSimulator.getPartitionSequencesMap();
            terminalPanel.setText(Utils.partitionDataListToString(dataList, simulatedTreeModelList));
            setStatus("Generated " + Utils.getSiteCount(dataList) + " sites.");
            setIdle();
        }
    };
    worker.execute();
}
Also used : Partition(dr.app.beagle.tools.Partition) FileWriter(java.io.FileWriter) ArrayList(java.util.ArrayList) BeagleSequenceSimulator(dr.app.beagle.tools.BeagleSequenceSimulator) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException) TreeModel(dr.evomodel.tree.TreeModel) SimpleAlignment(dr.evolution.alignment.SimpleAlignment) SwingWorker(javax.swing.SwingWorker) PrintWriter(java.io.PrintWriter)

Example 13 with SwingWorker

use of javax.swing.SwingWorker in project sic by belluccifranco.

the class FacturasCompraGUI method buscar.

private void buscar() {
    pb_Filtro.setIndeterminate(true);
    this.cambiarEstadoEnabled(false);
    SwingWorker<List<FacturaCompra>, Void> worker = new SwingWorker<List<FacturaCompra>, Void>() {

        @Override
        protected List<FacturaCompra> doInBackground() throws Exception {
            String criteria = "idEmpresa=" + EmpresaActiva.getInstance().getEmpresa().getId_Empresa();
            if (chk_Fecha.isSelected()) {
                criteria += "&desde=" + dc_FechaDesde.getDate().getTime();
                criteria += "&hasta=" + dc_FechaHasta.getDate().getTime();
            }
            if (chk_Proveedor.isSelected()) {
                criteria += "&idProveedor=" + ((Proveedor) cmb_Proveedor.getSelectedItem()).getId_Proveedor();
            }
            if (chk_NumFactura.isSelected()) {
                txt_SerieFactura.commitEdit();
                txt_NroFactura.commitEdit();
                criteria += "&nroSerie=" + Integer.valueOf(txt_SerieFactura.getValue().toString()) + "&nroFactura=" + Integer.valueOf(txt_NroFactura.getValue().toString());
            }
            if (chk_estadoFactura.isSelected() && rb_soloImpagas.isSelected()) {
                criteria += "&soloImpagas=true";
            }
            if (chk_estadoFactura.isSelected() && rb_soloPagadas.isSelected()) {
                criteria += "&soloPagas=true";
            }
            facturas = new ArrayList(Arrays.asList(RestClient.getRestTemplate().getForObject("/facturas/compra/busqueda/criteria?" + criteria, FacturaCompra[].class)));
            cargarResultadosAlTable();
            calcularResultados(criteria);
            return facturas;
        }

        @Override
        protected void done() {
            pb_Filtro.setIndeterminate(false);
            try {
                if (get().isEmpty()) {
                    JOptionPane.showMessageDialog(getParent(), ResourceBundle.getBundle("Mensajes").getString("mensaje_busqueda_sin_resultados"), "Aviso", JOptionPane.INFORMATION_MESSAGE);
                }
            } catch (InterruptedException ex) {
                String msjError = "La tarea que se estaba realizando fue interrumpida. Intente nuevamente.";
                LOGGER.error(msjError + " - " + ex.getMessage());
                JOptionPane.showInternalMessageDialog(getParent(), msjError, "Error", JOptionPane.ERROR_MESSAGE);
                cambiarEstadoEnabled(true);
            } catch (ExecutionException ex) {
                if (ex.getCause() instanceof RestClientResponseException) {
                    JOptionPane.showMessageDialog(getParent(), ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
                    cambiarEstadoEnabled(true);
                } else if (ex.getCause() instanceof ResourceAccessException) {
                    LOGGER.error(ex.getMessage());
                    JOptionPane.showMessageDialog(getParent(), ResourceBundle.getBundle("Mensajes").getString("mensaje_error_conexion"), "Error", JOptionPane.ERROR_MESSAGE);
                    cambiarEstadoEnabled(true);
                } else {
                    String msjError = "Se produjo un error en la ejecuciĆ³n de la tarea solicitada. Intente nuevamente.";
                    LOGGER.error(msjError + " - " + ex.getMessage());
                    JOptionPane.showInternalMessageDialog(getParent(), msjError, "Error", JOptionPane.ERROR_MESSAGE);
                    cambiarEstadoEnabled(true);
                }
            }
            cambiarEstadoEnabled(true);
        }
    };
    worker.execute();
}
Also used : Proveedor(sic.modelo.Proveedor) ArrayList(java.util.ArrayList) SwingWorker(javax.swing.SwingWorker) ArrayList(java.util.ArrayList) List(java.util.List) RestClientResponseException(org.springframework.web.client.RestClientResponseException) ExecutionException(java.util.concurrent.ExecutionException) ResourceAccessException(org.springframework.web.client.ResourceAccessException) FacturaCompra(sic.modelo.FacturaCompra)

Example 14 with SwingWorker

use of javax.swing.SwingWorker in project jgnash by ccavanaugh.

the class ExportTransactionsAction method exportTransactions.

public static void exportTransactions(final Account account, final LocalDate startDate, final LocalDate endDate) {
    final ResourceBundle rb = ResourceUtils.getBundle();
    final Preferences pref = Preferences.userNodeForPackage(ExportTransactionsAction.class);
    JFileChooser chooser = new JFileChooser(pref.get(CURRENT_DIR, null));
    FileNameExtensionFilter csvFilter = new FileNameExtensionFilter(rb.getString("Label.CsvFiles") + " (*.csv)", "csv");
    FileNameExtensionFilter ofxFilter = new FileNameExtensionFilter(rb.getString("Label.OfxFiles") + " (*.ofx)", OFX);
    FileNameExtensionFilter ssFilter = new FileNameExtensionFilter(rb.getString("Label.SpreadsheetFiles") + " (*.xls, *.xlsx)", "xls", "xlsx");
    chooser.addChoosableFileFilter(csvFilter);
    chooser.addChoosableFileFilter(ofxFilter);
    chooser.addChoosableFileFilter(ssFilter);
    chooser.setAcceptAllFileFilterUsed(false);
    chooser.setMultiSelectionEnabled(false);
    chooser.setFileFilter(csvFilter);
    if (chooser.showSaveDialog(UIApplication.getFrame()) == JFileChooser.APPROVE_OPTION) {
        pref.put(CURRENT_DIR, chooser.getCurrentDirectory().getAbsolutePath());
        final File file = chooser.getSelectedFile();
        final class Export extends SwingWorker<Void, Void> {

            @Override
            protected Void doInBackground() throws Exception {
                UIApplication.getFrame().displayWaitMessage(rb.getString("Message.PleaseWait"));
                if (OFX.equals(FileUtils.getFileExtension(file.getName()))) {
                    OfxExport export = new OfxExport(account, startDate, endDate, file);
                    export.exportAccount();
                } else if (FileUtils.getFileExtension(file.getName()).contains(XLS)) {
                    AccountExport.exportAccount(account, RegisterFactory.getColumnNames(account), startDate, endDate, file);
                } else {
                    CsvExport.exportAccount(account, startDate, endDate, file);
                }
                return null;
            }

            @Override
            protected void done() {
                UIApplication.getFrame().stopWaitMessage();
            }
        }
        new Export().execute();
    }
}
Also used : JFileChooser(javax.swing.JFileChooser) SwingWorker(javax.swing.SwingWorker) CsvExport(jgnash.convert.exports.csv.CsvExport) AccountExport(jgnash.convert.exports.ssf.AccountExport) OfxExport(jgnash.convert.exports.ofx.OfxExport) ResourceBundle(java.util.ResourceBundle) OfxExport(jgnash.convert.exports.ofx.OfxExport) Preferences(java.util.prefs.Preferences) FileNameExtensionFilter(javax.swing.filechooser.FileNameExtensionFilter) File(java.io.File)

Example 15 with SwingWorker

use of javax.swing.SwingWorker in project jgnash by ccavanaugh.

the class NewFileDialog method showDialog.

public static void showDialog(final Frame parent) {
    final class Setup extends SwingWorker<Void, Void> {

        NewFileDialog d;

        public Setup(NewFileDialog dialog) {
            d = dialog;
        }

        @SuppressWarnings("unchecked")
        @Override
        protected Void doInBackground() throws Exception {
            final ResourceBundle rb = ResourceUtils.getBundle();
            UIApplication.getFrame().displayWaitMessage(rb.getString("Message.PleaseWait"));
            final String database = (String) d.getSetting(Settings.DATABASE_NAME);
            final Set<CurrencyNode> nodes = (Set<CurrencyNode>) d.getSetting(Settings.CURRENCIES);
            final CurrencyNode defaultCurrency = (CurrencyNode) d.getSetting(Settings.DEFAULT_CURRENCY);
            final DataStoreType type = (DataStoreType) d.getSetting(Settings.TYPE);
            final String password = (String) d.getSetting(Settings.PASSWORD);
            final List<RootAccount> accountList = (List<RootAccount>) d.getSetting(Settings.ACCOUNT_SET);
            try {
                NewFileUtility.buildNewFile(database, type, password.toCharArray(), defaultCurrency, nodes, accountList);
                // force a save and reload of the file
                EngineFactory.closeEngine(EngineFactory.DEFAULT);
                EngineFactory.bootLocalEngine(database, EngineFactory.DEFAULT, password.toCharArray());
            } catch (final IOException e) {
                StaticUIMethods.displayError(e.getMessage());
            }
            return null;
        }

        @Override
        protected void done() {
            UIApplication.getFrame().stopWaitMessage();
        }
    }
    class DisplayDialog extends SwingWorker<Set<CurrencyNode>, Object> {

        @Override
        public Set<CurrencyNode> doInBackground() {
            return DefaultCurrencies.generateCurrencies();
        }

        @Override
        protected void done() {
            try {
                NewFileDialog d = new NewFileDialog(parent);
                d.setSetting(NewFileDialog.Settings.DEFAULT_CURRENCIES, get());
                d.setSetting(NewFileDialog.Settings.DATABASE_NAME, EngineFactory.getDefaultDatabase());
                d.addTaskPage(new NewFileOne());
                d.addTaskPage(new NewFileTwo());
                d.addTaskPage(new NewFileThree());
                d.addTaskPage(new NewFileFour());
                d.addTaskPage(new NewFileSummary());
                d.setLocationRelativeTo(parent);
                d.setVisible(true);
                if (d.isWizardValid()) {
                    new Setup(d).execute();
                }
            } catch (InterruptedException | ExecutionException e) {
                Logger.getLogger(DisplayDialog.class.getName()).log(Level.SEVERE, null, e);
            }
        }
    }
    new DisplayDialog().execute();
}
Also used : CurrencyNode(jgnash.engine.CurrencyNode) Set(java.util.Set) IOException(java.io.IOException) DataStoreType(jgnash.engine.DataStoreType) RootAccount(jgnash.engine.RootAccount) SwingWorker(javax.swing.SwingWorker) ResourceBundle(java.util.ResourceBundle) List(java.util.List) ExecutionException(java.util.concurrent.ExecutionException)

Aggregations

SwingWorker (javax.swing.SwingWorker)41 ExecutionException (java.util.concurrent.ExecutionException)15 IOException (java.io.IOException)14 List (java.util.List)10 ResourceBundle (java.util.ResourceBundle)10 ArrayList (java.util.ArrayList)9 Preferences (java.util.prefs.Preferences)8 File (java.io.File)6 JFileChooser (javax.swing.JFileChooser)6 JPanel (javax.swing.JPanel)6 BorderLayout (java.awt.BorderLayout)5 FileNameExtensionFilter (javax.swing.filechooser.FileNameExtensionFilter)5 Engine (jgnash.engine.Engine)5 FileNotFoundException (java.io.FileNotFoundException)4 InstanceNotFoundException (javax.management.InstanceNotFoundException)4 IntrospectionException (javax.management.IntrospectionException)4 MBeanInfo (javax.management.MBeanInfo)4 ReflectionException (javax.management.ReflectionException)4 JScrollPane (javax.swing.JScrollPane)4 ResourceAccessException (org.springframework.web.client.ResourceAccessException)4