Search in sources :

Example 6 with Job

use of org.eclipse.core.runtime.jobs.Job in project translationstudio8 by heartsome.

the class ExportTbxDialog method okPressed.

@Override
protected void okPressed() {
    String encoding = "UTF-8";
    if (hasChangedCodingCbtn.getSelection()) {
        encoding = this.encodingComboViewer.getCombo().getText();
    }
    String exportPath = this.tbxFileText.getText();
    ExportFilterBean filterBean = null;
    if (hasFilterChangedBtn.getSelection()) {
        IStructuredSelection sel = (IStructuredSelection) filterComboViewer.getSelection();
        filterBean = (ExportFilterBean) sel.getFirstElement();
        if (filterBean.equals(filterList.get(0))) {
            filterBean = null;
        }
    }
    if (this.dbList.size() == 0) {
        MessageDialog.openInformation(getShell(), Messages.getString("dialog.ExportTbxDialog.msgTitle"), Messages.getString("dialog.ExportTbxDialog.msg3"));
        return;
    }
    for (Iterator<ExportDatabaseBean> iterator = dbList.iterator(); iterator.hasNext(); ) {
        ExportDatabaseBean dbBean = iterator.next();
        if (dbBean.getHasSelectedLangs().size() < 2) {
            String dbType = dbBean.getDbBean().getDbType();
            String name = dbBean.getDbBean().getDatabaseName();
            MessageDialog.openInformation(getShell(), Messages.getString("dialog.ExportTbxDialog.msgTitle"), MessageFormat.format(Messages.getString("dialog.ExportTbxDialog.msg4"), dbType, name));
            return;
        }
    }
    if (exportPath == null || exportPath.equals("")) {
        MessageDialog.openInformation(getShell(), Messages.getString("dialog.ExportTbxDialog.msgTitle"), Messages.getString("dialog.ExportTbxDialog.msg5"));
        return;
    }
    if (this.dbList.size() > 1) {
        File f = new File(exportPath);
        if (!f.isDirectory()) {
            MessageDialog.openInformation(getShell(), Messages.getString("dialog.ExportTbxDialog.msgTitle"), Messages.getString("dialog.ExportTbxDialog.msg7"));
            return;
        }
    }
    if (this.dbList.size() == 1) {
        File f = new File(exportPath);
        if (f.isDirectory()) {
            MessageDialog.openInformation(getShell(), Messages.getString("dialog.ExportTbxDialog.msgTitle"), Messages.getString("dialog.ExportTbxDialog.msg8"));
            return;
        }
    }
    if (this.dbList.size() == 1) {
        dbList.get(0).setExportFilePath(exportPath);
        File file = new File(exportPath);
        if (file.exists()) {
            if (!MessageDialog.openConfirm(getShell(), Messages.getString("dialog.ExportTbxDialog.msgTitle"), MessageFormat.format(Messages.getString("dialog.ExportTbxDialog.msg6"), exportPath))) {
                return;
            }
        }
    } else {
        for (Iterator<ExportDatabaseBean> iterator = dbList.iterator(); iterator.hasNext(); ) {
            ExportDatabaseBean db = iterator.next();
            String databaseName = db.getDbBean().getDatabaseName();
            String path = exportPath + System.getProperty("file.separator") + databaseName + db.getDbBean().getDbType() + ".tbx";
            File file = new File(path);
            if (file.exists()) {
                if (!MessageDialog.openConfirm(getShell(), Messages.getString("dialog.ExportTbxDialog.msgTitle"), MessageFormat.format(Messages.getString("dialog.ExportTbxDialog.msg6"), path))) {
                    return;
                }
            }
            db.setExportFilePath(path);
        }
    }
    final ExportAbstract exportor = new ExportTbxImpl(this.dbList, filterBean, encoding);
    Job job = new Job(Messages.getString("dialog.ExportTbxDialog.job")) {

        @Override
        protected IStatus run(IProgressMonitor monitor) {
            final String result = DatabaseService.executeExport(exportor, monitor);
            Display.getDefault().syncExec(new Runnable() {

                public void run() {
                    MessageDialog.openInformation(getShell(), Messages.getString("dialog.ExportTbxDialog.msgTitle"), result);
                }
            });
            return Status.OK_STATUS;
        }
    };
    // 当程序退出时,检测当前 job 是否正常关闭
    CommonFunction.jobCantCancelTip(job);
    job.addJobChangeListener(new JobChangeAdapter() {

        @Override
        public void running(IJobChangeEvent event) {
            ProgressIndicatorManager.displayProgressIndicator();
            super.running(event);
        }

        @Override
        public void done(IJobChangeEvent event) {
            ProgressIndicatorManager.hideProgressIndicator();
            super.done(event);
        }
    });
    job.setUser(true);
    job.schedule();
    super.okPressed();
}
Also used : JobChangeAdapter(org.eclipse.core.runtime.jobs.JobChangeAdapter) ExportFilterBean(net.heartsome.cat.database.bean.ExportFilterBean) IStructuredSelection(org.eclipse.jface.viewers.IStructuredSelection) IJobChangeEvent(org.eclipse.core.runtime.jobs.IJobChangeEvent) ExportDatabaseBean(net.heartsome.cat.database.bean.ExportDatabaseBean) IProgressMonitor(org.eclipse.core.runtime.IProgressMonitor) ExportTbxImpl(net.heartsome.cat.document.ExportTbxImpl) ExportAbstract(net.heartsome.cat.document.ExportAbstract) Job(org.eclipse.core.runtime.jobs.Job) File(java.io.File)

