Example usage for org.eclipse.jface.operation IRunnableWithProgress IRunnableWithProgress

List of usage examples for org.eclipse.jface.operation IRunnableWithProgress IRunnableWithProgress

Introduction

In this page you can find the example usage for org.eclipse.jface.operation IRunnableWithProgress IRunnableWithProgress.

Prototype

IRunnableWithProgress

Source Link

Usage

From source file:ch.elexis.core.ui.commands.BillingProposalViewCreateBillsHandler.java

License:Open Source License

@Override
public Object execute(ExecutionEvent event) throws ExecutionException {
    List<Konsultation> kons = getToBill(event);
    final List<Konsultation> toBill = BillingUtil.getKonsultationsFromSameYear(kons);
    if (toBill.size() > 0 && toBill.size() != kons.size()) {
        if (!MessageDialog.openQuestion(HandlerUtil.getActiveShell(event), "Rechnung Validierung",
                "Eine Rechnung kann nur Leistungen innerhalb eines Jahres beinhalten.\n\nWollen Sie mit der Erstellung der Rechnung fr das Jahr "
                        + new TimeTool(toBill.get(0).getDatum()).get(TimeTool.YEAR) + " fortsetzen ?")) {
            LoggerFactory.getLogger(BillingProposalViewCreateBillsHandler.class)
                    .warn("Invoice creation canceled by user");
            return null;
        }//from   w  w w . jav  a  2  s .co m
    }

    ProgressMonitorDialog dialog = new ProgressMonitorDialog(HandlerUtil.getActiveShell(event));
    try {
        dialog.run(true, false, new IRunnableWithProgress() {

            private int successful = 0;
            private int errorneous = 0;
            private StringBuilder errorneousInfo = new StringBuilder();

            @Override
            public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
                monitor.beginTask("Rechnungen erstellen", 3);
                List<Konsultation> billable = BillingUtil.filterNotBillable(toBill);
                monitor.worked(1);
                Map<Rechnungssteller, Map<Fall, List<Konsultation>>> toBillMap = BillingUtil
                        .getGroupedBillable(billable);
                monitor.worked(1);
                // create all bills
                List<Result<Rechnung>> results = BillingUtil.createBills(toBillMap);
                // build information to show
                for (Result<Rechnung> result : results) {
                    if (result.isOK()) {
                        successful++;
                    } else {
                        errorneousInfo.append(result.getSeverity()).append(" -> ");
                        List<Result<Rechnung>.msg> messages = result.getMessages();
                        for (int i = 0; i < messages.size(); i++) {
                            if (i > 0) {
                                errorneousInfo.append(" / ");
                            }
                            errorneousInfo.append(messages.get(i).getText());
                        }
                        errorneousInfo.append("\n");
                        errorneous++;
                    }
                }
                monitor.worked(1);
                monitor.done();
                // show information
                Display.getDefault().syncExec(new Runnable() {
                    @Override
                    public void run() {
                        MessageDialog.openInformation(HandlerUtil.getActiveShell(event), "Info",
                                MessageFormat.format(
                                        "Es wurden {0} Rechnungen erfolgreich erstellt.\nBei {1} Rechnungen traten Fehler auf.\n{2}",
                                        successful, errorneous, errorneousInfo.toString()));
                    }
                });
            }
        });
    } catch (InvocationTargetException | InterruptedException e) {
        MessageDialog.openError(HandlerUtil.getActiveShell(event), "Fehler",
                "Fehler beim Ausfhren der Rechnungserstelltung. Details siehe Log.");
        LoggerFactory.getLogger(BillingProposalViewCreateBillsHandler.class).error("Error creating bills", e);
        return null;
    }

    return null;
}

From source file:ch.elexis.core.ui.stock.dialogs.ImportArticleDialog.java

License:Open Source License

