file_name
stringlengths
6
86
file_path
stringlengths
45
249
content
stringlengths
47
6.26M
file_size
int64
47
6.26M
language
stringclasses
1 value
extension
stringclasses
1 value
repo_name
stringclasses
767 values
repo_stars
int64
8
14.4k
repo_forks
int64
0
1.17k
repo_open_issues
int64
0
788
repo_created_at
stringclasses
767 values
repo_pushed_at
stringclasses
767 values
TextRect.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.MIF/src/net/heartsome/cat/converter/mif/bean/TextRect.java
package net.heartsome.cat.converter.mif.bean; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; public class TextRect { private String id; private String vPosition; public boolean validate(){ if(id == null || id.equals("")){ return false; } if(vPosition == null || vPosition.equals("")){ return false; } return true; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getvPosition() { return vPosition; } public void setvPosition(String vPosition) { this.vPosition = vPosition; } public static void main(String[] args){ // List<String> test = new ArrayList<String>(); // test.add("0.58527"); // test.add("1.31806"); // test.add("0.42088"); // // Collections.sort(test); // // System.out.println(test); List<TextRect> textRects = new ArrayList<TextRect>(); TextRect t1 = new TextRect(); t1.setId("1"); t1.setvPosition("0.58527"); textRects.add(t1); t1 = new TextRect(); t1.setId("2"); t1.setvPosition("1.31806"); textRects.add(t1); t1 = new TextRect(); t1.setId("3"); t1.setvPosition("0.42088"); textRects.add(t1); Collections.sort(textRects, new Comparator<TextRect>() { public int compare(TextRect o1, TextRect o2) { String p1 = o1.getvPosition(); String p2 = o2.getvPosition(); return p1.compareTo(p2); } }); for(TextRect t : textRects){ System.out.print(t.getId()); System.out.println(t.getvPosition()); } } }
1,626
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
MifParseBuffer.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.MIF/src/net/heartsome/cat/converter/mif/bean/MifParseBuffer.java
package net.heartsome.cat.converter.mif.bean; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class MifParseBuffer { /** key:id,value:Frame */ private Map<String, Frame> fms; /** key:id,value:Table */ private Map<String, Table> tbls; private List<Page> pages; /** key:reference id,value:TextFlow */ private Map<String, TextFlow> tfs; private List<Marker> markers; public MifParseBuffer() { fms = new HashMap<String, Frame>(); tbls = new HashMap<String, Table>(); pages = new ArrayList<Page>(); tfs = new HashMap<String, TextFlow>(); markers = new ArrayList<Marker>(); } public void appendFrame(Frame fm) { fms.put(fm.getId(), fm); } public void appendTbale(Table tbl) { tbls.put(tbl.getId(), tbl); } public void appendPage(Page page) { pages.add(page); } public void appendTextFlow(TextFlow tf) { tfs.put(tf.getTextRectId(), tf); } public void appendMarker(Marker m){ markers.add(m); } public Frame getFrame(String id) { return fms.get(id); } public Table getTable(String id) { return tbls.get(id); } public List<Page> getPages() { return pages; } public TextFlow getTextFlow(String id) { return tfs.get(id); } public List<Marker> getMarkers(){ return markers; } }
1,300
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
Marker.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.MIF/src/net/heartsome/cat/converter/mif/bean/Marker.java
/** * Marker.java * * Version information : * * Date:2012-8-15 * * Copyright notice : * 本文件及其附带的相关文件包含机密信息,仅限瀚特盛科技有限公司指定的,与本项目有关的内部人员和客户联络人员查阅和使用。 * 如果您不是本保密声明中指定的收件者,请立即销毁本文件,禁止对本文件或根据本文件中的内容采取任何其他行动, * 包括但不限于:泄露本文件中的信息、以任何方式制作本文件全部或部分内容之副本、将本文件或其相关副本提供给任何其他人。 */ package net.heartsome.cat.converter.mif.bean; /** * @author Jason * @version * @since JDK1.6 */ public class Marker { private int offset; private int endOffset; private String content; public Marker() { } public Marker(int offset, int endoffset, String content) { this.offset = offset; this.endOffset = endoffset; this.content = content; } /** @return the offset */ public int getOffset() { return offset; } /** * @param offset * the offset to set */ public void setOffset(int offset) { this.offset = offset; } /** @return the endOffset */ public int getEndOffset() { return endOffset; } /** * @param endOffset * the endOffset to set */ public void setEndOffset(int endOffset) { this.endOffset = endOffset; } /** @return the content */ public String getContent() { return content; } /** * @param content * the content to set */ public void setContent(String content) { this.content = content; } }
1,619
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
TextFlow.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.MIF/src/net/heartsome/cat/converter/mif/bean/TextFlow.java
package net.heartsome.cat.converter.mif.bean; public class TextFlow { private String textRectId; private int offset; private int endOffset; public String getTextRectId() { return textRectId; } public boolean validate(){ if(offset == 0 || endOffset == 0){ return false; } return true; } public void setTextRectId(String textRectId) { this.textRectId = textRectId; } public int getOffset() { return offset; } public void setOffset(int offset) { this.offset = offset; } public int getEndOffset() { return endOffset; } public void setEndOffset(int endOffset) { this.endOffset = endOffset; } }
674
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
Table.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.MIF/src/net/heartsome/cat/converter/mif/bean/Table.java
package net.heartsome.cat.converter.mif.bean; public class Table { private String id; private int offset; private int endOffset; public Table() { } public boolean validate(){ if(id == null || id.equals("")){ return false; } if(offset == 0 && endOffset == 0){ return false; } return true; } public String getId() { return id; } public void setId(String id) { this.id = id; } public int getOffset() { return offset; } public void setOffset(int offset) { this.offset = offset; } public int getEndOffset() { return endOffset; } public void setEndOffset(int endOffset) { this.endOffset = endOffset; } }
704
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
Page.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.MIF/src/net/heartsome/cat/converter/mif/bean/Page.java
package net.heartsome.cat.converter.mif.bean; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; public class Page { private int offset; private int endOffset; private String pageType; private String pageTag; private List<TextRect> textRects; public Page(){ textRects = new ArrayList<TextRect>(); } public boolean validate(){ if(offset == 0 || endOffset == 0){ return false; } if(pageType == null || pageType.equals("")){ return false; } if(pageTag == null && pageTag.equals("")){ return false; } return true; } /** * return the TextRect order by vertical position * @return */ public List<TextRect> getTextRects(){ Collections.sort(textRects, new Comparator<TextRect>() { public int compare(TextRect o1, TextRect o2) { return o1.getvPosition().compareTo(o2.getvPosition()); } }); return textRects; } public void appendTextRect(TextRect tr) { this.textRects.add(tr); } public int getOffset() { return offset; } public void setOffset(int offset) { this.offset = offset; } public int getEndOffset() { return endOffset; } public void setEndOffset(int endOffset) { this.endOffset = endOffset; } public String getPageType() { return pageType; } public void setPageType(String pageType) { this.pageType = pageType; } public String getPageTag() { return pageTag; } public void setPageTag(String pageTag) { this.pageTag = pageTag; } }
1,602
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
MifReaderBuffer.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.MIF/src/net/heartsome/cat/converter/mif/bean/MifReaderBuffer.java
package net.heartsome.cat.converter.mif.bean; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; public class MifReaderBuffer { private List<Object[]> cache; public MifReaderBuffer() { cache = new ArrayList<Object[]>(); } /** * * @param obj * obj[0] must contains the index。 */ public void addBuffer(Object[] obj) { cache.add(obj); } public List<Object[]> getBuffer(Comparator<Object[]> cp) { Collections.sort(cache, cp); return cache; } }
543
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
Frame.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.MIF/src/net/heartsome/cat/converter/mif/bean/Frame.java
package net.heartsome.cat.converter.mif.bean; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; public class Frame { private int offset; private int endOffset; private String id; private List<TextRect> textRects; public Frame() { textRects = new ArrayList<TextRect>(); } /** * return the TextRect order by vertical position * @return */ public List<TextRect> getTextRects(){ Collections.sort(textRects, new Comparator<TextRect>() { public int compare(TextRect o1, TextRect o2) { return o1.getvPosition().compareTo(o2.getvPosition()); } }); return textRects; } public void appendTextRect(TextRect tr) { this.textRects.add(tr); } public int getOffset() { return offset; } public void setOffset(int offset) { this.offset = offset; } public int getEndOffset() { return endOffset; } public void setEndOffset(int endOffset) { this.endOffset = endOffset; } public String getId() { return id; } public void setId(String id) { this.id = id; } }
1,145
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
Messages.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.MIF/src/net/heartsome/cat/converter/mif/resource/Messages.java
/** * Messages.java * * Version information : * * Date:Jan 14, 2010 * * Copyright notice : */ package net.heartsome.cat.converter.mif.resource; import java.util.MissingResourceException; import java.util.ResourceBundle; /** * The Class Messages. * @author John Zhu * @version * @since JDK1.6 */ public final class Messages { /** The Constant BUNDLE_NAME. */ private static final String BUNDLE_NAME = "net.heartsome.cat.converter.mif.resource.mif"; //$NON-NLS-1$ /** The Constant RESOURCE_BUNDLE. */ private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle.getBundle(BUNDLE_NAME); /** * Instantiates a new messages. */ private Messages() { // Do nothing } /** * Gets the string. * @param key * the key * @return the string */ public static String getString(String key) { try { return RESOURCE_BUNDLE.getString(key); } catch (MissingResourceException e) { return '!' + key + '!'; } } }
1,013
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
Xliff2MSOfficeTest.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.word2007/testSrc/net/heartsome/cat/converter/msoffice2007/test/Xliff2MSOfficeTest.java
package net.heartsome.cat.converter.msoffice2007.test; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.io.File; import java.util.HashMap; import java.util.Map; import net.heartsome.cat.converter.Converter; import net.heartsome.cat.converter.ConverterException; import net.heartsome.cat.converter.msoffice2007.Xliff2MSOffice; import org.junit.BeforeClass; import org.junit.Test; public class Xliff2MSOfficeTest { public static Xliff2MSOffice converter = new Xliff2MSOffice(); private String rootFolder = "/data/john/Workspaces/CAT/HSTS7/"; private static String xlfDocxFile = "rc/Test.docx.xlf"; private static String sklDocxFile = "rc/Test.docx.skl"; private static String tgtDocxFile = "rc/Test_en-US.docx"; private static String xlfXlsxFile = "rc/Test.xlsx.xlf"; private static String sklXlsxFile = "rc/Test.xlsx.skl"; private static String tgtXlsxFile = "rc/Test_en-US.xlsx"; private static String xlfPptxFile = "rc/Test.pptx.xlf"; private static String sklPptxFile = "rc/Test.pptx.skl"; private static String tgtPptxFile = "rc/Test_en-US.pptx"; @BeforeClass public static void setUp() { File tgt = new File(tgtXlsxFile); if (tgt.exists()) { tgt.delete(); } tgt = new File(tgtDocxFile); if (tgt.exists()) { tgt.delete(); } tgt = new File(tgtPptxFile); if (tgt.exists()) { tgt.delete(); } } @Test public void testConvertXlsx() throws ConverterException { Map<String, String> args = new HashMap<String, String>(); args.put(Converter.ATTR_TARGET_FILE, tgtXlsxFile); args.put(Converter.ATTR_XLIFF_FILE, xlfXlsxFile); args.put(Converter.ATTR_SKELETON_FILE, sklXlsxFile); args.put(Converter.ATTR_SOURCE_ENCODING, "UTF-8"); args.put(Converter.ATTR_CATALOGUE, rootFolder + "catalogue/catalogue.xml"); // args.put(Converter.ATTR_PROGRAM_FOLDER,rootFolder); Map<String, String> result = converter.convert(args, null); String target = result.get(Converter.ATTR_TARGET_FILE); assertNotNull(target); File tgtFile = new File(target); assertNotNull(tgtFile); assertTrue(tgtFile.exists()); } @Test public void testConvertDocx() throws ConverterException { Map<String, String> args = new HashMap<String, String>(); args.put(Converter.ATTR_TARGET_FILE, tgtDocxFile); args.put(Converter.ATTR_XLIFF_FILE, xlfDocxFile); args.put(Converter.ATTR_SKELETON_FILE, sklDocxFile); args.put(Converter.ATTR_SOURCE_ENCODING, "UTF-8"); args.put(Converter.ATTR_CATALOGUE, rootFolder + "catalogue/catalogue.xml"); // args.put(Converter.ATTR_PROGRAM_FOLDER,rootFolder); Map<String, String> result = converter.convert(args, null); String target = result.get(Converter.ATTR_TARGET_FILE); assertNotNull(target); File tgtFile = new File(target); assertNotNull(tgtFile); assertTrue(tgtFile.exists()); } @Test public void testConvertPptx() throws ConverterException { Map<String, String> args = new HashMap<String, String>(); args.put(Converter.ATTR_TARGET_FILE, tgtPptxFile); args.put(Converter.ATTR_XLIFF_FILE, xlfPptxFile); args.put(Converter.ATTR_SKELETON_FILE, sklPptxFile); args.put(Converter.ATTR_SOURCE_ENCODING, "UTF-8"); args.put(Converter.ATTR_CATALOGUE, rootFolder + "catalogue/catalogue.xml"); // args.put(Converter.ATTR_PROGRAM_FOLDER,rootFolder); Map<String, String> result = converter.convert(args, null); String target = result.get(Converter.ATTR_TARGET_FILE); assertNotNull(target); File tgtFile = new File(target); assertNotNull(tgtFile); assertTrue(tgtFile.exists()); } }
3,566
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
MSOffice2XliffTest.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.word2007/testSrc/net/heartsome/cat/converter/msoffice2007/test/MSOffice2XliffTest.java
package net.heartsome.cat.converter.msoffice2007.test; import static org.junit.Assert.*; import java.io.File; import java.util.HashMap; import java.util.Map; import net.heartsome.cat.converter.Converter; import net.heartsome.cat.converter.ConverterException; import net.heartsome.cat.converter.msoffice2007.MSOffice2Xliff; import org.junit.BeforeClass; import org.junit.Test; public class MSOffice2XliffTest { public static MSOffice2Xliff converter = new MSOffice2Xliff(); private static String rootFolder = "/data/john/Workspaces/CAT/HSTS7/"; private static String srcDocxFile = "rc/Test.docx"; private static String xlfDocxFile = "rc/Test.docx.xlf"; private static String sklDocxFile = "rc/Test.docx.skl"; private static String srcXlsxFile = "rc/Test.xlsx"; private static String xlfXlsxFile = "rc/Test.xlsx.xlf"; private static String sklXlsxFile = "rc/Test.xlsx.skl"; private static String srcPptxFile = "rc/Test.pptx"; private static String xlfPptxFile = "rc/Test.pptx.xlf"; private static String sklPptxFile = "rc/Test.pptx.skl"; @BeforeClass public static void setUp() { File xlf = new File(xlfDocxFile); if (xlf.exists()) { xlf.delete(); } File skl = new File(sklDocxFile); if (skl.exists()) { skl.delete(); } xlf = new File(xlfXlsxFile); if (xlf.exists()) { xlf.delete(); } skl = new File(sklXlsxFile); if (skl.exists()) { skl.delete(); } xlf = new File(xlfPptxFile); if (xlf.exists()) { xlf.delete(); } skl = new File(sklPptxFile); if (skl.exists()) { skl.delete(); } } @Test public void testConvertXlsx() throws ConverterException { Map<String, String> args = new HashMap<String, String>(); args.put(Converter.ATTR_SOURCE_FILE, srcXlsxFile); //$NON-NLS-1$ args.put(Converter.ATTR_XLIFF_FILE, xlfXlsxFile); //$NON-NLS-1$ args.put(Converter.ATTR_SKELETON_FILE, sklXlsxFile); //$NON-NLS-1$ args.put(Converter.ATTR_SOURCE_LANGUAGE, "zh-CN"); //$NON-NLS-1$ args.put(Converter.ATTR_SOURCE_ENCODING, "UTF-8"); //$NON-NLS-1$ args.put(Converter.ATTR_CATALOGUE, rootFolder + "catalogue/catalogue.xml"); args.put(Converter.ATTR_SRX, rootFolder + "srx/default_rules.srx"); args.put(Converter.ATTR_PROGRAM_FOLDER, rootFolder); Map<String, String> result = converter.convert(args, null); String xliff = result.get(Converter.ATTR_XLIFF_FILE); assertNotNull(xliff); File xlfFile = new File(xliff); assertNotNull(xlfFile); assertTrue(xlfFile.exists()); } @Test public void testConvertDocx() throws ConverterException { Map<String, String> args = new HashMap<String, String>(); args.put(Converter.ATTR_SOURCE_FILE, srcDocxFile); //$NON-NLS-1$ args.put(Converter.ATTR_XLIFF_FILE, xlfDocxFile); //$NON-NLS-1$ args.put(Converter.ATTR_SKELETON_FILE, sklDocxFile); //$NON-NLS-1$ args.put(Converter.ATTR_SOURCE_LANGUAGE, "zh-CN"); //$NON-NLS-1$ args.put(Converter.ATTR_SOURCE_ENCODING, "UTF-8"); //$NON-NLS-1$ args.put(Converter.ATTR_CATALOGUE, rootFolder + "catalogue/catalogue.xml"); args.put(Converter.ATTR_SRX, rootFolder + "srx/default_rules.srx"); args.put(Converter.ATTR_PROGRAM_FOLDER, rootFolder); Map<String, String> result = converter.convert(args, null); String xliff = result.get(Converter.ATTR_XLIFF_FILE); assertNotNull(xliff); File xlfFile = new File(xliff); assertNotNull(xlfFile); assertTrue(xlfFile.exists()); } @Test public void testConvertPptx() throws ConverterException { Map<String, String> args = new HashMap<String, String>(); args.put(Converter.ATTR_SOURCE_FILE, srcPptxFile); //$NON-NLS-1$ args.put(Converter.ATTR_XLIFF_FILE, xlfPptxFile); //$NON-NLS-1$ args.put(Converter.ATTR_SKELETON_FILE, sklPptxFile); //$NON-NLS-1$ args.put(Converter.ATTR_SOURCE_LANGUAGE, "zh-CN"); //$NON-NLS-1$ args.put(Converter.ATTR_SOURCE_ENCODING, "UTF-8"); //$NON-NLS-1$ args.put(Converter.ATTR_CATALOGUE, rootFolder + "catalogue/catalogue.xml"); args.put(Converter.ATTR_SRX, rootFolder + "srx/default_rules.srx"); args.put(Converter.ATTR_PROGRAM_FOLDER, rootFolder); Map<String, String> result = converter.convert(args, null); String xliff = result.get(Converter.ATTR_XLIFF_FILE); assertNotNull(xliff); File xlfFile = new File(xliff); assertNotNull(xlfFile); assertTrue(xlfFile.exists()); } }
4,289
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
Xliff2Docx.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.word2007/src/net/heartsome/cat/converter/word2007/Xliff2Docx.java
/** * Xliff2MSOffice.java * * Version information : * * Date:Jan 14, 2010 * * Copyright notice : */ package net.heartsome.cat.converter.word2007; import java.io.File; import java.util.HashMap; import java.util.Map; import net.heartsome.cat.converter.Converter; import net.heartsome.cat.converter.ConverterException; import net.heartsome.cat.converter.util.ConverterUtils; import net.heartsome.cat.converter.util.Progress; import net.heartsome.cat.converter.util.ReverseConversionInfoLogRecord; import net.heartsome.cat.converter.word2007.common.PathConstant; import net.heartsome.cat.converter.word2007.common.PathUtil; import net.heartsome.cat.converter.word2007.common.ZipUtil; import net.heartsome.cat.converter.word2007.partOper.DocumentPart; import net.heartsome.cat.converter.word2007.partOper.DocumentRelation; import net.heartsome.cat.converter.word2007.resource.Messages; import net.heartsome.util.CommonFunctions; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.OperationCanceledException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * The Class Xliff2MSOffice. * @author robert 2012-08-20 * @version * @since JDK1.6 */ public class Xliff2Docx implements Converter { public static final Logger LOGGER = LoggerFactory.getLogger(Xliff2Docx.class); /** The Constant TYPE_VALUE. */ public static final String TYPE_VALUE = "x-msofficeWord2007"; /** The Constant TYPE_NAME_VALUE. */ public static final String TYPE_NAME_VALUE = Messages.getString("utils.FileFormatUtils.MSWORD2007"); /** The Constant NAME_VALUE. */ public static final String NAME_VALUE = "XLIFF to MS Office Word 2007 Conveter"; /** * (non-Javadoc) * @see net.heartsome.cat.converter.Converter#convert(java.util.Map, org.eclipse.core.runtime.IProgressMonitor) * @param args * @param monitor * @return * @throws ConverterException */ public Map<String, String> convert(Map<String, String> args, IProgressMonitor monitor) throws ConverterException { Xliff2DocxImpl converter = new Xliff2DocxImpl(); return converter.run(args, monitor); } /** * (non-Javadoc) * @see net.heartsome.cat.converter.Converter#getName() * @return */ public String getName() { return NAME_VALUE; } /** * (non-Javadoc) * @see net.heartsome.cat.converter.Converter#getType() * @return */ public String getType() { return TYPE_VALUE; } /** * (non-Javadoc) * @see net.heartsome.cat.converter.Converter#getTypeName() * @return */ public String getTypeName() { return TYPE_NAME_VALUE; } /** * The Class Xliff2MSOfficeImpl. * @author robert 2012-08-20 * @version * @since JDK1.6 */ class Xliff2DocxImpl { /** The catalogue. */ private PathUtil pathUtil; /** * Run. * @param args * the args * @param monitor * the monitor * @return the map< string, string> * @throws ConverterException * the converter exception */ public Map<String, String> run(Map<String, String> args, IProgressMonitor monitor) throws ConverterException { monitor = Progress.getMonitor(monitor); ReverseConversionInfoLogRecord infoLogger = ConverterUtils.getReverseConversionInfoLogRecord(); infoLogger.startConversion(); Map<String, String> result = new HashMap<String, String>(); // 备注,这个 xliffFile 文件是原xliff,不做任何修改,要执行修改的是下面的 tempXLiffFile String xliffFile = args.get(Converter.ATTR_XLIFF_FILE); String outputFile = args.get(Converter.ATTR_TARGET_FILE); String skeleton = args.get(Converter.ATTR_SKELETON_FILE); try { File tempXLiffFile = File.createTempFile("tempxliff", "hsxliff"); tempXLiffFile.deleteOnExit(); CommonFunctions.copyFile(new File(xliffFile), tempXLiffFile); // 把转换过程分为三部分共 20 个任务,解压压缩各1个,页眉,页脚,批注,脚注,尾注各1个,其余 13 个为处理主文档 monitor.beginTask("", 20); // infoLogger.logConversionFileInfo(catalogue, null, xliffFile, null); // IProgressMonitor separateMonitor = Progress.getSubMonitor(monitor, 8); // long startTime = 0; // LOGGER.info(Messages.getString("msoffice2007.Xliff2MSOffice.logger1"), startTime); monitor.setTaskName(Messages.getString("xlf2Docx.task6")); String tempFolder = System.getProperty("java.io.tmpdir") + System.getProperty("file.separator") + new File(skeleton).getName(); String docxFolderPath = ZipUtil.upZipFile(skeleton, tempFolder); pathUtil = new PathUtil(docxFolderPath); monitor.worked(1); if (monitor.isCanceled()) { throw new OperationCanceledException(Messages.getString("docxConvert.task3")); } // 定义一个 hsxliff 的读入器 XliffInputer xlfInput = new XliffInputer(tempXLiffFile.getAbsolutePath(), pathUtil); // 正转换是从 主文档入手的,而逆转换则是从 word/_rels/document.xml.rels 入手,先处理掉 页眉,页脚,脚注,批注,尾注 String docRelsPath = pathUtil.getPackageFilePath(PathConstant.DOCUMENTRELS, false); DocumentRelation docRels = new DocumentRelation(docRelsPath, pathUtil); docRels.arrangeRelations(xlfInput, monitor); // 这里用掉 5 个格子 // 再处理主文档 pathUtil.setSuperRoot(); String docPath = pathUtil.getPackageFilePath(PathConstant.DOCUMENT, false); DocumentPart documentPart = new DocumentPart(docPath, xlfInput, monitor); documentPart.reverseConvert(); monitor.setTaskName(Messages.getString("xlf2Docx.task6")); ZipUtil.zipFolder(outputFile, pathUtil.getSuperRoot()); monitor.worked(1); if (monitor.isCanceled()) { throw new OperationCanceledException(Messages.getString("docxConvert.task3")); } } catch (OperationCanceledException e) { throw e; }catch (Exception e) { e.printStackTrace(); if (Converter.DEBUG_MODE) { e.printStackTrace(); } ConverterUtils.throwConverterException(Activator.PLUGIN_ID, Messages.getString("xlf2Docx.msg1"), e); } finally { deleteFileOrFolder(new File(pathUtil.getSuperRoot())); monitor.done(); } infoLogger.endConversion(); result.put(Converter.ATTR_TARGET_FILE, outputFile); return result; } } public static void deleteFileOrFolder(File file) { if (file.exists()) { if (file.isFile()) { file.delete(); } else if (file.isDirectory()) { File files[] = file.listFiles(); for (int i = 0; i < files.length; i++) { deleteFileOrFolder(files[i]); } } file.delete(); } } }
6,611
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
Activator.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.word2007/src/net/heartsome/cat/converter/word2007/Activator.java
package net.heartsome.cat.converter.word2007; import java.util.Properties; import net.heartsome.cat.converter.Converter; import net.heartsome.cat.converter.util.ConverterRegister; import org.eclipse.ui.plugin.AbstractUIPlugin; import org.osgi.framework.BundleActivator; import org.osgi.framework.BundleContext; import org.osgi.framework.ServiceRegistration; /** * The activator class controls the plug-in life cycle * word 2007 转换器的 Activator。 --robert 2012-08-28 */ public class Activator extends AbstractUIPlugin implements BundleActivator { // The plug-in ID public static final String PLUGIN_ID = "net.heartsome.cat.converter.trados2009"; //$NON-NLS-1$ // The shared instance private static Activator plugin; /** trados 2009文件转换至xliff文件的服务注册器 */ @SuppressWarnings("rawtypes") private ServiceRegistration docx2XliffSR; /** xliff文件转换至trados 2009文件的服务注册器 */ @SuppressWarnings("rawtypes") private ServiceRegistration xliff2DocxSR; /** * The constructor */ public Activator() { } /* * (non-Javadoc) * @see org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext) */ public void start(BundleContext context) throws Exception { plugin = this; Converter docx2Xliff = new Docx2Xliff(); Properties properties = new Properties(); properties.put(Converter.ATTR_NAME, Docx2Xliff.NAME_VALUE); properties.put(Converter.ATTR_TYPE, Docx2Xliff.TYPE_VALUE); properties.put(Converter.ATTR_TYPE_NAME, Docx2Xliff.TYPE_NAME_VALUE); docx2XliffSR = ConverterRegister.registerPositiveConverter(context, docx2Xliff, properties); Converter xliff2Docx = new Xliff2Docx(); properties = new Properties(); properties.put(Converter.ATTR_NAME, Xliff2Docx.NAME_VALUE); properties.put(Converter.ATTR_TYPE, Xliff2Docx.TYPE_VALUE); properties.put(Converter.ATTR_TYPE_NAME, Xliff2Docx.TYPE_NAME_VALUE); xliff2DocxSR = ConverterRegister.registerReverseConverter(context, xliff2Docx, properties); } /* * (non-Javadoc) * @see org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext) */ public void stop(BundleContext context) throws Exception { if (docx2XliffSR != null) { docx2XliffSR.unregister(); docx2XliffSR = null; } if (xliff2DocxSR != null) { xliff2DocxSR.unregister(); xliff2DocxSR = null; } plugin = null; } /** * Returns the shared instance * * @return the shared instance */ public static Activator getDefault() { return plugin; } }
2,527
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
XliffOutputer.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.word2007/src/net/heartsome/cat/converter/word2007/XliffOutputer.java
package net.heartsome.cat.converter.word2007; import java.io.FileOutputStream; import java.io.IOException; import net.heartsome.cat.converter.Converter; import net.heartsome.util.CRC16; import net.heartsome.util.TextUtil; /** * word 2007 转换至 xliff 文件时,xliff 文件的写入操作类。 * @author robert 2012-08-08 */ public class XliffOutputer { /** xliff 文件的路径 */ private String xliffPath; /** xliff 文件的源语言 */ private String sourceLanguage; /** xliff 文件的目标语言 */ private String targetLanguage; private FileOutputStream output; /** trans-unit 节点的id */ private int segId; /** 所有 标记的 id */ private int tagId; public XliffOutputer(){} public XliffOutputer(String xliffPath, String sourceLanguage, String targetLanguage) throws Exception { this.xliffPath = xliffPath; this.sourceLanguage = sourceLanguage; this.targetLanguage = targetLanguage; output = new FileOutputStream(this.xliffPath); } /** * 写下 xliff 文件的头信息 * @throws IOException */ public void writeHeader(String inputFile, String skeletonFile, boolean isSuite, String srcEncoding, String qtToolID) throws IOException { writeOut("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n"); writeOut("<xliff version=\"1.2\" xmlns=\"urn:oasis:names:tc:xliff:document:1.2\" " + "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" " + "xmlns:hs=\"" + Converter.HSNAMESPACE + "\" " + "xsi:schemaLocation=\"urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd " + Converter.HSSCHEMALOCATION + "\">\n"); if (!targetLanguage.equals("")) { writeOut("<file datatype=\"x-msofficeWord2007\" original=\"" + cleanString(inputFile) + "\" source-language=\"" + sourceLanguage + "\" target-language=\"" + targetLanguage + "\">\n"); }else { writeOut("<file datatype=\"x-msofficeWord2007\" original=\"" + cleanString(inputFile) + "\" source-language=\"" + sourceLanguage + "\">\n"); } writeOut("<header>\n"); writeOut("<skl>\n"); if (isSuite) { writeOut("<external-file crc=\"" + CRC16.crc16(TextUtil.cleanString(skeletonFile).getBytes("UTF-8")) + "\" href=\"" + cleanString(skeletonFile) + "\"/>\n"); } else { writeOut("<external-file href=\"" + cleanString(skeletonFile) + "\"/>\n"); } writeOut("</skl>\n"); writeOut(" <tool tool-id=\"" + qtToolID + "\" tool-name=\"HSStudio\"/>\n"); writeOut(" <hs:prop-group name=\"encoding\"><hs:prop prop-type=\"encoding\">" + srcEncoding + "</hs:prop></hs:prop-group>\n"); writeOut("</header>\n<body>\n"); writeOut("\n"); } private void writeOut(String string) throws IOException { output.write(string.getBytes("UTF-8")); } /** * 写入xliff文件的结束标记 */ public void outputEndTag() throws Exception{ writeOut("</body>\n</file>\n</xliff>"); } /** * 关闭 xliff 的写入流 */ public void close() throws Exception{ output.close(); } public String cleanString(String string) { string = string.replaceAll("&", "&amp;"); string = string.replaceAll("<", "&lt;"); string = string.replaceAll(">", "&gt;"); string = string.replaceAll("\"", "&quot;"); return string; } public int getSegId() { return segId; } public int getTagId() { return tagId; } /** * 设置phId 步增一值 */ public int useTagId() { return tagId++; } public int useSegId(){ return segId++; } /** * 生成 trans-unit 节点 * @param source */ public String addTransUnit(String source) throws Exception { if (source.length() > 0) { StringBuffer sb = new StringBuffer(); sb.append("\t<trans-unit id=\"" + segId + "\" xml:space=\"preserve\">\n"); sb.append("\t\t<source xml:lang=\""+ sourceLanguage +"\">"); sb.append(source); sb.append("</source>\n"); sb.append("\t</trans-unit>\n"); writeOut(sb.toString()); return "%%%" + (segId++) + "%%%"; } return null; } /** * 生成 trans-unit 节点 * @param source */ public void addTransUnit(String source, String segIdStr) throws Exception { if (source.length() > 0) { StringBuffer sb = new StringBuffer(); sb.append("\t<trans-unit id=\"" + segIdStr + "\" xml:space=\"preserve\">\n"); sb.append("\t\t<source xml:lang=\""+ sourceLanguage +"\">"); sb.append(source); sb.append("</source>\n"); sb.append("\t</trans-unit>\n"); writeOut(sb.toString()); } } public static void main(String[] args) { // String a = "<w:fldSimple w:instr=\" DOCPROPERTY \"Variable test\" \\* MERGEFORMAT \"><w:r><w:rPr><w:rFonts w:eastAsia=\"宋体\"/><w:sz w:val=\"22\"/><w:szCs w:val=\"22\"/><w:lang w:eastAsia=\"zh-CN\"/></w:rPr><w:t>Irrigation Pump</w:t></w:r></w:fldSimple>"; String a = "<w:fldSimple w:instr=\"DOCPROPERTY &quot;Variable test&quot; \\* MERGEFORMAT \"><w:r><w:rPr><w:rFonts w:eastAsia=\"宋体\"/>" +"<w:sz w:val=\"22\"/><w:szCs w:val=\"22\"/><w:lang w:eastAsia=\"zh-CN\"/></w:rPr><w:t>Irrigation Pump</w:t></w:r></w:fldSimple>"; System.out.println(cleanString11(a)); } public static String cleanString11(String string) { string = string.replaceAll("&", "&amp;"); string = string.replaceAll("<", "&lt;"); string = string.replaceAll(">", "&gt;"); string = string.replaceAll("\"", "&quot;"); return string; } }
5,333
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
PartOperate.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.word2007/src/net/heartsome/cat/converter/word2007/PartOperate.java
package net.heartsome.cat.converter.word2007; import java.text.MessageFormat; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.TreeMap; import net.heartsome.cat.converter.StringSegmenter; import net.heartsome.cat.converter.word2007.common.DocxConverterException; import net.heartsome.cat.converter.word2007.common.SectionSegBean; import net.heartsome.cat.converter.word2007.resource.Messages; import net.heartsome.xml.vtdimpl.VTDUtils; import com.ximpleware.AutoPilot; import com.ximpleware.VTDGen; import com.ximpleware.VTDNav; import com.ximpleware.XMLModifier; /** * 每个要处理的文件(比如 document.xml) 的父类,主要提示 vtd 的处理以及其他相公用方法 * @author robert 2012-08-08 */ public abstract class PartOperate { /** 文件的绝对路径 */ protected String partPath; protected VTDNav vn; protected AutoPilot ap; protected XMLModifier xm; protected VTDUtils vu; /** 其他进行循环用的 autopilot */ protected AutoPilot otherAP; /** 这个 AutoPilot 实例,是在ap 的循环中使用的 */ protected AutoPilot childAP; /** 扩展性 AutoPilot 实例,用于其扩展性情况 */ protected AutoPilot extendAP; /** 可翻译的属性的内容集合 */ protected Map<String, String> translateAttrMap; protected XliffOutputer xlfOutput; /** 命名空间 */ protected Map<String, String> nameSpaceMap = new HashMap<String, String>(); /** 分段规则 */ protected StringSegmenter segmenter; protected XliffInputer xlfInput; /** 是否是链接 */ private boolean isLink = false; /** 链接文本 */ private String linkText = null; /** * 正向转换所用到的构造方法 * @param partPath * @param xlfOutput * @param segmenter * @throws Exception */ public PartOperate(String partPath, XliffOutputer xlfOutput, StringSegmenter segmenter){ this.partPath = partPath; this.xlfOutput = xlfOutput; this.segmenter = segmenter; translateAttrMap = new HashMap<String, String>(); } /** * 逆转换用到的构造函数 * @param partPath * @param xlfInput */ public PartOperate(String partPath, XliffInputer xlfInput){ this.partPath = partPath; this.xlfInput = xlfInput; } /** * 解析文件 * @param nameSpaceMap 要申明的命名空间 * @throws Exception */ protected void loadFile(Map<String, String> nameSpaceMap) throws Exception { VTDGen vg = new VTDGen(); if (vg.parseFile(partPath, true)) { vn = vg.getNav(); ap = new AutoPilot(vn); otherAP = new AutoPilot(vn); childAP = new AutoPilot(vn); extendAP = new AutoPilot(vn); vu = new VTDUtils(vn); xm = new XMLModifier(vn); // 给 ap 申明命名空间 for(Entry<String, String> entry : nameSpaceMap.entrySet()){ ap.declareXPathNameSpace(entry.getKey(), entry.getValue()); childAP.declareXPathNameSpace(entry.getKey(), entry.getValue()); otherAP.declareXPathNameSpace(entry.getKey(), entry.getValue()); extendAP.declareXPathNameSpace(entry.getKey(), entry.getValue()); } }else { throw new DocxConverterException(MessageFormat.format(Messages.getString("docxConvert.msg2"), partPath)); } } /** * 开始运行正向转换,即 word 2007 转换成 hsxliff */ protected abstract void converter() throws Exception; /** * 开始运行逆转换 * @throws Exception */ protected abstract void reverseConvert() throws Exception; /** * 获取一个 p 节点的样式,限制:当前 vn 所处地点必须为 w:p * @param vn * @return */ protected String getPStyle() throws Exception { String style = null; vn.push(); otherAP.selectXPath("./w:pPr/w:rPr"); while (otherAP.evalXPath() != -1) { style = vu.getElementFragment(); } vn.pop(); return style; } /** * 获取一个文本段的格式,限制:当前的 vn 所处地点必须为 w:r * @return * @throws Exception */ protected String getRStyle() throws Exception { String style = null; vn.push(); otherAP.selectXPath("./w:rPr"); while (otherAP.evalXPath() != -1) { style = vu.getElementFragment(); } vn.pop(); if (style != null) { // 主要是针对 <w:font /> 与 <w:font>的情况,去除多作的空格 style = style.replace(" />", "/>").trim(); } return style; } /** * 获取一个 w:r 节点除样式(w:rPr)与文本(w:t)之外的其他结点 * @return * @throws Exception */ protected String getExtendNodes() throws Exception { String extendNodesStr = null; StringBuffer extendNodesSB = new StringBuffer(); vn.push(); otherAP.selectXPath("./node()[name()!='w:rPr' and name()!='w:t']"); while (otherAP.evalXPath() != -1) { extendNodesSB.append(vu.getElementFragment()); } vn.pop(); extendNodesStr = extendNodesSB.toString(); return extendNodesStr; } /** * 获取一个 w:r 节点里面的文本值。针对于 w:p/w:r/w:t * @return * @throws Exception */ protected String getText() throws Exception { String nodeName = vn.toRawString(vn.getCurrentIndex()); if ("w:fldSimple".equals(nodeName)) { return null; } if ("w:hyperlink".equals(nodeName)) { if (vn.getAttrVal("w:anchor") != -1) { return null; } } StringBuffer textSB = new StringBuffer(); vn.push(); otherAP.selectXPath("./descendant::w:t/text()"); while (otherAP.evalXPath() != -1) { textSB.append(vn.toRawString(vn.getCurrentIndex())); } vn.pop(); if (textSB.length() <= 0) { return null; } return textSB.toString(); } // <w:hyperlink r:id="rId5" w:history="1"> // <w:r w:rsidRPr="007267A9"> // <w:rPr> // <w:rStyle w:val="a5" /> // <w:noProof /> // </w:rPr> // <w:t>www.baidu.</w:t> // </w:r> // <w:r w:rsidRPr="0077163A"> // <w:rPr> // <w:rStyle w:val="a5" /> // <w:noProof /> // <w:color w:val="FF0000" /> // </w:rPr> // <w:t>com</w:t> // </w:r> // </w:hyperlink> /** * 获取链接的特殊文本<br/> * 备注:上面是一个关于 w:hyperlink 的例子,这时,一个 w:hyperlink 就当作一个 g 标记进行处理。那么,它的特列文本 就是其应提取的所有内容,不单指 "www.baidu.com",而是 3 个 w:r 节点。<br/> * 若当前节点中只有一个 w:r 节点,那么不予考虑。返回 null, 若有多个 w:r 节点,那将它们拼接成 sub 与 ph 标记组合的文本,当作 特殊文本进行返回。 * @return */ private String getLinkText() throws Exception{ vn.push(); String curLinkText = null; int rNodeCount = getNodeCount("./w:r"); if (rNodeCount == 1) { return curLinkText; } List<SectionSegBean> segList = new LinkedList<SectionSegBean>(); extendAP.selectXPath("./node()"); while(extendAP.evalXPath() != -1){ String rStyle = getRStyle(); String text = ""; String extendNodesStr = getExtendNodes(); int tNodeCount = getNodeCount("./w:t"); // 有 t 节点的,就一定有数据 if (tNodeCount == 1) { text = getText(); // extendNodesAttr 这个属性是自定义的,专门针对于除样式与文本之外的其他节点,如 <w:tab/> String extendNodesAttr = ("".equals(extendNodesStr) || extendNodesStr == null) ? "" : " extendNodes='"+ xlfOutput.cleanString(extendNodesStr) +"'"; // rprAttr 这个是保存 rpr 属性的。rpr属性是用于保存 w:r 样式。 String rprAttr = ("".equals(rStyle) || rStyle == null) ? "" : " rPr='" + xlfOutput.cleanString(rStyle) + "'"; segList.add(new SectionSegBean(null, text, rprAttr, extendNodesAttr, null)); }else { String phTagStr = vu.getElementFragment(); segList.add(new SectionSegBean(null, null, null, null, xlfOutput.cleanString(phTagStr))); } } vn.pop(); StringBuffer specialTextSB = new StringBuffer(); SectionSegBean bean; for (int i = 0; i < segList.size(); i++) { bean = segList.get(i); String style = bean.getStyle() == null ? "" : bean.getStyle(); String extendNodes = bean.getExtendNodesStr() == null ? "" : bean.getExtendNodesStr(); if (("".equals(style)) && ("".equals(extendNodes)) && bean.getPhTagStr() == null) { specialTextSB.append(bean.getText()); }else if (bean.getPhTagStr() == null) { specialTextSB.append("<sub id='" + xlfOutput.useTagId() + "'" + style + extendNodes +">"); specialTextSB.append(bean.getText()); // 判断下一个是否样式与扩展节点的内容都相同,若相同,就组装成一个g标记 while(i + 1 < segList.size()){ bean = segList.get(i +1); String curStyle = bean.getStyle() == null ? "" : bean.getStyle(); String curExtendNodes = bean.getExtendNodesStr() == null ? "" : bean.getExtendNodesStr(); // 当两个的 ctype 都为空时,才能进行拼接,因为 ctype 多半为 <w:hyperlink .... > if (curStyle.equals(style) && curExtendNodes.equals(extendNodes)) { specialTextSB.append(bean.getText()); i++; }else { break; } } specialTextSB.append("</sub>"); }else { String phTagStr = bean.getPhTagStr(); if (!"".equals(phTagStr.trim())) { specialTextSB.append("<ph id='" + xlfOutput.useTagId() + "'>"); specialTextSB.append(phTagStr); while(i + 1 < segList.size()){ bean = segList.get(i +1); if (bean.getPhTagStr() != null) { specialTextSB.append(bean.getPhTagStr()); i++; }else { break; } } specialTextSB.append("</ph>"); } } } curLinkText = specialTextSB.toString(); if (curLinkText.length() == 0) { curLinkText = null; } return curLinkText; } /** * 获取节点 w:t 的个数,如果个数为1,就不需要粹取标记 * @return * @throws Exception */ protected int getTextCount() throws Exception { int textCount = -1; otherAP.selectXPath("count(./node()[(name()='w:r' or name()='w:hyperlink') and not(@w:anchor) and not(descendant::node()[name()='w:p'])]//w:t)"); textCount = (int) otherAP.evalXPathToNumber(); return textCount; } /** * 获取某个节点的数量, * @param xpath 如 ./w:r/w:t * @return * @throws Exception */ private int getNodeCount(String xpath) throws Exception{ vn.push(); int nodeCount = -1; otherAP.selectXPath("count(" + xpath + ")"); nodeCount = (int) otherAP.evalXPathToNumber(); vn.pop(); return nodeCount; } /** * 将纯文本段更新成占位符,比如将<w:p><w:r><w:t>文本段</w:t></w:r></w:p> 中的“文本段” 更新成 %%%?%%% */ protected void updateTextToPlaceHoder(String placeHolderStr) throws Exception { // 如果是特殊节点,并且不为空,那么直接删除,并添加进占位符 if (isLink && linkText != null) { xm.remove(); String nodeName = vn.toString(vn.getCurrentIndex()); String headStr = vu.getElementHead(); StringBuffer sb = new StringBuffer(); sb.append(headStr); sb.append(placeHolderStr); sb.append("</" + nodeName + ">"); xm.insertAfterElement(sb.toString()); }else { vn.push(); otherAP.selectXPath("./w:t/text()"); while (otherAP.evalXPath() != -1) { xm.updateToken(vn.getCurrentIndex(), placeHolderStr); } vn.pop(); } } /** * 根据一个占位符,获取其占位符序列号的值 * @param placeHolderStr * @return */ protected String getSegIdFromPlaceHoderStr(String placeHolderStr) { String segIdStr = null; int firstPlaceHIdx = placeHolderStr.indexOf("%%%"); segIdStr = placeHolderStr.substring(firstPlaceHIdx + 3, placeHolderStr.indexOf("%%%", firstPlaceHIdx + 1)); return segIdStr.trim(); } /** * 根据多个占位符,获取其所有的占位符序列号的值,例如 %%%5%%%%%%6%%%%%%7%%% * @param placeHolderStr * @return */ protected List<String> getAllSegIdsFromPlaceHoderStr(String placeHolderStr) { List<String> idList = new LinkedList<String>(); int firstPlaceHIdx = placeHolderStr.indexOf("%%%"); while(firstPlaceHIdx != -1){ int endIdx = placeHolderStr.indexOf("%%%", firstPlaceHIdx + 1); String segIdStr = placeHolderStr.substring(firstPlaceHIdx + 3, endIdx); idList.add(segIdStr); firstPlaceHIdx = placeHolderStr.indexOf("%%%", endIdx + 3); } return idList; } /** * 处理可翻译的属性问题,例如 * @throws Exception */ protected void operateTransAttributes(String attrXpath) throws Exception { ap.selectXPath(attrXpath); int index = -1; while(ap.evalXPath() != -1){ index = vn.getCurrentIndex() + 1; if (!"".equals(vn.toRawString(index))) { String placeHoderStr = "%%%" + xlfOutput.useSegId() + "%%%"; translateAttrMap.put(placeHoderStr, vn.toString(index)); xm.updateToken(index, placeHoderStr); } } // 如果有修改的属性。那么,将修改的内容保存到文件,再重新解析文件。 if (translateAttrMap.size() > 0) { xm.output(partPath); loadFile(nameSpaceMap); } } /** * 删除指定字符串的所有空格,因为 trim() 方法无法删除全角字符。 * @return */ public static String deleteBlank(String string){ return string.replaceAll("[  ]", ""); } /** * 分析每个 w:p 节点,将要翻译的东西提取出来,用占位符替代。 * or name()='w:fldSimple' * @throws Exception */ protected void analysisNodeP() throws Exception { // 如果这个节点里面还有 p 节点,那么不进行处理 int textCount = getTextCount(); int index = -1; Map<Integer, SectionSegBean> sectionSegMap = new TreeMap<Integer, SectionSegBean>(); StringBuffer placeHolderSB = new StringBuffer(); // 占位符 // 开始处理每个节点的文本 if (textCount == 1) { // 如果一个节点里面只有一个 w:r//w:t ,那么直接获取出内容,如果这个节点里面还有 p 节点,那么不进行处理 childAP.selectXPath("./node()[(name()='w:r' or name()='w:hyperlink') and not(@w:anchor) and not(descendant::node()[name()='w:p'])]/descendant::w:t/text()"); vn.push(); if(childAP.evalXPath() != -1){ index = vn.getCurrentIndex(); String segment = vn.toRawString(index); if ("".equals(deleteBlank(segment))) { vn.pop(); return; } String[] segs = segmenter.segment(segment); for(String seg : segs){ // 生成 trans-unit 节点 placeHolderSB.append(xlfOutput.addTransUnit(seg)); } xm.updateToken(index, placeHolderSB.toString()); } vn.pop(); }else if (textCount > 1) { // 没有 w:/t 节点的段落,不进行处理。如果这个节点里面还有 p 节点,那么不进行处理 // System.out.println("vn.getCurrentIndex() = " + vn.getCurrentIndex()); // if (185 == vn.getCurrentIndex()) { // System.out.println("调试开始了。。。。"); // } vn.push(); // 先获取出这个段落里所有要翻译的数据,再分段 List<StringBuffer> segList = new ArrayList<StringBuffer>(); StringBuffer segSB = new StringBuffer(); childAP.selectXPath("./node()[(name()='w:r' or name()='w:hyperlink') and not(@w:anchor) and not(descendant::node()[name()='w:p'])]"); while(childAP.evalXPath() != -1){ if (vu.getElementContent().indexOf("<w:br") != -1) { segList.add(segSB); segSB = new StringBuffer(); } String curText = getText(); curText = (curText == null ? "" : curText); segSB.append(curText); } segList.add(segSB); // 如果为空格,直接退出 StringBuffer checkBlankSB = new StringBuffer(); for(StringBuffer curSB : segList){ checkBlankSB.append(curSB); } if (deleteBlank(checkBlankSB.toString()).length() <= 0) { vn.pop(); return; } // System.out.println("checkBlankSB.toString() =" + checkBlankSB.toString()); // if (segSB.toString().indexOf("Definition des vorzuhaltenden") != -1) { // System.out.println("错误信息开始了。。。。。"); // } vn.pop(); // 开始分割文本段 List<String> segArrayList = new ArrayList<String>(); for(StringBuffer curSB : segList){ String[] segArray = segmenter.segment(curSB.toString()); for (int i = 0; i < segArray.length; i++) { segArrayList.add(segArray[i]); } } String[] segArray = segArrayList.toArray(new String[]{}); // 开始遍历每个节点 ./node(),进行处理 vn.push(); childAP.selectXPath("./node()"); boolean segStart = false; // 一个文本段的开始 boolean segOver = false; // 一个文本段结束的标记 int segIdx = 0; String seg = segArray[segIdx]; while(childAP.evalXPath() != -1){ index = vn.getCurrentIndex(); isLink = false; linkText = null; String nodeName = vu.getCurrentElementName(); if ("w:r".equals(nodeName) || "w:hyperlink".equals(nodeName) || "w:fldSimple".equals(nodeName)) { if ("w:hyperlink".equals(nodeName)) { isLink = true; linkText = getLinkText(); } if ("w:r".equals(nodeName)) { // 检查是否有软回车 <w: br/> vn.push(); boolean hasBr = false; extendAP.selectXPath("./w:br"); if (extendAP.evalXPath() != -1) { hasBr = true; } vn.pop(); if (hasBr && (sectionSegMap.size() > 0)) { // 遇到软回车就开始分段 segOver = true; segStart = false; String placeHoderStr = xlfOutput.addTransUnit(createSourceStr(sectionSegMap)); xm.insertBeforeElement(placeHoderStr); segArray[segIdx] = seg; continue; } } String text = getText(); if (text != null) { segStart = true; segOver = false; String ctypeAttrStr = ""; String rStyle = null; String extendNodesStr = null; if (isLink) { ctypeAttrStr = " ctype='" + xlfOutput.cleanString(vu.getElementHead()) + "'"; vn.push(); extendAP.selectXPath("./w:r"); // 取第一个 w:r 节点的 属性,这种情况针对 特殊 节点中只有一个 w:t 的情况, // 如果 linkText 不为空的话,就不用获取 rStyle 与 extendNodesStr 属性了 if (linkText == null && extendAP.evalXPath() != -1) { rStyle = getRStyle(); extendNodesStr = getExtendNodes(); } vn.pop(); }else { rStyle = getRStyle(); extendNodesStr = getExtendNodes(); } // extendNodesAttr 这个属性是自定义的,专门针对于除样式与文本之外的其他节点,如 <w:tab/> String extendNodesAttr = ("".equals(extendNodesStr) || extendNodesStr == null) ? "" : " extendNodes='"+ xlfOutput.cleanString(extendNodesStr) +"'"; // rprAttr 这个是保存 rpr 属性的。rpr属性是用于保存 w:r 样式。 String rprAttr = ("".equals(rStyle) || rStyle == null) ? "" : " rPr='" + xlfOutput.cleanString(rStyle) + "'"; // 如果当前文本是一个独立的分段,则将其文本用占位符替换。 if (text.equals(segArray[segIdx])) { String placeHoderStr = ""; if (isLink && linkText != null) { placeHoderStr = xlfOutput.addTransUnit(linkText); }else { placeHoderStr = xlfOutput.addTransUnit(seg); } updateTextToPlaceHoder(placeHoderStr); if (segIdx + 1 < segArray.length) { seg = segArray[++segIdx]; } segOver = true; segStart = false; continue; } // 链接不应支持分段,现开始分析 if (isLink) { List<Object> resultList = modifySeg(segArray, segIdx, text, seg); segArray = (String[]) resultList.get(0); seg = (String) resultList.get(1); } // 分析分割后的文本段 if (text.equals(seg)) { if ("".equals(rprAttr) && "".equals(extendNodesAttr)) { // 只添加纯文本 sectionSegMap.put(index, newSectionSegBean(ctypeAttrStr, text, null, null, null)); }else { sectionSegMap.put(index, newSectionSegBean(ctypeAttrStr, text, rprAttr, extendNodesAttr, null)); } if (segIdx + 1 < segArray.length) { seg = segArray[++segIdx]; } segOver = true; segStart = false; xm.remove(); String placeHoderStr = xlfOutput.addTransUnit(createSourceStr(sectionSegMap)); xm.insertAfterElement(placeHoderStr); }else if (text.length() < seg.length() && seg.indexOf(text) == 0 ) { // 如果当前文本长度小于分段长度 if ("".equals(rprAttr) && "".equals(extendNodesAttr)) { sectionSegMap.put(index, newSectionSegBean(ctypeAttrStr, text, null, null, null)); }else { sectionSegMap.put(index, newSectionSegBean(ctypeAttrStr, text, rprAttr, extendNodesAttr, null)); } xm.remove(); // 在替换有 "(" 的情况。必须加一个 \\( 或者 [(],否则会报错 seg = seg.substring(text.length()); }else if (text.length() > seg.length() && text.indexOf(seg) == 0) { if ("".equals(rprAttr) && "".equals(extendNodesAttr)) { sectionSegMap.put(index, newSectionSegBean(ctypeAttrStr, seg, null, null, null)); }else { sectionSegMap.put(index, newSectionSegBean(ctypeAttrStr, seg, rprAttr, extendNodesAttr, null)); } text = text.substring(seg.length()); // 由于这里有可能要插入多个占位符,所以要把所有的占位符放到一起,一次性存入,因为 xmlModifial 不允许在同一个地方修改多次。 StringBuffer replaceHolderSB = new StringBuffer(); replaceHolderSB.append(xlfOutput.addTransUnit(createSourceStr(sectionSegMap))); xm.remove(); if (segIdx + 1 < segArray.length) { seg = segArray[++segIdx]; } // 开始处理剩下的文本 while(text.length() != 0){ if (text.equals(seg)) { if ("".equals(rprAttr) && "".equals(extendNodesAttr)) { sectionSegMap.put(index, newSectionSegBean(ctypeAttrStr, text, null, null, null)); }else { sectionSegMap.put(index, newSectionSegBean(ctypeAttrStr, text, rprAttr, extendNodesAttr, null)); } text = ""; segOver = true; segStart = false; replaceHolderSB.append(xlfOutput.addTransUnit(createSourceStr(sectionSegMap))); if (segIdx + 1 < segArray.length) { seg = segArray[++segIdx]; } }else if (text.length() < seg.length() && seg.indexOf(text) == 0) { if ("".equals(rprAttr) && "".equals(extendNodesAttr)) { sectionSegMap.put(index, newSectionSegBean(ctypeAttrStr, text, null, null, null)); }else { sectionSegMap.put(index, newSectionSegBean(ctypeAttrStr, text, rprAttr, extendNodesAttr, null)); } seg = seg.substring(text.length()); text = ""; }else if (text.length() > seg.length() && text.indexOf(seg) == 0) { if ("".equals(rprAttr) && "".equals(extendNodesAttr)) { sectionSegMap.put(index, newSectionSegBean(ctypeAttrStr, seg, null, null, null)); }else { sectionSegMap.put(index, newSectionSegBean(ctypeAttrStr, seg, rprAttr, extendNodesAttr, null)); } text = text.substring(seg.length()); replaceHolderSB.append(xlfOutput.addTransUnit(createSourceStr(sectionSegMap))); if (segIdx + 1 < segArray.length) { seg = segArray[++segIdx]; } } } xm.insertAfterElement(replaceHolderSB.toString()); } }else if(segStart && !segOver){ sectionSegMap.put(index, new SectionSegBean(null, null, null, null, xlfOutput.cleanString(vu.getElementFragment()))); xm.remove(); } }else if(segStart && !segOver){ sectionSegMap.put(index, new SectionSegBean(null, null, null, null, xlfOutput.cleanString(vu.getElementFragment()))); xm.remove(); } } vn.pop(); } } /** * 针对特殊情况,w:hyperlink 里面的文本 不应分段,故将不应分段的进行合并 * @param segArray * @param segIdx * @param text * @return */ private List<Object> modifySeg(String[] segArray, int segIdx, String text, String seg){ List<String> segList = new ArrayList<String>(); int start = segArray[segIdx].lastIndexOf(seg); StringBuffer temSB = new StringBuffer(); segFor:for(int i = 0; i < segArray.length; i++){ if (i < segIdx) { segList.add(segArray[i]); }else if (i == segIdx) { if (text.length() != 0) { temSB.append(segArray[i]); if (text.indexOf(seg) != -1) { text = text.substring(seg.length(), text.length()); }else if(seg.indexOf(text) != -1){ text = ""; } }else { if (temSB.length() != 0) { segList.add(temSB.toString()); temSB = new StringBuffer(); } for(int j = i; j < segArray.length; j ++){ segList.add(segArray[j]); } break segFor; } }else { if (text.length() != 0) { temSB.append(segArray[i]); if (text.indexOf(segArray[i]) != -1) { text = text.substring(segArray[i].length(), text.length()); }else if(segArray[i].indexOf(text) != -1){ text = ""; } }else { if (temSB.length() != 0) { segList.add(temSB.toString()); temSB = new StringBuffer(); } for(int j = i; j < segArray.length; j ++){ segList.add(segArray[j]); } break segFor; } } } if (temSB.length() != 0) { segList.add(temSB.toString()); temSB = new StringBuffer(); } segArray = segList.toArray(new String[]{}); seg = segArray[segIdx].substring(start, segArray[segIdx].length()); List<Object> resultList = new ArrayList<Object>(); resultList.add(segArray); resultList.add(seg); return resultList; } /** * 根据具体情况创建 sectionSegBean */ private SectionSegBean newSectionSegBean(String ctype, String text, String style, String extendNodesStr, String phTagStr){ SectionSegBean bean = null; if (isLink) { if (linkText == null) { bean = new SectionSegBean(ctype, text, style, extendNodesStr, phTagStr); }else { bean = new SectionSegBean(ctype, linkText, null, null, null); } }else { bean = new SectionSegBean(ctype, text, style, extendNodesStr, phTagStr); } return bean; } /** * 通过sectionSegMap生成要添加到 trans-unit 节点的源文本 * @param sectionSegMap * @return */ private String createSourceStr(Map<Integer, SectionSegBean> sectionSegMap) { List<SectionSegBean> segList = new LinkedList<SectionSegBean>(); for(Entry<Integer, SectionSegBean> entry : sectionSegMap.entrySet()){ segList.add(entry.getValue()); } StringBuffer srcTextSB = new StringBuffer(); SectionSegBean bean = null; for (int i = 0; i < segList.size(); i++) { bean = segList.get(i); String ctype = bean.getCtype() == null ? "" : bean.getCtype(); String style = bean.getStyle() == null ? "" : bean.getStyle(); String extendNodes = bean.getExtendNodesStr() == null ? "" : bean.getExtendNodesStr(); if (("".equals(ctype) && "".equals(style)) && ("".equals(extendNodes)) && bean.getPhTagStr() == null) { srcTextSB.append(bean.getText()); }else if (bean.getPhTagStr() == null) { srcTextSB.append("<g id='" + xlfOutput.useTagId() + "'" + ctype + style + extendNodes +">"); srcTextSB.append(bean.getText()); // 判断下一个是否样式与扩展节点的内容都相同,若相同,就组装成一个g标记 while(i + 1 < segList.size()){ bean = segList.get(i +1); String curCtype = bean.getCtype() == null ? "" : bean.getCtype(); String curStyle = bean.getStyle() == null ? "" : bean.getStyle(); String curExtendNodes = bean.getExtendNodesStr() == null ? "" : bean.getExtendNodesStr(); // 当两个的 ctype 都为空时,才能进行拼接,因为 ctype 多半为 <w:hyperlink .... > if (curStyle.equals(style) && curExtendNodes.equals(extendNodes) && "".equals(ctype) && "".equals(curCtype) ) { srcTextSB.append(bean.getText()); i++; }else { break; } } srcTextSB.append("</g>"); }else { String phTagStr = bean.getPhTagStr(); if (!"".equals(phTagStr.trim())) { srcTextSB.append("<ph id='" + xlfOutput.useTagId() + "'>"); srcTextSB.append(phTagStr); while(i + 1 < segList.size()){ bean = segList.get(i +1); if (bean.getPhTagStr() != null) { srcTextSB.append(bean.getPhTagStr()); i++; }else { break; } } srcTextSB.append("</ph>"); } } } sectionSegMap.clear(); return srcTextSB.toString(); } /** * 逆转换时处理 w:p 节点 * @throws Exception */ protected void analysisReversePnode() throws Exception { vn.push(); childAP.selectXPath("./text()|node()[name()='w:r' or name()='w:hyperlink' or name()='w:fldSimple']"); int index = -1; while(childAP.evalXPath() != -1){ index = vn.getCurrentIndex(); int tokenType = vn.getTokenType(index); if (tokenType == 0) { // 表示节点子节点 vn.push(); String nodeName = vn.toString(vn.getCurrentIndex()); String xpath = "./w:t"; if ("w:hyperlink".equals(nodeName) || "w:fldSimple".equals(nodeName)) { // 针对两种情况,一是 <w:hyperlink r:id="rId6" w:history="1">%%%0%%%</w:hyperlink> // 二是 <w:hyperlink r:id="rId6" w:history="1"><w:r><w:t>%%%0%%%</w:r></w:t></w:hyperlink> xpath = "./w:r/w:t"; otherAP.selectXPath(xpath); index = vn.getText(); if (index != -1) { String text = vn.toRawString(index); if (text.indexOf("%%%") != -1) { List<String> segIdList = getAllSegIdsFromPlaceHoderStr(text); String tgtStr = xlfInput.getTargetStrByTUId(segIdList, false); xm.updateToken(index, tgtStr); } }else { if (otherAP.evalXPath() != -1) { index = vn.getText(); if (index != -1) { String text = vn.toRawString(index); if (text.indexOf("%%%") != -1) { List<String> segIdList = getAllSegIdsFromPlaceHoderStr(text); String tgtStr = xlfInput.getTargetStrByTUId(segIdList, true); xm.remove(); xm.insertAfterElement("<w:t xml:space=\"preserve\">" + tgtStr + "</w:t>"); } } } } }else { otherAP.selectXPath(xpath); if (otherAP.evalXPath() != -1) { index = vn.getText(); if (index != -1) { String text = vn.toRawString(index); if (text.indexOf("%%%") != -1) { List<String> segIdList = getAllSegIdsFromPlaceHoderStr(text); String tgtStr = xlfInput.getTargetStrByTUId(segIdList, true); xm.remove(); xm.insertAfterElement("<w:t xml:space=\"preserve\">" + tgtStr + "</w:t>"); } } } } vn.pop(); }else if (tokenType == 5) { // 表示文本子节点 String placeHolderStr = vn.toRawString(index); if (placeHolderStr.indexOf("%%%") != -1) { List<String> segIdList = getAllSegIdsFromPlaceHoderStr(placeHolderStr); String tgtStr = xlfInput.getTargetStrByTUId(segIdList, false); xm.updateToken(index, tgtStr); } } } vn.pop(); } /** * 逆转换处理可翻译属性 * @param xpath * @throws Exception */ protected void reverseTranslateAttributes(String xpath) throws Exception { loadFile(nameSpaceMap); ap.selectXPath(xpath); while(ap.evalXPath() != -1){ String placeHolderStr = vn.toRawString(vn.getCurrentIndex() + 1); List<String> idList = getAllSegIdsFromPlaceHoderStr(placeHolderStr); String text = xlfInput.getTargetStrByTUId(idList, true); xm.updateToken(vn.getCurrentIndex() + 1, text); } xm.output(partPath); } public static void main(String[] args) { // String placeHolderStr = "asd asd fsad %%%5%%%%%%6%%%%%%7%%%dasdfa sdf asd f%%%7%%%"; // List<String> idList = new LinkedList<String>(); // int firstPlaceHIdx = placeHolderStr.indexOf("%%%"); // while(firstPlaceHIdx != -1){ // int endIdx = placeHolderStr.indexOf("%%%", firstPlaceHIdx + 1); // System.out.println("endIdx =" + endIdx); // String segIdStr = placeHolderStr.substring(firstPlaceHIdx + 3, endIdx); // idList.add(segIdStr); // System.out.println(segIdStr); // firstPlaceHIdx = placeHolderStr.indexOf("%%%", endIdx + 3); // } // <w:p w14:paraId="5D139D30" w14:textId="3565E204" w:rsidR="00814583" // w:rsidRDefault="00814583" w:rsidP="00814583"> // <w:pPr> // <w:rPr> // <w:noProof /> // </w:rPr> // </w:pPr> // <w:r> // <w:rPr> // <w:noProof /> // </w:rPr> // <w:t xml:space="preserve">go to </w:t> // </w:r> // <w:hyperlink w:history="1"> // <w:r w:rsidR="000911EF" w:rsidRPr="00F058AA"> // <w:rPr> // <w:rStyle w:val="a5" /> // <w:noProof /> // </w:rPr> // <w:t>www.</w:t> // </w:r> // <w:r w:rsidR="000911EF" w:rsidRPr="00F058AA"> // <w:rPr> // <w:rStyle w:val="a5" /> // <w:rFonts w:hint="eastAsia" /> // <w:noProof /> // </w:rPr> // <w:t>this</w:t> // </w:r> // <w:r w:rsidR="000911EF" w:rsidRPr="00F058AA"> // <w:rPr> // <w:rStyle w:val="a5" /> // <w:noProof /> // </w:rPr> // <w:t xml:space="preserve"> is a test. google.com</w:t> // </w:r> // </w:hyperlink> // </w:p> int segIdx = 0; String text = "www.this is a test. google.com"; // String[] segArray = new String[]{"go to www.this is a test. ", "google.com这后面还有其他东西", "第三块东西"}; String[] segArray = new String[]{"go to www.this is a test. ", "google.com"}; String seg = "www.this is a test. "; List<String> segList = new ArrayList<String>(); int start = segArray[segIdx].lastIndexOf(seg); StringBuffer temSB = new StringBuffer(); segFor:for(int i = 0; i < segArray.length; i++){ if (i < segIdx) { segList.add(segArray[i]); }else if (i == segIdx) { if (text.length() != 0) { temSB.append(segArray[i]); if (text.indexOf(seg) != -1) { text = text.substring(seg.length(), text.length()); }else if(seg.indexOf(text) != -1){ text = ""; } }else { if (temSB.length() != 0) { segList.add(temSB.toString()); temSB = new StringBuffer(); } for(int j = i; j < segArray.length; j ++){ segList.add(segArray[j]); } break segFor; } }else { if (text.length() != 0) { temSB.append(segArray[i]); if (text.indexOf(segArray[i]) != -1) { text = text.substring(segArray[i].length(), text.length()); }else if(segArray[i].indexOf(text) != -1){ text = ""; } }else { if (temSB.length() != 0) { segList.add(temSB.toString()); temSB = new StringBuffer(); } for(int j = i; j < segArray.length; j ++){ segList.add(segArray[j]); } break segFor; } } } if (temSB.length() != 0) { segList.add(temSB.toString()); temSB = new StringBuffer(); } segArray = segList.toArray(new String[]{}); seg = segArray[segIdx].substring(start, segArray[segIdx].length()); for (String str : segArray) { System.out.println(str); } System.out.println("-----------------"); System.out.println("seg =" + seg); } }
35,230
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
Docx2Xliff.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.word2007/src/net/heartsome/cat/converter/word2007/Docx2Xliff.java
/** * MSOffice2Xliff.java * * Version information : * * Date:Jan 14, 2010 * * Copyright notice : */ package net.heartsome.cat.converter.word2007; import java.io.File; import java.io.FileOutputStream; import java.util.HashMap; import java.util.Map; import net.heartsome.cat.converter.Converter; import net.heartsome.cat.converter.ConverterException; import net.heartsome.cat.converter.StringSegmenter; import net.heartsome.cat.converter.util.ConverterUtils; import net.heartsome.cat.converter.util.Progress; import net.heartsome.cat.converter.word2007.common.DocxConverterException; import net.heartsome.cat.converter.word2007.common.PathConstant; import net.heartsome.cat.converter.word2007.common.PathUtil; import net.heartsome.cat.converter.word2007.common.ZipUtil; import net.heartsome.cat.converter.word2007.partOper.DocumentPart; import net.heartsome.cat.converter.word2007.resource.Messages; import net.heartsome.xml.vtdimpl.VTDUtils; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.OperationCanceledException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.ximpleware.AutoPilot; import com.ximpleware.VTDGen; import com.ximpleware.VTDNav; import com.ximpleware.XMLModifier; /** * The Class MSOffice2Xliff. * @author robert 2012-08-21 * @version * @since JDK1.6 */ public class Docx2Xliff implements Converter { /** The Constant TYPE_VALUE. */ public static final String TYPE_VALUE = "x-msofficeWord2007"; /** The Constant TYPE_NAME_VALUE. */ public static final String TYPE_NAME_VALUE = Messages.getString("utils.FileFormatUtils.MSWORD2007"); /** The Constant NAME_VALUE. */ public static final String NAME_VALUE = "MS Office Word 2007 to XLIFF Conveter"; private static final Logger LOGGER = LoggerFactory.getLogger(Docx2Xliff.class); /** * (non-Javadoc) * @see net.heartsome.cat.converter.Converter#convert(java.util.Map, org.eclipse.core.runtime.IProgressMonitor) * @param args * @param monitor * @return * @throws ConverterException */ public Map<String, String> convert(Map<String, String> args, IProgressMonitor monitor) throws ConverterException { MSOffice2XliffImpl converter = new MSOffice2XliffImpl(); return converter.run(args, monitor); } /** * (non-Javadoc) * @see net.heartsome.cat.converter.Converter#getName() * @return */ public String getName() { return NAME_VALUE; } /** * (non-Javadoc) * @see net.heartsome.cat.converter.Converter#getType() * @return */ public String getType() { return TYPE_VALUE; } /** * (non-Javadoc) * @see net.heartsome.cat.converter.Converter#getTypeName() * @return */ public String getTypeName() { return TYPE_NAME_VALUE; } /** * The Class MSOffice2XliffImpl. * @author robert * @version * @since JDK1.6 */ class MSOffice2XliffImpl { /** The qt tool id. */ private String qtToolID = null; /** The input file. */ private String inputFile; /** The xliff file. */ private String xliffFile; /** The skeleton file. */ private String skeletonFile; /** The source language. */ private String sourceLanguage; /** The XLIFF file target language **/ private String targetLanguage; /** The catalogue. */ private String catalogue; /** The src encoding. */ private String srcEncoding; /** The is suite. */ private boolean isSuite; /** The srx. */ private String srx; private XliffOutputer xlfOutput; /** * Run. * @param args * the args * @param monitor * the monitor * @return the map< string, string> * @throws ConverterException * the converter exception */ public Map<String, String> run(Map<String, String> args, IProgressMonitor monitor) throws ConverterException { monitor = Progress.getMonitor(monitor); // 给 20 个进度格,解压加压各 1 个。处理页眉页脚共 1 个。其他 17 个处理主文档 monitor.beginTask("", 20); Map<String, String> result = new HashMap<String, String>(); inputFile = args.get(Converter.ATTR_SOURCE_FILE); xliffFile = args.get(Converter.ATTR_XLIFF_FILE); skeletonFile = args.get(Converter.ATTR_SKELETON_FILE); isSuite = false; if (Converter.TRUE.equals(args.get(Converter.ATTR_IS_SUITE))) { isSuite = true; } qtToolID = args.get(Converter.ATTR_QT_TOOLID) != null ? args.get(Converter.ATTR_QT_TOOLID) : Converter.QT_TOOLID_DEFAULT_VALUE; sourceLanguage = args.get(Converter.ATTR_SOURCE_LANGUAGE); targetLanguage = args.get(Converter.ATTR_TARGET_LANGUAGE); catalogue = args.get(Converter.ATTR_CATALOGUE); srx = args.get(Converter.ATTR_SRX); srcEncoding = args.get(Converter.ATTR_SOURCE_ENCODING); PathUtil pathUtil = null; String docxFolderPath = ""; // docx 文件解压后的存放的临时目录 try { StringSegmenter segmenter = new StringSegmenter(srx, sourceLanguage, catalogue); // 先解压 docx 文件 monitor.setTaskName(Messages.getString("docxConvert.task1")); String tempFolder = System.getProperty("java.io.tmpdir") + System.getProperty("file.separator") + new File(inputFile).getName(); docxFolderPath = ZipUtil.upZipFile(inputFile, tempFolder); pathUtil = new PathUtil(docxFolderPath); monitor.worked(1); // 定义一个 hsxliff 文件的写入方法 xlfOutput = new XliffOutputer(xliffFile, sourceLanguage, targetLanguage); xlfOutput.writeHeader(inputFile, skeletonFile, isSuite, "UTF-8", qtToolID); // System.out.println(skeletonFile); // System.out.println(tempFolder); // 先从主文档 document 文件入手 String docPath = pathUtil.getPackageFilePath(PathConstant.DOCUMENT, false); DocumentPart docPart = new DocumentPart(docPath, pathUtil, xlfOutput, segmenter, inputFile, monitor); docPart.clearNoUseNodeAndDealBR(); docPart.converter(); xlfOutput.outputEndTag(); idealizeGTag(xliffFile, pathUtil.getInterTagPath()); // 开始将文件进行压缩 monitor.setTaskName(Messages.getString("docx2Xlf.task4")); ZipUtil.zipFolder(skeletonFile, pathUtil.getSuperRoot()); monitor.worked(1); if (monitor.isCanceled()) { throw new OperationCanceledException(Messages.getString("docxConvert.task3")); } } catch (DocxConverterException e) { if (Converter.DEBUG_MODE) { e.printStackTrace(); } ConverterUtils.throwConverterException(Activator.PLUGIN_ID, e.getMessage(), e); } catch (OperationCanceledException e) { throw e; }catch (Exception e) { if (Converter.DEBUG_MODE) { e.printStackTrace(); } LOGGER.error(Messages.getString("docx2Xlf.msg1"), e); ConverterUtils.throwConverterException(Activator.PLUGIN_ID, Messages.getString("docx2Xlf.msg1") + "\n" + e.getMessage(), e); } finally { deleteFileOrFolder(new File(docxFolderPath)); monitor.done(); try { if (xlfOutput != null) { xlfOutput.close(); } } catch (Exception e) { e.printStackTrace(); } } return result; } } public static void deleteFileOrFolder(File file) { if (file.exists()) { if (file.isFile()) { file.delete(); } else if (file.isDirectory()) { File files[] = file.listFiles(); for (int i = 0; i < files.length; i++) { deleteFileOrFolder(files[i]); } } file.delete(); } } /** * 简化 xliff 文件的标记,主要功能是将一个源文中的 g 标记进行抽取到骨架的操作。针对一个源文中只有一个 g 标记,并且该 g 标记包褒全文本段 * 生成一个 名为 interTag.xml 的文件,存放于骨架文件的第一级子目录,与 word 文件夹同目录 * 其结构大致为<br> * &lt;docxTags&gt;<br> * &lt;tag tuId="0" &gt;this is a tag&lt;/tag&gt;<br> * &lt;/docxTags&gt;<br> * <div style="color:red">备注:interTag.xml 介绍: 此文件并非 docx 的内部文件,而是保存转换 docx 文件时的部份 g标记(源文中只有一对 g 标记,并且是它包褒一整个文本段)</div> */ private static void idealizeGTag(String xliffPath, String interTagPath) throws Exception{ final String constantGHeader = "<g"; final String constantGEnd = "</g>"; VTDGen vg = new VTDGen(); if (!vg.parseFile(xliffPath, true)) { throw new Exception(); } VTDNav vn = vg.getNav(); String xpath = "/xliff/file/body/descendant::trans-unit[source/text()!='' or source/*]"; AutoPilot ap = new AutoPilot(vn); AutoPilot childAP = new AutoPilot(vn); VTDUtils vu = new VTDUtils(vn); XMLModifier xm = new XMLModifier(vn); ap.selectXPath(xpath); int index = -1; String id = null; StringBuffer tagContentSB = new StringBuffer(); while(ap.evalXPath() != -1){ id = null; index = vn.getAttrVal("id"); if (index != -1) { id = vn.toString(index); } if (id == null) { vn.pop(); continue; } vn.push(); childAP.selectXPath("./source"); if (childAP.evalXPath() == -1) { vn.pop(); continue; } String srcText = vu.getElementContent(); childAP.selectXPath("count(./g)"); // 如果 g 标签个数为 1 ,并且包褒整个文本段,那么便可进行清理 if (childAP.evalXPathToNumber() == 1) { if (srcText.indexOf(constantGHeader) == 0 && srcText.indexOf(constantGEnd) == (srcText.length() - 4)) { childAP.selectXPath("./g"); if (childAP.evalXPath() != -1) { String header = vu.getElementHead(); String content = vu.getElementContent(); // 删除 g 标记 xm.remove(); xm.insertAfterElement(content); // 将删除的 g 标记保存至 interTag.xml 文件中 tagContentSB.append("\t<tag tuId=\"" + id + "\">" + header + "</g>" + "</tag>\n"); } } } vn.pop(); } xm.output(xliffPath); if (tagContentSB.length() > 0) { // 开始创建 interTag.xml 文件 File file = new File(interTagPath); if (!file.exists()) { FileOutputStream output; output = new FileOutputStream(interTagPath); output.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".getBytes("UTF-8")); output.write("<docxTags>\n".getBytes("UTF-8")); output.write(tagContentSB.toString().getBytes("UTF-8")); output.write("</docxTags>".getBytes("UTF-8")); output.close(); } } } public static void main(String[] args) { Docx2Xliff docx2Xliff = new Docx2Xliff(); String xliffPath = "/home/robert/Desktop/Heartsome Support Revised_转换后少一个字.docx.hsxliff"; try { docx2Xliff.idealizeGTag(xliffPath, null); } catch (Exception e) { e.printStackTrace(); } // final String constantGHeader = "<g"; // final String constantGEnd = "</g>"; // String srcText = "<g rPr='&lt;w:rPr&gt;&lt;w:rFonts w:hint=&quot;eastAsia&quot;/&gt;&lt;w:kern w:val=&quot;0&quot;/&gt;&lt;/w:rPr&gt;'>Heartsome 技术支持服务</g>"; // // if (srcText.indexOf(constantGHeader) == 0 && srcText.indexOf(constantGEnd) == (srcText.length() - 4)) { // System.out.println("这是正确的。"); // } } }
11,057
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
TestWord2007.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.word2007/src/net/heartsome/cat/converter/word2007/TestWord2007.java
package net.heartsome.cat.converter.word2007; import java.io.File; import org.eclipse.core.runtime.NullProgressMonitor; import net.heartsome.cat.converter.StringSegmenter; import net.heartsome.cat.converter.word2007.common.PathConstant; import net.heartsome.cat.converter.word2007.common.PathUtil; import net.heartsome.cat.converter.word2007.common.ZipUtil; import net.heartsome.cat.converter.word2007.partOper.DocumentPart; import net.heartsome.cat.converter.word2007.partOper.DocumentRelation; public class TestWord2007 { private XliffOutputer xlfOutput; public TestWord2007(){} public void docx2Xliff(){ try { // String inputFile = "/home/robert/Desktop/测试简单word文档.docx"; // String inputFile = "/home/robert/Desktop/Word2007 for test.docx"; // String xliffFile = "/home/robert/workspace/runtime-UltimateEdition.product/testDocxConverter/XLIFF/zh-CN/测试简单word文档.docx.hsxliff"; // String sourceLanguage = "en-US"; // String targetLanguage = "zh-CN"; // String srx = "/home/robert/workspace/newR8/.metadata/.plugins/org.eclipse.pde.core/UltimateEdition.product/net.heartsome.cat.converter/srx/default_rules.srx"; // String catalogue = "/home/robert/workspace/newR8/.metadata/.plugins/org.eclipse.pde.core/UltimateEdition.product/net.heartsome.cat.converter/catalogue/catalogue.xml"; String inputFile = "C:\\Users\\Administrator\\Desktop\\test word 2007 converter\\测试简单word文档.docx"; // String inputFile = "C:\\Users\\Administrator\\Desktop\\test word 2007 converter\\Word2007 for test.docx"; String xliffFile = "E:\\workspaces\\runtime-UltimateEdition.product\\testWord2007Convert\\XLIFF\\zh-CN\\测试简单word文档.docx.hsxliff"; String sourceLanguage = "en-US"; String targetLanguage = "zh-CN"; String srx = "E:\\workspaces\\newR8\\.metadata\\.plugins\\org.eclipse.pde.core\\UltimateEdition.product\\net.heartsome.cat.converter\\srx\\default_rules.srx"; String catalogue = "E:\\workspaces\\newR8\\.metadata\\.plugins\\org.eclipse.pde.core\\UltimateEdition.product\\net.heartsome.cat.converter\\catalogue\\catalogue.xml"; StringSegmenter segmenter = new StringSegmenter(srx, sourceLanguage, catalogue); // 先解压 docx 文件 String docxFolderPath = ZipUtil.upZipFile(inputFile, null); PathUtil pathUtil = new PathUtil(docxFolderPath); // 定义一个 hsxliff 文件的写入方法 xlfOutput = new XliffOutputer(xliffFile, sourceLanguage, targetLanguage); xlfOutput.writeHeader(inputFile, "skeletonFile", true, "UTF-8", ""); // 先从主文档 document 文件入手 String docPath = pathUtil.getPackageFilePath(PathConstant.DOCUMENT, false); DocumentPart docPart = new DocumentPart(docPath, pathUtil, xlfOutput, segmenter, inputFile, new NullProgressMonitor()); docPart.converter(); System.out.println("--------------"); xlfOutput.outputEndTag(); // 开始将文件进行压缩 // String zipPath = "/home/robert/Desktop/word 2007 skeleton/" + new File(pathUtil.getSuperRoot()).getName(); String zipPath = "C:\\Users\\Administrator\\Desktop\\word 2007 skeleton\\" + new File(pathUtil.getSuperRoot()).getName(); ZipUtil.zipFolder(zipPath, pathUtil.getSuperRoot()); } catch (Exception e) { e.printStackTrace(); }finally{ try { xlfOutput.close(); System.out.println("----------"); } catch (Exception e2) { e2.printStackTrace(); } } } public void xliff2Docx() { try { String xliffFile = "/home/robert/workspace/runtime-UltimateEdition.product/testDocxConverter/XLIFF/zh-CN/测试简单word文档.docx.hsxliff"; String outputFile = "/home/robert/Desktop/word 2007 skeleton/最终word文档.docx"; String skeletonFile = "/home/robert/Desktop/word 2007 skeleton/测试简单word文档.docx_files"; // String xliffFile = "E:\\workspaces\\runtime-UltimateEdition.product\\testWord2007Convert\\XLIFF\\zh-CN\\测试简单word文档.docx.hsxliff"; // String outputFile = "/home/robert/Desktop/word 2007 skeleton/最终word文档.docx"; // String skeletonFile = "C:\\Users\\Administrator\\Desktop\\word 2007 skeleton\\测试简单word文档.docx_files"; // 先解压 docx 文件 String docxFolderPath = ZipUtil.upZipFile(skeletonFile, null); PathUtil pathUtil = new PathUtil(docxFolderPath); // 定义一个 hsxliff 的读入器 XliffInputer xlfInput = new XliffInputer(xliffFile, pathUtil); // 正转换是从 主文档入手的,而逆转换则是从 word/_rels/document.xml.rels 入手,先处理掉 页眉,页脚,脚注,批注,尾注 String docRelsPath = pathUtil.getPackageFilePath(PathConstant.DOCUMENTRELS, false); DocumentRelation docRels = new DocumentRelation(docRelsPath, pathUtil); docRels.arrangeRelations(xlfInput, new NullProgressMonitor()); // 再处理主文档 // pathUtil.setSuperRoot(); // String docPath = pathUtil.getPackageFilePath(PathConstant.DOCUMENT, false); // DocumentPart documentPart = new DocumentPart(docPath, xlfInput); // documentPart.reverseConvert(); } catch (Exception e) { e.printStackTrace(); } finally { try { System.out.println("----------"); } catch (Exception e2) { e2.printStackTrace(); } } } public void testSegDocument(){ // String inputFile = "/home/robert/Desktop/测试简单word文档.docx"; // String inputFile = "/home/robert/Desktop/Word2007 for test.docx"; // String xliffFile = "/home/robert/workspace/runtime-UltimateEdition.product/testDocxConverter/XLIFF/zh-CN/测试简单word文档.docx.hsxliff"; // String sourceLanguage = "en-US"; // String targetLanguage = "zh-CN"; // String srx = "/home/robert/workspace/newR8/.metadata/.plugins/org.eclipse.pde.core/UltimateEdition.product/net.heartsome.cat.converter/srx/default_rules.srx"; // String catalogue = "/home/robert/workspace/newR8/.metadata/.plugins/org.eclipse.pde.core/UltimateEdition.product/net.heartsome.cat.converter/catalogue/catalogue.xml"; // String docPath = "/home/robert/Desktop/document.xml"; String inputFile = "C:\\Users\\Administrator\\Desktop\\test word 2007 converter\\测试简单word文档.docx"; // String inputFile = "C:\\Users\\Administrator\\Desktop\\test word 2007 converter\\Word2007 for test.docx"; String xliffFile = "E:\\workspaces\\runtime-UltimateEdition.product\\testWord2007Convert\\XLIFF\\zh-CN\\测试简单word文档.docx.hsxliff"; String sourceLanguage = "en-US"; String targetLanguage = "zh-CN"; String srx = "E:\\workspaces\\newR8\\.metadata\\.plugins\\org.eclipse.pde.core\\UltimateEdition.product\\net.heartsome.cat.converter\\srx\\default_rules.srx"; String catalogue = "E:\\workspaces\\newR8\\.metadata\\.plugins\\org.eclipse.pde.core\\UltimateEdition.product\\net.heartsome.cat.converter\\catalogue\\catalogue.xml"; String docPath = "C:\\Users\\Administrator\\Desktop\\document.xml"; try { StringSegmenter segmenter = new StringSegmenter(srx, sourceLanguage, catalogue); // 定义一个 hsxliff 文件的写入方法 xlfOutput = new XliffOutputer(xliffFile, sourceLanguage, targetLanguage); xlfOutput.writeHeader(inputFile, "skeletonFile", true, "UTF-8", ""); // 先从主文档 document 文件入手 DocumentPart docPart = new DocumentPart(docPath, null, xlfOutput, segmenter, inputFile, new NullProgressMonitor()); docPart.testSegFile(); System.out.println("--------------"); xlfOutput.outputEndTag(); } catch (Exception e) { e.printStackTrace(); } } public static void main(String[] args) { TestWord2007 test = new TestWord2007(); // test.docx2Xliff(); // test.xliff2Docx(); test.testSegDocument(); } }
7,674
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
XliffInputer.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.word2007/src/net/heartsome/cat/converter/word2007/XliffInputer.java
package net.heartsome.cat.converter.word2007; import java.io.File; import java.text.MessageFormat; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.TreeMap; import net.heartsome.cat.converter.word2007.common.PathUtil; import net.heartsome.cat.converter.word2007.common.SectionSegBean; import net.heartsome.cat.converter.word2007.resource.Messages; import net.heartsome.xml.vtdimpl.VTDUtils; import com.ximpleware.AutoPilot; import com.ximpleware.VTDGen; import com.ximpleware.VTDNav; import com.ximpleware.XMLModifier; /** * hsxliff 文件的读入器,主要是针对逆转换。根据一个占位符的 id 去获取 hsxliff 对应 id 的译文 * @author robert 2012-08-20 */ public class XliffInputer { /** hsxliff 读入器要读入的文件路径 */ private String xliffFile; private VTDNav vn; private AutoPilot ap; private AutoPilot childAP; private VTDUtils vu; public XliffInputer(String xliffFile, PathUtil pathUtil) throws Exception{ this.xliffFile = xliffFile; // 首先处理之前正转换时清理的一些标记,这些标记是存放在 /test.docx.skl/interTag.xml 下的。 String interTagPath = pathUtil.getInterTagPath(); restoreGTag(interTagPath); loadXliff(); } /** * 解析 hsxliff 文件 * @throws Exception */ private void loadXliff() throws Exception { VTDGen vg = new VTDGen(); if (vg.parseFile(xliffFile, true)) { vn = vg.getNav(); ap = new AutoPilot(vn); childAP = new AutoPilot(vn); ap.declareXPathNameSpace("hs", "http://www.heartsome.net.cn/2008/XLFExtension"); childAP.declareXPathNameSpace("hs", "http://www.heartsome.net.cn/2008/XLFExtension"); vu = new VTDUtils(vn); }else { throw new Exception(MessageFormat.format(Messages.getString("docxConvert.msg2"), xliffFile)); } } /** * 通过 trans-unit 的 id 的值去获取当前 trans-unit 节点的译文 * @param <div style='color:red'>isText 占位符所代表的字符串是否是 w:t 节点的内容, 如果是,则不需要组建 * w:r 节点,否则要组装 w:r 等一系列节点</div> * @return * @throws Exception */ public String getTargetStrByTUId(List<String> tuIdList, boolean isText) throws Exception { StringBuffer textSB = new StringBuffer(); for(String id : tuIdList){ // if ("75".equals(id)) { // System.out.println("逆转换调试开始。。。。。。。。"); // } String xpath = "/xliff/file/body/trans-unit[@id='" + id + "']"; ap.selectXPath(xpath); if (ap.evalXPath() != -1) { // 先取 target 节点的内容,如果为空,则取 source 的内容 boolean targetIsNull = true; childAP.selectXPath("./target"); vn.push(); if (childAP.evalXPath() != -1) { String tgtContent = vu.getElementContent(); if (tgtContent != null && !"".equals(tgtContent)) { anaysisTgtOrSrcNode(textSB, vn, isText); targetIsNull = false; } } vn.pop(); // 如果译文为空,则获取源文的信息 vn.push(); if (targetIsNull) { childAP.selectXPath("./source"); if (childAP.evalXPath() != -1) { String srcContent = vu.getElementContent(); if (srcContent != null && !"".equals(srcContent)) { anaysisTgtOrSrcNode(textSB, vn, isText); } } } vn.pop(); } } return textSB.toString(); } /** * 分析 source 或 target 节点,获取其内容 * @throws Exception */ private void anaysisTgtOrSrcNode(StringBuffer textSB, VTDNav vn, boolean isText) throws Exception { vn.push(); AutoPilot otherAP = new AutoPilot(vn); String childXpath = "./text()|node()"; otherAP.selectXPath(childXpath); int tokenId = -1; int index = -1; Map<Integer, SectionSegBean> targetMap = new TreeMap<Integer, SectionSegBean>(); while (otherAP.evalXPath() != -1) { index = vn.getCurrentIndex(); tokenId = vn.getTokenType(index); if (tokenId == 0) { //节点子节点 ananysisTag(vn, targetMap); }else if (tokenId == 5) { // 文本子节点 // if ("+1 845-536-1416".equals(vn.toString(index))) { // System.out.println("问题开始了。。。。"); // } targetMap.put(index, new SectionSegBean(null, vn.toRawString(index), null, null, null)); } } vn.pop(); SectionSegBean bean; for (Entry<Integer, SectionSegBean> entry : targetMap.entrySet()) { bean = entry.getValue(); if (isText) { if (bean.getText() != null) { textSB.append(bean.getText()); } }else { // 这个要组装 w:r 等节点 String ctype = bean.getCtype() == null ? "" : bean.getCtype(); String style = bean.getStyle() == null ? "" : bean.getStyle(); String extendNodes = bean.getExtendNodesStr() == null ? "" : bean.getExtendNodesStr(); if (bean.getPhTagStr() != null) { textSB.append(bean.getPhTagStr()); }else { if ("".equals(ctype)) { textSB.append("<w:r>" + style + extendNodes); textSB.append("<w:t xml:space=\"preserve\">" + bean.getText() + "</w:t></w:r>"); }else { // <w:hyperlink r:id="rId8" w:history="1"> int endIdx = ctype.indexOf(" ") == -1 ? ctype.indexOf(">") : ctype.indexOf(" "); String nodeName = ctype.substring(ctype.indexOf("<") + 1, endIdx); textSB.append(ctype); textSB.append("<w:r>" + style + extendNodes); textSB.append("<w:t xml:space=\"preserve\">" + bean.getText() + "</w:t></w:r>"); textSB.append("</" + nodeName + ">"); } } } } } /** * 分析标记 */ private void ananysisTag(VTDNav vn, Map<Integer, SectionSegBean> targetMap) throws Exception { vn.push(); AutoPilot tagAP = new AutoPilot(vn); int index = vn.getCurrentIndex(); String tagName = vn.toString(index); if ("g".equals(tagName)) { String style = ""; int attrIdx = -1; if ((attrIdx = vn.getAttrVal("rPr")) != -1) { style = vn.toString(attrIdx); } String extendNodes = ""; if ((attrIdx = vn.getAttrVal("extendNodes")) != -1) { extendNodes = vn.toString(attrIdx); } String ctype = ""; if ((attrIdx = vn.getAttrVal("ctype")) != -1) { ctype = vn.toString(attrIdx); } // 首先检查 g 标记下是否有 sub 节点 int subNodeCount = -1; tagAP.selectXPath("count(./descendant::sub)"); subNodeCount = (int)tagAP.evalXPathToNumber(); tagAP.selectXPath("./node()|text()"); if (subNodeCount > 0) { int curIdx = vn.getCurrentIndex(); StringBuffer gTextSB = new StringBuffer(); Map<Integer, String> gTextMap = new TreeMap<Integer, String>(); while(tagAP.evalXPath() != -1){ index = vn.getCurrentIndex(); int tokenType = vn.getTokenType(index); if (tokenType == 0) { //节点子节点 String nodeName = vn.toString(index); if ("ph".equals(nodeName)) { gTextMap.put(index, resetCleanStr(vu.getElementContent())); }else if ("g".equals(nodeName)) { ananysisTag(vn, targetMap); }else if ("sub".equals(nodeName)) { ananysisSubTag(vn, gTextMap, targetMap); } }else if (tokenType == 5) { //文本子节点 gTextMap.put(index, resetCleanStr(vn.toRawString(index))); } } for(Entry<Integer, String> entry : gTextMap.entrySet()){ gTextSB.append(entry.getValue()); } targetMap.put(curIdx, new SectionSegBean(ctype, gTextSB.toString(), style, extendNodes, null)); }else { while(tagAP.evalXPath() != -1){ index = vn.getCurrentIndex(); int tokenType = vn.getTokenType(index); if (tokenType == 0) { //节点子节点 String nodeName = vn.toString(index); if ("ph".equals(nodeName)) { targetMap.put(index, new SectionSegBean(null, null, null, null, resetCleanStr(vu.getElementContent()))); }else if ("g".equals(nodeName)) { ananysisTag(vn, targetMap); } }else if (tokenType == 5) { //文本子节点 targetMap.put(index, new SectionSegBean(ctype, vn.toRawString(index), style, extendNodes, null)); } } } }else if ("ph".equals(tagName)) { targetMap.put(index, new SectionSegBean(null, null, null, null, resetCleanStr(vu.getElementContent()))); }else if ("sub".equals(tagName)) { String style = ""; int attrIdx = -1; if ((attrIdx = vn.getAttrVal("rPr")) != -1) { style = vn.toString(attrIdx); } String extendNodes = ""; if ((attrIdx = vn.getAttrVal("extendNodes")) != -1) { extendNodes = vn.toString(attrIdx); } tagAP.selectXPath("./node()|text()"); while(tagAP.evalXPath() != -1){ index = vn.getCurrentIndex(); int tokenType = vn.getTokenType(index); if (tokenType == 0) { //节点子节点 String nodeName = vn.toString(index); if ("ph".equals(nodeName)) { targetMap.put(index, new SectionSegBean(null, null, null, null, resetCleanStr(vu.getElementContent()))); }else if ("g".equals(nodeName)) { ananysisTag(vn, targetMap); } }else if (tokenType == 5) { //文本子节点 targetMap.put(index, new SectionSegBean(null, vn.toRawString(index), style, extendNodes, null)); } } }else { //其他节点,一律当做字符串处理 targetMap.put(index, new SectionSegBean(null, null, null, null, resetCleanStr(vu.getElementFragment()))); } vn.pop(); } /** * 处理 sub 标记 * @param vn * @param textMap */ private void ananysisSubTag(VTDNav vn, Map<Integer, String> textMap, Map<Integer, SectionSegBean> targetMap) throws Exception{ vn.push(); String style = ""; int attrIdx = -1; if ((attrIdx = vn.getAttrVal("rPr")) != -1) { style = vn.toString(attrIdx); } String extendNodes = ""; if ((attrIdx = vn.getAttrVal("extendNodes")) != -1) { extendNodes = vn.toString(attrIdx); } AutoPilot curAP = new AutoPilot(vn); curAP.selectXPath("./node()|text()"); while(curAP.evalXPath() != -1){ int index = vn.getCurrentIndex(); int tokenType = vn.getTokenType(index); if (tokenType == 0) { //节点子节点 String nodeName = vn.toString(index); if ("ph".equals(nodeName)) { textMap.put(index, resetCleanStr(vu.getElementContent())); }else if ("g".equals(nodeName)) { ananysisTag(vn, targetMap); }else if ("sub".equals(nodeName)) { ananysisSubTag(vn, textMap, targetMap); } }else if (tokenType == 5) { //文本子节点 StringBuffer textSB = new StringBuffer(); textSB.append("<w:r>" + style + extendNodes); textSB.append("<w:t xml:space=\"preserve\">" + resetCleanStr(vn.toRawString(index)) + "</w:t></w:r>"); textMap.put(index, textSB.toString()); } } vn.pop(); } /** * 转义回去 * @param string * @return */ public String resetCleanStr(String string){ string = string.replaceAll("&lt;", "<" ); string = string.replaceAll("&gt;", ">"); string = string.replaceAll("&quot;", "\""); string = string.replaceAll("&amp;", "&"); return string; } public static void main(String[] args) { try { String xlfPath = "/home/robert/Desktop/testXliff.xml"; XliffInputer inputer = new XliffInputer(xlfPath, null); inputer.test_1(); } catch (Exception e) { e.printStackTrace(); } } public void test_1(){ try { // Map<Integer, SectionSegBean> targetMap = new LinkedHashMap<Integer, SectionSegBean>(); // AutoPilot ap = new AutoPilot(vn); // AutoPilot childAP = new AutoPilot(vn); // ap.selectXPath("/root/trans-unit/target"); // while(ap.evalXPath() != -1){ //// vn.push(); //// childAP.selectXPath("./text()|node()"); //// while (childAP.evalXPath() != -1) { //// System.out.println("vn.//// = " + vn.toString(vn.getCurrentIndex())); //// int tokenId = vn.getTokenType(vn.getCurrentIndex()); //// if (tokenId == 0) { //// ananysisTag(vn, targetMap); //// System.out.println("vn.//// = " + vn.toString(vn.getCurrentIndex())); //// } //// } //// vn.pop(); // } getTargetStrByTUId(Arrays.asList(new String[]{"75", "5"}), true); } catch (Exception e) { e.printStackTrace(); } } private void restoreGTag(String interTagPath) throws Exception{ if (!new File(interTagPath).exists()) { return; } // 先解析 interTag.xml VTDGen vg = new VTDGen(); if (!vg.parseFile(interTagPath, true)) { throw new Exception(); } VTDNav vn = vg.getNav(); AutoPilot ap = new AutoPilot(vn); VTDUtils vu = new VTDUtils(vn); String xpath = "/docxTags/tag"; ap.selectXPath(xpath); Map<String, String> tagMap = new HashMap<String, String>(); String tuId = null; int index = -1; while(ap.evalXPath() != -1){ tuId = null; if ((index = vn.getAttrVal("tuId")) != -1) { tuId = vn.toString(index); } if (tuId == null) { continue; } String content = vu.getElementContent().replace("</g>", ""); if (content.indexOf("<g") != 0) { continue; } tagMap.put(tuId, content); } // 再将结果传至 xliff 文件 vg = new VTDGen(); if (!vg.parseFile(xliffFile, true)) { throw new Exception(); } vn = vg.getNav(); vu.bind(vn); ap.bind(vn); XMLModifier xm = new XMLModifier(vn); for(Entry<String, String> entry : tagMap.entrySet()){ String thisTuId = entry.getKey(); String tagContent = entry.getValue(); // docx 转换器里面是没有 多个file节点 的情况 // 先处理源文 xpath = "/xliff/file/body//trans-unit[@id='" + thisTuId + "']/source"; ap.selectXPath(xpath); if (ap.evalXPath() != -1) { String srcHeader = vu.getElementHead(); String oldContent = vu.getElementContent(); xm.remove(); StringBuffer newFragSB = new StringBuffer(); newFragSB.append(srcHeader); newFragSB.append(tagContent); newFragSB.append(oldContent); newFragSB.append("</g></source>"); xm.insertAfterElement(newFragSB.toString()); } // 处理译文 xpath = "/xliff/file/body//trans-unit[@id='" + thisTuId + "']/target"; ap.selectXPath(xpath); if (ap.evalXPath() != -1) { String srcHeader = vu.getElementHead(); String oldContent = vu.getElementContent(); xm.remove(); StringBuffer newFragSB = new StringBuffer(); newFragSB.append(srcHeader); newFragSB.append(tagContent); newFragSB.append(oldContent); newFragSB.append("</g></target>"); xm.insertAfterElement(newFragSB.toString()); } } xm.output(xliffFile); // 删除 interTag.xml File interTagFile = new File(interTagPath); interTagFile.delete(); } }
14,472
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
DocxConverterException.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.word2007/src/net/heartsome/cat/converter/word2007/common/DocxConverterException.java
package net.heartsome.cat.converter.word2007.common; public class DocxConverterException extends Exception{ private static final long serialVersionUID = 1L; public DocxConverterException() { super(); } public DocxConverterException(String message) { super("\n"+message); } }
288
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
TagBean.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.word2007/src/net/heartsome/cat/converter/word2007/common/TagBean.java
package net.heartsome.cat.converter.word2007.common; /** * 正向转换时,读取到每个节点后存放相应的数据 * @author robert 2012-08-10 */ public class TagBean { /** 该标记的样式 */ private String style; /** 文本值 */ private String text; /** 文本值在整个文本段的起始值 */ private int start; /** 文本值在整个文本段的结束值 */ private int end; public TagBean (){} public TagBean(String style, String text, int start, int end){ this.style = style; this.text = text; this.start = start; this.end = end; } public String getStyle() { return style; } public void setStyle(String style) { this.style = style; } public String getText() { return text; } public void setText(String text) { this.text = text; } public int getStart() { return start; } public void setStart(int start) { this.start = start; } public int getEnd() { return end; } public void setEnd(int end) { this.end = end; } public static void main(String[] args) { String seg = "The pump can be mounted on a standard IV pole or a horizontal mounting rail using the removable pole \" clamp in Figure 2)."; String text= "The pump can be mounted on a standard IV pole or a horizontal mounting rail using the removable pole \" clamp in "; text = text.replace("(", "\\("); System.out.println(text); System.out.println(seg.replaceFirst(text, "")); } }
1,442
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
PathConstant.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.word2007/src/net/heartsome/cat/converter/word2007/common/PathConstant.java
package net.heartsome.cat.converter.word2007.common; /** * 保存部份需要使用的文件的相对路径,<div style='color:red'>使用之前,当前路径必须为根目录 superRoot</div> * @author robert 2012-08-08 */ public class PathConstant { /** 主文档 document.xml的相对路径 */ public static final String DOCUMENT = "word/document.xml"; /** 批注 comments.xml的相对路径 */ public static final String COMMENTS = "word/comments.xml"; /** 尾注 endnotes.xml的相对路径 */ public static final String ENDNOTES = "word/endnotes.xml"; public static final String FONTTABLE = "word/fontTable.xml"; /** 脚注 footnotes.xml的相对路径 */ public static final String FOOTNOTES = "word/footnotes.xml"; /** 文档设置 settings.xml的相对路径 */ public static final String SETTINGS = "word/settings.xml"; /** 样式定义 styles.xml的相对路径 */ public static final String STYLES = "word/styles.xml"; public static final String WEBSETTINGS = "word/webSettings.xml"; /** 主文档 与其他文件进行关联的关联文件 document.xml.rels */ public static final String DOCUMENTRELS = "word/_rels/document.xml.rels"; /** 文件夹 word 的位置,针对于主目录 */ public static final String WORD_FOLDER = "word"; /** 文件 interTag.xml 的位置,针对于主目录 */ public static final String interTag_FILE = "interTag.xml"; }
1,397
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
PathUtil.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.word2007/src/net/heartsome/cat/converter/word2007/common/PathUtil.java
package net.heartsome.cat.converter.word2007.common; import java.io.File; import java.io.FileNotFoundException; import java.text.MessageFormat; import net.heartsome.cat.converter.word2007.resource.Messages; /** * word 2007 的资源包<br> * 以最后一次处理前文件所在的目录做为根 * @author robert 2012-08-08 */ public class PathUtil { /** word 2007 文件解压后的根目录,即根文件夹 */ private String superRoot; /** 当前所处在的目录 */ private String root; /** 保存的临时路径 */ private String tempRoot; /** word 文件夹的路径 */ private String wordRoot; /** interTag.xml 的位置*/ private String interTagPath; /** * 构造SpreadsheetPackage对象 * @param root * 资源根路径,在此路径下,包含了Spreadsheet解压后的所有文件和正确的目录结构 * @throws Exception */ public PathUtil(String superRoot) throws Exception { this.superRoot = superRoot; setRoot(superRoot); wordRoot = superRoot + System.getProperty("file.separator") + PathConstant.WORD_FOLDER; interTagPath = superRoot + System.getProperty("file.separator") + PathConstant.interTag_FILE; if (!new File(wordRoot).exists() && !new File(wordRoot).isDirectory()) { throw new Exception(MessageFormat.format(Messages.getString("PathUtil.msg1"), PathConstant.WORD_FOLDER)); } } /** * 设置当前根路径 * @param root * @throws FileNotFoundException * ; */ public void setRoot(String root) throws FileNotFoundException { File f = new File(root); if (!f.exists()) { throw new FileNotFoundException(root); } this.root = root; } /** * 将当前目标设置成根目录 * @throws Exception */ public void setSuperRoot() throws Exception { setRoot(superRoot); } /** * 获取当前根路径 * @return */ public String getPackageRoot() { return this.root; } /** * 获取当前根路径的名称 * @return ; */ public String getRootName() { File f = new File(root); return f.getName(); } /** * 回到上一级目录,类似cd ..命令 */ public void back2TopLeve() { File f = new File(root); if (!f.getParent().equals(superRoot)) { try { setRoot(f.getParent()); } catch (FileNotFoundException e) { e.printStackTrace(); } } } /** * 获取Spreadsheet包中的文件路径<br> * 如获取workbook.xml,则relativePath的值应该为xl/workbook.xml<br> * 获取xl/workbook.xml后,{@link #root}/xl将作为根目录 * @param relativePath * @param isSetRoot 是否将当前文件的文件夹设置成当前目录 * @return * @throws FileNotFoundException */ public String getPackageFilePath(String relativePath, boolean isSetRoot) throws FileNotFoundException { if (relativePath.startsWith("..")) { back2TopLeve(); relativePath = relativePath.substring(relativePath.indexOf('/') + 1, relativePath.length()); } File ret = new File(root); String[] dirs = relativePath.split("/"); if (!ret.exists()) { throw new FileNotFoundException(root); } if (dirs.length >= 1) { for (int i = 0; i < dirs.length - 1; i++) { ret = new File(ret, dirs[i]); } ret = new File(ret, dirs[dirs.length - 1]); if (!ret.exists()) { throw new FileNotFoundException(relativePath); } } if (isSetRoot) { setRoot(ret.getParent()); } return ret.getAbsolutePath(); } /** * 标记当前Root位置,参考{@link #resetRoot()} */ public void markRoot() { tempRoot = this.root; } /** * 重置当前Root到标记位置,参考{@link #markRoot()} */ public void resetRoot() { if (tempRoot != null && tempRoot.length() != 0) { this.root = tempRoot; tempRoot = ""; } } /** * 将当前目录设置成 word 目录 */ public void setWordRoot(){ root = wordRoot; } public String getSuperRoot() { return superRoot; } public String getInterTagPath() { return interTagPath; } }
4,120
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
SectionSegBean.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.word2007/src/net/heartsome/cat/converter/word2007/common/SectionSegBean.java
package net.heartsome.cat.converter.word2007.common; /** * 保存每个文本段中一个小片段的容 * @author robert 2012-08-10 */ public class SectionSegBean { private String ctype; private String text; private String style; private String extendNodesStr; private String phTagStr; public SectionSegBean () {} public SectionSegBean(String ctype, String text, String style, String extendNodesStr, String phTagStr){ this.ctype = ctype; this.text = text; this.style = style; this.extendNodesStr = extendNodesStr; this.phTagStr = phTagStr; } public String getText() { return text; } public void setText(String text) { this.text = text; } public String getStyle() { return style; } public void setStyle(String style) { this.style = style; } public String getExtendNodesStr() { return extendNodesStr; } public void setExtendNodesStr(String extendNodesStr) { this.extendNodesStr = extendNodesStr; } public String getPhTagStr() { return phTagStr; } public void setPhTagStr(String phTagStr) { this.phTagStr = phTagStr; } public String getCtype() { return ctype; } public void setCtype(String ctype) { this.ctype = ctype; } }
1,189
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
ZipUtil.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.word2007/src/net/heartsome/cat/converter/word2007/common/ZipUtil.java
package net.heartsome.cat.converter.word2007.common; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import java.util.zip.ZipOutputStream; public class ZipUtil { /** * 压缩文件夹 * @param zipPath * 生成的zip文件路径 * @param filePath * 需要压缩的文件夹路径 * @throws Exception */ public static void zipFolder(String zipPath, String filePath) throws IOException { ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipPath)); File f = new File(filePath); zipFiles(out, f, ""); out.close(); } /** * 将压缩文件中的内容解压到指定目录中<br> * 如果<code>baseDir</code>的值为空,则将文件解压到相同的目录中,目录名称为"zipFile_files" * @param zipFile * 压缩文件路径 * @param baseDir * 解压的目标路径,可以为null * @throws IOException */ public static String upZipFile(String zipFile, String baseDir) throws IOException { File f = new File(zipFile); if (baseDir == null) { baseDir = f.getPath() + "_files"; } ZipInputStream zis = new ZipInputStream(new FileInputStream(f)); ZipEntry ze; byte[] buf = new byte[1024]; while ((ze = zis.getNextEntry()) != null) { File outFile = getRealFileName(baseDir, ze.getName()); FileOutputStream os = new FileOutputStream(outFile); int readLen = 0; while ((readLen = zis.read(buf, 0, 1024)) != -1) { os.write(buf, 0, readLen); } os.close(); } zis.close(); return baseDir; } /** * 递归调用,压缩文件夹和子文件夹的所有文件 * @param out * @param f * @param base * @throws Exception */ private static void zipFiles(ZipOutputStream out, File f, String base) throws IOException { if (f.isDirectory()) { File[] fl = f.listFiles(); // out.putNextEntry(new ZipEntry(base + "/")); base = base.length() == 0 ? "" : base + "/"; for (int i = 0; i < fl.length; i++) { zipFiles(out, fl[i], base + fl[i].getName());// 递归压缩子文件夹 } } else { out.putNextEntry(new ZipEntry(base)); FileInputStream in = new FileInputStream(f); int b; // System.out.println(base); while ((b = in.read()) != -1) { out.write(b); } in.close(); } } /** * 给定根目录,返回一个相对路径所对应的实际文件名. * @param baseDir * 指定根目录 * @param absFileName * 相对路径名,来自于ZipEntry中的name * @return java.io.File 实际的文件 */ private static File getRealFileName(String baseDir, String absFileName) { String[] dirs = absFileName.split("/"); File ret = new File(baseDir); if (!ret.exists()) { ret.mkdirs(); } if ("/".equals(System.getProperty("file.separator"))) { for (int i = 0; i < dirs.length; i++) { dirs[i] = dirs[i].replace("\\", "/"); } } if (dirs.length >= 1) { for (int i = 0; i < dirs.length - 1; i++) { ret = new File(ret, dirs[i]); } if (!ret.exists()) { ret.mkdirs(); } ret = new File(ret, dirs[dirs.length - 1]); if(!ret.exists()){ File p = ret.getParentFile(); if(!p.exists()){ p.mkdirs(); } } } return ret; } }
3,467
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
HeaderPart.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.word2007/src/net/heartsome/cat/converter/word2007/partOper/HeaderPart.java
package net.heartsome.cat.converter.word2007.partOper; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import net.heartsome.cat.converter.StringSegmenter; import net.heartsome.cat.converter.word2007.PartOperate; import net.heartsome.cat.converter.word2007.XliffInputer; import net.heartsome.cat.converter.word2007.XliffOutputer; /** * 处理 页眉 header*.xml 文件 * @author robert */ public class HeaderPart extends PartOperate { /** * 正向转换所用到的构造方法 * @param partPath * @param xlfOutput * @param segmenter * @throws Exception */ public HeaderPart(String partPath, XliffOutputer xlfOutput, StringSegmenter segmenter) throws Exception{ super(partPath, xlfOutput, segmenter); init(); } /** * 逆转换用到的构造函数 * @param partPath * @param xlfInput */ public HeaderPart (String partPath, XliffInputer xlfInput) throws Exception { super(partPath, xlfInput); init(); } private void init() throws Exception { nameSpaceMap = new HashMap<String, String>(); nameSpaceMap.put("w", "http://schemas.openxmlformats.org/wordprocessingml/2006/main"); nameSpaceMap.put("v", "urn:schemas-microsoft-com:vml"); loadFile(nameSpaceMap); } /** * <div style='color:red;'>这个 run() 主体方法内的内容,headerPart, footerPart 除了xpath 不一致,其他应保持一致 , 切记 。<br/> * 另外,页眉页脚是没有批注,尾注,脚注等信息</div>。 */ @Override protected void converter() throws Exception { operateTransAttributes("/w:hdr/descendant::w:p/w:r/w:pict/v:shape/@alt"); // 处理的单元为 w:p String xpath = "/w:hdr/descendant::w:p"; ap.selectXPath(xpath); while(ap.evalXPath() != -1){ 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(); 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); } } } } } xm.output(partPath); } // ------------------------------------------ 下面是逆转换的代码 ------------------------------------------------ @Override protected void reverseConvert() throws Exception { // 处理的单元为 w:p String xpath = "/w:hdr/descendant::w:p"; ap.selectXPath(xpath); while(ap.evalXPath() != -1){ // DOLATER 先处理所有的属性 analysisReversePnode(); } xm.output(partPath); //再处理可翻译属性 xpath = "/w:hdr/descendant::w:p/w:r/w:pict/v:shape/@alt"; reverseTranslateAttributes(xpath); } public static void main(String[] args) { String text = "1=-2 - English"; System.out.println(text.replaceAll(" ", "")); String transAttrPlaceHolderStr = "%%%21%%%"; int firstPlaceHIdx = transAttrPlaceHolderStr.indexOf("%%%"); System.out.println(firstPlaceHIdx); System.out.println(transAttrPlaceHolderStr.substring(firstPlaceHIdx + 3, transAttrPlaceHolderStr.indexOf("%%%", firstPlaceHIdx + 1))); } }
3,807
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
CommentsPart.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.word2007/src/net/heartsome/cat/converter/word2007/partOper/CommentsPart.java
package net.heartsome.cat.converter.word2007.partOper; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import net.heartsome.cat.converter.StringSegmenter; import net.heartsome.cat.converter.word2007.PartOperate; import net.heartsome.cat.converter.word2007.XliffInputer; import net.heartsome.cat.converter.word2007.XliffOutputer; /** * 批注文件 comments.xml 的处理 * @author robert */ public class CommentsPart extends PartOperate { /** * 正向转换所用到的构造方法 * @param partPath * @param xlfOutput * @param segmenter * @throws Exception */ public CommentsPart(String partPath, XliffOutputer xlfOutput, StringSegmenter segmenter) throws Exception { super(partPath, xlfOutput, segmenter); init(); } /** * 逆转换用到的构造函数 * @param partPath * @param xlfInput */ public CommentsPart (String partPath, XliffInputer xlfInput) throws Exception { super(partPath, xlfInput); init(); } private void init() throws Exception { nameSpaceMap = new HashMap<String, String>(); nameSpaceMap.put("w", "http://schemas.openxmlformats.org/wordprocessingml/2006/main"); nameSpaceMap.put("v", "urn:schemas-microsoft-com:vml"); loadFile(nameSpaceMap); } /** * 这里,因为处理尾注的时机是根据传入的 id 决定的,但针对对可翻译属性的处理,只能处理一次,故放在 run 方法里面。这种情况,尾注,批注,有点类似 */ @Override protected void converter() throws Exception { operateTransAttributes("/w:comments/w:comment/descendant::w:p/w:r/w:pict/v:shape/@alt"); } /** * 根据指定的 id 进行处理批注信息 * @param id * @throws Exception */ protected void operateCommentsContent(String id) throws Exception { // 处理的单元为 w:p String xpath = "/w:comments/w:comment[@w:id='" + id + "']/descendant::w:p"; ap.selectXPath(xpath); while(ap.evalXPath() != -1){ 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(); 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); } } } } } } public void outputPart() throws Exception{ xm.output(partPath); } // ------------------------------------------ 下面是逆转换的代码 ------------------------------------------------ @Override protected void reverseConvert() throws Exception { // 处理的单元为 w:p String xpath = "/w:comments/w:comment/descendant::w:p"; ap.selectXPath(xpath); while(ap.evalXPath() != -1){ // DOLATER 先处理所有的属性 analysisReversePnode(); } xm.output(partPath); //再处理可翻译属性 xpath = "/w:comments/w:comment/descendant::w:p/w:r/w:pict/v:shape/@alt"; reverseTranslateAttributes(xpath); } }
3,648
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
FooterNodesPart.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.word2007/src/net/heartsome/cat/converter/word2007/partOper/FooterNodesPart.java
package net.heartsome.cat.converter.word2007.partOper; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import net.heartsome.cat.converter.StringSegmenter; import net.heartsome.cat.converter.word2007.PartOperate; import net.heartsome.cat.converter.word2007.XliffInputer; import net.heartsome.cat.converter.word2007.XliffOutputer; /** * 脚注的处理类,针对于 footerNodes.xml 文件 * @author robert 2012-08-16 */ public class FooterNodesPart extends PartOperate { /** * 正向转换所用到的构造方法 * @param partPath * @param xlfOutput * @param segmenter * @throws Exception */ public FooterNodesPart(String partPath, XliffOutputer xlfOutput, StringSegmenter segmenter) throws Exception { super(partPath, xlfOutput, segmenter); init(); } /** * 逆转换用到的构造函数 * @param partPath * @param xlfInput */ public FooterNodesPart (String partPath, XliffInputer xlfInput) throws Exception { super(partPath, xlfInput); init(); } private void init() throws Exception { nameSpaceMap = new HashMap<String, String>(); nameSpaceMap.put("w", "http://schemas.openxmlformats.org/wordprocessingml/2006/main"); nameSpaceMap.put("v", "urn:schemas-microsoft-com:vml"); loadFile(nameSpaceMap); } /** * 这里,因为处理尾注的时机是根据传入的 id 决定的,但针对对可翻译属性的处理,只能处理一次,故放在 run 方法里面。这种情况,尾注,批注,有点类似 */ @Override protected void converter() throws Exception { operateTransAttributes("/w:footnotes/w:footnote/descendant::w:p/w:r/w:pict/v:shape/@alt"); } /** * 根据 * @param id * @throws Exception */ protected void operateFooterNodesContent(String id) throws Exception { // 处理的单元为 w:p String xpath = "/w:footnotes/w:footnote[@w:id='" + id + "']/descendant::w:p"; ap.selectXPath(xpath); while(ap.evalXPath() != -1){ 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(); 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); } } } } } } public void outputPart() throws Exception{ xm.output(partPath); } // ------------------------------------------ 下面是逆转换的代码 ------------------------------------------------ @Override protected void reverseConvert() throws Exception { // 处理的单元为 w:p String xpath = "/w:footnotes/w:footnote/descendant::w:p"; ap.selectXPath(xpath); while(ap.evalXPath() != -1){ // DOLATER 先处理所有的属性 analysisReversePnode(); } xm.output(partPath); //再处理可翻译属性 xpath = "/w:footnotes/w:footnote/descendant::w:p/w:r/w:pict/v:shape/@alt"; reverseTranslateAttributes(xpath); } }
3,683
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
FooterPart.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.word2007/src/net/heartsome/cat/converter/word2007/partOper/FooterPart.java
package net.heartsome.cat.converter.word2007.partOper; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import net.heartsome.cat.converter.StringSegmenter; import net.heartsome.cat.converter.word2007.PartOperate; import net.heartsome.cat.converter.word2007.XliffInputer; import net.heartsome.cat.converter.word2007.XliffOutputer; public class FooterPart extends PartOperate { /** * 正向转换所用到的构造方法 * @param partPath * @param xlfOutput * @param segmenter * @throws Exception */ public FooterPart(String partPath, XliffOutputer xlfOutput, StringSegmenter segmenter) throws Exception { super(partPath, xlfOutput, segmenter); init(); } /** * 逆转换用到的构造函数 * @param partPath * @param xlfInput */ public FooterPart (String partPath, XliffInputer xlfInput) throws Exception { super(partPath, xlfInput); init(); } private void init() throws Exception { nameSpaceMap = new HashMap<String, String>(); nameSpaceMap.put("w", "http://schemas.openxmlformats.org/wordprocessingml/2006/main"); nameSpaceMap.put("v", "urn:schemas-microsoft-com:vml"); loadFile(nameSpaceMap); } /** * <div style='color:red;'>这个 run() 主体方法内的内容,headerPart, footerPart 除了xpath 不一致,其他应保持一致 , 切记 。<br/> * 另外,页眉页脚是没有批注,尾注,脚注等信息</div>。 */ @Override protected void converter() throws Exception { operateTransAttributes("/w:ftr/descendant::w:p/w:r/w:pict/v:shape/@alt"); // 处理的单元为 w:p String xpath = "/w:ftr/descendant::w:p"; ap.selectXPath(xpath); while(ap.evalXPath() != -1){ 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(); 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); } } } } } xm.output(partPath); } // ------------------------------------------ 下面是逆转换的代码 ------------------------------------------------ @Override protected void reverseConvert() throws Exception { // 处理的单元为 w:p String xpath = "/w:ftr/descendant::w:p"; ap.selectXPath(xpath); while(ap.evalXPath() != -1){ // DOLATER 先处理所有的属性 analysisReversePnode(); } xm.output(partPath); //再处理可翻译属性 xpath = "/w:ftr/descendant::w:p/w:r/w:pict/v:shape/@alt"; reverseTranslateAttributes(xpath); } }
3,323
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
DocumentRelation.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.word2007/src/net/heartsome/cat/converter/word2007/partOper/DocumentRelation.java
package net.heartsome.cat.converter.word2007.partOper; import java.text.MessageFormat; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.core.runtime.OperationCanceledException; import net.heartsome.cat.converter.word2007.XliffInputer; import net.heartsome.cat.converter.word2007.common.PathUtil; import net.heartsome.cat.converter.word2007.resource.Messages; import com.ximpleware.AutoPilot; import com.ximpleware.VTDGen; import com.ximpleware.VTDNav; /** * 管理 document.xml 与其他文件之间的关联的类 * @author robert 2012-08-08 */ public class DocumentRelation { private VTDNav vn; private AutoPilot ap; /** document.xml 关系文件 document.xml.rels 的绝对路径 */ private String xmlPath; private PathUtil pathUtil; public DocumentRelation(String xmlPath, PathUtil pathUtil) throws Exception { this.xmlPath = xmlPath; this.pathUtil = pathUtil; loadFile(); } private void loadFile() throws Exception { VTDGen vg = new VTDGen(); if (vg.parseFile(xmlPath, true)) { vn = vg.getNav(); ap = new AutoPilot(vn); }else { throw new Exception(MessageFormat.format(Messages.getString("docxConvert.msg2"), xmlPath)); } } /** * 通过传入的 id 获取出与 document.xml 文件相关的其他文件 * @param Id * @return */ public String getPartPathById(String Id) throws Exception { String partPath = ""; String xpath = "/Relationships/Relationship[@Id='" + Id + "']"; ap.selectXPath(xpath); if (ap.evalXPath() != -1) { int index = -1; if ((index = vn.getAttrVal("Target")) != -1) { partPath = vn.toString(index); } } pathUtil.setWordRoot(); // 回到 superRoot/word 目录 partPath = pathUtil.getPackageFilePath(partPath, false); pathUtil.setSuperRoot(); // 回到根目录 return partPath; } /** * 处理主文档的关系 * @throws Exception */ public void arrangeRelations (XliffInputer xlfInput, IProgressMonitor monitor) throws Exception { if (monitor == null) { monitor = new NullProgressMonitor(); } String xpath = ""; // 先获取页眉的文件路径 monitor.setTaskName(Messages.getString("xlf2Docx.task1")); String headerType = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/header"; xpath = "/Relationships/Relationship[@Type='" + headerType + "']/@Target"; ap.selectXPath(xpath); while(ap.evalXPath() != -1){ String target = vn.toRawString(vn.getCurrentIndex() + 1); if (!"".equals(target)) { pathUtil.setWordRoot(); String partPath = pathUtil.getPackageFilePath(target, false); HeaderPart part = new HeaderPart(partPath, xlfInput); part.reverseConvert(); } } monitorWork(monitor); // 再处理页脚 monitor.setTaskName(Messages.getString("xlf2Docx.task2")); String footerType = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/footer"; xpath = "/Relationships/Relationship[@Type='" + footerType + "']/@Target"; ap.selectXPath(xpath); while(ap.evalXPath() != -1){ String target = vn.toRawString(vn.getCurrentIndex() + 1); if (!"".equals(target)) { pathUtil.setWordRoot(); String partPath = pathUtil.getPackageFilePath(target, false); FooterPart part = new FooterPart(partPath, xlfInput); part.reverseConvert(); } } monitorWork(monitor); // 再处理批注 monitor.setTaskName(Messages.getString("xlf2Docx.task3")); String CommentsType = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments"; xpath = "/Relationships/Relationship[@Type='" + CommentsType + "']/@Target"; ap.selectXPath(xpath); while(ap.evalXPath() != -1){ String target = vn.toRawString(vn.getCurrentIndex() + 1); if (!"".equals(target)) { pathUtil.setWordRoot(); String partPath = pathUtil.getPackageFilePath(target, false); CommentsPart part = new CommentsPart(partPath, xlfInput); part.reverseConvert(); } } monitorWork(monitor); // 再处理脚注 monitor.setTaskName(Messages.getString("xlf2Docx.task4")); String footNotesType = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/footnotes"; xpath = "/Relationships/Relationship[@Type='" + footNotesType + "']/@Target"; ap.selectXPath(xpath); while(ap.evalXPath() != -1){ String target = vn.toRawString(vn.getCurrentIndex() + 1); if (!"".equals(target)) { pathUtil.setWordRoot(); String partPath = pathUtil.getPackageFilePath(target, false); FooterNodesPart part = new FooterNodesPart(partPath, xlfInput); part.reverseConvert(); } } monitorWork(monitor); // 最后处理尾注 monitor.setTaskName(Messages.getString("xlf2Docx.task5")); String endNotesType = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/endnotes"; xpath = "/Relationships/Relationship[@Type='" + endNotesType + "']/@Target"; ap.selectXPath(xpath); while(ap.evalXPath() != -1){ String target = vn.toRawString(vn.getCurrentIndex() + 1); if (!"".equals(target)) { pathUtil.setWordRoot(); String partPath = pathUtil.getPackageFilePath(target, false); EndNotesPart part = new EndNotesPart(partPath, xlfInput); part.reverseConvert(); } } monitorWork(monitor); } public void monitorWork(IProgressMonitor monitor){ monitor.worked(1); if (monitor.isCanceled()) { throw new OperationCanceledException(Messages.getString("docxConvert.task3")); } } }
5,485
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
EndNotesPart.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.word2007/src/net/heartsome/cat/converter/word2007/partOper/EndNotesPart.java
package net.heartsome.cat.converter.word2007.partOper; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import net.heartsome.cat.converter.StringSegmenter; import net.heartsome.cat.converter.word2007.PartOperate; import net.heartsome.cat.converter.word2007.XliffInputer; import net.heartsome.cat.converter.word2007.XliffOutputer; /** * 处理尾注 endNotes.xml 文件。 * @author robert 2012-08-17 */ public class EndNotesPart extends PartOperate { /** * 正向转换所用到的构造方法 * @param partPath * @param xlfOutput * @param segmenter * @throws Exception */ public EndNotesPart(String partPath, XliffOutputer xlfOutput, StringSegmenter segmenter) throws Exception { super(partPath, xlfOutput, segmenter); init(); } /** * 逆转换用到的构造函数 * @param partPath * @param xlfInput */ public EndNotesPart (String partPath, XliffInputer xlfInput) throws Exception { super(partPath, xlfInput); init(); } private void init() throws Exception { nameSpaceMap = new HashMap<String, String>(); nameSpaceMap.put("w", "http://schemas.openxmlformats.org/wordprocessingml/2006/main"); nameSpaceMap.put("v", "urn:schemas-microsoft-com:vml"); loadFile(nameSpaceMap); } /** * 这里,因为处理尾注的时机是根据传入的 id 决定的,但针对对可翻译属性的处理,只能处理一次,故放在 run 方法里面。这种情况,尾注,批注,有点类似 */ @Override protected void converter() throws Exception { operateTransAttributes("/w:endnotes/w:endnote/descendant::w:p/w:r/w:pict/v:shape/@alt"); } /** * 根据指定的 id 进行处理批注信息 * @param id * @throws Exception */ protected void operateEndNotesContent(String id) throws Exception { // 处理的单元为 w:p String xpath = "/w:endnotes/w:endnote[@w:id='" + id + "']/descendant::w:p"; ap.selectXPath(xpath); while(ap.evalXPath() != -1){ 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(); 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); } } } } } } public void outputPart() throws Exception{ xm.output(partPath); } // ------------------------------------------ 下面是逆转换的代码 ------------------------------------------------ @Override protected void reverseConvert() throws Exception { // 处理的单元为 w:p String xpath = "/w:endnotes/w:endnote/descendant::w:p"; ap.selectXPath(xpath); while(ap.evalXPath() != -1){ // DOLATER 先处理所有的属性 analysisReversePnode(); } xm.output(partPath); //再处理可翻译属性 xpath = "/w:endnotes/w:endnote/descendant::w:p/w:r/w:pict/v:shape/@alt"; reverseTranslateAttributes(xpath); } }
3,663
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
DocumentPart.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.word2007/src/net/heartsome/cat/converter/word2007/partOper/DocumentPart.java
package net.heartsome.cat.converter.word2007.partOper; import java.io.File; import java.text.MessageFormat; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import net.heartsome.cat.converter.StringSegmenter; import net.heartsome.cat.converter.word2007.PartOperate; import net.heartsome.cat.converter.word2007.XliffInputer; import net.heartsome.cat.converter.word2007.XliffOutputer; import net.heartsome.cat.converter.word2007.common.DocxConverterException; import net.heartsome.cat.converter.word2007.common.PathConstant; import net.heartsome.cat.converter.word2007.common.PathUtil; import net.heartsome.cat.converter.word2007.resource.Messages; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.core.runtime.OperationCanceledException; import org.eclipse.core.runtime.SubProgressMonitor; /** * 文件 *.zip/word/document.xml 的处理类,主要是获取内容,添加占位符<br/>也是处理所有文件的入口类。 * @author robert 2012-08-08 */ public class DocumentPart extends PartOperate { private PathUtil pathUtil; /** 主文档与其他文件的关联类实例 */ private DocumentRelation docRel; private String inputFile; private FooterNodesPart footerNodesPart; private CommentsPart commentsPart; private EndNotesPart endNotesPart; private IProgressMonitor monitor; /** 这是进度条的前进间隔,也就是当循环多少个 w:p 节点后前进一格 */ private static int workInterval = 1; /** * 正转换的构造函数 * @param partPath * @param pathUtil * @param xlfOutput * @param segmenter * @throws Exception */ public DocumentPart(String partPath, PathUtil pathUtil, XliffOutputer xlfOutput, StringSegmenter segmenter, String inputFile, IProgressMonitor monitor) throws Exception { super(partPath, xlfOutput, segmenter); this.pathUtil = pathUtil; this.inputFile = inputFile; if (monitor == null) { monitor = new NullProgressMonitor(); } this.monitor = monitor; init(); } /** * 逆转换用到的构造函数 * @param partPath * @param xlfInput */ public DocumentPart(String partPath, XliffInputer xlfInput, IProgressMonitor monitor) throws Exception { super(partPath, xlfInput); if (monitor == null) { monitor = new NullProgressMonitor(); } this.monitor = monitor; init(); } /** * 初始化,解析文件 */ private void init() throws Exception { nameSpaceMap = new HashMap<String, String>(); nameSpaceMap.put("w", "http://schemas.openxmlformats.org/wordprocessingml/2006/main"); nameSpaceMap.put("v", "urn:schemas-microsoft-com:vml"); loadFile(nameSpaceMap); } /** * 清除一些无用的节点或属性,比如 <w:rFonts w:hint="eastAsia" /> 中的 w:hint、拼写检查 * <w:proofErr w:type="spellStart" /> <w:proofErr w:type="spellEnd" /> * 其他的可以进行补充 * * 以及,处理软回车的情况。将软回车的标识符单独成 w:r。 */ public void clearNoUseNodeAndDealBR() throws Exception{ ap.selectXPath("/w:document/w:body/descendant::w:p//w:proofErr[@w:type='spellStart' or @w:type='spellEnd']"); while(ap.evalXPath() != -1){ xm.remove(); } ap.selectXPath("/w:document/w:body/descendant::w:p//w:rFonts/@w:hint"); while(ap.evalXPath() != -1){ xm.remove(); } // // 处理软回车 // ap.selectXPath("/w:document/w:body/descendant::w:p//w:r[w:br]"); // while (ap.evalXPath() != -1) { // String fragment = vu.getElementFragment(); // String brFrag = null; // String textFrag = null; // vn.push(); // childAP.selectXPath("./w:br"); // if (childAP.evalXPath() != -1) { // brFrag = vu.getElementFragment(); // } // vn.pop(); // vn.push(); // childAP.selectXPath("./w:t"); // if (childAP.evalXPath() != -1) { // textFrag = vu.getElementFragment(); // } // vn.pop(); // // if (!(textFrag == null || textFrag.trim().isEmpty())) { // StringBuffer sb = new StringBuffer(); // sb.append(fragment.replace(textFrag, "<w:t></w:t>")); // sb.append(fragment.replace(brFrag, "")); // xm.remove(); // xm.insertAfterElement(sb.toString()); // } // } xm.output(partPath); super.loadFile(super.nameSpaceMap); } @Override public void converter() throws Exception { // 第一步是判断当前文档是否有未接受修订的文本,如果有,提示 if (validIsRevision()) { String messages = MessageFormat.format(Messages.getString("docx2Xlf.msg2"), new File(inputFile).getName()); throw new DocxConverterException(messages); } // 第一步先解析节点 w:sectPr 获取页眉与页脚的信息 monitor.setTaskName(Messages.getString("docx2Xlf.task1")); operateHeaderAndFooter(); monitor.worked(1); // 获取主文档的内容 getDocumentContent(); } /** * 判断是否接修个修订 * @return */ private boolean validIsRevision() throws Exception { String xpath = "/w:document/w:body/descendant::w:ins/w:r/w:t[text()!='']"; ap.selectXPath(xpath); if (ap.evalXPath() != -1) { return true; } return false; } public void testSegFile() throws Exception { // 处理的单元为 w:p String xpath = "/w:document/w:body/descendant::w:p"; ap.selectXPath(xpath); while(ap.evalXPath() != -1){ // 开始分析所循环的每一个 w:p 节点 analysisNodeP(); } xm.output(partPath); } /** * 获取页眉与页脚的信息,依据主文档的 W:sectPr 节点里面页眉与页脚的顺序。 * @throws Exception */ private void operateHeaderAndFooter() throws Exception { String xpath = "/w:document/w:body/descendant::w:sectPr/descendant::node()[name()='w:headerReference' or name()='w:footerReference']"; ap.selectXPath(xpath); Map<String, String> idMap = new LinkedHashMap<String, String>(); int index = -1; while (ap.evalXPath() != -1) { String nodeName = vn.toString(vn.getCurrentIndex()); if((index = vn.getAttrVal("r:id")) != -1){ idMap.put(vn.toString(index), nodeName); } } // 根据获取出的 id 去document.xml.rels 文件获取对应的页眉与页脚的文件路径 pathUtil.setSuperRoot(); String docRelPath = pathUtil.getPackageFilePath(PathConstant.DOCUMENTRELS, false); docRel = new DocumentRelation(docRelPath, pathUtil); // 测试单个文件。 header1.xml // HeaderPart headerPart = new HeaderPart("/home/robert/Desktop/header1.xml", xlfOutput, segmenter); // headerPart.run(); // 新建一个 footerList ,主要是为了先解析页眉,后解析页脚。 List<String> footerList = new LinkedList<String>(); for (Entry<String, String> entry : idMap.entrySet()) { String hfPartPath = docRel.getPartPathById(entry.getKey()); if ("w:headerReference".equals(entry.getValue())) { HeaderPart headerPart = new HeaderPart(hfPartPath, xlfOutput, segmenter); headerPart.converter(); }else if ("w:footerReference".equals(entry.getValue())) { footerList.add(hfPartPath); } } for (String footerPartPath : footerList) { FooterPart footerPart = new FooterPart(footerPartPath, xlfOutput, segmenter); footerPart.converter(); } } /** * 获取文本档 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); } /** * 获取脚注的ID * @throws Exception */ private void getFooterNodesId(List<String> footerNodesIdList) throws Exception { otherAP.selectXPath("./w:r/w:footnoteReference/@w:id"); while(otherAP.evalXPath() != -1) { String id = vn.toRawString(vn.getCurrentIndex() + 1); if (!"".equals(id) && id != null) { footerNodesIdList.add(id); } } } /** * 获取批注的id * @param commentsIdList * @throws Exception */ private void getCommentsId(List<String> commentsIdList) throws Exception { otherAP.selectXPath("./w:r/w:commentReference/@w:id"); while(otherAP.evalXPath() != -1) { String id = vn.toRawString(vn.getCurrentIndex() + 1); if (!"".equals(id) && id != null) { commentsIdList.add(id); } } } /** * 获取尾注的 id */ private void getEndNotesId(List<String> endNotesIdList) throws Exception { otherAP.selectXPath("./w:r/w:endnoteReference/@w:id"); while(otherAP.evalXPath() != -1) { String id = vn.toRawString(vn.getCurrentIndex() + 1); if (!"".equals(id) && id != null) { endNotesIdList.add(id); } } } /** * 根据id去处理脚注 * @param footerNodesIdList * @throws Exception */ private void operateFooterNodes(List<String> footerNodesIdList) throws Exception { if (footerNodesPart == null) { pathUtil.setSuperRoot(); String footerNodesPartPath = pathUtil.getPackageFilePath(PathConstant.FOOTNOTES, false); footerNodesPart = new FooterNodesPart(footerNodesPartPath, xlfOutput, segmenter); footerNodesPart.converter(); } for (String footerNodesId : footerNodesIdList) { footerNodesPart.operateFooterNodesContent(footerNodesId); } } /** * 根据id去处理批注 * @param commentsIdList * @throws Exception */ private void operateComments(List<String> commentsIdList) throws Exception { if (commentsPart == null) { pathUtil.setSuperRoot(); String commentsPartPath = pathUtil.getPackageFilePath(PathConstant.COMMENTS, false); commentsPart = new CommentsPart(commentsPartPath, xlfOutput, segmenter); commentsPart.converter(); } for (String footerNodesId : commentsIdList) { commentsPart.operateCommentsContent(footerNodesId); } } /** * 根据id去处理尾注 * @param commentsIdList * @throws Exception */ private void operateEndNotes(List<String> endNotesIdList) throws Exception { if (endNotesPart == null) { pathUtil.setSuperRoot(); String commentsPartPath = pathUtil.getPackageFilePath(PathConstant.ENDNOTES, false); endNotesPart = new EndNotesPart(commentsPartPath, xlfOutput, segmenter); endNotesPart.converter(); } for (String endNotesId : endNotesIdList) { endNotesPart.operateEndNotesContent(endNotesId); } } /** * 初始化进度条前进前隔值,使之总值不大于五百。 */ private void initWorkInterval(int allPSum){ if (allPSum > 500) { workInterval = allPSum / 500; } } /** * 获取某节点的总数 * @return */ public int getNodeCount(String xpath){ int nodeNum = 0; try { ap.selectXPath("count(" + xpath + ")"); nodeNum = (int) ap.evalXPathToNumber(); } catch (Exception e) { e.printStackTrace(); } return nodeNum; } /** * 进度条前进处理类,若返回false,则标志退出程序的执行 * @param monitor * @param traverPIdx * @param last * @return ; */ public boolean monitorWork(IProgressMonitor monitor, int traverPIdx, boolean last){ if (last) { if (traverPIdx % workInterval != 0) { if (monitor.isCanceled()) { throw new OperationCanceledException(Messages.getString("docxConvert.task3")); } monitor.worked(1); } }else { if (traverPIdx % workInterval == 0) { if (monitor.isCanceled()) { throw new OperationCanceledException(Messages.getString("docxConvert.task3")); } monitor.worked(1); } } return true; } // ------------------------------------------ 下面是逆转换的代码 ------------------------------------------------ @Override public void reverseConvert() throws Exception { // 处理的单元为 w:p String xpath = "/w:document/w:body/descendant::w:p"; int allPSum = getNodeCount(xpath); initWorkInterval(allPSum); IProgressMonitor subMonitor = new SubProgressMonitor(monitor, 12, SubProgressMonitor.PREPEND_MAIN_LABEL_TO_SUBTASK); subMonitor.beginTask("", allPSum % workInterval == 0 ? (allPSum / workInterval) : (allPSum / workInterval) + 1); subMonitor.setTaskName(Messages.getString("xlf2Docx.task5")); ap.selectXPath(xpath); int traverPIdx = 0; while(ap.evalXPath() != -1){ traverPIdx ++; analysisReversePnode(); monitorWork(subMonitor, traverPIdx, false); } xm.output(partPath); monitorWork(subMonitor, traverPIdx, true); subMonitor.done(); //再处理可翻译属性 xpath = "/w:document/w:body/descendant::w:p/w:r/w:pict/v:shape/@alt"; reverseTranslateAttributes(xpath); monitor.worked(1); if (monitor.isCanceled()) { throw new OperationCanceledException(Messages.getString("docxConvert.task3")); } } }
15,714
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
Messages.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.word2007/src/net/heartsome/cat/converter/word2007/resource/Messages.java
/** * Messages.java * * Version information : * * Date:Jan 14, 2010 * * Copyright notice : */ package net.heartsome.cat.converter.word2007.resource; import java.util.MissingResourceException; import java.util.ResourceBundle; /** * 国际化工具类 * @author peason * @version * @since JDK1.6 */ public final class Messages { /** The Constant BUNDLE_NAME. */ private static final String BUNDLE_NAME = "net.heartsome.cat.converter.word2007.resource.message"; //$NON-NLS-1$ /** The Constant RESOURCE_BUNDLE. */ private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle.getBundle(BUNDLE_NAME); /** * Instantiates a new messages. */ private Messages() { // Do nothing } /** * Gets the string. * @param key * the key * @return the string */ public static String getString(String key) { try { return RESOURCE_BUNDLE.getString(key); } catch (MissingResourceException e) { return '!' + key + '!'; } } }
1,028
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
TuMrkBean.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.trados2009/src/net/heartsome/cat/converter/trados2009/TuMrkBean.java
package net.heartsome.cat.converter.trados2009; import java.util.LinkedList; import java.util.List; /** * 这是sdlXliff文件trans-unit/source或target节点下mrk[mtype='seg']节点的内容 pojo类 * @author robert 2012-06-29 */ public class TuMrkBean { private String mid; private String content; private boolean isSource; /** 批注 */ private List<CommentBean> commentList; /** * <div>sdl文件的状态,下面是sdl至r8 xliff文件状态的转换</div> * <table border='1' cellSpacing='1' cellSpadding='0'> * <tr><td>sdl</td><td>R8 xliff</td><td>备注</td></tr> * <tr><td>Draft</td><td>new</td><td>草稿</td></tr> * <tr><td>Translated</td><td>translated</td><td>已翻译->完成翻译</td></tr> * <tr><td>RejectedTranslation</td><td>new</td><td>翻译被否决->草稿</td></tr> * <tr><td>ApprovedTranslation</td><td colSpan='2'>批准翻译,在trans-unit节点中设置 approved="yes"</td></tr> * <tr><td>RejectedSignOff</td><td colSpan='2'>签发被拒绝,回到批准状态</td></tr> * <tr><td>ApprovedSignOff</td><td>state="signed-off"</td><td>签发</td></tr> * </table> */ private String status; /** 是否锁定 * <div style="color:red">在R8中的锁定格式为 &lt trans-unit translate="no"&gt ... &lt/trans-unit&gt, * <br>而在sdl中这种表达方式为不需翻译,即不会加载到翻译工具界面中。</div> */ private boolean isLocked; private String quality; private String matchType; public TuMrkBean(){} public TuMrkBean(String mid, String content, List<CommentBean> commentList, String status, boolean isSource){ this.mid = mid; this.content = content; this.commentList = commentList; this.isSource = isSource; this.status = status; } /** * 判断当前mrk节点的文本是否为空 * @return */ public boolean isTextNull(){ if (content == null || "".equals(content)) { return true; } return false; } public String getMid() { return mid; } public void setMid(String mid) { this.mid = mid; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public List<CommentBean> getCommentList() { return commentList; } public void setCommentList(List<CommentBean> commentList) { this.commentList = commentList; } public boolean isSource() { return isSource; } public void setSource(boolean isSource) { this.isSource = isSource; } /** * <div>sdl文件的状态,下面是sdl至r8 xliff文件状态的转换,这个状态与锁定分开</div> * <table border='1' cellSpacing='1' cellSpadding='0'> * <tr><td>sdl</td><td>R8 xliff</td><td>备注</td></tr> * <tr><td>Draft</td><td>new</td><td>草稿</td></tr> * <tr><td>Translated</td><td>translated</td><td>已翻译->完成翻译</td></tr> * <tr><td>RejectedTranslation</td><td>new</td><td>翻译被否决->草稿</td></tr> * <tr><td>ApprovedTranslation</td><td colSpan='2'>批准翻译,在trans-unit节点中设置 approved="yes"</td></tr> * <tr><td>RejectedSignOff</td><td colSpan='2'>签发被拒绝,回到批准状态</td></tr> * <tr><td>ApprovedSignOff</td><td>state="signed-off"</td><td>签发</td></tr> * <tr><td>percent</td><td>hs:quality</td><td>匹配率</td></tr> * <tr><td>origin</td><td>hs:matchType="TM"</td><td>匹配类型</td></tr> * </table> */ public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } /** 是否锁定 * <div style="color:red">在R8中的锁定格式为 &lt trans-unit translate="no"&gt ... &lt/trans-unit&gt, * <br>而在sdl中这种表达方式为不需翻译,即不会加载到翻译工具界面中。</div> */ public boolean isLocked() { return isLocked; } public void setLocked(boolean isLocked) { this.isLocked = isLocked; } /** * 添加全局批注变量 * @param fileComments */ public void addFileComments(List<CommentBean> fileComments){ if (fileComments == null || fileComments.size() <= 0) { return; } if (commentList == null) { commentList = new LinkedList<CommentBean>(); } commentList.addAll(fileComments); } /** * 匹配率 * @return */ public String getQuality() { return quality; } public void setQuality(String quality) { this.quality = quality; } public String getMatchType() { return matchType; } public void setMatchType(String matchType) { this.matchType = matchType; } }
4,503
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
CommentBean.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.trados2009/src/net/heartsome/cat/converter/trados2009/CommentBean.java
package net.heartsome.cat.converter.trados2009; import net.heartsome.cat.common.util.DateUtils; /** * 批注信息,针对trados 2009的文件以及R8的XLIFF文件 * @author robert 2012-07-02 */ public class CommentBean { /** 标注的文件 */ private String commentText; /** 标注的作者 */ private String user; /** 标注的添加时间 */ private String date; /** trados 2009文件批注的提示级别,取值为Low供参考, Medium警告, High错误 */ private String severity; /** 是否是全局批注 */ private boolean isCurrentSeg; public CommentBean(){} public CommentBean(String user, String date, String severity, String commentText, boolean isCurrentSeg){ this.user = user; this.date = date; this.severity = severity; this.commentText = commentText; this.isCurrentSeg = isCurrentSeg; } public String getCommentText() { return commentText; } public void setCommentText(String commentText) { this.commentText = commentText; } public String getUser() { return user; } public void setUser(String user) { this.user = user; } public String getDate() { return date; } public void setDate(String date) { this.date = date; } public String getSeverity() { return severity; } public void setSeverity(String severity) { this.severity = severity; } public boolean isCurrent() { return isCurrentSeg; } public void setCurrent(boolean isCurrentSeg) { this.isCurrentSeg = isCurrentSeg; } /** * 获取R8状态下的批注文本 * @return */ public String getR8NoteText(){ String newDate = DateUtils.dateToStr(DateUtils.strToDate(date)); return newDate + ":" + commentText; } @Override public boolean equals(Object obj) { if (obj instanceof CommentBean) { CommentBean curBean = (CommentBean) obj; if (curBean.getUser().equals(this.user) && curBean.getDate().equals(this.date) && curBean.getCommentText().equals(this.commentText)) { return true; } } return false; } }
1,991
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
Activator.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.trados2009/src/net/heartsome/cat/converter/trados2009/Activator.java
package net.heartsome.cat.converter.trados2009; import java.util.Properties; import net.heartsome.cat.converter.Converter; import net.heartsome.cat.converter.util.ConverterRegister; import org.osgi.framework.BundleActivator; import org.osgi.framework.BundleContext; import org.osgi.framework.ServiceRegistration; /** * The activator class controls the plug-in life cycle * trados 2009 转换器的 Activator。 --robert 2012-06-27 */ public class Activator implements BundleActivator { // The plug-in ID public static final String PLUGIN_ID = "net.heartsome.cat.converter.trados2009"; //$NON-NLS-1$ // The shared instance private static Activator plugin; /** trados 2009文件转换至xliff文件的服务注册器 */ // @SuppressWarnings("rawtypes") private ServiceRegistration sdl2XliffSR; /** xliff文件转换至trados 2009文件的服务注册器 */ // @SuppressWarnings("rawtypes") private ServiceRegistration xliff2SdlSR; /** * The constructor */ public Activator() { } /* * (non-Javadoc) * @see org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext) */ public void start(BundleContext context) throws Exception { plugin = this; Converter sdl2Xliff = new Sdl2Xliff(); Properties properties = new Properties(); properties.put(Converter.ATTR_NAME, Sdl2Xliff.NAME_VALUE); properties.put(Converter.ATTR_TYPE, Sdl2Xliff.TYPE_VALUE); properties.put(Converter.ATTR_TYPE_NAME, Sdl2Xliff.TYPE_NAME_VALUE); sdl2XliffSR = ConverterRegister.registerPositiveConverter(context, sdl2Xliff, properties); Converter xliff2Sdl = new Xliff2Sdl(); properties = new Properties(); properties.put(Converter.ATTR_NAME, Xliff2Sdl.NAME_VALUE); properties.put(Converter.ATTR_TYPE, Xliff2Sdl.TYPE_VALUE); properties.put(Converter.ATTR_TYPE_NAME, Xliff2Sdl.TYPE_NAME_VALUE); xliff2SdlSR = ConverterRegister.registerReverseConverter(context, xliff2Sdl, properties); } /* * (non-Javadoc) * @see org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext) */ public void stop(BundleContext context) throws Exception { if (sdl2XliffSR != null) { sdl2XliffSR.unregister(); sdl2XliffSR = null; } if (xliff2SdlSR != null) { xliff2SdlSR.unregister(); xliff2SdlSR = null; } plugin = null; } /** * Returns the shared instance * * @return the shared instance */ public static Activator getDefault() { return plugin; } }
2,441
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
Sdl2Xliff.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.trados2009/src/net/heartsome/cat/converter/trados2009/Sdl2Xliff.java
package net.heartsome.cat.converter.trados2009; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.text.MessageFormat; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import net.heartsome.cat.converter.Converter; import net.heartsome.cat.converter.ConverterException; import net.heartsome.cat.converter.trados2009.resource.Messages; import net.heartsome.cat.converter.util.ConverterUtils; import net.heartsome.cat.converter.util.Progress; import net.heartsome.util.CRC16; import net.heartsome.util.TextUtil; import net.heartsome.xml.vtdimpl.VTDLoader; import net.heartsome.xml.vtdimpl.VTDUtils; import org.eclipse.core.runtime.IProgressMonitor; import com.ximpleware.AutoPilot; import com.ximpleware.VTDGen; import com.ximpleware.VTDNav; import com.ximpleware.XMLModifier; /** * trados 2009 的sdlXliff文件转换成R8的xliff文件 * @author robert 2012-06-27 */ public class Sdl2Xliff implements Converter{ /** The Constant TYPE_VALUE. */ public static final String TYPE_VALUE = "sdlxliff"; /** The Constant TYPE_NAME_VALUE. */ public static final String TYPE_NAME_VALUE = Messages.getString("utils.FileFormatUtils.SDL"); /** The Constant NAME_VALUE. */ public static final String NAME_VALUE = "SDLXLIFF to XLIFF Conveter"; public Map<String, String> convert(Map<String, String> args, IProgressMonitor monitor) throws ConverterException { Sdl2XliffImpl converter = new Sdl2XliffImpl(); return converter.run(args, monitor); } public String getName() { return NAME_VALUE; } public String getType() { return TYPE_VALUE; } public String getTypeName() { return TYPE_NAME_VALUE; } class Sdl2XliffImpl{ /** 源文件 */ private String inputFile; /** 转换成的XLIFF文件(临时文件) */ private String xliffFile; /** 骨架文件(临时文件) */ private String skeletonFile; /** 源语言 */ private String userSourceLang; /** 目标语言 */ private String targetLang; // private String detectedSourceLang; // private String detectedTargetLang; /** 转换的编码格式 */ private String srcEncoding; // private Element inputRoot; // private Document skeleton; // private Element skeletonRoot; /** 将数据输出到XLIFF文件的输出流 */ private FileOutputStream output; // private StringSegmenter segmenter; // /** xliff 文件的 trans-unit 节点的 id 值 */ // private int segId; /** sdl文件的全局批注 */ private List<CommentBean> fileCommentsList = new LinkedList<CommentBean>(); private int tagId; private String catalogue; private boolean ignoreTags; private boolean lockXtrans; private boolean lock100; private boolean isSuite; /** 转换工具的ID */ private String qtToolID; /** 解析骨架文件的VTDNav实例 */ private VTDNav sklVN; private XMLModifier sklXM; public Map<String, String> run(Map<String, String> params, IProgressMonitor monitor) throws ConverterException { monitor = Progress.getMonitor(monitor); monitor.beginTask("Converting...", 5); Map<String, String> result = new HashMap<String, String>(); inputFile = params.get(Converter.ATTR_SOURCE_FILE); xliffFile = params.get(Converter.ATTR_XLIFF_FILE); skeletonFile = params.get(Converter.ATTR_SKELETON_FILE); catalogue = params.get(Converter.ATTR_CATALOGUE); targetLang = params.get(Converter.ATTR_TARGET_LANGUAGE); userSourceLang = params.get(Converter.ATTR_SOURCE_LANGUAGE); srcEncoding = params.get(Converter.ATTR_SOURCE_ENCODING); isSuite = false; if (Converter.TRUE.equalsIgnoreCase(params.get(Converter.ATTR_IS_SUITE))) { isSuite = true; } qtToolID = params.get(Converter.ATTR_QT_TOOLID) != null ? params.get(Converter.ATTR_QT_TOOLID) : Converter.QT_TOOLID_DEFAULT_VALUE; lockXtrans = false; if (Converter.TRUE.equals(params.get(Converter.ATTR_LOCK_XTRANS))) { lockXtrans = true; } lock100 = false; if (Converter.TRUE.equals(params.get(Converter.ATTR_LOCK_100))) { lock100 = true; } try { output = new FileOutputStream(xliffFile); copyFile(inputFile, skeletonFile); parseSkeletonFile(); getFileComments(); //先写下头文件 writeHeader(); analyzeNodes(); writeString("</body>\n"); writeString("</file>\n"); writeString("</xliff>"); //为了逆转换时的方便,此时删除所有的批注 deleteSklComments(); sklXM.output(skeletonFile); // String file1 = "/home/robert/Desktop/file1.txt"; // String file2 = "/home/robert/Desktop/file2.txt"; // copyFile(skeletonFile, file1); // copyFile(xliffFile, file2); } catch (Exception e) { e.printStackTrace(); String errorTip = Messages.getString("sdl2Xlf.msg1") + "\n" + e.getMessage(); ConverterUtils.throwConverterException(Activator.PLUGIN_ID, errorTip, e); }finally{ try { if (output != null) { output.close(); } } catch (Exception e2) { e2.printStackTrace(); String errorTip = Messages.getString("sdl2Xlf.msg1") + "\n" + e2.getMessage(); ConverterUtils.throwConverterException(Activator.PLUGIN_ID, errorTip, e2); } monitor.done(); } return result; } /** * 写下XLIFF文件的头节点 */ private void writeHeader() throws IOException { writeString("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"); writeString("<xliff version=\"1.2\" xmlns=\"urn:oasis:names:tc:xliff:document:1.2\" " + "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" " + "xmlns:sdl=\"http://sdl.com/FileTypes/SdlXliff/1.0\" " + "xmlns:hs=\"" + Converter.HSNAMESPACE + "\" " + "xsi:schemaLocation=\"urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd " + Converter.HSSCHEMALOCATION + "\">\n"); writeString("<file original=\"" + TextUtil.cleanString(inputFile) + "\" source-language=\"" + userSourceLang); writeString("\" target-language=\"" + ((targetLang == null || "".equals(targetLang)) ? userSourceLang : targetLang)); writeString("\" datatype=\"" + TYPE_VALUE + "\">\n"); writeString("<header>\n"); writeString(" <skl>\n"); String crc = ""; if (isSuite) { crc = "crc=\"" + CRC16.crc16(TextUtil.cleanString(skeletonFile).getBytes("utf-8")) + "\""; } writeString(" <external-file href=\"" + TextUtil.cleanString(skeletonFile) + "\" " + crc + "/>\n"); writeString(" </skl>\n"); writeString(" <tool tool-id=\"" + qtToolID + "\" tool-name=\"HSStudio\"/>\n"); writeString(" <hs:prop-group name=\"encoding\"><hs:prop prop-type=\"encoding\">" + srcEncoding + "</hs:prop></hs:prop-group>\n"); writeString("</header>\n"); writeString("<body>\n"); } private void writeString(String string) throws IOException { output.write(string.getBytes("utf-8")); //$NON-NLS-1$ } /** * 解析骨架文件,此时的骨架文件的内容就是源文件的内容 * @throws Exception */ private void parseSkeletonFile() throws Exception{ // String errorInfo = ""; VTDGen vg = VTDLoader.loadVTDGen(new File(skeletonFile), "UTF-8"); // if (vg.parseFile(skeletonFile, true)) { sklVN = vg.getNav(); sklXM = new XMLModifier(sklVN); // }else { // errorInfo = MessageFormat.format(Messages.getString("sdl.parse.msg1"), // new Object[]{new File(inputFile).getName()}); // throw new Exception(errorInfo); // } } /** * 分析每一个节点 * @throws Exception */ private void analyzeNodes() throws Exception{ AutoPilot ap = new AutoPilot(sklVN); AutoPilot mrkAP = new AutoPilot(sklVN); VTDUtils vu = new VTDUtils(sklVN); String xpath = "/xliff/file/body//trans-unit[not(@translate='no')]"; ///seg-source/mrk[@mtype=\"seg\"] String srxMrkXpath = "./seg-source//mrk[@mtype=\"seg\"]"; String tgtMrkXpath = "./target//mrk[@mtype=\"seg\"]"; //存储源文的集合,key为mrk节点的mid。 Map<String, TuMrkBean> srcMap = new LinkedHashMap<String, TuMrkBean>(); //存储译文的集合,key为mrk节点的mid。 Map<String, TuMrkBean> tgtMap = new LinkedHashMap<String, TuMrkBean>(); //针对骨架文件的每一个源文节点的mrk保存占位符ID Map<String, Integer> segMap = new HashMap<String, Integer>(); ap.selectXPath(xpath); int attrIdx = -1; //xliff 文件的 trans-unit 节点的 id 值 int segId = 0; while (ap.evalXPath() != -1) { // 清除所有数据 srcMap.clear(); tgtMap.clear(); sklVN.push(); mrkAP.resetXPath(); mrkAP.selectXPath(srxMrkXpath); while (mrkAP.evalXPath() != -1) { // 先获取出节点mrk的属性mid的值 attrIdx = sklVN.getAttrVal("mid"); String mid; if (attrIdx == -1 || "".equals(mid = sklVN.toString(attrIdx))) { continue; } String srcContent = vu.getElementContent(); if (srcContent != null && !"".equals(srcContent)) { srcMap.put(mid, new TuMrkBean(mid, srcContent, null, null, true)); //开始填充占位符 insertPlaceHolder(vu, segId); segMap.put(mid, segId); segId ++; } } sklVN.pop(); // 开始处理骨架文件的译文信息 sklVN.push(); mrkAP.resetXPath(); mrkAP.selectXPath(tgtMrkXpath); while (mrkAP.evalXPath() != -1) { attrIdx = sklVN.getAttrVal("mid"); String mid; if (attrIdx == -1 || "".equals(mid = sklVN.toString(attrIdx))) { continue; } //注意两个填充占位符方法的位置不同。 if (segMap.get(mid) != null) { insertPlaceHolder(vu, segMap.get(mid)); TuMrkBean tgtBean = new TuMrkBean(); tgtBean.setSource(false); anysisTuMrkNode(sklVN, vu, tgtBean); anysisTuMrkStatus(sklVN, vu, tgtBean, mid); tgtBean.addFileComments(fileCommentsList); tgtMap.put(mid, tgtBean); } } //UNDO 这里还没有处理目标节点mrk的mid值与源文相比遗失的情况 2012-06-29 //开始填充数据到XLIFF文件 for(Entry<String, TuMrkBean> srcEntry : srcMap.entrySet()){ String key = srcEntry.getKey(); //这个key是mid TuMrkBean srcBean = srcEntry.getValue(); TuMrkBean tgtBean = tgtMap.get(key) == null ? new TuMrkBean() : tgtMap.get(key); int curSegId = segMap.get(key); writeSegment(srcBean, tgtBean, curSegId); } sklVN.pop(); } } /** * 给剔去翻译内容后的骨架文件填充占位符 * @throws Exception */ private void insertPlaceHolder(VTDUtils vu, int seg) throws Exception{ String mrkHeader = vu.getElementHead(); String newMrkStr = mrkHeader + "%%%"+ seg +"%%%" + "</mrk>"; sklXM.remove(); sklXM.insertAfterElement(newMrkStr.getBytes(srcEncoding)); } /** * 向XLIFF文件输入新生成的trans-unit节点 * @param srcContent * @param tgtContent * @param segId * @throws Exception */ private void writeSegment(TuMrkBean srcBean, TuMrkBean tgtBean, int segId) throws Exception{ String srcContent = srcBean.getContent(); StringBuffer tuSB = new StringBuffer(); String status = tgtBean.getStatus(); String tgtStatusStr = ""; boolean isApproved = false; // 具体的意思及与R8的转换请查看tgtBean.getStatus()的注释。 if ("Draft".equals(status)) { tgtStatusStr += " state=\"new\""; }else if ("Translated".equals(status)) { tgtStatusStr += " state=\"translated\""; }else if ("RejectedTranslation".equals(status)) { tgtStatusStr += " state=\"new\""; }else if ("ApprovedTranslation".equals(status)) { isApproved = true; tgtStatusStr += " state=\"translated\""; }else if ("RejectedSignOff".equals(status)) { isApproved = true; tgtStatusStr += " state=\"translated\""; }else if ("ApprovedSignOff".equals(status)) { isApproved = true; tgtStatusStr += " state=\"signed-off\""; } String strMatchType = null; String strQuality = null; strMatchType = tgtBean.getMatchType() == null ? "" : " hs:matchType=\"".concat(tgtBean.getMatchType()).concat("\""); strQuality = tgtBean.getQuality() == null ? "" : " hs:quality=\"".concat(tgtBean.getQuality()).concat("\""); String approveStr = isApproved ? " approved=\"yes\"" : ""; //是否锁定 String lockStr = tgtBean.isLocked() ? " translate=\"no\"" : ""; tuSB.append(" <trans-unit" + lockStr + approveStr + " id=\"" + segId + "\" xml:space=\"preserve\" >\n"); tuSB.append(" <source xml:lang=\"" + userSourceLang + "\">" + srcContent + "</source>\n"); if (!tgtBean.isTextNull()) { String tgtContent = tgtBean.getContent(); tuSB.append("<target").append(tgtStatusStr).append(" xml:lang=\"").append((targetLang == null || "".equals(targetLang)) ? userSourceLang : targetLang).append("\"") .append(strMatchType).append(strQuality).append(">").append(tgtContent).append("</target>\n"); } //添加备注信息 if (tgtBean.getCommentList() != null && tgtBean.getCommentList().size() > 0) { //这是R8的标注格式:<note from='robert'>2012-03-06:asdf</note> for(CommentBean cBean : tgtBean.getCommentList()){ tuSB.append("<note from='" + cBean.getUser() + "'"+ (cBean.isCurrent() ? "" : " hs:apply-current='No'") + ">" + cBean.getR8NoteText() + "</note>"); } } tuSB.append(" </trans-unit>\n"); writeString(tuSB.toString()); } /** * 获取sdlXliff文件的tu节点下的源文或译文,主要是分析mrk节点下的内容 * @param vu * @return */ private void anysisTuMrkNode(VTDNav vn, VTDUtils vu, TuMrkBean bean) throws Exception{ vn.push(); AutoPilot ap = new AutoPilot(vn); if (vu.getChildElementsCount() > 0) { ap.selectXPath("./mrk[@mtype='x-sdl-comment']"); int attrIdx = -1; if(ap.evalXPath() != -1){ //这是有标注的情况,那么添加标注,备注信息只需添加到目标文本段中 if (!bean.isSource()) { String commandId = ""; if ((attrIdx = vn.getAttrVal("sdl:cid")) != -1) { commandId = vn.toString(attrIdx); } getSdlComment(vn, vu, commandId, bean); } } } String content = vu.getElementContent(); if (content != null && !"".equals(content)) { bean.setContent(content); } vn.pop(); } /** * 分析每一个文本段的状态 * @param vn * @param vu * @param tgtBean * @param mid target节点下子节点mrk的mid属性,即唯一id值 */ private void anysisTuMrkStatus(VTDNav vn, VTDUtils vu, TuMrkBean tgtBean, String mid) throws Exception { vn.push(); String status = ""; //一个空字符串代表未翻译 String xpath = "ancestor::trans-unit/sdl:seg-defs/sdl:seg[@id='" + mid + "']"; AutoPilot ap = new AutoPilot(vn); ap.declareXPathNameSpace("sdl", "http://sdl.com/FileTypes/SdlXliff/1.0"); ap.selectXPath(xpath); if(ap.evalXPath() != -1){ int attrIdx = -1; if ((attrIdx = vn.getAttrVal("conf")) != -1) { status = vn.toString(attrIdx); tgtBean.setStatus(status); } //判断是否是锁定 if ((attrIdx = vn.getAttrVal("locked")) != -1) { if ("true".equals(vn.toString(attrIdx))) { tgtBean.setLocked(true); } } if ((attrIdx = vn.getAttrVal("origin")) != -1) { //TODO R8中占时没有与 SDL 相对应的匹配类型,这里以后处理 tgtBean.setMatchType("TM"); } if ((attrIdx = vn.getAttrVal("percent")) != -1) { tgtBean.setQuality(vn.toString(attrIdx)); } } vn.pop(); } /** * 获取sdl文件的全局批注。 */ private void getFileComments() throws Exception{ AutoPilot ap = new AutoPilot(sklVN); //无论有几个file节点,都获取所有的备注信息 String xpath = "/xliff/file/header/sdl:cmt"; ap.declareXPathNameSpace("sdl", "http://sdl.com/FileTypes/SdlXliff/1.0"); ap.selectXPath(xpath); //sdl="http://sdl.com/FileTypes/SdlXliff/1.0" VTDUtils vu = new VTDUtils(sklVN); while(ap.evalXPath() != -1){ if (sklVN.getAttrVal("id") != -1) { String commentId = sklVN.toString(sklVN.getAttrVal("id")); getSdlComment(sklVN, vu, commentId, null); } } } /** * 获取trados 2009的备注信息 */ private void getSdlComment(VTDNav vn, VTDUtils vu, String commentId, TuMrkBean bean) throws Exception{ vn.push(); List<CommentBean> commentList = new LinkedList<CommentBean>(); boolean isCurrentSeg = true; //当前文本段的批注 if (bean == null) { isCurrentSeg = false; } int attrIdx = -1; if (commentId != null && !"".equals(commentId)) { String commandXpath = "/xliff/doc-info/cmt-defs/cmt-def[@id='" + commentId + "']/Comments/Comment"; AutoPilot ap = new AutoPilot(vn); ap.selectXPath(commandXpath); while(ap.evalXPath() != -1){ String severity = null; String user = null; String date = null; String commentText = null; if ((attrIdx = vn.getAttrVal("severity")) != -1) { severity = vn.toString(attrIdx); } if ((attrIdx = vn.getAttrVal("user")) != -1) { user = vn.toString(attrIdx); } if ((attrIdx = vn.getAttrVal("date")) != -1) { date = vn.toString(attrIdx); } commentText = vu.getElementContent(); commentList.add(new CommentBean(user, date, severity, commentText, isCurrentSeg)); } } //针对单一文本段的批注 if (isCurrentSeg) { bean.setCommentList(commentList); }else { //这时是全局批注 fileCommentsList.addAll(commentList); } vn.pop(); } /** * 删除骨架文件中的所有批注 * @throws Exception */ private void deleteSklComments() throws Exception{ AutoPilot ap = new AutoPilot(sklVN); String xpath; //寻找全局批注的定义处,并删除 xpath = "/xliff/file/header/sdl:cmt"; ap.declareXPathNameSpace("sdl", "http://sdl.com/FileTypes/SdlXliff/1.0"); ap.selectXPath(xpath); while(ap.evalXPath() != -1){ sklXM.remove(); } //先删除每个文本段的批注 xpath = "/xliff/doc-info/cmt-defs"; ap.selectXPath(xpath); if (ap.evalXPath() != -1) { sklXM.remove(); } } } //----------------------------------------------------Sdl2XliffImpl 结束标志--------------------------------------------// /** * 将一个文件的数据复制到另一个文件 * @param in * @param out * @throws Exception */ private static void copyFile(String in, String out) throws Exception { FileInputStream fis = new FileInputStream(in); FileOutputStream fos = new FileOutputStream(out); byte[] buf = new byte[1024]; int i = 0; while ((i = fis.read(buf)) != -1) { fos.write(buf, 0, i); } fis.close(); fos.close(); } }
18,852
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
Xliff2Sdl.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.trados2009/src/net/heartsome/cat/converter/trados2009/Xliff2Sdl.java
package net.heartsome.cat.converter.trados2009; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream; import java.text.MessageFormat; import java.util.HashMap; import java.util.Hashtable; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.UUID; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.core.runtime.OperationCanceledException; import org.eclipse.core.runtime.SubProgressMonitor; import com.ximpleware.AutoPilot; import com.ximpleware.VTDGen; import com.ximpleware.VTDNav; import com.ximpleware.XMLModifier; import net.heartsome.cat.common.util.CommonFunction; import net.heartsome.cat.converter.Converter; import net.heartsome.cat.converter.ConverterException; import net.heartsome.cat.converter.trados2009.resource.Messages; import net.heartsome.cat.converter.util.CalculateProcessedBytes; import net.heartsome.cat.converter.util.ConverterUtils; import net.heartsome.cat.converter.util.Progress; import net.heartsome.xml.Catalogue; import net.heartsome.xml.Element; import net.heartsome.xml.vtdimpl.VTDUtils; /** * R8的XLIFF文件转换成trados 2009 的 xliff文件 * @author robert 2012-06-25 */ public class Xliff2Sdl implements Converter{ /** The Constant TYPE_VALUE. */ public static final String TYPE_VALUE = "sdlxliff"; /** The Constant TYPE_NAME_VALUE. */ public static final String TYPE_NAME_VALUE = Messages.getString("utils.FileFormatUtils.SDL"); /** The Constant NAME_VALUE. */ public static final String NAME_VALUE = "XLIFF to SDLXLIFF Conveter"; public Map<String, String> convert(Map<String, String> args, IProgressMonitor monitor) throws ConverterException { Xliff2SdlImpl impl = new Xliff2SdlImpl(); return impl.run(args, monitor); } public String getName() { return NAME_VALUE; } public String getType() { return TYPE_VALUE; } public String getTypeName() { return TYPE_NAME_VALUE; } class Xliff2SdlImpl{ /** The segments. */ private Hashtable<String, Element> segments; /** 逆转换的结果文件 */ private String outputFile; /** The encoding. */ private String encoding; /** The catalogue. */ private Catalogue catalogue; /** The detected source lang. */ private String detectedSourceLang; /** The detected target lang. */ private String detectedTargetLang; /** The fr. */ private InputStream fr = null; /** The br. */ private BufferedReader br = null; /** The bos. */ private BufferedWriter bos = null; /** The os. */ private OutputStream os = null; /** The started. */ private boolean started = false; /** The id. */ private String id = ""; //$NON-NLS-1$ /** The header. */ private StringBuffer header; /** The end header. */ private boolean endHeader = false; /** The write source. */ private boolean writeSource = false; /** The has tu tag. */ private boolean hasTuTag = false; /** The pre seg id. */ private String preSegID = ""; //$NON-NLS-1$ // 计算替换进度的对象 private CalculateProcessedBytes cpb; // 替换过程的进度监视器 private IProgressMonitor replaceMonitor; private boolean isPreviewMode; /** 这是进度条的前进间隔,也就是当循环多少个trans-unit节点后前进一格,针对匹配 */ private int workInterval = 1; /** 骨架文件的解析游标 */ private VTDNav outputVN; /** 骨架文件的修改类实例 */ private XMLModifier outputXM; /** 骨架文件的查询实例 */ private AutoPilot outputAP; /** xliff文件的解析游标 */ private VTDNav xlfVN; /** 全局变量 */ private List<CommentBean> fileCommentsList = new LinkedList<CommentBean>(); /** 这是map对象是存储的要添加的批注,key为要添加的批注的ID, */ private Map<String, List<CommentBean>> commentMap = new HashMap<String, List<CommentBean>>(); public Map<String, String> run(Map<String, String> params, IProgressMonitor monitor) throws ConverterException { monitor = Progress.getMonitor(monitor); IProgressMonitor subMonitor = null; // 把转换过程分为两大部分共 10 个任务,其中加载 xliff 文件占 4,替换过程占 6。 monitor.beginTask("Converting...", 10); Map<String, String> result = new HashMap<String, String>(); String sklFile = params.get(Converter.ATTR_SKELETON_FILE); String xliffFile = params.get(Converter.ATTR_XLIFF_FILE); encoding = params.get(Converter.ATTR_SOURCE_ENCODING); outputFile = params.get(Converter.ATTR_TARGET_FILE); try { //先将骨架文件的内容拷贝到目标文件,再解析目标文件 copyFile(sklFile, outputFile); parseOutputFile(outputFile, xliffFile); parseXlfFile(xliffFile); if (monitor.isCanceled()) { throw new OperationCanceledException(); } monitor.worked(1); subMonitor = new SubProgressMonitor(monitor, 9); ananysisXlfTU(subMonitor); subMonitor.done(); //生成批注节点 createComments(); outputXM.output(outputFile); } catch (Exception e) { e.printStackTrace(); String errorTip = "XLIFF 转换成 trados 2009 双语文件失败!" + "\n" + e.getMessage(); ConverterUtils.throwConverterException(Activator.PLUGIN_ID, errorTip, e); }finally{ if (subMonitor != null) { subMonitor.done(); } monitor.done(); } return result; } /** * 解析结果文件(解析时这个结果文件还是一个骨架文件) * @param file * @throws Exception */ private void parseOutputFile(String file, String xliffFile) throws Exception { VTDGen vg = new VTDGen(); if (vg.parseFile(file, true)) { outputVN = vg.getNav(); outputXM = new XMLModifier(outputVN); outputAP = new AutoPilot(outputVN); outputAP.declareXPathNameSpace("sdl", "http://sdl.com/FileTypes/SdlXliff/1.0"); }else { String errorInfo = MessageFormat.format(Messages.getString("sdl.parse.msg2"), new Object[]{new File(xliffFile).getName()}); throw new Exception(errorInfo); } } /** * 解析要被逆转换的xliff文件 * @param xliffFile * @throws Exception */ private void parseXlfFile(String xliffFile) throws Exception { VTDGen vg = new VTDGen(); if (vg.parseFile(xliffFile, true)) { xlfVN = vg.getNav(); }else { String errorInfo = MessageFormat.format(Messages.getString("sdl.parse.msg1"), new Object[]{new File(xliffFile).getName()}); throw new Exception(errorInfo); } } /** * 分析xliff文件的每一个 trans-unit 节点 * @throws Exception */ private void ananysisXlfTU(IProgressMonitor monitor) throws Exception { if (monitor == null) { monitor = new NullProgressMonitor(); } AutoPilot ap = new AutoPilot(xlfVN); AutoPilot childAP = new AutoPilot(xlfVN); VTDUtils vu = new VTDUtils(xlfVN); String xpath = "count(/xliff/file/body//trans-unit)"; ap.selectXPath(xpath); int totalTuNum = (int)ap.evalXPathToNumber(); if (totalTuNum > 500) { workInterval = totalTuNum / 500; } int matchWorkUnit = totalTuNum % workInterval == 0 ? (totalTuNum / workInterval) : (totalTuNum / workInterval) + 1; monitor.beginTask("", matchWorkUnit); xpath = "/xliff/file/body//trans-unit"; String srcXpath = "./source"; String tgtXpath = "./target"; ap.selectXPath(xpath); int attrIdx = -1; //trans-unit的id,对应sdl文件的占位符如%%%1%%% 。 String segId = ""; TuMrkBean srcBean = null; TuMrkBean tgtBean = null; int traversalTuIndex = 0; while (ap.evalXPath() != -1) { traversalTuIndex ++; if ((attrIdx = xlfVN.getAttrVal("id")) == -1) { continue; } srcBean = new TuMrkBean(); tgtBean = new TuMrkBean(); segId = xlfVN.toString(attrIdx); //处理source节点 xlfVN.push(); childAP.selectXPath(srcXpath); if (childAP.evalXPath() != -1) { String srcContent = vu.getElementContent(); srcContent = srcContent == null ? "" : srcContent; srcBean.setContent(srcContent); srcBean.setSource(true); } xlfVN.pop(); //处理target节点 String status = ""; //状态,针对target节点,空字符串为未翻译 xlfVN.push(); tgtBean.setSource(false); String tgtContent = null; childAP.selectXPath(tgtXpath); if (childAP.evalXPath() != -1) { tgtContent = vu.getElementContent(); if ((attrIdx = xlfVN.getAttrVal("state")) != -1) { status = xlfVN.toString(attrIdx); } } tgtContent = tgtContent == null ? "" : tgtContent; tgtBean.setContent(tgtContent); xlfVN.pop(); //处理批注 getNotes(xlfVN, tgtBean); //判断是否处于锁定状态 if ((attrIdx = xlfVN.getAttrVal("translate")) != -1) { if ("no".equalsIgnoreCase(xlfVN.toString(attrIdx))) { tgtBean.setLocked(true); } } //判断是否处于批准状态,若是签发,就没有必要判断了,因为签发了的一定就批准了的 if (!"signed-off".equalsIgnoreCase(status)) { if ((attrIdx = xlfVN.getAttrVal("approved")) != -1) { if ("yes".equalsIgnoreCase(xlfVN.toString(attrIdx))) { status = "approved"; //批准 } } } tgtBean.setStatus(status); replaceSegment(segId, srcBean, tgtBean); monitorWork(monitor, traversalTuIndex, false); } monitorWork(monitor, traversalTuIndex, true); } /** * 获取 R8 xliff文件的所有批注信息 * @param vn * @param tgtbeBean */ private void getNotes(VTDNav vn, TuMrkBean tgtbeBean) throws Exception { vn.push(); List<CommentBean> segCommentList = new LinkedList<CommentBean>(); AutoPilot ap = new AutoPilot(vn); String xpath = "./note"; ap.selectXPath(xpath); int atttIdx = -1; CommentBean bean; while(ap.evalXPath() != -1){ boolean isCurrent = true; if ((atttIdx = vn.getAttrVal("hs:apply-current")) != -1) { if ("no".equalsIgnoreCase(vn.toString(atttIdx))) { isCurrent = false; } } String user = ""; String date = ""; String commentText = ""; //R8 xliff 文件中没有提示级别一属性,故此处皆为供参考 String severity = "Low"; if ((atttIdx = vn.getAttrVal("from")) != -1) { user = vn.toString(atttIdx); } if (vn.getText() != -1) { String r8NoteText = vn.toString(vn.getText()); if (r8NoteText.indexOf(":") != -1) { date = r8NoteText.substring(0, r8NoteText.indexOf(":")); commentText = r8NoteText.substring(r8NoteText.indexOf(":") + 1, r8NoteText.length()); }else { commentText = r8NoteText; } } bean = new CommentBean(user, date, severity, commentText, true); if (isCurrent) { segCommentList.add(new CommentBean(user, date, severity, commentText, true)); }else { if (!fileCommentsList.contains(bean)) { fileCommentsList.add(bean); } } } tgtbeBean.setCommentList(segCommentList); vn.pop(); } /** * 替换掉骨架文件中的占位符 * @param segId * @param srcBean * @param tgtbeBean */ private void replaceSegment(String segId, TuMrkBean srcBean, TuMrkBean tgtbeBean) throws Exception { String segStr = "%%%" + segId + "%%%"; String srcXpath = "/xliff/file/body//trans-unit/seg-source//mrk[text()='" + segStr + "']"; //先处理源文 outputAP.selectXPath(srcXpath); if (outputAP.evalXPath() != -1) { int textIdx = outputVN.getText(); outputXM.updateToken(textIdx, srcBean.getContent().getBytes("utf-8")); } //处理译文 String tgtXpath = "/xliff/file/body//trans-unit/target//mrk[text()='" + segStr + "']"; outputAP.selectXPath(tgtXpath); if (outputAP.evalXPath() != -1) { String content = tgtbeBean.getContent(); if (tgtbeBean.getCommentList().size() > 0) { String uuId = CommonFunction.createUUID(); commentMap.put(uuId, tgtbeBean.getCommentList()); content = "<mrk mtype=\"x-sdl-comment\" sdl:cid=\"" + uuId + "\">" + tgtbeBean.getContent() + "</mrk>"; } int textIdx = outputVN.getText(); outputXM.updateToken(textIdx, content.getBytes("utf-8")); //开始处理状态 int attrIdx = -1; if ((attrIdx = outputVN.getAttrVal("mid"))!= -1) { boolean needLocked = false; String mid = outputVN.toString(attrIdx); //下面根据mid找到对应的sdl:seg节点,这个节点里面存放的有每个文本段的状态 String xpath = "ancestor::trans-unit/sdl:seg-defs/sdl:seg[@id='" + mid + "']"; outputAP.selectXPath(xpath); if (outputAP.evalXPath() != -1) { //先判断是否锁定 if (tgtbeBean.isLocked()) { if ((attrIdx = outputVN.getAttrVal("locked")) != -1) { if (!"true".equals(outputVN.toString(attrIdx))) { outputXM.updateToken(attrIdx, "true"); } }else { needLocked = true; } }else { if ((attrIdx = outputVN.getAttrVal("locked")) != -1) { if ("true".equals(outputVN.toString(attrIdx))) { outputXM.updateToken(attrIdx, "false"); } } } //下面根据R8的状态。修改sdl的状态。 String conf = ""; String status = tgtbeBean.getStatus(); if ("new".equals(status)) { conf = "Draft"; }else if ("translated".equals(status)) { conf = "Translated"; }else if ("approved".equals(status)) { conf = "ApprovedTranslation"; }else if ("signed-off".equals(status)) { conf = "ApprovedSignOff"; } if ("".equals(conf)) { if ((attrIdx = outputVN.getAttrVal("conf")) != -1) { outputXM.updateToken(attrIdx, ""); } }else { if ((attrIdx = outputVN.getAttrVal("conf")) != -1) { if (!conf.equals(outputVN.toString(attrIdx))) { outputXM.updateToken(attrIdx, conf); } }else { String attributeStr = ""; if (needLocked) { attributeStr = " locked=\"true\" "; } attributeStr += " conf=\"" + conf + "\" "; outputXM.insertAttribute(attributeStr.getBytes("utf-8")); needLocked = false; } } if (needLocked) { outputXM.insertAttribute(" locked=\"true\" ".getBytes("utf-8")); } } } } } /** * 创建所有批注节点 * @throws Exception */ private void createComments() throws Exception { String xpath = ""; //先生成全局批注的定义节点 if (fileCommentsList.size() > 0) { String fileCommentId = CommonFunction.createUUID(); String fileCommentStr = "<sdl:cmt id=\"" + fileCommentId + "\" />"; xpath = "/xliff/file/header"; outputAP.selectXPath(xpath); while(outputAP.evalXPath() != -1){ outputXM.insertBeforeTail(fileCommentStr.getBytes("utf-8")); commentMap.put(fileCommentId, fileCommentsList); } } //开始生成Comments节点 if (commentMap.size() == 0) { return; } xpath = "/xliff/doc-info"; outputAP.selectXPath(xpath); if (outputAP.evalXPath() != -1) { StringBuffer commentSB = new StringBuffer(); commentSB.append("<cmt-defs>"); for (Entry<String, List<CommentBean>> entry : commentMap.entrySet()) { String id = entry.getKey(); commentSB.append("<cmt-def id=\""+ id +"\">"); commentSB.append("<Comments xmlns=\"\">"); for(CommentBean bean : entry.getValue()){ commentSB.append("<Comment severity=\"" + bean.getSeverity() + "\" " + "user=\"" + bean.getUser() + "\" date=\"" + bean.getDate() + "\" version=\"1.0\">" + bean.getCommentText() + "</Comment>"); } commentSB.append("</Comments>"); commentSB.append("</cmt-def>"); } commentSB.append("</cmt-defs>"); outputXM.insertBeforeTail(commentSB.toString().getBytes("utf-8")); } } private boolean monitorWork(IProgressMonitor monitor, int traversalTuIndex, boolean last){ if (last) { if (traversalTuIndex % workInterval != 0) { if (monitor.isCanceled()) { return false; } monitor.worked(1); } }else { if (traversalTuIndex % workInterval == 0) { if (monitor.isCanceled()) { return false; } monitor.worked(1); } } return true; } } //----------------------------------------------------Xliff2SdlImpl 结束标志--------------------------------------------// /** * 将一个文件的数据复制到另一个文件 * @param in * @param out * @throws Exception */ private static void copyFile(String in, String out) throws Exception { FileInputStream fis = new FileInputStream(in); FileOutputStream fos = new FileOutputStream(out); byte[] buf = new byte[1024]; int i = 0; while ((i = fis.read(buf)) != -1) { fos.write(buf, 0, i); } fis.close(); fos.close(); } public static void main(String[] args) { } }
17,129
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
Messages.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.trados2009/src/net/heartsome/cat/converter/trados2009/resource/Messages.java
/** * Messages.java * * Version information : * * Date:Jan 14, 2010 * * Copyright notice : */ package net.heartsome.cat.converter.trados2009.resource; import java.util.MissingResourceException; import java.util.ResourceBundle; /** * The Class Messages. * @author John Zhu * @version * @since JDK1.6 */ public final class Messages { /** The Constant BUNDLE_NAME. */ private static final String BUNDLE_NAME = "net.heartsome.cat.converter.trados2009.resource.sdl"; //$NON-NLS-1$ /** The Constant RESOURCE_BUNDLE. */ private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle.getBundle(BUNDLE_NAME); /** * Instantiates a new messages. */ private Messages() { // Do nothing } /** * Gets the string. * @param key * the key * @return the string */ public static String getString(String key) { try { return RESOURCE_BUNDLE.getString(key); } catch (MissingResourceException e) { return '!' + key + '!'; } } }
1,027
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
Text2XliffTest.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.text/testSrc/net/heartsome/cat/converter/text/test/Text2XliffTest.java
package net.heartsome.cat.converter.text.test; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.io.File; import java.util.HashMap; import java.util.Map; import net.heartsome.cat.converter.Converter; import net.heartsome.cat.converter.ConverterException; import net.heartsome.cat.converter.text.Text2Xliff; import org.junit.AfterClass; import org.junit.Before; import org.junit.Test; public class Text2XliffTest { private static Text2Xliff converter = new Text2Xliff(); private static String srcFile = "rc/Test.txt"; private static String sklFile = "rc/Test.txt.skl"; private static String xlfFile = "rc/Test.txt.xlf"; @Before public void setUp() { File skl = new File(sklFile); if (skl.exists()) { skl.delete(); } File xlf = new File(xlfFile); if (xlf.exists()) { xlf.delete(); } } @Test(expected = ConverterException.class) public void testConvertMissingCatalog() throws ConverterException { String rootFolder = "/data/john/Workspaces/CAT/HSTS7/"; Map<String, String> args = new HashMap<String, String>(); args.put(Converter.ATTR_SOURCE_FILE, srcFile); //$NON-NLS-1$ args.put(Converter.ATTR_XLIFF_FILE, xlfFile); //$NON-NLS-1$ args.put(Converter.ATTR_SKELETON_FILE, sklFile); //$NON-NLS-1$ args.put(Converter.ATTR_SOURCE_LANGUAGE, "en-US"); //$NON-NLS-1$ args.put(Converter.ATTR_SOURCE_ENCODING, "UTF-8"); //$NON-NLS-1$ // args.put(Converter.ATTR_CATALOGUE, rootFolder + // "catalogue/catalogue.xml"); args.put(Converter.ATTR_SRX, rootFolder + "srx/default_rules.srx"); Map<String, String> result = converter.convert(args, null); String xliff = result.get(Converter.ATTR_XLIFF_FILE); assertNotNull(xliff); File xlfFile = new File(xliff); assertNotNull(xlfFile); assertTrue(xlfFile.exists()); } @Test(expected = ConverterException.class) public void testConvertMissingSRX() throws ConverterException { String rootFolder = "/data/john/Workspaces/CAT/HSTS7/"; Map<String, String> args = new HashMap<String, String>(); args.put(Converter.ATTR_SOURCE_FILE, srcFile); //$NON-NLS-1$ args.put(Converter.ATTR_XLIFF_FILE, xlfFile); //$NON-NLS-1$ args.put(Converter.ATTR_SKELETON_FILE, sklFile); //$NON-NLS-1$ args.put(Converter.ATTR_SOURCE_LANGUAGE, "en-US"); //$NON-NLS-1$ args.put(Converter.ATTR_SOURCE_ENCODING, "UTF-8"); //$NON-NLS-1$ args.put(Converter.ATTR_CATALOGUE, rootFolder + "catalogue/catalogue.xml"); // args.put(Converter.ATTR_SRX, rootFolder + "srx/default_rules.srx"); Map<String, String> result = converter.convert(args, null); String xliff = result.get(Converter.ATTR_XLIFF_FILE); assertNotNull(xliff); File xlfFile = new File(xliff); assertNotNull(xlfFile); assertTrue(xlfFile.exists()); } @AfterClass public static void testConvert() throws ConverterException { String rootFolder = "/data/john/Workspaces/CAT/HSTS7/"; Map<String, String> args = new HashMap<String, String>(); args.put(Converter.ATTR_SOURCE_FILE, srcFile); //$NON-NLS-1$ args.put(Converter.ATTR_XLIFF_FILE, xlfFile); //$NON-NLS-1$ args.put(Converter.ATTR_SKELETON_FILE, sklFile); //$NON-NLS-1$ args.put(Converter.ATTR_SOURCE_LANGUAGE, "en-US"); //$NON-NLS-1$ args.put(Converter.ATTR_SOURCE_ENCODING, "UTF-8"); //$NON-NLS-1$ args.put(Converter.ATTR_CATALOGUE, rootFolder + "catalogue/catalogue.xml"); args.put(Converter.ATTR_SRX, rootFolder + "srx/default_rules.srx"); Map<String, String> result = converter.convert(args, null); String xliff = result.get(Converter.ATTR_XLIFF_FILE); assertNotNull(xliff); File xlfFile = new File(xliff); assertNotNull(xlfFile); assertTrue(xlfFile.exists()); } }
3,675
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
Xliff2TextTest.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.text/testSrc/net/heartsome/cat/converter/text/test/Xliff2TextTest.java
package net.heartsome.cat.converter.text.test; import static org.junit.Assert.*; import java.io.File; import java.util.HashMap; import java.util.Map; import net.heartsome.cat.converter.Converter; import net.heartsome.cat.converter.ConverterException; import net.heartsome.cat.converter.text.Xliff2Text; import org.junit.Before; import org.junit.Test; public class Xliff2TextTest { public static Xliff2Text converter = new Xliff2Text(); private static String tgtFile = "rc/Test_zh-CN.txt"; private static String sklFile = "rc/Test.txt.skl"; private static String xlfFile = "rc/Test.txt.xlf"; @Before public void setUp(){ File tgt = new File(tgtFile); if(tgt.exists()){ tgt.delete(); } } @Test public void testConvert() throws ConverterException { String rootFolder = "/data/john/Workspaces/CAT/HSTS7/"; Map<String, String> args = new HashMap<String, String>(); args.put(Converter.ATTR_TARGET_FILE, tgtFile); //$NON-NLS-1$ args.put(Converter.ATTR_XLIFF_FILE, xlfFile); //$NON-NLS-1$ args.put(Converter.ATTR_SKELETON_FILE, sklFile); //$NON-NLS-1$ // args.put(Converter.ATTR_SOURCE_LANGUAGE, "en-US"); //$NON-NLS-1$ args.put(Converter.ATTR_SOURCE_ENCODING, "UTF-8"); //$NON-NLS-1$ args.put(Converter.ATTR_CATALOGUE, rootFolder + "catalogue/catalogue.xml"); // args.put(Converter.ATTR_SRX, rootFolder + "srx/default_rules.srx"); Map<String, String> result = converter.convert(args, null); String target = result.get(Converter.ATTR_TARGET_FILE); assertNotNull(target); File tgtFile = new File(target); assertNotNull(tgtFile); assertTrue(tgtFile.exists()); } }
1,619
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
Activator.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.text/src/net/heartsome/cat/converter/text/Activator.java
/** * Activator.java * * Version information : * * Date:Jan 14, 2010 * * Copyright notice : */ package net.heartsome.cat.converter.text; import java.util.Properties; import net.heartsome.cat.converter.Converter; import net.heartsome.cat.converter.util.ConverterRegister; import org.osgi.framework.BundleActivator; import org.osgi.framework.BundleContext; import org.osgi.framework.ServiceRegistration; /** * The Class Activator.The activator class controls the plug-in life cycle. * @author John Zhu * @version * @since JDK1.6 */ public class Activator implements BundleActivator { /** The Constant PLUGIN_ID. */ public static final String PLUGIN_ID = "net.heartsome.cat.converter.text"; // The shared instance /** The plugin. */ private static Activator plugin; /** The text2 xliff sr. */ private ServiceRegistration text2XliffSR; /** The xliff2 text sr. */ private ServiceRegistration xliff2TextSR; /** * The constructor. */ public Activator() { } /** * (non-Javadoc) * @see org.osgi.framework.BundleActivator#start(org.osgi.framework.BundleContext) * @param context * @throws Exception */ public void start(BundleContext context) throws Exception { plugin = this; // register the convert service Converter text2Xliff = new Text2Xliff(); Properties properties = new Properties(); properties.put(Converter.ATTR_NAME, Text2Xliff.NAME_VALUE); properties.put(Converter.ATTR_TYPE, Text2Xliff.TYPE_VALUE); properties.put(Converter.ATTR_TYPE_NAME, Text2Xliff.TYPE_NAME_VALUE); text2XliffSR = ConverterRegister.registerPositiveConverter(context, text2Xliff, properties); Converter xliff2Text = new Xliff2Text(); properties = new Properties(); properties.put(Converter.ATTR_NAME, Xliff2Text.NAME_VALUE); properties.put(Converter.ATTR_TYPE, Xliff2Text.TYPE_VALUE); properties.put(Converter.ATTR_TYPE_NAME, Xliff2Text.TYPE_NAME_VALUE); xliff2TextSR = ConverterRegister.registerReverseConverter(context, xliff2Text, properties); } /** * (non-Javadoc) * @see org.osgi.framework.BundleActivator#stop(org.osgi.framework.BundleContext) * @param context * @throws Exception */ public void stop(BundleContext context) throws Exception { if (text2XliffSR != null) { text2XliffSR.unregister(); } if (xliff2TextSR != null) { xliff2TextSR.unregister(); } plugin = null; } /** * Returns the shared instance. * @return the shared instance */ public static Activator getDefault() { return plugin; } }
2,502
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
Text2Xliff.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.text/src/net/heartsome/cat/converter/text/Text2Xliff.java
/** * Text2Xliff.java * * Version information : * * Date:Jan 14, 2010 * * Copyright notice : */ package net.heartsome.cat.converter.text; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.text.MessageFormat; import java.util.HashMap; import java.util.Map; import net.heartsome.cat.converter.Converter; import net.heartsome.cat.converter.ConverterException; import net.heartsome.cat.converter.StringSegmenter; import net.heartsome.cat.converter.text.resource.Messages; import net.heartsome.cat.converter.util.CalculateProcessedBytes; import net.heartsome.cat.converter.util.ConverterUtils; import net.heartsome.cat.converter.util.Progress; import net.heartsome.util.CRC16; import net.heartsome.util.TextUtil; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.OperationCanceledException; /** * The Class Text2Xliff. * @author John Zhu */ public class Text2Xliff implements Converter { /** The Constant TYPE_VALUE. */ public static final String TYPE_VALUE = "plaintext"; /** The Constant TYPE_NAME_VALUE. */ public static final String TYPE_NAME_VALUE = Messages.getString("text.TYPE_NAME_VALUE"); /** The Constant NAME_VALUE. */ public static final String NAME_VALUE = "Text to XLIFF Conveter"; /** * (non-Javadoc) * @see net.heartsome.cat.converter.Converter#convert(java.util.Map, org.eclipse.core.runtime.IProgressMonitor) * @param args * @param monitor * @return * @throws ConverterException */ public Map<String, String> convert(Map<String, String> args, IProgressMonitor monitor) throws ConverterException { Text2XliffImpl converter = new Text2XliffImpl(); return converter.run(args, monitor); } /** * (non-Javadoc) * @see net.heartsome.cat.converter.Converter#getName() * @return */ public String getName() { return NAME_VALUE; } /** * (non-Javadoc) * @see net.heartsome.cat.converter.Converter#getType() * @return */ public String getType() { return TYPE_VALUE; } /** * (non-Javadoc) * @see net.heartsome.cat.converter.Converter#getTypeName() * @return */ public String getTypeName() { return TYPE_NAME_VALUE; } /** * The Class Text2XliffImpl. * @author John Zhu * @version * @since JDK1.6 */ class Text2XliffImpl { /** The input. */ private InputStreamReader input; /** The output. */ private FileOutputStream output; /** The skeleton. */ private FileOutputStream skeleton; /** The buffer. */ private BufferedReader buffer; /** The input file. */ private String inputFile; /** The xliff file. */ private String xliffFile; /** The skeleton file. */ private String skeletonFile; /** The source. */ private String source; /** The source language. */ private String sourceLanguage; private String targetLanguage; /** The seg id. */ private int segId; /** The segmenter. */ private StringSegmenter segmenter; /** The seg by element. */ private boolean segByElement; /** * Write string. * @param string * the string * @throws IOException * Signals that an I/O exception has occurred. */ private void writeString(String string) throws IOException { output.write(string.getBytes("UTF-8")); //$NON-NLS-1$ } /** * Write skeleton. * @param string * the string * @throws IOException * Signals that an I/O exception has occurred. */ private void writeSkeleton(String string) throws IOException { skeleton.write(string.getBytes("UTF-8")); //$NON-NLS-1$ } /** * Write segment. * @throws IOException * Signals that an I/O exception has occurred. */ private void writeSegment() throws IOException { String[] segments; if (!segByElement) { segments = segmenter.segment(source); } else { segments = new String[1]; segments[0] = source; } for (int i = 0; i < segments.length; i++) { if (TextUtil.cleanString(segments[i]).trim().equals("")) { //$NON-NLS-1$ writeSkeleton(segments[i]); } else { writeString(" <trans-unit id=\"" + segId //$NON-NLS-1$ + "\" xml:space=\"preserve\" approved=\"no\">\n" //$NON-NLS-1$ + " <source xml:lang=\"" + sourceLanguage + "\">" //$NON-NLS-1$ //$NON-NLS-2$ + TextUtil.cleanString(segments[i]) + "</source>\n"); //$NON-NLS-1$ writeString(" </trans-unit>\n"); //$NON-NLS-1$ writeSkeleton("%%%" + segId++ + "%%%"); //$NON-NLS-1$ //$NON-NLS-2$ } } if (segments.length > 0) { writeSkeleton("\n"); } source = ""; //$NON-NLS-1$ } /** * Run. * @param args * the args * @param monitor * the monitor * @return the map< string, string> * @throws ConverterException * the converter exception */ Map<String, String> run(Map<String, String> args, IProgressMonitor monitor) throws ConverterException { monitor = Progress.getMonitor(monitor); inputFile = args.get(Converter.ATTR_SOURCE_FILE); File temp = new File(inputFile); long totalSize = 0; if (temp.exists()) { totalSize = temp.length(); } // BUG 2761 robert 2012-10-31 if (totalSize <= 0 ) { String errorTip = MessageFormat.format(Messages.getString("text.Text2Xliff.addTip1"), temp.getName()); ConverterUtils.throwConverterException(Activator.PLUGIN_ID, errorTip, null); } CalculateProcessedBytes cpb = ConverterUtils.getCalculateProcessedBytes(totalSize); monitor.beginTask(Messages.getString("text.Text2Xliff.task1"), cpb.getTotalTask()); monitor.subTask(""); Map<String, String> result = new HashMap<String, String>(); try { segId = 0; xliffFile = args.get(Converter.ATTR_XLIFF_FILE); skeletonFile = args.get(Converter.ATTR_SKELETON_FILE); sourceLanguage = args.get(Converter.ATTR_SOURCE_LANGUAGE); targetLanguage = args.get(Converter.ATTR_TARGET_LANGUAGE); String srcEncoding = args.get(Converter.ATTR_SOURCE_ENCODING); String catalogue = args.get(Converter.ATTR_CATALOGUE); String elementSegmentation = args.get(Converter.ATTR_SEG_BY_ELEMENT); boolean isSuite = false; if (Converter.TRUE.equalsIgnoreCase(args.get(Converter.ATTR_IS_SUITE))) { isSuite = true; } String qtToolID = args.get(Converter.ATTR_QT_TOOLID) != null ? args.get(Converter.ATTR_QT_TOOLID) : Converter.QT_TOOLID_DEFAULT_VALUE; // fixed bug 479 by john. // boolean breakOnCRLF = "yes".equals(params.get("breakOnCRLF")); //$NON-NLS-1$ //$NON-NLS-2$ if (elementSegmentation == null) { segByElement = false; } else { if (elementSegmentation.equals(Converter.TRUE)) { segByElement = true; } else { segByElement = false; } } source = ""; //$NON-NLS-1$ try { if (!segByElement) { String initSegmenter = args.get(Converter.ATTR_SRX); segmenter = new StringSegmenter(initSegmenter, sourceLanguage, catalogue); } FileInputStream stream = new FileInputStream(inputFile); input = new InputStreamReader(stream, srcEncoding); buffer = new BufferedReader(input); output = new FileOutputStream(xliffFile); writeString("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"); //$NON-NLS-1$ writeString("<xliff version=\"1.2\" xmlns=\"urn:oasis:names:tc:xliff:document:1.2\" " + //$NON-NLS-1$ "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" " + "xmlns:hs=\"" + Converter.HSNAMESPACE + "\" " + //$NON-NLS-1$ "xsi:schemaLocation=\"urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd " //$NON-NLS-1$ + Converter.HSSCHEMALOCATION + "\">\n"); //$NON-NLS-1$ if (!"".equals(targetLanguage)) { writeString("<file original=\"" + inputFile //$NON-NLS-1$ + "\" source-language=\"" + sourceLanguage //$NON-NLS-1$ + "\" target-language=\"" + targetLanguage + "\" datatype=\"" + TYPE_VALUE + "\">\n"); //$NON-NLS-1$ } else { writeString("<file original=\"" + inputFile //$NON-NLS-1$ + "\" source-language=\"" + sourceLanguage //$NON-NLS-1$ + "\" datatype=\"" + TYPE_VALUE + "\">\n"); //$NON-NLS-1$ } writeString("<header>\n"); //$NON-NLS-1$ writeString(" <skl>\n"); //$NON-NLS-1$ String crc = ""; //$NON-NLS-1$ if (isSuite) { crc = "crc=\"" + CRC16.crc16(TextUtil.cleanString(skeletonFile).getBytes("UTF-8")) + "\""; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } writeString(" <external-file href=\"" + TextUtil.cleanString(skeletonFile) + "\" " + crc + "/>\n"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ writeString(" </skl>\n"); //$NON-NLS-1$ writeString(" <tool tool-id=\"" + qtToolID + "\" tool-name=\"HSStudio\"/>\n"); //$NON-NLS-1$ //$NON-NLS-2$ writeString(" <hs:prop-group name=\"encoding\"><hs:prop prop-type=\"encoding\">" + srcEncoding //$NON-NLS-1$ + "</hs:prop></hs:prop-group>\n"); //$NON-NLS-1$ writeString("</header>\n"); //$NON-NLS-1$ writeString("<body>\n"); //$NON-NLS-1$ skeleton = new FileOutputStream(skeletonFile); // fixed bug 479 by john. // remarked breakOnCRLF validation. used the same implements // with // breakOnCRLF is true. // if (breakOnCRLF) { // Fixed a bug 1609 by John. while ((source = buffer.readLine()) != null) { int size = source.getBytes(srcEncoding).length; if (source.trim().length() == 0) { writeSkeleton(source + "\n"); //$NON-NLS-1$ } else { writeSegment(); } if (monitor.isCanceled()) { throw new OperationCanceledException(Messages.getString("text.Text2Xliff.msg1")); } if (size > 0) { // 考虑加上换行符的一个字节数 int workedTask = cpb.calculateProcessed(size + 1); if (workedTask > 0) { monitor.worked(workedTask); } } // source = buffer.readLine(); } // } else { // String line = changeEncoding(buffer.readLine(), srcEncoding); // while (line != null) { // line = line + "\n"; //$NON-NLS-1$ // // if (line.trim().length() == 0) { // // no text in this line // // segment separator // writeSkeleton(line); // } else { // while (line != null && line.trim().length() != 0) { // source = source + line; // line = changeEncoding(buffer.readLine(), srcEncoding); // if (line != null) { // line = line + "\n"; //$NON-NLS-1$ // } // } // writeSegment(); // } // line = changeEncoding(buffer.readLine(), srcEncoding); // } // } skeleton.close(); writeString("</body>\n"); //$NON-NLS-1$ writeString("</file>\n"); //$NON-NLS-1$ writeString("</xliff>"); //$NON-NLS-1$ input.close(); output.close(); result.put(Converter.ATTR_XLIFF_FILE, xliffFile); } catch (OperationCanceledException e) { throw e; } catch (Exception e) { if (Converter.DEBUG_MODE) { e.printStackTrace(); } ConverterUtils.throwConverterException(Activator.PLUGIN_ID, Messages.getString("text.Text2Xliff.msg2"), e); } } finally { monitor.done(); } return result; } } }
11,339
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
Xliff2Text.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.text/src/net/heartsome/cat/converter/text/Xliff2Text.java
/** * Xliff2Text.java * * Version information : * * Date:Jan 14, 2010 * * Copyright notice : */ package net.heartsome.cat.converter.text; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.text.MessageFormat; import java.util.HashMap; import java.util.Hashtable; import java.util.Iterator; import java.util.List; import java.util.Map; import net.heartsome.cat.converter.Converter; import net.heartsome.cat.converter.ConverterException; import net.heartsome.cat.converter.text.resource.Messages; import net.heartsome.cat.converter.util.CalculateProcessedBytes; import net.heartsome.cat.converter.util.ConverterUtils; import net.heartsome.cat.converter.util.Progress; import net.heartsome.cat.converter.util.ReverseConversionInfoLogRecord; import net.heartsome.xml.Catalogue; import net.heartsome.xml.Document; import net.heartsome.xml.Element; import net.heartsome.xml.SAXBuilder; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.OperationCanceledException; import org.w3c.dom.Node; import org.xml.sax.SAXException; /** * The Class Xliff2Text. * @author John Zhu */ public class Xliff2Text implements Converter { /** The Constant TYPE_VALUE. */ public static final String TYPE_VALUE = "plaintext"; /** The Constant TYPE_NAME_VALUE. */ public static final String TYPE_NAME_VALUE = Messages.getString("text.TYPE_NAME_VALUE"); /** The Constant NAME_VALUE. */ public static final String NAME_VALUE = "XLIFF to Text Conveter"; /** * (non-Javadoc) * @see net.heartsome.cat.converter.Converter#convert(java.util.Map, org.eclipse.core.runtime.IProgressMonitor) * @param args * @param monitor * @return * @throws ConverterException */ public Map<String, String> convert(Map<String, String> args, IProgressMonitor monitor) throws ConverterException { Xliff2TextImpl converter = new Xliff2TextImpl(); return converter.run(args, monitor); } /** * (non-Javadoc) * @see net.heartsome.cat.converter.Converter#getName() * @return */ public String getName() { return NAME_VALUE; } /** * (non-Javadoc) * @see net.heartsome.cat.converter.Converter#getType() * @return */ public String getType() { return TYPE_VALUE; } /** * (non-Javadoc) * @see net.heartsome.cat.converter.Converter#getTypeName() * @return */ public String getTypeName() { return TYPE_NAME_VALUE; } /** * The Class Xliff2TextImpl. * @author John Zhu * @version * @since JDK1.6 */ class Xliff2TextImpl { private static final String UTF_8 = "UTF-8"; /** The skl file. */ private String sklFile; /** The xliff file. */ private String xliffFile; /** The encoding. */ private String encoding; /** The segments. */ private Hashtable<String, Element> segments; /** The catalogue. */ private Catalogue catalogue; /** The output. */ private FileOutputStream output; /** The input. */ private InputStreamReader input; /** The buffer. */ private BufferedReader buffer; /** The line. */ private String line; /** * Run. * @param params * the params * @param monitor * the monitor * @return the map< string, string> * @throws ConverterException * the converter exception */ public Map<String, String> run(Map<String, String> params, IProgressMonitor monitor) throws ConverterException { monitor = Progress.getMonitor(monitor); ReverseConversionInfoLogRecord infoLogger = ConverterUtils.getReverseConversionInfoLogRecord(); infoLogger.startConversion(); Map<String, String> result = new HashMap<String, String>(); sklFile = params.get(Converter.ATTR_SKELETON_FILE); xliffFile = params.get(Converter.ATTR_XLIFF_FILE); encoding = params.get(Converter.ATTR_SOURCE_ENCODING); String catalogueFile = params.get(Converter.ATTR_CATALOGUE); String attrIsPreviewMode = params.get(Converter.ATTR_IS_PREVIEW_MODE); /* 是否为预览翻译模式 */ boolean isPreviewMode = attrIsPreviewMode != null && attrIsPreviewMode.equals(Converter.TRUE); try { infoLogger.logConversionFileInfo(catalogueFile, null, xliffFile, sklFile); // 把转换过程分为三大部分共 10 个任,其中加载 catalogue 占 3,加载 xliff 文件占 3,替换占 4。 monitor.beginTask("", 10); monitor.subTask(Messages.getString("text.Xliff2Text.task2")); infoLogger.startLoadingCatalogueFile(); if (catalogueFile != null) { catalogue = new Catalogue(catalogueFile); } infoLogger.endLoadingXliffFile(); monitor.worked(3); // 是否取消 if (monitor.isCanceled()) { throw new OperationCanceledException(Messages.getString("text.cancel")); } monitor.subTask(Messages.getString("text.Xliff2Text.task3")); infoLogger.startLoadingXliffFile(); String outputFile = params.get(Converter.ATTR_TARGET_FILE); output = new FileOutputStream(outputFile); loadSegments(); infoLogger.endLoadingXliffFile(); monitor.worked(3); // 是否取消操作 if (monitor.isCanceled()) { throw new OperationCanceledException(Messages.getString("text.cancel")); } IProgressMonitor replaceMonitor = Progress.getSubMonitor(monitor, 4); try { infoLogger.startReplacingSegmentSymbol(); CalculateProcessedBytes cpb = ConverterUtils.getCalculateProcessedBytes(sklFile); replaceMonitor.beginTask(Messages.getString("text.Xliff2Text.task4"), cpb.getTotalTask()); replaceMonitor.subTask(""); input = new InputStreamReader(new FileInputStream(sklFile), UTF_8); //$NON-NLS-1$ buffer = new BufferedReader(input); line = buffer.readLine(); while (line != null) { // 是否取消操作 if (replaceMonitor.isCanceled()) { throw new OperationCanceledException(Messages.getString("text.cancel")); } cpb.calculateProcessed(replaceMonitor, line, UTF_8); line = line + "\n"; //$NON-NLS-1$ if (line.indexOf("%%%") != -1) { //$NON-NLS-1$ // // contains translatable text // int index = line.indexOf("%%%"); //$NON-NLS-1$ while (index != -1) { String start = line.substring(0, index); writeString(start); line = line.substring(index + 3); String code = line.substring(0, line.indexOf("%%%")); //$NON-NLS-1$ line = line.substring(line.indexOf("%%%") + 3); //$NON-NLS-1$ Element segment = segments.get(code); if (segment != null) { Element target = segment.getChild("target"); //$NON-NLS-1$ Element source = segment.getChild("source"); //$NON-NLS-1$ if (target != null) { String tgtStr = extractText(target); if (isPreviewMode || !"".equals(tgtStr.trim())) { if (isPreviewMode) { if ("".equals(tgtStr.trim())) { writeString(extractText(source)); } else { writeString(tgtStr); } } else { writeString(tgtStr); } } else { writeString(extractText(source)); } } else { writeString(extractText(source)); } } else { MessageFormat mf = new MessageFormat(Messages.getString("text.Xliff2Text.msg0")); //$NON-NLS-1$ Object[] args = new Object[] { code }; ConverterUtils.throwConverterException(Activator.PLUGIN_ID, mf.format(args)); } index = line.indexOf("%%%"); //$NON-NLS-1$ if (index == -1) { writeString(line); } } // end while } else { // // non translatable portion // writeString(line); } line = buffer.readLine(); } } finally { replaceMonitor.done(); } infoLogger.endReplacingSegmentSymbol(); output.close(); result.put(Converter.ATTR_TARGET_FILE, outputFile); infoLogger.endConversion(); } catch (Exception e) { if (Converter.DEBUG_MODE) { e.printStackTrace(); } ConverterUtils.throwConverterException(Activator.PLUGIN_ID, Messages.getString("text.Xliff2Text.msg1"), e); } finally { monitor.done(); } return result; } /** * Extract text. * @param target * the target * @return the string */ private String extractText(Element target) { String result = ""; //$NON-NLS-1$ List<Node> content = target.getContent(); Iterator<Node> i = content.iterator(); while (i.hasNext()) { Node n = i.next(); switch (n.getNodeType()) { case Node.ELEMENT_NODE: Element e = new Element(n); result = result + extractText(e); break; case Node.TEXT_NODE: result = result + n.getNodeValue(); break; default: break; } } return result; } /** * Load segments. * @throws SAXException * the SAX exception * @throws IOException * Signals that an I/O exception has occurred. */ private void loadSegments() throws SAXException, IOException { SAXBuilder builder = new SAXBuilder(); if (catalogue != null) { builder.setEntityResolver(catalogue); } Document doc = builder.build(xliffFile); Element root = doc.getRootElement(); Element body = root.getChild("file").getChild("body"); //$NON-NLS-1$ //$NON-NLS-2$ List<Element> units = body.getChildren("trans-unit"); //$NON-NLS-1$ Iterator<Element> i = units.iterator(); segments = new Hashtable<String, Element>(); while (i.hasNext()) { Element unit = i.next(); segments.put(unit.getAttributeValue("id"), unit); //$NON-NLS-1$ } } /** * Write string. * @param string * the string * @throws IOException * Signals that an I/O exception has occurred. */ private void writeString(String string) throws IOException { output.write((string.replaceAll("\n", System.getProperty("line.separator"))).getBytes(encoding)); } } }
10,385
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
Messages.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.text/src/net/heartsome/cat/converter/text/resource/Messages.java
/** * Messages.java * * Version information : * * Date:Jan 14, 2010 * * Copyright notice : */ package net.heartsome.cat.converter.text.resource; import java.util.MissingResourceException; import java.util.ResourceBundle; /** * The Class Messages. * @author John Zhu * @version * @since JDK1.6 */ public final class Messages { /** The Constant BUNDLE_NAME. */ private static final String BUNDLE_NAME = "net.heartsome.cat.converter.text.resource.message"; //$NON-NLS-1$ /** The Constant RESOURCE_BUNDLE. */ private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle.getBundle(BUNDLE_NAME); /** * Instantiates a new messages. */ private Messages() { } /** * Gets the string. * @param key * the key * @return the string */ public static String getString(String key) { try { return RESOURCE_BUNDLE.getString(key); } catch (MissingResourceException e) { return '!' + key + '!'; } } }
954
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
ImplementationLoader.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.ui/src/net/heartsome/cat/convert/ui/ImplementationLoader.java
package net.heartsome.cat.convert.ui; import java.text.MessageFormat; /** * 加载具体的 factory facade 实现 * @author cheney * @since JDK1.6 */ public final class ImplementationLoader { /** * */ private ImplementationLoader() { // 防止创建实例 } /** * 加载特定实现类的实例 * @param type * 特定实现类的接口类型 * @return ; */ @SuppressWarnings("unchecked") public static Object newInstance(final Class type) { String name = type.getName(); Object result = null; try { result = type.getClassLoader().loadClass(name + "Impl").newInstance(); } catch (Throwable throwable) { String txt = "Could not load implementation for {0}"; String msg = MessageFormat.format(txt, new Object[] { name }); throw new RuntimeException(msg, throwable); } return result; } }
851
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
Activator.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.ui/src/net/heartsome/cat/convert/ui/Activator.java
package net.heartsome.cat.convert.ui; import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.ui.plugin.AbstractUIPlugin; import org.osgi.framework.BundleContext; /** * The activator class controls the plug-in life cycle */ public class Activator extends AbstractUIPlugin { /** * 在执行文件转换时,是否打印转换配置信息的控制开关 */ public static final String CONVERSION_DEBUG_ON = "net.heartsome.cat.converter.ui/debug/conversion"; /** * The plug-in ID */ public static final String PLUGIN_ID = "net.heartsome.cat.convert.ui"; // The shared instance private static Activator plugin; // bundle context private static BundleContext context; /** * The constructor */ public Activator() { } /** * (non-Javadoc) * @see org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext) */ public void start(BundleContext context) throws Exception { super.start(context); Activator.context = context; plugin = this; } /** * (non-Javadoc) * @see org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext) */ public void stop(BundleContext context) throws Exception { plugin = null; Activator.context = null; super.stop(context); } /** * Returns the shared instance * @return the shared instance */ public static Activator getDefault() { return plugin; } /** * Returns an image descriptor for the image file at the given plug-in relative path * @param path * the path * @return the image descriptor */ public static ImageDescriptor getImageDescriptor(String path) { return imageDescriptorFromPlugin(PLUGIN_ID, path); } /** * 获得插件的 bundle context * @return 插件的 bundle context; */ public static BundleContext getContext() { return context; } }
1,833
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
ConversionWizardDialog.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.ui/src/net/heartsome/cat/convert/ui/wizard/ConversionWizardDialog.java
package net.heartsome.cat.convert.ui.wizard; import net.heartsome.cat.convert.ui.Activator; import org.eclipse.jface.dialogs.IDialogSettings; import org.eclipse.jface.wizard.IWizard; import org.eclipse.jface.wizard.WizardDialog; import org.eclipse.swt.widgets.Shell; /** * 继承 WizardDialog,并覆盖 getDialogBoundsSettings 方法,以记住此向导对话框上一次打开时的大小 * @author cheney * @since JDK1.6 */ public class ConversionWizardDialog extends WizardDialog { /** * 正向转换向导对话框构造函数 * @param parentShell * @param newWizard */ public ConversionWizardDialog(Shell parentShell, IWizard newWizard) { super(parentShell, newWizard); } @Override protected IDialogSettings getDialogBoundsSettings() { return Activator.getDefault().getDialogSettings(); } }
827
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
ConversionWizardPage.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.ui/src/net/heartsome/cat/convert/ui/wizard/ConversionWizardPage.java
package net.heartsome.cat.convert.ui.wizard; import java.io.IOException; import java.text.MessageFormat; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import net.heartsome.cat.common.locale.Language; import net.heartsome.cat.convert.ui.dialog.FileDialogFactoryFacade; import net.heartsome.cat.convert.ui.dialog.IConversionItemDialog; import net.heartsome.cat.convert.ui.model.ConversionConfigBean; import net.heartsome.cat.convert.ui.model.ConverterContext; import net.heartsome.cat.convert.ui.model.ConverterUtil; import net.heartsome.cat.convert.ui.model.ConverterViewModel; import net.heartsome.cat.convert.ui.model.IConversionItem; import net.heartsome.cat.convert.ui.utils.ConversionResource; import net.heartsome.cat.convert.ui.utils.EncodingResolver; import net.heartsome.cat.convert.ui.utils.FileFormatUtils; import net.heartsome.cat.converter.Converter; import net.heartsome.cat.converter.util.ConverterBean; import org.eclipse.core.databinding.DataBindingContext; import org.eclipse.core.databinding.beans.BeanProperties; import org.eclipse.core.databinding.beans.BeansObservables; import org.eclipse.core.databinding.observable.list.WritableList; import org.eclipse.core.databinding.property.value.IValueProperty; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.FileLocator; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Platform; import org.eclipse.core.runtime.Status; import org.eclipse.jface.databinding.swt.SWTObservables; import org.eclipse.jface.databinding.viewers.ViewerSupport; import org.eclipse.jface.databinding.wizard.WizardPageSupport; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.jface.layout.GridLayoutFactory; import org.eclipse.jface.layout.LayoutConstants; import org.eclipse.jface.viewers.ArrayContentProvider; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.ISelectionChangedListener; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.LabelProvider; import org.eclipse.jface.viewers.SelectionChangedEvent; import org.eclipse.jface.viewers.TableViewer; import org.eclipse.jface.viewers.TableViewerColumn; import org.eclipse.jface.wizard.WizardPage; import org.eclipse.nebula.jface.tablecomboviewer.TableComboViewer; import org.eclipse.nebula.widgets.tablecombo.TableCombo; import org.eclipse.swt.SWT; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.events.PaintEvent; import org.eclipse.swt.events.PaintListener; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.ImageData; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Combo; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Group; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Table; import org.eclipse.swt.widgets.TableColumn; import org.eclipse.swt.widgets.TableItem; import org.eclipse.swt.widgets.Text; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * 项目正向转换选项配置页 * @author weachy * @since JDK1.5 */ public class ConversionWizardPage extends WizardPage { /** 支持的类型 */ private final List<ConverterBean> supportTypes = FileFormatUtils.getSupportTypes(); private List<ConverterViewModel> converterViewModels; /** 支持的格式列表 */ private Combo formatCombo; /** 源文件编码列表 */ private Combo srcEncCombo; /** 目标语言列表 */ private TableComboViewer tgtLangComboViewer; /** 文件列表 */ private Table filesTable; private TableColumn sourceColumn; private TableColumn formatColumn; private TableColumn srcEncColumn; private TableColumn xliffColumn; /** 分段选项 */ private Text srxFile; private ArrayList<ConversionConfigBean> conversionConfigBeans; private TableViewer tableViewer; /** * 正向项目转换配置信息页的构造函数 * @param pageName */ protected ConversionWizardPage(String pageName, List<ConverterViewModel> converterViewModels, ArrayList<ConversionConfigBean> conversionConfigBeans) { super(pageName); this.converterViewModels = converterViewModels; this.conversionConfigBeans = conversionConfigBeans; setTitle(Messages.getString("ConversionWizardPage.0")); //$NON-NLS-1$ setDescription(Messages.getString("ConversionWizardPage.1")); //$NON-NLS-1$ } public void createControl(Composite parent) { Composite contents = new Composite(parent, SWT.NONE); GridLayout layout = new GridLayout(); contents.setLayout(layout); GridData gridData = new GridData(); gridData.horizontalAlignment = SWT.FILL; gridData.grabExcessHorizontalSpace = true; contents.setLayoutData(gridData); createFilesGroup(contents); // 文件列表区域 createPropertiesGroup(contents);// 源文件属性区域组 createConversionOptionsGroup(contents); // 转换选项组 createSegmentationGroup(contents); // 分段规则选择区域组 bindValue(); // 数据绑定 loadFiles(); // 加载文件列表 filesTable.select(0); // 默认选中第一行数据 filesTable.notifyListeners(SWT.Selection, null); Dialog.applyDialogFont(parent); Point defaultMargins = LayoutConstants.getMargins(); GridLayoutFactory.fillDefaults().numColumns(1).margins(defaultMargins.x, defaultMargins.y) .generateLayout(contents); setControl(contents); srxFile.setText(ConverterContext.defaultSrx); validate(); } private void createPropertiesGroup(Composite contents) { Group langComposite = new Group(contents, SWT.NONE); langComposite.setText(Messages.getString("ConversionWizardPage.2")); //$NON-NLS-1$ langComposite.setLayout(new GridLayout(2, false)); langComposite.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); Label formatLabel = new Label(langComposite, SWT.NONE); formatLabel.setText(Messages.getString("ConversionWizardPage.3")); //$NON-NLS-1$ formatCombo = new Combo(langComposite, SWT.READ_ONLY | SWT.DROP_DOWN); formatCombo.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); formatCombo.addSelectionListener(new SelectionAdapter() { @SuppressWarnings("unchecked") public void widgetSelected(SelectionEvent arg0) { ISelection selection = tableViewer.getSelection(); if (selection != null && !selection.isEmpty() && selection instanceof IStructuredSelection) { IStructuredSelection structuredSelection = (IStructuredSelection) selection; Iterator<ConversionConfigBean> iter = structuredSelection.iterator(); while (iter.hasNext()) { ConversionConfigBean bean = iter.next(); bean.setFileType(formatCombo.getText()); } String format = getSelectedFormat(formatCombo.getText()); // 得到选中的文件类型 int[] indices = filesTable.getSelectionIndices(); for (int index : indices) { converterViewModels.get(index).setSelectedType(format); String sourcePath = converterViewModels.get(index).getConversionItem().getLocation() .toOSString(); String sourceLocalPath = ConverterUtil.toLocalPath(sourcePath); String srcEncValue = EncodingResolver.getEncoding(sourceLocalPath, formatCombo.getText()); if (srcEncValue != null) { conversionConfigBeans.get(index).setSrcEncoding(srcEncValue); } } validate(); } } }); Label srcEncLabel = new Label(langComposite, SWT.NONE); srcEncLabel.setText(Messages.getString("ConversionWizardPage.4")); //$NON-NLS-1$ srcEncCombo = new Combo(langComposite, SWT.DROP_DOWN | SWT.READ_ONLY); srcEncCombo.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); srcEncCombo.addSelectionListener(new SelectionAdapter() { @SuppressWarnings("unchecked") public void widgetSelected(SelectionEvent arg0) { ISelection selection = tableViewer.getSelection(); if (selection != null && !selection.isEmpty() && selection instanceof IStructuredSelection) { IStructuredSelection structuredSelection = (IStructuredSelection) selection; Iterator<ConversionConfigBean> iter = structuredSelection.iterator(); while (iter.hasNext()) { ConversionConfigBean bean = iter.next(); bean.setSrcEncoding(srcEncCombo.getText()); } validate(); } } }); // 目标语言框不需要纳入验证,可以不选择 Label tgtLangLabel = new Label(langComposite, SWT.NONE); tgtLangLabel.setText("目标语言"); //$NON-NLS-1$ tgtLangComboViewer = new TableComboViewer(langComposite, SWT.READ_ONLY|SWT.BORDER); TableCombo tableCombo = tgtLangComboViewer.getTableCombo(); // set options. tableCombo.setShowTableLines(false); tableCombo.setShowTableHeader(false); tableCombo.setDisplayColumnIndex(-1); tableCombo.setShowImageWithinSelection(true); tableCombo.setShowColorWithinSelection(false); tableCombo.setShowFontWithinSelection(false); tableCombo.setVisibleItemCount(20); tableCombo.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); tgtLangComboViewer.setLabelProvider(new LanguageLabelProvider(getShell())); tgtLangComboViewer.setContentProvider(new ArrayContentProvider()); tgtLangComboViewer.setInput(conversionConfigBeans.get(0).getTgtLangList()); tgtLangComboViewer.addSelectionChangedListener(new ISelectionChangedListener() { public void selectionChanged(SelectionChangedEvent event) { ISelection selection = tableViewer.getSelection(); if (selection != null && !selection.isEmpty() && selection instanceof IStructuredSelection) { IStructuredSelection structuredSelection = (IStructuredSelection) selection; @SuppressWarnings("unchecked") Iterator<ConversionConfigBean> iter = structuredSelection.iterator(); while (iter.hasNext()) { ConversionConfigBean bean = iter.next(); String langStr = tgtLangComboViewer.getTableCombo().getText(); if (langStr != null) { for (Language lang : bean.getTgtLangList()) { if (lang.toString().equals(langStr)) { bean.setTgtLang(lang.getCode()); break; } } } } } } }); } /** * 转换选项组 * @param contents * ; */ private void createConversionOptionsGroup(Composite contents) { Group options = new Group(contents, SWT.NONE); options.setText(Messages.getString("ConversionWizardPage.5")); //$NON-NLS-1$ options.setLayout(new GridLayout(2, false)); options.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); /* ------- 转换选项 ------- */ /* 是否按段落分段 */ final Button segType = new Button(options, SWT.CHECK); segType.setText(Messages.getString("ConversionWizardPage.6")); //$NON-NLS-1$ segType.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); segType.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { for (ConversionConfigBean conversionConfigBean : conversionConfigBeans) { conversionConfigBean.setSegByElement(segType.getSelection()); } validate(); } }); /** 按 CR/LF 分段 */ final Button useCRLF = new Button(options, SWT.CHECK); useCRLF.setText(Messages.getString("ConversionWizardPage.7")); //$NON-NLS-1$ useCRLF.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); useCRLF.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { for (ConversionConfigBean conversionConfigBean : conversionConfigBeans) { conversionConfigBean.setBreakOnCRLF(useCRLF.getSelection()); } validate(); } }); /* 是否将骨架嵌入 xliff 文件 */ final Button embedSkl = new Button(options, SWT.CHECK); embedSkl.setText(Messages.getString("ConversionWizardPage.8")); //$NON-NLS-1$ embedSkl.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); embedSkl.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { for (ConversionConfigBean conversionConfigBean : conversionConfigBeans) { conversionConfigBean.setEmbedSkl(embedSkl.getSelection()); } validate(); } }); /* 如果已经存在,是否要替换 */ final Button btnReplaceTarget = new Button(options, SWT.CHECK); btnReplaceTarget.setText(Messages.getString("ConversionWizardPage.9")); //$NON-NLS-1$ btnReplaceTarget.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); btnReplaceTarget.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { for (ConversionConfigBean conversionConfigBean : conversionConfigBeans) { conversionConfigBean.setReplaceTarget(btnReplaceTarget.getSelection()); } validate(); } }); } /** * 创建分段规则选择组 * @param contents * ; */ private void createSegmentationGroup(Composite contents) { Group segmentation = new Group(contents, SWT.NONE); segmentation.setText(Messages.getString("ConversionWizardPage.10")); //$NON-NLS-1$ segmentation.setLayout(new GridLayout(3, false)); GridData data = new GridData(GridData.FILL_HORIZONTAL); data.widthHint = 500; segmentation.setLayoutData(data); Label segLabel = new Label(segmentation, SWT.NONE); segLabel.setText(Messages.getString("ConversionWizardPage.11")); //$NON-NLS-1$ srxFile = new Text(segmentation, SWT.BORDER | SWT.READ_ONLY); srxFile.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); srxFile.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { for (ConversionConfigBean conversionConfigBean : conversionConfigBeans) { conversionConfigBean.setInitSegmenter(srxFile.getText()); } validate(); } }); final Button segBrowse = new Button(segmentation, SWT.PUSH); segBrowse.setText(Messages.getString("ConversionWizardPage.12")); //$NON-NLS-1$ segBrowse.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent arg0) { IConversionItemDialog conversionItemDialog = FileDialogFactoryFacade.createFileDialog(getShell(), SWT.NONE); int result = conversionItemDialog.open(); if (result == IDialogConstants.OK_ID) { IConversionItem conversionItem = conversionItemDialog.getConversionItem(); srxFile.setText(conversionItem.getLocation().toOSString()); } } }); } /** * 得到选中的类型 * @param description * 描述名字 * @return 类型名字; */ private String getSelectedFormat(String description) { for (ConverterBean converterBean : supportTypes) { if (description.equals(converterBean.getDescription())) { return converterBean.getName(); } } return ""; //$NON-NLS-1$ } private void validate() { IStatus result = Status.OK_STATUS; int line = 1; for (ConverterViewModel converterViewModel : converterViewModels) { result = converterViewModel.validate(); if (!result.isOK()) { break; } line++; } if (!result.isOK()) { setPageComplete(false); setErrorMessage(MessageFormat.format(Messages.getString("ConversionWizardPage.13"), line) + result.getMessage()); } else { setErrorMessage(null); setPageComplete(true); } } /** * 创建文件列表区域 * @param contents * ; */ private Composite createFilesGroup(Composite contents) { Composite filesComposite = new Composite(contents, SWT.NONE); filesComposite.setLayout(new GridLayout(1, false)); filesComposite.setLayoutData(new GridData(GridData.FILL_BOTH)); filesTable = new Table(filesComposite, SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL | SWT.MULTI | SWT.FULL_SELECTION); GridData tableData = new GridData(GridData.GRAB_HORIZONTAL | GridData.GRAB_VERTICAL | GridData.FILL_BOTH); tableData.heightHint = 100; filesTable.setLayoutData(tableData); filesTable.setLinesVisible(true); filesTable.setHeaderVisible(true); filesTable.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { TableItem[] selected = filesTable.getSelection(); if (selected.length == 0) { return; } String strSrcFormat = ""; //$NON-NLS-1$ String strSrcEnc = ""; //$NON-NLS-1$ for (int i = 0; i < selected.length; i++) { String curFormat = selected[i].getText(1); String curSrcEnc = selected[i].getText(2); if (i == 0) { strSrcFormat = curFormat; strSrcEnc = curSrcEnc; } else { if (!strSrcFormat.equals(curFormat)) { strSrcFormat = ""; //$NON-NLS-1$ } if (!strSrcEnc.equals(curSrcEnc)) { strSrcEnc = ""; //$NON-NLS-1$ } } } if (!"".equals(strSrcFormat)) { //$NON-NLS-1$ formatCombo.setText(strSrcFormat); } else { formatCombo.deselectAll(); } if (!"".equals(strSrcEnc)) { //$NON-NLS-1$ srcEncCombo.setText(strSrcEnc); } else { srcEncCombo.deselectAll(); } // 目标语言下拉框选中判断 ISelection selection = tableViewer.getSelection(); if (selection != null && !selection.isEmpty() && selection instanceof IStructuredSelection) { IStructuredSelection structuredSelection = (IStructuredSelection) selection; @SuppressWarnings("unchecked") Iterator<ConversionConfigBean> iter = structuredSelection.iterator(); int i = 0; String tgtLang = ""; while (iter.hasNext()) { ConversionConfigBean bean = iter.next(); String currLang = bean.getTgtLang(); for(Language lang :bean.getTgtLangList()){ if(lang.getCode().equals(currLang)){ currLang = lang.toString(); break; } } if (i == 0) { tgtLang = currLang; }else { if(!tgtLang.equals(currLang)){ tgtLang = ""; break; } } i++; } if(!"".equals(tgtLang)){ tgtLangComboViewer.getTableCombo().setText(tgtLang); }else{ tgtLangComboViewer.getTableCombo().select(-1); } } } }); tableViewer = new TableViewer(filesTable); sourceColumn = new TableViewerColumn(tableViewer, SWT.NONE).getColumn(); sourceColumn.setText(Messages.getString("ConversionWizardPage.14")); //$NON-NLS-1$ formatColumn = new TableViewerColumn(tableViewer, SWT.NONE).getColumn(); formatColumn.setText(Messages.getString("ConversionWizardPage.15")); //$NON-NLS-1$ srcEncColumn = new TableViewerColumn(tableViewer, SWT.NONE).getColumn(); srcEncColumn.setText(Messages.getString("ConversionWizardPage.16")); //$NON-NLS-1$ xliffColumn = new TableViewerColumn(tableViewer, SWT.NONE).getColumn(); xliffColumn.setText(Messages.getString("ConversionWizardPage.17")); //$NON-NLS-1$ IValueProperty[] valueProperties = BeanProperties.values(ConversionConfigBean.class, new String[] { "source", "fileType", "srcEncoding", "target" }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ ViewerSupport.bind(tableViewer, new WritableList(conversionConfigBeans, ConversionConfigBean.class), valueProperties); filesComposite.addPaintListener(new PaintListener() { public void paintControl(PaintEvent arg0) { int width = filesTable.getClientArea().width; sourceColumn.setWidth(width * 3 / 10); formatColumn.setWidth(width * 3 / 10); srcEncColumn.setWidth(width * 1 / 10); xliffColumn.setWidth(width * 3 / 10); } }); return filesComposite; } /** * 对 UI 和 View Model 进行绑定 ; */ private void bindValue() { DataBindingContext dbc = new DataBindingContext(); WizardPageSupport.create(this, dbc); ConversionConfigBean configBean = conversionConfigBeans.get(0); // bind the format dbc.bindList(SWTObservables.observeItems(formatCombo), BeansObservables.observeList(configBean, "fileFormats")); //$NON-NLS-1$ // final IObservableValue format = BeansObservables.observeValue(selectedModel, "selectedType"); // dbc.bindValue(SWTObservables.observeSelection(formatCombo), format); // bind the source encoding dbc.bindList(SWTObservables.observeItems(srcEncCombo), BeansObservables.observeList(configBean, "pageEncoding")); //$NON-NLS-1$ } /** * 加载文件数据。 */ private void loadFiles() { for (int i = 0; i < conversionConfigBeans.size(); i++) { ConversionConfigBean bean = conversionConfigBeans.get(i); String source = bean.getSource(); String sourceLocalPath = ConverterUtil.toLocalPath(source); // 自动识别文件类型 String format = FileFormatUtils.detectFormat(sourceLocalPath); if (format == null) { format = ""; //$NON-NLS-1$ } // 自动分析源文件编码 String srcEncValue = EncodingResolver.getEncoding(sourceLocalPath, format); if (srcEncValue == null) { srcEncValue = ""; //$NON-NLS-1$ } // XLIFF 文件路径 String xliff = ""; //$NON-NLS-1$ // 骨架文件路径 String skeleton = ""; //$NON-NLS-1$ try { ConversionResource resource = new ConversionResource(Converter.DIRECTION_POSITIVE, sourceLocalPath); xliff = resource.getXliffPath(); skeleton = resource.getSkeletonPath(); } catch (CoreException e) { e.printStackTrace(); } if (!"".equals(format)) { //$NON-NLS-1$ String name = getSelectedFormat(format); if (name != null && !"".equals(name)) { //$NON-NLS-1$ converterViewModels.get(i).setSelectedType(name); // 添加类型 } } bean.setFileType(format); bean.setSrcEncoding(srcEncValue); bean.setTarget(xliff); bean.setSkeleton(ConverterUtil.toLocalPath(skeleton)); } } @Override public void dispose() { super.dispose(); if (filesTable != null) { filesTable.dispose(); } if (conversionConfigBeans != null) { conversionConfigBeans.clear(); conversionConfigBeans = null; } System.gc(); } class LanguageLabelProvider extends LabelProvider { private Logger logger = LoggerFactory.getLogger(LanguageLabelProvider.class); private Map<String, Image> imageCache = new HashMap<String, Image>(); private String bundlePath; private Shell shell; public LanguageLabelProvider(Shell shell) { try { bundlePath = FileLocator.toFileURL(Platform.getBundle("net.heartsome.cat.ts.ui").getEntry("")).getPath(); } catch (IOException e) { logger.error("在转换器中获取插件路径出错,插件ID:net.heartsome.cat.ts.ui"); e.printStackTrace(); } this.shell = shell; } public Image getImage(Object element) { if (element instanceof Language) { Language lang = (Language) element; String code = lang.getCode(); String imagePath = lang.getImagePath(); if (imagePath != null && !imagePath.equals("")) { imagePath = bundlePath + imagePath; Image image = new Image(shell.getDisplay(), imagePath); if (image != null) { ImageData data = image.getImageData().scaledTo(16, 12); image = new Image(shell.getDisplay(), data); // 销毁原来的图片 Image im = imageCache.remove(code); if (im != null && !im.isDisposed()) { im.dispose(); } // 添加新的图片 imageCache.put(code, image); return image; } } } return null; } public void dispose(){ for (String code : imageCache.keySet()) { Image im = imageCache.get(code); if (im != null && !im.isDisposed()) { im.dispose(); } } imageCache.clear(); super.dispose(); } } }
23,661
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
Messages.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.ui/src/net/heartsome/cat/convert/ui/wizard/Messages.java
package net.heartsome.cat.convert.ui.wizard; /* * Created on Jul 6, 2004 * */ import java.util.MissingResourceException; import java.util.ResourceBundle; /** * @author Rodolfo M. Raya Copyright (c) 2004 Heartsome Holdings Pte Ltd http://www.heartsome.net */ public final class Messages { private static final String BUNDLE_NAME = "net.heartsome.cat.convert.ui.wizard.conversion_new"; //$NON-NLS-1$ private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle.getBundle(BUNDLE_NAME); /** * 私有构造函数 */ private Messages() { // private constructor } /** * 根据 key,获得相应的 value 值 * @param key * @return ; */ public static String getString(String key) { try { return RESOURCE_BUNDLE.getString(key); } catch (MissingResourceException e) { return '!' + key + '!'; } } }
878
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
ReverseConversionWizardPage.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.ui/src/net/heartsome/cat/convert/ui/wizard/ReverseConversionWizardPage.java
package net.heartsome.cat.convert.ui.wizard; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import net.heartsome.cat.bean.Constant; import net.heartsome.cat.common.resources.ResourceUtils; import net.heartsome.cat.convert.ui.model.ConversionConfigBean; import net.heartsome.cat.convert.ui.model.ConverterUtil; import net.heartsome.cat.convert.ui.model.ConverterViewModel; import net.heartsome.cat.convert.ui.model.IConversionItem; import net.heartsome.cat.convert.ui.utils.ConversionResource; import net.heartsome.cat.converter.Converter; import net.heartsome.cat.converter.util.Progress; import net.heartsome.cat.ts.core.file.DocumentPropertiesKeys; import net.heartsome.cat.ts.core.file.XLFHandler; import org.eclipse.core.databinding.DataBindingContext; import org.eclipse.core.databinding.beans.BeanProperties; import org.eclipse.core.databinding.beans.BeansObservables; import org.eclipse.core.databinding.observable.list.WritableList; import org.eclipse.core.databinding.property.value.IValueProperty; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.jface.databinding.swt.SWTObservables; import org.eclipse.jface.databinding.viewers.ViewerSupport; import org.eclipse.jface.databinding.wizard.WizardPageSupport; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.jface.layout.GridLayoutFactory; import org.eclipse.jface.layout.LayoutConstants; import org.eclipse.jface.operation.IRunnableWithProgress; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.TableViewer; import org.eclipse.jface.viewers.TableViewerColumn; import org.eclipse.jface.wizard.WizardPage; import org.eclipse.swt.SWT; import org.eclipse.swt.events.PaintEvent; import org.eclipse.swt.events.PaintListener; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Combo; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Group; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Table; import org.eclipse.swt.widgets.TableColumn; import org.eclipse.swt.widgets.TableItem; /** * 项目逆向转换选项配置页 * @author weachy * @since JDK1.5 */ public class ReverseConversionWizardPage extends WizardPage { private List<ConverterViewModel> converterViewModels; /** 源文件编码列表 */ private Combo tgtEncCombo; /** 如果已经存在,是否要替换 */ private Button btnReplaceTarget; /** 文件列表 */ private Table filesTable; /** xliff 文件列 */ private TableColumn xliffColumn; /** 目标编码列 */ private TableColumn tgtEncColumn; /** 目标文件列 */ private TableColumn targetColumn; private ArrayList<ConversionConfigBean> conversionConfigBeans; private TableViewer tableViewer; /** * 正向项目转换配置信息页的构造函数 * @param pageName */ protected ReverseConversionWizardPage(String pageName) { super(pageName); setTitle("转换 Xliff 到原格式"); } /** * 初始化本页面需要的数据 ; */ private void initData() { ReverseConversionWizard wizard = (ReverseConversionWizard) getWizard(); converterViewModels = wizard.getConverterViewModels(); conversionConfigBeans = new ArrayList<ConversionConfigBean>(); for (ConverterViewModel converterViewModel : converterViewModels) { IConversionItem conversionItem = converterViewModel.getConversionItem(); String xliff = ResourceUtils.toWorkspacePath(conversionItem.getLocation()); ConversionConfigBean bean = converterViewModel.getConfigBean(); bean.setSource(xliff); conversionConfigBeans.add(bean); } } public void createControl(Composite parent) { initData(); // 先初始化本页面需要的数据 Composite contents = new Composite(parent, SWT.NONE); GridLayout layout = new GridLayout(); contents.setLayout(layout); GridData gridData = new GridData(); gridData.horizontalAlignment = SWT.FILL; gridData.grabExcessHorizontalSpace = true; contents.setLayoutData(gridData); createFilesGroup(contents); // 文件列表区域 createPropertiesGroup(contents); // 源文件属性区域组 createConversionOptionsGroup(contents); // 转换选项组 bindValue(); // 数据绑定 try { loadFiles(); // 加载文件列表 } catch (Exception e) { e.printStackTrace(); } filesTable.select(0); // 默认选中第一行数据 filesTable.notifyListeners(SWT.Selection, null); Dialog.applyDialogFont(parent); Point defaultMargins = LayoutConstants.getMargins(); GridLayoutFactory.fillDefaults().numColumns(1).margins(defaultMargins.x, defaultMargins.y) .generateLayout(contents); setControl(contents); validate(); } private void createPropertiesGroup(Composite contents) { Group langComposite = new Group(contents, SWT.NONE); langComposite.setText("默认属性"); //$NON-NLS-1$ langComposite.setLayout(new GridLayout(2, false)); langComposite.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); Label tgtEncLabel = new Label(langComposite, SWT.NONE); tgtEncLabel.setText("目标编码"); //$NON-NLS-1$ tgtEncCombo = new Combo(langComposite, SWT.DROP_DOWN | SWT.READ_ONLY); tgtEncCombo.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); tgtEncCombo.addSelectionListener(new SelectionAdapter() { @SuppressWarnings("unchecked") public void widgetSelected(SelectionEvent arg0) { ISelection selection = tableViewer.getSelection(); if (selection != null && !selection.isEmpty() && selection instanceof IStructuredSelection) { IStructuredSelection structuredSelection = (IStructuredSelection) selection; Iterator<ConversionConfigBean> iter = structuredSelection.iterator(); while (iter.hasNext()) { ConversionConfigBean bean = iter.next(); bean.setTargetEncoding(tgtEncCombo.getText()); } validate(); } } }); } /** * 转换选项组 * @param contents * ; */ private void createConversionOptionsGroup(Composite contents) { Group options = new Group(contents, SWT.NONE); options.setText("转换选项"); options.setLayout(new GridLayout()); options.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); btnReplaceTarget = new Button(options, SWT.CHECK); btnReplaceTarget.setText("若目标文件已存在则直接覆盖"); btnReplaceTarget.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); btnReplaceTarget.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { for (ConversionConfigBean conversionConfigBean : conversionConfigBeans) { conversionConfigBean.setReplaceTarget(btnReplaceTarget.getSelection()); } validate(); } }); } /** XLFHandler 对象 */ XLFHandler xlfHandler = new XLFHandler(); /** 完成 */ private boolean complete = false; /** 错误信息 */ private String errorMessage = null; /** * 验证方法 ; */ private void validate() { IRunnableWithProgress runnable = new IRunnableWithProgress() { public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { monitor.setTaskName("逆转换验证"); monitor.beginTask("正在进行转换验证...", converterViewModels.size()); IStatus result = Status.OK_STATUS; int line = 1; for (ConverterViewModel converterViewModel : converterViewModels) { String xliff = converterViewModel.getConversionItem().getLocation().toOSString(); IProgressMonitor subMonitor = Progress.getSubMonitor(monitor, 1); result = converterViewModel.validateXliffFile(xliff, xlfHandler, subMonitor); if (!result.isOK()) { break; } result = converterViewModel.validate(); if (!result.isOK()) { break; } line++; } monitor.done(); final IStatus validateResult = result; final int i = line; if (validateResult.isOK()) { complete = true; errorMessage = null; } else { complete = false; errorMessage = "第 " + i + " 行: " + validateResult.getMessage(); } } }; try { // 验证 xliff 文件比较耗时,需把他放到后台线程进行处理。 // new ProgressMonitorDialog(shell).run(true, true, runnable); getContainer().run(true, true, runnable); setErrorMessage(errorMessage); setPageComplete(complete); } catch (InvocationTargetException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } } /** * 创建文件列表区域 * @param contents * ; */ private Composite createFilesGroup(Composite contents) { Composite filesComposite = new Composite(contents, SWT.NONE); filesComposite.setLayout(new GridLayout(1, false)); filesComposite.setLayoutData(new GridData(GridData.FILL_BOTH)); filesTable = new Table(filesComposite, SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL | SWT.MULTI | SWT.FULL_SELECTION); GridData tableData = new GridData(GridData.GRAB_HORIZONTAL | GridData.GRAB_VERTICAL | GridData.FILL_BOTH); tableData.heightHint = 100; filesTable.setLayoutData(tableData); filesTable.setLinesVisible(true); filesTable.setHeaderVisible(true); filesTable.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { TableItem[] selected = filesTable.getSelection(); if (selected.length == 0) { return; } String strTgtEnc = ""; //$NON-NLS-1$ for (int i = 0; i < selected.length; i++) { String curTgtEnc = selected[i].getText(1); if (i == 0) { strTgtEnc = curTgtEnc; } else { if (!strTgtEnc.equals(curTgtEnc)) { strTgtEnc = ""; //$NON-NLS-1$ break; } } } if (!"".equals(strTgtEnc)) { //$NON-NLS-1$ tgtEncCombo.setText(strTgtEnc); } else { tgtEncCombo.deselectAll(); } } }); tableViewer = new TableViewer(filesTable); xliffColumn = new TableViewerColumn(tableViewer, SWT.NONE).getColumn(); xliffColumn.setText("XLIFF 文件"); //$NON-NLS-1$ tgtEncColumn = new TableViewerColumn(tableViewer, SWT.NONE).getColumn(); tgtEncColumn.setText("目标编码"); //$NON-NLS-1$ targetColumn = new TableViewerColumn(tableViewer, SWT.NONE).getColumn(); targetColumn.setText("目标文件"); //$NON-NLS-1$ IValueProperty[] valueProperties = BeanProperties.values(ConversionConfigBean.class, new String[] { "source", "targetEncoding", "target" }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ ViewerSupport.bind(tableViewer, new WritableList(conversionConfigBeans, ConversionConfigBean.class), valueProperties); filesComposite.addPaintListener(new PaintListener() { public void paintControl(PaintEvent arg0) { int width = filesTable.getClientArea().width; targetColumn.setWidth(width * 4 / 10); tgtEncColumn.setWidth(width * 2 / 10); xliffColumn.setWidth(width * 4 / 10); } }); return filesComposite; } /** * 对 UI 和 View Model 进行绑定 ; */ private void bindValue() { DataBindingContext dbc = new DataBindingContext(); WizardPageSupport.create(this, dbc); ConversionConfigBean configBean = conversionConfigBeans.get(0); // bind the target encoding dbc.bindList(SWTObservables.observeItems(tgtEncCombo), BeansObservables.observeList(configBean, "pageEncoding")); //$NON-NLS-1$ } /** * 加载文件数据。 */ private void loadFiles() { ArrayList<String> xliffs = new ArrayList<String>(conversionConfigBeans.size()); for (int i = 0; i < conversionConfigBeans.size(); i++) { String xliff = conversionConfigBeans.get(i).getSource(); xliffs.add(ResourceUtils.toWorkspacePath(xliff)); } for (int i = 0; i < conversionConfigBeans.size(); i++) { ConversionConfigBean bean = conversionConfigBeans.get(i); // 逆转换时,source 其实是 XLIFF 文件。 String xliff = bean.getSource(); String local = ConverterUtil.toLocalPath(xliff); // 目标文件 String target; try { ConversionResource resource = new ConversionResource(Converter.DIRECTION_REVERSE, local); target = resource.getTargetPath(); } catch (CoreException e) { e.printStackTrace(); target = ""; //$NON-NLS-1$ } bean.getFileType(); // 目标编码 String tgtEncValue = getTgtEncoding(local); if (tgtEncValue == null) { tgtEncValue = ""; //$NON-NLS-1$ } bean.setSource(xliff); bean.setTargetEncoding(tgtEncValue); bean.setTarget(target); } } /** * 取得目标文件的编码 * @param xliffPath * @return ; */ private String getTgtEncoding(String xliffPath) { XLFHandler handler = new XLFHandler(); Map<String, Object> resultMap = handler.openFile(xliffPath); if (resultMap == null || Constant.RETURNVALUE_RESULT_SUCCESSFUL != (Integer) resultMap.get(Constant.RETURNVALUE_RESULT)) { // 打开文件失败。 return ""; //$NON-NLS-1$ } List<HashMap<String, String>> documentInfo = handler.getDocumentInfo(xliffPath); if (documentInfo.size() > 0) { return documentInfo.get(0).get(DocumentPropertiesKeys.ENCODING); } return ""; } @Override public void dispose() { super.dispose(); if (filesTable != null) { filesTable.dispose(); } if (conversionConfigBeans != null) { conversionConfigBeans.clear(); conversionConfigBeans = null; } System.gc(); } }
13,779
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
ConversionWizard.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.ui/src/net/heartsome/cat/convert/ui/wizard/ConversionWizard.java
package net.heartsome.cat.convert.ui.wizard; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import net.heartsome.cat.common.locale.Language; import net.heartsome.cat.common.resources.ResourceUtils; import net.heartsome.cat.convert.ui.model.ConversionConfigBean; import net.heartsome.cat.convert.ui.model.ConverterViewModel; import net.heartsome.cat.convert.ui.model.IConversionItem; import net.heartsome.cat.ts.core.file.ProjectConfiger; import org.eclipse.core.resources.IProject; import org.eclipse.jface.wizard.Wizard; /** * 项目正向转换向导 * @author weachy * @since JDK1.5 */ public class ConversionWizard extends Wizard { private List<ConverterViewModel> converterViewModels; private ArrayList<ConversionConfigBean> conversionConfigBeans; /** * 正向转换向导构造函数 * @param model */ public ConversionWizard(List<ConverterViewModel> models, IProject project) { this.converterViewModels = models; String projCfgFile = project.getLocation().append(".project").toOSString(); ProjectConfiger configer = new ProjectConfiger(projCfgFile); Language sourceLanguage = configer.getCurrentProjectConfig().getSourceLang(); List<Language> targetlanguage = configer.getCurrentProjectConfig().getTargetLang(); Collections.sort(targetlanguage, new Comparator<Language>() { public int compare(Language l1, Language l2) { return l1.toString().compareTo(l2.toString()); } }); conversionConfigBeans = new ArrayList<ConversionConfigBean>(); for (ConverterViewModel converterViewModel : converterViewModels) { IConversionItem conversionItem = converterViewModel.getConversionItem(); String source = ResourceUtils.toWorkspacePath(conversionItem.getLocation()); ConversionConfigBean bean = converterViewModel.getConfigBean(); bean.setSource(source); // 初始化源文件路径 bean.setSrcLang(sourceLanguage.getCode()); // 初始化源语言 bean.setTgtLangList(targetlanguage); conversionConfigBeans.add(bean); } setWindowTitle(Messages.getString("ConversionWizard.0")); //$NON-NLS-1$ } @Override public void addPages() { String title = Messages.getString("ConversionWizard.1"); //$NON-NLS-1$ ConversionWizardPage page = new ConversionWizardPage(title, converterViewModels, conversionConfigBeans); addPage(page); // TODO 添加预翻译选项设置 // addPage(new TranslationWizardPage(Messages.getString("ConversionWizard.2"))); //$NON-NLS-1$ } @Override public boolean performFinish() { return true; } /** * 返回此向导对应的 view model * @return ; */ public List<ConverterViewModel> getConverterViewModels() { return converterViewModels; } }
2,736
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
ReverseConversionWizard.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.ui/src/net/heartsome/cat/convert/ui/wizard/ReverseConversionWizard.java
package net.heartsome.cat.convert.ui.wizard; import java.util.List; import net.heartsome.cat.convert.ui.model.ConverterViewModel; import org.eclipse.core.resources.IProject; import org.eclipse.jface.wizard.Wizard; /** * 逆向转换向导 * @author weachy * @since JDK1.5 */ public class ReverseConversionWizard extends Wizard { private List<ConverterViewModel> converterViewModels; private IProject project; /** * 正向转换向导构造函数 * @param model */ public ReverseConversionWizard(List<ConverterViewModel> models, IProject projct) { this.converterViewModels = models; this.project = projct; setWindowTitle(Messages.getString("ReverseConversionWizard.0")); //$NON-NLS-1$ // 需要显示 progress monitor setNeedsProgressMonitor(true); } @Override public void addPages() { addPage(new ReverseConversionWizardPage(Messages.getString("ReverseConversionWizard.1"))); // TODO 存储翻译到翻译记译库 } @Override public boolean performFinish() { return true; } /** * 返回此向导对应的 view model * @return ; */ public List<ConverterViewModel> getConverterViewModels() { return converterViewModels; } /** * 返回此向导对应的 Project * @return ; */ public IProject getProject() { return project; } }
1,303
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
TranslationWizardPage.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.ui/src/net/heartsome/cat/convert/ui/wizard/TranslationWizardPage.java
package net.heartsome.cat.convert.ui.wizard; import org.eclipse.jface.layout.GridLayoutFactory; import org.eclipse.jface.wizard.WizardPage; import org.eclipse.swt.SWT; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Text; /** * 正向转换的预翻译配置页 * @author cheney * @since JDK1.6 */ public class TranslationWizardPage extends WizardPage { /** * 预翻译配置页构建函数 * @param pageName */ protected TranslationWizardPage(String pageName) { super(pageName); setTitle("翻译相关的设置"); setMessage("翻译相关的设置,待实现。"); } public void createControl(Composite parent) { Composite composite = new Composite(parent, SWT.NONE); Label label = new Label(composite, SWT.NONE); label.setText("Test:"); new Text(composite, SWT.BORDER); GridLayoutFactory.swtDefaults().numColumns(2).generateLayout(composite); setControl(composite); } }
974
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
ConversionCompleteAction.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.ui/src/net/heartsome/cat/convert/ui/action/ConversionCompleteAction.java
package net.heartsome.cat.convert.ui.action; import java.io.File; import java.util.Map; import net.heartsome.cat.converter.Converter; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IWorkspaceRoot; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.Assert; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Path; import org.eclipse.jface.action.Action; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.swt.widgets.Shell; import org.eclipse.ui.IEditorDescriptor; import org.eclipse.ui.IEditorRegistry; import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.PartInitException; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.ide.IDE; /** * 演示文件转换后台线程的转换结果 action * @author cheney,weachy * @since JDK1.5 */ public class ConversionCompleteAction extends Action { private IStatus status; private Map<String, String> conversionResult; /** * 转换完成 action 的构造函数 * @param name * action 的显示文本 * @param status * 转换的结果状态 * @param conversionResult */ public ConversionCompleteAction(String name, IStatus status, Map<String, String> conversionResult) { setText(name); setToolTipText(name); this.status = status; this.conversionResult = conversionResult; } @Override public void run() { IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow(); Assert.isNotNull(window); Shell shell = window.getShell(); if (status.getSeverity() == IStatus.ERROR) { MessageDialog.openError(shell, "文件转换失败", status.getMessage()); } else { // 转换完成后直接打开编辑器,不再进行弹框提示。 // MessageDialog.openInformation(shell, "文件转换完成", status.getMessage()); final String XLIFF_EDITOR_ID = "net.heartsome.cat.ts.ui.xliffeditor.nattable.editor"; String xliffFile = conversionResult.get(Converter.ATTR_XLIFF_FILE); IWorkbenchPage page = window.getActivePage(); Assert.isNotNull(page, "当前的 Active Page 为 null。无法打开转换后的文件。"); if (xliffFile != null) { IEditorDescriptor editorDescriptor = PlatformUI.getWorkbench().getEditorRegistry().findEditor( XLIFF_EDITOR_ID); if (editorDescriptor != null) { try { IDE.openEditor(page, new File(xliffFile).toURI(), XLIFF_EDITOR_ID, true); } catch (PartInitException e) { MessageDialog.openInformation(shell, "提示", "转换完成!但是在尝试打开该 XLIFF 文件时发生异常:\n" + e.getMessage()); e.printStackTrace(); } } } else { String targetFile = conversionResult.get(Converter.ATTR_TARGET_FILE); if (targetFile == null) { MessageDialog.openError(shell, "错误", "为找到已转换文件的路径!"); } else { IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); IFile input = root.getFileForLocation(new Path(targetFile)); try { // 使用外部编辑器(系统默认编辑器)打开文件。 IDE.openEditor(page, input, IEditorRegistry.SYSTEM_EXTERNAL_EDITOR_ID); } catch (PartInitException e) { MessageDialog.openInformation(shell, "提示", "转换完成!但是在尝试使用系统默认程序打开该文件时发生异常:\n" + e.getMessage()); e.printStackTrace(); } } } } } }
3,476
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
ConfigConversionDialog.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.ui/src/net/heartsome/cat/convert/ui/dialog/ConfigConversionDialog.java
package net.heartsome.cat.convert.ui.dialog; import net.heartsome.cat.convert.ui.model.ConverterUtil; import net.heartsome.cat.convert.ui.model.ConverterViewModel; import net.heartsome.cat.converter.Converter; import org.eclipse.core.databinding.DataBindingContext; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.jface.dialogs.TitleAreaDialog; import org.eclipse.jface.layout.GridLayoutFactory; import org.eclipse.jface.layout.LayoutConstants; import org.eclipse.jface.viewers.ComboViewer; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.ISelectionChangedListener; import org.eclipse.jface.viewers.SelectionChangedEvent; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Shell; /** * 转换文件配置对话框 * @author cheney * @since JDK1.6 */ public class ConfigConversionDialog extends TitleAreaDialog { private ConverterViewModel converterViewModel; private ComboViewer supportList; private Button okButton; /** * 构造函数 * @param parentShell * @param converterViewModel */ public ConfigConversionDialog(Shell parentShell, ConverterViewModel converterViewModel) { super(parentShell); this.converterViewModel = converterViewModel; } @Override protected Control createDialogArea(Composite parent) { Composite parentComposite = (Composite) super.createDialogArea(parent); Composite contents = new Composite(parentComposite, SWT.NONE); GridLayout layout = new GridLayout(); contents.setLayout(layout); GridData gridData = new GridData(); gridData.horizontalAlignment = SWT.FILL; gridData.grabExcessHorizontalSpace = true; contents.setLayoutData(gridData); Composite converterComposite = new Composite(contents, SWT.NONE); converterComposite.setLayout(new GridLayout(2, false)); gridData = new GridData(); gridData.horizontalAlignment = SWT.FILL; gridData.grabExcessHorizontalSpace = true; converterComposite.setLayoutData(gridData); String direction = converterViewModel.getDirection(); if (direction.equals(Converter.DIRECTION_POSITIVE)) { supportList = createConvertControl("Convert from Suport format to Xliff", converterComposite); } else { supportList = createConvertControl("Convert from Xliff to Support format", converterComposite); } supportList.getCombo().setFocus(); bindValue(); Dialog.applyDialogFont(parentComposite); Point defaultMargins = LayoutConstants.getMargins(); GridLayoutFactory.fillDefaults().numColumns(2).margins(defaultMargins.x, defaultMargins.y).generateLayout( contents); return contents; } @Override protected void createButtonsForButtonBar(Composite parent) { okButton = createButton(parent, IDialogConstants.OK_ID, "OK", true); okButton.setEnabled(false); createButton(parent, IDialogConstants.CANCEL_ID, "Cancel", false); } /** * 创建文件类型列表 * @param title * @param composite * @return ; */ private ComboViewer createConvertControl(String title, Composite composite) { Label positiveConvertLabel = new Label(composite, SWT.NONE); GridData positiveConvertLabelData = new GridData(); positiveConvertLabelData.horizontalSpan = 2; positiveConvertLabelData.horizontalAlignment = SWT.CENTER; positiveConvertLabelData.grabExcessHorizontalSpace = true; positiveConvertLabel.setLayoutData(positiveConvertLabelData); positiveConvertLabel.setText(title); Label suportFormat = new Label(composite, SWT.NONE); suportFormat.setText("Suport Format"); ComboViewer supportList = new ComboViewer(composite, SWT.READ_ONLY); GridData gridData = new GridData(); gridData.horizontalAlignment = SWT.FILL; gridData.grabExcessHorizontalSpace = true; supportList.getCombo().setLayoutData(gridData); supportList.addSelectionChangedListener(new ISelectionChangedListener() { public void selectionChanged(SelectionChangedEvent event) { ISelection selection = event.getSelection(); if (selection.isEmpty()) { okButton.setEnabled(false); } else { okButton.setEnabled(true); } } }); return supportList; } /** * 对 UI 和 View Model 进行绑定 ; */ private void bindValue() { DataBindingContext dbc = new DataBindingContext(); ConverterUtil.bindValue(dbc, supportList, converterViewModel); } }
4,608
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
IConversionItemDialog.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.ui/src/net/heartsome/cat/convert/ui/dialog/IConversionItemDialog.java
package net.heartsome.cat.convert.ui.dialog; import net.heartsome.cat.convert.ui.model.IConversionItem; /** * 选择转换项目的适配器接口,具体的实现可以为:在 RCP 环境中为 FileDialog 或 WorkspaceDialog;在 RAP 环境中为文件上传界面。 * @author cheney * @since JDK1.6 */ public interface IConversionItemDialog { /** * @return 打开转换项目选择对话框,并返回操作结果:用户点击确定按钮则返回 IDialogConstants.OK_ID; */ int open(); /** * 获得转换项目 * @return 返回转换项目,如果用户没有选择任何转换项目,则返回一个空的转换项目; */ IConversionItem getConversionItem(); }
697
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
FileDialogFactoryFacade.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.ui/src/net/heartsome/cat/convert/ui/dialog/FileDialogFactoryFacade.java
package net.heartsome.cat.convert.ui.dialog; import net.heartsome.cat.convert.ui.ImplementationLoader; import org.eclipse.swt.widgets.Shell; /** * 打开文件对话框的 factory facade * @author cheney * @since JDK1.6 */ public abstract class FileDialogFactoryFacade { private static final FileDialogFactoryFacade IMPL; static { IMPL = (FileDialogFactoryFacade) ImplementationLoader.newInstance(FileDialogFactoryFacade.class); } /** * @param shell * @return 返回具体的文件对话框实现; */ public static IConversionItemDialog createFileDialog(final Shell shell, int styled) { return IMPL.createFileDialogInternal(shell, styled); } /** * @param shell * @param styled * @return 返回显示工作空间中的文件的对话框; */ public static IConversionItemDialog createWorkspaceDialog(final Shell shell, int styled) { return IMPL.createWorkspaceDialogInternal(shell, styled); } /** * @param shell * @return 返回文件对话框的内部实现; */ protected abstract IConversionItemDialog createFileDialogInternal(Shell shell, int styled); /** * @param shell * @param styled * @return 返回显示工作空间中的文件的对话框;; */ protected abstract IConversionItemDialog createWorkspaceDialogInternal(Shell shell, int styled); }
1,311
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
ConversionResource.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.ui/src/net/heartsome/cat/convert/ui/utils/ConversionResource.java
package net.heartsome.cat.convert.ui.utils; import java.io.File; import net.heartsome.cat.bean.Constant; import net.heartsome.cat.convert.ui.Activator; import net.heartsome.cat.convert.ui.model.IConversionItem; import net.heartsome.cat.converter.Converter; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IWorkspaceRoot; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Path; import org.eclipse.core.runtime.Status; /** * 本类用于管理转换的资源 * @author weachy * @version * @since JDK1.5 */ public class ConversionResource { private String direction; IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); // 工作空间的 root private IFile file; // 源文件 private IProject project; // 所在项目 private IPath projectRelativePath; // 项目路径 /** * 本类用于管理转换的资源 * @param direction * 转换方向 * @param conversionItem * 转换项目对象 * @throws CoreException */ public ConversionResource(String direction, IConversionItem conversionItem) throws CoreException { this(direction, conversionItem.getLocation()); } /** * 本类用于管理转换的资源 * @param direction * 转换方向 * @param path * 绝对路径 * @throws CoreException */ public ConversionResource(String direction, String path) throws CoreException { this(direction, new Path(path)); } /** * 本类用于管理转换的资源 * @param direction * 转换方向 * @param location * 绝对路径 * @throws CoreException */ public ConversionResource(String direction, IPath location) throws CoreException { this.direction = direction; file = root.getFileForLocation(location); if (file != null) { project = file.getProject(); projectRelativePath = file.getProjectRelativePath(); if (projectRelativePath.segmentCount() > 1) { projectRelativePath = projectRelativePath.removeFirstSegments(1); // 移除 project 下的第一级目录。 } } else { throw new CoreException(new Status(IStatus.WARNING, Activator.PLUGIN_ID, "找不到该文件:" + location.toOSString())); } } /** * 得到源文件路径 * @return ; */ public String getSourcePath() { if (Converter.DIRECTION_POSITIVE.equals(direction)) { return file.getFullPath().toOSString(); } else { throw new RuntimeException("无法获取源文件路径。转换器转换方向:" + direction); } } /** * 得到 XLIFF 文件路径 * @return ; */ public String getXliffPath() { if (Converter.DIRECTION_POSITIVE.equals(direction)) { // 正向转换 IPath projectPath = project.getFullPath(); // 得到项目路径 IPath targetPath = projectRelativePath.addFileExtension("xlf"); // 添加 xlf 后缀名 // 放到 XLIFF 文件夹下 String xliffFilePath = projectPath.append(Constant.FOLDER_XLIFF).append(targetPath).toOSString(); return xliffFilePath; } else { // 反向转换 return file.getFullPath().toOSString(); } } /** * 得到骨架文件路径 * @return ; */ public String getSkeletonPath() { if (Converter.DIRECTION_POSITIVE.equals(direction)) { // 正向转换 IPath projectPath = project.getFullPath(); // 得到项目路径 IPath skeletonPath = projectRelativePath.addFileExtension("skl"); // 添加 skl 后缀名 // 放到 SKL 文件夹下 String skeletonFileFile = projectPath.append(Constant.FOLDER_SKL).append(skeletonPath).toOSString(); return skeletonFileFile; } else { // 反向转换 throw new RuntimeException("无法获取骨架文件路径。转换器转换方向:" + direction); } } /** * 得到目标文件路径 * @return ; */ public String getTargetPath() { return getTargetPath(Constant.FOLDER_TGT); } /** * 得到目标文件路径 * @param tgtFolder * 目标文件存放文件夹,默认值为{@link net.heartsome.cat.bean.Constant#FOLDER_TGT},默认情况下建议使用 {@link #getTargetPath()} * @return ; */ public String getTargetPath(String tgtFolder) { if (Converter.DIRECTION_POSITIVE.equals(direction)) { // 正向转换 throw new RuntimeException("无法获取目标文件路径。转换器转换方向:" + direction); } else { IPath projectPath = project.getFullPath(); // 得到项目路径 String fileExtension = projectRelativePath.getFileExtension(); IPath targetPath; if ("xlf".equalsIgnoreCase(fileExtension)) { targetPath = projectRelativePath.removeFileExtension(); // 去除 .xlf 后缀 } else { targetPath = projectRelativePath; } // 放到 Target 文件夹下 String targetFilePath = projectPath.append(tgtFolder).append(targetPath).toOSString(); return targetFilePath; } } /** * 得到目标文件路径 * @param tgtFolder * 目标文件存放文件夹,默认值为{@link net.heartsome.cat.bean.Constant#FOLDER_TGT},默认情况下建议使用 {@link #getTargetPath()} * @return ; */ public String getPreviewPath() { if (Converter.DIRECTION_POSITIVE.equals(direction)) { // 正向转换 throw new RuntimeException("无法获取目标文件路径。转换器转换方向:" + direction); } else { IPath projectPath = project.getFullPath(); // 得到项目路径 String fileExtension = projectRelativePath.getFileExtension(); IPath targetPath; if ("xlf".equalsIgnoreCase(fileExtension)) { targetPath = projectRelativePath.removeFileExtension(); // 去除 .xlf 后缀 } else { targetPath = projectRelativePath; } // 放到 Target 文件夹下 String targetFilePath = projectPath.append(Constant.FOLDER_OTHER).append(targetPath).toOSString(); int index = targetFilePath.lastIndexOf("."); if (index > -1 && index > targetFilePath.lastIndexOf(File.separatorChar)) { targetFilePath = targetFilePath.substring(0, index) + "_Preview" + targetFilePath.substring(index); } return targetFilePath; } } }
6,190
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
EncodingResolver.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.ui/src/net/heartsome/cat/convert/ui/utils/EncodingResolver.java
/* * Created on 24-nov-2004 * */ package net.heartsome.cat.convert.ui.utils; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.StringTokenizer; import net.heartsome.cat.bean.Constant; import net.heartsome.util.TextUtil; /** * 编码分析工具 * @author Gonzalo Pennino Greco * * Copyright (c) 2004 Heartsome Holdings Pte. Ltd. http://www.heartsome.net */ public class EncodingResolver { /** * This method returns the file encoding * * @param fileName * @param fileType * @return */ public static String getEncoding(String fileName, String fileType) { if (fileType == null || fileName == null) { return null; } else if (fileType.equals(FileFormatUtils.OO) || fileType.equals(FileFormatUtils.OFF)) { return "UTF-8"; //$NON-NLS-1$ //fixed bug 424 by john. } else if (fileType.equals(FileFormatUtils.MIF) || fileType.equals(FileFormatUtils.TEXT) || fileType.equals(FileFormatUtils.JS)) { return "US-ASCII"; //$NON-NLS-1$ } else if (fileType.equals(FileFormatUtils.JAVA)) { return "ISO-8859-1"; //$NON-NLS-1$ } else if (fileType.equals(FileFormatUtils.PO)) { return "UTF-8"; //$NON-NLS-1$ } if (fileType.equals(FileFormatUtils.RTF) || fileType.equals(FileFormatUtils.TRTF)) { return getRTFEncoding(fileName); } else if (fileType.equals(FileFormatUtils.XML) || fileType.equals(FileFormatUtils.TTX) || fileType.equals(FileFormatUtils.RESX) || fileType.equals(FileFormatUtils.INX)) { return getXMLEncoding(fileName); } else if (fileType.equals(FileFormatUtils.RC)) { return getRCEncoding(fileName); } return null; } private static String getRCEncoding(String fileName) { try { FileInputStream input = new FileInputStream(fileName); // read 4K bytes int read = 4096; if (input.available() < read){ read = input.available(); } byte[] bytes = new byte[read]; input.read(bytes); input.close(); String content = new String(bytes); if (content.indexOf("code_page(") != -1) { //$NON-NLS-1$ String code = content.substring(content.indexOf("code_page(")+10); //$NON-NLS-1$ code = code.substring(0,code.indexOf(")")); //$NON-NLS-1$ return RTF2JavaEncoding(code); } } catch(Exception e) { return null; } return null; } /** * This method returns the most suitable encoding according to the file type * * @param fileType * @return */ public static String getEncoding(String fileType){ if ( fileType == null) { return null; } else if (fileType.equals(FileFormatUtils.OO)){ return "UTF-8"; //$NON-NLS-1$ } else if (fileType.equals(FileFormatUtils.MIF)){ return "US-ASCII"; //$NON-NLS-1$ } else if (fileType.equals(FileFormatUtils.JAVA)){ return "ISO-8859-1"; //$NON-NLS-1$ } else if (fileType.equals(FileFormatUtils.TTX)){ return "UTF-16LE"; //$NON-NLS-1$ } else if (fileType.equals(FileFormatUtils.PO) || fileType.equals(FileFormatUtils.XML) || fileType.equals(FileFormatUtils.INX) ){ return "UTF-8"; //$NON-NLS-1$ } return null; } public static boolean isFixedEncoding(String fileType){ if (fileType.equals(FileFormatUtils.OO) || // fileType.equals(FileFormatUtils.MIF) || //Fixed a bug 1651 by john. fileType.equals(FileFormatUtils.RTF) || fileType.equals(FileFormatUtils.TRTF)) { return true; } return false; } private static String getXMLEncoding(String fileName) { // return UTF-8 as default String result = "UTF-8"; //$NON-NLS-1$ try{ // check if there is a BOM (byte order mark) // at the start of the document FileInputStream inputStream = new FileInputStream(fileName); byte[] array = new byte[2]; inputStream.read(array); inputStream.close(); byte[] lt = "<".getBytes(); //$NON-NLS-1$ byte[] feff = {-1,-2}; byte[] fffe = {-2,-1}; if (array[0] != lt[0] ) { // there is a BOM, now check the order if (array[0] == fffe[0] && array[1] == fffe[1]) { return "UTF-16BE"; //$NON-NLS-1$ } if (array[0] == feff[0] && array[1] == feff[1]) { return "UTF-16LE"; //$NON-NLS-1$ } } // check declared encoding FileReader input = new FileReader(fileName); BufferedReader buffer = new BufferedReader(input); String line = buffer.readLine(); input.close(); if (line.startsWith("<?")) { //$NON-NLS-1$ line = line.substring(2, line.indexOf("?>")); //$NON-NLS-1$ line = line.replaceAll("\'", "\""); //$NON-NLS-1$ //$NON-NLS-2$ StringTokenizer tokenizer = new StringTokenizer(line); while (tokenizer.hasMoreTokens()) { String token = tokenizer.nextToken(); if (token.startsWith("encoding")) { //$NON-NLS-1$ result = token.substring(token.indexOf("\"") + 1, token.lastIndexOf("\"")); //$NON-NLS-1$ //$NON-NLS-2$ } } } } catch(Exception e) { if(Constant.RUNNING_MODE == Constant.MODE_DEBUG){ e.printStackTrace(); } try { File log = File.createTempFile("error", ".log", new File("logs")); FileWriter writer = new FileWriter(log); PrintWriter print = new PrintWriter(writer); e.printStackTrace(print); writer.close(); print.close(); writer = null; print = null; } catch (IOException e2) { //do nothing } //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } String[] encodings = TextUtil.getPageCodes(); for (int i=0 ; i<encodings.length ; i++) { if (encodings[i].equalsIgnoreCase(result)) { return encodings[i]; } } return result; } private static String getRTFEncoding(String fileName){ try{ FileInputStream input = new FileInputStream(fileName); // read 200 bytes int read = 200; if (input.available() < read){ read = input.available(); } byte[] bytes = new byte[read]; input.read(bytes); input.close(); String content = new String(bytes); StringTokenizer tk = new StringTokenizer(content,"\\",true); //$NON-NLS-1$ while (tk.hasMoreTokens()) { String token = tk.nextToken(); if ( token.equals("\\")) { //$NON-NLS-1$ token = token + tk.nextToken(); } if (token.startsWith("\\ansicpg")) { //$NON-NLS-1$ String javaEnc = RTF2JavaEncoding(token.substring(8).trim()); System.out.println("Encoding: "+javaEnc); //$NON-NLS-1$ return javaEnc; } } } catch(Exception e) { if(Constant.RUNNING_MODE == Constant.MODE_DEBUG){ e.printStackTrace(); } try { File log = File.createTempFile("error", ".log", new File("logs")); FileWriter writer = new FileWriter(log); PrintWriter print = new PrintWriter(writer); e.printStackTrace(print); writer.close(); print.close(); writer = null; print = null; } catch (IOException e2) { //do nothing } //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ return null; } // Encoding not declared. Assume OpenOffice and return its XML encoding return "UTF-8"; //$NON-NLS-1$ } private static String RTF2JavaEncoding(String encoding){ String[] codes = TextUtil.getPageCodes(); for (int h=0 ; h<codes.length ; h++) { if (codes[h].toLowerCase().indexOf("windows-" + encoding) != -1) { //$NON-NLS-1$ return codes[h]; } } if (encoding.equals("10000")) { //$NON-NLS-1$ for (int h=0 ; h<codes.length ; h++) { if (codes[h].toLowerCase().indexOf("macroman") != -1) { //$NON-NLS-1$ return codes[h]; } } } if (encoding.equals("10006")) { //$NON-NLS-1$ for (int h=0 ; h<codes.length ; h++) { if (codes[h].toLowerCase().indexOf("macgreek") != -1) { //$NON-NLS-1$ return codes[h]; } } } if (encoding.equals("10007")) { //$NON-NLS-1$ for (int h=0 ; h<codes.length ; h++) { if (codes[h].toLowerCase().indexOf("maccyrillic") != -1) { //$NON-NLS-1$ return codes[h]; } } } if (encoding.equals("10029")) { //$NON-NLS-1$ for (int h=0 ; h<codes.length ; h++) { if (codes[h].toLowerCase().indexOf("maccentraleurope") != -1) { //$NON-NLS-1$ return codes[h]; } } } if (encoding.equals("10079")) { //$NON-NLS-1$ for (int h=0 ; h<codes.length ; h++) { if (codes[h].toLowerCase().indexOf("maciceland") != -1) { //$NON-NLS-1$ return codes[h]; } } } if (encoding.equals("10081")) { //$NON-NLS-1$ for (int h=0 ; h<codes.length ; h++) { if (codes[h].toLowerCase().indexOf("macturkish") != -1) { //$NON-NLS-1$ return codes[h]; } } } if (encoding.equals("65000")) { //$NON-NLS-1$ for (int h=0 ; h<codes.length ; h++) { if (codes[h].toLowerCase().indexOf("utf-7") != -1) { //$NON-NLS-1$ return codes[h]; } } } if (encoding.equals("650001")) { //$NON-NLS-1$ for (int h=0 ; h<codes.length ; h++) { if (codes[h].toLowerCase().indexOf("utf-8") != -1) { //$NON-NLS-1$ return codes[h]; } } } if (encoding.equals("932")) { //$NON-NLS-1$ for (int h=0 ; h<codes.length ; h++) { if (codes[h].toLowerCase().indexOf("shift_jis") != -1) { //$NON-NLS-1$ return codes[h]; } } } if (encoding.equals("936")) { //$NON-NLS-1$ for (int h=0 ; h<codes.length ; h++) { if (codes[h].toLowerCase().indexOf("gbk") != -1) { //$NON-NLS-1$ return codes[h]; } } } if (encoding.equals("949")) { //$NON-NLS-1$ for (int h=0 ; h<codes.length ; h++) { if (codes[h].toLowerCase().indexOf("euc-kr") != -1) { //$NON-NLS-1$ return codes[h]; } } } if (encoding.equals("950")) { //$NON-NLS-1$ for (int h=0 ; h<codes.length ; h++) { if (codes[h].toLowerCase().indexOf("big5") != -1) { //$NON-NLS-1$ return codes[h]; } } } if (encoding.equals("1361")) { //$NON-NLS-1$ for (int h=0 ; h<codes.length ; h++) { if (codes[h].toLowerCase().indexOf("johab") != -1) { //$NON-NLS-1$ return codes[h]; } } } return null; } }
10,661
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
FileFormatUtils.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.ui/src/net/heartsome/cat/convert/ui/utils/FileFormatUtils.java
package net.heartsome.cat.convert.ui.utils; import java.io.File; import java.io.FileInputStream; import java.util.ArrayList; import java.util.List; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import net.heartsome.cat.common.core.IPreferenceConstants; import net.heartsome.cat.convert.ui.Activator; import net.heartsome.cat.convert.ui.model.ConverterViewModel; import net.heartsome.cat.converter.Converter; import net.heartsome.cat.converter.util.ConverterBean; import org.eclipse.core.runtime.Platform; import org.eclipse.core.runtime.preferences.IPreferencesService; /** * 文件格式相关辅助类。<br/> * 由于 R8 中采用 OSGI 服务的方式将转换器分割成单个插件,因而增加了此类来取代 R7 中的 FileFormats.java。<br/> * 用以在注册的转换器服务中获取转换器支持的文件类型名、文件拓展名等等。 * @author weachy * @version * @since JDK1.5 */ public class FileFormatUtils { private static ConverterBean allFileBean = new ConverterBean("All", "All", new String[] { "*.*" }); private static final ConverterViewModel MODEL = new ConverterViewModel(Activator.getContext(), Converter.DIRECTION_POSITIVE); /** * 得到支持的类型 * @return ; */ public static List<ConverterBean> getSupportTypes() { return MODEL.getSupportTypes(); } /** * 得到转换器支持的所有文件类型的拓展名 * @return ; */ public static String[] getExtensions() { List<ConverterBean> list = MODEL.getSupportTypes(); checkAutomaticOO(list); ArrayList<String> FileFormats = new ArrayList<String>(); for (ConverterBean bean : list) { String[] extensions = bean.getExtensions(); for (String extension : extensions) { FileFormats.add(extension); } } return FileFormats.toArray(new String[] {}); } /** * 得到所有文件格式 * @return ; */ public static String[] getFileFormats() { List<ConverterBean> list = MODEL.getSupportTypes(); checkAutomaticOO(list); String[] FileFormats = new String[list.size()]; for (int i = 0; i < list.size(); i++) { FileFormats[i] = list.get(i).getDescription(); } return FileFormats; } /** * 得到所有文件过滤拓展名。 * @return ; */ public static String[] getFilterExtensions() { List<ConverterBean> list = MODEL.getSupportTypes(); checkAutomaticOO(list); list.add(0, allFileBean); String[] FilterExtensions = new String[list.size()]; for (int i = 0; i < list.size(); i++) { FilterExtensions[i] = list.get(i).getFilterExtensions(); } return FilterExtensions; } /** * 得到所有文件过滤条件名。 * @return ; */ public static String[] getFilterNames() { List<ConverterBean> list = MODEL.getSupportTypes(); checkAutomaticOO(list); list.add(0, allFileBean); String[] filterNames = new String[list.size()]; for (int i = 0; i < list.size(); i++) { filterNames[i] = list.get(i).getFilterNames(); } return filterNames; } /** * 检查是否启用 Open Office */ private static void checkAutomaticOO(List<ConverterBean> list) { IPreferencesService service = Platform.getPreferencesService(); String qualifier = Activator.getDefault().getBundle().getSymbolicName(); boolean automaticOO = service.getBoolean(qualifier, IPreferenceConstants.AUTOMATIC_OO, false, null); if (!automaticOO) { list.remove(new ConverterBean("MS Office Document to XLIFF Conveter", null)); } } public static String[] formats = { "Adobe InDesign Interchange", //$NON-NLS-1$ "HTML Page", //$NON-NLS-1$ "JavaScript", //$NON-NLS-1$ "Java Properties", //$NON-NLS-1$ "MIF (Maker Interchange Format)", //$NON-NLS-1$ "Microsoft Office 2007 Document", //$NON-NLS-1$ "OpenOffice Document", //$NON-NLS-1$ "Plain Text", //$NON-NLS-1$ "PO (Portable Objects)", //$NON-NLS-1$ "RC (Windows C/C++ Resources)", //$NON-NLS-1$ "ResX (Windows .NET Resources)", //$NON-NLS-1$ "RTF (Rich Text Format)", //$NON-NLS-1$ "Tagged RTF", //$NON-NLS-1$ "TTX Document", //$NON-NLS-1$ "XML Document", //$NON-NLS-1$ "XML (Generic)" //$NON-NLS-1$ }; public final static String INX = formats[0]; public final static String HTML = formats[1]; public final static String JS = formats[2]; public final static String JAVA = formats[3]; public final static String MIF = formats[4]; public final static String OFF = formats[5]; public final static String OO = formats[6]; public final static String TEXT = formats[7]; public final static String PO = formats[8]; public final static String RC = formats[9]; public final static String RESX = formats[10]; public final static String RTF = formats[11]; public final static String TRTF = formats[12]; public final static String TTX = formats[13]; public final static String XML = formats[14]; public final static String XMLG = formats[15]; public static String detectFormat(String fileName) { File file = new File(fileName); if (!file.exists()) { return null; } try { FileInputStream input = new FileInputStream(file); byte[] array = new byte[40960]; input.read(array); input.close(); String string = ""; //$NON-NLS-1$ byte[] feff = { -1, -2 }; byte[] fffe = { -2, -1 }; // there may be a BOM, now check the order if (array[0] == fffe[0] && array[1] == fffe[1]) { string = new String(array, "UTF-16BE"); //$NON-NLS-1$ } else if (array[0] == feff[0] && array[1] == feff[1]) { string = new String(array, "UTF-16LE"); //$NON-NLS-1$ } else { string = new String(array); } if (string.startsWith("<MIFFile")) { //$NON-NLS-1$ return MIF; } if (string.startsWith("{\\rtf")) { //$NON-NLS-1$ // TODO check all header for Trados styles if (string.indexOf("tw4win") != -1) { //$NON-NLS-1$ return TRTF; } return RTF; } if (string.startsWith("<?xml") || string.startsWith('\uFEFF' + "<?xml") || string.startsWith('\uFFFE' + "<?xml")) { //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ if (string.indexOf("<TRADOStag ") != -1) { //$NON-NLS-1$ return TTX; } if (string.indexOf("<docu") != -1 && string.indexOf("<?aid ") != -1) { //$NON-NLS-1$ //$NON-NLS-2$ return INX; } if (string.indexOf("xmlns:msdata") != -1 && string.indexOf("<root") != -1) { //$NON-NLS-1$ //$NON-NLS-2$ return RESX; } return XML; } if (string.startsWith("<!DOCTYPE") || string.startsWith('\uFEFF' + "<!DOCTYPE") || string.startsWith('\uFFFE' + "<!DOCTYPE")) { //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ int index = string.indexOf("-//IETF//DTD HTML"); //$NON-NLS-1$ if (index != -1) { return HTML; } index = string.indexOf("-//W3C//DTD HTML"); //$NON-NLS-1$ if (index != -1) { return HTML; } return XML; } int index = string.toLowerCase().indexOf("<html"); //$NON-NLS-1$ if (index != -1) { return HTML; } if (string.indexOf("msgid") != -1 && string.indexOf("msgstr") != -1) { //$NON-NLS-1$ //$NON-NLS-2$ return PO; } if (string.startsWith("PK")) { //$NON-NLS-1$ // might be a zipped file ZipInputStream in = new ZipInputStream(new FileInputStream(file)); ZipEntry entry = null; boolean found = false; boolean hasXML = false; while ((entry = in.getNextEntry()) != null) { if (entry.getName().equals("content.xml")) { //$NON-NLS-1$ found = true; break; } if (entry.getName().matches(".*\\.xml")) { //$NON-NLS-1$ hasXML = true; } } in.close(); if (found) { return OO; } if (hasXML) { return OFF; } } if (string.indexOf("#include") != -1 || //$NON-NLS-1$ string.indexOf("#define") != -1 || //$NON-NLS-1$ string.indexOf("DIALOG") != -1 || //$NON-NLS-1$ string.indexOf("DIALOGEX") != -1 || //$NON-NLS-1$ string.indexOf("MENU") != -1 || //$NON-NLS-1$ string.indexOf("MENUEX") != -1 || //$NON-NLS-1$ string.indexOf("POPUP") != -1 || //$NON-NLS-1$ string.indexOf("STRINGTABLE") != -1 || //$NON-NLS-1$ string.indexOf("AUTO3STATE") != -1 || //$NON-NLS-1$ string.indexOf("AUTOCHECKBOX") != -1 || //$NON-NLS-1$ string.indexOf("AUTORADIOBUTTON") != -1 || //$NON-NLS-1$ string.indexOf("CHECKBOX") != -1 || //$NON-NLS-1$ string.indexOf("COMBOBOX") != -1 || //$NON-NLS-1$ string.indexOf("CONTROL") != -1 || //$NON-NLS-1$ string.indexOf("CTEXT") != -1 || //$NON-NLS-1$ string.indexOf("DEFPUSHBUTTON") != -1 || //$NON-NLS-1$ string.indexOf("GROUPBOX") != -1 || //$NON-NLS-1$ string.indexOf("ICON") != -1 || //$NON-NLS-1$ string.indexOf("LISTBOX") != -1 || //$NON-NLS-1$ string.indexOf("LTEXT") != -1 || //$NON-NLS-1$ string.indexOf("PUSHBOX") != -1 || //$NON-NLS-1$ string.indexOf("PUSHBUTTON") != -1 || //$NON-NLS-1$ string.indexOf("RADIOBUTTON") != -1 || //$NON-NLS-1$ string.indexOf("RTEXT") != -1 || //$NON-NLS-1$ string.indexOf("SCROLLBAR") != -1 || //$NON-NLS-1$ string.indexOf("STATE3") != -1) //$NON-NLS-1$ { return RC; } } catch (Exception e) { // do nothing } if (fileName.endsWith(".properties")) { //$NON-NLS-1$ return JAVA; } if (fileName.toLowerCase().endsWith(".rc")) { //$NON-NLS-1$ return RC; } if (fileName.endsWith(".txt")) { //$NON-NLS-1$ return TEXT; } if (fileName.endsWith(".js")) { //$NON-NLS-1$ return JS; } return null; } }
9,399
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
OpenReverseConversionDialogHandler.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.ui/src/net/heartsome/cat/convert/ui/handler/OpenReverseConversionDialogHandler.java
package net.heartsome.cat.convert.ui.handler; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.List; import net.heartsome.cat.common.ui.handlers.AbstractSelectProjectFilesHandler; import net.heartsome.cat.convert.ui.Activator; import net.heartsome.cat.convert.ui.model.ConverterViewModel; import net.heartsome.cat.convert.ui.model.IConversionItem; import net.heartsome.cat.convert.ui.wizard.ReverseConversionWizard; import net.heartsome.cat.converter.Converter; import net.heartsome.cat.converter.util.Progress; import org.eclipse.core.commands.ExecutionEvent; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IProject; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.Platform; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.dialogs.ProgressMonitorDialog; import org.eclipse.jface.operation.IRunnableWithProgress; import org.eclipse.jface.wizard.WizardDialog; /** * 打开转换文件配置对话框 * @author weachy * @since JDK1.5 */ public class OpenReverseConversionDialogHandler extends AbstractSelectProjectFilesHandler { public Object execute(ExecutionEvent event, List<IFile> list) { ArrayList<ConverterViewModel> converterViewModels = new ArrayList<ConverterViewModel>(); for (int i = 0; i < list.size(); i++) { Object adapter = Platform.getAdapterManager().getAdapter(list.get(i), IConversionItem.class); IConversionItem sourceItem = null; if (adapter instanceof IConversionItem) { sourceItem = (IConversionItem) adapter; } ConverterViewModel converterViewModel = new ConverterViewModel(Activator.getContext(), Converter.DIRECTION_REVERSE); converterViewModel.setConversionItem(sourceItem); // 记住所选择的文件 converterViewModels.add(converterViewModel); } IProject project = list.get(0).getProject(); ReverseConversionWizard wizard = new ReverseConversionWizard(converterViewModels, project); WizardDialog dialog = new WizardDialog(shell, wizard); int result = dialog.open(); if (result == IDialogConstants.OK_ID) { final List<ConverterViewModel> models = wizard.getConverterViewModels(); IRunnableWithProgress runnable = new IRunnableWithProgress() { public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { monitor.setTaskName("转换项目"); monitor.beginTask("转换项目中的 XLIFF 为目标文件...", models.size()); for (ConverterViewModel converterViewModel : models) { try { IProgressMonitor subMonitor = Progress.getSubMonitor(monitor, 1); subMonitor.setTaskName("开始转换文件:" + converterViewModel.getConversionItem().getLocation().toOSString()); converterViewModel.convertWithoutJob(subMonitor); } catch (Exception e) { MessageDialog.openError(shell, "文件转换失败", e.getMessage()); e.printStackTrace(); } } monitor.done(); } }; try { new ProgressMonitorDialog(shell).run(true, true, runnable); } catch (InvocationTargetException e) { MessageDialog.openError(shell, "文件转换失败", e.getMessage()); e.printStackTrace(); } catch (InterruptedException e) { MessageDialog.openError(shell, "文件转换失败", e.getMessage()); e.printStackTrace(); } } return null; } @Override public String[] getLegalFileExtensions() { return new String[] { "xlf" }; } }
3,544
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
PreviewTranslationHandler.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.ui/src/net/heartsome/cat/convert/ui/handler/PreviewTranslationHandler.java
package net.heartsome.cat.convert.ui.handler; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.List; import java.util.Map; import net.heartsome.cat.bean.Constant; import net.heartsome.cat.convert.ui.Activator; import net.heartsome.cat.convert.ui.model.ConversionConfigBean; import net.heartsome.cat.convert.ui.model.ConverterUtil; import net.heartsome.cat.convert.ui.model.ConverterViewModel; import net.heartsome.cat.convert.ui.model.IConversionItem; import net.heartsome.cat.convert.ui.utils.ConversionResource; import net.heartsome.cat.converter.Converter; import net.heartsome.cat.converter.ConverterException; import net.heartsome.cat.converter.util.Progress; import net.heartsome.cat.ts.core.file.XLFHandler; import org.eclipse.core.commands.AbstractHandler; import org.eclipse.core.commands.ExecutionEvent; import org.eclipse.core.commands.ExecutionException; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IFolder; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IWorkspaceRoot; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.Assert; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Path; import org.eclipse.core.runtime.Platform; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.dialogs.ProgressMonitorDialog; import org.eclipse.jface.operation.IRunnableWithProgress; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Shell; import org.eclipse.ui.IEditorInput; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.IEditorRegistry; import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.PartInitException; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.handlers.HandlerUtil; import org.eclipse.ui.ide.IDE; import org.eclipse.ui.ide.ResourceUtil; /** * 预览翻译 Handler * @author weachy * @version 1.1 * @since JDK1.5 */ public class PreviewTranslationHandler extends AbstractHandler { private IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); private Shell shell; public Object execute(ExecutionEvent event) throws ExecutionException { IEditorPart editor = HandlerUtil.getActiveEditor(event); if (editor == null) { return false; } IEditorInput input = editor.getEditorInput(); IFile file = ResourceUtil.getFile(input); shell = HandlerUtil.getActiveWorkbenchWindowChecked(event).getShell(); if (file == null) { MessageDialog.openInformation(shell, "提示", "未找当前编辑器打开的文件资源。"); } else { String fileExtension = file.getFileExtension(); if (fileExtension != null && "xlf".equalsIgnoreCase(fileExtension)) { ConverterViewModel model = getConverterViewModel(file); if (model != null) { model.convert(); } } else if (fileExtension != null && "xlp".equalsIgnoreCase(fileExtension)) { if (file.exists()) { IFolder xliffFolder = file.getProject().getFolder(Constant.FOLDER_XLIFF); if (xliffFolder.exists()) { ArrayList<IFile> files = new ArrayList<IFile>(); try { getChildFiles(xliffFolder, "xlf", files); } catch (CoreException e) { throw new ExecutionException(e.getMessage(), e); } previewFiles(files); } else { MessageDialog.openWarning(shell, "提示", "未找到系统默认的 XLIFF 文件夹!"); } } } else { MessageDialog.openInformation(shell, "提示", "当前编辑器打开的文件不是一个合法的 XLIFF 文件。"); } } return null; } /** * 预览翻译多个文件 * @param files * 文件集合 * @throws ExecutionException * ; */ private void previewFiles(final List<IFile> files) throws ExecutionException { IRunnableWithProgress runnable = new IRunnableWithProgress() { public void run(IProgressMonitor monitor) throws InvocationTargetException, InvocationTargetException { monitor.setTaskName("项目预览翻译"); monitor.beginTask("开始预翻译文件...", files.size()); for (IFile file : files) { IProgressMonitor subMonitor = Progress.getSubMonitor(monitor, 1); subMonitor.setTaskName("开始转换文件:" + file.getLocation().toOSString()); try { preview(file, subMonitor); // 预览单个文件 } catch (ExecutionException e) { throw new InvocationTargetException(e, e.getMessage()); } } monitor.done(); } }; try { new ProgressMonitorDialog(shell).run(true, true, runnable); } catch (InvocationTargetException e) { throw new ExecutionException(e.getMessage(), e); } catch (InterruptedException e) { throw new ExecutionException(e.getMessage(), e); } } /** * 预览单个文件 * @param file * IFile 对象 * @param subMonitor * 进度监视器 * @throws ExecutionException * ; */ private void preview(IFile file, IProgressMonitor subMonitor) throws ExecutionException { ConverterViewModel model = getConverterViewModel(file); if (model != null) { try { Map<String, String> result = model.convertWithoutJob(subMonitor); String targetFile = result.get(Converter.ATTR_TARGET_FILE); if (targetFile == null) { MessageDialog.openError(shell, "错误", "未找到已转换文件的路径!"); } else { final IFile input = root.getFileForLocation(new Path(targetFile)); Display.getDefault().syncExec(new Runnable() { public void run() { try { // 使用外部编辑器(系统默认编辑器)打开文件。 IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow() .getActivePage(); Assert.isNotNull(page, "当前的 Active Page 为 null。无法打开转换后的文件。"); IDE.openEditor(page, input, IEditorRegistry.SYSTEM_EXTERNAL_EDITOR_ID); } catch (PartInitException e) { MessageDialog.openInformation(shell, "提示", "转换完成!但是在尝试使用系统默认程序打开该文件时发生异常:\n" + e.getMessage()); e.printStackTrace(); } } }); } } catch (ConverterException e) { throw new ExecutionException(e.getMessage(), e); } } subMonitor.done(); } /** * 得到 ConverterViewModel 对象 * @param file * 需要预览翻译的文件 * @return * @throws ExecutionException * ; */ private ConverterViewModel getConverterViewModel(IFile file) throws ExecutionException { Object adapter = Platform.getAdapterManager().getAdapter(file, IConversionItem.class); if (adapter instanceof IConversionItem) { IConversionItem item = (IConversionItem) adapter; ConverterViewModel converterViewModel = new ConverterViewModel(Activator.getContext(), Converter.DIRECTION_REVERSE); // 逆向转换 converterViewModel.setConversionItem(item); try { ConversionResource resource = new ConversionResource(Converter.DIRECTION_REVERSE, item); String xliffpath = resource.getXliffPath(); String targetPath = resource.getPreviewPath(); ConversionConfigBean configBean = converterViewModel.getConfigBean(); configBean.setSource(xliffpath); configBean.setTarget(targetPath); configBean.setTargetEncoding("UTF-8"); configBean.setPreviewMode(true); // 设为预览翻译模式 IStatus status = converterViewModel.validateXliffFile(ConverterUtil.toLocalPath(xliffpath), new XLFHandler(), null); // 注:验证的过程中,会为文件类型和骨架文件的路径赋值。 if (status != null && status.isOK()) { return converterViewModel; } else { throw new ExecutionException(status.getMessage(), status.getException()); } } catch (CoreException e) { throw new ExecutionException(e.getMessage(), e); } } return null; } /** * 得到子文件 * @param folder * 文件夹 * @param fileExtension * 子文件后缀名 * @param list * 子文件集合 * @throws CoreException * ; */ public static void getChildFiles(IFolder folder, String fileExtension, List<IFile> list) throws CoreException { if (list == null) { list = new ArrayList<IFile>(); } if (folder.isAccessible() && folder.exists()) { IResource[] members = folder.members(); for (IResource resource : members) { if (resource instanceof IFile && (fileExtension).equalsIgnoreCase(resource.getFileExtension())) { list.add((IFile) resource); } else if (resource instanceof IFolder) { getChildFiles((IFolder) resource, fileExtension, list); } } } } }
8,776
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
OpenConversionDialogHandler.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.ui/src/net/heartsome/cat/convert/ui/handler/OpenConversionDialogHandler.java
package net.heartsome.cat.convert.ui.handler; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.List; import net.heartsome.cat.common.ui.handlers.AbstractSelectProjectFilesHandler; import net.heartsome.cat.convert.ui.Activator; import net.heartsome.cat.convert.ui.model.ConverterViewModel; import net.heartsome.cat.convert.ui.model.IConversionItem; import net.heartsome.cat.convert.ui.wizard.ConversionWizard; import net.heartsome.cat.converter.Converter; import net.heartsome.cat.converter.util.Progress; import org.eclipse.core.commands.ExecutionEvent; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IProject; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.Platform; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.dialogs.ProgressMonitorDialog; import org.eclipse.jface.operation.IRunnableWithProgress; import org.eclipse.jface.wizard.WizardDialog; /** * 打开项目转换文件配置对话框 * @author weachy * @since JDK1.5 */ public class OpenConversionDialogHandler extends AbstractSelectProjectFilesHandler { @Override public Object execute(ExecutionEvent event, List<IFile> list) { ArrayList<ConverterViewModel> converterViewModels = new ArrayList<ConverterViewModel>(); for (int i = 0; i < list.size(); i++) { Object adapter = Platform.getAdapterManager().getAdapter(list.get(i), IConversionItem.class); IConversionItem sourceItem = null; if (adapter instanceof IConversionItem) { sourceItem = (IConversionItem) adapter; } ConverterViewModel converterViewModel = new ConverterViewModel(Activator.getContext(), Converter.DIRECTION_POSITIVE); converterViewModel.setConversionItem(sourceItem); // 记住所选择的文件 converterViewModels.add(converterViewModel); } IProject project = list.get(0).getProject(); ConversionWizard wizard = new ConversionWizard(converterViewModels, project); WizardDialog dialog = new WizardDialog(shell, wizard); int result = dialog.open(); if (result == IDialogConstants.OK_ID) { final List<ConverterViewModel> models = wizard.getConverterViewModels(); IRunnableWithProgress runnable = new IRunnableWithProgress() { public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { monitor.setTaskName("转换项目"); monitor.beginTask("开始批量转换项目文件...", models.size()); for (ConverterViewModel converterViewModel : models) { try { IProgressMonitor subMonitor = Progress.getSubMonitor(monitor, 1); subMonitor.setTaskName("开始转换文件:" + converterViewModel.getConversionItem().getLocation().toOSString()); converterViewModel.convertWithoutJob(subMonitor); } catch (Exception e) { MessageDialog.openError(shell, "文件转换失败", e.getMessage()); e.printStackTrace(); } } monitor.done(); } }; try { new ProgressMonitorDialog(shell).run(true, true, runnable); } catch (InvocationTargetException e) { MessageDialog.openError(shell, "文件转换失败", e.getMessage()); e.printStackTrace(); } catch (InterruptedException e) { MessageDialog.openError(shell, "文件转换失败", e.getMessage()); e.printStackTrace(); } } return null; } @Override public String[] getLegalFileExtensions() { return null; } }
3,505
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
ConverterCommandTrigger.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.ui/src/net/heartsome/cat/convert/ui/command/ConverterCommandTrigger.java
package net.heartsome.cat.convert.ui.command; import java.util.Collections; import org.eclipse.core.commands.Command; import org.eclipse.core.commands.ExecutionEvent; import org.eclipse.core.commands.ExecutionException; import org.eclipse.core.commands.NotEnabledException; import org.eclipse.core.commands.NotHandledException; import org.eclipse.core.commands.common.NotDefinedException; import org.eclipse.core.expressions.EvaluationContext; import org.eclipse.core.expressions.IEvaluationContext; import org.eclipse.core.resources.IFile; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.ui.ISources; import org.eclipse.ui.IWorkbench; import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.commands.ICommandService; public class ConverterCommandTrigger { /** * 打开正转换对话框 * @param window * @param file * ; */ public static void openConversionDialog(IWorkbenchWindow window, IFile file) { openDialog(window, file, "net.heartsome.cat.convert.ui.commands.openConvertDialogCommand"); } /** * 打开逆转换对话框 * @param window * @param file * ; */ public static void openReverseConversionDialog(IWorkbenchWindow window, IFile file) { openDialog(window, file, "net.heartsome.cat.convert.ui.commands.openReverseConvertDialogCommand"); } private static void openDialog(IWorkbenchWindow window, IFile file, String commandId) { IWorkbench workbench = window.getWorkbench(); ICommandService commandService = (ICommandService) workbench.getService(ICommandService.class); Command command = commandService.getCommand(commandId); try { EvaluationContext context = new EvaluationContext(null, IEvaluationContext.UNDEFINED_VARIABLE); context.addVariable(ISources.ACTIVE_WORKBENCH_WINDOW_NAME, window); if (file != null) { StructuredSelection selection = new StructuredSelection(file); context.addVariable(ISources.ACTIVE_CURRENT_SELECTION_NAME, selection); } command.executeWithChecks(new ExecutionEvent(command, Collections.EMPTY_MAP, null, context)); } catch (ExecutionException e) { e.printStackTrace(); } catch (NotDefinedException e) { e.printStackTrace(); } catch (NotEnabledException e) { e.printStackTrace(); } catch (NotHandledException e) { e.printStackTrace(); } } }
2,333
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
JobRunnable.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.ui/src/net/heartsome/cat/convert/ui/job/JobRunnable.java
package net.heartsome.cat.convert.ui.job; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.jface.action.IAction; /** * 定义此接口来封装需要在 Job 中运行的代码 * @author cheney * @since JDK1.6 */ public interface JobRunnable { /** * 在 run 方法中包含所要执行的代码 * @param monitor * 监视器,可以为 NULL * @return 代码执行的结果; */ IStatus run(IProgressMonitor monitor); /** * 显示此 runnable 的运行结果,如直接弹出成功或失败对话框,主要用于进度显示对话框没有关闭的情况,即进度显示在模式对话框中。 * @param status * runnable 运行结果的 status; */ void showResults(IStatus status); /** * 用于显示 runnable 运行结果的 action,通常是 job 在后台运行完成后,通过在进度显示视图中触发相关的 action 链接来查看结果。 * @param status * runnable 运行结果的 status * @return 返回显示 runnable 运行结果的 action; */ IAction getRunnableCompletedAction(IStatus status); }
1,158
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
JobFactoryFacade.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.ui/src/net/heartsome/cat/convert/ui/job/JobFactoryFacade.java
package net.heartsome.cat.convert.ui.job; import net.heartsome.cat.convert.ui.ImplementationLoader; import org.eclipse.core.runtime.jobs.Job; import org.eclipse.swt.widgets.Display; /** * 创建 Job 的 factory facade * @author cheney * @since JDK1.6 */ public abstract class JobFactoryFacade { private static final JobFactoryFacade IMPL; static { IMPL = (JobFactoryFacade) ImplementationLoader.newInstance(JobFactoryFacade.class); } /** * 创建 Job * @param display * @param name * @param runnable * @return ; */ public static Job createJob(final Display display, final String name, final JobRunnable runnable) { return IMPL.createJobInternal(display, name, runnable); } /** * 创建 Job 的内部实现 * @param display * @param name * @param runnable * @return ; */ protected abstract Job createJobInternal(Display display, String name, JobRunnable runnable); }
913
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
ConverterNotFoundException.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.ui/src/net/heartsome/cat/convert/ui/model/ConverterNotFoundException.java
package net.heartsome.cat.convert.ui.model; import net.heartsome.cat.converter.ConverterException; import org.eclipse.core.runtime.IStatus; /** * 找不到所需转换器的需捕获异常 * @author cheney * @since JDK1.6 */ public class ConverterNotFoundException extends ConverterException { /** serialVersionUID. */ private static final long serialVersionUID = 1L; /** * 构造函数 * @param status */ public ConverterNotFoundException(IStatus status) { super(status); } }
500
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
ConverterContext.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.ui/src/net/heartsome/cat/convert/ui/model/ConverterContext.java
package net.heartsome.cat.convert.ui.model; import static net.heartsome.cat.converter.Converter.FALSE; import static net.heartsome.cat.converter.Converter.TRUE; import java.io.File; import java.net.URISyntaxException; import java.net.URL; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import net.heartsome.cat.converter.Converter; import org.eclipse.core.runtime.Platform; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * 在转换文件的过程,用于构建除用户(UI)设置的其他所需配置信息 * @author cheney * @since JDK1.6 */ public class ConverterContext { private static final Logger LOGGER = LoggerFactory.getLogger(ConverterContext.class); // 转换器相关配置文件顶层目录的名称 private static final String CONVERTER_ROOT_CONFIG_FOLDER_NAME = "net.heartsome.cat.converter"; /** * srx 目录 */ public static String srxFolder; // 文件路径分割符 private static String fileSeparator = System.getProperty("file.separator"); // 系统的配置文件夹路径 private URL configurationLocation; // 转换器相关配置文件所在的顶层目录 private String configurationFolderForConverter; // 转换 xliff 的配置 bean private ConversionConfigBean configBean; /** * catalogue 文件路径 */ public static String catalogue; // default srx 文件路径 public static String defaultSrx; // ini 目录路径 private String iniDir; static { URL temp = Platform.getConfigurationLocation().getURL(); if (temp != null) { String configurationPath = new File(temp.getPath()).getAbsolutePath(); String converterConfigurationPath = configurationPath + fileSeparator + CONVERTER_ROOT_CONFIG_FOLDER_NAME + fileSeparator; srxFolder = converterConfigurationPath + "srx" + fileSeparator; defaultSrx = srxFolder + "default_rules.srx"; catalogue = converterConfigurationPath + "catalogue" + fileSeparator + "catalogue.xml"; } } /** * 构建函数 * @param configBean * 用户在 UI 所设置的配置信息 */ public ConverterContext(ConversionConfigBean configBean) { this.configBean = configBean; configurationLocation = Platform.getConfigurationLocation().getURL(); if (configurationLocation != null) { try { String configurationPath = new File(configurationLocation.toURI()).getAbsolutePath(); configurationFolderForConverter = configurationPath + fileSeparator + CONVERTER_ROOT_CONFIG_FOLDER_NAME + fileSeparator; iniDir = configurationFolderForConverter + "ini"; } catch (URISyntaxException e) { e.printStackTrace(); } } } /** * 转换文件所需要的配置信息 * @return 返回转换文件所需要的配置信息; */ public Map<String, String> getConvertConfiguration() { Map<String, String> configuration = new HashMap<String, String>(); configuration.put(Converter.ATTR_SOURCE_FILE, ConverterUtil.toLocalPath(configBean.getSource())); configuration.put(Converter.ATTR_XLIFF_FILE, ConverterUtil.toLocalPath(configBean.getTarget())); configuration.put(Converter.ATTR_SKELETON_FILE, ConverterUtil.toLocalPath(configBean.getSkeleton())); configuration.put(Converter.ATTR_SOURCE_LANGUAGE, configBean.getSrcLang()); configuration.put(Converter.ATTR_TARGET_LANGUAGE, configBean.getTgtLang()); configuration.put(Converter.ATTR_SOURCE_ENCODING, configBean.getSrcEncoding()); boolean segByElement = configBean.isSegByElement(); configuration.put(Converter.ATTR_SEG_BY_ELEMENT, segByElement ? TRUE : FALSE); configuration.put(Converter.ATTR_INI_FILE, ConverterUtil.toLocalPath(configBean.getInitSegmenter())); String srx = configBean.getInitSegmenter(); if (srx == null || srx.trim().equals("")) { srx = defaultSrx; } configuration.put(Converter.ATTR_SRX, srx); configuration.put(Converter.ATTR_LOCK_XTRANS, configBean.isLockXtrans() ? TRUE : FALSE); configuration.put(Converter.ATTR_LOCK_100, configBean.isLock100() ? TRUE : FALSE); configuration.put(Converter.ATTR_LOCK_101, configBean.isLock101() ? TRUE : FALSE); configuration.put(Converter.ATTR_LOCK_REPEATED, configBean.isLockRepeated() ? TRUE : FALSE); configuration.put(Converter.ATTR_BREAKONCRLF, configBean.isBreakOnCRLF() ? TRUE : FALSE); configuration.put(Converter.ATTR_EMBEDSKL, configBean.isEmbedSkl() ? TRUE : FALSE); configuration = getCommonConvertConfiguration(configuration); if (LOGGER.isInfoEnabled()) { printConfigurationInfo(configuration); } return configuration; } /** * 逆转换文件所需要的配置信息 * @return 返回逆转换文件所需要的配置信息; */ public Map<String, String> getReverseConvertConfiguraion() { Map<String, String> configuration = new HashMap<String, String>(); configuration.put(Converter.ATTR_XLIFF_FILE, ConverterUtil.toLocalPath(configBean.getSource())); configuration.put(Converter.ATTR_TARGET_FILE, ConverterUtil.toLocalPath(configBean.getTarget())); configuration.put(Converter.ATTR_SKELETON_FILE, configBean.getSkeleton()); configuration.put(Converter.ATTR_SOURCE_ENCODING, configBean.getTargetEncoding()); configuration.put(Converter.ATTR_IS_PREVIEW_MODE, configBean.isPreviewMode() ? TRUE : FALSE); configuration = getCommonConvertConfiguration(configuration); if (LOGGER.isInfoEnabled()) { printConfigurationInfo(configuration); } return configuration; } /** * 设置通用的配置信息 * @param configuration * @return ; */ private Map<String, String> getCommonConvertConfiguration(Map<String, String> configuration) { configuration.put(Converter.ATTR_CATALOGUE, catalogue); configuration.put(Converter.ATTR_INIDIR, iniDir); // 设置 xml 转换器中需要用到的 program folder,指向程序的配置目录 configuration.put(Converter.ATTR_PROGRAM_FOLDER, configurationFolderForConverter); return configuration; } /** * 打印配置信息 * @param configuration */ private void printConfigurationInfo(Map<String, String> configuration) { Iterator<String> iterator = configuration.keySet().iterator(); StringBuffer buffer = new StringBuffer(); buffer.append("configuration:--------------------\n"); while (iterator.hasNext()) { String key = iterator.next(); String value = configuration.get(key); buffer.append("key:" + key + "--value:" + value + "\n"); } buffer.append("---------------------------------"); System.out.println(buffer.toString()); } }
6,444
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
ConverterUtil.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.ui/src/net/heartsome/cat/convert/ui/model/ConverterUtil.java
package net.heartsome.cat.convert.ui.model; import java.io.File; import org.eclipse.core.databinding.DataBindingContext; import org.eclipse.core.databinding.beans.BeansObservables; import org.eclipse.core.databinding.observable.value.IObservableValue; import org.eclipse.core.filesystem.URIUtil; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IWorkspaceRoot; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.Path; import org.eclipse.core.runtime.Platform; import org.eclipse.jface.databinding.viewers.IViewerObservableValue; import org.eclipse.jface.databinding.viewers.ViewersObservables; import org.eclipse.jface.viewers.ArrayContentProvider; import org.eclipse.jface.viewers.ComboViewer; import org.eclipse.jface.viewers.ViewerComparator; /** * @author cheney * @since JDK1.6 */ public final class ConverterUtil { private static final String PROPERTIES_NAME = "name"; private static final String PROPERTIES_SELECTED_TYPE = "selectedType"; private static IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); /** * 私有构建函数 */ private ConverterUtil() { // 防止创建实例 } /** * 对下拉列表和转换器列表进行绑定 * @param context * @param comboViewer * @param model * ; */ public static void bindValue(DataBindingContext context, ComboViewer comboViewer, ConverterViewModel model) { // ViewerSupport.bind(comboViewer, BeansObservables.observeList( // model, "supportTypes", String.class), // Properties.selfValue(String.class)); // // // context.bindValue(ViewersObservables // .observeSingleSelection(comboViewer), BeansObservables // .observeValue(model, // "selectedType")); // ObservableListContentProvider viewerContentProvider=new ObservableListContentProvider(); comboViewer.setContentProvider(new ArrayContentProvider()); comboViewer.setComparator(new ViewerComparator()); // IObservableMap[] attributeMaps = BeansObservables.observeMaps( // viewerContentProvider.getKnownElements(), // ConverterBean.class, new String[] { "description" }); // comboViewer.setLabelProvider(new ObservableMapLabelProvider( // attributeMaps)); // comboViewer.setInput(Observables.staticObservableList(model.getSupportTypes(),ConverterBean.class)); comboViewer.setInput(model.getSupportTypes()); IViewerObservableValue selection = ViewersObservables.observeSingleSelection(comboViewer); IObservableValue observableValue = BeansObservables.observeDetailValue(selection, PROPERTIES_NAME, null); context.bindValue(observableValue, BeansObservables.observeValue(model, PROPERTIES_SELECTED_TYPE)); } /** * 是否为工作空间内的路径 * @param workspacePath * @return ; */ private static boolean isWorkspacePath(String workspacePath) { IFile file = root.getFileForLocation(URIUtil.toPath(new File(workspacePath).toURI())); return file == null; } /** * 得到本地文件系统路径 * @param workspacePath * @return ; */ public static String toLocalPath(String workspacePath) { if (isWorkspacePath(workspacePath)) { IPath path = Platform.getLocation(); return path.append(workspacePath).toOSString(); } else { return workspacePath; } } /** * 得到本地文件。 * @param workspacePath * @return ; */ public static File toLocalFile(String workspacePath) { if (isWorkspacePath(workspacePath)) { IPath path = Platform.getLocation(); return path.append(workspacePath).toFile(); } else { return new File(workspacePath); } } }
3,616
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
DefaultConversionItem.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.ui/src/net/heartsome/cat/convert/ui/model/DefaultConversionItem.java
package net.heartsome.cat.convert.ui.model; import java.io.File; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.Path; import org.eclipse.core.runtime.jobs.ISchedulingRule; /** * 默认的转项目实现 * @author cheney * @since JDK1.6 */ public class DefaultConversionItem implements IConversionItem { /** * 空转换项目 */ public static final IConversionItem EMPTY_CONVERSION_ITEM = new DefaultConversionItem(Path.EMPTY); /** * 转换项目的路径 */ protected IPath path; /** * 相对于转换项目路径的上一层转换项目 */ protected IConversionItem parent; /** * 默认转换项目的构建函数 * @param path */ public DefaultConversionItem(IPath path) { this.path = path; } public void refresh() { // do nothing } public boolean contains(ISchedulingRule rule) { if (this == rule) { return true; } if (!(rule instanceof DefaultConversionItem)) { return false; } DefaultConversionItem defaultConversionItem = (DefaultConversionItem) rule; // 处理路径相同的情况 return path.equals(defaultConversionItem.path); } public boolean isConflicting(ISchedulingRule rule) { if (!(rule instanceof DefaultConversionItem)) { return false; } DefaultConversionItem defaultConversionItem = (DefaultConversionItem) rule; // 处理路径相同的情况 return path.equals(defaultConversionItem.path); } public IPath getLocation() { return path; } public IConversionItem getParent() { if (parent == null) { File temp = path.toFile().getParentFile(); if (temp != null) { parent = new DefaultConversionItem(new Path(temp.getAbsolutePath())); } } return parent; } public String getName() { return path.toFile().getName(); } public IConversionItem getProject() { return getParent(); } }
1,839
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
ConverterViewModel.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.ui/src/net/heartsome/cat/convert/ui/model/ConverterViewModel.java
package net.heartsome.cat.convert.ui.model; import java.io.File; import java.io.IOException; import java.util.Map; import net.heartsome.cat.bean.Constant; import net.heartsome.cat.convert.ui.Activator; import net.heartsome.cat.convert.ui.action.ConversionCompleteAction; import net.heartsome.cat.convert.ui.job.JobFactoryFacade; import net.heartsome.cat.convert.ui.job.JobRunnable; import net.heartsome.cat.convert.ui.wizard.Messages; import net.heartsome.cat.converter.Converter; import net.heartsome.cat.converter.ConverterException; import net.heartsome.cat.converter.util.ConverterTracker; import net.heartsome.cat.converter.util.ConverterUtils; import net.heartsome.cat.ts.core.file.XLFHandler; import org.eclipse.core.databinding.validation.ValidationStatus; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.OperationCanceledException; import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.jobs.Job; import org.eclipse.jface.action.IAction; import org.eclipse.swt.widgets.Display; import org.eclipse.ui.statushandlers.StatusManager; import org.osgi.framework.BundleContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * 在界面上显示转换器列表的 View Model * @author cheney,weachy * @since JDK1.5 */ public class ConverterViewModel extends ConverterTracker { private static final Logger LOGGER = LoggerFactory.getLogger(ConverterViewModel.class.getName()); private ConversionConfigBean configBean; private IConversionItem conversionItem; /** * UI 跟 转换器之间的 View Model * @param bundleContext * @param direction */ public ConverterViewModel(BundleContext bundleContext, String direction) { super(bundleContext, direction); configBean = new ConversionConfigBean(); } /** * 获得转换文件时存储配置信息的对象 * @return ; */ public ConversionConfigBean getConfigBean() { return configBean; } @Override public Map<String, String> convert(Map<String, String> parameters) { return convert(); } /** * 根据用户的选择和配置信息,执行文件的转换功能 * @return ; */ public Map<String, String> convert() { System.out.print(getConfigBean().toString()); // 以用户最后在配置对话框所选择的源文件为准 JobRunnable runnalbe = new JobRunnable() { private Map<String, String> conversionResult; public IStatus run(IProgressMonitor monitor) { IStatus result = Status.OK_STATUS; try { conversionResult = convertWithoutJob(monitor); } catch (OperationCanceledException e) { result = Status.CANCEL_STATUS; } catch (ConverterException e) { result = e.getStatus(); } finally { ConverterViewModel.this.close(); } return result; } public void showResults(IStatus status) { IAction action = getRunnableCompletedAction(status); if (action != null) { action.run(); } } public IAction getRunnableCompletedAction(IStatus status) { return new ConversionCompleteAction("文件转换", status, conversionResult); } }; Job conversionJob = JobFactoryFacade.createJob(Display.getDefault(), "conversion job", runnalbe); conversionJob.setUser(true); conversionJob.setRule(conversionItem.getProject()); conversionJob.schedule(); return null; } /** * 正向转换(只是转换的过程,未放入后台线程,未处理转换结果提示信息); * @param sourceItem * @param monitor * @return ; * @throws ConverterException */ public Map<String, String> convertWithoutJob(IProgressMonitor subMonitor) throws ConverterException { if (getDirection().equals(Converter.DIRECTION_POSITIVE)) { return convert(conversionItem, subMonitor); } else { return reverseConvert(conversionItem, subMonitor); } } /** * 正向转换 * @param sourceItem * @param monitor * @return ; */ private Map<String, String> convert(final IConversionItem sourceItem, IProgressMonitor monitor) throws ConverterException { Map<String, String> result = null; String sourcePathStr = configBean.getSource(); String targetFile = ConverterUtil.toLocalPath(configBean.getTarget()); String skeletonFile = ConverterUtil.toLocalPath(configBean.getSkeleton()); boolean convertSuccessful = false; File target = null; // 正向转换的目标文件,即 XLIFF 文件 File skeleton = null; // 骨架文件 try { target = new File(targetFile); if (!target.exists()) { try { File parent = target.getParentFile(); if (!parent.exists()) { parent.mkdirs(); } target.createNewFile(); } catch (IOException e) { if (LOGGER.isErrorEnabled()) { LOGGER.error("创建目标文件:" + targetFile + "失败。", e); } } } skeleton = new File(skeletonFile); if (!skeleton.exists()) { try { File parent = skeleton.getParentFile(); if (!parent.exists()) { parent.mkdirs(); } skeleton.createNewFile(); } catch (IOException e) { if (LOGGER.isErrorEnabled()) { LOGGER.error("创建骨架文件:" + skeletonFile + "失败。", e); } } } ConverterContext converterContext = new ConverterContext(configBean); final Map<String, String> configuration = converterContext.getConvertConfiguration(); Converter converter = getConverter(); if (converter == null) { // Build a message String message = "此源文件类型对应的转换器不存在:" + configBean.getFileType(); // Build a new IStatus IStatus status = new Status(IStatus.ERROR, Activator.PLUGIN_ID, message); throw new ConverterNotFoundException(status); } result = converter.convert(configuration, monitor); convertSuccessful = true; } catch (OperationCanceledException e) { // 捕获用户取消操作的异常 LOGGER.info("用户取消操作。", e); throw e; } catch (ConverterException e) { if (LOGGER.isErrorEnabled()) { LOGGER.error("转换文件:" + sourcePathStr + " 失败。", e); } throw e; } finally { // 在转换失败或用户取消转换时,清除目标文件和骨架文件 if (!convertSuccessful) { if (target != null && target.exists()) { target.delete(); } if (skeleton != null && skeleton.exists()) { skeleton.delete(); } } sourceItem.refresh(); } return result; } /** * 逆向转换 * @param sourceItem * @param monitor * @return ; */ private Map<String, String> reverseConvert(IConversionItem sourceItem, IProgressMonitor monitor) throws ConverterException { Map<String, String> result = null; String sourcePathStr = configBean.getSource(); String targetFile = ConverterUtil.toLocalPath(configBean.getTarget()); boolean convertSuccessful = false; File target = null; try { target = new File(targetFile); if (!target.exists()) { try { File parent = target.getParentFile(); if (!parent.exists()) { parent.mkdirs(); } target.createNewFile(); } catch (IOException e) { if (LOGGER.isErrorEnabled()) { LOGGER.error("创建目标文件:" + targetFile + "失败。", e); } } } Converter converter = getConverter(); if (converter == null) { // Build a message String message = "xliff 对应的源文件类型的转换器不存在:" + configBean.getFileType(); // Build a new IStatus IStatus status = new Status(IStatus.ERROR, Activator.PLUGIN_ID, message); throw new ConverterNotFoundException(status); } ConverterContext converterContext = new ConverterContext(configBean); final Map<String, String> configuration = converterContext.getReverseConvertConfiguraion(); result = converter.convert(configuration, monitor); convertSuccessful = true; } catch (OperationCanceledException e) { // 捕获用户取消操作的异常 LOGGER.info("用户取消操作。", e); throw e; } catch (ConverterNotFoundException e) { // Let the StatusManager handle the Status and provide a hint StatusManager.getManager().handle(e.getStatus(), StatusManager.LOG | StatusManager.SHOW); if (LOGGER.isErrorEnabled()) { LOGGER.error(e.getMessage(), e); } throw e; } catch (ConverterException e) { if (LOGGER.isErrorEnabled()) { LOGGER.error("转换文件:{}失败。", sourcePathStr, e); } throw e; } finally { if (!convertSuccessful) { // 在转换失败或用户取消转换时,清除目标文件和骨架文件 if (target != null && target.exists()) { target.delete(); } } sourceItem.refresh(); } return result; } /** * 验证 * @return ; */ public IStatus validate() { if (direction.equals(Converter.DIRECTION_POSITIVE)) { return validateConversion(); } else { return validateReverseConversion(); } } /** * 逆向转换验证 * @return ; */ private IStatus validateReverseConversion() { return configBean.validateReverseConversion(); } /** * 验证 xliff 所需要转换的 xliff 文件 * @param xliffPath * xliff 文件路径 * @param monitor * @return ; */ public IStatus validateXliffFile(String xliffPath, XLFHandler handler, IProgressMonitor monitor) { IStatus result = new ReverseConversionValidateWithLibrary3().validate(xliffPath, configBean, monitor); if (!result.isOK()) { return result; } // 验证是否存在 xliff 对应的源文件类型的转换器实现 String fileType = configBean.getFileType(); Converter converter = getConverter(fileType); if (converter != null) { result = validateFileNodeInXliff(handler, xliffPath, converter.getType()); // 验证 XLIFF 文件的 file 节点 if (!result.isOK()) { return result; } setSelectedType(fileType); result = Status.OK_STATUS; } else { result = ValidationStatus.error("xliff 对应的源文件类型的转换器不存在:" + fileType); } return result; } /** * 验证 XLIFF 文件中的 file 节点 * @param handler * XLFHandler 实例 * @param xliffPath * XLIFF 文件路径 * @param type * 文件类型,(Converter.getType() 的值,XLIIF 文件 file 节点的 datatype 属性值) * @return ; */ private IStatus validateFileNodeInXliff(XLFHandler handler, String xliffPath, String type) { handler.reset(); // 重置,以便重新使用。 Map<String, Object> resultMap = handler.openFile(xliffPath); if (resultMap == null || Constant.RETURNVALUE_RESULT_SUCCESSFUL != (Integer) resultMap.get(Constant.RETURNVALUE_RESULT)) { // 打开文件失败。 return ValidationStatus.error(Messages.getString("ConverterViewModel.0")); //$NON-NLS-1$ } try { int fileCount = handler.getFileCountInXliff(xliffPath); if (fileCount < 1) { // 不存在 file 节点。提示为不合法的 XLIFF return ValidationStatus.error(Messages.getString("ConverterViewModel.0")); //$NON-NLS-1$ } else if (fileCount > 1) { // 多个 file 节点,提示分割。 if (ConverterUtils.isOpenOfficeOrMSOffice2007(type)) { // 验证源文件是 OpenOffice 和 MSOffice 2007 的XLIFF 的 file 节点信息是否完整 return validateOpenOfficeOrMSOffice2007(handler, xliffPath); } return ValidationStatus.error(Messages.getString("ConverterViewModel.1")); //$NON-NLS-1$ } else { // 只有一个 file 节点 return Status.OK_STATUS; } } catch (Exception e) { // 当前打开了多个 XLIFF 文件,参看 XLFHandler.getFileCountInXliff() 方法 return ValidationStatus.error(Messages.getString("ConverterViewModel.1")); //$NON-NLS-1$ } } /** * 验证源文件是 OpenOffice 和 MSOffice 2007 的XLIFF 的 file 节点信息是否完整 * @param handler * @param path * @return ; */ private IStatus validateOpenOfficeOrMSOffice2007(XLFHandler handler, String path) { if (!handler.validateMultiFileNodes(path)) { return ValidationStatus.error("XLIFF 文件中 “document” 属性组(prop-group)信息缺失或者不完整,无法转换。"); } return Status.OK_STATUS; } /** * 正向转换验证 * @return ; */ private IStatus validateConversion() { if (selectedType == null || selectedType.trim().equals("")) { return ValidationStatus.error("请选择文件类型。"); } return configBean.validateConversion(); } /** * 在导航视图中所选择的文件 * @param file * ; */ public void setConversionItem(IConversionItem file) { this.conversionItem = file; } /** * 在导航视图中所选择的文件 * @return ; */ public IConversionItem getConversionItem() { return conversionItem; } }
12,687
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
ReverseConversionValidateWithLibrary3.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.ui/src/net/heartsome/cat/convert/ui/model/ReverseConversionValidateWithLibrary3.java
package net.heartsome.cat.convert.ui.model; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.text.MessageFormat; import java.util.Iterator; import java.util.List; import java.util.Vector; import javax.xml.parsers.ParserConfigurationException; import net.heartsome.cat.convert.ui.wizard.Messages; import net.heartsome.cat.converter.util.Progress; import net.heartsome.xml.Catalogue; import net.heartsome.xml.Document; import net.heartsome.xml.Element; import net.heartsome.xml.SAXBuilder; import net.heartsome.xml.XMLOutputter; import org.eclipse.core.databinding.validation.ValidationStatus; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.w3c.dom.Node; import org.xml.sax.SAXException; /** * 使用 heartsome library 3 对文件的逆转换进行验证 * @author cheney * @since JDK1.6 */ public class ReverseConversionValidateWithLibrary3 implements ConversionValidateStrategy { private static final Logger LOGGER = LoggerFactory.getLogger(ReverseConversionValidateWithLibrary3.class); private SAXBuilder builder; private Document doc; private Element root; private List<Element> segments = new Vector<Element>(); // 从 xliff 文件的 file 节点获取目标语言 private String targetLanguage; // 文件类型 private String dataType; // 骨架文件路径 private String skl; public IStatus validate(String path, ConversionConfigBean configuraion, IProgressMonitor monitor) { long start = System.currentTimeMillis(); LOGGER.info("开始分析 xliff 文件,当前时间为:{}", start); IStatus result = null; monitor = Progress.getMonitor(monitor); monitor.beginTask("正在分析 xliff 文件...", 4); String xliffFile = path; try { if (monitor.isCanceled()) { return Status.CANCEL_STATUS; } long startTime = 0; if (LOGGER.isInfoEnabled()) { File temp = new File(xliffFile); if (temp.exists()) { LOGGER.info("分析的 xliff 文件大小为(bytes):{}", temp.length()); } startTime = System.currentTimeMillis(); LOGGER.info("开始加载 xliff 文件,当前时间为:{}", startTime); } // 验证所需要转换的 xliff 文件 readXliff(xliffFile); monitor.worked(1); long endTime = 0; if (LOGGER.isInfoEnabled()) { endTime = System.currentTimeMillis(); LOGGER.info("加载 xliff 文件结束,当前时间为:{}", endTime); LOGGER.info("加载 xliff 用时:{}", (endTime - startTime)); } if (monitor.isCanceled()) { return Status.CANCEL_STATUS; } if (LOGGER.isInfoEnabled()) { startTime = System.currentTimeMillis(); LOGGER.info("开始处理获得 skeleton 文件的逻辑,当前时间为:{}", startTime); } // 获取骨架文件路径 skl = getSkeleton(); monitor.worked(1); if (LOGGER.isInfoEnabled()) { endTime = System.currentTimeMillis(); LOGGER.info("获得 skeleton 文件结束,当前时间为:{}", endTime); LOGGER.info("获得 skeleton 文件用时:{}", (endTime - startTime)); } if (skl != null && !skl.equals("")) { //$NON-NLS-1$ File sklFile = new File(skl); if (!sklFile.exists()) { return ValidationStatus.error("xliff 文件对应的骨架文件不存在。"); } } // 设置骨架文件的路径 configuraion.setSkeleton(skl); if (monitor.isCanceled()) { return Status.CANCEL_STATUS; } if (LOGGER.isInfoEnabled()) { startTime = System.currentTimeMillis(); LOGGER.info("开始创建 segments 列表,当前时间为:{}", startTime); } createList(root); monitor.worked(1); if (LOGGER.isInfoEnabled()) { endTime = System.currentTimeMillis(); LOGGER.info("创建 segments 列表结束,当前时间为:{}", endTime); LOGGER.info("创建 segments 列表用时:{}", (endTime - startTime)); } if (monitor.isCanceled()) { return Status.CANCEL_STATUS; } // TODO 确认为什么需要创建一个 xliff 文件副本,并需要确认什么时候删除此副本 File tmpXLFFile = File.createTempFile("tmpXLF", ".xlf"); //$NON-NLS-1$ //$NON-NLS-2$ reBuildXlf(tmpXLFFile); // 设置文件类型 configuraion.setFileType(dataType); result = Status.OK_STATUS; monitor.worked(1); long end = System.currentTimeMillis(); if (LOGGER.isInfoEnabled()) { LOGGER.info("分析 xliff 文件结束,当前时间为:{}", end); LOGGER.info("分析 xliff 文件总用时:{}", (end - start)); } } catch (Exception e) { // TODO 需要针对不同的异常返回不能的提示信息 String messagePattern = "分析{0}失败。"; String message = MessageFormat.format(messagePattern, new Object[] { xliffFile }); LOGGER.error(message, e); result = ValidationStatus.error("分析 xliff 文件失败。", e); } finally { if (segments != null) { segments = null; } if (root != null) { root = null; } if (doc != null) { doc = null; } if (builder != null) { builder = null; } monitor.done(); } return result; } /** * @param xliff *  xliff 文件的路径 * @throws ParserConfigurationException * @throws IOException * @throws SAXException */ private void readXliff(String xliff) throws SAXException, IOException, ParserConfigurationException { builder = new SAXBuilder(); builder.setEntityResolver(new Catalogue(ConverterContext.catalogue)); doc = builder.build(xliff); root = doc.getRootElement(); Element file = root.getChild("file"); //$NON-NLS-1$ dataType = file.getAttributeValue("datatype"); //$NON-NLS-1$ targetLanguage = file.getAttributeValue("target-language", Messages.getString("ReverseConversionValidateWithLibrary3.0")); //$NON-NLS-1$ //$NON-NLS-2$ } /** * 构建 xliff 文件副本 * @param tmpXLFFile * @throws IOException * ; */ private void reBuildXlf(File tmpXLFFile) throws IOException { long startTime = 0; if (LOGGER.isInfoEnabled()) { startTime = System.currentTimeMillis(); LOGGER.info("在重写 xliff 文件的过程中,对 segments 列表的处理开始,当前时间为:{}", startTime); } for (int i = 0, size = segments.size() - 1; i < size; i++) { Element e = segments.get(i); Element src = e.getChild("source"); //$NON-NLS-1$ Element tgt = e.getChild("target"); //$NON-NLS-1$ boolean isApproved = e.getAttributeValue("approved", "no").equalsIgnoreCase("yes"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ List<Node> srcList = src.getContent(); Vector<Node> tmp = new Vector<Node>(); for (int j = 0, jSize = srcList.size(); j < jSize; j++) { Node o = srcList.get(j); if (o.getNodeType() == Node.ELEMENT_NODE && o.getNodeName().equals("ph")) { //$NON-NLS-1$ Element el = new Element(o); if (el.getAttributeValue("id", "").startsWith("hs-merge")) { //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ String tmpMergeId = el.getAttributeValue("id", "").substring(8); //$NON-NLS-1$ //$NON-NLS-2$ String[] pairId = tmpMergeId.split("~"); //$NON-NLS-1$ srcList.remove(j); j--; jSize--; int idIndex = pairId[0].indexOf("-"); //$NON-NLS-1$ if (idIndex != -1) { pairId[0] = pairId[0].substring(0, idIndex); } idIndex = pairId[1].indexOf("-"); //$NON-NLS-1$ if (idIndex != -1) { pairId[1] = pairId[1].substring(0, idIndex); } if (!pairId[0].equals(pairId[1])) { pairId = null; break; } pairId = null; } else { srcList.remove(j); j--; jSize--; tmp.add(o); } } else { srcList.remove(j); j--; jSize--; tmp.add(o); } } src.removeAllChildren(); src.setContent(tmp); tmp = null; if (tgt == null) { tgt = new Element("target", doc); //$NON-NLS-1$ tgt.setAttribute(Messages.getString("ReverseConversionValidateWithLibrary3.1"), targetLanguage); //$NON-NLS-1$ tgt.setAttribute("state", "new"); //$NON-NLS-1$ //$NON-NLS-2$ List<Element> content = e.getChildren(); Vector<Element> newContent = new Vector<Element>(); for (int m = 0; m < content.size(); m++) { Element tmpEl = content.get(m); newContent.add(tmpEl); if (tmpEl.getName().equals("source")) { //$NON-NLS-1$ newContent.add(tgt); } tmpEl = null; } e.setContent(newContent); newContent = null; content = null; } List<Node> tgtList = tgt.getContent(); tmp = new Vector<Node>(); for (int j = 0, jSize = tgtList.size(); j < jSize; j++) { Node o = tgtList.get(j); if (o.getNodeType() == Node.ELEMENT_NODE && o.getNodeName().equals("ph")) { //$NON-NLS-1$ Element el = new Element(o); if (el.getAttributeValue("id", "").startsWith("hs-merge")) { //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ String tmpMergeId = el.getAttributeValue("id", "").substring(8); //$NON-NLS-1$ //$NON-NLS-2$ String[] pairId = tmpMergeId.split("~"); //$NON-NLS-1$ tgtList.remove(j); j--; jSize--; int idIndex = pairId[0].indexOf("-"); //$NON-NLS-1$ if (idIndex != -1) { pairId[0] = pairId[0].substring(0, idIndex); } idIndex = pairId[1].indexOf("-"); //$NON-NLS-1$ if (idIndex != -1) { pairId[1] = pairId[1].substring(0, idIndex); } if (!pairId[0].equals(pairId[1])) { pairId = null; break; } pairId = null; } else { tgtList.remove(j); j--; jSize--; tmp.add(o); } el = null; } else { tgtList.remove(j); j--; jSize--; tmp.add(o); } } tgt.removeAllChildren(); tgt.setContent(tmp); tmp = null; Element nextEl = segments.get(i + 1); if (!isApproved && srcList.size() > 0) { nextEl.setAttribute("approved", "no"); //$NON-NLS-1$ //$NON-NLS-2$ } Element nextSrc = nextEl.getChild("source"); //$NON-NLS-1$ Element nextTgt = nextEl.getChild("target"); //$NON-NLS-1$ if (nextTgt == null) { nextTgt = new Element("target", doc); //$NON-NLS-1$ nextTgt.setAttribute("xml:lang", targetLanguage); //$NON-NLS-1$ nextTgt.setAttribute("state", "new"); //$NON-NLS-1$ //$NON-NLS-2$ List<Element> content = nextEl.getChildren(); Vector<Element> newContent = new Vector<Element>(); for (int m = 0; m < content.size(); m++) { Element tmpEl = content.get(m); newContent.add(tmpEl); if (tmpEl.getName().equals("source")) { //$NON-NLS-1$ newContent.add(nextTgt); } tmpEl = null; } nextEl.setContent(newContent); newContent = null; content = null; } List<Node> nextSrcContent = nextSrc.getContent(); List<Node> nextTgtContent = nextTgt.getContent(); nextSrc.removeAllChildren(); Vector<Node> newNextSrcContent = new Vector<Node>(); newNextSrcContent.addAll(srcList); for (int j = 0, jSize = nextSrcContent.size(); j < jSize; j++) { newNextSrcContent.add(nextSrcContent.get(j)); } nextSrc.setContent(newNextSrcContent); newNextSrcContent = null; nextTgt.removeAllChildren(); Vector<Node> newNextTgtContent = new Vector<Node>(); newNextTgtContent.addAll(tgtList); for (int j = 0, jSize = nextTgtContent.size(); j < jSize; j++) { newNextTgtContent.add(nextTgtContent.get(j)); } nextTgt.setContent(newNextTgtContent); newNextTgtContent = null; } long endTime = 0; if (LOGGER.isInfoEnabled()) { endTime = System.currentTimeMillis(); LOGGER.info("在重写 xliff 文件的过程中,对 segments 列表的处理结束,当前时间为:{}", endTime); LOGGER.info("在重写 xliff 文件的过程中,对 segments 列表的处理用时:{}", (endTime - startTime)); } XMLOutputter outputter = new XMLOutputter(); outputter.preserveSpace(true); FileOutputStream out; out = new FileOutputStream(tmpXLFFile); if (LOGGER.isInfoEnabled()) { startTime = System.currentTimeMillis(); LOGGER.info("在重写 xliff 文件的过程中,开始调用 XMLOutputter 的 output 方法,当前时间为:{}", startTime); } outputter.output(doc, out); if (LOGGER.isInfoEnabled()) { endTime = System.currentTimeMillis(); LOGGER.info("在重写 xliff 文件的这程中,调用 XMLOutputter 的 output 方法结束,当前时间为:{}", endTime); LOGGER.info("在重写 xliff 文件的这程中,调用 XMLOutputter 的 output 方法用时:{}", (endTime - startTime)); } out.close(); outputter = null; } /** * 创建翻译节点列表 * @param rootPara * ; */ private void createList(Element rootPara) { List<Element> files = rootPara.getChildren(); Iterator<Element> it = files.iterator(); while (it.hasNext()) { Element el = it.next(); if (el.getName().equals("trans-unit")) { //$NON-NLS-1$ segments.add(el); } else { createList(el); } } } /** * 获取骨架文件 * @return 骨架文件路径 * @throws IOException * 在读取骨架文件失败时抛出 IO 异常 ; */ private String getSkeleton() throws IOException { String result = ""; //$NON-NLS-1$ Element file = root.getChild("file"); //$NON-NLS-1$ Element header = null; String encoding = ""; if (file != null) { header = file.getChild("header"); //$NON-NLS-1$ if (header != null) { // 添加源文件编码的读取 List<Element> propGroups = header.getChildren("hs:prop-group"); //$NON-NLS-1$ for (int i = 0; i < propGroups.size(); i++) { Element prop = propGroups.get(i); if (prop.getAttributeValue("name").equals("encoding")) { //$NON-NLS-1$ //$NON-NLS-2$ encoding = prop.getText().trim(); break; } } if (encoding.equals("utf-8")) { //$NON-NLS-1$ encoding = "UTF-8"; //$NON-NLS-1$ } Element mskl = header.getChild("skl"); //$NON-NLS-1$ if (mskl != null) { Element external = mskl.getChild("external-file"); //$NON-NLS-1$ if (external != null) { result = external.getAttributeValue("href"); //$NON-NLS-1$ result = result.replaceAll("&amp;", "&"); //$NON-NLS-1$ //$NON-NLS-2$ result = result.replaceAll("&lt;", "<"); //$NON-NLS-1$ //$NON-NLS-2$ result = result.replaceAll("&gt;", ">"); //$NON-NLS-1$ //$NON-NLS-2$ result = result.replaceAll("&apos;", "\'"); //$NON-NLS-1$ //$NON-NLS-2$ result = result.replaceAll("&quot;", "\""); //$NON-NLS-1$ //$NON-NLS-2$ } else { Element internal = mskl.getChild("internal-file"); //$NON-NLS-1$ if (internal != null) { File tmp = File.createTempFile("internal", ".skl", new File("skl")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ tmp.deleteOnExit(); FileOutputStream out = new FileOutputStream(tmp); List<Node> content = internal.getContent(); for (int i = 0; i < content.size(); i++) { Node n = content.get(i); if (n.getNodeType() == Node.TEXT_NODE) { out.write(n.getNodeValue().getBytes(encoding)); } else if (n.getNodeType() == Node.CDATA_SECTION_NODE) { // fixed bub 515 by john. String cdataString = n.getNodeValue(); if (cdataString.endsWith("]]")) { //$NON-NLS-1$ cdataString += ">"; //$NON-NLS-1$ } out.write(cdataString.getBytes(encoding)); } } out.close(); return tmp.getAbsolutePath(); } return result; } external = null; mskl = null; } else { return result; } } else { return result; } } else { return result; } if (encoding != null) { if (encoding.equals("")) { //$NON-NLS-1$ List<Element> groups = header.getChildren("hs:prop-group"); //$NON-NLS-1$ for (int i = 0; i < groups.size(); i++) { Element group = groups.get(i); List<Element> props = group.getChildren("hs:prop"); //$NON-NLS-1$ for (int k = 0; k < props.size(); k++) { Element prop = props.get(k); if (prop.getAttributeValue("prop-type", "").equals("encoding")) { //$NON-NLS-1$ encoding = prop.getText(); } } } } } header = null; file = null; return result; } }
16,251
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
IConversionItem.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.ui/src/net/heartsome/cat/convert/ui/model/IConversionItem.java
package net.heartsome.cat.convert.ui.model; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.jobs.ISchedulingRule; /** * 转换过程中表示源、目标或骨架等的转换项目,具体的实现可以是文件或其他形式,定义此接口的目的是适配 org.eclipse.core.resources 中 的 IFile 等接口,org.eclipse.core.resources * 不包含在 RAP 目标平台中,且 org.eclipse.core.resources 的实现不是多用户的,所以不建议把 org.eclipse.core.resources 及其依赖放到 RAP 平台中直接使用。同时实现 * ISchedulingRule 接口定义资源的访问规则。 * @author cheney */ public interface IConversionItem extends ISchedulingRule { /** * 刷新 conversion item ; */ void refresh(); /** * @return 返回此转换项目的位置; */ IPath getLocation(); /** * 获得转换项目的父 * @return ; */ IConversionItem getParent(); /** * 获得转换项目所在的项目,如果转换项目不在工作空间中,则直接返回其上一层转换项目 * @return ; */ IConversionItem getProject(); /** * 获得转换项目的名称 * @return ; */ String getName(); }
1,188
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
ConversionConfigBean.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.ui/src/net/heartsome/cat/convert/ui/model/ConversionConfigBean.java
package net.heartsome.cat.convert.ui.model; import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.List; import net.heartsome.cat.common.locale.Language; import net.heartsome.cat.common.locale.LocaleService; import net.heartsome.cat.common.util.CommonFunctions; import net.heartsome.cat.convert.ui.utils.FileFormatUtils; import net.heartsome.cat.converter.util.AbstractModelObject; import org.eclipse.core.databinding.validation.ValidationStatus; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; /** * 在转换 xliff 文件时,转换设置对话框中可设置参数对应的实体 bean * @author cheney * @since JDK1.6 */ public class ConversionConfigBean extends AbstractModelObject { // 源文件的路径 private String source; // 目标文件路径 private String target; // 骨架文件路径 private String skeleton; // 源文件语言 private String srcLang; // 目标语言 private String tgtLang; // 源文件编码 private String srcEncoding; // 目标文件编码 private String targetEncoding; // 是否按段茖分段 private boolean segByElement; // SRX 规则文件路径 private String initSegmenter; // 是否标记为不可翻译 private boolean lockXtrans; // 是否为 100% 匹配的文本进行进行标记 private boolean lock100; // 是否为上下文匹配的文本进行进行标记 private boolean lock101; // 是否为重复的文本段进行标记 private boolean lockRepeated; // 是否按 CR/LF 分段 private boolean breakOnCRLF; // 将骨架嵌入 xliff 文件 private boolean embedSkl; // 如果目标文件已存在,是否覆盖 private boolean replaceTarget; // 预览模式 private boolean previewMode; // 文件格式 private List<String> fileFormats; // 编码列表 private List<String> pageEncoding; // 目标语言列表 private List<Language> tgtLangList; // 语言列表 private List<Language> languages; // 文件类型 private String fileType; /** * 文件类型 * @return ; */ public String getFileType() { return fileType; } /** * 文件类型 * @param fileType * ; */ public void setFileType(String fileType) { firePropertyChange("fileType", this.fileType, this.fileType = fileType); } /** * 语言列表 * @return ; */ public List<Language> getLanguages() { if (languages == null) { languages = new ArrayList<Language>(LocaleService.getDefaultLanguage().values()); Collections.sort(languages, new Comparator<Language>() { public int compare(Language o1, Language o2) { return o1.toString().compareTo(o2.toString()); } }); } return languages; } /** * 语言列表 * @param languages * ; */ public void setLanguages(List<Language> languages) { this.languages = languages; } /** * 编码列表 * @return ; */ public List<String> getPageEncoding() { if (pageEncoding == null) { String[] codeArray = LocaleService.getPageCodes(); pageEncoding = Arrays.asList(codeArray); } return pageEncoding; } /** * 编码列表 * @param pageEncoding * ; */ public void setPageEncoding(List<String> pageEncoding) { this.pageEncoding = pageEncoding; } /** * 将骨架嵌入 xliff 文件 * @return ; */ public boolean isEmbedSkl() { return embedSkl; } /** * 将骨架嵌入 xliff 文件 * @param embedSkl * ; */ public void setEmbedSkl(boolean embedSkl) { this.embedSkl = embedSkl; } /** * 源文件的路径 * @return ; */ public String getSource() { return source; } /** * 源文件的路径 * @param source * ; */ public void setSource(String source) { firePropertyChange("source", this.source, this.source = source); } /** * 目标文件路径 * @return ; */ public String getTarget() { return target; } /** * 目标文件路径 * @param target * ; */ public void setTarget(String target) { firePropertyChange("target", this.target, this.target = target); } /** * 骨架文件路径 * @return ; */ public String getSkeleton() { return skeleton; } /** * 骨架文件路径 * @param skeleton * ; */ public void setSkeleton(String skeleton) { this.skeleton = skeleton; } /** * 源文件语言 * @return ; */ public String getSrcLang() { return srcLang; } /** * 源文件语言 * @param srcLang * ; */ public void setSrcLang(String srcLang) { firePropertyChange("srcLang", this.srcLang, this.srcLang = srcLang); } /** * 目标语言 * @return the tgtLang */ public String getTgtLang() { if(tgtLang == null){ tgtLang = ""; } return tgtLang; } /** * 目标语言 * @param tgtLang * the tgtLang to set */ public void setTgtLang(String tgtLang) { firePropertyChange("tgtLang", this.tgtLang, this.tgtLang = tgtLang); } /** @return 目标语言 */ public List<Language> getTgtLangList() { return tgtLangList; } /** * 目标语言 * @param tgtLang * the tgtLang to set */ public void setTgtLangList(List<Language> tgtLangList) { this.tgtLangList = tgtLangList; } /** * 源文件编码 * @return ; */ public String getSrcEncoding() { return srcEncoding; } /** * 源文件编码 * @param srcEncoding * ; */ public void setSrcEncoding(String srcEncoding) { firePropertyChange("srcEncoding", this.srcEncoding, this.srcEncoding = srcEncoding); } /** * 是否按段茖分段 * @return ; */ public boolean isSegByElement() { return segByElement; } /** * 是否按段茖分段 * @param segByElement * ; */ public void setSegByElement(boolean segByElement) { this.segByElement = segByElement; } /** * SRX 规则文件路径 * @return ; */ public String getInitSegmenter() { return initSegmenter; } /** * SRX 规则文件路径 * @param initSegmenter * ; */ public void setInitSegmenter(String initSegmenter) { firePropertyChange("initSegmenter", this.initSegmenter, this.initSegmenter = initSegmenter); } /** * 是否标记为不可翻译 * @return ; */ public boolean isLockXtrans() { return lockXtrans; } /** * 是否标记为不可翻译 * @param lockXtrans * ; */ public void setLockXtrans(boolean lockXtrans) { this.lockXtrans = lockXtrans; } /** * 是否为 100% 匹配的文本进行进行标记 * @return ; */ public boolean isLock100() { return lock100; } /** * 是否为 100% 匹配的文本进行进行标记 * @param lock100 * ; */ public void setLock100(boolean lock100) { this.lock100 = lock100; } /** * 是否为上下文匹配的文本进行进行标记 * @return ; */ public boolean isLock101() { return lock101; } /** * 是否为上下文匹配的文本进行进行标记 * @param lock101 * ; */ public void setLock101(boolean lock101) { this.lock101 = lock101; } /** * 是否为上下文匹配的文本进行进行标记 * @return ; */ public boolean isLockRepeated() { return lockRepeated; } /** * 是否为上下文匹配的文本进行进行标记 * @param lockRepeated * ; */ public void setLockRepeated(boolean lockRepeated) { this.lockRepeated = lockRepeated; } /** * 是否按 CR/LF 分段 * @return ; */ public boolean isBreakOnCRLF() { return breakOnCRLF; } /** * 是否按 CR/LF 分段 * @param breakOnCRLF * ; */ public void setBreakOnCRLF(boolean breakOnCRLF) { this.breakOnCRLF = breakOnCRLF; } /** * 目标文件编码 * @param targetEncoding * ; */ public void setTargetEncoding(String targetEncoding) { firePropertyChange("targetEncoding", this.targetEncoding, this.targetEncoding = targetEncoding); } /** * 目标文件编码 * @return ; */ public String getTargetEncoding() { return targetEncoding; } @Override public String toString() { StringBuffer buffer = new StringBuffer(); buffer.append("configuration:--------------------\n"); buffer.append("source:" + getSource() + "\n"); buffer.append("target:" + getTarget() + "\n"); buffer.append("skeleton:" + getSkeleton() + "\n"); buffer.append("srclang:" + getSrcLang() + "\n"); buffer.append("tgtlang:" + getTgtLang() + "\n"); buffer.append("srcEncoding:" + getSrcEncoding() + "\n"); buffer.append("targetEncoding:" + getTargetEncoding() + "\n"); buffer.append("segByElement:" + isSegByElement() + "\n"); buffer.append("initSegmenter:" + getInitSegmenter() + "\n"); buffer.append("lockXtrans:" + isLockXtrans() + "\n"); buffer.append("lock100:" + isLock100() + "\n"); buffer.append("lock101:" + isLock101() + "\n"); buffer.append("lockRepeated:" + isLockRepeated() + "\n"); buffer.append("breakOnCRLF:" + isBreakOnCRLF() + "\n"); buffer.append("embedSkl:" + isEmbedSkl() + "\n"); buffer.append("--------------------------"); return buffer.toString(); } /** * 正向转换验证 * @return ; */ public IStatus validateConversion() { if (source == null || source.trim().equals("")) { return ValidationStatus.error("请选择源文件。"); } else { String localSource = ConverterUtil.toLocalPath(source); File file = new File(localSource); if (!file.exists()) { return ValidationStatus.error("源文件不存在。"); } } if (target == null || target.trim().equals("")) { return ValidationStatus.error("请选择目标文件。"); } else { if (!replaceTarget) { // 如果未选择覆盖,判断并提示目标文件是否存在 String localTarget = ConverterUtil.toLocalPath(target); File file = new File(localTarget); if (file.exists()) { return ValidationStatus.error("目标文件已存在。"); } } } if (srcLang == null || srcLang.trim().equals("")) { return ValidationStatus.error("请选择源文件的语言"); } if (srcEncoding == null || srcEncoding.trim().equals("")) { return ValidationStatus.error("请选择源文件的编码。"); } if (initSegmenter == null || initSegmenter.trim().equals("")) { return ValidationStatus.error("请选择分段规则文件。"); } else { File file = new File(initSegmenter); if (!file.exists()) { return ValidationStatus.error("当前选择的分段规则文件不存在。"); } } return Status.OK_STATUS; } /** * 逆向转换验证 * @return ; */ public IStatus validateReverseConversion() { if (target == null || target.trim().equals("")) { return ValidationStatus.error("请选择已转换的文件。"); } else { if (!replaceTarget) { // 如果未选择覆盖,判断并提示目标文件是否存在 String localTarget = ConverterUtil.toLocalPath(target); File file = new File(localTarget); if (file.exists()) { return ValidationStatus.error("已转换的文件已存在。"); } } } if (targetEncoding == null || targetEncoding.trim().equals("")) { return ValidationStatus.error("请选择已转换文件的编码。"); } return Status.OK_STATUS; } public void setReplaceTarget(boolean replaceTarget) { this.replaceTarget = replaceTarget; } public boolean isReplaceTarget() { return replaceTarget; } public void setFileFormats(List<String> fileFormats) { this.fileFormats = fileFormats; } public List<String> getFileFormats() { if (fileFormats == null) { fileFormats = CommonFunctions.array2List(FileFormatUtils.getFileFormats()); } return fileFormats; } public boolean isPreviewMode() { return previewMode; } public void setPreviewMode(boolean previewMode) { this.previewMode = previewMode; } }
11,843
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
ConversionValidateStrategy.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.ui/src/net/heartsome/cat/convert/ui/model/ConversionValidateStrategy.java
/** * ConversionValidateStrategy.java * * Version information : * * Date:Apr 13, 2010 * * Copyright notice : */ package net.heartsome.cat.convert.ui.model; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; /** * 验证文件转换的配置信息是否正确的顶层接口。 * @author cheney * @since JDK1.6 */ public interface ConversionValidateStrategy { /** * 验证文件转换的配置信息 * @param path * 文件路径 * @param configuraion * 文件转换配置信息 * @param monitor * @return 返回验证的结果状态; */ IStatus validate(String path, ConversionConfigBean configuraion, IProgressMonitor monitor); }
725
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
ParagraphManagement.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.idml/src/net/heartsome/cat/converter/idml/ParagraphManagement.java
package net.heartsome.cat.converter.idml; public class ParagraphManagement { /** * 将字符串转换为 16 进制,以过滤掉 FFFE 和 FEFF 不可见字符 * @param s * @return ; */ public String toHexString(String s) { String str = ""; for (int i = 0; i < s.length(); i++) { int ch = (int) s.charAt(i); String s4 = Integer.toHexString(ch); str = str + s4; } return str;// 0x表示十六进制 } }
433
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
XLIFF2IDML.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.idml/src/net/heartsome/cat/converter/idml/XLIFF2IDML.java
package net.heartsome.cat.converter.idml; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.text.MessageFormat; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.zip.ZipOutputStream; import net.heartsome.cat.common.file.FileManager; import net.heartsome.cat.common.util.TextUtil; import net.heartsome.cat.converter.Converter; import net.heartsome.cat.converter.ConverterException; import net.heartsome.cat.converter.idml.resource.Messages; import net.heartsome.cat.converter.util.ConverterUtils; import net.heartsome.cat.converter.util.Progress; import net.heartsome.xml.vtdimpl.VTDUtils; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.OperationCanceledException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.ximpleware.AutoPilot; import com.ximpleware.NavException; import com.ximpleware.VTDGen; import com.ximpleware.VTDNav; import com.ximpleware.XMLModifier; import com.ximpleware.XPathEvalException; import com.ximpleware.XPathParseException; /** * XLIFF 转换为 IDML * @author peason * @version * @since JDK1.6 */ public class XLIFF2IDML implements Converter { private static final Logger LOGGER = LoggerFactory.getLogger(IDML2XLIFF.class); /** The Constant TYPE_VALUE. */ public static final String TYPE_VALUE = "idml"; /** The Constant TYPE_NAME_VALUE. */ public static final String TYPE_NAME_VALUE = Messages.getString("idml.TYPE_NAME_VALUE"); /** The Constant NAME_VALUE. */ public static final String NAME_VALUE = "XLIFF to IDML Conveter"; public Map<String, String> convert(Map<String, String> args, IProgressMonitor monitor) throws ConverterException { XLIFF2IDMLImpl impl = new XLIFF2IDMLImpl(); return impl.run(args, monitor); } public String getName() { return NAME_VALUE; } public String getType() { return TYPE_VALUE; } public String getTypeName() { return TYPE_NAME_VALUE; } /** * XLIFF 转换为 IDML 的实现类 * @author peason * @version * @since JDK1.6 */ class XLIFF2IDMLImpl { /** IDML 中 Story 文件的前缀 */ private static final String IDML_PREFIX = "idPkg"; /** IDML 中 Story 文件的命名空间 */ private static final String IDML_NAMESPACE = "http://ns.adobe.com/AdobeInDesign/idml/1.0/packaging"; /** XLIFF 文件路径 */ private String strXLIFFPath; /** 骨架文件路径 */ private String strSklPath; private ZipOutputStream zipOut; /** 骨架文件的临时解压目录 */ private String strTmpFolderPath; private FileManager fileManager = new FileManager(); /** 存放文本段的集合,key 为 trans-unit 的 id, value 的第一个值为 source, 第二个为 target */ private HashMap<String, String[]> mapSegment = new HashMap<String, String[]>(); /** * 转换器的处理顺序如下:<br/> * 1. 解析 XLIFF 文件,获取所有文本段并存放入集合中。<br/> * 2. 将骨架文件解压到临时目录。<br/> * 3. 将临时目录中除 Stories 文件夹之外的其他文件及 Stories 文件夹中以 .xml 结尾的文件放入目标文件。<br/> * 4. 解析 Stories 文件夹中以 .skl 结尾的文件,并替换文件中的骨架信息,替换完成之后将此文件去除 .skl 后缀放入目标文件。<br/> * 5. 删除临时解压目录。<br/> * @param args * @param monitor * @return * @throws ConverterException */ public Map<String, String> run(Map<String, String> args, IProgressMonitor monitor) throws ConverterException { monitor = Progress.getMonitor(monitor); monitor.beginTask("", 5); // 转换过程分为 11 部分,loadSegment 占 1,releaseSklZip 占 1,createZip 占 1, handleStoryFile 占 7,deleteFileOrFolder 占 1 IProgressMonitor firstMonitor = Progress.getSubMonitor(monitor, 1); firstMonitor.beginTask(Messages.getString("idml.XLIFF2IDML.task2"), 1); firstMonitor.subTask(""); Map<String, String> result = new HashMap<String, String>(); strXLIFFPath = args.get(Converter.ATTR_XLIFF_FILE); String strTgtPath = args.get(Converter.ATTR_TARGET_FILE); strSklPath = args.get(Converter.ATTR_SKELETON_FILE); try { zipOut = new ZipOutputStream(new FileOutputStream(strTgtPath)); if (firstMonitor.isCanceled()) { throw new OperationCanceledException(Messages.getString("idml.cancel")); } loadSegment(); firstMonitor.worked(1); firstMonitor.done(); if (monitor.isCanceled()) { throw new OperationCanceledException(Messages.getString("idml.cancel")); } IProgressMonitor secondMonitor = Progress.getSubMonitor(monitor, 1); secondMonitor.beginTask(Messages.getString("idml.XLIFF2IDML.task3"), 1); secondMonitor.subTask(""); // 将骨架文件解压到临时目录。 releaseSklZip(strSklPath); secondMonitor.worked(1); secondMonitor.done(); if (monitor.isCanceled()) { throw new OperationCanceledException(Messages.getString("idml.cancel")); } IProgressMonitor thirdMonitor = Progress.getSubMonitor(monitor, 1); thirdMonitor.beginTask(Messages.getString("idml.XLIFF2IDML.task4"), 1); thirdMonitor.subTask(""); fileManager.createZip(strTmpFolderPath, zipOut, strTmpFolderPath + File.separator + "Stories"); thirdMonitor.worked(1); thirdMonitor.done(); handleStoryFile(Progress.getSubMonitor(monitor, 7)); zipOut.flush(); zipOut.close(); if (monitor.isCanceled()) { throw new OperationCanceledException(Messages.getString("idml.cancel")); } IProgressMonitor fourthMonitor = Progress.getSubMonitor(monitor, 1); fourthMonitor.beginTask(Messages.getString("idml.XLIFF2IDML.task5"), 1); fourthMonitor.subTask(""); // 删除解压目录 fileManager.deleteFileOrFolder(new File(strTmpFolderPath)); fourthMonitor.worked(1); fourthMonitor.done(); result.put(Converter.ATTR_TARGET_FILE, strTgtPath); } catch (OperationCanceledException e) { throw e; } catch (Exception e) { e.printStackTrace(); LOGGER.error(Messages.getString("idml.XLIFF2IDML.logger1"), e); ConverterUtils.throwConverterException(Activator.PLUGIN_ID, Messages.getString("idml.XLIFF2IDML.msg1"), e); } finally { monitor.done(); } return result; } /** * 解析 XLIFF 文件,获取所有文本段集合 * @throws NavException * @throws XPathParseException * @throws XPathEvalException */ private void loadSegment() throws NavException, XPathParseException, XPathEvalException { VTDGen vg = new VTDGen(); if (vg.parseFile(strXLIFFPath, true)) { VTDNav vn = vg.getNav(); VTDUtils vu = new VTDUtils(vn); AutoPilot ap = new AutoPilot(vn); ap.selectXPath("/xliff/file/body//trans-unit"); AutoPilot gAp = new AutoPilot(vn); while (ap.evalXPath() != -1) { // 没有g标签 if(vn.getAttrVal("gid")!=-1){ String gId = vu.getCurrentElementAttribut("gid", null); vn.push(); gAp.selectXPath("./source"); while (gAp.evalXPath() != -1) { if (gId != null) { String[] arrText = new String[2]; arrText[0] = vu.getElementContent(); mapSegment.put(gId, arrText); } } vn.pop(); vn.push(); gAp.selectXPath("./target"); while (gAp.evalXPath() != -1) { if (gId != null) { if (mapSegment.containsKey(gId)) { String[] arrText = mapSegment.get(gId); arrText[1] = vu.getElementContent(); } else { String[] arrText = new String[2]; arrText[1] = vu.getElementContent(); mapSegment.put(gId, arrText); } } } vn.pop(); continue; } // 有<g>标签的情况 vn.push(); gAp.selectXPath("./source/g"); while (gAp.evalXPath() != -1) { String gId = vu.getCurrentElementAttribut("id", null); if (gId != null) { String[] arrText = new String[2]; arrText[0] = vu.getElementContent(); mapSegment.put(gId, arrText); } } vn.pop(); vn.push(); gAp.selectXPath("./target/g"); while (gAp.evalXPath() != -1) { String gId = vu.getCurrentElementAttribut("id", null); if (gId != null) { if (mapSegment.containsKey(gId)) { String[] arrText = mapSegment.get(gId); arrText[1] = vu.getElementContent(); } else { String[] arrText = new String[2]; arrText[1] = vu.getElementContent(); mapSegment.put(gId, arrText); } } } vn.pop(); } } } /** * 解压骨架文件到临时目录 * @param sklPath * 骨架文件路径 * @throws IOException */ private void releaseSklZip(String sklPath) throws IOException { String sysTemp = System.getProperty("java.io.tmpdir"); String dirName = "tmpidmlfolder" + System.currentTimeMillis(); File dir = new File(sysTemp + File.separator + dirName); dir.mkdirs(); strTmpFolderPath = dir.getAbsolutePath(); fileManager.releaseZipToFile(sklPath, strTmpFolderPath); } /** * 处理临时解压目录中的 Story 文件 * @throws Exception */ private void handleStoryFile(IProgressMonitor monitor) throws Exception { List<File> lstStoryFile = fileManager.getSubFiles(new File(strTmpFolderPath + File.separator + "Stories"), null); monitor.beginTask("", lstStoryFile.size() + 10); VTDGen vg = new VTDGen(); VTDUtils vu = new VTDUtils(); XMLModifier xm = new XMLModifier(); AutoPilot ap = new AutoPilot(); ap.declareXPathNameSpace(IDML_PREFIX, IDML_NAMESPACE); String strSklTag = "###"; List<String> lstX = new ArrayList<String>(); List<String> lstStoryPath = new ArrayList<String>(); List<String> lstId = new ArrayList<String>(); Pattern pattern = Pattern.compile("###\\d+###"); ParagraphManagement paraManagement = new ParagraphManagement(); StringBuffer sbText = new StringBuffer(); for (File storyFile : lstStoryFile) { if (monitor.isCanceled()) { throw new OperationCanceledException(Messages.getString("idml.cancel")); } monitor.subTask(MessageFormat.format(Messages.getString("idml.XLIFF2IDML.task6"), storyFile.getName())); if (storyFile.getAbsolutePath().endsWith(".xml")) { lstStoryPath.add(storyFile.getAbsolutePath()); // fileManager.addFileToZip(zipOut, strTmpFolderPath, storyFile.getAbsolutePath()); } else if (storyFile.getAbsolutePath().endsWith(".x")) { lstX.add(storyFile.getAbsolutePath()); } else if (storyFile.getAbsolutePath().endsWith(".skl")) { String strStoryPath = storyFile.getAbsolutePath(); if (vg.parseFile(strStoryPath, true)) { VTDNav vn = vg.getNav(); vu.bind(vn); ap.bind(vn); xm.bind(vn); ap.selectXPath("/idPkg:Story/Story//Content/text()"); while (ap.evalXPath() != -1) { String content = vn.toString(vn.getCurrentIndex()); if (content == null || content.equals("")) { continue; } String string = paraManagement.toHexString(content.replaceAll("\r\n", "").replaceAll("\n", "")); if (string.toUpperCase().replaceAll("FFFE", "").replaceAll("FEFF", "") .replaceAll("2028", "").trim().equals("")) { continue; } lstId.clear(); Matcher matcher = pattern.matcher(content); while (matcher.find()) { String group = matcher.group(); lstId.add(group.substring(group.indexOf(strSklTag) + strSklTag.length(), group.lastIndexOf(strSklTag))); } if (lstId.size() == 0) { continue; } if (lstId.size() == 1) { String id = lstId.get(0); String[] arrSrcAndTgt = mapSegment.get(id); if (arrSrcAndTgt != null) { String strSrc = arrSrcAndTgt[0]; String strTgt = arrSrcAndTgt[1]; if (strTgt != null) { strTgt = cleanTag(strTgt); if (!"".equals(strTgt)) { //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ xm.updateToken(vn.getCurrentIndex(), strTgt); } else { xm.updateToken(vn.getCurrentIndex(), cleanTag(strSrc)); } } else { xm.updateToken(vn.getCurrentIndex(), cleanTag(strSrc)); } } else { ConverterUtils.throwConverterException(Activator.PLUGIN_ID, MessageFormat.format(Messages.getString("idml.XLIFF2IDML.msg2"), id)); } } else { sbText.delete(0, sbText.length()); for (String id : lstId) { String[] arrSrcAndTgt = mapSegment.get(id); if (arrSrcAndTgt != null) { String strSrc = arrSrcAndTgt[0]; String strTgt = arrSrcAndTgt[1]; if (strTgt != null) { strTgt = cleanTag(strTgt); if (!"".equals(strTgt)) { //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ sbText.append(strTgt); } else { sbText.append(cleanTag(strSrc)); } } else { sbText.append(cleanTag(strSrc)); } } else { ConverterUtils.throwConverterException( Activator.PLUGIN_ID, MessageFormat.format(Messages.getString("pptx.XLIFF2PPTX.msg2"), lstId.get(0))); } } xm.updateToken(vn.getCurrentIndex(), sbText.toString()); } } strStoryPath = strStoryPath.substring(0, strStoryPath.lastIndexOf(".skl")); xm.output(strStoryPath); lstStoryPath.add(strStoryPath); } } monitor.worked(1); } if (lstX.size() > 0) { IProgressMonitor subMonitor = Progress.getSubMonitor(monitor, lstX.size()); subMonitor.beginTask("", lstX.size()); AutoPilot apX = new AutoPilot(); VTDGen vgX = new VTDGen(); boolean isUpdate = false; for (String strX : lstX) { vgX.clear(); subMonitor.subTask(MessageFormat.format(Messages.getString("idml.XLIFF2IDML.task6"), strX.substring(strX.lastIndexOf(File.separator) + File.separator.length()))); if (vgX.parseFile(strX, true)) { isUpdate = false; VTDNav vn = vgX.getNav(); vu.bind(vn); apX.bind(vn); apX.selectXPath("/root/x"); vg.clear(); vg.parseFile(strX + "ml", true); VTDNav vnXML = vg.getNav(); ap.bind(vnXML); xm.bind(vnXML); while (apX.evalXPath() != -1) { String id = vu.getCurrentElementAttribut("id", null); String content = vu.getElementContent(); // id 非空时,解析对应的 xml 文件 if (id != null) { ap.selectXPath("/idPkg:Story/Story//ParagraphStyleRange/CharacterStyleRange/x[@id='" + id + "']"); if (ap.evalXPath() != -1) { xm.remove(); xm.insertAfterElement(content); isUpdate = true; } } } if (isUpdate) { xm.output(strX + "ml"); } } subMonitor.worked(1); } subMonitor.done(); } monitor.worked(1); for (String storyPath : lstStoryPath) { fileManager.addFileToZip(zipOut, strTmpFolderPath, storyPath); } monitor.done(); } /** 匹配 ph 标记的正则表达式 */ private Pattern pattern = Pattern.compile("<ph>[^<>]*</ph>"); /** * 清除 string 中的标记 * @param string * 待处理的字符串 * @return ; */ private String cleanTag(String string) { Matcher matcher = pattern.matcher(string); int start = 0; int end = 0; StringBuffer sbText = new StringBuffer(); while (matcher.find()) { String group = matcher.group(); // 去除标记。如 <ph id="1">abcd</ph> 去除标记后为 abcd // group = group.substring(group.indexOf(">") + 1, group.lastIndexOf("<")); group.replaceAll("<ph>", ""); group.replaceAll("</ph>", ""); group = TextUtil.resetSpecialString(group); start = matcher.start(); sbText.append(string.substring(end, start)).append(group); end = matcher.end(); } sbText.append(string.substring(end, string.length())); String text = sbText.toString(); return text.replaceAll("'", "&apos;"); } } }
16,204
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
Activator.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.idml/src/net/heartsome/cat/converter/idml/Activator.java
package net.heartsome.cat.converter.idml; import java.util.Properties; import net.heartsome.cat.converter.Converter; import net.heartsome.cat.converter.util.ConverterRegister; import org.osgi.framework.BundleActivator; import org.osgi.framework.BundleContext; import org.osgi.framework.ServiceRegistration; public class Activator implements BundleActivator { /** The Constant PLUGIN_ID. */ public static final String PLUGIN_ID = "net.heartsome.cat.converter.idml"; private static BundleContext context; @SuppressWarnings("rawtypes") private ServiceRegistration idml2XLIFFSR; @SuppressWarnings("rawtypes") private ServiceRegistration xliff2IDMLSR; static BundleContext getContext() { return context; } /* * (non-Javadoc) * @see org.osgi.framework.BundleActivator#start(org.osgi.framework.BundleContext) */ public void start(BundleContext bundleContext) throws Exception { Activator.context = bundleContext; Converter idml2XLIFF = new IDML2XLIFF(); Properties properties = new Properties(); properties.put(Converter.ATTR_NAME, IDML2XLIFF.NAME_VALUE); properties.put(Converter.ATTR_TYPE, IDML2XLIFF.TYPE_VALUE); properties.put(Converter.ATTR_TYPE_NAME, IDML2XLIFF.TYPE_NAME_VALUE); idml2XLIFFSR = ConverterRegister.registerPositiveConverter(context, idml2XLIFF, properties); Converter xliff2IDML = new XLIFF2IDML(); properties = new Properties(); properties.put(Converter.ATTR_NAME, XLIFF2IDML.NAME_VALUE); properties.put(Converter.ATTR_TYPE, XLIFF2IDML.TYPE_VALUE); properties.put(Converter.ATTR_TYPE_NAME, XLIFF2IDML.TYPE_NAME_VALUE); xliff2IDMLSR = ConverterRegister.registerReverseConverter(context, xliff2IDML, properties); } /* * (non-Javadoc) * @see org.osgi.framework.BundleActivator#stop(org.osgi.framework.BundleContext) */ public void stop(BundleContext bundleContext) throws Exception { if (idml2XLIFFSR != null) { idml2XLIFFSR.unregister(); idml2XLIFFSR = null; } if (xliff2IDMLSR != null) { xliff2IDMLSR.unregister(); xliff2IDMLSR = null; } Activator.context = null; } }
2,079
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
IDML2XLIFF.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.idml/src/net/heartsome/cat/converter/idml/IDML2XLIFF.java
package net.heartsome.cat.converter.idml; import java.io.BufferedOutputStream; import java.io.BufferedWriter; import java.io.File; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.zip.ZipOutputStream; import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import net.heartsome.cat.common.file.FileManager; import net.heartsome.cat.common.util.TextUtil; import net.heartsome.cat.converter.Converter; import net.heartsome.cat.converter.ConverterException; import net.heartsome.cat.converter.StringSegmenter; import net.heartsome.cat.converter.idml.resource.Messages; import net.heartsome.cat.converter.util.ConverterUtils; import net.heartsome.cat.converter.util.Progress; import net.heartsome.util.CRC16; import net.heartsome.xml.vtdimpl.VTDUtils; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.OperationCanceledException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; import com.ximpleware.AutoPilot; import com.ximpleware.NavException; import com.ximpleware.VTDGen; import com.ximpleware.VTDNav; import com.ximpleware.XMLModifier; import com.ximpleware.XPathEvalException; import com.ximpleware.XPathParseException; /** * IDML 转换为 XLIFF * @author peason * @version * @since JDK1.6 */ public class IDML2XLIFF implements Converter { private static final Logger LOGGER = LoggerFactory.getLogger(IDML2XLIFF.class); /** The Constant TYPE_VALUE. */ public static final String TYPE_VALUE = "idml"; /** The Constant TYPE_NAME_VALUE. */ public static final String TYPE_NAME_VALUE = Messages.getString("idml.TYPE_NAME_VALUE"); /** The Constant NAME_VALUE. */ public static final String NAME_VALUE = "IDML to XLIFF Conveter"; public Map<String, String> convert(Map<String, String> args, IProgressMonitor monitor) throws ConverterException { IDML2XLIFFImpl impl = new IDML2XLIFFImpl(); return impl.run(args, monitor); } public String getName() { return NAME_VALUE; } public String getType() { return TYPE_VALUE; } public String getTypeName() { return TYPE_NAME_VALUE; } /** * IDML 转换为 XLIFF 的实现类 * @author peason * @version * @since JDK1.6 */ class IDML2XLIFFImpl { /** IDML 中 Story 文件的前缀 */ private static final String IDML_PREFIX = "idPkg"; /** IDML 中 Story 文件的命名空间 */ private static final String IDML_NAMESPACE = "http://ns.adobe.com/AdobeInDesign/idml/1.0/packaging"; /** 源文件路径 */ private String strSrcPath; /** 骨架文件路径 */ private String strSklPath; /** XLIFF 文件路径 */ private String strXLIFFPath; private boolean blnIsSuite; private String strQtToolID; /** 源语言 */ private String strSrcLang; /** 目标语言 */ private String strTgtLang; /** Catalogue 路径 */ private String strCatalogue; /** 分段规则文件路径 */ private String strSrx; /** 编码 */ private String strSrcEncoding; private boolean blnSegByElement; private StringSegmenter segmenter; /** 存放 Spread 的名称,按实际显示页的顺序 */ private LinkedList<String> lstSpread = new LinkedList<String>(); /** 存放 MasterSpread 的名称,按 designmap.xml 中指定的顺序 */ private LinkedList<String> lstMasterSpread = new LinkedList<String>(); /** designmap.xml 中指定的 story 文件的集合 */ private ArrayList<String> lstAllStory = new ArrayList<String>(); /** Story 文件的集合,已排序 */ private LinkedList<String> lstStoryBySort = new LinkedList<String>(); /** 生成 XLIFF 文件的输出流 */ private FileOutputStream out; /** 生成骨架文件的输出流 */ private ZipOutputStream zipSklOut; private FileManager fileManager = new FileManager(); /** 临时解压目录(将 IDML 文件先解压到此目录) */ private String strTmpFolderPath; /** 文本段 ID 值 */ private int segNum = 0; /** * 转换器的处理顺序如下:<br/> * 1. 解压源文件到临时目录。<br/> * 2. 将临时目录中除 Stories 文件夹外的其他文件及目录添加到骨架文件。<br/> * 3. 解析 designmap.xml 文件,获取 Spread 文件的顺序及需要处理的 Story 文件<br/> * 4. 按顺序解析 Spread 文件,从中确定 Story 文件的顺序 <br/> * 5. 对第 4 步中确定的 Story 文件逐一解析,如果 Story 文件中无 Content 节点,则直接放入骨架文件;<br/> * 如果有 Content 节点,则对该 Story 文件添加骨架信息后,文件名添加 .skl 后缀并放入骨架文件 <br/> * 6. 删除临时解压目录 <br/> * @param args * @param monitor * @return * @throws ConverterException * ; */ public Map<String, String> run(Map<String, String> args, IProgressMonitor monitor) throws ConverterException { monitor = Progress.getMonitor(monitor); monitor.beginTask("", 13); Map<String, String> result = new HashMap<String, String>(); // 转换过程分为 11 部分,releaseSrcZip 占 1,createZip 占 1,initSpreadAllStory 占 1, parseSpreadFile 占2, // parseStoryFile 占 5,deleteFileOrFolder 占 1 IProgressMonitor firstPartMonitor = Progress.getSubMonitor(monitor, 1); firstPartMonitor.beginTask(Messages.getString("idml.IDML2XLIFF.task2"), 1); firstPartMonitor.subTask(""); strSrcPath = args.get(Converter.ATTR_SOURCE_FILE); strXLIFFPath = args.get(Converter.ATTR_XLIFF_FILE); strSklPath = args.get(Converter.ATTR_SKELETON_FILE); blnIsSuite = Converter.TRUE.equals(args.get(Converter.ATTR_IS_SUITE)); strQtToolID = args.get(Converter.ATTR_QT_TOOLID) != null ? args.get(Converter.ATTR_QT_TOOLID) : Converter.QT_TOOLID_DEFAULT_VALUE; strSrcLang = args.get(Converter.ATTR_SOURCE_LANGUAGE); strTgtLang = args.get(Converter.ATTR_TARGET_LANGUAGE); strCatalogue = args.get(Converter.ATTR_CATALOGUE); String elementSegmentation = args.get(Converter.ATTR_SEG_BY_ELEMENT); strSrx = args.get(Converter.ATTR_SRX); strSrcEncoding = args.get(Converter.ATTR_SOURCE_ENCODING); if (elementSegmentation == null) { blnSegByElement = false; } else { blnSegByElement = elementSegmentation.equals(Converter.TRUE); } try { out = new FileOutputStream(strXLIFFPath); zipSklOut = new ZipOutputStream(new FileOutputStream(strSklPath)); writeHeader(); if (!blnSegByElement) { segmenter = new StringSegmenter(strSrx, strSrcLang, strCatalogue); } if (firstPartMonitor.isCanceled()) { throw new OperationCanceledException(Messages.getString("idml.cancel")); } releaseSrcZip(strSrcPath); firstPartMonitor.worked(1); firstPartMonitor.done(); if (monitor.isCanceled()) { throw new OperationCanceledException(Messages.getString("idml.cancel")); } IProgressMonitor secondPartMonitor = Progress.getSubMonitor(monitor, 1); secondPartMonitor.beginTask(Messages.getString("idml.IDML2XLIFF.task3"), 1); secondPartMonitor.subTask(""); fileManager.createZip(strTmpFolderPath, zipSklOut, strTmpFolderPath + File.separator + "Stories"); secondPartMonitor.worked(1); secondPartMonitor.done(); if (monitor.isCanceled()) { throw new OperationCanceledException(Messages.getString("idml.cancel")); } initSpreadAllStory(Progress.getSubMonitor(monitor, 1)); if (monitor.isCanceled()) { throw new OperationCanceledException(Messages.getString("idml.cancel")); } // 先提取母版内容 parseSpreadFile(true, Progress.getSubMonitor(monitor, 2)); if (monitor.isCanceled()) { throw new OperationCanceledException(Messages.getString("idml.cancel")); } // 再提取文本内容 parseSpreadFile(false, Progress.getSubMonitor(monitor, 2)); if (monitor.isCanceled()) { throw new OperationCanceledException(Messages.getString("idml.cancel")); } // 按顺序解析 Story 文件 parseStoryFile(Progress.getSubMonitor(monitor, 5)); lstAllStory.removeAll(lstStoryBySort); if (lstAllStory.size() > 0) { // 将剩余的 story 文件放入压缩包 for (String strStoryPath : lstAllStory) { fileManager.addFileToZip(zipSklOut, strTmpFolderPath, strTmpFolderPath + File.separator + strStoryPath); } } writeOut("</body>\n</file>\n</xliff>"); out.close(); zipSklOut.flush(); zipSklOut.close(); IProgressMonitor thirdMonitor = Progress.getSubMonitor(monitor, 1); thirdMonitor.beginTask(Messages.getString("idml.IDML2XLIFF.task4"), 1); thirdMonitor.subTask(""); // 删除解压目录 fileManager.deleteFileOrFolder(new File(strTmpFolderPath)); thirdMonitor.worked(1); thirdMonitor.done(); result.put(Converter.ATTR_XLIFF_FILE, strXLIFFPath); } catch(OperationCanceledException e) { throw e; } catch (Exception e) { e.printStackTrace(); LOGGER.error(Messages.getString("idml.IDML2XLIFF.logger1"), e); ConverterUtils.throwConverterException(Activator.PLUGIN_ID, Messages.getString("idml.IDML2XLIFF.msg1"), e); } finally { monitor.done(); } return result; } /** * 加载 designmap.xml 文件,初始化 lstSpread 和 lstAllStory * @throws XPathParseException * @throws XPathEvalException * @throws NavException * ; */ private void initSpreadAllStory(IProgressMonitor monitor) throws XPathParseException, XPathEvalException, NavException { monitor.beginTask("", 1); monitor.subTask(MessageFormat.format(Messages.getString("idml.IDML2XLIFF.task5"), "designmap.xml")); VTDGen vg = new VTDGen(); if (vg.parseZIPFile(strSrcPath, "designmap.xml", true)) { VTDNav vn = vg.getNav(); AutoPilot ap = new AutoPilot(vn); ap.declareXPathNameSpace(IDML_PREFIX, IDML_NAMESPACE); ap.selectXPath("/Document/node()"); while (ap.evalXPath() != -1) { int curIndex = vn.getCurrentIndex(); int tokenType = vn.getTokenType(curIndex); String name = vn.toString(curIndex); // 节点 if (tokenType == 0) { if (name.equals("idPkg:Spread")) { String strSpread = vn.toString(vn.getAttrVal("src")); lstSpread.add(strSpread); } else if (name.equals("idPkg:Story")) { String strStory = vn.toString(vn.getAttrVal("src")); lstAllStory.add(strStory); } else if (name.equals("idPkg:MasterSpread")) { String strMasterSpread = vn.toString(vn.getAttrVal("src")); lstMasterSpread.add(strMasterSpread); } } } } monitor.worked(1); monitor.done(); } /** * 按 designmap.xml 中指定 Spread 的顺序解析 Spread 文件 * @throws XPathParseException * @throws XPathEvalException * @throws NavException * ; */ private void parseSpreadFile(final boolean isParseMasterSpread, IProgressMonitor monitor) throws XPathParseException, XPathEvalException, NavException { monitor.beginTask("", isParseMasterSpread ? lstMasterSpread.size() : lstSpread.size()); Iterator<String> it = isParseMasterSpread ? lstMasterSpread.iterator() : lstSpread.iterator(); final ArrayList<Double> lstPageX = new ArrayList<Double>(); // 总页数 int pageAmount = 0; // 每个 Spread 所包含的页数 int pageCount = 0; final LinkedHashMap<String, Double[]> mapStoryAndCoordinate = new LinkedHashMap<String, Double[]>(); //与匿名内部类通信 class FieldBridge { int pageAmount; int pageCount; } final FieldBridge spreadAttr = new FieldBridge(); spreadAttr.pageAmount = pageAmount; spreadAttr.pageCount = pageCount; while (it.hasNext()) { if (monitor.isCanceled()) { throw new OperationCanceledException(Messages.getString("idml.cancel")); } String strSpreadPath = it.next(); monitor.subTask(MessageFormat.format(Messages.getString("idml.IDML2XLIFF.task5"), strSpreadPath)); SAXParserFactory factory = SAXParserFactory.newInstance(); try { SAXParser saxParser = factory.newSAXParser(); lstPageX.clear(); saxParser.parse(new File(strTmpFolderPath + File.separator + strSpreadPath), new DefaultHandler() { boolean hasSpreadNode = false; String strPageCount = null; String pageItemTransform = null; List<TextFrameAttr> textFrameList = new LinkedList<TextFrameAttr>(); @Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { if (qName.trim().equalsIgnoreCase("Page") && hasSpreadNode) { String strItemTransform = attributes.getValue("ItemTransform"); String strName = attributes.getValue("Name");// 页号 if (strItemTransform == null || strName == null) { return; } Pattern pattern = Pattern.compile("(?<=\\D*)\\d+(?=(\\D*$))"); Matcher matcher = pattern.matcher(strName); if (matcher.find()) { int curPageNumber = Integer.parseInt(matcher.group()); if (curPageNumber >= spreadAttr.pageAmount && (curPageNumber - spreadAttr.pageAmount) <= spreadAttr.pageCount) { String[] arrTransform = strItemTransform.trim().split(" "); if (arrTransform.length == 6) { double dblX = Double.parseDouble(arrTransform[4].trim()); lstPageX.add(dblX); } } } } else if (qName.trim().equalsIgnoreCase("TextFrame") && hasSpreadNode) { TextFrameAttr attr = new TextFrameAttr(); attr.itemTransform = attributes.getValue("ItemTransform"); attr.parentStory = attributes.getValue("ParentStory"); textFrameList.add(attr); } else if (qName.trim().equalsIgnoreCase(isParseMasterSpread ? "MasterSpread" : "Spread")) { hasSpreadNode = true; strPageCount = attributes.getValue("PageCount"); spreadAttr.pageCount = Integer.parseInt(strPageCount.trim()); pageItemTransform = attributes.getValue("ItemTransform"); } } @Override public void endDocument() throws SAXException { if (!hasSpreadNode) { return; } if (lstPageX.size() == 0 && pageItemTransform != null) { lstPageX.add(Double.MIN_VALUE); String[] arrTransform = pageItemTransform.trim().split(" "); if (arrTransform.length == 6) { double dblX = Double.parseDouble(arrTransform[4].trim()); lstPageX.add(dblX); } lstPageX.add(Double.MAX_VALUE); } Collections.sort(lstPageX); spreadAttr.pageAmount += spreadAttr.pageCount; mapStoryAndCoordinate.clear(); for (TextFrameAttr attr : textFrameList) { String strStoryName = attr.parentStory; String strItemTransform = attr.itemTransform; String[] arrTransform = strItemTransform.trim().split(" "); if (arrTransform.length == 6) { double dblX = Double.parseDouble(arrTransform[4].trim()); double dblY = Double.parseDouble(arrTransform[5].trim()); mapStoryAndCoordinate.put(strStoryName, new Double[] { dblX, dblY }); } } // 对 mapStoryAndCoordinate 排序 sortMap(mapStoryAndCoordinate, lstPageX); } /** * TextFrame 节点属性 * @author Austen * @version * @since JDK1.6 */ class TextFrameAttr { /** ParentStory 属性. */ String parentStory = null; /** ItemTransform 属性. */ String itemTransform = null; } }); } catch (SAXException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (ParserConfigurationException e) { e.printStackTrace(); } monitor.worked(1); } monitor.done(); } // 原来的解析 Spread 的方法, // /** // * 按 designmap.xml 中指定 Spread 的顺序解析 Spread 文件 // * @throws XPathParseException // * @throws XPathEvalException // * @throws NavException // * ; // */ // private void parseSpreadFile(boolean isParseMasterSpread, IProgressMonitor monitor) throws // XPathParseException, // XPathEvalException, NavException { // monitor.beginTask("", isParseMasterSpread ? lstMasterSpread.size() : lstSpread.size()); // Iterator<String> it = isParseMasterSpread ? lstMasterSpread.iterator() : lstSpread.iterator(); // ArrayList<Double> lstPageX = new ArrayList<Double>(); // // 总页数 // int pageAmount = 0; // // 每个 Spread 所包含的页数 // int pageCount; // LinkedHashMap<String, Double[]> mapStoryAndCoordinate = new LinkedHashMap<String, Double[]>(); // AutoPilot ap = new AutoPilot(); // AutoPilot apPage = new AutoPilot(); // AutoPilot apTextFrame = new AutoPilot(); // VTDUtils vu = new VTDUtils(); // int i = 0; // while (it.hasNext()) { // System.out.println(i++); // if (monitor.isCanceled()) { // throw new OperationCanceledException(Messages.getString("idml.cancel")); // } // String strSpreadPath = it.next(); // monitor.subTask(MessageFormat.format(Messages.getString("idml.IDML2XLIFF.task5"), strSpreadPath)); // VTDGen vg = new VTDGen(); // if (vg.parseZIPFile(strSrcPath, strSpreadPath, true)) { // lstPageX.clear(); // VTDNav vn = vg.getNav(); // ap.bind(vn); // ap.declareXPathNameSpace(IDML_PREFIX, IDML_NAMESPACE); // ap.selectXPath(isParseMasterSpread ? "/idPkg:MasterSpread/MasterSpread" : "/idPkg:Spread/Spread"); // vu.bind(vn); // if (ap.evalXPath() != -1) { // String strPageCount = vn.toString(vn.getAttrVal("PageCount"));// 页数 // pageCount = Integer.parseInt(strPageCount.trim()); // int transformIndex = vn.getAttrVal("ItemTransform"); // String pageItemTransform = null; // if (transformIndex != -1) { // pageItemTransform = vn.toString(transformIndex); // } // vn.push(); // apPage.bind(vn); // apPage.selectXPath("./Page"); // while (apPage.evalXPath() != -1) { // String strItemTransform = vu.getCurrentElementAttribut("ItemTransform", null); // String strName = vu.getCurrentElementAttribut("Name", null);// 页号 // if (strItemTransform == null || strName == null) { // continue; // } // Pattern pattern = Pattern.compile("(?<=\\D*)\\d+(?=(\\D*$))"); // Matcher matcher = pattern.matcher(strName); // if (matcher.find()) { // int curPageNumber = Integer.parseInt(matcher.group()); // if (curPageNumber >= pageAmount && (curPageNumber - pageAmount) <= pageCount) { // String[] arrTransform = strItemTransform.trim().split(" "); // if (arrTransform.length == 6) { // double dblX = Double.parseDouble(arrTransform[4].trim()); // lstPageX.add(dblX); // } // } // } // } // if (lstPageX.size() == 0 && pageItemTransform != null) { // lstPageX.add(Double.MIN_VALUE); // String[] arrTransform = pageItemTransform.trim().split(" "); // if (arrTransform.length == 6) { // double dblX = Double.parseDouble(arrTransform[4].trim()); // lstPageX.add(dblX); // } // lstPageX.add(Double.MAX_VALUE); // } // Collections.sort(lstPageX); // pageAmount += pageCount; // vn.pop(); // mapStoryAndCoordinate.clear(); // apTextFrame.bind(vn); // apTextFrame.selectXPath(".//TextFrame"); // while (apTextFrame.evalXPath() != -1) { // String strStoryName = vn.toString(vn.getAttrVal("ParentStory")); // String strItemTransform = vn.toString(vn.getAttrVal("ItemTransform")); // String[] arrTransform = strItemTransform.trim().split(" "); // if (arrTransform.length == 6) { // double dblX = Double.parseDouble(arrTransform[4].trim()); // double dblY = Double.parseDouble(arrTransform[5].trim()); // mapStoryAndCoordinate.put(strStoryName, new Double[] { dblX, dblY }); // } // } // // 对 mapStoryAndCoordinate 排序 // sortMap(mapStoryAndCoordinate, lstPageX); // } // } // monitor.worked(1); // } // monitor.done(); // } /** * 对集合 map 进行排序 * @param map * 要排序的集合 * @param lstPageX * Spread 中 Page 的横坐标集合(已按从小到大的顺序排序) */ private void sortMap(LinkedHashMap<String, Double[]> map, final ArrayList<Double> lstPageX) { List<Map.Entry<String, Double[]>> lstMap = new ArrayList<Map.Entry<String, Double[]>>(map.entrySet()); Collections.sort(lstMap, new Comparator<Map.Entry<String, Double[]>>() { public int compare(Entry<String, Double[]> o1, Entry<String, Double[]> o2) { Double[] arrDbl1 = o1.getValue(); Double[] arrDbl2 = o2.getValue(); boolean isSamePage = false; if (lstPageX.size() == 1) { isSamePage = true; } else { for (int i = 0; i < lstPageX.size() - 1; i++) { double dbl1 = lstPageX.get(i); double dbl2 = lstPageX.get(i + 1); if (arrDbl1[0] >= dbl1 && arrDbl1[0] <= dbl2 && arrDbl2[0] >= dbl1 && arrDbl2[0] <= dbl2) { isSamePage = true; break; } } } // 在同一页 if (isSamePage) { // 先比较纵坐标,纵坐标相同再比较横坐标,由于 y 轴的正方向向下,因此此处为 arrDbl2[1] - arrDbl1[1] if (arrDbl1[1] != arrDbl2[1]) { return arrDbl1[1] > arrDbl2[1] ? 1 : -1; } else { return arrDbl1[0] > arrDbl2[0] ? 1 : -1; } } else { // 未在同一页时只需比较横坐标 return arrDbl1[0] > arrDbl2[0] ? 1 : -1; } } }); for (Entry<String, Double[]> entry : lstMap) { String strStorySuffix = entry.getKey(); String strStoryModule = lstAllStory.get(0); String strStoryPath = strStoryModule.substring(0, strStoryModule.lastIndexOf("_") + 1) + strStorySuffix + strStoryModule.substring(strStoryModule.lastIndexOf(".")); if (lstAllStory.contains(strStoryPath) && !lstStoryBySort.contains(strStoryPath)) { lstStoryBySort.add(strStoryPath); } } } int gId = 0; /** * 解析 Story 文件 * @throws Exception * ; */ private void parseStoryFile(IProgressMonitor monitor) throws Exception { monitor.beginTask("", lstStoryBySort.size()); Iterator<String> it = lstStoryBySort.iterator(); // 标识 Story 文件是否有修改。 boolean isUpdate = false; int xId; boolean isModify = false; // 存储删除的节点,在修改完成后要重新添加到原来的位置 HashMap<String, String> mapDelete = new HashMap<String, String>(); VTDGen vg = new VTDGen(); XMLModifier xm = new XMLModifier(); AutoPilot ap = new AutoPilot(); ap.declareXPathNameSpace(IDML_PREFIX, IDML_NAMESPACE); VTDUtils vu = new VTDUtils(); while (it.hasNext()) { String strStoryPath = it.next(); if (monitor.isCanceled()) { throw new OperationCanceledException(Messages.getString("idml.cancel")); } monitor.subTask(MessageFormat.format(Messages.getString("idml.IDML2XLIFF.task5"), strStoryPath)); vg.clear(); if (vg.parseZIPFile(strSrcPath, strStoryPath, true)) { isUpdate = false; VTDNav vn = vg.getNav(); xm.bind(vn); vu.bind(vn); ap.bind(vn); ap.selectXPath("/idPkg:Story/Story/descendant::ParagraphStyleRange/CharacterStyleRange/node()[name()='Rectangle' or name()='Group']"); xId = 0; // 新建一个以 x 为扩展名的文件,文件名与 strStoryPath 的文件名相同 File tmpFile = new File(strTmpFolderPath + File.separator + strStoryPath.substring(0, strStoryPath.lastIndexOf(".")) + ".x"); tmpFile.createNewFile(); BufferedWriter fos = new BufferedWriter(new FileWriter(tmpFile, true)); fos.append("<root>\n"); while (ap.evalXPath() != -1) { String strRectangle = vu.getElementFragment(); String strReplaceText = "<x id=\"" + xId + "\">\n" + strRectangle + "\n</x>\n"; fos.append(strReplaceText); xm.remove(); xm.insertAfterElement("<x id=\"" + xId + "\"/>"); isUpdate = true; xId++; } fos.append("</root>"); fos.close(); if (isUpdate) { vn = xm.outputAndReparse(); xm.bind(vn); ap.bind(vn); vu.bind(vn); fileManager.addFileToZip(zipSklOut, strTmpFolderPath, tmpFile.getAbsolutePath()); } isModify = false; ap.selectXPath("/idPkg:Story/Story/descendant::node()[name()='HiddenText' or (name()='Change' and @ChangeType='DeletedText')]"); mapDelete.clear(); xId = 0; while (ap.evalXPath() != -1) { String strDel = vu.getElementFragment(); xm.remove(); String strText = "%%%%" + xId++ + "%%%%"; xm.insertAfterElement(strText); mapDelete.put(strText, strDel); isModify = true; isUpdate = true; } if (isModify) { vn = xm.outputAndReparse(); xm.bind(vn); ap.bind(vn); vu.bind(vn); } // 选取 ParagraphStyleRange 节点,只选取第一层 ap.selectXPath("/idPkg:Story/Story/descendant::ParagraphStyleRange[not(ancestor::node()[name()='ParagraphStyleRange']) and descendant::node()[name()='Content']]"); while (ap.evalXPath() != -1) { String paragraphElement = vu.getElementFragment(); String paraModified = handlePara(paragraphElement, mapDelete); if (!paragraphElement.equals(paraModified)) { xm.remove(); xm.insertAfterElement(paraModified); isUpdate = true; } } if (isUpdate) { // Story 文件有修改时,文件名添加 .skl 后缀并放入压缩包 saveStoryFile(xm, strStoryPath); } else { // Story 文件无修改时,将源文件放入压缩包,文件名未改变。 fileManager.addFileToZip(zipSklOut, strTmpFolderPath, strTmpFolderPath + File.separator + strStoryPath); } } monitor.worked(1); } monitor.done(); } public String handlePara(String para, HashMap<String, String> mapDelete) throws Exception { StringBuffer sb = new StringBuffer(); List<Integer> lstDepth = new ArrayList<Integer>(); VTDGen vg = new VTDGen(); vg.setDoc(para.getBytes()); vg.parse(true); VTDNav vn = vg.getNav(); XMLModifier xm = new XMLModifier(vn); AutoPilot ap = new AutoPilot(vn); VTDUtils vu = new VTDUtils(vn); boolean isFind = false; int curDepth = 0; ArrayList<String> lstSegment = new ArrayList<String>(); ArrayList<Integer> lstIndex = new ArrayList<Integer>(); ap.selectXPath("/ParagraphStyleRange/descendant::node()"); StringBuffer sbSkl = new StringBuffer(); StringBuffer sbXLF = new StringBuffer(); StringBuffer sbContent = new StringBuffer(); AutoPilot ap2 = new AutoPilot(vn); AutoPilot childAp = new AutoPilot(vn); while (ap.evalXPath() != -1) { String nodeName = vu.getCurrentElementName(); curDepth = vn.getCurrentDepth(); // 跳过 ParagraphStyleRange 节点 if (nodeName.equalsIgnoreCase("ParagraphStyleRange")) { lstDepth.add(curDepth); // vn.pop(); // 一个文本段结束,要进行分段 if (sb.length() > 0) { vn.push(); updateParaAndXLF(sb, vn, lstSegment, sbSkl, sbContent, sbXLF, xm, ap2, childAp, lstIndex); vn.pop(); } continue; } else { isFind = false; Iterator<Integer> it = lstDepth.iterator(); while (it.hasNext()) { Integer depth = (Integer) it.next(); if (curDepth >= depth) { isFind = true; it.remove(); } } if (isFind || nodeName.equalsIgnoreCase("Br") || nodeName.equalsIgnoreCase("Table")) { // 一个文本段结束,要进行分段 if (sb.length() > 0) { vn.push(); updateParaAndXLF(sb, vn, lstSegment, sbSkl, sbContent, sbXLF, xm, ap2, childAp, lstIndex); vn.pop(); } } if (nodeName.equalsIgnoreCase("Content")) { String seg = vu.getElementContent(); sb.append(seg); lstSegment.add(seg); lstIndex.add(vn.getCurrentIndex()); } } } if (sb.length() > 0) { vn.push(); updateParaAndXLF(sb, vn, lstSegment, sbSkl, sbContent, sbXLF, xm, ap2, childAp, lstIndex); vn.pop(); } if (mapDelete.size() > 0) { childAp.bind(vn); ap.selectXPath("/ParagraphStyleRange/descendant::node()[text()!='' and starts-with(normalize-space(text()),'%%%%') and ends-with(normalize-space(text()),'%%%%')]"); while (ap.evalXPath() != -1) { String strId = vu.getElementPureText().trim(); String strPrimary = mapDelete.get(strId); vn.push(); childAp.selectXPath("./text()"); if (childAp.evalXPath() != -1) { xm.updateToken(vn.getCurrentIndex(), strPrimary); } vn.pop(); } } vn = xm.outputAndReparse(); vu.bind(vn); return vu.getElementFragment(); } public void updateParaAndXLF(StringBuffer sb, VTDNav vn, ArrayList<String> lstSegment, StringBuffer sbSkl, StringBuffer sbContent, StringBuffer sbXLF, XMLModifier xm, AutoPilot ap2, AutoPilot childAp, ArrayList<Integer> lstIndex) throws Exception { ParagraphManagement paraManagement = new ParagraphManagement(); String string = paraManagement.toHexString(sb.toString().replaceAll("\r\n", "").replaceAll("\n", "")); if (string.toUpperCase().replaceAll("FFFE", "").replaceAll("FEFF", "").replaceAll("2028", "").trim() .equals("")) { sbSkl.delete(0, sbSkl.length()); sbXLF.delete(0, sbXLF.length()); sbContent.delete(0, sbContent.length()); sb.delete(0, sb.length()); lstSegment.clear(); lstIndex.clear(); return; } String[] arrSeg = segmenter.segment(sb.toString()); arr: for (String segment : arrSeg) { // 修改 XLIFF 和骨架 Iterator<String> it = lstSegment.iterator(); int index = -1; while (it.hasNext()) { String seg = (String) it.next(); index++; if (segment.equals(seg)) { // 一个 trans-unit : <source><g id=''>segment</g></source> sbXLF.append("<g id=\"" + gId + "\">" + insertPhTag(segment) + "</g>"); writeSegment(sbXLF.toString(), gId); sbXLF.delete(0, sbXLF.length()); // 骨架:sbSkl.append(###id###), 然后写入文件;sbSkl = 0 sbContent.append(segment) sbContent=0 sbSkl.append("###" + gId++ + "###"); sbContent.append(segment); ap2.selectXPath("/ParagraphStyleRange/descendant::node()[text()!='' and text()=" + VTDUtils.dealEscapeQuotes(sbContent.toString()) + "]"); while (ap2.evalXPath() != -1) { int curIndex = vn.getCurrentIndex(); boolean isFind = false; for (Iterator<Integer> iterator = lstIndex.iterator(); iterator.hasNext();) { Integer item = iterator.next(); if (item == curIndex) { iterator.remove(); isFind = true; } } if (!isFind) { continue; } vn.push(); childAp.selectXPath("./text()"); if (childAp.evalXPath() != -1) { xm.updateToken(vn.getCurrentIndex(), sbSkl.toString()); } vn.pop(); break; } sbSkl.delete(0, sbSkl.length()); sbContent.delete(0, sbContent.length()); it.remove(); continue arr; } else if (segment.startsWith(seg)) { sbXLF.append("<g id=\"" + gId + "\">" + insertPhTag(seg) + "</g>"); // 骨架:sbSkl.append(###id###), 然后写入文件并sbSkl = 0 sbContent.append(seg) sbContent=0 sbSkl.append("###" + gId++ + "###"); sbContent.append(seg); ap2.selectXPath("/ParagraphStyleRange/descendant::node()[text()!='' and text()=" + VTDUtils.dealEscapeQuotes(sbContent.toString()) + "]"); while (ap2.evalXPath() != -1) { int curIndex = vn.getCurrentIndex(); boolean isFind = false; for (Iterator<Integer> iterator = lstIndex.iterator(); iterator.hasNext();) { Integer item = iterator.next(); if (item == curIndex) { iterator.remove(); isFind = true; } } if (!isFind) { continue; } vn.push(); childAp.selectXPath("./text()"); if (childAp.evalXPath() != -1) { xm.updateToken(vn.getCurrentIndex(), sbSkl.toString()); } vn.pop(); break; } sbSkl.delete(0, sbSkl.length()); sbContent.delete(0, sbContent.length()); segment = segment.substring(seg.length()); it.remove(); index--; continue; } else if (seg.startsWith(segment)) { // sbXLF.append("<g id=''>segment</g>"), 然后写入 XLIFF 文件 sbXLF.append("<g id=\"" + gId + "\">" + insertPhTag(segment) + "</g>"); writeSegment(sbXLF.toString(), gId); sbXLF.delete(0, sbXLF.length()); // 骨架:sbSkl.append(###id###); sbContent.append(segment) sbSkl.append("###" + gId++ + "###"); sbContent.append(segment); lstSegment.set(index, seg.substring(segment.length())); continue arr; } } } sbSkl.delete(0, sbSkl.length()); sbXLF.delete(0, sbXLF.length()); sbContent.delete(0, sbContent.length()); sb.delete(0, sb.length()); lstSegment.clear(); lstIndex.clear(); } private String insertPhTag(String input) { // 匹配 Content 子节点的正则表达式 Pattern pattern = Pattern.compile("<[^<>]+>"); Matcher matcher = pattern.matcher(input); int start = 0; int end = 0; StringBuffer sbText = new StringBuffer(); while (matcher.find()) { start = matcher.start(); sbText.append(input.substring(end, start)).append("<ph>") .append(TextUtil.cleanSpecialString(matcher.group())).append("</ph>"); end = matcher.end(); } sbText.append(input.substring(end, input.length())); return sbText.toString(); } /** * 保存 Story 文件的修改并将其添加到压缩包 * @param xm * @param storyName * Story 文件在源文件中的相对路径 * @throws Exception * ; */ private void saveStoryFile(XMLModifier xm, String storyName) throws Exception { File tempFile = new File(strTmpFolderPath + File.separator + storyName + ".skl"); FileOutputStream fos = new FileOutputStream(tempFile); BufferedOutputStream bos = new BufferedOutputStream(fos); xm.output(bos); // 写入文件 bos.close(); fileManager.addFileToZip(zipSklOut, strTmpFolderPath, tempFile.getAbsolutePath()); } /** * 将 strSrc 写入 XLIFF 文件 * @param strSrc * @throws IOException * ; */ private void writeSegment(String strSrc, int id) throws IOException { // 去掉只有一个G标签的情况 if (getGTagCount(strSrc) == 1) { writeOut("<trans-unit id=\"" + segNum++ + "\" gid=\"" + id + "\">\n"); strSrc = strSrc.replaceAll("<g.+?>|</g>", ""); } else { writeOut("<trans-unit id=\"" + segNum++ + "\">\n"); } // int phId = 1; // 将源文件中的 &apos; 替换为 ',因为在 XLIFF 中 &apos; 不是转义字符,而 InDesign 中是,在逆转换时,要注意将 ' 替换为 &apos; strSrc = strSrc.replaceAll("&apos;", "'"); writeOut("<source xml:lang=\"" + strSrcLang + "\">" + strSrc + "</source>\n"); writeOut("</trans-unit>\n\n"); //$NON-NLS-1$ } /** * 判断只有一个G标签的情况 * @param strSrc * @return ; */ private int getGTagCount(String strSrc) { int i = 0; if (strSrc.startsWith("<g") && strSrc.endsWith("</g>")) { Pattern p = Pattern.compile("</g>"); Matcher m = p.matcher(strSrc); while (m.find()) { i++; } } return i; } /** * 写 XLIFF 的头节点内容 * @throws IOException * ; */ private void writeHeader() throws IOException { writeOut("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n"); //$NON-NLS-1$ writeOut("<xliff version=\"1.2\" xmlns=\"urn:oasis:names:tc:xliff:document:1.2\" " + //$NON-NLS-1$ "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" " + "xmlns:hs=\"" + Converter.HSNAMESPACE + "\" " + //$NON-NLS-1$ "xsi:schemaLocation=\"urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd " //$NON-NLS-1$ + Converter.HSSCHEMALOCATION + "\">\n"); //$NON-NLS-1$ if (!strTgtLang.equals("")) { writeOut("<file datatype=\"" + TYPE_VALUE + "\" original=\"" + TextUtil.cleanSpecialString(strSrcPath) + "\" source-language=\"" + strSrcLang + "\" target-language=\"" + strTgtLang + "\">\n"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } else { writeOut("<file datatype=\"" + TYPE_VALUE + "\" original=\"" + TextUtil.cleanSpecialString(strSrcPath) + "\" source-language=\"" + strSrcLang + "\">\n"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } writeOut("<header>\n"); //$NON-NLS-1$ writeOut("<skl>\n"); //$NON-NLS-1$ if (blnIsSuite) { writeOut("<external-file crc=\"" + CRC16.crc16(TextUtil.cleanString(strSklPath).getBytes("UTF-8")) + "\" href=\"" + TextUtil.cleanSpecialString(strSklPath) + "\"/>\n"); //$NON-NLS-1$ //$NON-NLS-2$ } else { writeOut("<external-file href=\"" + TextUtil.cleanSpecialString(strSklPath) + "\"/>\n"); //$NON-NLS-1$ //$NON-NLS-2$ } writeOut("</skl>\n"); //$NON-NLS-1$ writeOut(" <tool tool-id=\"" + strQtToolID + "\" tool-name=\"HSStudio\"/>\n"); //$NON-NLS-1$ //$NON-NLS-2$ writeOut(" <hs:prop-group name=\"encoding\"><hs:prop prop-type=\"encoding\">" //$NON-NLS-1$ + strSrcEncoding + "</hs:prop></hs:prop-group>\n"); //$NON-NLS-1$ writeOut("</header>\n<body>\n"); //$NON-NLS-1$ writeOut("\n"); //$NON-NLS-1$ } private void writeOut(String string) throws IOException { out.write(string.getBytes("UTF-8")); //$NON-NLS-1$ } /** * 将 source 所代表的压缩包解压到临时目录 strTmpFolderPath * @param source * @throws IOException * ; */ private void releaseSrcZip(String source) throws IOException { String sysTemp = System.getProperty("java.io.tmpdir"); String dirName = "tmpidmlfolder" + System.currentTimeMillis(); File dir = new File(sysTemp + File.separator + dirName); dir.mkdirs(); strTmpFolderPath = dir.getAbsolutePath(); fileManager.releaseZipToFile(source, strTmpFolderPath); } } }
38,477
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
Messages.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.idml/src/net/heartsome/cat/converter/idml/resource/Messages.java
/** * Messages.java * * Version information : * * Date:Jan 14, 2010 * * Copyright notice : */ package net.heartsome.cat.converter.idml.resource; import java.util.MissingResourceException; import java.util.ResourceBundle; /** * 国际化工具类 * @author peason * @version * @since JDK1.6 */ public final class Messages { /** The Constant BUNDLE_NAME. */ private static final String BUNDLE_NAME = "net.heartsome.cat.converter.idml.resource.idml"; //$NON-NLS-1$ /** The Constant RESOURCE_BUNDLE. */ private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle.getBundle(BUNDLE_NAME); /** * Instantiates a new messages. */ private Messages() { // do nothing } /** * Gets the string. * @param key * the key * @return the string */ public static String getString(String key) { try { return RESOURCE_BUNDLE.getString(key); } catch (MissingResourceException e) { return '!' + key + '!'; } } }
1,017
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
Rtf2XliffTest.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.rtf/testSrc/net/heartsome/cat/converter/rtf/test/Rtf2XliffTest.java
package net.heartsome.cat.converter.rtf.test; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.io.File; import java.util.HashMap; import java.util.Map; import net.heartsome.cat.converter.Converter; import net.heartsome.cat.converter.ConverterException; import net.heartsome.cat.converter.rtf.Rtf2Xliff; import org.junit.AfterClass; import org.junit.Before; import org.junit.Test; public class Rtf2XliffTest { public static Rtf2Xliff converter = new Rtf2Xliff(); private static String srcODTFile = "rc/TestODT.rtf"; private static String xlfODTFile = "rc/TestODT.rtf.xlf"; private static String sklODTFile = "rc/TestODT.rtf.skl"; private static String srcDocFile = "rc/TestDoc.rtf"; private static String xlfDocFile = "rc/TestDoc.rtf.xlf"; private static String sklDocFile = "rc/TestDoc.rtf.skl"; @Before public void setUp() { File xlf = new File(xlfODTFile); if (xlf.exists()) { xlf.delete(); } File skl = new File(sklODTFile); if (skl.exists()) { skl.delete(); } xlf = new File(xlfDocFile); if (xlf.exists()) { xlf.delete(); } skl = new File(sklDocFile); if (skl.exists()) { skl.delete(); } } @Test(expected = ConverterException.class) public void testConvertMissingCatalog() throws ConverterException { String rootFolder = "/data/john/Workspaces/CAT/HSTS7/"; Map<String, String> args = new HashMap<String, String>(); args.put(Converter.ATTR_SOURCE_FILE, srcODTFile); //$NON-NLS-1$ args.put(Converter.ATTR_XLIFF_FILE, xlfODTFile); //$NON-NLS-1$ args.put(Converter.ATTR_SKELETON_FILE, sklODTFile); //$NON-NLS-1$ args.put(Converter.ATTR_SOURCE_LANGUAGE, "zh-CN"); //$NON-NLS-1$ args.put(Converter.ATTR_SOURCE_ENCODING, "UTF-8"); //$NON-NLS-1$ // args.put(Converter.ATTR_CATALOGUE, rootFolder + // "catalogue/catalogue.xml"); args.put(Converter.ATTR_SRX, rootFolder + "srx/default_rules.srx"); args.put(Converter.ATTR_PROGRAM_FOLDER, rootFolder); Map<String, String> result = converter.convert(args, null); String xliff = result.get(Converter.ATTR_XLIFF_FILE); assertNotNull(xliff); File xlfFile = new File(xliff); assertNotNull(xlfFile); assertTrue(xlfFile.exists()); } @Test(expected = ConverterException.class) public void testConvertMissingSRX() throws ConverterException { String rootFolder = "/data/john/Workspaces/CAT/HSTS7/"; Map<String, String> args = new HashMap<String, String>(); args.put(Converter.ATTR_SOURCE_FILE, srcODTFile); //$NON-NLS-1$ args.put(Converter.ATTR_XLIFF_FILE, xlfODTFile); //$NON-NLS-1$ args.put(Converter.ATTR_SKELETON_FILE, sklODTFile); //$NON-NLS-1$ args.put(Converter.ATTR_SOURCE_LANGUAGE, "zh-CN"); //$NON-NLS-1$ args.put(Converter.ATTR_SOURCE_ENCODING, "UTF-8"); //$NON-NLS-1$ args.put(Converter.ATTR_CATALOGUE, rootFolder + "catalogue/catalogue.xml"); // args.put(Converter.ATTR_SRX, rootFolder + "srx/default_rules.srx"); args.put(Converter.ATTR_PROGRAM_FOLDER, rootFolder); Map<String, String> result = converter.convert(args, null); String xliff = result.get(Converter.ATTR_XLIFF_FILE); assertNotNull(xliff); File xlfFile = new File(xliff); assertNotNull(xlfFile); assertTrue(xlfFile.exists()); } @Test(expected = ConverterException.class) public void testConvertMissingINI() throws ConverterException { String rootFolder = "/data/john/Workspaces/CAT/HSTS7/"; Map<String, String> args = new HashMap<String, String>(); args.put(Converter.ATTR_SOURCE_FILE, srcODTFile); //$NON-NLS-1$ args.put(Converter.ATTR_XLIFF_FILE, xlfODTFile); //$NON-NLS-1$ args.put(Converter.ATTR_SKELETON_FILE, sklODTFile); //$NON-NLS-1$ args.put(Converter.ATTR_SOURCE_LANGUAGE, "zh-CN"); //$NON-NLS-1$ args.put(Converter.ATTR_SOURCE_ENCODING, "UTF-8"); //$NON-NLS-1$ args.put(Converter.ATTR_CATALOGUE, rootFolder + "catalogue/catalogue.xml"); args.put(Converter.ATTR_SRX, rootFolder + "srx/default_rules.srx"); // args.put(Converter.ATTR_PROGRAM_FOLDER, rootFolder); Map<String, String> result = converter.convert(args, null); String xliff = result.get(Converter.ATTR_XLIFF_FILE); assertNotNull(xliff); File xlfFile = new File(xliff); assertNotNull(xlfFile); assertTrue(xlfFile.exists()); } @Test public void testConvert() throws ConverterException { String rootFolder = "/data/john/Workspaces/CAT/HSTS7/"; Map<String, String> args = new HashMap<String, String>(); args.put(Converter.ATTR_SOURCE_FILE, srcODTFile); //$NON-NLS-1$ args.put(Converter.ATTR_XLIFF_FILE, xlfODTFile); //$NON-NLS-1$ args.put(Converter.ATTR_SKELETON_FILE, sklODTFile); //$NON-NLS-1$ args.put(Converter.ATTR_SOURCE_LANGUAGE, "zh-CN"); //$NON-NLS-1$ args.put(Converter.ATTR_SOURCE_ENCODING, "UTF-8"); //$NON-NLS-1$ args.put(Converter.ATTR_CATALOGUE, rootFolder + "catalogue/catalogue.xml"); args.put(Converter.ATTR_SRX, rootFolder + "srx/default_rules.srx"); args.put(Converter.ATTR_PROGRAM_FOLDER, rootFolder); Map<String, String> result = converter.convert(args, null); String xliff = result.get(Converter.ATTR_XLIFF_FILE); assertNotNull(xliff); File xlfFile = new File(xliff); assertNotNull(xlfFile); assertTrue(xlfFile.exists()); args = new HashMap<String, String>(); args.put(Converter.ATTR_SOURCE_FILE, srcDocFile); //$NON-NLS-1$ args.put(Converter.ATTR_XLIFF_FILE, xlfDocFile); //$NON-NLS-1$ args.put(Converter.ATTR_SKELETON_FILE, sklDocFile); //$NON-NLS-1$ args.put(Converter.ATTR_SOURCE_LANGUAGE, "zh-CN"); //$NON-NLS-1$ args.put(Converter.ATTR_SOURCE_ENCODING, "UTF-8"); //$NON-NLS-1$ args.put(Converter.ATTR_CATALOGUE, rootFolder + "catalogue/catalogue.xml"); args.put(Converter.ATTR_SRX, rootFolder + "srx/default_rules.srx"); args.put(Converter.ATTR_PROGRAM_FOLDER, rootFolder); result = converter.convert(args, null); xliff = result.get(Converter.ATTR_XLIFF_FILE); assertNotNull(xliff); xlfFile = new File(xliff); assertNotNull(xlfFile); assertTrue(xlfFile.exists()); } @AfterClass public static void finalConverter() throws ConverterException { String rootFolder = "/data/john/Workspaces/CAT/HSTS7/"; Map<String, String> args = new HashMap<String, String>(); args.put(Converter.ATTR_SOURCE_FILE, srcODTFile); //$NON-NLS-1$ args.put(Converter.ATTR_XLIFF_FILE, xlfODTFile); //$NON-NLS-1$ args.put(Converter.ATTR_SKELETON_FILE, sklODTFile); //$NON-NLS-1$ args.put(Converter.ATTR_SOURCE_LANGUAGE, "zh-CN"); //$NON-NLS-1$ args.put(Converter.ATTR_SOURCE_ENCODING, "UTF-8"); //$NON-NLS-1$ args.put(Converter.ATTR_CATALOGUE, rootFolder + "catalogue/catalogue.xml"); args.put(Converter.ATTR_SRX, rootFolder + "srx/default_rules.srx"); args.put(Converter.ATTR_PROGRAM_FOLDER, rootFolder); Map<String, String> result = converter.convert(args, null); String xliff = result.get(Converter.ATTR_XLIFF_FILE); assertNotNull(xliff); File xlfFile = new File(xliff); assertNotNull(xlfFile); assertTrue(xlfFile.exists()); args = new HashMap<String, String>(); args.put(Converter.ATTR_SOURCE_FILE, srcDocFile); //$NON-NLS-1$ args.put(Converter.ATTR_XLIFF_FILE, xlfDocFile); //$NON-NLS-1$ args.put(Converter.ATTR_SKELETON_FILE, sklDocFile); //$NON-NLS-1$ args.put(Converter.ATTR_SOURCE_LANGUAGE, "zh-CN"); //$NON-NLS-1$ args.put(Converter.ATTR_SOURCE_ENCODING, "UTF-8"); //$NON-NLS-1$ args.put(Converter.ATTR_CATALOGUE, rootFolder + "catalogue/catalogue.xml"); args.put(Converter.ATTR_SRX, rootFolder + "srx/default_rules.srx"); args.put(Converter.ATTR_PROGRAM_FOLDER, rootFolder); result = converter.convert(args, null); xliff = result.get(Converter.ATTR_XLIFF_FILE); assertNotNull(xliff); xlfFile = new File(xliff); assertNotNull(xlfFile); assertTrue(xlfFile.exists()); } }
7,747
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
Xliff2RtfTest.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.rtf/testSrc/net/heartsome/cat/converter/rtf/test/Xliff2RtfTest.java
package net.heartsome.cat.converter.rtf.test; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.io.File; import java.util.HashMap; import java.util.Map; import net.heartsome.cat.converter.Converter; import net.heartsome.cat.converter.ConverterException; import net.heartsome.cat.converter.rtf.Xliff2Rtf; import org.junit.Before; import org.junit.Test; public class Xliff2RtfTest { public static Xliff2Rtf converter = new Xliff2Rtf(); private static String tgtODTFile = "rc/TestODT_en-US.rtf"; private static String xlfODTFile = "rc/TestODT.rtf.xlf"; private static String sklODTFile = "rc/TestODT.rtf.skl"; private static String tgtDocFile = "rc/TestDoc_en-US.rtf"; private static String xlfDocFile = "rc/TestDoc.rtf.xlf"; private static String sklDocFile = "rc/TestDoc.rtf.skl"; @Before public void setUp() { File tgt = new File(tgtODTFile); if (tgt.exists()) { tgt.delete(); } tgt = new File(tgtDocFile); if (tgt.exists()) { tgt.delete(); } } @Test public void testConvertODT() throws ConverterException { String rootFolder = "/data/john/Workspaces/CAT/HSTS7/"; Map<String, String> args = new HashMap<String, String>(); args.put(Converter.ATTR_TARGET_FILE, tgtODTFile); args.put(Converter.ATTR_XLIFF_FILE, xlfODTFile); args.put(Converter.ATTR_SKELETON_FILE, sklODTFile); args.put(Converter.ATTR_SOURCE_ENCODING, "UTF-8"); args.put(Converter.ATTR_CATALOGUE, rootFolder + "catalogue/catalogue.xml"); Map<String, String> result = converter.convert(args, null); String target = result.get(Converter.ATTR_TARGET_FILE); assertNotNull(target); File tgtFile = new File(target); assertNotNull(tgtFile); assertTrue(tgtFile.exists()); } @Test public void testConvertDoc() throws ConverterException { String rootFolder = "/data/john/Workspaces/CAT/HSTS7/"; Map<String, String> args = new HashMap<String, String>(); args.put(Converter.ATTR_TARGET_FILE, tgtDocFile); args.put(Converter.ATTR_XLIFF_FILE, xlfDocFile); args.put(Converter.ATTR_SKELETON_FILE, sklDocFile); args.put(Converter.ATTR_SOURCE_ENCODING, "UTF-8"); args.put(Converter.ATTR_CATALOGUE, rootFolder + "catalogue/catalogue.xml"); Map<String, String> result = converter.convert(args, null); String target = result.get(Converter.ATTR_TARGET_FILE); assertNotNull(target); File tgtFile = new File(target); assertNotNull(tgtFile); assertTrue(tgtFile.exists()); } }
2,472
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
Activator.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.rtf/src/net/heartsome/cat/converter/rtf/Activator.java
/** * Activator.java * * Version information : * * Date:Jan 14, 2010 * * Copyright notice : */ package net.heartsome.cat.converter.rtf; import java.util.Properties; import net.heartsome.cat.converter.Converter; import net.heartsome.cat.converter.util.ConverterRegister; import org.osgi.framework.BundleActivator; import org.osgi.framework.BundleContext; import org.osgi.framework.ServiceRegistration; /** * The Class Activator.The activator class controls the plug-in life cycle. * @author John Zhu * @version * @since JDK1.6 */ public class Activator implements BundleActivator { /** The Constant PLUGIN_ID. */ public static final String PLUGIN_ID = "net.heartsome.cat.converter.rtf"; // The shared instance /** The plugin. */ private static Activator plugin; /** The rtf2 xliff sr. */ private ServiceRegistration rtf2XliffSR; /** The xliff2 rtf sr. */ private ServiceRegistration xliff2RtfSR; /** * The constructor. */ public Activator() { } /** * (non-Javadoc). * @param context * the context * @throws Exception * the exception * @see org.osgi.framework.BundleActivator#start(org.osgi.framework.BundleContext) */ public void start(BundleContext context) throws Exception { plugin = this; // register the converter services Converter rtf2Xliff = new Rtf2Xliff(); Properties properties = new Properties(); properties.put(Converter.ATTR_NAME, Rtf2Xliff.NAME_VALUE); properties.put(Converter.ATTR_TYPE, Rtf2Xliff.TYPE_VALUE); properties.put(Converter.ATTR_TYPE_NAME, Rtf2Xliff.TYPE_NAME_VALUE); rtf2XliffSR = ConverterRegister.registerPositiveConverter(context, rtf2Xliff, properties); Converter xliff2Rtf = new Xliff2Rtf(); properties = new Properties(); properties.put(Converter.ATTR_NAME, Xliff2Rtf.NAME_VALUE); properties.put(Converter.ATTR_TYPE, Xliff2Rtf.TYPE_VALUE); properties.put(Converter.ATTR_TYPE_NAME, Xliff2Rtf.TYPE_NAME_VALUE); xliff2RtfSR = ConverterRegister.registerReverseConverter(context, xliff2Rtf, properties); } /** * (non-Javadoc). * @param context * the context * @throws Exception * the exception * @see org.osgi.framework.BundleActivator#stop(org.osgi.framework.BundleContext) */ public void stop(BundleContext context) throws Exception { if (rtf2XliffSR != null) { rtf2XliffSR.unregister(); } if (xliff2RtfSR != null) { xliff2RtfSR.unregister(); } plugin = null; } /** * Returns the shared instance. * @return the shared instance */ public static Activator getDefault() { return plugin; } }
2,597
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
Rtf2Xliff.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.rtf/src/net/heartsome/cat/converter/rtf/Rtf2Xliff.java
/** * Rtf2Xliff.java * * Version information : * * Date:Jan 14, 2010 * * Copyright notice : */ package net.heartsome.cat.converter.rtf; import java.io.ByteArrayInputStream; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.text.MessageFormat; import java.util.HashMap; import java.util.Hashtable; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Stack; import java.util.StringTokenizer; import java.util.Vector; import net.heartsome.cat.converter.Converter; import net.heartsome.cat.converter.ConverterException; import net.heartsome.cat.converter.StringSegmenter; import net.heartsome.cat.converter.rtf.resource.Messages; import net.heartsome.cat.converter.util.ConverterUtils; import net.heartsome.cat.converter.util.Progress; import net.heartsome.util.CRC16; import net.heartsome.util.TextUtil; import net.heartsome.xml.Document; import net.heartsome.xml.Element; import net.heartsome.xml.SAXBuilder; import net.heartsome.xml.XMLOutputter; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.OperationCanceledException; import org.w3c.dom.Node; import org.xml.sax.SAXException; /** * The Class Rtf2Xliff. * @author John Zhu * @version * @since JDK1.6 */ public class Rtf2Xliff implements Converter { /** The Constant TYPE_VALUE. */ public static final String TYPE_VALUE = "rtf"; /** The Constant TYPE_NAME_VALUE. */ public static final String TYPE_NAME_VALUE = Messages.getString("rtf.TYPE_NAME_VALUE"); /** The Constant NAME_VALUE. */ public static final String NAME_VALUE = "RTF to XLIFF Conveter"; /** * (non-Javadoc) * @see net.heartsome.cat.converter.Converter#convert(java.util.Map, org.eclipse.core.runtime.IProgressMonitor) * @param args * @param monitor * @return * @throws ConverterException */ public Map<String, String> convert(Map<String, String> args, IProgressMonitor monitor) throws ConverterException { Rtf2XliffImpl converter = new Rtf2XliffImpl(); return converter.run(args, monitor); } /** * (non-Javadoc) * @see net.heartsome.cat.converter.Converter#getName() * @return */ public String getName() { return NAME_VALUE; } /** * (non-Javadoc) * @see net.heartsome.cat.converter.Converter#getType() * @return */ public String getType() { return TYPE_VALUE; } /** * (non-Javadoc) * @see net.heartsome.cat.converter.Converter#getTypeName() * @return */ public String getTypeName() { return TYPE_NAME_VALUE; } /** * The Class Rtf2XliffImpl. * @author John Zhu * @version * @since JDK1.6 */ class Rtf2XliffImpl { // check text hidden in tags using the XML inLocalisation sample /** The input. */ private FileInputStream input; /** The output. */ private FileOutputStream output; /** The skeleton. */ private FileOutputStream skeleton; /** The content. */ private String content; /** The header. */ private String header; /** The groups. */ private Vector<String> groups; /** The main text. */ private String mainText; /** The styles. */ private Vector<String> styles; /** The default cpg. */ private String defaultCpg; /** The default font. */ private String defaultFont; /** The default lang. */ private String defaultLang; /** The default uc. */ private String defaultUC; /** The in loch. */ private boolean inLOCH; /** The in hich. */ private boolean inHICH; /** The in dbch. */ private boolean inDBCH; /** The src encoding. */ private String srcEncoding; /** The font table. */ Hashtable<String, String> fontTable; /** The charsets. */ Hashtable<String, String> charsets; /** The fonts. */ private Vector<String> fonts; /** The status. */ Hashtable<String, Object> status; /** The stack. */ Stack<Hashtable<String, Object>> stack; /** The ignore. */ Hashtable<String, String> ignore; /** The skip. */ private int skip; /** The default af. */ private String defaultAF; /** The default status. */ private Hashtable<String, Object> defaultStatus; /** The tw4win term. */ private boolean tw4winTerm = false; /** The tw4win mark. */ private boolean tw4winMark = false; /** The tw4win error. */ private boolean tw4winError = false; /** The tw4win popup. */ private boolean tw4winPopup = false; /** The tw4win jump. */ private boolean tw4winJump = false; /** The tw4win external. */ private boolean tw4winExternal = false; /** The tw4win internal. */ private boolean tw4winInternal = false; /** The do_not_translate. */ private boolean do_not_translate = false; /** The win external. */ private String winExternal = ""; //$NON-NLS-1$ /** The win internal. */ private String winInternal = ""; //$NON-NLS-1$ /** The win mark. */ private String winMark = ""; //$NON-NLS-1$ /** The not_translate. */ private String not_translate = ""; //$NON-NLS-1$ /** The internal value. */ private String internalValue = ""; //$NON-NLS-1$ /** The external value. */ private String externalValue = ""; //$NON-NLS-1$ /** The no translate value. */ private String noTranslateValue = ""; //$NON-NLS-1$ /** The color list. */ private Vector<String> colorList; /** The color group. */ private int colorGroup; /** The font group. */ private int fontGroup; /** The style group. */ private int styleGroup; /** The style fonts. */ private Hashtable<String, String> styleFonts; /** The source language. */ private String sourceLanguage; private String targetLanguage; /** The tagged rtf. */ private boolean taggedRTF; /** The seg by element. */ private boolean segByElement; /** The seg id. */ int segId; /** The breaks. */ private Hashtable<String, String> breaks; /** The segments. */ private Vector<String> segments; /** The start. */ private String start; /** The end. */ private String end; /** The meat. */ private String meat; /** The in external. */ private boolean inExternal; /** The segmenter. */ private StringSegmenter segmenter; /** The skeleton file. */ private String skeletonFile; /** The xliff file. */ private String xliffFile; /** The mark style. */ private Object markStyle; /** The input file. */ private String inputFile; /** The symbols. */ private Hashtable<Integer, String> symbols; /** The ignorable fonts. */ private Hashtable<String, String> ignorableFonts; /** The default cf. */ private String defaultCF = "1"; //$NON-NLS-1$ /** The cf table. */ private Hashtable<String, String> cfTable; /** The qt tool id. */ private String qtToolID; /** The is suite. */ private boolean isSuite; /** The data type. */ private String dataType; /** The program foler. */ private String programFoler; /** * Run. * @param params * the params * @param monitor * the monitor * @return the map< string, string> * @throws ConverterException * the converter exception */ public Map<String, String> run(Map<String, String> params, IProgressMonitor monitor) throws ConverterException { monitor = Progress.getMonitor(monitor); Map<String, String> result = new HashMap<String, String>(); try { // 把转换过程分为 10 部分:parseMainText 方法之前的部分占 1, parseMainText 方法中的处理占 5,pase 方法占 2,剩余部分占 2。 monitor.beginTask("", 10); // 再把 parseMainText 之前的任务进一步进行细分,分为 4 部分:读取文件内容,构建文件的组内容,解析组内容,处理组内容。 IProgressMonitor firstPartMonitor = Progress.getSubMonitor(monitor, 1); firstPartMonitor.beginTask("", 4); dataType = params.get(Converter.ATTR_FORMAT); if (dataType == null) { dataType = TYPE_VALUE; } inputFile = params.get(Converter.ATTR_SOURCE_FILE); xliffFile = params.get(Converter.ATTR_XLIFF_FILE); skeletonFile = params.get(Converter.ATTR_SKELETON_FILE); sourceLanguage = params.get(Converter.ATTR_SOURCE_LANGUAGE); targetLanguage = params.get(Converter.ATTR_TARGET_LANGUAGE); srcEncoding = params.get(Converter.ATTR_SOURCE_ENCODING); programFoler = params.get(Converter.ATTR_PROGRAM_FOLDER); String catalogue = params.get(Converter.ATTR_CATALOGUE); String elementSegmentation = params.get(Converter.ATTR_SEG_BY_ELEMENT); String tagged = params.get(Converter.ATTR_IS_TAGGEDRTF); if (tagged != null && tagged.equalsIgnoreCase(Converter.TRUE)) { taggedRTF = true; } else { taggedRTF = false; } if (elementSegmentation == null) { segByElement = false; } else { if (elementSegmentation.equalsIgnoreCase(Converter.TRUE)) { segByElement = true; } else { segByElement = false; } } isSuite = false; if (Converter.TRUE.equals(params.get(Converter.ATTR_IS_SUITE))) { isSuite = true; } qtToolID = params.get(Converter.ATTR_QT_TOOLID) != null ? params.get(Converter.ATTR_QT_TOOLID) : Converter.QT_TOOLID_DEFAULT_VALUE; segId = 0; if (!segByElement || taggedRTF) { String initSegmenter = params.get(Converter.ATTR_SRX); segmenter = new StringSegmenter(initSegmenter, sourceLanguage, catalogue); } // read the file into a String // 检查是否取消操作 if (firstPartMonitor.isCanceled()) { throw new OperationCanceledException(Messages.getString("rtf.cancel")); } firstPartMonitor.subTask(Messages.getString("rtf.Rtf2Xliff.task3")); input = new FileInputStream(inputFile); int size = input.available(); byte[] array = new byte[size]; input.read(array); content = new String(array); array = null; input.close(); firstPartMonitor.worked(1); // get the header StringBuffer buffer = new StringBuffer(); buffer.append(content.charAt(0)); int i = 1; char c = 0; while (i < size && (c = content.charAt(i++)) != '{') { buffer.append(c); } header = buffer.toString(); stack = new Stack<Hashtable<String, Object>>(); processHeader(); // build all groups styles = new Vector<String>(); // 检查是否取消操作 if (firstPartMonitor.isCanceled()) { throw new OperationCanceledException(Messages.getString("rtf.cancel")); } firstPartMonitor.subTask(Messages.getString("rtf.Rtf2Xliff.task4")); buildGroups(); buildCharsets(); loadSymbols(); firstPartMonitor.worked(1); System.out.println("Groups built"); //$NON-NLS-1$ // parse individual groups Hashtable<String, String> mainGroups = new Hashtable<String, String>(); mainText = ""; //$NON-NLS-1$ firstPartMonitor.subTask(Messages.getString("rtf.Rtf2Xliff.task5")); for (i = 0; i < groups.size(); i++) { // 检查是否取消操作 if (firstPartMonitor.isCanceled()) { throw new OperationCanceledException(Messages.getString("rtf.cancel")); } String group = groups.get(i); if (group.indexOf("\\stylesheet") != -1) { //$NON-NLS-1$ buildStyleList(group); styleGroup = i; if (taggedRTF) { addStyles(); System.out.println("Styles added"); //$NON-NLS-1$ } parseStyles(); if (taggedRTF) { internalValue = getValue(winInternal); externalValue = getValue(winExternal); noTranslateValue = getValue(not_translate); } } if (group.indexOf("\\fonttbl") != -1) { //$NON-NLS-1$ buildFontList(group); fontGroup = i; } if (group.indexOf("\\colortbl") != -1) { //$NON-NLS-1$ buildColorList(group); colorGroup = i; } if (group.indexOf("\\fonttbl") != -1 //$NON-NLS-1$ || group.indexOf("\\filetbl") != -1 //$NON-NLS-1$ || group.indexOf("\\colortbl") != -1 //$NON-NLS-1$ || group.indexOf("\\stylesheet") != -1 //$NON-NLS-1$ || group.indexOf("\\listtable") != -1 //$NON-NLS-1$ || group.indexOf("\\revtable") != -1 //$NON-NLS-1$ || group.indexOf("\\rsidtable") != -1 //$NON-NLS-1$ || group.indexOf("\\generator") != -1 //$NON-NLS-1$ || group.indexOf("\\info") != -1 //$NON-NLS-1$ || group.indexOf("\\colorschememapping") != -1 //$NON-NLS-1$ || group.indexOf("\\latentstyles") != -1 //$NON-NLS-1$ || group.indexOf("\\pgptbl") != -1 //$NON-NLS-1$ || group.indexOf("\\operator") != -1 //$NON-NLS-1$ || group.indexOf("\\xmlnstbl") != -1 //$NON-NLS-1$ || group.indexOf("\\fchars") != -1 //$NON-NLS-1$ || group.indexOf("\\lchars") != -1 //$NON-NLS-1$ || group.indexOf("\\pgptbl") != -1 //$NON-NLS-1$ || group.indexOf("\\listtext") != -1 //$NON-NLS-1$ || group.indexOf("\\wgrffmtfilter") != -1 //$NON-NLS-1$ || group.indexOf("\\themedata") != -1 //$NON-NLS-1$ || group.indexOf("\\datastore") != -1 //$NON-NLS-1$ || group.indexOf("\\defchp") != -1 //$NON-NLS-1$ || group.indexOf("\\defpap") != -1 //$NON-NLS-1$ || group.indexOf("\\defshp") != -1 //$NON-NLS-1$ || group.indexOf("\\shp") != -1 //$NON-NLS-1$ || group.indexOf("\\pgdsctbl") != -1) { //$NON-NLS-1$ // should be ignored, unless it contains text if (group.indexOf("\\par") != -1 //$NON-NLS-1$ || group.indexOf("\\cell") != -1 //$NON-NLS-1$ || group.indexOf("\\row") != -1 //$NON-NLS-1$ || group.indexOf("\\nestcell") != -1 //$NON-NLS-1$ || group.indexOf("\\dobypara") != -1) { //$NON-NLS-1$ mainText = mainText + group; mainGroups.put("" + i, ""); //$NON-NLS-1$ //$NON-NLS-2$ } } else { mainText = mainText + group; mainGroups.put("" + i, ""); //$NON-NLS-1$ //$NON-NLS-2$ } } firstPartMonitor.worked(1); System.out.println("Groups parsed"); //$NON-NLS-1$ fillIgnore(); output = new FileOutputStream(xliffFile); skeleton = new FileOutputStream(skeletonFile); writeSkl(header + "\n"); //$NON-NLS-1$ writeHeader(); System.out.println("Header written"); //$NON-NLS-1$ firstPartMonitor.subTask(Messages.getString("rtf.Rtf2Xliff.task6")); for (int h = 0; h < groups.size() - 1; h++) { // 是否取消操作 if (firstPartMonitor.isCanceled()) { throw new OperationCanceledException(Messages.getString("rtf.cancel")); } if (mainGroups.containsKey("" + h)) { //$NON-NLS-1$ continue; } if (h == fontGroup) { writeSkl("{\\fonttbl \n"); //$NON-NLS-1$ for (int k = 0; k < fonts.size(); k++) { writeSkl(fonts.get(k) + "\n"); //$NON-NLS-1$ } writeSkl("}\n\n"); //$NON-NLS-1$ continue; } if (h == colorGroup) { writeSkl("{\\colortbl;"); //$NON-NLS-1$ for (int k = 0; k < colorList.size(); k++) { writeSkl(colorList.get(k) + ";"); //$NON-NLS-1$ } writeSkl("}\n\n"); //$NON-NLS-1$ continue; } if (h == styleGroup) { writeSkl("{\\stylesheet \n"); //$NON-NLS-1$ for (int k = 0; k < styles.size(); k++) { writeSkl(styles.get(k) + "\n"); //$NON-NLS-1$ } writeSkl("}\n\n"); //$NON-NLS-1$ continue; } String group = groups.get(h); writeSkl(group); writeSkl("\n\n"); //$NON-NLS-1$ } firstPartMonitor.worked(1); firstPartMonitor.done(); mainText = parseMainText(Progress.getSubMonitor(monitor, 5)); parse(mainText, Progress.getSubMonitor(monitor, 2)); System.out.println("Processing " + segments.size() + " segments"); //$NON-NLS-1$ //$NON-NLS-2$ checkSegments(Progress.getSubMonitor(monitor, 1)); writeSkl("\n}\n"); //$NON-NLS-1$ writeStr("</body>\n"); //$NON-NLS-1$ writeStr("</file>\n"); //$NON-NLS-1$ writeStr("</xliff>"); //$NON-NLS-1$ output.close(); skeleton.close(); result.put(Converter.ATTR_XLIFF_FILE, xliffFile); } catch (OperationCanceledException e) { throw e; } catch (Exception e) { if (Converter.DEBUG_MODE) { e.printStackTrace(); } if (taggedRTF) { if (e instanceof ConverterException) { throw (ConverterException)e; } else { ConverterUtils.throwConverterException(Activator.PLUGIN_ID, Messages.getString("rtf.Rtf2Xliff.msg3"), e); } } else { if (e instanceof ConverterException) { throw (ConverterException)e; } else { ConverterUtils.throwConverterException(Activator.PLUGIN_ID, Messages.getString("rtf.Rtf2Xliff.msg4"), e); } } } finally { monitor.done(); } return result; } /** * Load symbols. * @throws SAXException * the SAX exception * @throws IOException * Signals that an I/O exception has occurred. */ private void loadSymbols() throws SAXException, IOException { symbols = new Hashtable<Integer, String>(); SAXBuilder b = new SAXBuilder(); Document d = b.build(programFoler + "ini/symbol.xml"); //$NON-NLS-1$ Element r = d.getRootElement(); List<Element> l = r.getChildren(); Iterator<Element> i = l.iterator(); while (i.hasNext()) { Element e = i.next(); symbols.put(new Integer(e.getAttributeValue("code")), e.getText()); //$NON-NLS-1$ } i = null; l = null; r = null; d = null; b = null; } /** * Parses the group. * @param group * the group * @return the string */ private String parseGroup(String group, IProgressMonitor monitor) { int size = group.length(); // 如果 size 大于 10000,则把总任务数按比例缩小 100 倍;如果 size 大于 100000,则把总任务数按比例缩小 1000 倍。 int scale = 1; if (size > 100000) { scale = 1000; } else if (size > 10000) { scale = 100; } int totalTask = size / scale; monitor.beginTask("", totalTask); monitor.subTask(Messages.getString("rtf.Rtf2Xliff.task7")); Stack<String> localStack = new Stack<String>(); String buff = ""; //$NON-NLS-1$ int count = 0; for (int i = 0; i < group.length(); i++) { // 是否取消操作 if (monitor.isCanceled()) { throw new OperationCanceledException(Messages.getString("rtf.cancel")); } char c = group.charAt(i); if (c == '{') { localStack.push(buff); buff = ""; //$NON-NLS-1$ } buff = buff + c; if (c == '}') { String clean = cleanGroup(buff); buff = localStack.pop(); if (buff.matches(".*\\\\[a-zA-Z]+") && clean.matches("[a-zA-z0-9].*")) { //$NON-NLS-1$ //$NON-NLS-2$ buff = buff + " "; //$NON-NLS-1$ } if (buff.matches(".*\\\\[a-zA-Z]+[0-9]+") && clean.matches("[0-9].*")) { //$NON-NLS-1$ //$NON-NLS-2$ buff = buff + " "; //$NON-NLS-1$ } buff = buff + clean; } count++; int temp = count / scale; count %= scale; if (temp > 0) { monitor.worked(temp); } } monitor.done(); return buff; } /** * Clean group. * @param buff * the buff * @return the string */ private String cleanGroup(String buff) { if (buff.indexOf("\\ltrch") != -1 && buff.indexOf("\\rtlch") != -1) { //$NON-NLS-1$ //$NON-NLS-2$ buff = removeControl(buff, "\\ltrch"); //$NON-NLS-1$ buff = removeControl(buff, "\\rtlch"); //$NON-NLS-1$ } if (buff.indexOf("\\fcs0") != -1 && buff.indexOf("\\fcs1") != -1) { //$NON-NLS-1$ //$NON-NLS-2$ buff = removeControl(buff, "\\fcs"); //$NON-NLS-1$ } if (buff.matches("\\{(\\\\*)?\\\\.*\\}")) { //$NON-NLS-1$ // contains text and controls // braces should be preserved return buff; } if (buff.matches("\\{.*\\}")) { //$NON-NLS-1$ // contains text without control words // braces should be removed return buff.substring(1, buff.length() - 1); } return buff; } /** * Removes the control. * @param string * the string * @param ctrl * the ctrl * @return the string */ private String removeControl(String string, String ctrl) { int index = string.indexOf(ctrl); while (index != -1) { String left = string.substring(0, index); if (left.endsWith("\\*")) { //$NON-NLS-1$ left = left.substring(0, left.length() - 2); } String right = string.substring(index + ctrl.length()); if (right.matches("^[0-9]+\\s[a-zA-Z0-9\\s].*")) { //$NON-NLS-1$ right = right.replaceAll("^[0-9]+\\s", ""); //$NON-NLS-1$ //$NON-NLS-2$ } else { right = right.replaceAll("^[0-9]+", ""); //$NON-NLS-1$ //$NON-NLS-2$ } if (left.matches(".*\\\\[a-zA-Z]+") && right.matches("^[a-zA-Z0-9\\s].*")) { //$NON-NLS-1$ //$NON-NLS-2$ right = " " + right; //$NON-NLS-1$ } else if (left.matches(".*\\\\[a-zA-Z]+[0-9]+") && right.matches("[0-9\\s].*")) { //$NON-NLS-1$ //$NON-NLS-2$ right = " " + right; //$NON-NLS-1$ } string = left + right; index = string.indexOf(ctrl); } return string; } /** * Parses the styles. * @throws ConverterException */ private void parseStyles() throws ConverterException { styleFonts = new Hashtable<String, String>(); cfTable = new Hashtable<String, String>(); for (int i = 0; i < styles.size(); i++) { String style = styles.get(i); StringTokenizer tk = new StringTokenizer(style, "\\{} \t", true); //$NON-NLS-1$ String control = ""; //$NON-NLS-1$ String value = ""; //$NON-NLS-1$ while (tk.hasMoreElements()) { String token = tk.nextToken(); if (token.length() == 1) { continue; } String ctl = getControl("\\" + token); //$NON-NLS-1$ if (ctl.equals("s") || // paragraph style //$NON-NLS-1$ ctl.equals("cs") || // character style //$NON-NLS-1$ ctl.equals("ts") || // table style //$NON-NLS-1$ ctl.equals("ds")) { // section style //$NON-NLS-1$ control = getValue("\\" + token); //$NON-NLS-1$ } if (ctl.equals("f")) { //$NON-NLS-1$ value = getValue("\\" + token); //$NON-NLS-1$ } } if (!control.equals("") && !value.equals("")) { //$NON-NLS-1$ //$NON-NLS-2$ if (fontTable.containsKey(value)) { styleFonts.put(control, value); } else { MessageFormat mf = new MessageFormat(taggedRTF ? Messages.getString("rtf.Rtf2Xliff.msg5") : Messages.getString("rtf.Rtf2Xliff.msg1")); //$NON-NLS-1$ Object[] args = { value }; String msg = mf.format(args); System.err.println(msg); args = null; fontTable.put(control, "0"); //$NON-NLS-1$ // throw new ConverterException(new Status(IStatus.ERROR, Activator.PLUGIN_ID, msg)); } } cfTable.put(getStyle(style), getValue("cf", style)); //$NON-NLS-1$ } } /** * Builds the charsets. * @throws SAXException * the SAX exception * @throws IOException * Signals that an I/O exception has occurred. */ private void buildCharsets() throws SAXException, IOException { SAXBuilder builder = new SAXBuilder(); Document doc = builder.build(programFoler + "ini/rtf_encodings.xml"); //$NON-NLS-1$ charsets = new Hashtable<String, String>(); Element root = doc.getRootElement(); List<Element> list = root.getChildren("encoding"); //$NON-NLS-1$ Iterator<Element> it = list.iterator(); while (it.hasNext()) { Element e = it.next(); charsets.put(e.getAttributeValue("codePage"), getEncoding(e.getText().trim())); //$NON-NLS-1$ } } /** * Builds the font list. * @param group * the group * @throws Exception * the exception */ private void buildFontList(String group) throws Exception { int upr = group.indexOf("\\upr"); //$NON-NLS-1$ int ud = group.indexOf("\\ud"); //$NON-NLS-1$ if (upr != -1 && ud != -1) { group = group.substring(upr + 4, ud); group = group.substring(0, group.lastIndexOf("}")); //$NON-NLS-1$ } fontTable = new Hashtable<String, String>(); ignorableFonts = new Hashtable<String, String>(); fonts = new Vector<String>(); int level = 0; int i = group.indexOf("{", group.indexOf("\\fonttbl")); //$NON-NLS-1$ //$NON-NLS-2$ StringBuffer buffer = new StringBuffer(); while (i < group.length()) { char c = group.charAt(i++); if (c == '\r' || c == '\n') { continue; } buffer.append(c); if (c == '{') { level++; } if (c == '}') { level--; } if (level == 0) { String font = buffer.toString().trim(); if (!font.trim().equals("")) { //$NON-NLS-1$ font = parseFont(font); } fonts.add(font); buffer = null; buffer = new StringBuffer(); } } } /** * Parses the font. * @param font * the font * @return the string */ private String parseFont(String font) { StringTokenizer tk = new StringTokenizer(font, "\\{} \t", true); //$NON-NLS-1$ String control = ""; //$NON-NLS-1$ String value = ""; //$NON-NLS-1$ while (tk.hasMoreElements()) { String token = tk.nextToken(); if (token.length() == 1) { continue; } if (getControl("\\" + token).equals("f")) { //$NON-NLS-1$ //$NON-NLS-2$ control = getValue("\\" + token); //$NON-NLS-1$ } if (getControl("\\" + token).equals("fcharset")) { //$NON-NLS-1$ //$NON-NLS-2$ value = getValue("\\" + token); //$NON-NLS-1$ } } if (!control.equals("") && !value.equals("")) { //$NON-NLS-1$ //$NON-NLS-2$ if (value.equals("2")) { //$NON-NLS-1$ if (font.indexOf("Symbol") != -1) { //$NON-NLS-1$ ignorableFonts.put(control, ""); //$NON-NLS-1$ } else { font = font.replace("fcharset2", "fcharset0"); //$NON-NLS-1$ //$NON-NLS-2$ } } if (charsets.containsKey(value)) { fontTable.put(control, value); } else { MessageFormat mf = new MessageFormat(Messages.getString("rtf.Rtf2Xliff.msg2")); //$NON-NLS-1$ Object[] args = { value }; System.err.println(mf.format(args)); args = null; fontTable.put(control, "0"); //$NON-NLS-1$ } } return font; } /** * Process header. */ private void processHeader() { defaultUC = "0"; //$NON-NLS-1$ defaultFont = ""; //$NON-NLS-1$ defaultLang = ""; //$NON-NLS-1$ defaultCpg = "1252"; //$NON-NLS-1$ defaultAF = ""; //$NON-NLS-1$ StringTokenizer tk = new StringTokenizer(header, "\\", true); //$NON-NLS-1$ while (tk.hasMoreTokens()) { String token = tk.nextToken(); if (token.equals("\\")) { //$NON-NLS-1$ token = token + tk.nextToken(); } String ctrlString = getControl(token); if (ctrlString.equals("ansicpg")) { //$NON-NLS-1$ defaultCpg = getValue(token); // fixed a bug 921 by john. String tmpEncoding = getEncoding(defaultCpg); if (tmpEncoding != null) { srcEncoding = tmpEncoding; } } if (ctrlString.equals("deff")) { //$NON-NLS-1$ defaultFont = getValue(token); } if (ctrlString.equals("deflang")) { //$NON-NLS-1$ defaultLang = getValue(token); } if (ctrlString.equals("adeff")) { //$NON-NLS-1$ System.out.println("Default afont: " + getValue(token)); //$NON-NLS-1$ } if (ctrlString.equals("uc")) { //$NON-NLS-1$ defaultUC = getValue(token); } } status = new Hashtable<String, Object>(); status.put("defaultUC", defaultUC); //$NON-NLS-1$ status.put("defaultFont", defaultFont); //$NON-NLS-1$ status.put("defaultLang", defaultLang); //$NON-NLS-1$ status.put("srcEncoding", srcEncoding); //$NON-NLS-1$ status.put("defaultCpg", defaultCpg); //$NON-NLS-1$ status.put("defaultCF", defaultCF); //$NON-NLS-1$ status.put("defaultAF", defaultAF); //$NON-NLS-1$ status.put("inLOCH", new Boolean(inLOCH)); //$NON-NLS-1$ status.put("inHICH", new Boolean(inHICH)); //$NON-NLS-1$ status.put("inDBCH", new Boolean(inDBCH)); //$NON-NLS-1$ stack.push(status); defaultStatus = status; } /** * Gets the encoding. * @param encoding * the encoding * @return the encoding */ private String getEncoding(String encoding) { String[] codes = TextUtil.getPageCodes(); for (int h = 0; h < codes.length; h++) { if (codes[h].toLowerCase().indexOf("windows-" + encoding) != -1) { //$NON-NLS-1$ return codes[h]; } } if (encoding.equals("10000")) { //$NON-NLS-1$ for (int h = 0; h < codes.length; h++) { if (codes[h].toLowerCase().indexOf("macroman") != -1) { //$NON-NLS-1$ return codes[h]; } } } if (encoding.equals("10001")) { //$NON-NLS-1$ for (int h = 0; h < codes.length; h++) { if (codes[h].toLowerCase().indexOf("shift_jis") != -1) { //$NON-NLS-1$ return codes[h]; } } } if (encoding.equals("10006")) { //$NON-NLS-1$ for (int h = 0; h < codes.length; h++) { if (codes[h].toLowerCase().indexOf("macgreek") != -1) { //$NON-NLS-1$ return codes[h]; } } } if (encoding.equals("10007")) { //$NON-NLS-1$ for (int h = 0; h < codes.length; h++) { if (codes[h].toLowerCase().indexOf("maccyrillic") != -1) { //$NON-NLS-1$ return codes[h]; } } } if (encoding.equals("10029")) { //$NON-NLS-1$ for (int h = 0; h < codes.length; h++) { if (codes[h].toLowerCase().indexOf("maccentraleurope") != -1) { //$NON-NLS-1$ return codes[h]; } } } if (encoding.equals("10079")) { //$NON-NLS-1$ for (int h = 0; h < codes.length; h++) { if (codes[h].toLowerCase().indexOf("maciceland") != -1) { //$NON-NLS-1$ return codes[h]; } } } if (encoding.equals("10081")) { //$NON-NLS-1$ for (int h = 0; h < codes.length; h++) { if (codes[h].toLowerCase().indexOf("macturkish") != -1) { //$NON-NLS-1$ return codes[h]; } } } if (encoding.equals("65000")) { //$NON-NLS-1$ for (int h = 0; h < codes.length; h++) { if (codes[h].toLowerCase().indexOf("utf-7") != -1) { //$NON-NLS-1$ return codes[h]; } } } if (encoding.equals("650001")) { //$NON-NLS-1$ for (int h = 0; h < codes.length; h++) { if (codes[h].toLowerCase().indexOf("utf-8") != -1) { //$NON-NLS-1$ return codes[h]; } } } if (encoding.equals("932")) { //$NON-NLS-1$ for (int h = 0; h < codes.length; h++) { if (codes[h].toLowerCase().indexOf("shift_jis") != -1) { //$NON-NLS-1$ return codes[h]; } } } if (encoding.equals("936")) { //$NON-NLS-1$ for (int h = 0; h < codes.length; h++) { if (codes[h].toLowerCase().indexOf("gb2312") != -1) { //$NON-NLS-1$ return codes[h]; } } } if (encoding.equals("949")) { //$NON-NLS-1$ for (int h = 0; h < codes.length; h++) { if (codes[h].toLowerCase().indexOf("euc-kr") != -1) { //$NON-NLS-1$ return codes[h]; } } } if (encoding.equals("950")) { //$NON-NLS-1$ for (int h = 0; h < codes.length; h++) { if (codes[h].toLowerCase().indexOf("big5") != -1) { //$NON-NLS-1$ return codes[h]; } } } if (encoding.equals("1361")) { //$NON-NLS-1$ for (int h = 0; h < codes.length; h++) { if (codes[h].toLowerCase().indexOf("johab") != -1) { //$NON-NLS-1$ return codes[h]; } } } if (encoding.equalsIgnoreCase("Symbol")) { //$NON-NLS-1$ return "Symbol"; //$NON-NLS-1$ } if (defaultStatus != null) { return (String) defaultStatus.get("srcEncoding"); //$NON-NLS-1$ } return null; } /** * Parses the main text. * @return the string * @throws Exception * the exception */ private String parseMainText(IProgressMonitor monitor) throws Exception { // 此处把任务分为 10 个部分:第一个 while 循环占 1,每二个 for 循环占 1,最后的 paseGroup 方法占 8。 monitor.beginTask("", 10); System.out.println("Replacing braces..."); //$NON-NLS-1$ mainText = replaceToken(mainText, "\\{", "\uE008"); //$NON-NLS-1$ //$NON-NLS-2$ mainText = replaceToken(mainText, "\\}", "\uE007"); //$NON-NLS-1$ //$NON-NLS-2$ mainText = replaceToken(mainText, "\\\\", "\uE011"); //$NON-NLS-1$ //$NON-NLS-2$ System.out.println("Braces replaced"); //$NON-NLS-1$ StringTokenizer tk = new StringTokenizer(mainText, "{}\\", true); //$NON-NLS-1$ System.out.println("Processing " + tk.countTokens() + " tokens"); //$NON-NLS-1$ //$NON-NLS-2$ // 对每一部分的内容再进行细分 int tokenSize = tk.countTokens(); IProgressMonitor subMonitor1 = Progress.getSubMonitor(monitor, 1); subMonitor1.beginTask("", tokenSize); subMonitor1.subTask(Messages.getString("rtf.Rtf2Xliff.task8")); Vector<String> v = new Vector<String>(); while (tk.hasMoreElements()) { // 是否取消操作 if (subMonitor1.isCanceled()) { throw new OperationCanceledException(Messages.getString("rtf.cancel")); } String token = tk.nextToken(); if (token.equals("\\")) { //$NON-NLS-1$ token = token + tk.nextToken(); } if (token.equals("\\*")) { //$NON-NLS-1$ token = token + tk.nextToken() + tk.nextToken(); } if (token.startsWith("\\'")) { //$NON-NLS-1$ if (token.length() == 4) { v.add(token); } else { v.add(token.substring(0, 4)); v.add(token.substring(4)); } } else if (token.startsWith("\\")) { //$NON-NLS-1$ String ctl = getControl(token); String value = getValue(token); String s = token.substring(0, token.indexOf(ctl)) + ctl + value; v.add(s); String remainder = token.substring(s.length()); if (remainder.startsWith(" ")) { //$NON-NLS-1$ if (!remainder.matches("^\\s[a-zA-Z0-9\\s].*")) { //$NON-NLS-1$ remainder = remainder.substring(1); } else if (s.matches(".*[0-9]")) { //$NON-NLS-1$ remainder = remainder.substring(1); } } if (!remainder.equals("")) { //$NON-NLS-1$ v.add(remainder); } } else { v.add(token); } subMonitor1.worked(1); } subMonitor1.done(); String result = ""; //$NON-NLS-1$ int level = 0; System.out.println("Processing " + v.size() + " frag..."); // 对第二部分的同样进行细分 IProgressMonitor subMonitor2 = Progress.getSubMonitor(monitor, 1); subMonitor2.beginTask("", v.size()); subMonitor2.subTask(Messages.getString("rtf.Rtf2Xliff.task9")); for (int i = 0; i < v.size(); i++) { // 是否取消操作 if (subMonitor2.isCanceled()) { throw new OperationCanceledException(Messages.getString("rtf.cancel")); } String frag = v.get(i); frag = replaceToken(frag, "\\emdash ", "" + '\u2014'); //$NON-NLS-1$ //$NON-NLS-2$ frag = replaceToken(frag, "\\endash ", "" + '\u2013'); //$NON-NLS-1$ //$NON-NLS-2$ frag = replaceToken(frag, "\\lquote ", "" + '\u2018'); //$NON-NLS-1$ //$NON-NLS-2$ frag = replaceToken(frag, "\\rquote ", "" + '\u2019'); //$NON-NLS-1$ //$NON-NLS-2$ frag = replaceToken(frag, "\\ldblquote ", "" + '\u201C'); //$NON-NLS-1$ //$NON-NLS-2$ frag = replaceToken(frag, "\\rdblquote ", "" + '\u201D'); //$NON-NLS-1$ //$NON-NLS-2$ frag = replaceToken(frag, "\\tab ", "" + '\u0009'); //$NON-NLS-1$ //$NON-NLS-2$ // replace the same characters again, without the space frag = replaceToken(frag, "\\emdash", "" + '\u2014'); //$NON-NLS-1$ //$NON-NLS-2$ frag = replaceToken(frag, "\\endash", "" + '\u2013'); //$NON-NLS-1$ //$NON-NLS-2$ frag = replaceToken(frag, "\\lquote", "" + '\u2018'); //$NON-NLS-1$ //$NON-NLS-2$ frag = replaceToken(frag, "\\rquote", "" + '\u2019'); //$NON-NLS-1$ //$NON-NLS-2$ frag = replaceToken(frag, "\\ldblquote", "" + '\u201C'); //$NON-NLS-1$ //$NON-NLS-2$ frag = replaceToken(frag, "\\rdblquote", "" + '\u201D'); //$NON-NLS-1$ //$NON-NLS-2$ frag = replaceToken(frag, "\\tab", "" + '\u0009'); //$NON-NLS-1$ //$NON-NLS-2$ // remove special spaces and replace with Unicode version frag = replaceToken(frag, "\\enspace", "" + '\u2002'); //$NON-NLS-1$ //$NON-NLS-2$ frag = replaceToken(frag, "\\emspace", "" + '\u2003'); //$NON-NLS-1$ //$NON-NLS-2$ frag = replaceToken(frag, "\\qmspace", "" + '\u2005'); //$NON-NLS-1$ //$NON-NLS-2$ frag = replaceToken(frag, "\\~", "" + '\u00A0'); // non breaking //$NON-NLS-1$ //$NON-NLS-2$ // space // //$NON-NLS-1$ // //$NON-NLS-2$ // Hyphens frag = replaceToken(frag, "\\_", "" + '\u2011'); // non breaking //$NON-NLS-1$ //$NON-NLS-2$ // hyphen // //$NON-NLS-1$ // //$NON-NLS-2$ frag = replaceToken(frag, "\\-", "" + '\u00AD'); // soft hyphen //$NON-NLS-1$ //$NON-NLS-2$ // //$NON-NLS-1$ // //$NON-NLS-2$ if (frag.equals("{")) { //$NON-NLS-1$ saveCurrStatus(); level++; } else if (frag.equals("}")) { //$NON-NLS-1$ level--; restoreStatus(); } if (frag.startsWith("\\\'")) { //$NON-NLS-1$ String run = frag; while (v.get(i + 1).startsWith("\\\'")) { //$NON-NLS-1$ run = run + v.get(i + 1); i++; } frag = decode(run); if (frag.trim().length() == 1 && skip > 0 && result.charAt(result.length() - 1) == frag.charAt(0)) { frag = ""; //$NON-NLS-1$ } skip--; } else if (frag.startsWith("\\")) { //$NON-NLS-1$ String ctl = getControl(frag); String remainder = getReminder(frag); if (ctl.equals("loch")) { //$NON-NLS-1$ inDBCH = false; inLOCH = true; inHICH = false; frag = remainder; } else if (ctl.equals("hich")) { //$NON-NLS-1$ inDBCH = false; inLOCH = false; inHICH = true; frag = remainder; } else if (ctl.equals("dbch")) { //$NON-NLS-1$ inDBCH = true; inLOCH = false; inHICH = false; frag = remainder; } else if (ctl.equals("uc")) { //$NON-NLS-1$ defaultUC = getValue(frag); frag = remainder; } else if (ctl.equals("u")) { //$NON-NLS-1$ frag = decodeU(getValue(frag)) + remainder; skip = Integer.parseInt(defaultUC); } else if (ctl.equals("f")) { //$NON-NLS-1$ String value = getValue(frag); if (!fontTable.containsKey(value)) { value = defaultFont; } defaultCpg = fontTable.get(value); srcEncoding = charsets.get(defaultCpg); if (value.equals(defaultFont) || ignorableFonts.containsKey(value)) { frag = remainder; } defaultFont = value; } else if (ctl.equals("af")) { //$NON-NLS-1$ String value = getValue(frag); if (!value.equals(defaultAF)) { defaultAF = value; } frag = remainder; } else if (ctl.equals("cf")) { //$NON-NLS-1$ String value = getValue(frag); if (value.equals(defaultCF)) { frag = remainder; } defaultCF = value; } else if (ctl.equals("s") || //$NON-NLS-1$ ctl.equals("cs") || //$NON-NLS-1$ ctl.equals("ts") || //$NON-NLS-1$ ctl.equals("ds")) { //$NON-NLS-1$ String style = getValue(frag); if (styleFonts.containsKey(style)) { String value = styleFonts.get(style); defaultCpg = fontTable.get(value); srcEncoding = charsets.get(defaultCpg); defaultFont = value; } if (cfTable.containsKey(style)) { defaultCF = cfTable.get(style); } else { defaultCF = "1"; //$NON-NLS-1$ } } else if (ctl.equals("pard")) { //$NON-NLS-1$ resetStatus(); } else if (ignore.containsKey(ctl)) { String value = getValue(frag); if (value.equals("")) { //$NON-NLS-1$ value = ctl; } frag = remainder; } if (frag.matches("[0-9].*")) { //$NON-NLS-1$ if (result.matches(".*\\\\[a-z]+[0-9]+")) { //$NON-NLS-1$ frag = " " + frag; //$NON-NLS-1$ } } else if (frag.matches("[a-zA-Z].*")) { //$NON-NLS-1$ if (result.matches(".*\\\\[a-z]+")) { //$NON-NLS-1$ frag = " " + frag; //$NON-NLS-1$ } } } else { // plain text if (skip > 0 && frag.startsWith(" ?")) { //$NON-NLS-1$ frag = frag.substring(2); skip--; } if (skip > 0 && frag.startsWith("?")) { //$NON-NLS-1$ frag = frag.substring(1); skip--; } } if (frag.matches("[0-9].*")) { //$NON-NLS-1$ if (result.matches(".*\\\\[a-z]+[0-9]*")) { //$NON-NLS-1$ frag = " " + frag; //$NON-NLS-1$ } } else if (frag.matches("[a-zA-Z].*")) { //$NON-NLS-1$ if (result.matches(".*\\\\[a-z]+")) { //$NON-NLS-1$ frag = " " + frag; //$NON-NLS-1$ } } result = result + frag; subMonitor2.worked(1); } subMonitor2.done(); // 此 paseGroup 方法非常耗时,经过测试,文件大小为 1867519 bytes(约 1.8m) 的 rtf 文件,在 paseGroup 方法中需热循环 1793397 次。 String temp = parseGroup(result, Progress.getSubMonitor(monitor, 8)); monitor.done(); return temp; } /** * Gets the reminder. * @param token * the token * @return the reminder */ private String getReminder(String token) { String control = getControl(token); token = token.substring(token.indexOf(control) + control.length()); StringBuffer buffer = new StringBuffer(); for (int i = 0; i < token.length(); i++) { char c = token.charAt(i); if ((c >= '0' && c <= '9') || c == '-') { buffer.append(c); } else { if (c == ' ') { buffer.append(c); } break; } } return token.substring(buffer.toString().length()); } /** * Reset status. */ private void resetStatus() { defaultUC = (String) defaultStatus.get("defaultUC"); //$NON-NLS-1$ defaultFont = (String) defaultStatus.get("defaultFont"); //$NON-NLS-1$ defaultAF = (String) defaultStatus.get("defaultAF"); //$NON-NLS-1$ defaultLang = (String) defaultStatus.get("defaultLang"); //$NON-NLS-1$ srcEncoding = (String) defaultStatus.get("srcEncoding"); //$NON-NLS-1$ defaultCpg = (String) defaultStatus.get("defaultCpg"); //$NON-NLS-1$ defaultCF = (String) defaultStatus.get("defaultCF"); //$NON-NLS-1$ } /** * Decode. * @param string * the string * @return the string * @throws UnsupportedEncodingException * the unsupported encoding exception */ private String decode(String string) throws UnsupportedEncodingException { String remainder = ""; //$NON-NLS-1$ if (string.indexOf(" ") != -1) { //$NON-NLS-1$ remainder = string.substring(string.indexOf(" ") + 1); //$NON-NLS-1$ } string = string.replaceAll("\'", ""); //$NON-NLS-1$ //$NON-NLS-2$ StringTokenizer tk = new StringTokenizer(string, "\\"); //$NON-NLS-1$ String converted = ""; //$NON-NLS-1$ if (inDBCH) { int size = tk.countTokens(); byte[] array = new byte[size]; int j = 0; while (tk.hasMoreTokens()) { String s = tk.nextToken(); array[j++] = (byte) Integer.parseInt(s, 16); } if (!srcEncoding.equals("Symbol")) { //$NON-NLS-1$ converted = new String(array, srcEncoding); } else { converted = new String(array, getEncoding("1252")); //$NON-NLS-1$ } } else if (inHICH) { while (tk.hasMoreTokens()) { String s = tk.nextToken(); if (!srcEncoding.equals("Symbol")) { //$NON-NLS-1$ byte[] array = new byte[1]; array[0] = (byte) Integer.parseInt(s, 16); converted = converted + new String(array, srcEncoding); } else { converted = converted + symbols.get(new Integer(Integer.parseInt(s, 16))); } } } else { // inLOCH if (!srcEncoding.equals("Symbol")) { //$NON-NLS-1$ while (tk.hasMoreTokens()) { String s = tk.nextToken(); byte b = (byte) Integer.parseInt(s, 16); byte[] array = new byte[2]; if (isLeadByte(b)) { // it is a leading byte, get next one and convert array[0] = b; array[1] = (byte) Integer.parseInt(tk.nextToken(), 16); } else { array[0] = b; array[1] = 0; } String ss = ""; //$NON-NLS-1$ try { ss = new String(array, srcEncoding); } catch (Exception e) { ss = new String(array, getEncoding("1252")); //$NON-NLS-1$ } converted = converted + ss.charAt(0); } } else { while (tk.hasMoreTokens()) { String s = tk.nextToken(); converted = converted + symbols.get(Integer.parseInt(s, 16)); } } } converted = replaceToken(converted, "{", "\uE008"); //$NON-NLS-1$ //$NON-NLS-2$ converted = replaceToken(converted, "}", "\uE007"); //$NON-NLS-1$ //$NON-NLS-2$ converted = replaceToken(converted, "\\", "\uE011"); //$NON-NLS-1$ //$NON-NLS-2$ return converted + remainder; } /** * Restore status. */ private void restoreStatus() { if (!stack.isEmpty()) { status = stack.pop(); defaultUC = (String) status.get("defaultUC"); //$NON-NLS-1$ defaultFont = (String) status.get("defaultFont"); //$NON-NLS-1$ defaultAF = (String) status.get("defaultAF"); //$NON-NLS-1$ defaultLang = (String) status.get("defaultLang"); //$NON-NLS-1$ srcEncoding = (String) status.get("srcEncoding"); //$NON-NLS-1$ defaultCpg = (String) status.get("defaultCpg"); //$NON-NLS-1$ inLOCH = ((Boolean) status.get("inLOCH")).booleanValue(); //$NON-NLS-1$ inHICH = ((Boolean) status.get("inHICH")).booleanValue(); //$NON-NLS-1$ inDBCH = ((Boolean) status.get("inDBCH")).booleanValue(); //$NON-NLS-1$ } else { status = new Hashtable<String, Object>(); status.put("defaultUC", defaultUC); //$NON-NLS-1$ status.put("defaultFont", defaultFont); //$NON-NLS-1$ status.put("defaultLang", defaultLang); //$NON-NLS-1$ status.put("srcEncoding", srcEncoding); //$NON-NLS-1$ status.put("defaultCpg", defaultCpg); //$NON-NLS-1$ status.put("defaultAF", defaultAF); //$NON-NLS-1$ status.put("inLOCH", new Boolean(inLOCH)); //$NON-NLS-1$ status.put("inHICH", new Boolean(inHICH)); //$NON-NLS-1$ status.put("inDBCH", new Boolean(inDBCH)); //$NON-NLS-1$ } } /** * Save curr status. */ private void saveCurrStatus() { status = new Hashtable<String, Object>(); status.put("defaultUC", defaultUC); //$NON-NLS-1$ status.put("defaultFont", defaultFont); //$NON-NLS-1$ status.put("defaultLang", defaultLang); //$NON-NLS-1$ status.put("srcEncoding", srcEncoding); //$NON-NLS-1$ status.put("defaultCpg", defaultCpg); //$NON-NLS-1$ status.put("defaultAF", defaultAF); //$NON-NLS-1$ status.put("inLOCH", new Boolean(inLOCH)); //$NON-NLS-1$ status.put("inHICH", new Boolean(inHICH)); //$NON-NLS-1$ status.put("inDBCH", new Boolean(inDBCH)); //$NON-NLS-1$ stack.push(status); } /** * Write str. * @param string * the string * @throws IOException * Signals that an I/O exception has occurred. */ private void writeStr(String string) throws IOException { string = replaceToken(string, "\uE008", "{"); //$NON-NLS-1$ //$NON-NLS-2$ string = replaceToken(string, "\uE007", "}"); //$NON-NLS-1$ //$NON-NLS-2$ string = replaceToken(string, "\uE011", "\\\\"); //$NON-NLS-1$ //$NON-NLS-2$ output.write(string.getBytes("UTF-8")); //$NON-NLS-1$ } /** * Builds the groups. */ private void buildGroups() { groups = new Vector<String>(); int level = 0; int i = header.length(); StringBuffer buffer = new StringBuffer(); int size = content.length(); while (i < size) { char c = content.charAt(i++); if (c != '\r' && c != '\n') { buffer.append(c); } if (c == '{') { level++; } if (c == '}') { level--; } if (level == 0) { groups.add(buffer.toString()); buffer = null; buffer = new StringBuffer(); } } groups.add(content.substring(i)); content = null; } /** * Builds the style list. * @param group * the group * @throws Exception * the exception */ private void buildStyleList(String group) throws Exception { int level = 0; int i = group.indexOf("{", 1); //$NON-NLS-1$ StringBuffer buffer = new StringBuffer(); while (i < group.length()) { char c = group.charAt(i++); if (c == '\n' || c == '\r') { continue; } buffer.append(c); if (c == '{') { level++; } if (c == '}') { level--; } if (level == 0) { String style = buffer.toString().trim(); if (style.indexOf("tw4winMark") != -1) { //$NON-NLS-1$ tw4winMark = true; winMark = getStyle(style) + "\\v\\cf" + getValue("cf", style) + "\\sub\\f" + getValue("f", style) + "\\fs24"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ } if (style.indexOf("tw4winError") != -1) { //$NON-NLS-1$ tw4winError = true; } if (style.indexOf("tw4winPopup") != -1) { //$NON-NLS-1$ tw4winPopup = true; } if (style.indexOf("tw4winJump") != -1) { //$NON-NLS-1$ tw4winJump = true; } if (style.indexOf("tw4winExternal") != -1) { //$NON-NLS-1$ tw4winExternal = true; winExternal = getStyle(style) + "\\cf" + getValue("cf", style) + "\\f" + getValue("f", style) + "\\lang1024"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ } if (style.indexOf("tw4winInternal") != -1) { //$NON-NLS-1$ tw4winInternal = true; winInternal = getStyle(style) + "\\cf" + getValue("cf", style) + "\\f" + getValue("f", style) + "\\lang1024"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ markStyle = "\\v\\cf" + getValue("cf", style) + "\\sub\\f" + getValue("f", style) + "\\fs24"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ } if (style.indexOf("tw4winTerm") != -1) { //$NON-NLS-1$ tw4winTerm = true; } if (style.indexOf("DO_NOT_TRANSLATE") != -1) { //$NON-NLS-1$ do_not_translate = true; not_translate = getStyle(style); } styles.add(style); buffer = null; buffer = new StringBuffer(); } } } /** * Gets the value. * @param token * the token * @return the value */ private String getValue(String token) { String control = getControl(token); if (control.equals("'")) { //$NON-NLS-1$ return token.substring(token.indexOf("'"), token.indexOf("'") + 2); //$NON-NLS-1$ //$NON-NLS-2$ } token = token.substring(token.indexOf(control) + control.length()); StringBuffer buffer = new StringBuffer(); for (int i = 0; i < token.length(); i++) { char c = token.charAt(i); if ((c >= '0' && c <= '9') || c == '-') { buffer.append(c); } else { break; } } return buffer.toString(); } /** * Gets the control. * @param token * the token * @return the control */ private String getControl(String token) { if (token.trim().length() < 2 || "{\\".indexOf(token.trim().charAt(0)) == -1) { //$NON-NLS-1$ return ""; //$NON-NLS-1$ } StringBuffer buffer = new StringBuffer(); for (int i = 1; i < token.length(); i++) { char c = token.charAt(i); if (c == '\\' || c == '*' || c == '{') { continue; } if (c == '\'') { return "'"; //$NON-NLS-1$ } if (!((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'))) { break; } buffer.append(c); } return buffer.toString(); } /** * Replace token. * @param string * the string * @param token * the token * @param newText * the new text * @return the string */ String replaceToken(String string, String token, String newText) { int index = string.indexOf(token); while (index != -1) { String before = string.substring(0, index); String after = string.substring(index + token.length()); string = before + newText + after; index = string.indexOf(token, index + newText.length()); } return string; } /** * Decode u. * @param current * the current * @return the string */ private String decodeU(String current) { String run = ""; //$NON-NLS-1$ int i = 0; for (i = 0; i < current.length(); i++) { if (isDigit(current.charAt(i)) || current.charAt(i) == '-') { break; } } if (current.charAt(i) == '-') { run = "-"; //$NON-NLS-1$ i++; } for (; i < current.length(); i++) { if (isDigit(current.charAt(i))) { run = run + current.charAt(i); } else { // avoid trailing spaces if any break; } } int value = Integer.parseInt(run); if (value < 0) { value = value + 65536; } if (!srcEncoding.equals("Symbol")) { //$NON-NLS-1$ return "" + new Character((char) value); //$NON-NLS-1$ } if (value > 0xF000) { value = value - 0xF000; } return symbols.get(new Integer(value)); } /** * Checks if is digit. * @param c * the c * @return true, if is digit */ private boolean isDigit(char c) { return c >= '0' && c <= '9'; } /** * Fill ignore. */ private void fillIgnore() { ignore = new Hashtable<String, String>(); ignore.put("insrsid", ""); //$NON-NLS-1$ //$NON-NLS-2$ ignore.put("charrsid", ""); //$NON-NLS-1$ //$NON-NLS-2$ ignore.put("langfe", ""); //$NON-NLS-1$ //$NON-NLS-2$ ignore.put("lang", ""); //$NON-NLS-1$ //$NON-NLS-2$ ignore.put("langnp", ""); //$NON-NLS-1$ //$NON-NLS-2$ ignore.put("sectrsid", ""); //$NON-NLS-1$ //$NON-NLS-2$ ignore.put("pararsid", ""); //$NON-NLS-1$ //$NON-NLS-2$ ignore.put("tblrsid", ""); //$NON-NLS-1$ //$NON-NLS-2$ ignore.put("delrsid", ""); //$NON-NLS-1$ //$NON-NLS-2$ } /** * Builds the color list. * @param group * the group */ private void buildColorList(String group) { colorList = new Vector<String>(); String list = group.substring(group.indexOf("colortbl") + "colortbl".length()).trim(); //$NON-NLS-1$ //$NON-NLS-2$ list = list.substring(list.indexOf("\\"), list.indexOf("}")).trim(); //$NON-NLS-1$ //$NON-NLS-2$ StringTokenizer tk = new StringTokenizer(list, ";"); //$NON-NLS-1$ while (tk.hasMoreTokens()) { String color = tk.nextToken().trim(); colorList.add(color); } } /** * Adds the styles. */ private void addStyles() { String tw4winMarkColor = "\\red128\\green0\\blue128"; //$NON-NLS-1$ String tw4winErrorColor = "\\red0\\green255\\blue0"; //$NON-NLS-1$ String tw4winPopupColor = "\\red0\\green128\\blue0"; //$NON-NLS-1$ String tw4winJumpColor = "\\red0\\green128\\blue128"; //$NON-NLS-1$ String tw4winExternalColor = "\\red128\\green128\\blue128"; //$NON-NLS-1$ String tw4winInternalColor = "\\red255\\green0\\blue0"; //$NON-NLS-1$ String tw4winTermColor = "\\red0\\green0\\blue255"; //$NON-NLS-1$ String doNotTranslateColor = "\\red128\\green0\\blue0"; //$NON-NLS-1$ int code = getNextFreestyle(); int font = getMaxFont(); fonts.add("{\\f" + font + "\\fmodern\\fprq1 {\\*\\panose 02070309020205020404}\\fcharset0 Courier New;}"); //$NON-NLS-1$ //$NON-NLS-2$ fontTable.put("" + font, "0"); //$NON-NLS-1$ //$NON-NLS-2$ int color = 0; String style = ""; //$NON-NLS-1$ if (!tw4winMark) { color = getColor(tw4winMarkColor); winMark = "\\cs" + code + "\\v\\cf" + color //$NON-NLS-1$ //$NON-NLS-2$ + "\\sub\\f" + font + "\\fs24"; //$NON-NLS-1$ //$NON-NLS-2$ style = "{\\*\\cs" + code++ + " \\additive \\v\\cf" + color //$NON-NLS-1$ //$NON-NLS-2$ + "\\sub\\f" + font + "\\fs24 tw4winMark;}"; //$NON-NLS-1$ //$NON-NLS-2$ styles.add(style); tw4winMark = true; } if (!tw4winError) { color = getColor(tw4winErrorColor); style = "{\\*\\cs" + code++ + " \\additive \\cf" + color + "\\fs40\\f" + font //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + "\\fs24 tw4winError;}"; //$NON-NLS-1$ styles.add(style); tw4winError = true; } if (!tw4winPopup) { color = getColor(tw4winPopupColor); style = "{\\*\\cs" + code++ + " \\additive \\f" + font + "\\cf" + color + " tw4winPopup;}"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ styles.add(style); tw4winPopup = true; } if (!tw4winJump) { color = getColor(tw4winJumpColor); style = "{\\*\\cs" + code++ + " \\additive \\f" + font + "\\cf" + color + " tw4winJump;}"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ styles.add(style); tw4winJump = true; } if (!tw4winExternal) { winExternal = "\\cs" + code + "\\cf" + color + "\\f" + font //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + "\\lang1024"; //$NON-NLS-1$ color = getColor(tw4winExternalColor); style = "{\\*\\cs" + code++ + " \\additive \\cf" + color + "\\f" + font //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + "\\lang1024 tw4winExternal;}"; //$NON-NLS-1$ styles.add(style); tw4winExternal = true; } if (!tw4winInternal) { color = getColor(tw4winInternalColor); winInternal = "\\cs" + code + "\\cf" + color + "\\f" + font //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + "\\lang1024"; //$NON-NLS-1$ style = "{\\*\\cs" + code++ + " \\additive \\cf" + color + "\\f" + font //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + "\\lang1024 tw4winInternal;}"; //$NON-NLS-1$ styles.add(style); tw4winInternal = true; } if (!tw4winTerm) { color = getColor(tw4winTermColor); style = "{\\*\\cs" + code++ + " \\additive \\cf" + color + " tw4winTerm;}"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ styles.add(style); tw4winTerm = true; } if (!do_not_translate) { color = getColor(doNotTranslateColor); style = "{\\*\\cs" + code++ + " \\additive \\cf" + color + "\\f" + font //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + "\\lang1024 DO_NOT_TRANSLATE;}"; //$NON-NLS-1$ styles.add(style); do_not_translate = true; } } /** * Gets the color. * @param color * the color * @return the color */ private int getColor(String color) { for (int i = 0; i < colorList.size(); i++) { if (color.equals(colorList.get(i))) { return i + 1; } } colorList.add(color); return colorList.size(); } /** * Gets the next freestyle. * @return the next freestyle */ private int getNextFreestyle() { int max = -1; for (int i = 0; i < styles.size(); i++) { String string = styles.get(i); StringTokenizer tk = new StringTokenizer(string, "\\", true); //$NON-NLS-1$ while (tk.hasMoreTokens()) { String token = tk.nextToken(); if (token.equals("\\")) { //$NON-NLS-1$ if (!tk.hasMoreTokens()) { break; } token = token + tk.nextToken(); } if (getControl(token).equals("s") //$NON-NLS-1$ || getControl(token).equals("cs") //$NON-NLS-1$ || getControl(token).equals("ds") //$NON-NLS-1$ || getControl(token).equals("ts")) { //$NON-NLS-1$ int value = Integer.parseInt(getValue(token).trim()); if (value > max) { max = value; } } } } return max + 1; } /** * Gets the max font. * @return the max font */ private int getMaxFont() { int max = -1; for (int i = 0; i < fonts.size(); i++) { String string = fonts.get(i); StringTokenizer tk = new StringTokenizer(string, "\\", true); //$NON-NLS-1$ while (tk.hasMoreTokens()) { String token = tk.nextToken(); if (token.equals("\\")) { //$NON-NLS-1$ token = token + tk.nextToken(); } if (getControl(token).equals("f")) { //$NON-NLS-1$ int value = Integer.parseInt(getValue(token).trim()); if (value > max) { max = value; } } } } return max + 1; } /** * Checks if is lead byte. * @param aByte * the a byte * @return true, if is lead byte */ private boolean isLeadByte(byte aByte) { if (srcEncoding.equals(charsets.get("128"))) { //$NON-NLS-1$ // Shift-JIS if ((aByte >= 0x81) && (aByte <= 0x9F)) { return true; } if ((aByte >= 0xE0) && (aByte <= 0xEE)) { return true; } if ((aByte >= 0xFA) && (aByte <= 0xFC)) { return true; } } if (srcEncoding.equals(charsets.get("134"))) { //$NON-NLS-1$ // 936: Chinese Simplified (GB2312) if ((aByte >= 0xA1) && (aByte <= 0xA9)) { return true; } if ((aByte >= 0xB0) && (aByte <= 0xF7)) { return true; } } if (srcEncoding.equals(getEncoding("949"))) { //$NON-NLS-1$ // 949: Korean if ((aByte >= 0x81) && (aByte <= 0xC8)) { return true; } if ((aByte >= 0xCA) && (aByte <= 0xFD)) { return true; } } if (srcEncoding.equals(charsets.get("136"))) { //$NON-NLS-1$ // 950: Chinese Traditional (Big5) if ((aByte >= 0xA1) && (aByte <= 0xC6)) { return true; } if ((aByte >= 0xC9) && (aByte <= 0xF9)) { return true; } } // All other encoding: No lead bytes return false; } /** * Parses the. * @param group * the group */ private void parse(String group, IProgressMonitor monitor) { System.out.println("Initializing rules"); //$NON-NLS-1$ initBreaks(); segments = new Vector<String>(); StringTokenizer tk = new StringTokenizer(group, "\\{}", true); //$NON-NLS-1$ System.out.println("Processing " + tk.countTokens() + " tokens"); //$NON-NLS-1$ //$NON-NLS-2$ String segment = ""; //$NON-NLS-1$ String token = ""; //$NON-NLS-1$ int tokenSize = tk.countTokens(); monitor.beginTask(Messages.getString("rtf.Rtf2Xliff.task10"), tokenSize); monitor.subTask(""); while (tk.hasMoreTokens()) { // 是否取消操作 if (monitor.isCanceled()) { throw new OperationCanceledException(Messages.getString("rtf.cancel")); } token = tk.nextToken(); if (token.equals("\\")) { //$NON-NLS-1$ token = token + tk.nextToken(); } if (token.equals("{")) { //$NON-NLS-1$ token = token + tk.nextToken(); } if (token.equals("}")) { //$NON-NLS-1$ skip = 0; } if (token.equals("{\\")) { //$NON-NLS-1$ token = token + tk.nextToken(); } if (token.equals("\\*") || token.equals("{\\*")) { //$NON-NLS-1$ //$NON-NLS-2$ token = token + tk.nextToken() + tk.nextToken(); } String ctrl = getControl(token); if (ctrl.equals("footnote")) { //$NON-NLS-1$ // skip until the end of the footnote // ignore any breaking token segment = segment + token.substring(0, token.indexOf("\\footnote")); //$NON-NLS-1$ token = token.substring(token.indexOf("\\footnote")); //$NON-NLS-1$ int level = 1; boolean canBreak = false; do { if (token.equals("{")) { //$NON-NLS-1$ level++; } if (token.equals("}")) { //$NON-NLS-1$ level--; } if (level == 0) { canBreak = true; } segment = segment + token; token = tk.nextToken(); } while (!canBreak); // == false); ctrl = getControl(token); } if (breaks.containsKey(ctrl)) { if (token.startsWith("{")) { //$NON-NLS-1$ segment = segment + token.substring(0, token.indexOf("\\")); //$NON-NLS-1$ token = token.substring(token.indexOf("\\")); //$NON-NLS-1$ } segments.add(segment); segment = ""; //$NON-NLS-1$ } segment = segment + token; monitor.worked(1); } monitor.done(); segments.add(segment); } /** * Inits the breaks. */ private void initBreaks() { breaks = new Hashtable<String, String>(); breaks.put("par", ""); //$NON-NLS-1$ //$NON-NLS-2$ breaks.put("pard", ""); //$NON-NLS-1$ //$NON-NLS-2$ breaks.put("row", ""); //$NON-NLS-1$ //$NON-NLS-2$ breaks.put("cell", ""); //$NON-NLS-1$ //$NON-NLS-2$ breaks.put("nestcell", ""); //$NON-NLS-1$ //$NON-NLS-2$ breaks.put("dobypara", ""); //$NON-NLS-1$ //$NON-NLS-2$ breaks.put("sectd", ""); //$NON-NLS-1$ //$NON-NLS-2$ breaks.put("header", ""); //$NON-NLS-1$ //$NON-NLS-2$ breaks.put("footer", ""); //$NON-NLS-1$ //$NON-NLS-2$ breaks.put("headerf", ""); //$NON-NLS-1$ //$NON-NLS-2$ breaks.put("footerf", ""); //$NON-NLS-1$ //$NON-NLS-2$ breaks.put("headerl", ""); //$NON-NLS-1$ //$NON-NLS-2$ breaks.put("headerr", ""); //$NON-NLS-1$ //$NON-NLS-2$ breaks.put("footerl", ""); //$NON-NLS-1$ //$NON-NLS-2$ breaks.put("footerr", ""); //$NON-NLS-1$ //$NON-NLS-2$ if (!taggedRTF) { breaks.put("line", ""); //$NON-NLS-1$ //$NON-NLS-2$ // breaks.put("tab",""); } // breaks.put("do",""); // breaks.put("sp",""); } /** * Check segments. * @throws IOException * Signals that an I/O exception has occurred. * @throws SAXException * the SAX exception */ private void checkSegments(IProgressMonitor monitor) throws IOException, SAXException { monitor.beginTask(Messages.getString("rtf.Rtf2Xliff.task11"), segments.size()); monitor.subTask(""); for (int i = 0; i < segments.size(); i++) { // 是否取消操作 if (monitor.isCanceled()) { throw new OperationCanceledException(Messages.getString("rtf.cancel")); } String segment = segments.get(i); String trimmed = segment.trim(); if (inExternal && trimmed.startsWith("\\pard")) { //$NON-NLS-1$ inExternal = false; } processSegment(segment); monitor.worked(1); } monitor.done(); } /** * Write skl. * @param string * the string * @throws IOException * Signals that an I/O exception has occurred. */ private void writeSkl(String string) throws IOException { string = replaceToken(string, "\uE008", "\\{"); //$NON-NLS-1$ //$NON-NLS-2$ string = replaceToken(string, "\uE007", "\\}"); //$NON-NLS-1$ //$NON-NLS-2$ string = replaceToken(string, "\uE011", "\\\\"); //$NON-NLS-1$ //$NON-NLS-2$ string = replaceToken(string, "\u0009", "\\tab "); //$NON-NLS-1$ //$NON-NLS-2$ string = restoreControls(string); skeleton.write(string.getBytes("UTF-8")); //$NON-NLS-1$ } /** * Write skeleton. * @param string * the string * @throws IOException * Signals that an I/O exception has occurred. */ private void writeSkeleton(String string) throws IOException { string = replaceToken(string, "\uE008", "\\{"); //$NON-NLS-1$ //$NON-NLS-2$ string = replaceToken(string, "\uE007", "\\}"); //$NON-NLS-1$ //$NON-NLS-2$ string = replaceToken(string, "\uE011", "\\\\"); //$NON-NLS-1$ //$NON-NLS-2$ string = replaceToken(string, "\u0009", "\\tab "); //$NON-NLS-1$ //$NON-NLS-2$ string = restoreControls(string); skeleton.write(clean(string).getBytes("UTF-8")); //$NON-NLS-1$ } /** * Restore controls. * @param value * the value * @return the string */ private String restoreControls(String value) { value = replaceToken(value, "" + '\u2002', "\\enspace "); //$NON-NLS-1$ //$NON-NLS-2$ value = replaceToken(value, "" + '\u2003', "\\emspace "); //$NON-NLS-1$ //$NON-NLS-2$ value = replaceToken(value, "" + '\u2005', "\\qmspace "); //$NON-NLS-1$ //$NON-NLS-2$ value = replaceToken(value, "" + '\u2014', "\\emdash "); //$NON-NLS-1$ //$NON-NLS-2$ value = replaceToken(value, "" + '\u2013', "\\endash "); //$NON-NLS-1$ //$NON-NLS-2$ value = replaceToken(value, "" + '\u2018', "\\lquote "); //$NON-NLS-1$ //$NON-NLS-2$ value = replaceToken(value, "" + '\u2019', "\\rquote "); //$NON-NLS-1$ //$NON-NLS-2$ value = replaceToken(value, "" + '\u201C', "\\ldblquote "); //$NON-NLS-1$ //$NON-NLS-2$ value = replaceToken(value, "" + '\u201D', "\\rdblquote "); //$NON-NLS-1$ //$NON-NLS-2$ value = replaceToken(value, "" + '\u00A0', "\\~"); //$NON-NLS-1$ //$NON-NLS-2$ value = replaceToken(value, "" + '\u2011', "\\_"); //$NON-NLS-1$ //$NON-NLS-2$ value = replaceToken(value, "" + '\u00AD', "\\-"); //$NON-NLS-1$ //$NON-NLS-2$ return value; } /** * Process segment. * @param fragment * the fragment * @throws IOException * Signals that an I/O exception has occurred. * @throws SAXException * the SAX exception */ private void processSegment(String fragment) throws IOException, SAXException { String string = XMLOutputter.validChars(TextUtil.cleanString(fragment)); String segment = ""; //$NON-NLS-1$ boolean inPh = false; StringTokenizer tk = new StringTokenizer(string, "\\{}", true); //$NON-NLS-1$ while (tk.hasMoreElements()) { String token = tk.nextToken(); if (token.equals("\\")) { //$NON-NLS-1$ token = token + tk.nextToken(); } if (token.equals("\\*")) { //$NON-NLS-1$ token = token + tk.nextToken() + tk.nextToken(); } if (!inPh && (token.startsWith("\\") || token.startsWith("{") || token.startsWith("}"))) { //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ segment = segment + "<ph>"; //$NON-NLS-1$ inPh = true; } if (taggedRTF && (inExternal || getControl(token).equals("cs") && ((getValue(token).equals(externalValue)) || (getValue(token).equals(noTranslateValue))))) { //$NON-NLS-1$ // skip Trados external tags, until '}' is found if (inPh && !inExternal) { segment = segment + "</ph><ph>"; //$NON-NLS-1$ } inExternal = true; segment = segment + token; String s = ""; //$NON-NLS-1$ if (tk.hasMoreTokens()) { s = tk.nextToken(); } while (!s.equals("}") && tk.hasMoreTokens()) { //$NON-NLS-1$ String clean = clean(s); segment = segment + clean; s = tk.nextToken(); } if (s.equals("}")) { //$NON-NLS-1$ inExternal = false; } if (!tk.hasMoreTokens() && inExternal) { segment = segment + clean(s); s = ""; //$NON-NLS-1$ } token = s; if (token.equals("\\")) { //$NON-NLS-1$ token = token + tk.nextToken(); } if (token.equals("\\*")) { //$NON-NLS-1$ token = token + tk.nextToken() + tk.nextToken(); } } if (taggedRTF && getControl(token).equals("cs") && getValue(token).equals(internalValue)) { //$NON-NLS-1$ // skip Trados internal tags, until '}' is found if (inPh) { int idx = segment.lastIndexOf("{"); //$NON-NLS-1$ int phStarts = segment.lastIndexOf("<ph>") + 4; //$NON-NLS-1$ String tag = segment.substring(phStarts); if (idx != -1 && idx > phStarts && (tag.startsWith("\\par") //$NON-NLS-1$ || tag.startsWith("\\cell") //$NON-NLS-1$ || tag.startsWith("\\row") //$NON-NLS-1$ || tag.startsWith("\\nestcell") //$NON-NLS-1$ || tag.startsWith("\\dobypara") //$NON-NLS-1$ )) { segment = segment.substring(0, idx) + "</ph><ph>" + segment.substring(idx); //$NON-NLS-1$ } } segment = segment + token; String s = tk.nextToken(); while (!s.equals("}") && tk.hasMoreTokens()) { //$NON-NLS-1$ segment = segment + clean(s); s = tk.nextToken(); } if (!tk.hasMoreTokens()) { segment = segment + clean(s); s = ""; //$NON-NLS-1$ } token = s; if (token.equals("\\")) { //$NON-NLS-1$ token = token + tk.nextToken(); } if (token.equals("\\*")) { //$NON-NLS-1$ token = token + tk.nextToken() + tk.nextToken(); } } if (getControl(token).equals("field") //$NON-NLS-1$ || getControl(token).equals("listtext") //$NON-NLS-1$ || getControl(token).equals("do") //$NON-NLS-1$ || getControl(token).equals("sp")) { //$NON-NLS-1$ // skip field definition, until '}' is found // check if there are fonts to preserve segment = segment + token; if (tk.hasMoreTokens()) { String s = tk.nextToken(); int level = 1; if (s.equals("{")) { //$NON-NLS-1$ level++; } if (s.equals("}")) { //$NON-NLS-1$ level--; } while (!(s.equals("}") && level <= 0) && tk.hasMoreTokens()) { //$NON-NLS-1$ s = replaceToken(s, "\uE008", "\\{"); //$NON-NLS-1$ //$NON-NLS-2$ s = replaceToken(s, "\uE007", "\\}"); //$NON-NLS-1$ //$NON-NLS-2$ s = replaceToken(s, "\uE011", "\\\\"); //$NON-NLS-1$ //$NON-NLS-2$ s = replaceToken(s, "\u0009", "\\tab "); //$NON-NLS-1$ //$NON-NLS-2$ segment = segment + clean(s); s = tk.nextToken(); if (s.equals("\\")) { //$NON-NLS-1$ s = s + tk.nextToken(); } if (s.equals("\\*")) { //$NON-NLS-1$ s = s + tk.nextToken() + tk.nextToken(); } if (s.equals("{")) { //$NON-NLS-1$ level++; } if (s.equals("}")) { //$NON-NLS-1$ level--; } s = replaceToken(s, "\uE011", "\\\\"); //$NON-NLS-1$ //$NON-NLS-2$ } token = s; if (!(token.startsWith("\\") || token.startsWith("}") || token.startsWith("{")) && segment.endsWith("\\")) { //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ token = "\\" + s; //$NON-NLS-1$ segment = segment.substring(0, segment.length() - 1); } if (token.equals("\\")) { //$NON-NLS-1$ token = token + tk.nextToken(); } if (token.equals("\\*")) { //$NON-NLS-1$ token = token + tk.nextToken() + tk.nextToken(); } } } if (getControl(token).equals("pict")) { //$NON-NLS-1$ // skip the picture data int level = 1; while (level > 0) { segment = segment + token; token = tk.nextToken(); if (token.equals("{")) { //$NON-NLS-1$ level++; } if (token.equals("}")) { //$NON-NLS-1$ level--; } } if (token.equals("\\")) { //$NON-NLS-1$ token = token + tk.nextToken(); } if (token.equals("\\*")) { //$NON-NLS-1$ token = token + tk.nextToken() + tk.nextToken(); } } if (getControl(token).equals("datafield") //$NON-NLS-1$ || getControl(token).equals("bkmkstart") //$NON-NLS-1$ || getControl(token).equals("bkmkend")) { //$NON-NLS-1$ // skip field data, until '}' is found segment = segment + token; String s = tk.nextToken(); while (!s.equals("}") && tk.hasMoreTokens()) { //$NON-NLS-1$ segment = segment + clean(s); s = tk.nextToken(); } token = s; if (token.equals("\\")) { //$NON-NLS-1$ token = token + tk.nextToken(); } if (token.equals("\\*")) { //$NON-NLS-1$ token = token + tk.nextToken() + tk.nextToken(); } } if (token.startsWith("\\")) { //$NON-NLS-1$ String text = removeCtrl(token); String ctl = getControl(token); if (ctl.equals("pntxta") //$NON-NLS-1$ || ctl.equals("pntxtb") //$NON-NLS-1$ || ctl.equals("sv") //$NON-NLS-1$ || ctl.equals("sn")) { //$NON-NLS-1$ // this control needs a parameter if (text.matches("^\\s[a-zA-Z0-9\\s].*")) { //$NON-NLS-1$ // has a space in front of the parameter text = text.substring(2); } else { text = text.substring(1); } } if (text.trim().equals("")) { //$NON-NLS-1$ segment = segment + token; } else { segment = segment + token.substring(0, token.indexOf(text)) + "</ph>" + text; //$NON-NLS-1$ inPh = false; } } else if (token.startsWith("{") || token.startsWith("}")) { //$NON-NLS-1$ //$NON-NLS-2$ String text = token.substring(1); if (text.trim().equals("")) { //$NON-NLS-1$ segment = segment + token; } else { segment = segment + token.charAt(0) + "</ph>" + text; //$NON-NLS-1$ inPh = false; } } else { if (inPh) { segment = segment + "</ph>"; //$NON-NLS-1$ inPh = false; } segment = segment + token; } } if (inPh) { segment = segment + "</ph>"; //$NON-NLS-1$ } if (containsText(segment)) { writeSegment(segment); } else { writeSkl(Xliff2Rtf.cleanChars(fragment)); } } /** * Clean. * @param source * the source * @return the string */ private String clean(String source) { String clean = ""; //$NON-NLS-1$ int from = source.indexOf("blipuid"); //$NON-NLS-1$ if (from != -1) { StringTokenizer tk = new StringTokenizer(source, "\\{}", true); //$NON-NLS-1$ while (tk.hasMoreTokens()) { String token = tk.nextToken(); if (token.length() < 1000) { clean = clean + Xliff2Rtf.clean(token); } else { clean = clean + token; } } } else { return Xliff2Rtf.clean(source); } return clean; } /** * Contains text. * @param segment * the segment * @return true, if successful * @throws SAXException * the SAX exception * @throws IOException * Signals that an I/O exception has occurred. */ private boolean containsText(String segment) throws SAXException, IOException { SAXBuilder builder = new SAXBuilder(); String text = "<?xml version=\"1.0\"?>\n<segment>" + segment //$NON-NLS-1$ + "</segment>"; //$NON-NLS-1$ ByteArrayInputStream stream = new ByteArrayInputStream(text.getBytes("UTF-8")); //$NON-NLS-1$ Document doc = builder.build(stream); List<Node> rootContent = doc.getRootElement().getContent(); Iterator<Node> it = rootContent.iterator(); while (it.hasNext()) { Node n = it.next(); if (n.getNodeType() == Node.TEXT_NODE) { String s = n.getNodeValue(); if (taggedRTF) { s = removeTradosTag(s); } if (!s.trim().equals("")) { //$NON-NLS-1$ s = s.trim(); for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); if (c != '.' && c != ',' && c != '(' && c != ')' && c != '-' && c != '\u2022' && c != '\u00B7' && c != '\u2219' && c != '\u25D8' && c != '\u25E6') { return true; } } } } } return false; } /** * Removes the trados tag. * @param s * the s * @return the string */ private String removeTradosTag(String s) { s = replaceToken(s, '\uE008' + "0>", ""); //$NON-NLS-1$ //$NON-NLS-2$ s = replaceToken(s, "<0" + '\uE007', ""); //$NON-NLS-1$ //$NON-NLS-2$ int from = s.indexOf("<" + '\uE007'); //$NON-NLS-1$ int to = s.indexOf('\uE008' + ">"); //$NON-NLS-1$ if (from != -1 && to != -1) { s = s.substring(0, from) + s.substring(to + 2); } return s; } /** * Removes the ctrl. * @param token * the token * @return the string */ private String removeCtrl(String token) { int i = 1; // skip ctrl word for (; i < token.length(); i++) { char c = token.charAt(i); if (c == '\\' || c == '*' || (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) { continue; } break; } // skip numeric argument for (; i < token.length(); i++) { char c = token.charAt(i); if (c == '-' || (c >= '0' && c <= '9')) { continue; } break; } StringBuffer buffer = new StringBuffer(); for (; i < token.length(); i++) { char c = token.charAt(i); buffer.append(c); } String result = buffer.toString(); if (result.length() == 0) { return ""; //$NON-NLS-1$ } if (Character.isSpaceChar(result.charAt(0))) { return result.substring(1); } return result; } /** * Write segment. * @param string * the string * @throws IOException * Signals that an I/O exception has occurred. * @throws SAXException * the SAX exception */ private void writeSegment(String string) throws IOException, SAXException { if (segByElement) { if (taggedRTF) { if (find(string, "\uE008" + "0&gt;", 0) != -1) { //$NON-NLS-1$ //$NON-NLS-2$ // segmented by trados String[] segs = splitTagged(string); for (int i = 0; i < segs.length; i++) { if (containsText(segs[i])) { if (find(segs[i], "\uE008" + "0&gt;", 0) != -1) { //$NON-NLS-1$ //$NON-NLS-2$ writeStr(tag(segs[i])); writeSkeleton("%%%" + segId++ + "%%%\n"); //$NON-NLS-1$ //$NON-NLS-2$ } else { tidy(segs[i]); writeSkeleton(Xliff2Rtf.cleanChars(start)); writeStr(tag(meat)); writeSkeleton("%%%" + segId++ + "%%%\n"); //$NON-NLS-1$ //$NON-NLS-2$ writeSkeleton(Xliff2Rtf.cleanChars(end)); } } else { writeSkeleton(Xliff2Rtf.cleanChars(unTag(segs[i]))); } } } else { // not presegmented, segment by sentence String[] segs = segmenter.segment(string); for (int i = 0; i < segs.length; i++) { if (containsText(segs[i])) { tidy(segs[i]); writeSkeleton(Xliff2Rtf.cleanChars(start)); writeStr(tag(meat)); writeSkeleton("%%%" + segId++ + "%%%\n"); //$NON-NLS-1$ //$NON-NLS-2$ writeSkeleton(Xliff2Rtf.cleanChars(end)); } else { writeSkeleton(unTag(Xliff2Rtf.cleanChars(segs[i]))); } } } } else { // segment by paragraph tidy(string); writeSkeleton(Xliff2Rtf.cleanChars(start)); writeStr(tag(meat)); writeSkeleton("%%%" + segId++ + "%%%\n"); //$NON-NLS-1$ //$NON-NLS-2$ writeSkeleton(Xliff2Rtf.cleanChars(end)); } } else { // segment by sentence String[] segs = segmenter.segment(string); for (int i = 0; i < segs.length; i++) { if (containsText(segs[i])) { tidy(segs[i]); writeSkeleton(Xliff2Rtf.cleanChars(start)); writeStr(tag(meat)); writeSkeleton("%%%" + segId++ + "%%%\n"); //$NON-NLS-1$ //$NON-NLS-2$ writeSkeleton(Xliff2Rtf.cleanChars(end)); } else { writeSkeleton(unTag(Xliff2Rtf.cleanChars(segs[i]))); } } } } /** * Find. * @param text * the text * @param token * the token * @param from * the from * @return the int */ public int find(String text, String token, int from) { int length = text.length(); for (int i = from; i < length; i++) { String remaining = text.substring(i); if (remaining.startsWith("<ph")) { //$NON-NLS-1$ int ends = remaining.indexOf("</ph>"); //$NON-NLS-1$ if (ends != -1) { remaining = remaining.substring(ends + 5); i = i + ends + 5; } } String trimmed = removePh(remaining); if (trimmed.startsWith(token)) { return i; } } return -1; } /** * Removes the ph. * @param string * the string * @return the string */ private String removePh(String string) { String result = ""; //$NON-NLS-1$ int starts = string.indexOf("<ph"); //$NON-NLS-1$ while (starts != -1) { result = result + string.substring(0, starts); string = string.substring(starts); int ends = string.indexOf("</ph>"); //$NON-NLS-1$ if (ends != -1) { string = string.substring(ends + 5); } starts = string.indexOf("<ph"); //$NON-NLS-1$ } return result + string; } /** * Tidy. * @param string * the string * @throws SAXException * the SAX exception * @throws IOException * Signals that an I/O exception has occurred. */ private void tidy(String string) throws SAXException, IOException { if (!taggedRTF) { string = string.replaceAll("</ph><ph>", ""); //$NON-NLS-1$ //$NON-NLS-2$ } else { string = replaceToken(string, "<ph>}</ph><ph>", "<ph>}"); //$NON-NLS-1$ //$NON-NLS-2$ string = replaceToken(string, "</ph><ph>{</ph>", "{</ph>"); //$NON-NLS-1$ //$NON-NLS-2$ } start = ""; //$NON-NLS-1$ end = ""; //$NON-NLS-1$ meat = string; SAXBuilder builder = new SAXBuilder(); String text = "<?xml version=\"1.0\"?>\n<segment>" + string //$NON-NLS-1$ + "</segment>"; //$NON-NLS-1$ ByteArrayInputStream stream = new ByteArrayInputStream(text.getBytes("UTF-8")); //$NON-NLS-1$ Document doc = builder.build(stream); Element root = doc.getRootElement(); List<Node> rootContent = root.getContent(); Iterator<Node> it = rootContent.iterator(); int tags = 0; while (it.hasNext()) { Node n = it.next(); if (n.getNodeType() == Node.ELEMENT_NODE) { tags++; } } if (tags == 0) { return; } if (tags == 1) { Node n = rootContent.get(0); if (n.getNodeType() == Node.ELEMENT_NODE) { // starts with a tag Element e = new Element(n); if (!(taggedRTF && e.toString().indexOf(winInternal) != -1)) { start = e.getText(); rootContent.remove(n); root.setContent(rootContent); meat = root.toString().substring(9, root.toString().length() - 10); } return; } n = rootContent.get(rootContent.size() - 1); if (n.getNodeType() == Node.ELEMENT_NODE) { // ends with a tag Element e = new Element(n); if (!(taggedRTF && e.toString().indexOf(winInternal) != -1)) { end = e.getText(); rootContent.remove(n); root.setContent(rootContent); meat = root.toString().substring(9, root.toString().length() - 10); } return; } } Node n1 = rootContent.get(0); Node n2 = rootContent.get(rootContent.size() - 1); if (tags == 2 && n1.getNodeType() == Node.ELEMENT_NODE && n2.getNodeType() == Node.ELEMENT_NODE) { // starts and ends with a tag, no tags in the middle Element e1 = new Element(n1); start = e1.getText(); Element e2 = new Element(n2); end = e2.getText(); rootContent.remove(n1); rootContent.remove(n2); root.setContent(rootContent); meat = root.toString().substring(9, root.toString().length() - 10); return; } if (n1.getNodeType() == Node.ELEMENT_NODE) { // remove initial tag Element e1 = new Element(n1); if (!(taggedRTF && e1.toString().indexOf(winInternal) != -1)) { start = e1.getText(); rootContent.remove(n1); root.setContent(rootContent); meat = root.toString().substring(9, root.toString().length() - 10); } } } /** * Tag. * @param string * the string * @return the string * @throws SAXException * the SAX exception * @throws IOException * Signals that an I/O exception has occurred. */ private String tag(String string) throws SAXException, IOException { if (!taggedRTF && string.indexOf("</ph><ph>") != -1) { //$NON-NLS-1$ string = string.replaceAll("</ph><ph>", ""); //$NON-NLS-1$ //$NON-NLS-2$ } SAXBuilder builder = new SAXBuilder(); String text = "<?xml version=\"1.0\"?>\n<source xml:lang=\"" + sourceLanguage + "\">" + string //$NON-NLS-1$ //$NON-NLS-2$ + "</source>"; //$NON-NLS-1$ ByteArrayInputStream stream = new ByteArrayInputStream(text.getBytes("UTF-8")); //$NON-NLS-1$ Document doc = builder.build(stream); Element root = doc.getRootElement(); List<Node> rootContent = root.getContent(); int k = 0; Iterator<Node> it = rootContent.iterator(); Vector<Node> v = new Vector<Node>(); while (it.hasNext()) { Node n = it.next(); if (n.getNodeType() == Node.ELEMENT_NODE) { Element e = new Element(n); e.setAttribute("id", "" + k++); //$NON-NLS-1$ //$NON-NLS-2$ v.add(n); } else { v.add(n); } } root.setContent(v); return " <trans-unit id=\"" //$NON-NLS-1$ + segId + "\" xml:space=\"preserve\" approved=\"no\">\n " + root.toString() //$NON-NLS-1$ + "\n </trans-unit>\n"; //$NON-NLS-1$ } /** * Split tagged. * @param text * the text * @return the string[] */ private String[] splitTagged(String text) { Vector<String> strings = new Vector<String>(); int index = find(text, "\uE008" + "0&gt;", 1); //$NON-NLS-1$ //$NON-NLS-2$ while (index != -1) { String candidate = text.substring(0, index); int ends = find(candidate, "&lt;0" + "\uE007", 0); //$NON-NLS-1$ //$NON-NLS-2$ while (ends != -1) { if (!candidate.substring(0, ends + 6).endsWith("0" + "\uE007")) { //$NON-NLS-1$ //$NON-NLS-2$ ends += candidate.substring(ends).indexOf("0" + "\uE007") + 2; //$NON-NLS-1$ //$NON-NLS-2$ strings.add(candidate.substring(0, ends)); candidate = candidate.substring(ends); } else { strings.add(candidate.substring(0, ends + 6)); candidate = candidate.substring(ends + 6); } ends = find(candidate, "&lt;0" + "\uE007", 1); //$NON-NLS-1$ //$NON-NLS-2$ } strings.add(candidate); text = text.substring(index); index = find(text, "\uE008" + "0&gt;", 1); //$NON-NLS-1$ //$NON-NLS-2$ } if (!text.endsWith("0" + "\uE007")) { //$NON-NLS-1$ //$NON-NLS-2$ index = text.lastIndexOf("0" + "\uE007"); //$NON-NLS-1$ //$NON-NLS-2$ if (index != -1) { strings.add(text.substring(0, index + 2)); text = text.substring(index + 2); } } strings.add(text); String[] result = new String[strings.size()]; for (int i = 0; i < strings.size(); i++) { result[i] = strings.get(i); } return result; } /** * Un tag. * @param string * the string * @return the string * @throws SAXException * the SAX exception * @throws IOException * Signals that an I/O exception has occurred. */ private String unTag(String string) throws SAXException, IOException { SAXBuilder builder = new SAXBuilder(); String text = "<?xml version=\"1.0\"?>\n<tag>" + string + "</tag>"; //$NON-NLS-1$ //$NON-NLS-2$ ByteArrayInputStream stream = new ByteArrayInputStream(text.getBytes("UTF-8")); //$NON-NLS-1$ Document doc = builder.build(stream); Element root = doc.getRootElement(); List<Node> rootContent = root.getContent(); Iterator<Node> it = rootContent.iterator(); String result = ""; //$NON-NLS-1$ while (it.hasNext()) { Node n = it.next(); if (n.getNodeType() == Node.ELEMENT_NODE) { Element e = new Element(n); result = result + e.getText(); } else if (n.getNodeType() == Node.TEXT_NODE) { result = result + n.getNodeValue(); } } return result; } /** * Gets the style. * @param style * the style * @return the style */ private String getStyle(String style) { StringTokenizer tk = new StringTokenizer(style, "\\", true); //$NON-NLS-1$ String token = tk.nextToken(); if (token.equals("{")) { //$NON-NLS-1$ token = tk.nextToken(); } if (token.equals("\\")) { //$NON-NLS-1$ token = token + tk.nextToken(); } if (token.equals("\\*")) { //$NON-NLS-1$ // Skip the \\* token = tk.nextToken() + tk.nextToken(); } return token.trim(); } /** * Write header. * @throws IOException * Signals that an I/O exception has occurred. */ private void writeHeader() throws IOException { writeStr("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"); //$NON-NLS-1$ writeStr("<xliff version=\"1.2\" xmlns=\"urn:oasis:names:tc:xliff:document:1.2\" " + //$NON-NLS-1$ "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" " + "xmlns:hs=\"" + Converter.HSNAMESPACE + "\" " + //$NON-NLS-1$ "xsi:schemaLocation=\"urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd " //$NON-NLS-1$ + Converter.HSSCHEMALOCATION + "\">\n"); //$NON-NLS-1$ if (!"".equals(targetLanguage)) { writeStr("<file original=\"" //$NON-NLS-1$ + TextUtil.cleanString(inputFile) + "\" source-language=\"" //$NON-NLS-1$ + sourceLanguage + "\" target-language=\"" + targetLanguage + "\" datatype=\"" + dataType + "\">\n"); //$NON-NLS-1$ } else { writeStr("<file original=\"" //$NON-NLS-1$ + TextUtil.cleanString(inputFile) + "\" source-language=\"" //$NON-NLS-1$ + sourceLanguage + "\" datatype=\"" + dataType + "\">\n"); //$NON-NLS-1$ } writeStr("<header>\n"); //$NON-NLS-1$ writeStr(" <skl>\n"); //$NON-NLS-1$ String crc = ""; //$NON-NLS-1$ if (isSuite) { crc = "crc=\"" + CRC16.crc16(TextUtil.cleanString(skeletonFile).getBytes("UTF-8")) + "\""; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } writeStr(" <external-file href=\"" + TextUtil.cleanString(skeletonFile) + "\" " + crc + "/>\n"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ writeStr(" </skl>\n"); //$NON-NLS-1$ writeStr("<tool tool-id=\"" + qtToolID + "\" tool-name=\"HSStudio\"/>\n"); //$NON-NLS-1$ //$NON-NLS-2$ writeStr(" <hs:prop-group name=\"encoding\">\n <hs:prop prop-type=\"encoding\" >" //$NON-NLS-1$ + srcEncoding + "</hs:prop>\n</hs:prop-group>\n"); //$NON-NLS-1$ if (taggedRTF) { writeStr("<hs:prop-group name=\"tags\">\n" //$NON-NLS-1$ + " <hs:prop prop-type=\"Internal\" >" //$NON-NLS-1$ + winInternal + "</hs:prop>\n" //$NON-NLS-1$ + " <hs:prop prop-type=\"External\" >" //$NON-NLS-1$ + winExternal + "</hs:prop>\n" //$NON-NLS-1$ + " <hs:prop prop-type=\"Mark\" >" //$NON-NLS-1$ + winMark + "</hs:prop>\n" //$NON-NLS-1$ + " <hs:prop prop-type=\"style\" >" //$NON-NLS-1$ + markStyle + "</hs:prop>\n" //$NON-NLS-1$ + "</hs:prop-group>\n"); //$NON-NLS-1$ } writeStr("</header>\n"); //$NON-NLS-1$ writeStr("<body>\n"); //$NON-NLS-1$ } /** * Gets the value. * @param control * the control * @param style * the style * @return the value */ private String getValue(String control, String style) { StringTokenizer tk = new StringTokenizer(style, "\\", true); //$NON-NLS-1$ while (tk.hasMoreTokens()) { String token = tk.nextToken(); if (token.equals("\\")) { //$NON-NLS-1$ token = token + tk.nextToken(); } if (token.equals("\\*")) { //$NON-NLS-1$ token = token + tk.nextToken() + tk.nextToken(); } if (getControl(token).equals(control)) { return getValue(token); } } return "1"; //$NON-NLS-1$ } } }
96,368
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
Xliff2Rtf.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.rtf/src/net/heartsome/cat/converter/rtf/Xliff2Rtf.java
/** * Xliff2Rtf.java * * Version information : * * Date:Jan 14, 2010 * * Copyright notice : */ package net.heartsome.cat.converter.rtf; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.text.MessageFormat; import java.util.HashMap; import java.util.Hashtable; import java.util.Iterator; import java.util.List; import java.util.Map; import net.heartsome.cat.converter.Converter; import net.heartsome.cat.converter.ConverterException; import net.heartsome.cat.converter.rtf.resource.Messages; import net.heartsome.cat.converter.util.CalculateProcessedBytes; import net.heartsome.cat.converter.util.ConverterUtils; import net.heartsome.cat.converter.util.Progress; import net.heartsome.cat.converter.util.ReverseConversionInfoLogRecord; import net.heartsome.xml.Catalogue; import net.heartsome.xml.Document; import net.heartsome.xml.Element; import net.heartsome.xml.SAXBuilder; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.OperationCanceledException; import org.w3c.dom.Node; import org.xml.sax.SAXException; /** * The Class Xliff2Rtf. * @author John Zhu */ public class Xliff2Rtf implements Converter { /** The Constant TYPE_VALUE. */ public static final String TYPE_VALUE = "rtf"; /** The Constant TYPE_NAME_VALUE. */ public static final String TYPE_NAME_VALUE = Messages.getString("rtf.TYPE_NAME_VALUE"); /** The Constant NAME_VALUE. */ public static final String NAME_VALUE = "XLIFF to RTF Conveter"; /** * (non-Javadoc) * @see net.heartsome.cat.converter.Converter#convert(java.util.Map, org.eclipse.core.runtime.IProgressMonitor) * @param args * @param monitor * @return * @throws ConverterException */ public Map<String, String> convert(Map<String, String> args, IProgressMonitor monitor) throws ConverterException { Xliff2RtfImpl converter = new Xliff2RtfImpl(); return converter.run(args, monitor); } /** * (non-Javadoc) * @see net.heartsome.cat.converter.Converter#getName() * @return */ public String getName() { return NAME_VALUE; } /** * (non-Javadoc) * @see net.heartsome.cat.converter.Converter#getType() * @return */ public String getType() { return TYPE_VALUE; } /** * (non-Javadoc) * @see net.heartsome.cat.converter.Converter#getTypeName() * @return */ public String getTypeName() { return TYPE_NAME_VALUE; } /** * The Class Xliff2RtfImpl. * @author John Zhu * @version * @since JDK1.6 */ class Xliff2RtfImpl { private static final String UTF_8 = "UTF-8"; /** The skl file. */ private String sklFile; /** The xliff file. */ private String xliffFile; /** The catalogue. */ private Catalogue catalogue; /** The output. */ private FileOutputStream output; /** The input. */ private InputStreamReader input; /** The buffer. */ private BufferedReader buffer; /** The segments. */ private Hashtable<String, Element> segments; /** The line. */ private String line; /** * Run. * @param params * the params * @param monitor * the monitor * @return the map< string, string> * @throws ConverterException * the converter exception */ public Map<String, String> run(Map<String, String> params, IProgressMonitor monitor) throws ConverterException { monitor = Progress.getMonitor(monitor); ReverseConversionInfoLogRecord infoLogger = ConverterUtils.getReverseConversionInfoLogRecord(); infoLogger.startConversion(); Map<String, String> result = new HashMap<String, String>(); sklFile = params.get(Converter.ATTR_SKELETON_FILE); xliffFile = params.get(Converter.ATTR_XLIFF_FILE); String catalogueFile = params.get(Converter.ATTR_CATALOGUE); String outputFile = params.get(Converter.ATTR_TARGET_FILE); String attrIsPreviewMode = params.get(Converter.ATTR_IS_PREVIEW_MODE); /* 是否为预览翻译模式 */ boolean isPreviewMode = attrIsPreviewMode != null && attrIsPreviewMode.equals(Converter.TRUE); try { // 把转换过程分为三大部分共 10 个任务,其中加载 catalogue 占 2,加载 xliff 文件占 3,替换过程占 5。 monitor.beginTask("", 10); infoLogger.logConversionFileInfo(catalogueFile, null, xliffFile, sklFile); try { monitor.subTask(Messages.getString("rtf.Xliff2Rtf.task2")); infoLogger.startLoadingCatalogueFile(); if (catalogueFile != null) { catalogue = new Catalogue(catalogueFile); } infoLogger.endLoadingCatalogueFile(); monitor.worked(2); // 是否取消操作 if (monitor.isCanceled()) { throw new OperationCanceledException(Messages.getString("rtf.cancel")); } monitor.subTask(Messages.getString("rtf.Xliff2Rtf.task3")); infoLogger.startLoadingXliffFile(); output = new FileOutputStream(outputFile); loadSegments(); infoLogger.endLoadingXliffFile(); monitor.worked(3); } catch (OperationCanceledException e) { throw e; } catch (Exception e1) { if (Converter.DEBUG_MODE) { e1.printStackTrace(); } ConverterUtils.throwConverterException(Activator.PLUGIN_ID, Messages.getString("rtf.Xliff2Rtf.msg1"), e1); } IProgressMonitor replaceMonitor = Progress.getSubMonitor(monitor, 5); try { infoLogger.startReplacingSegmentSymbol(); CalculateProcessedBytes cpb = ConverterUtils.getCalculateProcessedBytes(sklFile); replaceMonitor.beginTask(Messages.getString("rtf.Xliff2Rtf.task4"), cpb.getTotalTask()); replaceMonitor.subTask(""); input = new InputStreamReader(new FileInputStream(sklFile), UTF_8); //$NON-NLS-1$ buffer = new BufferedReader(input); line = buffer.readLine(); while (line != null) { // 是否取消操作 if (replaceMonitor.isCanceled()) { throw new OperationCanceledException(Messages.getString("rtf.cancel")); } cpb.calculateProcessed(replaceMonitor, line, UTF_8); line = line + "\n"; //$NON-NLS-1$ if (line.indexOf("%%%") != -1) { //$NON-NLS-1$ // // contains translatable text // int index = line.indexOf("%%%"); //$NON-NLS-1$ while (index != -1) { String start = line.substring(0, index); writeString(start); line = line.substring(index + 3); String code = line.substring(0, line.indexOf("%%%")); //$NON-NLS-1$ line = line.substring(line.indexOf("%%%\n") + 4); //$NON-NLS-1$ Element segment = segments.get(code); if (segment != null) { Element target = segment.getChild("target"); //$NON-NLS-1$ Element source = segment.getChild("source"); //$NON-NLS-1$ if (target != null) { String tgtStr = cleanChars(extractText(target)); if (isPreviewMode || !"".equals(tgtStr.trim())) { //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ // writeString(tgtStr); if (isPreviewMode) { if ("".equals(tgtStr.trim())) { writeString(cleanChars(extractText(source))); } else { writeString(tgtStr); } } else { writeString(tgtStr); } } else { writeString(cleanChars(extractText(source))); } } else { writeString(cleanChars(extractText(source))); } } else { MessageFormat mf = new MessageFormat(Messages.getString("rtf.Xliff2Rtf.msg0")); //$NON-NLS-1$ Object[] args = { "" + code }; //$NON-NLS-1$ String errMsg = mf.format(args); args = null; throw new Exception(errMsg); } index = line.indexOf("%%%"); //$NON-NLS-1$ if (index == -1) { writeString(line); } } // end while } else { // // non translatable portion // writeString(line); } line = buffer.readLine(); } infoLogger.endReplacingSegmentSymbol(); output.close(); } catch (OperationCanceledException e) { throw e; } catch (Exception e) { if (Converter.DEBUG_MODE) { e.printStackTrace(); } ConverterUtils.throwConverterException(Activator.PLUGIN_ID, Messages.getString("rtf.Xliff2Rtf.msg1"), e); } finally { replaceMonitor.done(); } } finally { monitor.done(); } result.put(Converter.ATTR_TARGET_FILE, outputFile); infoLogger.endConversion(); return result; } /** * Load segments. * @throws SAXException * the SAX exception * @throws IOException * Signals that an I/O exception has occurred. */ private void loadSegments() throws SAXException, IOException { SAXBuilder builder = new SAXBuilder(); if (catalogue != null) { builder.setEntityResolver(catalogue); } Document doc = builder.build(xliffFile); Element root = doc.getRootElement(); Element body = root.getChild("file").getChild("body"); //$NON-NLS-1$ //$NON-NLS-2$ List<Element> units = body.getChildren("trans-unit"); //$NON-NLS-1$ Iterator<Element> i = units.iterator(); segments = new Hashtable<String, Element>(); while (i.hasNext()) { Element unit = i.next(); segments.put(unit.getAttributeValue("id"), unit); //$NON-NLS-1$ } } /** * Write string. * @param string * the string * @throws IOException * Signals that an I/O exception has occurred. */ private void writeString(String string) throws IOException { string = replaceToken(string, "\\par", "\n\\par"); //$NON-NLS-1$ //$NON-NLS-2$ string = replaceToken(string, "\\line", "\n\\line"); //$NON-NLS-1$ //$NON-NLS-2$ output.write(string.getBytes("UTF-8")); //$NON-NLS-1$ } /** * Extract text. * @param target * the target * @return the string * @throws UnsupportedEncodingException * the unsupported encoding exception */ private String extractText(Element target) throws UnsupportedEncodingException { String result = ""; //$NON-NLS-1$ List<Node> content = target.getContent(); Iterator<Node> it = content.iterator(); while (it.hasNext()) { Node n = it.next(); switch (n.getNodeType()) { case Node.ELEMENT_NODE: Element e = new Element(n); if (e.getName().equals("ph")) { //$NON-NLS-1$ result = result + e.getText(); } else { result = result + extractText(e); } break; case Node.TEXT_NODE: String value = n.getNodeValue(); if (!n.getParentNode().getNodeName().equals("ph")) { //$NON-NLS-1$ value = replaceToken(value, "\\", "\\\'5C"); //$NON-NLS-1$ //$NON-NLS-2$ value = replaceToken(value, "" + '\u2002', "\\enspace "); //$NON-NLS-1$ //$NON-NLS-2$ value = replaceToken(value, "" + '\u2003', "\\emspace "); //$NON-NLS-1$ //$NON-NLS-2$ value = replaceToken(value, "" + '\u2005', "\\qmspace "); //$NON-NLS-1$ //$NON-NLS-2$ value = replaceToken(value, "" + '\u2014', "\\emdash "); //$NON-NLS-1$ //$NON-NLS-2$ value = replaceToken(value, "" + '\u2013', "\\endash "); //$NON-NLS-1$ //$NON-NLS-2$ value = replaceToken(value, "" + '\u2018', "\\lquote "); //$NON-NLS-1$ //$NON-NLS-2$ value = replaceToken(value, "" + '\u2019', "\\rquote "); //$NON-NLS-1$ //$NON-NLS-2$ value = replaceToken(value, "" + '\u201C', "\\ldblquote "); //$NON-NLS-1$ //$NON-NLS-2$ value = replaceToken(value, "" + '\u201D', "\\rdblquote "); //$NON-NLS-1$ //$NON-NLS-2$ value = replaceToken(value, "{", "\\{"); //$NON-NLS-1$ //$NON-NLS-2$ value = replaceToken(value, "}", "\\}"); //$NON-NLS-1$ //$NON-NLS-2$ value = replaceToken(value, "" + '\u0009', "\\tab "); //$NON-NLS-1$ //$NON-NLS-2$ value = replaceToken(value, "" + '\u00A0', "\\~"); //$NON-NLS-1$ //$NON-NLS-2$ value = replaceToken(value, "" + '\u2011', "\\_"); //$NON-NLS-1$ //$NON-NLS-2$ value = replaceToken(value, "" + '\u00AD', "\\-"); //$NON-NLS-1$ //$NON-NLS-2$ value = clean(value); } else { value = replaceToken(value, "" + '\u00BB', "\\\'"); //$NON-NLS-1$ //$NON-NLS-2$ } if (result.matches(".*\\\\[a-z]+([0-9]+)?") && value.matches("^[a-zA-Z0-9\\s].*")) { //$NON-NLS-1$ //$NON-NLS-2$ value = " " + value; //$NON-NLS-1$ } result = result + value; break; default: break; } } return result; } /** * Replace token. * @param string * the string * @param token * the token * @param newText * the new text * @return the string */ String replaceToken(String string, String token, String newText) { int index = string.indexOf(token); while (index != -1) { String before = string.substring(0, index); String after = string.substring(index + token.length()); if (token.endsWith(" ") && after.length() > 0 && Character.isSpaceChar(after.charAt(0))) { //$NON-NLS-1$ after = after.substring(1); } string = before + newText + after; index = string.indexOf(token, index + newText.length()); } return string; } } /** * Clean. * @param string * the string * @return the string */ protected static String clean(String string) { String clean = ""; //$NON-NLS-1$ int length = string.length(); for (int i = 0; i < length; i++) { char c = string.charAt(i); if (c <= '\u007F') { clean = clean + c; } else if (c == '\uE007') { clean = clean + "}"; //$NON-NLS-1$ } else if (c == '\uE008') { clean = clean + "{"; //$NON-NLS-1$ } else if (c == '\uE011') { clean = clean + "\\\\"; //$NON-NLS-1$ } else { // Forget about conversion rules that use \' because there // can // be encoding issues, specially when handling Mac text. // Do the OpenOffice trick for all extended characters // instead. clean = clean + "\\uc0\\u" + (int) c + " "; //$NON-NLS-1$ //$NON-NLS-2$ } } return clean; } /** * Clean chars. * @param string * the string * @return the string */ protected static String cleanChars(String string) { String clean = ""; //$NON-NLS-1$ int length = string.length(); for (int i = 0; i < length; i++) { char c = string.charAt(i); if (c <= '\u007F' || c == '\uE007' || c == '\uE008' || c == '\uE011') { clean = clean + c; } else { // Forget about conversion rules that use \' because there // can // be encoding issues, specially when handling Mac text. // Do the OpenOffice trick for all extended characters // instead. clean = clean + "\\uc0\\u" + (int) c + " "; //$NON-NLS-1$ //$NON-NLS-2$ } } return clean; } }
15,236
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
Messages.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.rtf/src/net/heartsome/cat/converter/rtf/resource/Messages.java
/** * Messages.java * * Version information : * * Date:Jan 14, 2010 * * Copyright notice : */ package net.heartsome.cat.converter.rtf.resource; import java.util.MissingResourceException; import java.util.ResourceBundle; /** * The Class Messages. * @author John Zhu * @version * @since JDK1.6 */ public final class Messages { /** The Constant BUNDLE_NAME. */ private static final String BUNDLE_NAME = "net.heartsome.cat.converter.rtf.resource.rtf"; //$NON-NLS-1$ /** The Constant RESOURCE_BUNDLE. */ private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle.getBundle(BUNDLE_NAME); /** * Instantiates a new messages. */ private Messages() { // Do nothing } /** * Gets the string. * @param key * the key * @return the string */ public static String getString(String key) { try { return RESOURCE_BUNDLE.getString(key); } catch (MissingResourceException e) { return '!' + key + '!'; } } }
1,013
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
PPTX2XLIFF.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.pptx/src/net/heartsome/cat/converter/pptx/PPTX2XLIFF.java
package net.heartsome.cat.converter.pptx; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.zip.ZipOutputStream; import net.heartsome.cat.common.file.FileManager; import net.heartsome.cat.common.util.TextUtil; import net.heartsome.cat.converter.Converter; import net.heartsome.cat.converter.ConverterException; import net.heartsome.cat.converter.StringSegmenter; import net.heartsome.cat.converter.pptx.preference.Constants; import net.heartsome.cat.converter.pptx.resource.Messages; import net.heartsome.cat.converter.util.ConverterUtils; import net.heartsome.cat.converter.util.Progress; import net.heartsome.util.CRC16; import net.heartsome.xml.vtdimpl.VTDUtils; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.OperationCanceledException; import org.eclipse.jface.preference.IPreferenceStore; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.ximpleware.AutoPilot; import com.ximpleware.NavException; import com.ximpleware.VTDGen; import com.ximpleware.VTDNav; import com.ximpleware.XMLModifier; import com.ximpleware.XPathEvalException; import com.ximpleware.XPathParseException; /** * PPTX 转换为 XLIFF * @author peason * @version * @since JDK1.6 */ public class PPTX2XLIFF implements Converter { private static final Logger LOGGER = LoggerFactory.getLogger(PPTX2XLIFF.class); /** The Constant TYPE_VALUE. */ public static final String TYPE_VALUE = "pptx"; /** The Constant TYPE_NAME_VALUE. */ public static final String TYPE_NAME_VALUE = Messages.getString("pptx.TYPE_NAME_VALUE"); /** The Constant NAME_VALUE. */ public static final String NAME_VALUE = "MS Office PowerPoint 2007 to XLIFF Conveter"; public Map<String, String> convert(Map<String, String> args, IProgressMonitor monitor) throws ConverterException { PPTX2XLIFFImpl impl = new PPTX2XLIFFImpl(); return impl.run(args, monitor); } public String getName() { return NAME_VALUE; } public String getType() { return TYPE_VALUE; } public String getTypeName() { return TYPE_NAME_VALUE; } /** * PPTX 转换为 XLIFF 的实现类 * @author peason * @version * @since JDK1.6 */ class PPTX2XLIFFImpl { /** SlideMaster 文件中 a 的前缀 */ private static final String PREFIX_A = "a"; /** SlideMaster 文件中 a 的命名空间 */ private static final String NAMESPACE_A = "http://schemas.openxmlformats.org/drawingml/2006/main"; /** SlideMaster 文件中 p 的前缀 */ private static final String PREFIX_P = "p"; /** SlideMaster 文件中 a 的命名空间 */ private static final String NAMESPACE_P = "http://schemas.openxmlformats.org/presentationml/2006/main"; /** 源文件路径 */ private String strSrcPath; /** 骨架文件路径 */ private String strSklPath; /** XLIFF 文件路径 */ private String strXLIFFPath; private boolean blnIsSuite; private String strQtToolID; /** 源语言 */ private String strSrcLang; /** 目标语言 */ private String strTgtLang; /** Catalogue 路径 */ private String strCatalogue; /** 分段规则文件路径 */ private String strSrx; /** 编码 */ private String strSrcEncoding; private boolean blnSegByElement; private StringSegmenter segmenter; /** 生成 XLIFF 文件的输出流 */ private FileOutputStream out; /** 生成骨架文件的输出流 */ private ZipOutputStream zipSklOut; private FileManager fileManager = new FileManager(); /** 临时解压目录(将源文件先解压到此目录) */ private String strTmpFolderPath; /** 文本段 ID 值 */ private int segNum = 0; /** key 为 slideMasterN.xml 文件名,value 中第一个值为 ph 节点的 type 属性值,第二个为横坐标,第三个为纵坐标 */ private HashMap<String, ArrayList<String[]>> mapSldMasterPH = new HashMap<String, ArrayList<String[]>>(); /** key 为 slideLayoutN.xml 文件名,value 中第一个值为 ph 节点的 type 属性值,第二个为横坐标,第三个为纵坐标 */ private HashMap<String, ArrayList<String[]>> mapSldLayoutPH = new HashMap<String, ArrayList<String[]>>(); /** key 为 slideMasterN.xml 文件名,value 为 slideLayoutN.xml 文件名 */ private HashMap<String, ArrayList<String>> mapLayout = new HashMap<String, ArrayList<String>>(); /** slide 文件名集合,已按实际显示的顺序排序 */ private ArrayList<String> lstSlide = new ArrayList<String>(); /** 是否萃取备注内容,此属性在首选项中设置(备注中的页眉页脚不受此变量控制) */ private boolean blnIsFilterNote; /** * 转换器的处理流程如下: <br/> * 1. 解压源文件到临时目录 <br/> * 2. 创建骨架文件压缩包,并将除 ppt/notesSlides 和 ppt/slides 文件夹外的其他文件放入压缩包 <br/> * 3. 解析 ppt/slideMasters 下的 slideMasterN.xml 文件(如果存在的话),查找 ph 不是 dt 和 sldNum 的节点,取出其 type, idx 属性值和坐标值<br/> * (key 为 slideMasterN.xml 文件名,value 为 type, idx 属性值和坐标值的集合) <br/> * 4. 解析 ppt/slideMasters/_rels 下的 rels 文件,取出其包含的 slideLayoutN.xml 文件名(key 为 slideMasterN.xml 文件名,<br/> * value 为 slideLayoutN.xml 文件名) <br/> * 5. 解析 ppt/presentation.xml 文件和 ppt/_rels/presentation.xml.rels 文件,确定 slideN.xml 文件的顺序。 <br/> * 6. 按顺序解析 slideN.xml.rels 文件,取出 slideLayoutN.xml 和 noteSlideN.xml 文件名,然后解析对应的 slideN.xml 文件,<br/> * 并放入骨架信息,每解析完一个 slideN.xml 文件后就去 _rels 查找相应的 rels 文件并解析,从中确定对应的 noteSlideN.xml 文件 <br/> * 7. 解析第 6 步确定的 noteSlideN.xml 文件,查找 ph 的 type 属性值为 body, hdr, ftr 的节点,从中取出文本信息 <br/> * 8. 重复 6, 7 步 <br/> * 9. 删除临时目录 <br/> * @param args * @param monitor * @return * @throws ConverterException * ; */ public Map<String, String> run(Map<String, String> args, IProgressMonitor monitor) throws ConverterException { Map<String, String> result = new HashMap<String, String>(); monitor = Progress.getMonitor(monitor); monitor.beginTask("", 13); // 转换过程分为 13 部分,releaseSrcZip 占 1,createZip 占 1,parseSlideMaster 占 2,parseSlideMasterRels 占 // 2,getSlideAndSort 占 1, // parseSlideBySort 占 5,deleteFileOrFolder 占 1 IProgressMonitor firstMonitor = Progress.getSubMonitor(monitor, 1); firstMonitor.beginTask(Messages.getString("pptx.PPTX2XLIFF.task1"), 1); firstMonitor.subTask(""); IPreferenceStore store = Activator.getDefault().getPreferenceStore(); blnIsFilterNote = store.getBoolean(Constants.PPTX_FILTER); strSrcPath = args.get(Converter.ATTR_SOURCE_FILE); strXLIFFPath = args.get(Converter.ATTR_XLIFF_FILE); strSklPath = args.get(Converter.ATTR_SKELETON_FILE); blnIsSuite = Converter.TRUE.equals(args.get(Converter.ATTR_IS_SUITE)); strQtToolID = args.get(Converter.ATTR_QT_TOOLID) != null ? args.get(Converter.ATTR_QT_TOOLID) : Converter.QT_TOOLID_DEFAULT_VALUE; strSrcLang = args.get(Converter.ATTR_SOURCE_LANGUAGE); strTgtLang = args.get(Converter.ATTR_TARGET_LANGUAGE); strCatalogue = args.get(Converter.ATTR_CATALOGUE); String elementSegmentation = args.get(Converter.ATTR_SEG_BY_ELEMENT); strSrx = args.get(Converter.ATTR_SRX); strSrcEncoding = args.get(Converter.ATTR_SOURCE_ENCODING); if (elementSegmentation == null) { blnSegByElement = false; } else { blnSegByElement = elementSegmentation.equals(Converter.TRUE); } try { out = new FileOutputStream(strXLIFFPath); zipSklOut = new ZipOutputStream(new FileOutputStream(strSklPath)); writeHeader(); if (!blnSegByElement) { segmenter = new StringSegmenter(strSrx, strSrcLang, strCatalogue); } if (firstMonitor.isCanceled()) { throw new OperationCanceledException(Messages.getString("preference.cancel")); } // 第 1 步 releaseSrcZip(strSrcPath); firstMonitor.worked(1); firstMonitor.done(); if (monitor.isCanceled()) { throw new OperationCanceledException(Messages.getString("preference.cancel")); } IProgressMonitor secondMonitor = Progress.getSubMonitor(monitor, 1); secondMonitor.beginTask(Messages.getString("pptx.PPTX2XLIFF.task2"), 1); secondMonitor.subTask(""); List<String> lstExcludeFolder = new ArrayList<String>(); lstExcludeFolder.add(strTmpFolderPath + File.separator + "ppt" + File.separator + "notesSlides"); lstExcludeFolder.add(strTmpFolderPath + File.separator + "ppt" + File.separator + "slides"); // 第 2 步 fileManager.createZip(strTmpFolderPath, zipSklOut, lstExcludeFolder); File notesSlideRelsDic = new File(strTmpFolderPath + File.separator + "ppt" + File.separator + "notesSlides" + File.separator + "_rels"); if (notesSlideRelsDic.isDirectory()) { for (File notesSlideRelsFile : notesSlideRelsDic.listFiles()) { if (notesSlideRelsFile.isFile()) { fileManager.addFileToZip(zipSklOut, strTmpFolderPath, notesSlideRelsFile.getAbsolutePath()); } } } File slideRelsDic = new File(strTmpFolderPath + File.separator + "ppt" + File.separator + "slides" + File.separator + "_rels"); if (slideRelsDic.isDirectory()) { for (File slideRelsFile : slideRelsDic.listFiles()) { if (slideRelsFile.isFile()) { fileManager.addFileToZip(zipSklOut, strTmpFolderPath, slideRelsFile.getAbsolutePath()); } } } secondMonitor.worked(1); secondMonitor.done(); if (monitor.isCanceled()) { throw new OperationCanceledException(Messages.getString("preference.cancel")); } // 第 3 步 parseSlideMaster(Progress.getSubMonitor(monitor, 2)); parseSlideLayout(); if (monitor.isCanceled()) { throw new OperationCanceledException(Messages.getString("preference.cancel")); } // 第 4 步 parseSlideMasterRels(Progress.getSubMonitor(monitor, 2)); if (monitor.isCanceled()) { throw new OperationCanceledException(Messages.getString("preference.cancel")); } // 第 5 步 getSlideAndSort(Progress.getSubMonitor(monitor, 1)); if (monitor.isCanceled()) { throw new OperationCanceledException(Messages.getString("preference.cancel")); } // 第 6, 7 步 parseSlideBySort(Progress.getSubMonitor(monitor, 5)); if (monitor.isCanceled()) { throw new OperationCanceledException(Messages.getString("preference.cancel")); } writeOut("</body>\n</file>\n</xliff>"); out.close(); zipSklOut.flush(); zipSklOut.close(); IProgressMonitor thirdMonitor = Progress.getSubMonitor(monitor, 1); thirdMonitor.beginTask(Messages.getString("pptx.PPTX2XLIFF.task3"), 1); thirdMonitor.subTask(""); // 第 9 步 thirdMonitor.worked(1); thirdMonitor.done(); result.put(Converter.ATTR_XLIFF_FILE, strXLIFFPath); } catch (OperationCanceledException e) { throw e; } catch (Exception e) { e.printStackTrace(); LOGGER.error(Messages.getString("pptx.PPTX2XLIFF.logger1"), e); ConverterUtils.throwConverterException(Activator.PLUGIN_ID, Messages.getString("pptx.PPTX2XLIFF.msg1"), e); } finally { fileManager.deleteFileOrFolder(new File(strTmpFolderPath)); monitor.done(); } return result; } /** * 解析 ppt/slideMasters/_rels 目录下的 rels 文件,确定 slideMasterN.xml 与 slideLayoutN.xml 的对应关系 * @throws XPathParseException * @throws XPathEvalException * @throws NavException * ; */ private void parseSlideMasterRels(IProgressMonitor monitor) throws XPathParseException, XPathEvalException, NavException { File relsFile = new File(strTmpFolderPath + File.separator + "ppt" + File.separator + "slideMasters" + File.separator + "_rels"); if (relsFile.isDirectory()) { File[] arrRelFile = relsFile.listFiles(); monitor.beginTask("", arrRelFile.length); VTDGen vg = new VTDGen(); AutoPilot ap = new AutoPilot(); VTDUtils vu = new VTDUtils(); for (File relFile : arrRelFile) { String name = relFile.getName(); monitor.subTask(MessageFormat.format(Messages.getString("pptx.PPTX2XLIFF.task4"), name)); if (relFile.isFile() && name.toLowerCase().endsWith(".rels")) { if (vg.parseFile(relFile.getAbsolutePath(), true)) { ArrayList<String> lstLayout = new ArrayList<String>(); VTDNav vn = vg.getNav(); ap.bind(vn); vu.bind(vn); ap.selectXPath("/Relationships/Relationship"); while (ap.evalXPath() != -1) { String strTarget = vu.getCurrentElementAttribut("Target", ""); if (strTarget.indexOf("slideLayout") != -1) { strTarget = strTarget.substring(strTarget.lastIndexOf("/") + 1); lstLayout.add(strTarget); } } mapLayout.put(name.substring(0, name.lastIndexOf(".")), lstLayout); } } monitor.worked(1); } } monitor.done(); } /** * 解析 ppt/slideMasters 目录下的 slideMasterN.xml 文件,查找 ph 中 type 不是 dt 和 sldNum 的节点,<br/> * 取出其 type, idx 属性值和坐标值,因为有的幻灯片中节点的坐标是存放在此文件中的 * @throws Exception */ private void parseSlideMaster(IProgressMonitor monitor) throws Exception { File slideMasterDic = new File(strTmpFolderPath + File.separator + "ppt" + File.separator + "slideMasters"); if (slideMasterDic.isDirectory()) { VTDGen vg = new VTDGen(); VTDUtils vu = new VTDUtils(); AutoPilot ap = new AutoPilot(); ap.declareXPathNameSpace(PREFIX_A, NAMESPACE_A); ap.declareXPathNameSpace(PREFIX_P, NAMESPACE_P); File[] arrSlideMasterFile = slideMasterDic.listFiles(); monitor.beginTask("", arrSlideMasterFile.length); for (File slideMasterFile : arrSlideMasterFile) { if (monitor.isCanceled()) { throw new OperationCanceledException(Messages.getString("preference.cancel")); } monitor.subTask(MessageFormat.format(Messages.getString("pptx.PPTX2XLIFF.task4"), slideMasterFile.getName())); if (slideMasterFile.isFile() && slideMasterFile.getName().toLowerCase().endsWith(".xml")) { if (vg.parseFile(slideMasterFile.getAbsolutePath(), true)) { String name = slideMasterFile.getName(); VTDNav vn = vg.getNav(); vu.bind(vn); ap.bind(vn); ap.selectXPath("/p:sldMaster/p:cSld/p:spTree//p:sp[descendant::p:ph[not(@type='dt') and not(@type='sldNum')]]"); ArrayList<String[]> lstFld = new ArrayList<String[]>(); while (ap.evalXPath() != -1) { String strType = getElementAttribute(".//p:ph", "type", vn); String idx = getElementAttribute(".//p:ph", "idx", vn); if (strType == null && idx == null) { continue; } String strX = getElementAttribute(".//a:xfrm/a:off", "x", vn); String strY = getElementAttribute(".//a:xfrm/a:off", "y", vn); if (strX != null && strY != null) { lstFld.add(new String[] { strType, idx, strX, strY }); } } if (lstFld.size() > 0) { mapSldMasterPH.put(name, lstFld); } } } monitor.worked(1); } } monitor.done(); } /** * 获取当前元素节点的某个属性值。如果当前节点没有该属性,返回默认值。 * @exception NavException */ public String getCurrentElementAttribut(String AttributName, String defaultValue, VTDNav vn) throws NavException { int index = vn.getAttrVal(AttributName); return index != -1 ? vn.toString(index) : defaultValue; } public String getElementAttribute(String elementXPath, String attributeName, VTDNav vn) throws XPathParseException, XPathEvalException, NavException { String text = null; AutoPilot ap = new AutoPilot(vn); ap.declareXPathNameSpace(PREFIX_A, NAMESPACE_A); ap.declareXPathNameSpace(PREFIX_P, NAMESPACE_P); ap.selectXPath(elementXPath); vn.push(); if (ap.evalXPath() != -1) { int inx = vn.getAttrVal(attributeName); if (inx != -1) { text = vn.toString(inx); } } vn.pop(); return text; } /** * 获取 ppt/slides 目录下的 slideN.xml 文件并排序 ; * @throws NavException * @throws XPathParseException * @throws XPathEvalException */ private void getSlideAndSort(IProgressMonitor monitor) throws NavException, XPathParseException, XPathEvalException { monitor.beginTask(Messages.getString("pptx.PPTX2XLIFF.task5"), 2); monitor.subTask(""); VTDGen vg = new VTDGen(); AutoPilot ap = new AutoPilot(); ap.declareXPathNameSpace(PREFIX_P, NAMESPACE_P); VTDUtils vu = new VTDUtils(); ArrayList<String> lstRId = new ArrayList<String>(); if (vg.parseFile(strTmpFolderPath + File.separator + "ppt" + File.separator + "presentation.xml", true)) { VTDNav vn = vg.getNav(); ap.bind(vn); vu.bind(vn); ap.selectXPath("/p:presentation/p:sldIdLst/p:sldId"); while (ap.evalXPath() != -1) { String strRid = vu.getCurrentElementAttribut("r:id", null); if (strRid != null) { lstRId.add(strRid); } } } monitor.worked(1); if (lstRId.size() > 0) { if (vg.parseFile(strTmpFolderPath + File.separator + "ppt" + File.separator + "_rels" + File.separator + "presentation.xml.rels", true)) { VTDNav vn = vg.getNav(); ap.bind(vn); vu.bind(vn); StringBuffer sbCondition = new StringBuffer(); for (int i = 0; i < lstRId.size(); i++) { if (i == 0) { sbCondition.append("Relationship[@Id='" + lstRId.get(i) + "']"); } else { sbCondition.append("|Relationship[@Id='" + lstRId.get(i) + "']"); } } ap.selectXPath("/Relationships/" + sbCondition.toString() + ""); while (ap.evalXPath() != -1) { String strSlidePath = vu.getCurrentElementAttribut("Target", null); if (strSlidePath != null) { lstSlide.add(strSlidePath.substring(strSlidePath.lastIndexOf("/") + 1)); } } } } monitor.worked(1); monitor.done(); } /** * 解析 slideLayoutN.xml 文件,获取坐标值,因为有的幻灯片中节点的坐标是存放在此文件中的 * @throws NavException * @throws XPathParseException * @throws XPathEvalException */ private void parseSlideLayout() throws NavException, XPathParseException, XPathEvalException { File slideLayoutDic = new File(strTmpFolderPath + File.separator + "ppt" + File.separator + "slideLayouts"); if (slideLayoutDic.isDirectory()) { VTDGen vg = new VTDGen(); AutoPilot ap = new AutoPilot(); ap.declareXPathNameSpace(PREFIX_A, NAMESPACE_A); ap.declareXPathNameSpace(PREFIX_P, NAMESPACE_P); VTDUtils vu = new VTDUtils(); File[] arrSlideLayoutFile = slideLayoutDic.listFiles(); for (File slideLayoutFile : arrSlideLayoutFile) { if (slideLayoutFile.isFile() && slideLayoutFile.getName().toLowerCase().endsWith(".xml")) { if (vg.parseFile(slideLayoutFile.getAbsolutePath(), true)) { String name = slideLayoutFile.getName(); VTDNav vn = vg.getNav(); ap.bind(vn); vu.bind(vn); ap.selectXPath("/p:sldLayout/p:cSld/p:spTree//p:sp[descendant::p:ph[not(@type='dt') and not(@type='sldNum')]]"); ArrayList<String[]> lstPH = new ArrayList<String[]>(); while (ap.evalXPath() != -1) { String strType = getElementAttribute(".//p:ph", "type", vn); String idx = getElementAttribute(".//p:ph", "idx", vn); if (strType == null && idx == null) { continue; } String strX = getElementAttribute(".//a:xfrm/a:off", "x", vn); String strY = getElementAttribute(".//a:xfrm/a:off", "y", vn); if (strX != null && strY != null) { lstPH.add(new String[] { strType, idx, strX, strY }); } } if (lstPH.size() > 0) { mapSldLayoutPH.put(name, lstPH); } } } } } } private void parseSlideBySort(IProgressMonitor monitor) throws Exception { monitor.beginTask(Messages.getString("pptx.PPTX2XLIFF.task6"), lstSlide.size()); monitor.subTask(""); VTDGen vg = new VTDGen(); AutoPilot apRels = new AutoPilot(); AutoPilot apSlide = new AutoPilot(); apSlide.declareXPathNameSpace(PREFIX_A, NAMESPACE_A); apSlide.declareXPathNameSpace(PREFIX_P, NAMESPACE_P); AutoPilot apParent = new AutoPilot(); apParent.declareXPathNameSpace(PREFIX_A, NAMESPACE_A); apParent.declareXPathNameSpace(PREFIX_P, NAMESPACE_P); VTDUtils vu = new VTDUtils(); StringBuffer sbContent = new StringBuffer(); XMLModifier xm = new XMLModifier(); boolean isUpdate = false; List<Integer> removedIndexList = new ArrayList<Integer>(); for (final String slideName : lstSlide) { removedIndexList.clear(); isUpdate = false; String strSlideLayout = null; String strNotesSlide = null; // 先解析对应的 rels 文件 if (vg.parseFile(strTmpFolderPath + File.separator + "ppt" + File.separator + "slides" + File.separator + "_rels" + File.separator + slideName + ".rels", true)) { VTDNav vn = vg.getNav(); apRels.bind(vn); vu.bind(vn); apRels.selectXPath("/Relationships/Relationship"); while (apRels.evalXPath() != -1) { String strTarget = getCurrentElementAttribut("Target", null, vn); if (strTarget != null) { if (strSlideLayout == null && strTarget.indexOf("slideLayout") != -1) { strSlideLayout = strTarget.substring(strTarget.lastIndexOf("/") + 1); } if (strNotesSlide == null && strTarget.indexOf("notesSlide") != -1) { strNotesSlide = strTarget.substring(strTarget.lastIndexOf("/") + 1); } } if (strSlideLayout != null && strNotesSlide != null) { break; } } } final String slideLayoutName = strSlideLayout; String strSlideMaster = null; if (strSlideLayout != null && mapLayout.size() > 0) { Iterator<Entry<String, ArrayList<String>>> it = mapLayout.entrySet().iterator(); while (it.hasNext()) { Entry<String, ArrayList<String>> entry = (Entry<String, ArrayList<String>>) it.next(); ArrayList<String> lstLayout = entry.getValue(); if (lstLayout.contains(strSlideLayout)) { strSlideMaster = entry.getKey(); } } } final String slideMasterName = strSlideMaster; // 解析 slideN.xml 文件 vg.clear(); String strSlideFilePath = strTmpFolderPath + File.separator + "ppt" + File.separator + "slides" + File.separator + slideName; vg = new VTDGen(); if (vg.parseFile(strSlideFilePath, true)) { ArrayList<String[]> lstCoordinate = new ArrayList<String[]>(); VTDNav vn = vg.getNav(); apSlide.bind(vn); vu.bind(vn); xm.bind(vn); apParent.bind(vn); apSlide.selectXPath("/p:sld/p:cSld/p:spTree//p:sp[descendant::node()[name()='a:t']] " + "| /p:sld/p:cSld/p:spTree//p:graphicFrame[descendant::node()[name()='a:t']]"); // 标记是否有坐标值 boolean isContainOff = true; while (apSlide.evalXPath() != -1) { String strX = getElementAttribute(".//p:xfrm/a:off | .//a:xfrm/a:off", "x", vn); String strY = getElementAttribute(".//p:xfrm/a:off | .//a:xfrm/a:off", "y", vn); String strType = getElementAttribute(".//p:ph", "type", vn); String strIdx = getElementAttribute(".//p:ph", "idx", vn); String name = vu.getCurrentElementName(); vn.push(); String parentX = null; String parentY = null; if (name.equals("p:sp")) { // 如果 p:sp 的父节点为 p:grpSp,则要将 p:grpSp/p:grpSpPr/a:xfrm/a:off 的 x,y 值取出,因为 p:grpSpPr // 的坐标是相对整个幻灯片的坐标,而 p:sp 的坐标则是相对 p:grpSpPr 的。 apParent.selectXPath("parent::node()[name()='p:grpSp']"); if (apParent.evalXPath() != -1) { parentX = getElementAttribute("./p:grpSpPr/a:xfrm/a:off", "x", vn); parentY = getElementAttribute("./p:grpSpPr/a:xfrm/a:off", "y", vn); } } vn.pop(); if (strX == null && strY == null) { // ph 节点无坐标 if (strType != null) { if (!strType.equals("dt") && !strType.equals("sldNum")) { isContainOff = false; } } else { isContainOff = false; } } if ((strType == null || (!strType.equals("dt") && !strType.equals("sldNum")))) { lstCoordinate.add(new String[] { strType, strIdx, strX, strY, parentX, parentY }); } } removeDuplicateWithOrder(lstCoordinate); if (isContainOff) { Collections.sort(lstCoordinate, new Comparator<String[]>() { public int compare(String[] o1, String[] o2) { int x1 = Integer.parseInt(o1[2]); int y1 = Integer.parseInt(o1[3]); int parentX1 = 0; int parentY1 = 0; int parentX2 = 0; int parentY2 = 0; if (o1[4] != null) { parentX1 = Integer.parseInt(o1[4]); } if (o1[5] != null) { parentY1 = Integer.parseInt(o1[5]); } int x2 = Integer.parseInt(o2[2]); int y2 = Integer.parseInt(o2[3]); if (o2[4] != null) { parentX2 = Integer.parseInt(o2[4]); } if (o2[5] != null) { parentY2 = Integer.parseInt(o2[5]); } if (o1[4] != null && o1[5] != null && o2[4] != null && o2[5] != null) { if (parentY1 != parentY2) { return parentY1 - parentY2; } else if (parentX1 != parentX2) { return parentX1 - parentX2; } else { if (y1 != y2) { return y1 - y2; } else { return x1 - x2; } } } else if (o1[4] != null && o1[5] != null) { if (parentY1 != y2) { return parentY1 - y2; } else { return parentX1 - x2; } } else if (o2[4] != null && o2[5] != null) { if (y1 != parentY2) { return y1 - parentY2; } else { return x1 - parentX2; } } else { if (y1 != y2) { return y1 - y2; } else { return x1 - x2; } } } }); } else { Collections.sort(lstCoordinate, new Comparator<String[]>() { public int compare(String[] o1, String[] o2) { int x1 = o1[2] == null ? 0 : Integer.parseInt(o1[2]); int y1 = o1[3] == null ? 0 : Integer.parseInt(o1[3]); int x2 = o2[2] == null ? 0 : Integer.parseInt(o2[2]); int y2 = o2[3] == null ? 0 : Integer.parseInt(o2[3]); ArrayList<String[]> lstLayoutPH = mapSldLayoutPH.get(slideLayoutName); if (lstLayoutPH == null || lstLayoutPH.size() == 0) { lstLayoutPH = mapSldMasterPH.get(slideMasterName); } if (o1[0] != null && o1[0].equals("ftr")) { y1 = Integer.MAX_VALUE; } else { if (lstLayoutPH != null) { for (String[] arrLayoutPH : lstLayoutPH) { if (o1[0] != null && arrLayoutPH[0] != null && arrLayoutPH[0].equals(o1[0])) { x1 = Integer.parseInt(arrLayoutPH[2]); y1 = Integer.parseInt(arrLayoutPH[3]); break; } else if (o1[1] != null && arrLayoutPH[1] != null && arrLayoutPH[1].equals(o1[1])) { x1 = Integer.parseInt(arrLayoutPH[2]); y1 = Integer.parseInt(arrLayoutPH[3]); break; } } } } if (o2[0] != null && o2[0].equals("ftr")) { y2 = Integer.MAX_VALUE; } else { if (lstLayoutPH != null) { for (String[] arrLayoutPH : lstLayoutPH) { if (o2[0] != null && arrLayoutPH[0] != null && arrLayoutPH[0].equals(o2[0])) { x2 = Integer.parseInt(arrLayoutPH[2]); y2 = Integer.parseInt(arrLayoutPH[3]); break; } else if (o2[1] != null && arrLayoutPH[1] != null && arrLayoutPH[1].equals(o2[1])) { x2 = Integer.parseInt(arrLayoutPH[2]); y2 = Integer.parseInt(arrLayoutPH[3]); break; } } } } if (y1 != y2) { return y1 - y2; } else { return x1 - x2; } } }); } for (String[] arrCoordinate : lstCoordinate) { StringBuffer sbCondition = new StringBuffer("[descendant::node()[name()='a:t']"); if (arrCoordinate[0] != null && arrCoordinate[1] != null) { sbCondition.append(" and descendant::node()[name()='p:ph' and @type='" + arrCoordinate[0] + "' and @idx='" + arrCoordinate[1] + "']"); } else if (arrCoordinate[0] != null) { sbCondition.append(" and descendant::node()[name()='p:ph' and @type='" + arrCoordinate[0] + "']"); } else if (arrCoordinate[1] != null) { sbCondition.append(" and descendant::node()[name()='p:ph' and @idx='" + arrCoordinate[1] + "']"); } if (arrCoordinate[2] != null && arrCoordinate[3] != null) { sbCondition.append(" and descendant::node()[name()='a:off' and @x='" + arrCoordinate[2] + "' and @y='" + arrCoordinate[3] + "']"); } if (arrCoordinate[4] != null && arrCoordinate[5] != null) { // p:sp 的父节点为 p:grpSp,判断 p:grpSp/p:grpSpPr/a:xfrm/a:off 的 x,y 值, p:sp 与 p:grpSp 是同胞 sbCondition .append(" and parent::node()[name()='p:grpSp'] and (preceding-sibling::node()[name()='p:grpSpPr' and a:xfrm/a:off[@x='" + arrCoordinate[4] + "' and @y='" + arrCoordinate[5] + "']] or following-sibling::node()[name()='p:grpSpPr' and a:xfrm/a:off[@x='" + arrCoordinate[4] + "' and @y='" + arrCoordinate[5] + "']])"); } sbCondition.append("]"); String xpath = "/p:sld/p:cSld/p:spTree//p:sp" + sbCondition + "/p:txBody/a:p " + "| /p:sld/p:cSld/p:spTree//p:graphicFrame" + sbCondition + "//a:txBody/a:p"; apSlide.selectXPath(xpath); while (apSlide.evalXPath() != -1) { sbContent.delete(0, sbContent.length()); String strFragment = vu.getElementFragment(); if (strFragment.indexOf("<a:t>") == -1) { continue; } String strText = strFragment.substring(strFragment.indexOf("<a:t>") + "<a:t>".length(), strFragment.lastIndexOf("</a:t>")); sbContent.append(strFragment.substring(0, strFragment.indexOf("<a:t>") + "<a:t>".length())) .append(strFragment.substring(strFragment.lastIndexOf("</a:t>"))); if (blnSegByElement) { writeSegment(strText); sbContent.insert(sbContent.lastIndexOf("</a:t>"), "%%%" + segNum++ + "%%%"); } else { String[] segs = segmenter.segment(strText); for (int h = 0; h < segs.length; h++) { String seg = segs[h]; writeSegment(seg); sbContent.insert(sbContent.lastIndexOf("</a:t>"), "%%%" + segNum++ + "%%%"); } } int currentIndex = vn.getCurrentIndex(); if (!removedIndexList.contains(currentIndex)) { xm.remove(vn.getElementFragment()); xm.insertAfterElement(sbContent.toString().getBytes()); isUpdate = true; removedIndexList.add(currentIndex); } } } if (isUpdate) { xm.output(strSlideFilePath + ".skl"); fileManager.addFileToZip(zipSklOut, strTmpFolderPath, strSlideFilePath + ".skl"); isUpdate = false; } else { fileManager.addFileToZip(zipSklOut, strTmpFolderPath, strSlideFilePath); } } if (strNotesSlide != null) { String strNotesSlidePath = strTmpFolderPath + File.separator + "ppt" + File.separator + "notesSlides" + File.separator + strNotesSlide; if (vg.parseFile(strNotesSlidePath, true)) { VTDNav vn = vg.getNav(); apSlide.bind(vn); vu.bind(vn); xm.bind(vn); StringBuffer sbXpath = new StringBuffer(); // notesSlideN.xml 文件中按照 type 为 body, hdr, ftr 的顺序查找,如果过滤备注文本,则是按照 type 为 hdr, ftr 的顺序查找。 if (!blnIsFilterNote) { sbXpath.append("/p:notes/p:cSld/p:spTree/p:sp[p:nvSpPr/p:nvPr/p:ph[@type='body']] | "); } sbXpath.append("/p:notes/p:cSld/p:spTree/p:sp[p:nvSpPr/p:nvPr/p:ph[@type='hdr']] | /p:notes/p:cSld/p:spTree/p:sp[p:nvSpPr/p:nvPr/p:ph[@type='ftr']]"); apSlide.selectXPath(sbXpath.toString()); while (apSlide.evalXPath() != -1) { sbContent.delete(0, sbContent.length()); String strFragment = vu.getElementFragment(); if (strFragment.indexOf("<a:t>") == -1) { continue; } String strText = strFragment.substring(strFragment.indexOf("<a:t>") + "<a:t>".length(), strFragment.lastIndexOf("</a:t>")); sbContent.append(strFragment.substring(0, strFragment.indexOf("<a:t>") + "<a:t>".length())) .append(strFragment.substring(strFragment.lastIndexOf("</a:t>"))); if (blnSegByElement) { writeSegment(strText); sbContent.insert(sbContent.lastIndexOf("</a:t>"), "%%%" + segNum++ + "%%%"); } else { String[] segs = segmenter.segment(strText); for (int h = 0; h < segs.length; h++) { String seg = segs[h]; writeSegment(seg); sbContent.insert(sbContent.lastIndexOf("</a:t>"), "%%%" + segNum++ + "%%%"); } } xm.remove(vn.getElementFragment()); xm.insertAfterElement(sbContent.toString().getBytes()); isUpdate = true; } if (isUpdate) { xm.output(strNotesSlidePath + ".skl"); fileManager.addFileToZip(zipSklOut, strTmpFolderPath, strNotesSlidePath + ".skl"); isUpdate = false; } else { fileManager.addFileToZip(zipSklOut, strTmpFolderPath, strNotesSlidePath); } } } monitor.worked(1); } monitor.done(); } /** * 移除 list 中的重复数据 * @param list * ; */ public void removeDuplicateWithOrder(List<String[]> list) { for (int i = 0; i < list.size() - 1; i++) { for (int j = list.size() - 1; j > i; j--) { String[] arr1 = list.get(j); String[] arr2 = list.get(i); boolean isEqual = true; for (int len = 0; len < (arr1.length > arr2.length ? arr2.length : arr1.length); len++) { if (!cleanNull(arr1[len]).equals(cleanNull(arr2[len]))) { isEqual = false; break; } } if (isEqual) { list.remove(j); } } } } public String cleanNull(String string) { return string == null ? "" : string; } /** * 将 strText 写入 XLIFF 文件 * @param strText * @throws IOException * ; */ private void writeSegment(String strText) throws IOException { writeOut("<trans-unit id=\"" + segNum + "\">\n"); String phText = "<ph>"; String phEndText = "</ph>"; int phId = 1; StringBuffer sbText = new StringBuffer(strText); int index = 0; int endIndex = 0; while (true) { if (index >= 0) { index = sbText.indexOf("</a:t>", index == 0 ? index : index + 1); if (index != -1) { sbText.insert(index, phText); index += phText.length(); endIndex = sbText.indexOf("<a:t>", index == 0 ? index : index + 1); sbText.insert(endIndex + "<a:t>".length(), phEndText); String subText = TextUtil.cleanSpecialString(sbText.substring(index, endIndex + "<a:t>".length())); sbText.replace(index, endIndex + "<a:t>".length(), subText); index = endIndex; } } else { break; } } strText = sbText.toString(); strText = strText.replaceAll(phEndText + phText, ""); while (strText.indexOf(phText) != -1) { strText = strText.replaceFirst(phText, "<ph id=\"" + phId++ + "\">"); } writeOut("<source xml:lang=\"" + strSrcLang + "\">" + strText + "</source>\n"); writeOut("</trans-unit>\n\n"); } /** * 写 XLIFF 的头节点内容 * @throws IOException * ; */ private void writeHeader() throws IOException { writeOut("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n"); //$NON-NLS-1$ writeOut("<xliff version=\"1.2\" xmlns=\"urn:oasis:names:tc:xliff:document:1.2\" " + //$NON-NLS-1$ "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" " + "xmlns:hs=\"" + Converter.HSNAMESPACE + "\" " + //$NON-NLS-1$ "xsi:schemaLocation=\"urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd " //$NON-NLS-1$ + Converter.HSSCHEMALOCATION + "\">\n"); //$NON-NLS-1$ if (!strTgtLang.equals("")) { writeOut("<file datatype=\"" + TYPE_VALUE + "\" original=\"" + TextUtil.cleanSpecialString(strSrcPath) + "\" source-language=\"" + strSrcLang + "\" target-language=\"" + strTgtLang + "\">\n"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } else { writeOut("<file datatype=\"" + TYPE_VALUE + "\" original=\"" + TextUtil.cleanSpecialString(strSrcPath) + "\" source-language=\"" + strSrcLang + "\">\n"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } writeOut("<header>\n"); //$NON-NLS-1$ writeOut("<skl>\n"); //$NON-NLS-1$ if (blnIsSuite) { writeOut("<external-file crc=\"" + CRC16.crc16(TextUtil.cleanString(strSklPath).getBytes("UTF-8")) + "\" href=\"" + TextUtil.cleanSpecialString(strSklPath) + "\"/>\n"); //$NON-NLS-1$ //$NON-NLS-2$ } else { writeOut("<external-file href=\"" + TextUtil.cleanSpecialString(strSklPath) + "\"/>\n"); //$NON-NLS-1$ //$NON-NLS-2$ } writeOut("</skl>\n"); //$NON-NLS-1$ writeOut(" <tool tool-id=\"" + strQtToolID + "\" tool-name=\"HSStudio\"/>\n"); //$NON-NLS-1$ //$NON-NLS-2$ writeOut(" <hs:prop-group name=\"encoding\"><hs:prop prop-type=\"encoding\">" //$NON-NLS-1$ + strSrcEncoding + "</hs:prop></hs:prop-group>\n"); //$NON-NLS-1$ writeOut("</header>\n<body>\n"); //$NON-NLS-1$ writeOut("\n"); //$NON-NLS-1$ } private void writeOut(String string) throws IOException { out.write(string.getBytes("UTF-8")); //$NON-NLS-1$ } /** * 将 source 所代表的压缩包解压到临时目录 strTmpFolderPath * @param source * @throws IOException * ; */ private void releaseSrcZip(String source) throws IOException { String sysTemp = System.getProperty("java.io.tmpdir"); String dirName = "tmpPPTXfolder" + System.currentTimeMillis(); File dir = new File(sysTemp + File.separator + dirName); dir.mkdirs(); strTmpFolderPath = dir.getAbsolutePath(); fileManager.releaseZipToFile(source, strTmpFolderPath); } } }
39,097
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
Activator.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.pptx/src/net/heartsome/cat/converter/pptx/Activator.java
package net.heartsome.cat.converter.pptx; import java.util.Properties; import net.heartsome.cat.converter.Converter; import net.heartsome.cat.converter.util.ConverterRegister; import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.ui.plugin.AbstractUIPlugin; import org.osgi.framework.BundleActivator; import org.osgi.framework.BundleContext; import org.osgi.framework.ServiceRegistration; public class Activator extends AbstractUIPlugin implements BundleActivator { /** The Constant PLUGIN_ID. */ public static final String PLUGIN_ID = "net.heartsome.cat.converter.pptx"; private static BundleContext context; @SuppressWarnings("rawtypes") private ServiceRegistration pptx2XLIFFSR; @SuppressWarnings("rawtypes") private ServiceRegistration xliff2PPTXSR; private static Activator plugin; public Activator() { } static BundleContext getContext() { return context; } /* * (non-Javadoc) * @see org.osgi.framework.BundleActivator#start(org.osgi.framework.BundleContext) */ public void start(BundleContext bundleContext) throws Exception { super.start(bundleContext); Activator.context = bundleContext; Converter pptx2XLIFF = new PPTX2XLIFF(); Properties properties = new Properties(); properties.put(Converter.ATTR_NAME, PPTX2XLIFF.NAME_VALUE); properties.put(Converter.ATTR_TYPE, PPTX2XLIFF.TYPE_VALUE); properties.put(Converter.ATTR_TYPE_NAME, PPTX2XLIFF.TYPE_NAME_VALUE); pptx2XLIFFSR = ConverterRegister.registerPositiveConverter(context, pptx2XLIFF, properties); Converter xliff2PPTX = new XLIFF2PPTX(); properties = new Properties(); properties.put(Converter.ATTR_NAME, XLIFF2PPTX.NAME_VALUE); properties.put(Converter.ATTR_TYPE, XLIFF2PPTX.TYPE_VALUE); properties.put(Converter.ATTR_TYPE_NAME, XLIFF2PPTX.TYPE_NAME_VALUE); xliff2PPTXSR = ConverterRegister.registerReverseConverter(context, xliff2PPTX, properties); plugin = this; } /* * (non-Javadoc) * @see org.osgi.framework.BundleActivator#stop(org.osgi.framework.BundleContext) */ public void stop(BundleContext bundleContext) throws Exception { plugin = null; if (pptx2XLIFFSR != null) { pptx2XLIFFSR.unregister(); pptx2XLIFFSR = null; } if (xliff2PPTXSR != null) { xliff2PPTXSR.unregister(); xliff2PPTXSR = null; } Activator.context = null; super.stop(bundleContext); } public static ImageDescriptor getImageDescriptor(String path) { return imageDescriptorFromPlugin(PLUGIN_ID, path); } public static Activator getDefault() { return plugin; } }
2,543
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
XLIFF2PPTX.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.pptx/src/net/heartsome/cat/converter/pptx/XLIFF2PPTX.java
package net.heartsome.cat.converter.pptx; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.text.MessageFormat; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.zip.ZipOutputStream; import net.heartsome.cat.common.file.FileManager; import net.heartsome.cat.common.util.TextUtil; import net.heartsome.cat.converter.Converter; import net.heartsome.cat.converter.ConverterException; import net.heartsome.cat.converter.pptx.resource.Messages; import net.heartsome.cat.converter.util.ConverterUtils; import net.heartsome.cat.converter.util.Progress; import net.heartsome.xml.vtdimpl.VTDUtils; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.OperationCanceledException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.ximpleware.AutoPilot; import com.ximpleware.NavException; import com.ximpleware.VTDGen; import com.ximpleware.VTDNav; import com.ximpleware.XMLModifier; import com.ximpleware.XPathEvalException; import com.ximpleware.XPathParseException; /** * XLIFF 转换为 PPTX * @author peason * @version * @since JDK1.6 */ public class XLIFF2PPTX implements Converter { private static final Logger LOGGER = LoggerFactory.getLogger(XLIFF2PPTX.class); /** The Constant TYPE_VALUE. */ public static final String TYPE_VALUE = "pptx"; /** The Constant TYPE_NAME_VALUE. */ public static final String TYPE_NAME_VALUE = Messages.getString("pptx.TYPE_NAME_VALUE"); /** The Constant NAME_VALUE. */ public static final String NAME_VALUE = "XLIFF to MS Office PowerPoint 2007 Conveter"; public Map<String, String> convert(Map<String, String> args, IProgressMonitor monitor) throws ConverterException { XLIFF2PPTXImpl impl = new XLIFF2PPTXImpl(); return impl.run(args, monitor); } public String getName() { return NAME_VALUE; } public String getType() { return TYPE_VALUE; } public String getTypeName() { return TYPE_NAME_VALUE; } /** * XLIFF 转换为 PPTX 的实现类 * @author peason * @version * @since JDK1.6 */ class XLIFF2PPTXImpl { /** SlideMaster 文件中 a 的前缀 */ private static final String PREFIX_A = "a"; /** SlideMaster 文件中 a 的命名空间 */ private static final String NAMESPACE_A = "http://schemas.openxmlformats.org/drawingml/2006/main"; /** SlideMaster 文件中 p 的前缀 */ private static final String PREFIX_P = "p"; /** SlideMaster 文件中 a 的命名空间 */ private static final String NAMESPACE_P = "http://schemas.openxmlformats.org/presentationml/2006/main"; /** XLIFF 文件路径 */ private String strXLIFFPath; /** 骨架文件路径 */ private String strSklPath; private ZipOutputStream zipOut; /** 骨架文件的临时解压目录 */ private String strTmpFolderPath; private FileManager fileManager = new FileManager(); /** 存放文本段的集合,key 为 trans-unit 的 id, value 的第一个值为 source, 第二个为 target */ private HashMap<String, String[]> mapSegment = new HashMap<String, String[]>(); /** 是否为预览翻译模式 */ private boolean blnIsPreviewMode; /** * 转换器的处理流程如下: <br/> * 1. 解析 XLIFF 文件,获取所有文本段并存放入集合中。 <br/> * 2. 将骨架文件解压到临时目录。<br/> * 3. 将临时目录中除 slides 和 notesSlides 文件夹之外的其他文件放入目标文件。<br/> * 4. 解析 slides 目录下以 .skl 结尾的文件,并替换文件中的骨架信息,替换完成后去除 .skl 后缀放入目标文件, <br/> * slides 目录下的其他文件直接放入目标文件。<br/> * 5. 解析 notesSlides 目录下以 .skl 结尾的文件,并替换文件中的骨架信息,替换完成后去除 .skl 后缀放入目标文件, <br/> * slides 目录下的其他文件直接放入目标文件。<br/> * 6. 删除临时解压目录。<br/> * @param args * @param monitor * @return * @throws ConverterException * ; */ public Map<String, String> run(Map<String, String> args, IProgressMonitor monitor) throws ConverterException { monitor = Progress.getMonitor(monitor); monitor.beginTask("", 12); // 转换过程分为 11 部分,loadSegment 占 1,releaseSklZip 占 1,createZip 占 1, handleSklFile(slides) 占 5, // handleSklFile(notesSlides) 占 3,deleteFileOrFolder 占 1 IProgressMonitor firstMonitor = Progress.getSubMonitor(monitor, 1); firstMonitor.beginTask(Messages.getString("pptx.XLIFF2PPTX.task1"), 1); firstMonitor.subTask(""); Map<String, String> result = new HashMap<String, String>(); strXLIFFPath = args.get(Converter.ATTR_XLIFF_FILE); String strTgtPath = args.get(Converter.ATTR_TARGET_FILE); strSklPath = args.get(Converter.ATTR_SKELETON_FILE); String strIsPreviewMode = args.get(Converter.ATTR_IS_PREVIEW_MODE); blnIsPreviewMode = strIsPreviewMode != null && strIsPreviewMode.equals(Converter.TRUE); try { zipOut = new ZipOutputStream(new FileOutputStream(strTgtPath)); if (firstMonitor.isCanceled()) { throw new OperationCanceledException(Messages.getString("preference.cancel")); } loadSegment(); firstMonitor.worked(1); firstMonitor.done(); if (monitor.isCanceled()) { throw new OperationCanceledException(Messages.getString("preference.cancel")); } IProgressMonitor secondMonitor = Progress.getSubMonitor(monitor, 1); secondMonitor.beginTask(Messages.getString("pptx.XLIFF2PPTX.task2"), 1); secondMonitor.subTask(""); releaseSklZip(strSklPath); secondMonitor.worked(1); secondMonitor.done(); if (monitor.isCanceled()) { throw new OperationCanceledException(Messages.getString("preference.cancel")); } IProgressMonitor thirdMonitor = Progress.getSubMonitor(monitor, 1); thirdMonitor.beginTask(Messages.getString("pptx.XLIFF2PPTX.task3"), 1); thirdMonitor.subTask(""); List<String> lstExcludeFolder = new ArrayList<String>(); lstExcludeFolder.add(strTmpFolderPath + File.separator + "ppt" + File.separator + "slides"); lstExcludeFolder.add(strTmpFolderPath + File.separator + "ppt" + File.separator + "notesSlides"); fileManager.createZip(strTmpFolderPath, zipOut, lstExcludeFolder); thirdMonitor.worked(1); thirdMonitor.done(); handleSklFile(strTmpFolderPath + File.separator + "ppt" + File.separator + "slides", Progress.getSubMonitor(monitor, 5)); handleSklFile(strTmpFolderPath + File.separator + "ppt" + File.separator + "notesSlides", Progress.getSubMonitor(monitor, 3)); zipOut.flush(); zipOut.close(); if (monitor.isCanceled()) { throw new OperationCanceledException(Messages.getString("preference.cancel")); } IProgressMonitor fourthMonitor = Progress.getSubMonitor(monitor, 1); fourthMonitor.beginTask(Messages.getString("pptx.XLIFF2PPTX.task4"), 1); fourthMonitor.subTask(""); fileManager.deleteFileOrFolder(new File(strTmpFolderPath)); fourthMonitor.worked(1); fourthMonitor.done(); result.put(Converter.ATTR_TARGET_FILE, strTgtPath); } catch (OperationCanceledException e) { throw e; } catch (Exception e) { e.printStackTrace(); LOGGER.error(Messages.getString("pptx.XLIFF2PPTX.logger1"), e); ConverterUtils.throwConverterException(Activator.PLUGIN_ID, Messages.getString("pptx.XLIFF2PPTX.msg1"), e); } finally { monitor.done(); } return result; } /** * 解析 XLIFF 文件,获取所有文本段集合 * @throws NavException * @throws XPathParseException * @throws XPathEvalException */ private void loadSegment() throws NavException, XPathParseException, XPathEvalException { VTDGen vg = new VTDGen(); if (vg.parseFile(strXLIFFPath, true)) { VTDNav vn = vg.getNav(); VTDUtils vu = new VTDUtils(vn); AutoPilot ap = new AutoPilot(vn); ap.selectXPath("/xliff/file/body//trans-unit"); while (ap.evalXPath() != -1) { String strTuId = vu.getCurrentElementAttribut("id", null); String strSource = vu.getElementContent("./source"); String strTarget = vu.getElementContent("./target"); mapSegment.put(strTuId, new String[] { strSource, strTarget }); } } } /** * 解压骨架文件到临时目录 * @param sklPath * 骨架文件路径 * @throws IOException */ private void releaseSklZip(String sklPath) throws IOException { String sysTemp = System.getProperty("java.io.tmpdir"); String dirName = "tmpPPTXfolder" + System.currentTimeMillis(); File dir = new File(sysTemp + File.separator + dirName); dir.mkdirs(); strTmpFolderPath = dir.getAbsolutePath(); fileManager.releaseZipToFile(sklPath, strTmpFolderPath); } /** * 处理 filePath 指定目录下的骨架文件,非骨架文件直接放入压缩包。 * @param filePath * @throws Exception * ; */ private void handleSklFile(String filePath, IProgressMonitor monitor) throws Exception { File file = new File(filePath); if (!file.exists()) { monitor.done(); return; } List<File> lstSlideFile = fileManager.getSubFiles(file, null); monitor.beginTask("", lstSlideFile.size()); VTDGen vg = new VTDGen(); VTDUtils vu = new VTDUtils(); XMLModifier xm = new XMLModifier(); AutoPilot ap = new AutoPilot(); ap.declareXPathNameSpace(PREFIX_A, NAMESPACE_A); ap.declareXPathNameSpace(PREFIX_P, NAMESPACE_P); String strSklTag = "%%%"; Pattern pattern = Pattern.compile("%%%\\d+%%%"); List<String> lstId = new ArrayList<String>(); StringBuffer sbText = new StringBuffer(); for (File slideFile : lstSlideFile) { if (monitor.isCanceled()) { throw new OperationCanceledException(Messages.getString("preference.cancel")); } monitor.subTask(MessageFormat.format(Messages.getString("pptx.XLIFF2PPTX.task5"), slideFile.getName())); if (slideFile.isDirectory()) { for (File tmpFile : slideFile.listFiles()) { fileManager.addFileToZip(zipOut, strTmpFolderPath, tmpFile.getAbsolutePath()); } } else if (!slideFile.getName().endsWith(".skl")) { fileManager.addFileToZip(zipOut, strTmpFolderPath, slideFile.getAbsolutePath()); } else if (slideFile.getName().endsWith(".skl")) { // 解析骨架文件 String strSlidePath = slideFile.getAbsolutePath(); vg = new VTDGen(); if (vg.parseFile(strSlidePath, true)) { VTDNav vn = vg.getNav(); vu.bind(vn); ap.bind(vn); xm.bind(vn); ap.selectXPath("//p:cSld/p:spTree//a:t"); while (ap.evalXPath() != -1) { String content = vu.getValue("./text()"); if (content == null) { continue; } Matcher matcher = pattern.matcher(content); lstId.clear(); while (matcher.find()) { String group = matcher.group(); lstId.add(group.substring(group.indexOf(strSklTag) + strSklTag.length(), group.lastIndexOf(strSklTag))); } if (lstId.size() == 1) { String[] arrSrcAndTgt = mapSegment.get(lstId.get(0)); if (arrSrcAndTgt != null) { String strSrc = arrSrcAndTgt[0]; String strTgt = arrSrcAndTgt[1]; if (strTgt != null) { strTgt = cleanTag(strTgt); if (blnIsPreviewMode || !"".equals(strTgt.trim())) { //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ xm = vu.update(null, xm, "./text()", strTgt); } else { xm = vu.update(null, xm, "./text()", cleanTag(strSrc)); } } else { xm = vu.update(null, xm, "./text()", cleanTag(strSrc)); } } else { ConverterUtils.throwConverterException( Activator.PLUGIN_ID, MessageFormat.format(Messages.getString("pptx.XLIFF2PPTX.msg2"), lstId.get(0))); } } else { sbText.delete(0, sbText.length()); for (String id : lstId) { String[] arrSrcAndTgt = mapSegment.get(id); if (arrSrcAndTgt != null) { String strSrc = arrSrcAndTgt[0]; String strTgt = arrSrcAndTgt[1]; if (strTgt != null) { strTgt = cleanTag(strTgt); if (blnIsPreviewMode || !"".equals(strTgt.trim())) { //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ sbText.append(strTgt); } else { sbText.append(cleanTag(strSrc)); } } else { sbText.append(cleanTag(strSrc)); } } else { ConverterUtils.throwConverterException( Activator.PLUGIN_ID, MessageFormat.format(Messages.getString("pptx.XLIFF2PPTX.msg2"), lstId.get(0))); } } xm = vu.update(null, xm, "./text()", sbText.toString()); } } strSlidePath = strSlidePath.substring(0, strSlidePath.lastIndexOf(".skl")); xm.output(strSlidePath); fileManager.addFileToZip(zipOut, strTmpFolderPath, strSlidePath); } } monitor.worked(1); } monitor.done(); } /** 匹配 ph 标记的正则表达式 */ private Pattern pattern = Pattern.compile("<ph\\s*(\\w*=('|\")[^</>'\"]+('|\"))*>[^<>]*</ph>"); /** * 清除 string 中的标记 * @param string * 待处理的字符串 * @return ; */ private String cleanTag(String string) { Matcher matcher = pattern.matcher(string); int start = 0; int end = 0; StringBuffer sbText = new StringBuffer(); while (matcher.find()) { String group = matcher.group(); // 去除标记。如 <ph id="1">abcd</ph> 去除标记后为 abcd group = group.substring(group.indexOf(">") + 1, group.lastIndexOf("<")); group = TextUtil.resetSpecialString(group); start = matcher.start(); sbText.append(string.substring(end, start)).append(group); end = matcher.end(); } sbText.append(string.substring(end, string.length())); return sbText.toString(); } } }
14,079
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
ConverterPreferenceInitializer.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.pptx/src/net/heartsome/cat/converter/pptx/preference/ConverterPreferenceInitializer.java
package net.heartsome.cat.converter.pptx.preference; import net.heartsome.cat.converter.pptx.Activator; import org.eclipse.core.runtime.preferences.AbstractPreferenceInitializer; import org.eclipse.jface.preference.IPreferenceStore; /** * 设置首选项的 PowerPoint 2007 默认值类 * @author peason * @version * @since JDK1.6 */ public class ConverterPreferenceInitializer extends AbstractPreferenceInitializer { @Override public void initializeDefaultPreferences() { IPreferenceStore store = Activator.getDefault().getPreferenceStore(); store.setDefault(Constants.PPTX_FILTER, false); } }
616
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
PPTXPreferencePage.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.pptx/src/net/heartsome/cat/converter/pptx/preference/PPTXPreferencePage.java
package net.heartsome.cat.converter.pptx.preference; import net.heartsome.cat.common.ui.HsImageLabel; import net.heartsome.cat.converter.pptx.Activator; import net.heartsome.cat.converter.pptx.resource.Messages; import org.eclipse.jface.layout.GridDataFactory; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.preference.PreferencePage; import org.eclipse.swt.SWT; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Group; import org.eclipse.ui.IWorkbench; import org.eclipse.ui.IWorkbenchPreferencePage; /** * 首选项-->Microsoft PowerPoint 2007 页面 * @author peason * @version * @since JDK1.6 */ public class PPTXPreferencePage extends PreferencePage implements IWorkbenchPreferencePage { private IPreferenceStore preferenceStore; /** 备注复选框 */ private Button btnNote; public PPTXPreferencePage() { setTitle(Messages.getString("preference.PPTXPreferencePage.title")); setPreferenceStore(Activator.getDefault().getPreferenceStore()); preferenceStore = getPreferenceStore(); } @Override protected Control createContents(Composite parent) { Composite tparent = new Composite(parent, SWT.NONE); tparent.setLayout(new GridLayout()); tparent.setLayoutData(new GridData(GridData.FILL_BOTH)); Group groupCommon = new Group(tparent, SWT.NONE); groupCommon.setLayout(new GridLayout()); groupCommon.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); groupCommon.setText(Messages.getString("preference.PPTXPreferencePage.groupCommon")); HsImageLabel imageLabel = new HsImageLabel(Messages.getString("preference.PPTXPreferencePage.imageLabel"), Activator.getImageDescriptor(Constants.PREFERENCE_PPTX_32)); Composite cmpCommon = imageLabel.createControl(groupCommon); cmpCommon.setLayout(new GridLayout()); cmpCommon.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); btnNote = new Button(cmpCommon, SWT.CHECK); btnNote.setText(Messages.getString("preference.PPTXPreferencePage.btnNote")); GridDataFactory.fillDefaults().applyTo(btnNote); imageLabel.computeSize(); btnNote.setSelection(preferenceStore.getBoolean(Constants.PPTX_FILTER)); return parent; } public void init(IWorkbench workbench) { } @Override protected void performDefaults() { btnNote.setSelection(preferenceStore.getDefaultBoolean(Constants.PPTX_FILTER)); } @Override public boolean performOk() { preferenceStore.setValue(Constants.PPTX_FILTER, btnNote.getSelection()); return true; } }
2,662
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
Constants.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.pptx/src/net/heartsome/cat/converter/pptx/preference/Constants.java
package net.heartsome.cat.converter.pptx.preference; /** * 常量类 * @author peason * @version * @since JDK1.6 */ public class Constants { /** 首选项-->Microsoft PowerPoint 2007 页面的提示信息图片 */ public static final String PREFERENCE_PPTX_32 = "images/preference/powerpoint_32.png"; public static final String PPTX_FILTER = "net.heartsome.cat.converter.pptx.preference.PPTX2007"; }
417
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
Messages.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.pptx/src/net/heartsome/cat/converter/pptx/resource/Messages.java
/** * Messages.java * * Version information : * * Date:Jan 14, 2010 * * Copyright notice : */ package net.heartsome.cat.converter.pptx.resource; import java.util.MissingResourceException; import java.util.ResourceBundle; /** * 国际化工具类 * @author peason * @version * @since JDK1.6 */ public final class Messages { /** The Constant BUNDLE_NAME. */ private static final String BUNDLE_NAME = "net.heartsome.cat.converter.pptx.resource.pptx"; //$NON-NLS-1$ /** The Constant RESOURCE_BUNDLE. */ private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle.getBundle(BUNDLE_NAME); /** * Instantiates a new messages. */ private Messages() { // do nothing } /** * Gets the string. * @param key * the key * @return the string */ public static String getString(String key) { try { return RESOURCE_BUNDLE.getString(key); } catch (MissingResourceException e) { return '!' + key + '!'; } } }
1,017
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
Xliff2TaggedRtfTest.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.taggedrtf/testSrc/net/heartsome/cat/converter/taggedrtf/test/Xliff2TaggedRtfTest.java
package net.heartsome.cat.converter.taggedrtf.test; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.io.File; import java.util.HashMap; import java.util.Map; import net.heartsome.cat.converter.Converter; import net.heartsome.cat.converter.ConverterException; import net.heartsome.cat.converter.taggedrtf.Xliff2TaggedRtf; import org.junit.Before; import org.junit.Test; public class Xliff2TaggedRtfTest { public static Xliff2TaggedRtf converter = new Xliff2TaggedRtf(); private static String tgtFile = "rc/Test_en-US.rtf"; private static String xlfFile = "rc/Test.rtf.xlf"; private static String sklFile = "rc/Test.rtf.skl.tg.skl"; @Before public void setUp() { File tgt = new File(tgtFile); if (tgt.exists()) { tgt.delete(); } } @Test public void testConvertODT() throws ConverterException { String rootFolder = "/data/john/Workspaces/CAT/HSTS7/"; Map<String, String> args = new HashMap<String, String>(); args.put(Converter.ATTR_TARGET_FILE, tgtFile); args.put(Converter.ATTR_XLIFF_FILE, xlfFile); args.put(Converter.ATTR_SKELETON_FILE, sklFile); args.put(Converter.ATTR_SOURCE_ENCODING, "BIG5"); args.put(Converter.ATTR_CATALOGUE, rootFolder + "catalogue/catalogue.xml"); Map<String, String> result = converter.convert(args, null); String target = result.get(Converter.ATTR_TARGET_FILE); assertNotNull(target); File tgtFile = new File(target); assertNotNull(tgtFile); assertTrue(tgtFile.exists()); } }
1,514
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
TaggedRtf2XliffTest.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.taggedrtf/testSrc/net/heartsome/cat/converter/taggedrtf/test/TaggedRtf2XliffTest.java
package net.heartsome.cat.converter.taggedrtf.test; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.io.File; import java.util.HashMap; import java.util.Map; import net.heartsome.cat.converter.Converter; import net.heartsome.cat.converter.ConverterException; import net.heartsome.cat.converter.taggedrtf.TaggedRtf2Xliff; import org.junit.AfterClass; import org.junit.Before; import org.junit.Test; public class TaggedRtf2XliffTest { public static TaggedRtf2Xliff converter = new TaggedRtf2Xliff(); private static String srcFile = "rc/Test.rtf"; private static String xlfFile = "rc/Test.rtf.xlf"; private static String sklFile = "rc/Test.rtf.skl"; @Before public void setUp() { File xlf = new File(xlfFile); if (xlf.exists()) { xlf.delete(); } File skl = new File(sklFile); if (skl.exists()) { skl.delete(); } } @Test(expected = ConverterException.class) public void testConvertMissingCatalog() throws ConverterException { String rootFolder = "/data/john/Workspaces/CAT/HSTS7/"; Map<String, String> args = new HashMap<String, String>(); args.put(Converter.ATTR_SOURCE_FILE, srcFile); //$NON-NLS-1$ args.put(Converter.ATTR_XLIFF_FILE, xlfFile); //$NON-NLS-1$ args.put(Converter.ATTR_SKELETON_FILE, sklFile); //$NON-NLS-1$ args.put(Converter.ATTR_SOURCE_LANGUAGE, "zh-CN"); //$NON-NLS-1$ args.put(Converter.ATTR_SOURCE_ENCODING, "BIG5"); //$NON-NLS-1$ // args.put(Converter.ATTR_CATALOGUE, rootFolder + // "catalogue/catalogue.xml"); args.put(Converter.ATTR_SRX, rootFolder + "srx/default_rules.srx"); args.put(Converter.ATTR_PROGRAM_FOLDER, rootFolder); Map<String, String> result = converter.convert(args, null); String xliff = result.get(Converter.ATTR_XLIFF_FILE); assertNotNull(xliff); File xlfFile = new File(xliff); assertNotNull(xlfFile); assertTrue(xlfFile.exists()); } @Test(expected = ConverterException.class) public void testConvertMissingSRX() throws ConverterException { String rootFolder = "/data/john/Workspaces/CAT/HSTS7/"; Map<String, String> args = new HashMap<String, String>(); args.put(Converter.ATTR_SOURCE_FILE, srcFile); //$NON-NLS-1$ args.put(Converter.ATTR_XLIFF_FILE, xlfFile); //$NON-NLS-1$ args.put(Converter.ATTR_SKELETON_FILE, sklFile); //$NON-NLS-1$ args.put(Converter.ATTR_SOURCE_LANGUAGE, "zh-CN"); //$NON-NLS-1$ args.put(Converter.ATTR_SOURCE_ENCODING, "BIG5"); //$NON-NLS-1$ args.put(Converter.ATTR_CATALOGUE, rootFolder + "catalogue/catalogue.xml"); // args.put(Converter.ATTR_SRX, rootFolder + "srx/default_rules.srx"); args.put(Converter.ATTR_PROGRAM_FOLDER, rootFolder); Map<String, String> result = converter.convert(args, null); String xliff = result.get(Converter.ATTR_XLIFF_FILE); assertNotNull(xliff); File xlfFile = new File(xliff); assertNotNull(xlfFile); assertTrue(xlfFile.exists()); } @Test(expected = ConverterException.class) public void testConvertMissingINI() throws ConverterException { String rootFolder = "/data/john/Workspaces/CAT/HSTS7/"; Map<String, String> args = new HashMap<String, String>(); args.put(Converter.ATTR_SOURCE_FILE, srcFile); //$NON-NLS-1$ args.put(Converter.ATTR_XLIFF_FILE, xlfFile); //$NON-NLS-1$ args.put(Converter.ATTR_SKELETON_FILE, sklFile); //$NON-NLS-1$ args.put(Converter.ATTR_SOURCE_LANGUAGE, "zh-CN"); //$NON-NLS-1$ args.put(Converter.ATTR_SOURCE_ENCODING, "BIG5"); //$NON-NLS-1$ args.put(Converter.ATTR_CATALOGUE, rootFolder + "catalogue/catalogue.xml"); args.put(Converter.ATTR_SRX, rootFolder + "srx/default_rules.srx"); // args.put(Converter.ATTR_PROGRAM_FOLDER, rootFolder); Map<String, String> result = converter.convert(args, null); String xliff = result.get(Converter.ATTR_XLIFF_FILE); assertNotNull(xliff); File xlfFile = new File(xliff); assertNotNull(xlfFile); assertTrue(xlfFile.exists()); } @Test public void testConvert() throws ConverterException { String rootFolder = "/data/john/Workspaces/CAT/HSTS7/"; Map<String, String> args = new HashMap<String, String>(); args.put(Converter.ATTR_SOURCE_FILE, srcFile); //$NON-NLS-1$ args.put(Converter.ATTR_XLIFF_FILE, xlfFile); //$NON-NLS-1$ args.put(Converter.ATTR_SKELETON_FILE, sklFile); //$NON-NLS-1$ args.put(Converter.ATTR_SOURCE_LANGUAGE, "zh-CN"); //$NON-NLS-1$ args.put(Converter.ATTR_SOURCE_ENCODING, "BIG5"); //$NON-NLS-1$ args.put(Converter.ATTR_CATALOGUE, rootFolder + "catalogue/catalogue.xml"); args.put(Converter.ATTR_SRX, rootFolder + "srx/default_rules.srx"); args.put(Converter.ATTR_PROGRAM_FOLDER, rootFolder); Map<String, String> result = converter.convert(args, null); String xliff = result.get(Converter.ATTR_XLIFF_FILE); assertNotNull(xliff); File xlfFile = new File(xliff); assertNotNull(xlfFile); assertTrue(xlfFile.exists()); } @AfterClass public static void finalConverter() throws ConverterException { String rootFolder = "/data/john/Workspaces/CAT/HSTS7/"; Map<String, String> args = new HashMap<String, String>(); args.put(Converter.ATTR_SOURCE_FILE, srcFile); //$NON-NLS-1$ args.put(Converter.ATTR_XLIFF_FILE, xlfFile); //$NON-NLS-1$ args.put(Converter.ATTR_SKELETON_FILE, sklFile); //$NON-NLS-1$ args.put(Converter.ATTR_SOURCE_LANGUAGE, "zh-CN"); //$NON-NLS-1$ args.put(Converter.ATTR_SOURCE_ENCODING, "BIG5"); //$NON-NLS-1$ args.put(Converter.ATTR_CATALOGUE, rootFolder + "catalogue/catalogue.xml"); args.put(Converter.ATTR_SRX, rootFolder + "srx/default_rules.srx"); args.put(Converter.ATTR_PROGRAM_FOLDER, rootFolder); Map<String, String> result = converter.convert(args, null); String xliff = result.get(Converter.ATTR_XLIFF_FILE); assertNotNull(xliff); File xlfFile = new File(xliff); assertNotNull(xlfFile); assertTrue(xlfFile.exists()); } }
5,820
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
Activator.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.taggedrtf/src/net/heartsome/cat/converter/taggedrtf/Activator.java
/** * Activator.java * * Version information : * * Date:Jan 14, 2010 * * Copyright notice : */ package net.heartsome.cat.converter.taggedrtf; import java.util.Properties; import net.heartsome.cat.converter.Converter; import net.heartsome.cat.converter.rtf.Rtf2Xliff; import net.heartsome.cat.converter.rtf.Xliff2Rtf; import net.heartsome.cat.converter.util.AndFilter; import net.heartsome.cat.converter.util.ConverterRegister; import net.heartsome.cat.converter.util.EqFilter; import org.osgi.framework.BundleActivator; import org.osgi.framework.BundleContext; import org.osgi.framework.Constants; import org.osgi.framework.ServiceReference; import org.osgi.framework.ServiceRegistration; import org.osgi.util.tracker.ServiceTracker; import org.osgi.util.tracker.ServiceTrackerCustomizer; /** * The Class Activator.The activator class controls the plug-in life cycle. * @author John Zhu * @version * @since JDK1.6 */ public class Activator implements BundleActivator { /** The Constant PLUGIN_ID. */ public static final String PLUGIN_ID = "net.heartsome.cat.converter.taggedrtf"; // The shared instance /** The plugin. */ private static Activator plugin; /** The bundle context. */ private static BundleContext bundleContext; /** The positive tracker. */ private static ServiceTracker positiveTracker; /** The reverse tracker. */ private static ServiceTracker reverseTracker; /** * The constructor. */ public Activator() { } /** * (non-Javadoc) * @see org.osgi.framework.BundleActivator#start(org.osgi.framework.BundleContext) * @param context * @throws Exception */ public void start(BundleContext context) throws Exception { plugin = this; bundleContext = context; // tracker the rtf converter service String positiveFilter = new AndFilter(new EqFilter(Constants.OBJECTCLASS, Converter.class.getName()), new EqFilter(Converter.ATTR_TYPE, Rtf2Xliff.TYPE_VALUE), new EqFilter(Converter.ATTR_DIRECTION, Converter.DIRECTION_POSITIVE)).toString(); positiveTracker = new ServiceTracker(context, context.createFilter(positiveFilter), new RtfPositiveCustomizer()); positiveTracker.open(); String reverseFilter = new AndFilter(new EqFilter(Constants.OBJECTCLASS, Converter.class.getName()), new EqFilter(Converter.ATTR_TYPE, Xliff2Rtf.TYPE_VALUE), new EqFilter(Converter.ATTR_DIRECTION, Converter.DIRECTION_REVERSE)).toString(); reverseTracker = new ServiceTracker(context, context.createFilter(reverseFilter), new RtfReverseCustomize()); reverseTracker.open(); } /** * (non-Javadoc) * @see org.osgi.framework.BundleActivator#stop(org.osgi.framework.BundleContext) * @param context * @throws Exception */ public void stop(BundleContext context) throws Exception { positiveTracker.close(); reverseTracker.close(); plugin = null; bundleContext = null; } /** * Returns the shared instance. * @return the shared instance */ public static Activator getDefault() { return plugin; } // just for test /** * Gets the rtf converter. * @param direction * the direction * @return the rtf converter */ public static Converter getRtfConverter(String direction) { if (Converter.DIRECTION_POSITIVE.equals(direction)) { return new Rtf2Xliff(); } else { return new Xliff2Rtf(); } } /** * The Class RtfPositiveCustomizer. * @author John Zhu * @version * @since JDK1.6 */ private class RtfPositiveCustomizer implements ServiceTrackerCustomizer { /** * (non-Javadoc). * @param reference * the reference * @return the object * @see org.osgi.util.tracker.ServiceTrackerCustomizer#addingService(org.osgi.framework.ServiceReference) */ public Object addingService(ServiceReference reference) { Converter converter = (Converter) bundleContext.getService(reference); // register the converter services Converter resx2Xliff = new TaggedRtf2Xliff(converter); Properties properties = new Properties(); properties.put(Converter.ATTR_NAME, TaggedRtf2Xliff.NAME_VALUE); properties.put(Converter.ATTR_TYPE, TaggedRtf2Xliff.TYPE_VALUE); properties.put(Converter.ATTR_TYPE_NAME, TaggedRtf2Xliff.TYPE_NAME_VALUE); ServiceRegistration registration = ConverterRegister.registerPositiveConverter(bundleContext, resx2Xliff, properties); return registration; } /** * (non-Javadoc). * @param reference * the reference * @param service * the service * @see org.osgi.util.tracker.ServiceTrackerCustomizer#modifiedService(org.osgi.framework.ServiceReference, * java.lang.Object) */ public void modifiedService(ServiceReference reference, Object service) { } /** * (non-Javadoc). * @param reference * the reference * @param service * the service * @see org.osgi.util.tracker.ServiceTrackerCustomizer#removedService(org.osgi.framework.ServiceReference, * java.lang.Object) */ public void removedService(ServiceReference reference, Object service) { ServiceRegistration registration = (ServiceRegistration) service; registration.unregister(); bundleContext.ungetService(reference); } } /** * The Class RtfReverseCustomize. * @author John Zhu * @version * @since JDK1.6 */ private class RtfReverseCustomize implements ServiceTrackerCustomizer { /** * (non-Javadoc). * @param reference * the reference * @return the object * @see org.osgi.util.tracker.ServiceTrackerCustomizer#addingService(org.osgi.framework.ServiceReference) */ public Object addingService(ServiceReference reference) { Converter converter = (Converter) bundleContext.getService(reference); Converter xliff2Resx = new Xliff2TaggedRtf(converter); Properties properties = new Properties(); properties.put(Converter.ATTR_NAME, Xliff2TaggedRtf.NAME_VALUE); properties.put(Converter.ATTR_TYPE, Xliff2TaggedRtf.TYPE_VALUE); properties.put(Converter.ATTR_TYPE_NAME, Xliff2TaggedRtf.TYPE_NAME_VALUE); ServiceRegistration registration = ConverterRegister.registerReverseConverter(bundleContext, xliff2Resx, properties); return registration; } /** * (non-Javadoc). * @param reference * the reference * @param service * the service * @see org.osgi.util.tracker.ServiceTrackerCustomizer#modifiedService(org.osgi.framework.ServiceReference, * java.lang.Object) */ public void modifiedService(ServiceReference reference, Object service) { } /** * (non-Javadoc). * @param reference * the reference * @param service * the service * @see org.osgi.util.tracker.ServiceTrackerCustomizer#removedService(org.osgi.framework.ServiceReference, * java.lang.Object) */ public void removedService(ServiceReference reference, Object service) { ServiceRegistration registration = (ServiceRegistration) service; registration.unregister(); bundleContext.ungetService(reference); } } }
7,047
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
Xliff2TaggedRtf.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.taggedrtf/src/net/heartsome/cat/converter/taggedrtf/Xliff2TaggedRtf.java
/** * Xliff2TaggedRtf.java * * Version information : * * Date:Jan 14, 2010 * * Copyright notice : */ package net.heartsome.cat.converter.taggedrtf; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.util.HashMap; import java.util.Hashtable; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.StringTokenizer; import net.heartsome.cat.converter.Converter; import net.heartsome.cat.converter.ConverterException; import net.heartsome.cat.converter.taggedrtf.resource.Messages; import net.heartsome.cat.converter.util.ConverterUtils; import net.heartsome.cat.converter.util.Progress; import net.heartsome.cat.converter.util.ReverseConversionInfoLogRecord; import net.heartsome.xml.Document; import net.heartsome.xml.Element; import net.heartsome.xml.SAXBuilder; import net.heartsome.xml.XMLOutputter; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.OperationCanceledException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.w3c.dom.Node; import org.xml.sax.SAXException; /** * The Class Xliff2TaggedRtf. * @author John Zhu * @version * @since JDK1.6 */ public class Xliff2TaggedRtf implements Converter { private static final Logger LOGGER = LoggerFactory.getLogger(Xliff2TaggedRtf.class); /** The Constant TYPE_VALUE. */ public static final String TYPE_VALUE = "x-trtf"; /** The Constant TYPE_NAME_VALUE. */ public static final String TYPE_NAME_VALUE = Messages.getString("taggedrtf.TYPE_NAME_VALUE"); /** The Constant NAME_VALUE. */ public static final String NAME_VALUE = "XLIFF to Tagged RTF Conveter"; // 内部实现所依赖的转换器 /** The dependant converter. */ private Converter dependantConverter; /** * for test to initialize depend on converter. */ public Xliff2TaggedRtf() { dependantConverter = Activator.getRtfConverter(Converter.DIRECTION_REVERSE); } /** * 运行时把所依赖的转换器,在初始化的时候通过构造函数注入。. * @param converter * the converter */ public Xliff2TaggedRtf(Converter converter) { dependantConverter = converter; } /** * (non-Javadoc) * @see net.heartsome.cat.converter.Converter#convert(java.util.Map, org.eclipse.core.runtime.IProgressMonitor) * @param args * @param monitor * @return * @throws ConverterException */ public Map<String, String> convert(Map<String, String> args, IProgressMonitor monitor) throws ConverterException { Xliff2TaggedRtfImpl converter = new Xliff2TaggedRtfImpl(); return converter.run(args, monitor); } /** * (non-Javadoc) * @see net.heartsome.cat.converter.Converter#getName() * @return */ public String getName() { return NAME_VALUE; } /** * (non-Javadoc) * @see net.heartsome.cat.converter.Converter#getType() * @return */ public String getType() { return TYPE_VALUE; } /** * (non-Javadoc) * @see net.heartsome.cat.converter.Converter#getTypeName() * @return */ public String getTypeName() { return TYPE_NAME_VALUE; } /** * The Class Xliff2TaggedRtfImpl. * @author John Zhu * @version * @since JDK1.6 */ class Xliff2TaggedRtfImpl { /** The skeleton. */ private String skeleton; /** The xliff. */ private String xliff; /** The skl doc. */ private Document sklDoc; /** The skl root. */ private Element sklRoot; /** The segments. */ private Hashtable<String, Element> segments; /** The tw4win mark. */ private String tw4winMark; /** The source start. */ private Element sourceStart; /** The source end. */ private Element sourceEnd; /** The target start. */ private Element targetStart; /** The target end. */ private Element targetEnd; /** The tags. */ private String tags; /** The close. */ private String close; /** * Run. * @param params * the params * @param monitor * the monitor * @return the map< string, string> * @throws ConverterException * the converter exception */ public Map<String, String> run(Map<String, String> params, IProgressMonitor monitor) throws ConverterException { monitor = Progress.getMonitor(monitor); ReverseConversionInfoLogRecord infoLogger = ConverterUtils.getReverseConversionInfoLogRecord(); infoLogger.startConversion(); Map<String, String> result = new HashMap<String, String>(); try { // 把转换过程分为四大部分共 10 个任务,其中加载文件占 2,文件处理占 2,重写 xml 文件占 2,委派其它转换器进行转换占 4。 monitor.beginTask("", 10); monitor.subTask(Messages.getString("taggedrtf.Xliff2TaggedRtf.task2")); infoLogger.startLoadingXliffFile(); xliff = params.get(Converter.ATTR_XLIFF_FILE); skeleton = params.get(Converter.ATTR_SKELETON_FILE) + ".tg.skl"; infoLogger.logConversionFileInfo(null, null, xliff, skeleton); loadFiles(); infoLogger.endLoadingXliffFile(); monitor.worked(2); // 是否取消操作 if (monitor.isCanceled()) { throw new OperationCanceledException(); } monitor.subTask(Messages.getString("taggedrtf.Xliff2TaggedRtf.task3")); long startTime = 0; if (LOGGER.isInfoEnabled()) { startTime = System.currentTimeMillis(); LOGGER.info(Messages.getString("taggedrtf.Xliff2TaggedRtf.logger1"), startTime); } processFiles(); long endTime = 0; if (LOGGER.isInfoEnabled()) { endTime = System.currentTimeMillis(); LOGGER.info(Messages.getString("taggedrtf.Xliff2TaggedRtf.logger2"), endTime); LOGGER.info(Messages.getString("taggedrtf.Xliff2TaggedRtf.logger3"), endTime - startTime); } monitor.worked(2); // 是否取消操作 if (monitor.isCanceled()) { throw new OperationCanceledException(); } monitor.subTask(Messages.getString("taggedrtf.Xliff2TaggedRtf.task4")); if (LOGGER.isInfoEnabled()) { startTime = System.currentTimeMillis(); LOGGER.info(Messages.getString("taggedrtf.Xliff2TaggedRtf.logger4"), startTime); } File nskl = new File(skeleton + ".xlf"); FileOutputStream output = new FileOutputStream(nskl.getAbsolutePath()); XMLOutputter outputter = new XMLOutputter(); outputter.preserveSpace(true); outputter.output(sklDoc, output); output.close(); if (LOGGER.isInfoEnabled()) { endTime = System.currentTimeMillis(); LOGGER.info(Messages.getString("taggedrtf.Xliff2TaggedRtf.logger5"), endTime); LOGGER.info(Messages.getString("taggedrtf.Xliff2TaggedRtf.logger6"), endTime - startTime); } monitor.worked(2); params.put(Converter.ATTR_XLIFF_FILE, nskl.getAbsolutePath()); params.put(Converter.ATTR_SKELETON_FILE, getSkeleton()); // 委派其它转换器进行转换 result = dependantConverter.convert(params, Progress.getSubMonitor(monitor, 4)); nskl.delete(); } catch (OperationCanceledException e) { throw e; } catch (Exception e) { if (Converter.DEBUG_MODE) { e.printStackTrace(); } if (e instanceof ConverterException) { throw (ConverterException)e; } else { ConverterUtils.throwConverterException(Activator.PLUGIN_ID, Messages.getString("taggedrtf.Xliff2TaggedRtf.msg1"), e); } } finally { monitor.done(); } infoLogger.endConversion(); return result; } /** * Gets the skeleton. * @return the skeleton */ private String getSkeleton() { String result = ""; //$NON-NLS-1$ Element file = sklRoot.getChild("file"); //$NON-NLS-1$ if (file != null) { Element header = file.getChild("header"); //$NON-NLS-1$ if (header != null) { Element mskl = header.getChild("skl"); //$NON-NLS-1$ if (mskl != null) { Element external = mskl.getChild("external-file"); //$NON-NLS-1$ if (external != null) { result = external.getAttributeValue("href"); //$NON-NLS-1$ } } } } return result; } /** * Process files. * @throws SAXException * the SAX exception * @throws IOException * Signals that an I/O exception has occurred. */ private void processFiles() throws SAXException, IOException { Element body = sklRoot.getChild("file").getChild("body"); //$NON-NLS-1$ //$NON-NLS-2$ List<Element> units = body.getChildren("trans-unit"); //$NON-NLS-1$ Iterator<Element> i = units.iterator(); while (i.hasNext()) { Element unit = i.next(); Element segment = segments.get(unit.getAttributeValue("id")); //$NON-NLS-1$ //FIX Bug #3417 :Tagged RTF 转换器:转换为目标文件时无法获取译文 //if (segment.getAttributeValue("approved", "no").equalsIgnoreCase("yes")) { //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ buildTarget(unit, segment); // unit.setAttribute("approved", "yes"); //$NON-NLS-1$ //$NON-NLS-2$ //} } } /** * Builds the target. * @param original * the original * @param translated * the translated * @throws SAXException * the SAX exception * @throws IOException * Signals that an I/O exception has occurred. */ private void buildTarget(Element original, Element translated) throws SAXException, IOException { Element source = original.getChild("source"); //$NON-NLS-1$ Element target = original.getChild("target"); //$NON-NLS-1$ if (target == null) { target = new Element("target", sklDoc); //$NON-NLS-1$ original.addContent(target); } int phId = 1000; if (TaggedRtf2Xliff.find(source.toString(), "{0&gt;", 0) != -1) { //$NON-NLS-1$ // this segment was already formatted by Trados buildMissingTags(translated); List<Node> content = sourceStart.getContent(); Iterator<Node> it = content.iterator(); while (it.hasNext()) { Node n = it.next(); if (n.getNodeType() == Node.TEXT_NODE) { String s = n.getNodeValue(); Element open = new Element("ph", sklDoc); //$NON-NLS-1$ open.setAttribute("id", "" + phId++); //$NON-NLS-1$ //$NON-NLS-2$ if (s.matches("^[0-9a-zA-Z\\s].*")) { //$NON-NLS-1$ open.setText("\\v "); //$NON-NLS-1$ } else { open.setText("\\v"); //$NON-NLS-1$ } target.addContent(open); target.addContent(s); } else if (n.getNodeType() == Node.ELEMENT_NODE) { Element e = new Element(n); Element tag = new Element(e.getName(), sklDoc); tag.clone(e, sklDoc); target.addContent(tag); } } content = translated.getChild("source").getContent(); //$NON-NLS-1$ it = content.iterator(); while (it.hasNext()) { Node n = it.next(); if (n.getNodeType() == Node.TEXT_NODE) { String s = n.getNodeValue(); Element open = new Element("ph", sklDoc); //$NON-NLS-1$ open.setAttribute("id", "" + phId++); //$NON-NLS-1$ //$NON-NLS-2$ if (s.matches("^[0-9a-zA-Z\\s].*")) { //$NON-NLS-1$ open.setText("\\v "); //$NON-NLS-1$ } else { open.setText("\\v"); //$NON-NLS-1$ } target.addContent(open); target.addContent(s); } else if (n.getNodeType() == Node.ELEMENT_NODE) { Element e = new Element(n); Element tag = new Element(e.getName(), sklDoc); tag.clone(e, sklDoc); String s = tag.getText(); if (s.matches("^[0-9a-zA-Z\\s].*")) { //$NON-NLS-1$ tag.setText("\\v " + s); //$NON-NLS-1$ } else { tag.setText("\\v" + s); //$NON-NLS-1$ } target.addContent(tag); } } content = sourceEnd.getContent(); it = content.iterator(); while (it.hasNext()) { Node n = it.next(); if (n.getNodeType() == Node.TEXT_NODE) { String s = n.getNodeValue(); Element open = new Element("ph", sklDoc); //$NON-NLS-1$ open.setAttribute("id", "" + phId++); //$NON-NLS-1$ //$NON-NLS-2$ if (s.matches("^[0-9a-zA-Z\\s].*")) { //$NON-NLS-1$ open.setText("\\v "); //$NON-NLS-1$ } else { open.setText("\\v"); //$NON-NLS-1$ } target.addContent(open); target.addContent(s); } else if (n.getNodeType() == Node.ELEMENT_NODE) { Element e = new Element(n); Element tag = new Element(e.getName(), sklDoc); tag.clone(e, sklDoc); target.addContent(tag); } } Element percent = new Element("ph", sklDoc); //$NON-NLS-1$ percent.setText("\\v0{" + tw4winMark + " <\\}100\\{>}"); //$NON-NLS-1$ //$NON-NLS-2$ target.addContent(percent); percent.setAttribute("id", "" + phId++); //$NON-NLS-1$ //$NON-NLS-2$ content = targetStart.getContent(); it = content.iterator(); while (it.hasNext()) { Node n = it.next(); if (n.getNodeType() == Node.TEXT_NODE) { String s = n.getNodeValue(); Element open = new Element("ph", sklDoc); //$NON-NLS-1$ open.setAttribute("id", "" + phId++); //$NON-NLS-1$ //$NON-NLS-2$ if (s.matches("^[0-9a-zA-Z\\s].*")) { //$NON-NLS-1$ open.setText("\\v0 "); //$NON-NLS-1$ } else { open.setText("\\v0"); //$NON-NLS-1$ } target.addContent(open); target.addContent(s); } else if (n.getNodeType() == Node.ELEMENT_NODE) { Element e = new Element(n); Element tag = new Element(e.getName(), sklDoc); tag.clone(e, sklDoc); target.addContent(tag); } } content = translated.getChild("target").getContent(); //$NON-NLS-1$ it = content.iterator(); while (it.hasNext()) { Node n = it.next(); if (n.getNodeType() == Node.TEXT_NODE) { String s = n.getNodeValue(); target.addContent(s); } else if (n.getNodeType() == Node.ELEMENT_NODE) { Element e = new Element(n); Element tag = new Element(e.getName(), sklDoc); tag.clone(e, sklDoc); target.addContent(tag); } } content = targetEnd.getContent(); it = content.iterator(); while (it.hasNext()) { Node n = it.next(); if (n.getNodeType() == Node.TEXT_NODE) { target.addContent(n.getNodeValue()); } else if (n.getNodeType() == Node.ELEMENT_NODE) { Element e = new Element(n); Element tag = new Element(e.getName(), sklDoc); tag.clone(e, sklDoc); target.addContent(tag); } } } else { // It is necessary to add Trados formatting // and hide source text Element start = new Element("ph", sklDoc); //$NON-NLS-1$ start.setText("{" + tw4winMark + " \\{0>}"); //$NON-NLS-1$ //$NON-NLS-2$ start.setAttribute("id", "" + phId++); //$NON-NLS-1$ //$NON-NLS-2$ target.addContent(start); tags = ""; //$NON-NLS-1$ List<Node> content = source.getContent(); Iterator<Node> it = content.iterator(); while (it.hasNext()) { Node n = it.next(); if (n.getNodeType() == Node.TEXT_NODE) { String s = n.getNodeValue(); Element open = new Element("ph", sklDoc); //$NON-NLS-1$ open.setAttribute("id", "" + phId++); //$NON-NLS-1$ //$NON-NLS-2$ if (s.matches("^[0-9a-zA-Z\\s]")) { //$NON-NLS-1$ open.setText("\\v "); //$NON-NLS-1$ } else { open.setText("\\v"); //$NON-NLS-1$ } target.addContent(open); target.addContent(s); } else if (n.getNodeType() == Node.ELEMENT_NODE) { Element e = new Element(n); checkTags(e); Element tag = new Element(e.getName(), sklDoc); tag.clone(e, sklDoc); String s = tag.getText(); if (s.matches("^[0-9a-zA-Z\\s].*")) { //$NON-NLS-1$ tag.setText("\\v " + s); //$NON-NLS-1$ } else { tag.setText("\\v" + s); //$NON-NLS-1$ } target.addContent(tag); } } closeTags(); Element percent = new Element("ph", sklDoc); //$NON-NLS-1$ percent.setText(close + "\\v0{" + tw4winMark + " <\\}100\\{>}"); //$NON-NLS-1$ //$NON-NLS-2$ percent.setAttribute("id", "" + phId++); //$NON-NLS-1$ //$NON-NLS-2$ target.addContent(percent); Element transTarget = translated.getChild("target"); //$NON-NLS-1$ if(null == transTarget){ return ; } List<Node> transContent = transTarget.getContent(); it = transContent.iterator(); boolean skip = false; while (it.hasNext()) { Node n = it.next(); if (n.getNodeType() == Node.TEXT_NODE) { String s = n.getNodeValue(); Element open = new Element("ph", sklDoc); //$NON-NLS-1$ open.setAttribute("id", "" + phId++); //$NON-NLS-1$ //$NON-NLS-2$ if (s.matches("^[0-9a-zA-Z\\s].*")) { //$NON-NLS-1$ open.setText("\\v0 "); //$NON-NLS-1$ } else { open.setText("\\v0"); //$NON-NLS-1$ } target.addContent(open); target.addContent(s); } else if (n.getNodeType() == Node.ELEMENT_NODE) { Element e = new Element(n); if (e.toString().indexOf(tw4winMark) != -1) { skip = true; } else { skip = false; } Element tag = new Element(e.getName(), sklDoc); tag.clone(e, sklDoc); target.addContent(tag); } } if (!skip) { Element last = new Element("ph", sklDoc); //$NON-NLS-1$ last.setAttribute("id", "" + phId++); //$NON-NLS-1$ //$NON-NLS-2$ last.setText("{" + tw4winMark + " <0\\}}"); //$NON-NLS-1$ //$NON-NLS-2$ target.addContent(last); } } } /** * Close tags. */ private void closeTags() { StringTokenizer tk = new StringTokenizer(tags, "\\{}", true); //$NON-NLS-1$ String result = ""; //$NON-NLS-1$ int balance = 0; while (tk.hasMoreTokens()) { String token = tk.nextToken(); if (token.equals("\\")) { //$NON-NLS-1$ if (tk.hasMoreTokens()) { token = token + tk.nextToken(); } else { // TODO check why this happens System.out.println(tags); } } if (token.equals("{")) { //$NON-NLS-1$ balance++; } else if (token.equals("}")) { //$NON-NLS-1$ balance--; } if (token.equals("}")) { //$NON-NLS-1$ int index = result.lastIndexOf("{"); //$NON-NLS-1$ if (index != -1) { result = result.substring(0, index + 1); continue; } result = ""; //$NON-NLS-1$ continue; } result = result + token; } close = ""; //$NON-NLS-1$ if (result.indexOf("\\super") != -1 || result.indexOf("\\sub") != -1) { //$NON-NLS-1$ //$NON-NLS-2$ close = close + "\\nosupersub"; //$NON-NLS-1$ } if (result.indexOf("\\b\\") != -1 || result.indexOf("\\b ") != -1) { //$NON-NLS-1$ //$NON-NLS-2$ close = close + "\\b0"; //$NON-NLS-1$ } if (result.indexOf("\\i\\") != -1 || result.indexOf("\\i ") != -1) { //$NON-NLS-1$ //$NON-NLS-2$ close = close + "\\i0"; //$NON-NLS-1$ } if (result.indexOf("\\ul\\") != -1 || result.indexOf("\\ul ") != -1) { //$NON-NLS-1$ //$NON-NLS-2$ close = close + "\\ul0"; //$NON-NLS-1$ } if (result.indexOf("\\strike") != -1) { //$NON-NLS-1$ close = close + "\\strike0"; //$NON-NLS-1$ } if (balance > 0) { for (int i = 0; i < balance; i++) { close = close + "}"; //$NON-NLS-1$ } } if (balance < 0) { balance = -1 * balance; for (int i = 0; i < balance; i++) { close = close + "{"; //$NON-NLS-1$ } } } /** * Check tags. * @param e * the e */ private void checkTags(Element e) { tags = tags + e.getText(); } /** * Builds the missing tags. * @param tu * the tu * @throws SAXException * the SAX exception * @throws IOException * Signals that an I/O exception has occurred. */ private void buildMissingTags(Element tu) throws SAXException, IOException { List<Element> groups = tu.getChildren("hs:prop-group"); //$NON-NLS-1$ Iterator<Element> it = groups.iterator(); while (it.hasNext()) { Element group = it.next(); if (group.getAttributeValue("name", "").equals("tags")) { //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ List<Element> props = group.getChildren(); Iterator<Element> j = props.iterator(); while (j.hasNext()) { Element prop = j.next(); SAXBuilder builder = new SAXBuilder(); String text = "<?xml version=\"1.0\"?>\n<tag>" + prop.getText() + "</tag>"; //$NON-NLS-1$ //$NON-NLS-2$ ByteArrayInputStream stream = new ByteArrayInputStream(text.getBytes("UTF-8")); //$NON-NLS-1$ Document doc = builder.build(stream); Element root = doc.getRootElement(); if (prop.getAttributeValue("prop-type").equals("sourceStart")) { //$NON-NLS-1$ //$NON-NLS-2$ sourceStart = new Element("tags", sklDoc); //$NON-NLS-1$ sourceStart.clone(root, sklDoc); } if (prop.getAttributeValue("prop-type").equals("sourceEnd")) { //$NON-NLS-1$ //$NON-NLS-2$ sourceEnd = new Element("tags", sklDoc); //$NON-NLS-1$ sourceEnd.clone(root, sklDoc); } if (prop.getAttributeValue("prop-type").equals("targetStart")) { //$NON-NLS-1$ //$NON-NLS-2$ targetStart = new Element("tags", sklDoc); //$NON-NLS-1$ targetStart.clone(root, sklDoc); } if (prop.getAttributeValue("prop-type").equals("targetEnd")) { //$NON-NLS-1$ //$NON-NLS-2$ targetEnd = new Element("tags", sklDoc); //$NON-NLS-1$ targetEnd.clone(root, sklDoc); } } } } } /** * Load files. * @throws SAXException * the SAX exception * @throws IOException * Signals that an I/O exception has occurred. * @throws ConverterException */ private void loadFiles() throws ConverterException { SAXBuilder builder = new SAXBuilder(); try { sklDoc = builder.build(skeleton); } catch (Exception e) { ConverterUtils.throwConverterException(Activator.PLUGIN_ID, Messages.getString("taggedrtf.Xliff2TaggedRtf.msg2"), e); } sklRoot = sklDoc.getRootElement(); try { Document xlfDoc = builder.build(xliff); Element xlfRoot = xlfDoc.getRootElement(); Element body = xlfRoot.getChild("file").getChild("body"); //$NON-NLS-1$ //$NON-NLS-2$ List<Element> units = body.getChildren("trans-unit"); //$NON-NLS-1$ Iterator<Element> i = units.iterator(); segments = new Hashtable<String, Element>(); while (i.hasNext()) { Element unit = i.next(); segments.put(unit.getAttributeValue("id"), unit); //$NON-NLS-1$ } List<Element> properties = xlfRoot.getChild("file").getChild("header").getChildren("hs:prop-group"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ i = properties.iterator(); while (i.hasNext()) { Element group = i.next(); if (group.getAttributeValue("name", "").equals("tags")) { //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ List<Element> taglist = group.getChildren("hs:prop"); //$NON-NLS-1$ Iterator<Element> t = taglist.iterator(); while (t.hasNext()) { Element prop = t.next(); if (prop.getAttributeValue("prop-type").equals("Mark")) { //$NON-NLS-1$ //$NON-NLS-2$ tw4winMark = prop.getText(); } } } } } catch (Exception e) { ConverterUtils.throwConverterException(Activator.PLUGIN_ID, Messages.getString("taggedrtf.Xliff2TaggedRtf.msg3"), e); } } } }
23,814
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
TaggedRtf2Xliff.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.taggedrtf/src/net/heartsome/cat/converter/taggedrtf/TaggedRtf2Xliff.java
/** * TaggedRtf2Xliff.java * * Version information : * * Date:Jan 14, 2010 * * Copyright notice : */ package net.heartsome.cat.converter.taggedrtf; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Vector; import net.heartsome.cat.converter.Converter; import net.heartsome.cat.converter.ConverterException; import net.heartsome.cat.converter.taggedrtf.resource.Messages; import net.heartsome.cat.converter.util.ConverterUtils; import net.heartsome.cat.converter.util.Progress; import net.heartsome.util.CRC16; import net.heartsome.util.TextUtil; import net.heartsome.xml.Attribute; import net.heartsome.xml.Document; import net.heartsome.xml.Element; import net.heartsome.xml.SAXBuilder; import net.heartsome.xml.XMLOutputter; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.OperationCanceledException; import org.w3c.dom.Node; import org.xml.sax.SAXException; /** * The Class TaggedRtf2Xliff. * @author John Zhu * @version * @since JDK1.6 */ public class TaggedRtf2Xliff implements Converter { /** The Constant TYPE_VALUE. */ public static final String TYPE_VALUE = "x-trtf"; /** The Constant TYPE_NAME_VALUE. */ public static final String TYPE_NAME_VALUE = Messages.getString("taggedrtf.TYPE_NAME_VALUE"); /** The Constant NAME_VALUE. */ public static final String NAME_VALUE = "Tagged RTF to XLIFF Conveter"; // 内部实现所依赖的转换器 /** The dependant converter. */ private Converter dependantConverter; /** * for test to initialize depend on converter. */ public TaggedRtf2Xliff() { dependantConverter = Activator.getRtfConverter(Converter.DIRECTION_POSITIVE); } /** * 运行时把所依赖的转换器,在初始化的时候通过构造函数注入。. * @param converter * the converter */ public TaggedRtf2Xliff(Converter converter) { dependantConverter = converter; } /** * (non-Javadoc) * @see net.heartsome.cat.converter.Converter#convert(java.util.Map, org.eclipse.core.runtime.IProgressMonitor) * @param args * @param monitor * @return * @throws ConverterException */ public Map<String, String> convert(Map<String, String> args, IProgressMonitor monitor) throws ConverterException { TaggedRtf2XliffImpl converter = new TaggedRtf2XliffImpl(); return converter.run(args, monitor); } /** * (non-Javadoc) * @see net.heartsome.cat.converter.Converter#getName() * @return */ public String getName() { return NAME_VALUE; } /** * (non-Javadoc) * @see net.heartsome.cat.converter.Converter#getType() * @return */ public String getType() { return TYPE_VALUE; } /** * (non-Javadoc) * @see net.heartsome.cat.converter.Converter#getTypeName() * @return */ public String getTypeName() { return TYPE_NAME_VALUE; } /** * The Class TaggedRtf2XliffImpl. * @author John Zhu * @version * @since JDK1.6 */ class TaggedRtf2XliffImpl { /** The sdoc. */ private Document sdoc; /** The tdoc. */ private Document tdoc; /** The sroot. */ private Element sroot; /** The troot. */ private Element troot; /** The tbody. */ private Element tbody; /** The match. */ private String match; /** The source start. */ private String sourceStart; /** The source end. */ private String sourceEnd; /** The target start. */ private String targetStart; /** The target end. */ private String targetEnd; /** The lock100. */ private boolean lock100; /** The is suite. */ private boolean isSuite; /** The qt tool id. */ private String qtToolID; /** * Run. * @param params * the params * @param monitor * the monitor * @return the map< string, string> * @throws ConverterException * the converter exception */ public Map<String, String> run(Map<String, String> params, IProgressMonitor monitor) throws ConverterException { monitor = Progress.getMonitor(monitor); params.put(Converter.ATTR_SEG_BY_ELEMENT, Converter.TRUE); params.put(Converter.ATTR_IS_TAGGEDRTF, Converter.TRUE); params.put(Converter.ATTR_FORMAT, TYPE_VALUE); isSuite = false; if (Converter.TRUE.equals(params.get(Converter.ATTR_IS_SUITE))) { isSuite = true; } qtToolID = params.get(Converter.ATTR_QT_TOOLID) != null ? params.get(Converter.ATTR_QT_TOOLID) : Converter.QT_TOOLID_DEFAULT_VALUE; lock100 = Boolean.parseBoolean(params.get(Converter.ATTR_LOCK_100)); Map<String, String> result = null; try { // 把转换过程分为 10 部分:用 RTF 转换器进行转换的部分占 8,此转换器处理剩余的转换部分占 2 monitor.beginTask("", 10); result = dependantConverter.convert(params, Progress.getSubMonitor(monitor, 8)); if (result.get(Converter.ATTR_XLIFF_FILE) == null) { ConverterUtils.throwConverterException(Activator.PLUGIN_ID, Messages.getString("taggedrtf.TaggedRtf2Xliff.msg1")); } // 是否取消操作 if (monitor.isCanceled()) { throw new OperationCanceledException(Messages.getString("taggedrtf.cancel")); } File source = new File(params.get(Converter.ATTR_XLIFF_FILE)); File original = new File(params.get(Converter.ATTR_SKELETON_FILE)); File skeleton = new File(original.getAbsolutePath() + ".tg.skl"); //$NON-NLS-1$ SAXBuilder builder = new SAXBuilder(); sdoc = builder.build(source.getAbsolutePath()); sroot = sdoc.getRootElement(); tdoc = new Document(null, "xliff", sdoc.getPublicId(), sdoc.getSystemId()); //$NON-NLS-1$ troot = tdoc.getRootElement(); copyAttributes(sroot, troot); troot.setAttribute("xmlns:hs", Converter.HSNAMESPACE); //$NON-NLS-1$ Attribute a = troot.getAttribute("xsi:schemaLocation"); //$NON-NLS-1$ if (a == null) { troot.setAttribute("xsi:schemaLocation", Converter.HSSCHEMALOCATION); //$NON-NLS-1$ } else { String attValue = a.getValue(); if (attValue.indexOf(Converter.HSSCHEMALOCATION) == -1) { troot.setAttribute("xsi:schemaLocation", attValue + " " + Converter.HSSCHEMALOCATION); //$NON-NLS-1$ //$NON-NLS-2$ } } Element sfile = sroot.getChild("file"); //$NON-NLS-1$ Element tfile = new Element("file", tdoc); //$NON-NLS-1$ tfile.setAttribute("datatype", TYPE_VALUE); //$NON-NLS-1$ tfile.setAttribute("original", params.get(Converter.ATTR_SOURCE_FILE)); //$NON-NLS-1$ tfile.setAttribute("source-language", params.get(Converter.ATTR_SOURCE_LANGUAGE)); //$NON-NLS-1$ String targetLang = params.get(Converter.ATTR_TARGET_LANGUAGE); if(!"".equals(targetLang)){ tfile.setAttribute("target-language",targetLang); //$NON-NLS-1$ } troot.addContent("\n"); //$NON-NLS-1$ troot.addContent(tfile); Element header = new Element("header", tdoc); //$NON-NLS-1$ Element skl = new Element("skl", tdoc); //$NON-NLS-1$ Element extfile = new Element("external-file", tdoc); //$NON-NLS-1$ extfile.setAttribute("href", TextUtil.cleanString(skeleton.getAbsolutePath())); //$NON-NLS-1$ if (isSuite) { extfile .setAttribute( "crc", "" + CRC16.crc16(TextUtil.cleanString(skeleton.getAbsolutePath()).getBytes("UTF-8"))); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } skl.addContent("\n"); //$NON-NLS-1$ skl.addContent(extfile); skl.addContent("\n"); //$NON-NLS-1$ header.addContent("\n"); //$NON-NLS-1$ header.addContent(skl); Element tool = new Element("tool", tdoc); //$NON-NLS-1$ tool.setAttribute("tool-id", qtToolID); //$NON-NLS-1$ tool.setAttribute("tool-name", "HSStudio"); //$NON-NLS-1$ //$NON-NLS-2$ header.addContent("\n"); //$NON-NLS-1$ header.addContent(tool); tfile.addContent("\n"); //$NON-NLS-1$ tfile.addContent(header); List<Element> properties = sfile.getChild("header").getChildren("hs:prop-group"); //$NON-NLS-1$ //$NON-NLS-2$ Iterator<Element> it = properties.iterator(); while (it.hasNext()) { Element group = it.next(); Element pgroup = new Element(group.getName(), tdoc); pgroup.clone(group, tdoc); header.addContent("\n"); //$NON-NLS-1$ header.addContent(pgroup); } header.addContent("\n"); //$NON-NLS-1$ tbody = new Element("body", tdoc); //$NON-NLS-1$ tfile.addContent("\n"); //$NON-NLS-1$ tfile.addContent(tbody); tfile.addContent("\n"); //$NON-NLS-1$ troot.addContent("\n"); //$NON-NLS-1$ // 对所占比例为 2 的转换任务再进一步细分为 10 个部分:处理翻译单元占 6,写骨架文件占 2,写源文件占 2 IProgressMonitor subMonitor1 = Progress.getSubMonitor(monitor, 2); subMonitor1.beginTask("", 10); subMonitor1.subTask(Messages.getString("taggedrtf.TaggedRtf2Xliff.task2")); List<Element> units = sfile.getChild("body").getChildren("trans-unit"); //$NON-NLS-1$ //$NON-NLS-2$ int size = units.size(); IProgressMonitor subMonitor2 = Progress.getSubMonitor(subMonitor1, 6); subMonitor2.beginTask(Messages.getString("taggedrtf.TaggedRtf2Xliff.task3"), size); subMonitor2.subTask(""); for (int i = 0; i < size; i++) { // 是否取消操作 if (subMonitor2.isCanceled()) { throw new OperationCanceledException(Messages.getString("taggedrtf.cancel")); } parseUnit(units.get(i)); subMonitor2.worked(1); } subMonitor2.done(); tbody.addContent("\n"); //$NON-NLS-1$ subMonitor1.subTask(Messages.getString("taggedrtf.TaggedRtf2Xliff.task4")); XMLOutputter outputter = new XMLOutputter(); FileOutputStream output = new FileOutputStream(skeleton); outputter.preserveSpace(true); outputter.output(sdoc, output); output.close(); output = null; subMonitor1.worked(2); // 是否取消操作 if (subMonitor1.isCanceled()) { throw new OperationCanceledException(Messages.getString("taggedrtf.cancel")); } subMonitor1.subTask(Messages.getString("taggedrtf.TaggedRtf2Xliff.task5")); output = new FileOutputStream(source.getAbsolutePath()); outputter.output(tdoc, output); output.close(); output = null; subMonitor1.worked(2); subMonitor1.done(); } catch (OperationCanceledException e) { throw e; } catch (ConverterException e) { throw e; } catch (Exception e) { if (Converter.DEBUG_MODE) { e.printStackTrace(); } ConverterUtils.throwConverterException(Activator.PLUGIN_ID, Messages.getString("taggedrtf.TaggedRtf2Xliff.msg1"), e); } finally { monitor.done(); } return result; } /** * Parses the unit. * @param unit * the unit * @throws SAXException * the SAX exception * @throws IOException * Signals that an I/O exception has occurred. */ private void parseUnit(Element unit) throws SAXException, IOException { Element src = unit.getChild("source"); //$NON-NLS-1$ String text = src.toString(); Vector<Element> tags = new Vector<Element>(); match = ""; //$NON-NLS-1$ if (find(text, "&lt;0", 0) != -1 && find(text, "0&gt;", 0) != -1) { //$NON-NLS-1$ //$NON-NLS-2$ Element t = new Element("trans-unit", tdoc); //$NON-NLS-1$ copyAttributes(unit, t); t.addContent("\n"); //$NON-NLS-1$ Element source = new Element("source", tdoc); //$NON-NLS-1$ copyAttributes(src, source); t.addContent(source); t.addContent("\n"); //$NON-NLS-1$ Element target = new Element("target", tdoc); //$NON-NLS-1$ t.addContent(target); t.addContent("\n"); //$NON-NLS-1$ sourceStart = ""; //$NON-NLS-1$ sourceEnd = ""; //$NON-NLS-1$ targetStart = ""; //$NON-NLS-1$ targetEnd = ""; //$NON-NLS-1$ if (text.indexOf("0&gt;") == -1) { //$NON-NLS-1$ src = fix(src, "0&gt;"); //$NON-NLS-1$ text = src.toString(); } if (text.indexOf("&lt;0") == -1) { //$NON-NLS-1$ src = fix(src, "&lt;0}"); //$NON-NLS-1$ text = src.toString(); } List<Node> content = compact(src.getContent()); Iterator<Node> i = content.iterator(); // skip initial portion while (i.hasNext()) { Node n = i.next(); if (n.getNodeType() == Node.TEXT_NODE) { String s = n.getNodeValue(); int index = s.indexOf("0>"); //$NON-NLS-1$ if (index != -1) { if (index != 0 && s.charAt(index - 1) != '{') { sourceStart = sourceStart + TextUtil.cleanString(s); continue; } int end = s.indexOf("<}"); //$NON-NLS-1$ if (end == -1) { sourceStart = sourceStart + TextUtil.cleanString(s.substring(0, index + 2)); source.addContent(s.substring(index + 2)); } else { sourceStart = sourceStart + TextUtil.cleanString(s.substring(0, index + 2)); source.addContent(s.substring(index + 2, end)); s.substring(end + 2); index = s.indexOf("{>"); //$NON-NLS-1$ end = s.indexOf("<0}"); //$NON-NLS-1$ if (index != -1) { if (end == -1) { target.addContent(s.substring(index + 2)); } else { target.addContent(s.substring(index + 2, end)); targetEnd = targetEnd + TextUtil.cleanString(s.substring(end)); } } } break; } } else if (n.getNodeType() == Node.ELEMENT_NODE) { Element e = new Element(n); sourceStart = sourceStart + e.toString(); } } // copy text to source while (i.hasNext()) { Node n = i.next(); if (n.getNodeType() == Node.TEXT_NODE) { String s = n.getNodeValue(); int end = s.indexOf("<}"); //$NON-NLS-1$ if (end != -1) { source.addContent(s.substring(0, end)); // skip the match quality value and add the // remainder to // the target s = s.substring(end); int index = s.indexOf("{>"); //$NON-NLS-1$ if (s.startsWith("<}") && s.endsWith("{>")) { //$NON-NLS-1$ //$NON-NLS-2$ match = s; } else if (index != -1) { match = s.substring(0, index + 2); } if ("<}100{>".equals(match) && lock100) { //$NON-NLS-1$ t.setAttribute("translate", "no"); //$NON-NLS-1$ //$NON-NLS-2$ } if (index != -1) { target.addContent(s.substring(index + 2)); } break; } source.addContent(s); } else if (n.getNodeType() == Node.ELEMENT_NODE) { Element e = new Element(n); Element c = new Element(e.getName(), tdoc); c.clone(e, tdoc); source.addContent(c); tags.add(c); } } if (target.getContent().size() == 0) { // target empty, skip tags and match quality while (i.hasNext()) { Node n = i.next(); if (n.getNodeType() == Node.TEXT_NODE) { String s = n.getNodeValue(); int start = s.indexOf("<}"); //$NON-NLS-1$ int end = s.indexOf("{>"); //$NON-NLS-1$ if (start != -1 && end != -1 && end > start) { match = s.substring(start, end + 2); } if (end != -1) { target.addContent(s.substring(end + 2)); break; } } else if (n.getNodeType() == Node.ELEMENT_NODE) { Element e = new Element(n); targetStart = targetStart + e.toString(); } } } // copy text to target while (i.hasNext()) { Node n = i.next(); if (n.getNodeType() == Node.TEXT_NODE) { String s = n.getNodeValue(); int end = s.indexOf("<0}"); //$NON-NLS-1$ if (end != -1) { target.addContent(s.substring(0, end)); targetEnd = targetEnd + TextUtil.cleanString(s.substring(end)); } else { target.addContent(s); } } else if (n.getNodeType() == Node.ELEMENT_NODE) { Element e = new Element(n); for (int h = 0; h < tags.size(); h++) { Element k = tags.get(h); if (e.getText().equals(k.getText())) { e.clone(k, sdoc); } } Element c = new Element(e.getName(), tdoc); c.clone(e, tdoc); target.addContent(c); } } trimTags(source); trimTags(target); int srcTags = countTags(source); int tgtTags = countTags(target); if (srcTags == 0 && tgtTags != 0) { removeTags(target); } if (srcTags == 1 && tgtTags == 1) { equalizeTags(source, target); } if (!match.equals("")) { //$NON-NLS-1$ Element note = new Element("note", tdoc); //$NON-NLS-1$ note.setText(match); t.addContent("\n"); //$NON-NLS-1$ t.addContent(note); t.addContent("\n"); //$NON-NLS-1$ if (match.equals("<}100{>")) { //$NON-NLS-1$ Element altTrans = new Element("alt-trans", tdoc); //$NON-NLS-1$ altTrans.setAttribute("match-quality", "100"); //$NON-NLS-1$ //$NON-NLS-2$ altTrans.setAttribute("tool", "Trados or Similar"); //$NON-NLS-1$ //$NON-NLS-2$ altTrans.setAttribute("xml:space", "default"); //$NON-NLS-1$ //$NON-NLS-2$ altTrans.addContent("\n"); //$NON-NLS-1$ Element s = new Element("source", tdoc); //$NON-NLS-1$ s.clone(source, tdoc); altTrans.addContent(s); altTrans.addContent("\n"); //$NON-NLS-1$ Element tg = new Element("target", tdoc); //$NON-NLS-1$ tg.clone(target, tdoc); altTrans.addContent(tg); t.addContent(altTrans); t.addContent("\n"); //$NON-NLS-1$ } } if (!sourceStart.equals("") || !sourceEnd.equals("") || //$NON-NLS-1$ //$NON-NLS-2$ !targetStart.equals("") || !targetEnd.equals("")) //$NON-NLS-1$ //$NON-NLS-2$ { Element group = new Element("hs:prop-group", tdoc); //$NON-NLS-1$ group.setAttribute("name", "tags"); //$NON-NLS-1$ //$NON-NLS-2$ t.addContent(group); Element prop1 = new Element("hs:prop", tdoc); //$NON-NLS-1$ prop1.setAttribute("prop-type", "sourceStart"); //$NON-NLS-1$ //$NON-NLS-2$ prop1.addContent(sourceStart); group.addContent("\n"); //$NON-NLS-1$ group.addContent(prop1); Element prop2 = new Element("hs:prop", tdoc); //$NON-NLS-1$ prop2.setAttribute("prop-type", "sourceEnd"); //$NON-NLS-1$ //$NON-NLS-2$ prop2.addContent(sourceEnd); group.addContent("\n"); //$NON-NLS-1$ group.addContent(prop2); Element prop3 = new Element("hs:prop", tdoc); //$NON-NLS-1$ prop3.setAttribute("prop-type", "targetStart"); //$NON-NLS-1$ //$NON-NLS-2$ prop3.addContent(targetStart); group.addContent("\n"); //$NON-NLS-1$ group.addContent(prop3); Element prop4 = new Element("hs:prop", tdoc); //$NON-NLS-1$ prop4.setAttribute("prop-type", "targetEnd"); //$NON-NLS-1$ //$NON-NLS-2$ prop4.addContent(targetEnd); group.addContent("\n"); //$NON-NLS-1$ group.addContent(prop4); group.addContent("\n"); //$NON-NLS-1$ } tbody.addContent("\n"); //$NON-NLS-1$ tbody.addContent(t); tbody.addContent("\n"); //$NON-NLS-1$ enumerateTags(source); enumerateTags(target); } else { // this unit doesn't have a translation from Trados unit.setAttribute("datatype", "rtf"); //$NON-NLS-1$ //$NON-NLS-2$ Element c = new Element(unit.getName(), tdoc); c.clone(unit, tdoc); tbody.addContent("\n"); //$NON-NLS-1$ tbody.addContent(c); } } /** * Compact. * @param list * the list * @return the list< node> */ private List<Node> compact(List<Node> list) { List<Node> result = new ArrayList<Node>(); for (int i = 0; i < list.size(); i++) { Node n = list.get(i); if (n.getNodeType() == Node.TEXT_NODE) { while (i + 1 < list.size() && (list.get(i + 1)).getNodeType() == Node.TEXT_NODE) { n.setNodeValue(n.getNodeValue() + (list.get(i + 1)).getNodeValue()); i++; } } result.add(n); } return result; } /** * Equalize tags. * @param source * the source * @param target * the target */ private void equalizeTags(Element source, Element target) { if (source.getChildren().get(0).equals(target.getChildren().get(0))) { return; } target.getChildren().get(0).clone(source.getChildren().get(0), tdoc); } /** * Enumerate tags. * @param e * the e */ private void enumerateTags(Element e) { List<Element> list = e.getChildren("ph"); //$NON-NLS-1$ for (int i = 0; i < list.size(); i++) { Element ph = list.get(i); ph.setAttribute("id", "" + (i + 1)); //$NON-NLS-1$ //$NON-NLS-2$ } } /** * Removes the tags. * @param target * the target */ private void removeTags(Element target) { List<Element> children = target.getChildren(); Iterator<Element> it = children.iterator(); while (it.hasNext()) { target.removeChild(it.next()); } } /** * Count tags. * @param e * the e * @return the int */ private int countTags(Element e) { return e.getChildren().size(); } /** * Fix. * @param src * the src * @param token * the token * @return the element * @throws SAXException * the SAX exception * @throws IOException * Signals that an I/O exception has occurred. */ private Element fix(Element src, String token) throws SAXException, IOException { String text = src.toString(); int index = find(text, token, 0); if (index == -1) { return src; } String first = text.substring(0, index); String last = text.substring(index); while (last.indexOf(token) == -1) { index = last.indexOf("<ph"); //$NON-NLS-1$ int end = last.indexOf("</ph>"); //$NON-NLS-1$ last = last.substring(0, index) + last.substring(end + 5); } ByteArrayInputStream stream = new ByteArrayInputStream((first + last).getBytes("UTF-8")); //$NON-NLS-1$ SAXBuilder b = new SAXBuilder(); Document d = b.build(stream); return d.getRootElement(); } /** * Trim tags. * @param e * the e */ private void trimTags(Element e) { List<Node> original = e.getContent(); List<Node> trimmed = new ArrayList<Node>(); // skip initial tags Iterator<Node> i = original.iterator(); while (i.hasNext()) { Node n = i.next(); if (n.getNodeType() != Node.ELEMENT_NODE && !n.getNodeValue().equals("")) { //$NON-NLS-1$ trimmed.add(n); break; } if (n.getNodeType() == Node.ELEMENT_NODE) { Element h = new Element(n); if (e.getName().equals("source")) { //$NON-NLS-1$ sourceStart = sourceStart + h.toString(); } else { targetStart = targetStart + h.toString(); } } else { if (e.getName().equals("source")) { //$NON-NLS-1$ sourceStart = sourceStart + TextUtil.cleanString(n.getNodeValue()); } else { targetStart = targetStart + TextUtil.cleanString(n.getNodeValue()); } } } while (i.hasNext()) { Node n = i.next(); if (n.getNodeType() == Node.TEXT_NODE && n.getNodeValue().equals("")) { //$NON-NLS-1$ continue; } trimmed.add(n); } while (trimmed.size() > 0) { Node n = trimmed.get(trimmed.size() - 1); if (n.getNodeType() == Node.ELEMENT_NODE) { Element h = new Element(n); if (e.getName().equals("source")) { //$NON-NLS-1$ sourceEnd = h.toString() + sourceEnd; } else { targetEnd = h.toString() + targetEnd; } trimmed.remove(n); } if (n.getNodeType() == Node.TEXT_NODE) { int idx = n.getNodeValue().indexOf("<0}"); //$NON-NLS-1$ if (idx == -1) { break; } if (e.getName().equals("source")) { //$NON-NLS-1$ sourceEnd = n.getNodeValue().substring(idx) + sourceEnd; } else { targetEnd = n.getNodeValue().substring(idx) + targetEnd; } n.setNodeValue(n.getNodeValue().substring(0, idx)); } } e.setContent(trimmed); } /** * Copy attributes. * @param src * the src * @param tgt * the tgt */ private void copyAttributes(Element src, Element tgt) { List<Attribute> attributes = src.getAttributes(); for (int i = 0; i < attributes.size(); i++) { Attribute a = attributes.get(i); tgt.setAttribute(a.getName(), a.getValue()); } attributes = null; } } /** * Find. * @param text * the text * @param token * the token * @param from * the from * @return the int */ public static int find(String text, String token, int from) { int length = text.length(); for (int i = from; i < length; i++) { String remaining = text.substring(i); if (remaining.startsWith("<ph")) { //$NON-NLS-1$ int ends = remaining.indexOf("</ph>"); //$NON-NLS-1$ if (ends != -1) { remaining = remaining.substring(ends + 5); i = i + ends + 5; } } String trimmed = removePh(remaining); if (trimmed.startsWith(token)) { return i; } } return -1; } /** * Removes the ph. * @param string * the string * @return the string */ private static String removePh(String string) { String result = ""; //$NON-NLS-1$ int starts = string.indexOf("<ph"); //$NON-NLS-1$ while (starts != -1) { result = result + string.substring(0, starts); string = string.substring(starts); int ends = string.indexOf("</ph>"); //$NON-NLS-1$ if (ends != -1) { string = string.substring(ends + 5); } starts = string.indexOf("<ph"); //$NON-NLS-1$ } return result + string; } }
26,247
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
Messages.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.taggedrtf/src/net/heartsome/cat/converter/taggedrtf/resource/Messages.java
/** * Messages.java * * Version information : * * Date:Jan 14, 2010 * * Copyright notice : */ package net.heartsome.cat.converter.taggedrtf.resource; import java.util.MissingResourceException; import java.util.ResourceBundle; /** * The Class Messages. * @author John Zhu * @version * @since JDK1.6 */ public final class Messages { /** The Constant BUNDLE_NAME. */ private static final String BUNDLE_NAME = "net.heartsome.cat.converter.taggedrtf.resource.message"; //$NON-NLS-1$ /** The Constant RESOURCE_BUNDLE. */ private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle.getBundle(BUNDLE_NAME); /** * Instantiates a new messages. */ private Messages() { // Do nothing } /** * Gets the string. * @param key * the key * @return the string */ public static String getString(String key) { try { return RESOURCE_BUNDLE.getString(key); } catch (MissingResourceException e) { return '!' + key + '!'; } } }
1,029
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z
Messages.java
/FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.ui.rcp/src/net/heartsome/cat/converter/ui/rcp/resource/Messages.java
package net.heartsome.cat.converter.ui.rcp.resource; import java.util.MissingResourceException; import java.util.ResourceBundle; /** * 国际化工具类 * @author peason * @version * @since JDK1.6 */ public final class Messages { /** The Constant BUNDLE_NAME. */ private static final String BUNDLE_NAME = "net.heartsome.cat.converter.ui.rcp.resource.message"; //$NON-NLS-1$ /** The Constant RESOURCE_BUNDLE. */ private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle.getBundle(BUNDLE_NAME); /** * Instantiates a new messages. */ private Messages() { // Do nothing } /** * Gets the string. * @param key * the key * @return the string */ public static String getString(String key) { try { return RESOURCE_BUNDLE.getString(key); } catch (MissingResourceException e) { return '!' + key + '!'; } } }
913
Java
.java
heartsome/translationstudio8
83
45
18
2014-06-03T17:56:15Z
2020-10-13T06:46:15Z