Example 7 with Job

use of org.eclipse.core.runtime.jobs.Job in project translationstudio8 by heartsome.

the class QualityAssurance method beginMultiFileQA.

/**
	 * 开始处理多个合并打开文件的品质检查,由于合并打开文件的处理,是个很特殊的例子,因为处理对像不再是单个文件,而是针对语言对。
	 * @param qaResult ;
	 */
public void beginMultiFileQA(final QAResult qaResult) {
    this.qaResult = qaResult;
    handler = new QAXmlHandler();
    Job job = new Job(Messages.getString("qa.all.qa")) {

        @Override
        protected IStatus run(IProgressMonitor monitor) {
            long time1 = System.currentTimeMillis();
            int fileNum = model.getQaXlfList().size();
            // 定义的进度条总共五格,其中,解析文件1格,进行检查9格
            monitor.beginTask(Messages.getString("qa.QualityAssurance.tip1"), fileNum * 10);
            //先将所有的文件进行解析
            if (!openFile(monitor)) {
                monitor.done();
                return Status.CANCEL_STATUS;
            }
            if (model.getQaXlfList().size() == 0) {
                MessageDialog.openInformation(shell, _INFO, Messages.getString("qa.QualityAssurance.tip2"));
                return Status.CANCEL_STATUS;
            }
            initWorkInterval();
            int allTUSize = handler.getAllTUSize();
            //遍历tu节点的序列号
            int traversalTuIndex = 0;
            IProgressMonitor subMonitor = new SubProgressMonitor(monitor, fileNum * 9, SubProgressMonitor.PREPEND_MAIN_LABEL_TO_SUBTASK);
            subMonitor.beginTask("", allTUSize % workInterval == 0 ? (allTUSize / workInterval) : (allTUSize / workInterval) + 1);
            QARealization realization = null;
            Map<String, ArrayList<String>> languageList = handler.getLanguages();
            int lineNumber = 0;
            IFile iFile;
            for (Entry<String, ArrayList<String>> langEntry : languageList.entrySet()) {
                String srcLang = langEntry.getKey();
                for (String tgtLang : langEntry.getValue()) {
                    List<String> rowIdsList = handler.getAllRowIdsByLanguages(srcLang.toUpperCase(), tgtLang.toUpperCase());
                    model.setRowIdsList(rowIdsList);
                    //开始针对每一个文本段进行检查
                    for (String rowId : rowIdsList) {
                        traversalTuIndex++;
                        //行号
                        lineNumber = rowIdsList.indexOf(rowId) + 1;
                        String filePath = RowIdUtil.getFileNameByRowId(rowId);
                        iFile = ResourceUtils.fileToIFile(filePath);
                        String langPair = srcLang + Hyphen + tgtLang;
                        QATUDataBean tuDataBean = handler.getFilteredTUText(filePath, RowIdUtil.parseRowIdToXPath(rowId), model.getNotInclude());
                        if (tuDataBean == null) {
                            if (!monitorWork(subMonitor, traversalTuIndex, false)) {
                                closeDB();
                                return Status.CANCEL_STATUS;
                            }
                            continue;
                        }
                        if (!tuDataBean.isPassFilter()) {
                            if (!monitorWork(subMonitor, traversalTuIndex, false)) {
                                closeDB();
                                return Status.CANCEL_STATUS;
                            }
                            continue;
                        }
                        tuDataBean.setLineNumber(lineNumber + "");
                        tuDataBean.setFileName(iFile.getName());
                        tuDataBean.setSrcLang(srcLang);
                        tuDataBean.setTgtLang(tgtLang);
                        for (int i = 0; i < model.getBatchQAItemIdList().size(); i++) {
                            final String qaItemId = model.getBatchQAItemIdList().get(i);
                            realization = getClassInstance(qaItemId);
                            // 若没有该项检查的实例,提示出错
                            if (realization == null) {
                                Display.getDefault().asyncExec(new Runnable() {

                                    public void run() {
                                        MessageDialog.openError(shell, _ERROR, MessageFormat.format(Messages.getString("qa.QualityAssurance.tip4"), new Object[] { model.getQaItemId_Name_Class().get(qaItemId).get(QAConstant.QA_ITEM_NAME) }));
                                    }
                                });
                                closeDB();
                                return Status.CANCEL_STATUS;
                            }
                            // 开始进行该项文件的该项检查
                            final String result = realization.startQA(model, subMonitor, iFile, handler, tuDataBean);
                            // // 当未设置术语库、拼写检查词典配置 错误时才会返回 null,所以这时可以直接删。
                            if (result == null) {
                                model.getBatchQAItemIdList().remove(qaItemId);
                                i--;
                            }
                            if (monitor.isCanceled()) {
                                return Status.CANCEL_STATUS;
                            }
                        }
                        qaResult.sendDataToViewer(null);
                        if (!monitorWork(subMonitor, traversalTuIndex, false)) {
                            closeDB();
                            return Status.CANCEL_STATUS;
                        }
                    }
                }
                if (!monitorWork(subMonitor, traversalTuIndex, true)) {
                    closeDB();
                    return Status.CANCEL_STATUS;
                }
            }
            closeDB();
            qaResult.informQAEndFlag();
            subMonitor.done();
            monitor.done();
            System.out.println("所用时间为" + (System.currentTimeMillis() - time1));
            return Status.OK_STATUS;
        }
    };
    // 当程序退出时,检测当前 job 是否正常关闭
    CommonFunction.jobCantCancelTip(job);
    job.addJobChangeListener(new JobChangeAdapter() {

        @Override
        public void running(IJobChangeEvent event) {
            ProgressIndicatorManager.displayProgressIndicator();
            super.running(event);
        }

        @Override
        public void done(IJobChangeEvent event) {
            ProgressIndicatorManager.hideProgressIndicator();
            super.done(event);
        }
    });
    job.setUser(true);
    job.schedule();
}
Also used : IFile(org.eclipse.core.resources.IFile) QATUDataBean(net.heartsome.cat.ts.core.qa.QATUDataBean) JobChangeAdapter(org.eclipse.core.runtime.jobs.JobChangeAdapter) QAXmlHandler(net.heartsome.cat.ts.core.qa.QAXmlHandler) ArrayList(java.util.ArrayList) IJobChangeEvent(org.eclipse.core.runtime.jobs.IJobChangeEvent) SubProgressMonitor(org.eclipse.core.runtime.SubProgressMonitor) IProgressMonitor(org.eclipse.core.runtime.IProgressMonitor) Job(org.eclipse.core.runtime.jobs.Job)