private void runImport(StringBuffer buf, final List<String> storeIds, final Stock stock, ExcelWrapper xl,
        boolean overrideStockEntries) {
    ProgressMonitorDialog progress = new ProgressMonitorDialog(getShell());
    try {//from   w  w  w  .j a  va 2  s.c  o  m
        progress.run(true, true, new IRunnableWithProgress() {
            public void run(IProgressMonitor monitor) {

                int importCount = 0;
                int articleNotFoundByGtin = 0;
                int articleNotFoundInStock = 0;
                int unexpectedErrors = 0;
                int lastRow = xl.getLastRow();
                int firstRow = xl.getFirstRow() + 1; //header offset
                monitor.beginTask("Artikel in Lager Import", 100);

                for (int i = firstRow; i <= lastRow; i++) {
                    Optional<? extends IArticle> opArticle = Optional.empty();
                    List<String> row = xl.getRow(i);
                    String stockCount = row.get(0);
                    String articleName = row.get(1);
                    String gtin = row.get(6);
                    String stockMin = null;
                    String stockMax = null;
                    if (row.size() > 8) {
                        stockMin = row.get(8);
                    }
                    if (row.size() > 9) {
                        stockMax = row.get(9);
                    }

                    // search for article
                    for (String storeId : storeIds) {
                        opArticle = ArticleServiceHolder.getService(storeId).get().findAnyByGTIN(gtin);
                    }

                    if (opArticle.isPresent()) {
                        // check if article is present in stock
                        IStockEntry stockEntry = CoreHub.getStockService().findStockEntryForArticleInStock(
                                stock, ((Artikel) opArticle.get()).storeToString());

                        String result = "MODIFY";
                        if (stockEntry == null) {
                            PersistentObject article = (PersistentObject) opArticle.get();
                            stockEntry = CoreHub.getStockService().storeArticleInStock(stock,
                                    article.storeToString());
                            result = "ADDITION";
                        }

                        if (stockEntry instanceof StockEntry) {
                            StockEntry poStockEntry = (StockEntry) stockEntry;
                            if (CoreHub.getLocalLockService().acquireLock(poStockEntry).isOk()) {
                                // do import
                                stockEntry.setCurrentStock(overrideStockEntries
                                        ? StringTool.parseSafeInt(stockCount)
                                        : (StringTool.parseSafeInt(stockCount) + stockEntry.getCurrentStock()));
                                if (stockMin != null) {
                                    stockEntry.setMinimumStock(StringTool.parseSafeInt(stockMin));
                                }
                                if (stockMax != null) {
                                    stockEntry.setMaximumStock(StringTool.parseSafeInt(stockMax));
                                }
                                importCount++;
                                addToReport("OK " + result + " '" + stock.getLabel() + "'", articleName, gtin);
                                CoreHub.getLocalLockService().releaseLock(poStockEntry);
                            } else {
                                addToReport("NO LOCK", articleName, gtin);
                                unexpectedErrors++;
                            }
                        } else {
                            addToReport("Not in Stock '" + stock.getLabel() + "'", articleName, gtin);
                            articleNotFoundInStock++;
                        }
                    } else {
                        articleNotFoundByGtin++;
                        addToReport("Not found by GTIN", articleName, gtin);
                    }

                    monitor.worked(1);
                    if (monitor.isCanceled()) {
                        buf.append("Der Import wurde durch den Benutzer abgebrochen.");
                        break;
                    }
                }

                buf.append(lastRow);
                buf.append(" Artikel gelesen.");
                buf.append("\n");
                buf.append("\n");
                buf.append(importCount);
                buf.append(" Artikel erfolgreich nach Lager '");
                buf.append(stock.getLabel());
                buf.append("' importiert.");
                buf.append("\n");
                if (articleNotFoundInStock > 0) {
                    buf.append("\n");
                    buf.append(articleNotFoundInStock);
                    buf.append(" Artikel nicht im Lager '");
                    buf.append(stock.getLabel());
                    buf.append("' vorhanden.");
                }

                if (articleNotFoundByGtin > 0) {
                    buf.append("\n");
                    buf.append(articleNotFoundByGtin);
                    buf.append(" Artikel nicht in der Datenbank gefunden.");
                }
                if (unexpectedErrors > 0) {
                    buf.append("\n");
                    buf.append(unexpectedErrors);
                    buf.append(" Artikel konnten nicht verarbeitet werden.");
                }
            }

        });
    } catch (InvocationTargetException | InterruptedException e) {
        LoggerFactory.getLogger(ImportArticleDialog.class).warn("Exception during article to lager import.", e);
    }
}

From source file:ch.elexis.core.ui.util.KGDrucker.java

License:Open Source License

