Search in sources :

Example 6 with SubProgressMonitor

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

the class Txt2TbxConverter method doConvert.

/**
	 * (non-Javadoc)
	 * @see net.heartsome.cat.document.converter.AbstractConverter#doConvert(java.lang.String,
	 *      org.eclipse.core.runtime.IProgressMonitor)
	 */
@Override
public void doConvert(String targetFile, IProgressMonitor monitor) throws Exception {
    try {
        monitor.beginTask("", 10);
        monitor.worked(2);
        out = new FileOutputStream(new File(targetFile));
        File f = new File(txtFile);
        String encoding = FileEncodingDetector.detectFileEncoding(f);
        TxtRowReader reader = new TxtRowReader(f, encoding);
        int rowsNum = reader.getLineNumber();
        if (rowsNum < 2) {
            throw new Exception(Messages.getString("converter.common.vaild.langcode.error"));
        }
        // read header
        List<String[]> h = reader.read(1);
        if (h == null || h.size() == 0) {
            throw new Exception(Messages.getString("converter.common.vaild.langcode.error"));
        }
        String[] hv = h.get(0);
        if (hv == null || hv.length < 2) {
            throw new Exception(Messages.getString("converter.common.vaild.langcode.error"));
        }
        Map<String, Language> defaultLanguage = LocaleService.getDefaultLanguage();
        List<String> _temp = new ArrayList<String>();
        for (String s : hv) {
            s = LanguageUtils.convertLangCode(s);
            if (_temp.contains(s)) {
                throw new Exception(Messages.getString("converter.common.vaild.duplicatelangcode.error"));
            }
            if (defaultLanguage.get(s) == null) {
                throw new Exception(Messages.getString("converter.common.vaild.langcode.error"));
            }
            _temp.add(s);
        }
        if (_temp.size() < 2) {
            throw new Exception(Messages.getString("converter.common.vaild.langcode.error"));
        }
        header = _temp.toArray(new String[] {});
        // generate header
        String s = generateTbxHeader(header[0]);
        writeString(s);
        // generate body
        int readSize = 10;
        List<String[]> rs = null;
        if (monitor.isCanceled()) {
            throw new OperationCanceledException();
        }
        SubProgressMonitor subMonitor = new SubProgressMonitor(monitor, 8);
        subMonitor.beginTask("", rowsNum / readSize == 0 ? 1 : rowsNum / readSize);
        while ((rs = reader.read(readSize)) != null) {
            for (String[] r : rs) {
                if (r == null || r.length < 2) {
                    continue;
                }
                int loopSize = r.length < header.length ? r.length : header.length;
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < loopSize; i++) {
                    String value = r[i];
                    String lang = header[i];
                    sb.append("<langSet id=\"_" + (System.currentTimeMillis() + 1) + "\" xml:lang=\"" + lang + "\">\n");
                    sb.append("<tig>\n");
                    sb.append("<term>" + value + "</term>\n");
                    sb.append("</tig>\n");
                    sb.append("</langSet>\n");
                }
                if (sb.length() != 0) {
                    writeString("<termEntry id=\"_" + System.currentTimeMillis() + "\">\n");
                    writeString(sb.toString());
                    writeString("</termEntry>\n");
                }
                subMonitor.worked(1);
            }
            if (subMonitor.isCanceled()) {
                throw new OperationCanceledException();
            }
        }
        // generate end
        s = generateTbxEnd();
        if (s != null && s.length() != 0) {
            writeString(s);
        }
        subMonitor.done();
    } finally {
        out.close();
        monitor.done();
    }
}
Also used : OperationCanceledException(org.eclipse.core.runtime.OperationCanceledException) ArrayList(java.util.ArrayList) TxtRowReader(net.heartsome.cat.document.txt.TxtRowReader) IOException(java.io.IOException) OperationCanceledException(org.eclipse.core.runtime.OperationCanceledException) SubProgressMonitor(org.eclipse.core.runtime.SubProgressMonitor) Language(net.heartsome.cat.common.locale.Language) FileOutputStream(java.io.FileOutputStream) File(java.io.File)