Example 8 with Job

use of org.eclipse.core.runtime.jobs.Job in project translationstudio8 by heartsome.

the class DeleteResourceAndCloseEditorAction method run.

/*
	 * (non-Javadoc) Method declared on IAction.
	 */
public void run() {
    final IResource[] resources = getSelectedResourcesArray();
    if (!fTestingMode) {
        if (LTKLauncher.openDeleteWizard(getStructuredSelection())) {
            return;
        }
    }
    // deletes/moves the wrong file
    if (!confirmDelete(resources)) {
        return;
    }
    Job deletionCheckJob = new Job(IDEWorkbenchMessages.DeleteResourceAction_checkJobName) {

        /*
			 * (non-Javadoc)
			 * 
			 * @see org.eclipse.core.runtime.jobs.Job#run(org.eclipse.core.runtime.IProgressMonitor)
			 */
        protected IStatus run(IProgressMonitor monitor) {
            if (resources.length == 0)
                return Status.CANCEL_STATUS;
            closeRelatedEditors();
            scheduleDeleteJob(resources);
            return Status.OK_STATUS;
        }

        /*
			 * (non-Javadoc)
			 * 
			 * @see org.eclipse.core.runtime.jobs.Job#belongsTo(java.lang.Object)
			 */
        public boolean belongsTo(Object family) {
            if (IDEWorkbenchMessages.DeleteResourceAction_jobName.equals(family)) {
                return true;
            }
            return super.belongsTo(family);
        }
    };
    deletionCheckJob.schedule();
}
Also used : IProgressMonitor(org.eclipse.core.runtime.IProgressMonitor) WorkbenchJob(org.eclipse.ui.progress.WorkbenchJob) Job(org.eclipse.core.runtime.jobs.Job) IResource(org.eclipse.core.resources.IResource)