public void doPrint(Patient pat) {
    this.patient = pat;
    kgPage = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
    IProgressService progressService = PlatformUI.getWorkbench().getProgressService();

    try {/*w w w  . j  av  a  2s .  c  o m*/
        kgp = (KGPrintView) kgPage.showView(KGPrintView.ID);
        progressService.runInUI(PlatformUI.getWorkbench().getProgressService(), new IRunnableWithProgress() {
            public void run(IProgressMonitor monitor) {
                monitor.beginTask(Messages.KGDrucker_printEMR, 1); //$NON-NLS-1$
                // gw 23.7.2006 an neues Selectionmodell angepasst
                Patient actPatient = ElexisEventDispatcher.getSelectedPatient();
                if (kgp.doPrint(actPatient, monitor) == false) {
                    ErrorDialog.openError(null, Messages.KGDrucker_errorPrinting,
                            Messages.KGDrucker_couldntprint + patient.getLabel() + Messages.KGDrucker_emr,
                            null); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$

                }

                monitor.done();
            }
        }, null);

        kgPage.hideView(kgp);

    } catch (Exception ex) {
        ElexisStatus status = new ElexisStatus(ElexisStatus.ERROR, Hub.PLUGIN_ID, ElexisStatus.CODE_NONE,
                Messages.KGDrucker_errorPrinting + ": " + Messages.KGDrucker_couldntShow, ex);
        StatusManager.getManager().handle(status);
    }
}

From source file:ch.elexis.core.ui.util.SqlWithUiRunner.java

License:Open Source License