Example 7 with SubProgressMonitor

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

the class DatabaseService method importTbxWithFile.

/**
	 * 将TBX文件导入到指定的数据库中
	 * @param fileName
	 *            TBX文件完整路径
	 * @param monitor
	 *            需要使用的进度条,如果不需要使用进度条,则为null
	 * @param metaData
	 *            数据库元数据,封装了一系列连接数据库的参数,用于连接数据,参考{@link MetaData}
	 * @param strategy
	 *            TBX导入策略,参考{@link Constants}中的定义
	 * @return 导入结果,为int型数据,参考{@link ImportAbstract}中的定义;;
	 * @throws ImportException
	 */
public static int importTbxWithFile(String fileName, IProgressMonitor monitor, MetaData metaData, int strategy) throws ImportException {
    File file = new File(fileName);
    if (file.exists() || !file.isDirectory()) {
        if (!fileName.toLowerCase().endsWith(".tbx")) {
            monitor.beginTask("", 100);
            File convet2tbx = null;
            try {
                convet2tbx = ConverterUtil.convert2Tbx(fileName, new SubProgressMonitor(monitor, 30));
            } catch (OperationCanceledException e) {
                return CANCEL;
            } catch (ImportException e) {
                LOGGER.error("", e);
                throw new ImportException(e.getMessage().replace("\n", " "));
            }
            if (convet2tbx != null) {
                file = convet2tbx;
            } else {
                file = new File(fileName);
            }
        } else {
            monitor.beginTask("", 70);
        }
        DBOperator dbOp = getDBOperator(metaData);
        try {
            dbOp.start();
            ImportAbstract impOp = new ImportTbx(dbOp, strategy);
            int result = impOp.doImport(file.getAbsolutePath(), new SubProgressMonitor(monitor, 70));
            return result;
        } catch (SQLException e) {
            LOGGER.error(Messages.getString("service.DatabaseService.logger10") + dbOp.getMetaData().getDatabaseName(), e);
            return ImportAbstract.FAILURE_3;
        } catch (ClassNotFoundException e) {
            LOGGER.error(Messages.getString("service.DatabaseService.logger11"), e);
            return ImportAbstract.FAILURE_3;
        } finally {
            if (dbOp != null) {
                try {
                    dbOp.end();
                } catch (SQLException e) {
                    LOGGER.error(Messages.getString("service.DatabaseService.logger12"), e);
                }
            }
            monitor.done();
        }
    }
    return ImportAbstract.FAILURE;
}
Also used : ImportException(net.heartsome.cat.common.core.exception.ImportException) ImportTbx(net.heartsome.cat.document.ImportTbx) ImportAbstract(net.heartsome.cat.document.ImportAbstract) SQLException(java.sql.SQLException) OperationCanceledException(org.eclipse.core.runtime.OperationCanceledException) SystemDBOperator(net.heartsome.cat.database.SystemDBOperator) DBOperator(net.heartsome.cat.database.DBOperator) File(java.io.File) SubProgressMonitor(org.eclipse.core.runtime.SubProgressMonitor)

Example 8 with SubProgressMonitor

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

the class ConverterUtil method convert2Tmx.