Example 9 with Job

use of org.eclipse.core.runtime.jobs.Job in project azure-tools-for-java by Microsoft.

the class BlobExplorerFileEditor method uploadFile.

private void uploadFile(final String path, final File selectedFile) {
    Job job = new Job("Uploading blob...") {

        @Override
        protected IStatus run(final IProgressMonitor monitor) {
            monitor.beginTask("Uploading blob...", IProgressMonitor.UNKNOWN);
            try {
                final BlobDirectory blobDirectory = directoryQueue.peekLast();
                final BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream(selectedFile));
                monitor.subTask("0% uploaded");
                try {
                    final CallableSingleArg<Void, Long> callable = new CallableSingleArg<Void, Long>() {

                        @Override
                        public Void call(Long uploadedBytes) throws Exception {
                            double progress = ((double) uploadedBytes) / selectedFile.length();
                            monitor.worked((int) (100 * progress));
                            monitor.subTask(String.format("%s%% uploaded", (int) (progress * 100)));
                            return null;
                        }
                    };
                    try {
                        StorageClientSDKManager.getManager().uploadBlobFileContent(connectionString, blobContainer, path, bufferedInputStream, callable, 1024 * 1024, selectedFile.length());
                    } catch (AzureCmdException e) {
                        e.printStackTrace();
                    } finally {
                        try {
                            bufferedInputStream.close();
                        } catch (IOException ignored) {
                        }
                    }
                    if (monitor.isCanceled()) {
                        //                                future.cancel(true);
                        bufferedInputStream.close();
                        for (BlobItem blobItem : StorageClientSDKManager.getManager().getBlobItems(connectionString, blobDirectory)) {
                            if (blobItem instanceof BlobFile && blobItem.getPath().equals(path)) {
                                StorageClientSDKManager.getManager().deleteBlobFile(connectionString, (BlobFile) blobItem);
                            }
                        }
                    }
                    try {
                        directoryQueue.clear();
                        directoryQueue.addLast(StorageClientSDKManager.getManager().getRootDirectory(connectionString, blobContainer));
                        for (String pathDir : path.split("/")) {
                            for (BlobItem blobItem : StorageClientSDKManager.getManager().getBlobItems(connectionString, directoryQueue.getLast())) {
                                if (blobItem instanceof BlobDirectory && blobItem.getName().equals(pathDir)) {
                                    directoryQueue.addLast((BlobDirectory) blobItem);
                                }
                            }
                        }
                    } catch (AzureCmdException e) {
                        DefaultLoader.getUIHelper().showException("Error showing new blob", e, "Error showing new blob", false, true);
                    }
                    DefaultLoader.getIdeHelper().invokeLater(new Runnable() {

                        @Override
                        public void run() {
                            fillGrid();
                        }
                    });
                } catch (Exception e) {
                    Throwable connectionFault = e.getCause();
                    Throwable realFault = null;
                    if (connectionFault != null) {
                        realFault = connectionFault.getCause();
                    }
                    monitor.setTaskName("Error uploading Blob");
                    String message = realFault == null ? null : realFault.getMessage();
                    if (connectionFault != null && message == null) {
                        message = "Error type " + connectionFault.getClass().getName();
                    }
                    monitor.subTask((connectionFault instanceof SocketTimeoutException) ? "Connection timed out" : message);
                }
            } catch (Exception e) {
                DefaultLoader.getUIHelper().showException("Error uploading Blob", e, "Error uploading Blob", false, true);
                return Status.CANCEL_STATUS;
            } finally {
                monitor.done();
            }
            return Status.OK_STATUS;
        }
    };
    job.schedule();
}
Also used : BlobDirectory(com.microsoft.tooling.msservices.model.storage.BlobDirectory) CallableSingleArg(com.microsoft.tooling.msservices.helpers.CallableSingleArg) BlobFile(com.microsoft.tooling.msservices.model.storage.BlobFile) IOException(java.io.IOException) FileInputStream(java.io.FileInputStream) PartInitException(org.eclipse.ui.PartInitException) SocketTimeoutException(java.net.SocketTimeoutException) IOException(java.io.IOException) AzureCmdException(com.microsoft.azuretools.azurecommons.helpers.AzureCmdException) BlobItem(com.microsoft.tooling.msservices.model.storage.BlobItem) IProgressMonitor(org.eclipse.core.runtime.IProgressMonitor) SocketTimeoutException(java.net.SocketTimeoutException) BufferedInputStream(java.io.BufferedInputStream) AzureCmdException(com.microsoft.azuretools.azurecommons.helpers.AzureCmdException) Job(org.eclipse.core.runtime.jobs.Job)