public boolean runSql() {
    sql = new ArrayList<UpdateDbSql>();
    // create UpdateDbSql objects from input list
    for (String sqlString : sqlStrings) {
        sql.add(new UpdateDbSql(sqlString));
    }/*from  w w w  . j  a  va 2  s . com*/
    // run the update with progress in the UI Thread if a Display is available ...
    if (isDisplayAvailable()) {
        Display.getDefault().syncExec(new Runnable() {
            @Override
            public void run() {
                Shell parent = null;
                try {
                    parent = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell();
                } catch (IllegalStateException e) {
                    // the workbench has not been created yet ... create a dummy Shell on the
                    // display
                    parent = new Shell(Display.getDefault());
                } catch (NullPointerException e) {
                    // the workbench has not been created yet ... create a dummy Shell on the
                    // display
                    parent = new Shell(Display.getDefault());
                }
                ProgressMonitorDialog dialog = new ProgressMonitorDialog(parent);
                try {
                    dialog.run(true, false, new IRunnableWithProgress() {
                        @Override
                        public void run(IProgressMonitor monitor) {
                            monitor.beginTask("Running DB Script", sql.size());
                            for (UpdateDbSql update : sql) {
                                monitor.subTask(update.getSql());
                                update.run();
                                // worked increates the monitor, the values is added to the
                                // existing ones
                                monitor.worked(1);
                            }
                            monitor.done();
                        }
                    });
                } catch (InvocationTargetException e) {
                    e.printStackTrace();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
    } else {
        // this code should only be reached during tests!
        for (UpdateDbSql update : sql) {
            update.run();
        }
    }
    // determine if all updates were successful
    for (UpdateDbSql update : sql) {
        if (update.getStatus() == SqlStatus.FAIL)
            return false;
    }
    return true;
}

From source file:ch.elexis.core.ui.util.TemplateDrucker.java

License:Open Source License

public void doPrint(Patient pat) {
    this.patient = pat;
    page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
    IProgressService progressService = PlatformUI.getWorkbench().getProgressService();

    try {/*from ww w.  j a v  a  2s. c o m*/
        tpw = (TemplatePrintView) page.showView(TemplatePrintView.ID);
        progressService.runInUI(PlatformUI.getWorkbench().getProgressService(), new IRunnableWithProgress() {
            public void run(IProgressMonitor monitor) {
                monitor.beginTask(Messages.TemplateDrucker_printing + template + "...", 1); //$NON-NLS-1$

                Patient actPatient = (Patient) ElexisEventDispatcher.getSelected(Patient.class);
                if (tpw.doPrint(actPatient, template, printer, tray, monitor) == false) {
                    Status status = new Status(Status.ERROR, "ch.elexis", Status.ERROR,
                            Messages.TemplateDrucker_errorPrinting, null);
                    ErrorDialog.openError(null, Messages.TemplateDrucker_errorPrinting,
                            Messages.TemplateDrucker_docname + template + Messages.TemplateDrucker_couldntPrint,
                            status); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$

                }

                monitor.done();
            }
        }, null);

        page.hideView(tpw);

    } catch (Exception ex) {
        ElexisStatus status = new ElexisStatus(ElexisStatus.ERROR, Hub.PLUGIN_ID, ElexisStatus.CODE_NONE,
                Messages.TemplateDrucker_errorPrinting + ": " + Messages.TemplateDrucker_couldntOpen, ex);
        StatusManager.getManager().handle(status);
    }
}

From source file:ch.elexis.core.ui.views.MediVerlaufView.java

License:Open Source License

public void reload() {
    IProgressService progressService = PlatformUI.getWorkbench().getProgressService();
    try {/*from  www. ja va  2s.  c  om*/
        progressService.runInUI(PlatformUI.getWorkbench().getProgressService(), new IRunnableWithProgress() {
            public void run(final IProgressMonitor monitor)
                    throws InvocationTargetException, InterruptedException {
                Patient sp = ElexisEventDispatcher.getSelectedPatient();
                if (sp == null) {
                    return;
                }

                monitor.beginTask(Messages.MediVerlaufView_reading, IProgressMonitor.UNKNOWN); //$NON-NLS-1$
                monitor.subTask(Messages.MediVerlaufView_findPrescriptions); //$NON-NLS-1$
                Query<Prescription> qbe = new Query<Prescription>(Prescription.class);
                qbe.add(Prescription.FLD_PATIENT_ID, Query.EQUALS, sp.getId());
                List<Prescription> list = qbe.execute();
                mListe.clear();
                monitor.subTask(Messages.MediVerlaufView_findMedicaments); //$NON-NLS-1$
                try {
                    for (Prescription p : list) {
                        Map<TimeTool, String> terms = p.getTerms();
                        TimeTool[] tts = terms.keySet().toArray(new TimeTool[0]);
                        for (int i = 0; i < tts.length - 1; i++) {
                            if (i < tts.length - 1) {
                                mListe.add(new MediAbgabe(tts[i].toString(TimeTool.DATE_GER),
                                        tts[i + 1].toString(TimeTool.DATE_GER), p));
                            } else {
                                mListe.add(new MediAbgabe(tts[i].toString(TimeTool.DATE_GER), TOOPEN, p)); //$NON-NLS-1$
                            }
                        }
                        mListe.add(new MediAbgabe(tts[tts.length - 1].toString(TimeTool.DATE_GER), TOOPEN, p)); //$NON-NLS-1$
                    }
                } catch (Exception ex) {
                    ExHandler.handle(ex);
                }
                tv.refresh();
                monitor.done();
            }
        }, null);
    } catch (Throwable ex) {
        ExHandler.handle(ex);
    }
}

From source file:ch.elexis.core.ui.views.rechnung.KonsZumVerrechnenView.java

License:Open Source License

private void makeActions() {
    billAction = new Action(Messages.KonsZumVerrechnenView_createInvoices) { //$NON-NLS-1$
        {//  w ww  . j ava 2s  .  co  m
            setImageDescriptor(Images.IMG_BILL.getImageDescriptor()); //$NON-NLS-1$
            setToolTipText(Messages.KonsZumVerrechnenView_createInvoices); //$NON-NLS-1$
        }

        @SuppressWarnings("unchecked")
        @Override
        public void run() {
            if (((StructuredSelection) tvSel.getSelection()).size() > 0) {
                if (!SWTHelper.askYesNo(Messages.KonsZumVerrechnenView_RealleCreateBillsCaption, //$NON-NLS-1$
                        Messages.KonsZumVerrechnenView_ReallyCreateBillsBody)) { //$NON-NLS-1$
                    return;
                }
            }
            // Handler.execute(getViewSite(), "bill.create", tSelection);
            ErstelleRnnCommand.ExecuteWithParams(getViewSite(), tSelection);
            /*
             * IHandlerService handlerService = (IHandlerService)
             * getViewSite().getService(IHandlerService.class); ICommandService cmdService =
             * (ICommandService) getViewSite().getService(ICommandService.class); try {
             * Command command = cmdService.getCommand("bill.create"); Parameterization px =
             * new Parameterization(command.getParameter
             * ("ch.elexis.RechnungErstellen.parameter" ), new
             * TreeToStringConverter().convertToString(tSelection)); ParameterizedCommand
             * parmCommand = new ParameterizedCommand(command, new Parameterization[] { px
             * });
             * 
             * handlerService.executeCommand(parmCommand, null);
             * 
             * } catch (Exception ex) { throw new RuntimeException("add.command not found");
             * }
             */

            tvSel.refresh();
        }
    };
    clearAction = new Action(Messages.KonsZumVerrechnenView_clearSelection) { //$NON-NLS-1$
        {
            setImageDescriptor(Images.IMG_REMOVEITEM.getImageDescriptor()); //$NON-NLS-1$
            setToolTipText(Messages.KonsZumVerrechnenView_deleteList); //$NON-NLS-1$

        }

        @Override
        public void run() {
            tSelection.clear();
            tvSel.refresh();
        }
    };
    refreshAction = new Action(Messages.KonsZumVerrechnenView_reloadAction) { //$NON-NLS-1$
        {
            setImageDescriptor(Images.IMG_REFRESH.getImageDescriptor());
            setToolTipText(Messages.KonsZumVerrechnenView_reloadToolTip); //$NON-NLS-1$
        }

        @Override
        public void run() {
            tAll.clear();
            cv.notify(CommonViewer.Message.update);
            tvSel.refresh(true);
        }
    };
    wizardAction = new Action(Messages.KonsZumVerrechnenView_autoAction) { //$NON-NLS-1$
        {
            setImageDescriptor(Images.IMG_WIZARD.getImageDescriptor());
            setToolTipText(Messages.KonsZumVerrechnenView_autoToolTip); //$NON-NLS-1$
        }

        @Override
        public void run() {
            KonsZumVerrechnenWizardDialog kzvd = new KonsZumVerrechnenWizardDialog(getViewSite().getShell());
            if (kzvd.open() == Dialog.OK) {
                IProgressService progressService = PlatformUI.getWorkbench().getProgressService();
                try {
                    progressService.runInUI(progressService,
                            new Rechnungslauf(self, kzvd.bMarked, kzvd.ttFirstBefore, kzvd.ttLastBefore,
                                    kzvd.mAmount, kzvd.bQuartal, kzvd.bSkip, kzvd.ttFrom, kzvd.ttTo,
                                    kzvd.accountSys),
                            null);
                } catch (Throwable ex) {
                    ExHandler.handle(ex);
                }
                tvSel.refresh();
                cv.notify(CommonViewer.Message.update);
            }
        }
    };
    printAction = new Action(Messages.KonsZumVerrechnenView_printSelection) { //$NON-NLS-1$
        {
            setImageDescriptor(Images.IMG_PRINTER.getImageDescriptor());
            setToolTipText(Messages.KonsZumVerrechnenView_printToolTip); //$NON-NLS-1$
        }

        @Override
        public void run() {
            new SelectionPrintDialog(getViewSite().getShell()).open();

        }
    };
    removeAction = new Action(Messages.KonsZumVerrechnenView_removeFromSelection) { //$NON-NLS-1$
        @SuppressWarnings("unchecked")
        @Override
        public void run() {
            IStructuredSelection sel = (IStructuredSelection) tvSel.getSelection();
            if (!sel.isEmpty()) {
                for (Object o : sel.toList()) {
                    if (o instanceof Tree) {
                        Tree t = (Tree) o;
                        if (t.contents instanceof Patient) {
                            selectPatient((Patient) t.contents, tSelection, tAll);
                        } else if (t.contents instanceof Fall) {
                            selectFall((Fall) t.contents, tSelection, tAll);
                        } else if (t.contents instanceof Konsultation) {
                            selectBehandlung((Konsultation) t.contents, tSelection, tAll);
                        }
                    }
                }
                tvSel.refresh();
                cv.notify(CommonViewer.Message.update);
            }
        }
    };

    // expand action for tvSel
    expandSelAction = new Action(Messages.KonsZumVerrechnenView_expand) { //$NON-NLS-1$
        @SuppressWarnings("unchecked")
        @Override
        public void run() {
            IStructuredSelection sel = (IStructuredSelection) tvSel.getSelection();
            if (!sel.isEmpty()) {
                for (Object o : sel.toList()) {
                    if (o instanceof Tree) {
                        Tree t = (Tree) o;
                        tvSel.expandToLevel(t, TreeViewer.ALL_LEVELS);
                    }
                }
            }
        }
    };
    // expandAll action for tvSel
    expandSelAllAction = new Action(Messages.KonsZumVerrechnenView_expandAll) { //$NON-NLS-1$
        @Override
        public void run() {
            tvSel.expandAll();
        }
    };

    selectByDateAction = new Action(Messages.KonsZumVerrechnenView_selectByDateAction) { //$NON-NLS-1$
        TimeTool fromDate;
        TimeTool toDate;

        {
            setImageDescriptor(Images.IMG_WIZARD.getImageDescriptor());
            setToolTipText(Messages.KonsZumVerrechnenView_selectByDateActionToolTip); //$NON-NLS-1$
        }

        @Override
        public void run() {
            // select date
            SelectDateDialog dialog = new SelectDateDialog(getViewSite().getShell());
            if (dialog.open() == TitleAreaDialog.OK) {
                fromDate = dialog.getFromDate();
                toDate = dialog.getToDate();

                IProgressService progressService = PlatformUI.getWorkbench().getProgressService();
                try {
                    progressService.runInUI(PlatformUI.getWorkbench().getProgressService(),
                            new IRunnableWithProgress() {
                                public void run(final IProgressMonitor monitor) {
                                    doSelectByDate(monitor, fromDate, toDate);
                                }
                            }, null);
                } catch (Throwable ex) {
                    ExHandler.handle(ex);
                }
                tvSel.refresh();
                cv.notify(CommonViewer.Message.update);
            }
        }

    };
    detailAction = new RestrictedAction(AccessControlDefaults.LSTG_VERRECHNEN,
            Messages.KonsZumVerrechnenView_billingDetails) { //$NON-NLS-1$
        @SuppressWarnings("unchecked")
        @Override
        public void doRun() {
            Object[] sel = cv.getSelection();
            if ((sel != null) && (sel.length > 0)) {
                new VerrDetailDialog(getViewSite().getShell(), (Tree) sel[0]).open();
            }
        }
    };
}

From source file:ch.elexis.core.ui.views.rechnung.RnContentProvider.java

License:Open Source License

@SuppressWarnings("unchecked")
public Object[] getElements(final Object inputElement) {
    IProgressService progressService = PlatformUI.getWorkbench().getProgressService();
    try {/*from   w  w w. ja  v a  2  s  .co m*/
        progressService.run(true, true, new IRunnableWithProgress() {

            @Override
            public void run(final IProgressMonitor monitor) {
                reload(monitor);
                if (monitor.isCanceled()) {
                    monitor.done();
                }

                rlv.getSite().getShell().getDisplay().syncExec(new Runnable() {
                    @Override
                    public void run() {
                        InvoiceListBottomComposite invoiceListeBottomComposite = rlv
                                .getInvoiceListeBottomComposite();
                        if (invoiceListeBottomComposite != null) {
                            invoiceListeBottomComposite.update(Integer.toString(iPat), Integer.toString(iRn),
                                    mAmount.getAmountAsString(), mOpen.getAmountAsString());
                        }
                    }
                });
            }
        });
    } catch (Throwable ex) {
        ExHandler.handle(ex);
    }

    return result == null ? new Tree[0] : result;
}

From source file:ch.elexis.extdoc.dialogs.MoveIntoSubDirsDialog.java

License:Open Source License

public void run() {
    if (logger == null)
        logger = LoggerFactory.getLogger(this.getClass());
    logger.info("MoveIntoSubDirsDialog started"); //$NON-NLS-1$

    ProgressMonitorDialog dialog = new ProgressMonitorDialog(null);
    try {//from  w  w  w  .j a v a 2 s.  co  m
        dialog.run(true, true, new IRunnableWithProgress() {
            public void run(IProgressMonitor monitor) {
                int nrTreated = 0;
                java.util.List<File> oldFiles = MatchPatientToPath.getAllOldConventionFiles();
                int nrFiles = oldFiles.size();
                String dialogTitle = String.format("Alle (%1d) Dateien in Unterverzeichnisse auslagern ...", //$NON-NLS-1$
                        nrFiles);
                logger.info(dialogTitle);
                if (oldFiles == null) {
                    SWTHelper.showInfo(dialogTitle, Messages.MoveIntoSubDirsDialog_no_old_Files_found);
                    return;
                }
                monitor.beginTask(dialogTitle, oldFiles.size());
                Iterator<File> iterator = oldFiles.iterator();
                while (iterator.hasNext()) {
                    if (monitor.isCanceled())
                        break;
                    File f = iterator.next();
                    logger.info("Moving " + f.getAbsolutePath()); //$NON-NLS-1$
                    MatchPatientToPath.MoveIntoSubDir(f.getAbsolutePath());
                    ++nrTreated;
                    if (nrTreated % 10 == 1) {
                        monitor.subTask(String.format(Messages.MoveIntoSubDirsDialog_sub_task, f.getName()));
                        monitor.worked(10);
                    }
                }
                monitor.done();
                logger.info("MoveIntoSubDirsDialog done"); //$NON-NLS-1$
                SWTHelper.showInfo(dialogTitle, Messages.MoveIntoSubDirsDialog_finished);
            }
        });
    } catch (InvocationTargetException e) {
        e.printStackTrace();
        SWTHelper.showInfo("Fehler beim Auslagern!!",
                Messages.MoveIntoSubDirsDialog_finished + "\n" + e.getMessage());
        logger.info("Fehler beim Auslagern!!" + e.getLocalizedMessage()); //$NON-NLS-1$
    } catch (InterruptedException e) {
        e.printStackTrace();
        SWTHelper.showInfo("Fehler beim Auslagern!",
                Messages.MoveIntoSubDirsDialog_finished + "\n" + e.getMessage());
        logger.info("Fehler beim Auslagern!!" + e.getLocalizedMessage()); //$NON-NLS-1$
    }
    return;
}

From source file:ch.elexis.privatrechnung.rechnung.RechnungsDrucker.java

License:Open Source License

/**
 * Print the bill(s)//from w  ww  .  j  av  a  2s  .  c o  m
 */
public Result<Rechnung> doOutput(final TYPE type, final Collection<Rechnung> rnn, Properties props) {
    IWorkbenchPage rnPage;
    final Result<Rechnung> result = new Result<Rechnung>(); // =new
    // Result<Rechnung>(Log.ERRORS,99,"Not
    // yet implemented",null,true);
    rnPage = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
    IProgressService progressService = PlatformUI.getWorkbench().getProgressService();
    final Result<Rechnung> res = new Result<Rechnung>();

    try {
        final RnPrintView rnp = (RnPrintView) rnPage.showView(RnPrintView.ID);
        progressService.runInUI(PlatformUI.getWorkbench().getProgressService(), new IRunnableWithProgress() {
            public void run(final IProgressMonitor monitor) {
                monitor.beginTask("Drucke Rechnungen", rnn.size() * 10);
                int errors = 0;
                for (Rechnung rn : rnn) {
                    try {
                        // select Rechnung before printing for correct placeholder replacement
                        ElexisEventDispatcher.fireSelectionEvent(rn);
                        result.add(rnp.doPrint(rn));
                        monitor.worked(10);
                        if (!result.isOK()) {
                            String errms = "Rechnung " + rn.getNr() + "konnte nicht gedruckt werden";
                            res.add(Result.SEVERITY.ERROR, 1, errms, rn, true);
                            errors++;
                            continue;
                        }
                        int status_vorher = rn.getStatus();
                        if ((status_vorher == RnStatus.OFFEN) || (status_vorher == RnStatus.MAHNUNG_1)
                                || (status_vorher == RnStatus.MAHNUNG_2)
                                || (status_vorher == RnStatus.MAHNUNG_3)) {
                            rn.setStatus(status_vorher + 1);
                        }
                        rn.addTrace(Rechnung.OUTPUT,
                                getDescription() + ": " + RnStatus.getStatusText(rn.getStatus()));
                    } catch (Exception ex) {
                        SWTHelper.showError("Fehler beim Drucken der Rechnung " + rn.getRnId(),
                                ex.getMessage());
                        errors++;
                    }
                }
                monitor.done();
                if (errors == 0) {
                    SWTHelper.showInfo("OK", "OK");
                } else {
                    SWTHelper.showError("Fehler", "Fehler");
                }
            }
        }, null);

        rnPage.hideView(rnp);

    } catch (Exception ex) {
        ExHandler.handle(ex);
        res.add(Result.SEVERITY.ERROR, 2, ex.getMessage(), null, true);
        ErrorDialog.openError(null, "Exception", "Exception", ResultAdapter.getResultAsStatus(res));
        return res;
    }
    if (!result.isOK()) {
        ResultAdapter.displayResult(result, "Fehler beim Rechnungsdruck");
    }
    return result;
}