public static File convert2Tmx(String fileName, IProgressMonitor monitor) throws ImportException {
    File file = new File(fileName);
    if (!file.exists()) {
        throw new ImportException(fileName + Messages.getString("converter.ConverterUtil.msg"));
    }
    if (fileName.toLowerCase().endsWith(".tmx")) {
        return null;
    }
    AbstractFile2Tmx file2TmxConverter = ConverterFactory.getFile2TmxConverter(fileName);
    if (null == file2TmxConverter) {
        return null;
    }
    File createTempFile = null;
    boolean hasError = true;
    try {
        createTempFile = File.createTempFile("Tmx_", "" + System.currentTimeMillis() + ".tmx");
        SubProgressMonitor spm = new SubProgressMonitor(monitor, 30);
        File2TmxConvertBean bean = new File2TmxConvertBean();
        bean.sourceFilePath = fileName;
        bean.newTmxFilePath = createTempFile.getAbsolutePath();
        file2TmxConverter.doCovnerter(bean, spm);
        hasError = false;
    } catch (IOException e) {
        LOGGER.error("", e);
        throw new ImportException(e.getMessage().replace("\n", " "));
    } catch (Exception e) {
        LOGGER.error("", e);
        throw new ImportException(e.getMessage().replace("\n", " "));
    } finally {
        if (hasError && null != createTempFile) {
            createTempFile.delete();
        }
    }
    return createTempFile;
}
Also used : ImportException(net.heartsome.cat.common.core.exception.ImportException) File2TmxConvertBean(net.heartsome.cat.tmx.converter.bean.File2TmxConvertBean) IOException(java.io.IOException) File(java.io.File) SubProgressMonitor(org.eclipse.core.runtime.SubProgressMonitor) OperationCanceledException(org.eclipse.core.runtime.OperationCanceledException) ImportException(net.heartsome.cat.common.core.exception.ImportException) IOException(java.io.IOException)

Example 9 with SubProgressMonitor

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

the class DocumentPart method getDocumentContent.

/**
	 * 获取文本档 document.xml 的内容。
	 */
private void getDocumentContent() throws Exception {
    // 先处理可翻译属性
    operateTransAttributes("/w:document/w:body/descendant::w:p/w:r/w:pict/v:shape/@alt");
    //String xpath="/root/descendant::a";
    String xpath = "/w:document/w:body/descendant::w:p";
    int allPSum = getNodeCount(xpath);
    initWorkInterval(allPSum);
    IProgressMonitor subMonitor = new SubProgressMonitor(monitor, 17, SubProgressMonitor.PREPEND_MAIN_LABEL_TO_SUBTASK);
    subMonitor.beginTask("", allPSum % workInterval == 0 ? (allPSum / workInterval) : (allPSum / workInterval) + 1);
    subMonitor.setTaskName(Messages.getString("docx2Xlf.task2"));
    int traveledPIdx = 0;
    // 处理的单元为 w:p
    ap.selectXPath(xpath);
    while (ap.evalXPath() != -1) {
        //			String pid = vn.toString(vn.getAttrVal("w:rsidRDefault"));
        //			if ("00320541".equals(pid)) {
        //				System.out.println("开始处理了");
        //			}
        //			System.out.println("pId =" + pid);
        traveledPIdx++;
        List<String> transAttrList = new LinkedList<String>();
        vn.push();
        // 寻找可翻译的属性,并添加到 transAttrList 中,这时的属性值已经为占位符了。
        childAP.selectXPath("./w:r/w:pict/v:shape/@alt");
        while (childAP.evalXPath() != -1) {
            String altText = vn.toRawString(vn.getCurrentIndex() + 1);
            transAttrList.add(altText);
        }
        vn.pop();
        // 寻找当前 w:p 节点是否有脚注,如果有,则最后时添加
        List<String> footerNodesIdList = new LinkedList<String>();
        getFooterNodesId(footerNodesIdList);
        // 录找当前 w:p 节点是否有批注,如果有,则最后时添加
        List<String> commentsIdList = new LinkedList<String>();
        getCommentsId(commentsIdList);
        // 录找当前 w:p 节点是否有尾注,如果有,则最后时添加
        List<String> endNotesIdList = new LinkedList<String>();
        getEndNotesId(endNotesIdList);
        // 开始分析所循环的每一个 w:p 节点
        analysisNodeP();
        // transAttrPlaceHolderStr 为可翻译属性的占位符,通过占位符获取其代替的值,再将值进行分割后写入 trans-unit 中。
        if (transAttrList.size() > 0) {
            for (String transAttrPlaceHolderStr : transAttrList) {
                String transAttrStr = translateAttrMap.get(transAttrPlaceHolderStr);
                if (transAttrStr != null) {
                    String segIdStr = getSegIdFromPlaceHoderStr(transAttrPlaceHolderStr);
                    String[] segs = segmenter.segment(transAttrStr);
                    for (String seg : segs) {
                        // 生成 trans-unit 节点
                        xlfOutput.addTransUnit(seg, segIdStr);
                    }
                }
            }
        }
        // 处理脚注
        if (footerNodesIdList.size() > 0) {
            operateFooterNodes(footerNodesIdList);
        }
        // 处理批注
        if (commentsIdList.size() > 0) {
            operateComments(commentsIdList);
        }
        // 处理尾注
        if (endNotesIdList.size() > 0) {
            operateEndNotes(endNotesIdList);
        }
        monitorWork(subMonitor, traveledPIdx, false);
    }
    monitorWork(subMonitor, traveledPIdx, true);
    subMonitor.done();
    //结束时,先保存修改 footerNodes.xml 文件
    if (footerNodesPart != null) {
        footerNodesPart.outputPart();
    }
    if (commentsPart != null) {
        commentsPart.outputPart();
    }
    if (endNotesPart != null) {
        endNotesPart.outputPart();
    }
    xm.output(partPath);
}
Also used : IProgressMonitor(org.eclipse.core.runtime.IProgressMonitor) SubProgressMonitor(org.eclipse.core.runtime.SubProgressMonitor) LinkedList(java.util.LinkedList)