Example 10 with Job

use of org.eclipse.core.runtime.jobs.Job in project azure-tools-for-java by Microsoft.

the class BlobExplorerFileEditor method downloadSelectedFile.

private void downloadSelectedFile(final File targetFile, final boolean open) {
    final BlobFile fileSelection = getFileSelection();
    if (fileSelection != null) {
        Job job = new Job("Downloading blob...") {

            @Override
            protected IStatus run(final IProgressMonitor monitor) {
                monitor.beginTask("Downloading blob...", IProgressMonitor.UNKNOWN);
                try {
                    if (!targetFile.exists()) {
                        if (!targetFile.createNewFile()) {
                            throw new IOException("File not created");
                        }
                    }
                    final BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(targetFile), 65536) {

                        private long runningCount = 0;

                        @Override
                        public synchronized void write(@NotNull byte[] bytes, int i, int i1) throws IOException {
                            super.write(bytes, i, i1);
                            runningCount += i1;
                            double progress = (double) runningCount / fileSelection.getSize();
                            monitor.worked((int) (100 * progress));
                            monitor.subTask(String.format("%s%% downloaded", (int) (progress * 100)));
                        }
                    };
                    try {
                        //                                public void run() {
                        try {
                            StorageClientSDKManager.getManager().downloadBlobFileContent(connectionString, fileSelection, bufferedOutputStream);
                            if (open && targetFile.exists()) {
                                try {
                                    final Process p;
                                    Runtime runtime = Runtime.getRuntime();
                                    p = runtime.exec(new String[] { "open", "-R", targetFile.getName() }, null, targetFile.getParentFile());
                                    InputStream errorStream = p.getErrorStream();
                                    String errResponse = new String(IOUtils.readFully(errorStream, -1, true));
                                    if (p.waitFor() != 0) {
                                        throw new Exception(errResponse);
                                    }
                                } catch (Exception e) {
                                    monitor.setTaskName("Error opening file");
                                    monitor.subTask(e.getMessage());
                                }
                            //                                            Desktop.getDesktop().open(targetFile);
                            }
                        } catch (AzureCmdException e) {
                            Throwable connectionFault = e.getCause().getCause();
                            monitor.setTaskName("Error downloading Blob");
                            monitor.subTask((connectionFault instanceof SocketTimeoutException) ? "Connection timed out" : connectionFault.getMessage());
                            return Status.CANCEL_STATUS;
                        }
                    } finally {
                        bufferedOutputStream.close();
                    }
                } catch (IOException e) {
                    DefaultLoader.getUIHelper().showException("Error downloading Blob", e, "Error downloading Blob", false, true);
                    return Status.CANCEL_STATUS;
                } finally {
                    monitor.done();
                }
                return Status.OK_STATUS;
            }
        };
        job.schedule();
    }
}
Also used : BufferedInputStream(java.io.BufferedInputStream) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) BlobFile(com.microsoft.tooling.msservices.model.storage.BlobFile) IOException(java.io.IOException) NotNull(com.microsoft.azuretools.azurecommons.helpers.NotNull) PartInitException(org.eclipse.ui.PartInitException) SocketTimeoutException(java.net.SocketTimeoutException) IOException(java.io.IOException) AzureCmdException(com.microsoft.azuretools.azurecommons.helpers.AzureCmdException) IProgressMonitor(org.eclipse.core.runtime.IProgressMonitor) SocketTimeoutException(java.net.SocketTimeoutException) AzureCmdException(com.microsoft.azuretools.azurecommons.helpers.AzureCmdException) FileOutputStream(java.io.FileOutputStream) Job(org.eclipse.core.runtime.jobs.Job) BufferedOutputStream(java.io.BufferedOutputStream)

Aggregations

Job (org.eclipse.core.runtime.jobs.Job)82 IProgressMonitor (org.eclipse.core.runtime.IProgressMonitor)57 IStatus (org.eclipse.core.runtime.IStatus)20 IJobChangeEvent (org.eclipse.core.runtime.jobs.IJobChangeEvent)17 JobChangeAdapter (org.eclipse.core.runtime.jobs.JobChangeAdapter)17 JobFamily (com.cubrid.common.ui.spi.progress.JobFamily)14 IOException (java.io.IOException)14 Status (org.eclipse.core.runtime.Status)12 File (java.io.File)11 CoreException (org.eclipse.core.runtime.CoreException)8 ArrayList (java.util.ArrayList)7 IFile (org.eclipse.core.resources.IFile)6 PersistenceException (org.talend.commons.exception.PersistenceException)6 InvocationTargetException (java.lang.reflect.InvocationTargetException)5 TreeViewer (org.eclipse.jface.viewers.TreeViewer)5 ExecTaskWithProgress (com.cubrid.common.ui.spi.progress.ExecTaskWithProgress)4 TaskExecutor (com.cubrid.common.ui.spi.progress.TaskExecutor)4 AzureCmdException (com.microsoft.azuretools.azurecommons.helpers.AzureCmdException)4 SubProgressMonitor (org.eclipse.core.runtime.SubProgressMonitor)4 Shell (org.eclipse.swt.widgets.Shell)4