Example 10 with SubProgressMonitor

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

the class ApplicationWorkbenchWindowAdvisor method restorEditorHistory.

/**
	 * 重新恢复产品上次退时出所保存的编辑器,此修复针对 mac 下的 bug 2998 启动:某客户安装的软件只能使用一次.		robert	2013-05-21
	 */
private void restorEditorHistory() {
    // 只针对 mac 下的用户
    if (System.getProperty("os.name").indexOf("Mac") == -1) {
        return;
    }
    final WorkbenchPage page = (WorkbenchPage) PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
    IRunnableWithProgress runnable = new IRunnableWithProgress() {

        public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
            monitor.beginTask("", 10);
            String tempEditorHistoryLC = ResourcesPlugin.getWorkspace().getRoot().getLocation().append(Constant.TEMP_EDITOR_HISTORY).toOSString();
            File tempEditorHistoryFile = new File(tempEditorHistoryLC);
            if (!tempEditorHistoryFile.exists()) {
                return;
            }
            monitor.worked(1);
            IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
            VTDGen vg = new VTDGen();
            try {
                boolean parseResult = vg.parseFile(tempEditorHistoryLC, true);
                if (!parseResult) {
                    return;
                }
                VTDNav vn = vg.getNav();
                AutoPilot ap = new AutoPilot(vn);
                int storeFileSum = 0;
                ap.selectXPath("count(/editors/editor)");
                storeFileSum = (int) ap.evalXPathToNumber();
                IProgressMonitor subMonitor = new SubProgressMonitor(monitor, 9, SubProgressMonitor.PREPEND_MAIN_LABEL_TO_SUBTASK);
                subMonitor.beginTask("", storeFileSum);
                ap.selectXPath("/editors/editor");
                String editorId = null;
                String localFilePath = null;
                boolean activate = false;
                IEditorReference activateEditorRefe = null;
                IEditorReference firstEditor = null;
                IFile curIFile = null;
                int index = -1;
                while (ap.evalXPath() != -1) {
                    activate = false;
                    editorId = null;
                    localFilePath = null;
                    if ((index = vn.getAttrVal("id")) != -1) {
                        editorId = vn.toRawString(index);
                    }
                    if ((index = vn.getAttrVal("path")) != -1) {
                        localFilePath = vn.toRawString(index);
                    }
                    if (editorId == null || editorId.trim().length() <= 0 || localFilePath == null || localFilePath.trim().length() <= 0) {
                        continue;
                    }
                    if ((index = vn.getAttrVal("active")) != -1) {
                        if ("true".equals(vn.toRawString(index))) {
                            activate = true;
                        }
                    }
                    curIFile = root.getFileForLocation(new Path(localFilePath));
                    if (!curIFile.exists()) {
                        subMonitor.worked(1);
                        continue;
                    }
                    if (activate) {
                        activateEditorRefe = page.getEditorManager().openEditor(editorId, new FileEditorInput(curIFile), false, null);
                        PlatformUI.getWorkbench().getActiveWorkbenchWindow().setActivePage(page);
                    } else {
                        if (firstEditor == null) {
                            firstEditor = page.getEditorManager().openEditor(editorId, new FileEditorInput(curIFile), false, null);
                        } else {
                            page.getEditorManager().openEditor(editorId, new FileEditorInput(curIFile), false, null);
                        }
                        PlatformUI.getWorkbench().getActiveWorkbenchWindow().setActivePage(page);
                    }
                    subMonitor.worked(1);
                }
                PlatformUI.getWorkbench().getActiveWorkbenchWindow().setActivePage(page);
                if (activateEditorRefe != null) {
                    if (firstEditor != null) {
                        page.activate(firstEditor.getEditor(true));
                    }
                    page.activate(activateEditorRefe.getEditor(true));
                }
                subMonitor.done();
                monitor.done();
            } catch (Exception e) {
                LOGGER.error("restore editor file error", e);
            }
        }
    };
    try {
        new ProgressMonitorDialog(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell()).run(true, true, runnable);
    } catch (Exception e) {
        LOGGER.error("restore editor file error", e);
    }
}
Also used : Path(org.eclipse.core.runtime.Path) IFile(org.eclipse.core.resources.IFile) ProgressMonitorDialog(org.eclipse.jface.dialogs.ProgressMonitorDialog) VTDGen(com.ximpleware.VTDGen) SubProgressMonitor(org.eclipse.core.runtime.SubProgressMonitor) CoreException(org.eclipse.core.runtime.CoreException) InvocationTargetException(java.lang.reflect.InvocationTargetException) IRunnableWithProgress(org.eclipse.jface.operation.IRunnableWithProgress) IProgressMonitor(org.eclipse.core.runtime.IProgressMonitor) IWorkbenchPage(org.eclipse.ui.IWorkbenchPage) WorkbenchPage(org.eclipse.ui.internal.WorkbenchPage) IEditorReference(org.eclipse.ui.IEditorReference) IWorkspaceRoot(org.eclipse.core.resources.IWorkspaceRoot) AutoPilot(com.ximpleware.AutoPilot) FileEditorInput(org.eclipse.ui.part.FileEditorInput) IFile(org.eclipse.core.resources.IFile) File(java.io.File) VTDNav(com.ximpleware.VTDNav)

Aggregations

SubProgressMonitor (org.eclipse.core.runtime.SubProgressMonitor)217 IProgressMonitor (org.eclipse.core.runtime.IProgressMonitor)54 NullProgressMonitor (org.eclipse.core.runtime.NullProgressMonitor)53 CoreException (org.eclipse.core.runtime.CoreException)40 OperationCanceledException (org.eclipse.core.runtime.OperationCanceledException)39 ArrayList (java.util.ArrayList)36 IFile (org.eclipse.core.resources.IFile)33 RefactoringStatus (org.eclipse.ltk.core.refactoring.RefactoringStatus)31 ICompilationUnit (org.eclipse.jdt.core.ICompilationUnit)30 IOException (java.io.IOException)23 IType (org.eclipse.jdt.core.IType)19 HashSet (java.util.HashSet)17 IPath (org.eclipse.core.runtime.IPath)17 IResource (org.eclipse.core.resources.IResource)16 IProject (org.eclipse.core.resources.IProject)15 File (java.io.File)14 List (java.util.List)13 IMethod (org.eclipse.jdt.core.IMethod)13 InvocationTargetException (java.lang.reflect.InvocationTargetException)12 HashMap (java.util.HashMap)12