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 |
---|---|---|---|---|---|---|---|---|---|---|---|
Xliff2OpenOffice.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.openoffice/src/net/heartsome/cat/converter/openoffice/Xliff2OpenOffice.java | /**
* Xliff2OpenOffice.java
*
* Version information :
*
* Date:Jan 14, 2010
*
* Copyright notice :
*/
package net.heartsome.cat.converter.openoffice;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
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.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;
import net.heartsome.cat.converter.Converter;
import net.heartsome.cat.converter.ConverterException;
import net.heartsome.cat.converter.openoffice.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.util.StringConverter;
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.runtime.IProgressMonitor;
import org.eclipse.core.runtime.OperationCanceledException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* The Class Xliff2OpenOffice.
* @author John Zhu
* @version
* @since JDK1.6
*/
public class Xliff2OpenOffice implements Converter {
private static final Logger LOGGER = LoggerFactory.getLogger(Xliff2OpenOffice.class);
/** The Constant TYPE_VALUE. */
public static final String TYPE_VALUE = "x-openoffice";
/** The Constant TYPE_NAME_VALUE. */
public static final String TYPE_NAME_VALUE = Messages.getString("openoffice.TYPE_NAME_VALUE");
/** The Constant NAME_VALUE. */
public static final String NAME_VALUE = "XLIFF to OpenOffice Conveter";
// 内部实现所依赖的转换器
/** The dependant converter. */
private Converter dependantConverter;
/**
* for test to initialize depend on converter.
*/
public Xliff2OpenOffice() {
dependantConverter = Activator.getXMLConverter(Converter.DIRECTION_REVERSE);
}
/**
* 运行时把所依赖的转换器,在初始化的时候通过构造函数注入。.
* @param converter
* the converter
*/
public Xliff2OpenOffice(Converter converter) {
dependantConverter = converter;
}
/**
* (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;
}
/**
* (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 {
Xliff2OpenOfficeImpl converter = new Xliff2OpenOfficeImpl();
return converter.run(args, monitor);
}
/**
* The Class Xliff2OpenOfficeImpl.
* @author John Zhu
* @version
* @since JDK1.6
*/
class Xliff2OpenOfficeImpl {
/** The files table. */
private Hashtable<String, String> filesTable;
/** The is embedded. */
private boolean isEmbedded = false;
/** The catalogue. */
private String catalogue;
private boolean isInfoEnabled = LOGGER.isInfoEnabled();
/**
* Builds the doc.
* @param filename
* the filename
* @return the document
* @throws Exception
* the exception
*/
public Document buildDoc(String filename) throws Exception {
SAXBuilder builder = new SAXBuilder();
builder.setEntityResolver(new Catalogue(catalogue));
Document doc = builder.build(filename);
return doc;
}
/**
* Creates the empty doc.
* @param filename
* the filename
* @return the document
* @throws Exception
* the exception
*/
public Document createEmptyDoc(String filename) throws Exception {
File file = new File(filename);
FileOutputStream fos = new FileOutputStream(file);
OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF-8"); //$NON-NLS-1$
BufferedWriter bw = new BufferedWriter(osw);
bw.write("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n"); //$NON-NLS-1$
bw.write("<xliff version=\"1.2\" xmlns=\"urn:oasis:names:tc:xliff:document:1.2\" \n" //$NON-NLS-1$
+ "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" \n" //$NON-NLS-1$
+ "xmlns:hs=\"" + Converter.HSNAMESPACE + "\" \n" //$NON-NLS-1$ //$NON-NLS-2$
+ "xsi:schemaLocation=\"urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd \n" //$NON-NLS-1$
+ Converter.HSSCHEMALOCATION + "\">\n"); //$NON-NLS-1$
bw.write("</xliff>\n"); //$NON-NLS-1$
bw.flush();
bw.close();
osw.close();
fos.close();
bw = null;
osw = null;
fos = null;
return buildDoc(filename);
}
/**
* Save file.
* @param element
* the element
* @throws Exception
* the exception
*/
private void saveFile(Element element) throws Exception {
File xliff = File.createTempFile("tmp", ".xlf"); //$NON-NLS-1$ //$NON-NLS-2$
Document doc = createEmptyDoc(xliff.getAbsolutePath());
Element root = doc.getRootElement();
root.setAttribute("version", "1.2"); //$NON-NLS-1$ //$NON-NLS-2$
Element file = new Element("file", doc); //$NON-NLS-1$
file.clone(element, doc);
root.addContent(file);
List<Element> groups = file.getChild("header").getChildren("hs:prop-group"); //$NON-NLS-1$ //$NON-NLS-2$
Iterator<Element> i = groups.iterator();
while (i.hasNext()) {
Element group = i.next();
if (group.getAttributeValue("name").equals("document")) { //$NON-NLS-1$ //$NON-NLS-2$
filesTable.put(group.getChild("hs:prop").getText(), xliff.getAbsolutePath()); //$NON-NLS-1$
}
}
if (file.getChild("header").getChild("skl").getChild("external-file") == null) { //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
// embedded skeleton
file.getChild("header").getChild("skl").addContent(new Element("external-file", doc)); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
isEmbedded = true;
}
file
.getChild("header").getChild("skl").getChild("external-file").setAttribute("href", xliff.getAbsolutePath() + ".skl"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
XMLOutputter outputter = new XMLOutputter();
FileOutputStream output = new FileOutputStream(xliff.getAbsolutePath());
outputter.output(doc, output);
output.close();
outputter = null;
}
/**
* 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>();
String xliffFile = args.get(Converter.ATTR_XLIFF_FILE);
String outputFile = args.get(Converter.ATTR_TARGET_FILE);
catalogue = args.get(Converter.ATTR_CATALOGUE);
filesTable = new Hashtable<String, String>();
try {
// 把转换过程分为三部分共 20 个任务,其中分离出各个 xliff 文件占 8,分离出 skeleton 文件占 2,生成目标文件占 10。
monitor.beginTask("", 20);
infoLogger.logConversionFileInfo(catalogue, null, xliffFile, null);
IProgressMonitor separateMonitor = Progress.getSubMonitor(monitor, 8);
long startTime = 0;
try {
if (isInfoEnabled) {
startTime = System.currentTimeMillis();
LOGGER.info(Messages.getString("openoffice.Xliff2OpenOffice.logger1"), startTime);
}
SAXBuilder builder = new SAXBuilder();
Document doc = builder.build(xliffFile);
Element root = doc.getRootElement();
List<Element> files = root.getChildren("file"); //$NON-NLS-1$
separateMonitor.beginTask(Messages.getString("openoffice.Xliff2OpenOffice.task2"), files.size());
separateMonitor.subTask("");
Iterator<Element> it = files.iterator();
while (it.hasNext()) {
saveFile(it.next());
// 是否取消操作
if (separateMonitor.isCanceled()) {
throw new OperationCanceledException(Messages.getString("openoffice.cancel"));
}
separateMonitor.worked(1);
}
} finally {
separateMonitor.done();
}
long endTime = 0;
if (isInfoEnabled) {
endTime = System.currentTimeMillis();
LOGGER.info(Messages.getString("openoffice.Xliff2OpenOffice.logger2"), endTime);
LOGGER.info(Messages.getString("openoffice.Xliff2OpenOffice.logger3"), endTime - startTime);
}
monitor.subTask(Messages.getString("openoffice.Xliff2OpenOffice.task3"));
if (isInfoEnabled) {
startTime = System.currentTimeMillis();
LOGGER.info(Messages.getString("openoffice.Xliff2OpenOffice.logger4"), startTime);
}
String skeleton = args.get(Converter.ATTR_SKELETON_FILE);
if (isEmbedded) {
File t = File.createTempFile("tmp", ".skl"); //$NON-NLS-1$ //$NON-NLS-2$
StringConverter.decodeFile(skeleton, t.getAbsolutePath());
skeleton = t.getAbsolutePath();
}
if (isInfoEnabled) {
endTime = System.currentTimeMillis();
LOGGER.info(Messages.getString("openoffice.Xliff2OpenOffice.logger5"), endTime);
LOGGER.info(Messages.getString("openoffice.Xliff2OpenOffice.logger6"), endTime - startTime);
}
monitor.worked(2);
IProgressMonitor conversionMonitor = Progress.getSubMonitor(monitor, 10);
try {
ZipFile zipFile = new ZipFile(skeleton);
int totalTask = zipFile.size();
conversionMonitor.beginTask("", totalTask);
if (isInfoEnabled) {
startTime = System.currentTimeMillis();
LOGGER.info(Messages.getString("openoffice.Xliff2OpenOffice.logger7"), startTime);
}
ZipInputStream in = new ZipInputStream(new FileInputStream(skeleton));
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(outputFile));
ZipEntry entry = null;
String messagePattern = Messages.getString("openoffice.Xliff2OpenOffice.msg1");
while ((entry = in.getNextEntry()) != null) {
// 标识是否委派其它转换器进行了处理
boolean isDelegate = false;
// 是否取消
if (conversionMonitor.isCanceled()) {
throw new OperationCanceledException(Messages.getString("openoffice.cancel"));
}
String message = MessageFormat.format(messagePattern, new Object[] { entry.getName() });
conversionMonitor.subTask(message);
if (entry.getName().matches(".*\\.[xX][mM][lL]\\.skl")) { //$NON-NLS-1$
String name = entry.getName().substring(0, entry.getName().lastIndexOf(".skl")); //$NON-NLS-1$
File tmp = new File(filesTable.get(name) + ".skl"); //$NON-NLS-1$
FileOutputStream output = new FileOutputStream(tmp.getAbsolutePath());
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
output.write(buf, 0, len);
}
output.close();
Hashtable<String, String> table = new Hashtable<String, String>();
table.put(Converter.ATTR_XLIFF_FILE, filesTable.get(name));
table.put(Converter.ATTR_TARGET_FILE, filesTable.get(name) + ".xml");
table.put(Converter.ATTR_CATALOGUE, catalogue);
table.put(Converter.ATTR_SKELETON_FILE, filesTable.get(name) + ".skl");
Map<String, String> res = dependantConverter.convert(table, Progress.getSubMonitor(
separateMonitor, 1));
isDelegate = true;
if (res.get(Converter.ATTR_TARGET_FILE) == null) {
ConverterUtils.throwConverterException(Activator.PLUGIN_ID,
Messages.getString("openoffice.Xliff2OpenOffice.msg2"));
}
ZipEntry content = new ZipEntry(name);
content.setMethod(ZipEntry.DEFLATED);
out.putNextEntry(content);
FileInputStream input = new FileInputStream(filesTable.get(name) + ".xml"); //$NON-NLS-1$
while ((len = input.read(buf)) > 0) {
out.write(buf, 0, len);
}
out.closeEntry();
input.close();
tmp.delete();
File xml = new File(filesTable.get(name) + ".xml"); //$NON-NLS-1$
xml.delete();
File xlf = new File(filesTable.get(name));
xlf.delete();
} else {
File tmp = File.createTempFile("entry", ".tmp"); //$NON-NLS-1$ //$NON-NLS-2$
FileOutputStream output = new FileOutputStream(tmp.getAbsolutePath());
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
output.write(buf, 0, len);
}
output.close();
ZipEntry content = new ZipEntry(entry.getName());
content.setMethod(ZipEntry.DEFLATED);
out.putNextEntry(content);
FileInputStream input = new FileInputStream(tmp.getAbsolutePath());
while ((len = input.read(buf)) > 0) {
out.write(buf, 0, len);
}
out.closeEntry();
input.close();
tmp.delete();
}
if (!isDelegate) {
conversionMonitor.worked(1);
}
}
out.close();
} finally {
conversionMonitor.done();
}
if (isInfoEnabled) {
endTime = System.currentTimeMillis();
LOGGER.info(Messages.getString("openoffice.Xliff2OpenOffice.logger8"), endTime);
LOGGER.info(Messages.getString("openoffice.Xliff2OpenOffice.logger9"), endTime - startTime);
}
if (isEmbedded) {
File f = new File(skeleton);
f.delete();
}
result.put(Converter.ATTR_TARGET_FILE, outputFile);
} 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("openoffice.Xliff2OpenOffice.msg2"), e);
} finally {
monitor.done();
}
infoLogger.endConversion();
return result;
}
}
}
| 14,542 | 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.openoffice/src/net/heartsome/cat/converter/openoffice/resource/Messages.java | /**
* Messages.java
*
* Version information :
*
* Date:Jan 14, 2010
*
* Copyright notice :
*/
package net.heartsome.cat.converter.openoffice.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.openoffice.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 + '!';
}
}
}
| 966 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
Rc2XliffTest.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.rc/testSrc/net/heartsome/cat/converter/rc/test/Rc2XliffTest.java | package net.heartsome.cat.converter.rc.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.rc.Rc2Xliff;
import org.junit.Before;
import org.junit.Test;
public class Rc2XliffTest {
public static Rc2Xliff converter = new Rc2Xliff();
private static String srcFile = "rc/Test.rc";
private static String xlfFile = "rc/Test.rc.xlf";
private static String sklFile = "rc/Test.rc.skl";
@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
public void testConvert() throws ConverterException {
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$
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());
}
}
| 1,508 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
Xliff2RcTest.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.rc/testSrc/net/heartsome/cat/converter/rc/test/Xliff2RcTest.java | package net.heartsome.cat.converter.rc.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.rc.Xliff2Rc;
import org.junit.Before;
import org.junit.Test;
public class Xliff2RcTest {
public static Xliff2Rc converter = new Xliff2Rc();
private static String tgtFile = "rc/Test_zh-CN.rc";
private static String xlfFile = "rc/Test.rc.xlf";
private static String sklFile = "rc/Test.rc.skl";
@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_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());
}
}
| 1,500 | 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.rc/src/net/heartsome/cat/converter/rc/Activator.java | /**
* Activator.java
*
* Version information :
*
* Date:Jan 14, 2010
*
* Copyright notice :
*/
package net.heartsome.cat.converter.rc;
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 plug-in ID
/** The Constant PLUGIN_ID. */
public static final String PLUGIN_ID = "net.heartsome.cat.converter.rc";
// The shared instance
/** The plugin. */
private static Activator plugin;
/** The rc2 xliff sr. */
private ServiceRegistration rc2XliffSR;
/** The xliff2 rc sr. */
private ServiceRegistration xliff2RcSR;
/**
* 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 converter services
Converter rc2Xliff = new Rc2Xliff();
Properties properties = new Properties();
properties.put(Converter.ATTR_NAME, Rc2Xliff.NAME_VALUE);
properties.put(Converter.ATTR_TYPE, Rc2Xliff.TYPE_VALUE);
properties.put(Converter.ATTR_TYPE_NAME, Rc2Xliff.TYPE_NAME_VALUE);
rc2XliffSR = ConverterRegister.registerPositiveConverter(context, rc2Xliff, properties);
Converter xliff2Rc = new Xliff2Rc();
properties = new Properties();
properties.put(Converter.ATTR_NAME, Xliff2Rc.NAME_VALUE);
properties.put(Converter.ATTR_TYPE, Xliff2Rc.TYPE_VALUE);
properties.put(Converter.ATTR_TYPE_NAME, Xliff2Rc.TYPE_NAME_VALUE);
xliff2RcSR = ConverterRegister.registerReverseConverter(context, xliff2Rc, 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 (rc2XliffSR != null) {
rc2XliffSR.unregister();
}
if (xliff2RcSR != null) {
xliff2RcSR.unregister();
}
plugin = null;
}
/**
* Returns the shared instance.
* @return the shared instance
*/
public static Activator getDefault() {
return plugin;
}
}
| 2,477 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
Rc2Xliff.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.rc/src/net/heartsome/cat/converter/rc/Rc2Xliff.java | /**
* Rc2Xliff.java
*
* Version information :
*
* Date:Jan 14, 2010
*
* Copyright notice :
*/
package net.heartsome.cat.converter.rc;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
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.rc.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 Rc2Xliff.
* @author John Zhu
*/
public class Rc2Xliff implements Converter {
/** The Constant TYPE_VALUE. */
public static final String TYPE_VALUE = "winres";
/** The Constant TYPE_NAME_VALUE. */
public static final String TYPE_NAME_VALUE = Messages.getString("rc.TYPE_NAME_VALUE");
/** The Constant NAME_VALUE. */
public static final String NAME_VALUE = "RC 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 {
Rc2XliffImpl converter = new Rc2XliffImpl();
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 Rc2XliffImpl.
* @author John Zhu
* @version
* @since JDK1.6
*/
class Rc2XliffImpl {
/** The input. */
private FileInputStream input;
/** The output. */
private FileOutputStream output;
/** The skeleton. */
private FileOutputStream skeleton;
/** The buffer. */
private InputStreamReader buffer;
/** The input file. */
private String inputFile;
/** The xliff file. */
private String xliffFile;
/** The skeleton file. */
private String skeletonFile;
/** The last word. */
private String lastWord = ""; //$NON-NLS-1$
/** The source language. */
private String sourceLanguage;
private String targetLanguage;
/** The seg id. */
private int segId;
/** The stack. */
private String stack;
/** The block stack. */
private int blockStack;
/**
* 源文件编码
*/
private String srcEncoding;
/**
* 计算当前转换的进度
*/
private CalculateProcessedBytes cpb;
/**
* 转换进度监视器
*/
private IProgressMonitor monitor;
/**
* 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 {
this.monitor = Progress.getMonitor(monitor);
Map<String, String> result = new HashMap<String, String>();
segId = 0;
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);
boolean isSuite = false;
if (Converter.TRUE.equalsIgnoreCase(params.get(Converter.ATTR_IS_SUITE))) {
isSuite = true;
}
String qtToolID = params.get(Converter.ATTR_QT_TOOLID) != null ? params.get(Converter.ATTR_QT_TOOLID)
: Converter.QT_TOOLID_DEFAULT_VALUE;
try {
/*
* 此转换器的实现逻辑比较复杂,且存在各方法相互调用的情况,故在逻辑中添加进度计算的代码比较困难。考虑到转换过程中,要么把源文件的可翻译单元写入到 xliff 文件中,要么把源文件中的不可翻译单元写入到
* skeleton 文件中,所以可以根据源文件的大小,以及当前已经写 xliff 和 skeleton 文件的大小,算出当前的转换进度。
*/
cpb = ConverterUtils.getCalculateProcessedBytes(inputFile);
this.monitor.beginTask(Messages.getString("rc.Rc2Xliff.task1"), cpb.getTotalTask());
this.monitor.subTask("");
input = new FileInputStream(inputFile);
buffer = new InputStreamReader(input, srcEncoding);
output = new FileOutputStream(xliffFile);
stack = ""; //$NON-NLS-1$
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=\"" + 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\" >" //$NON-NLS-1$
+ srcEncoding + "</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);
parseRC();
skeleton.close();
writeString("</body>\n"); //$NON-NLS-1$
writeString("</file>\n"); //$NON-NLS-1$
writeString("</xliff>"); //$NON-NLS-1$
buffer.close();
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("rc.Rc2Xliff.msg1"), e);
} finally {
this.monitor.done();
}
return result;
}
/**
* 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$
// 计算转换进度
caculateProcessed(string);
}
/**
* Write skeleton.
* @param character
* the character
* @throws IOException
* Signals that an I/O exception has occurred.
*/
private void writeSkeleton(char character) throws IOException {
writeSkeleton(String.valueOf(character));
}
/**
* Write segment.
* @param segment
* the segment
* @throws IOException
* Signals that an I/O exception has occurred.
*/
private void writeSegment(String segment) throws IOException {
// add sentence segmentation
if (segment.equals("")) {
return;
} //$NON-NLS-1$
writeString(" <trans-unit id=\"" + segId //$NON-NLS-1$
+ "\" xml:space=\"preserve\">\n" + " <source xml:lang=\"" //$NON-NLS-1$ //$NON-NLS-2$
+ sourceLanguage + "\">" + TextUtil.cleanString(segment) + "</source>\n" //$NON-NLS-1$ //$NON-NLS-2$
+ " </trans-unit>\n"); //$NON-NLS-1$
writeSkeleton("%%%" + segId++ + "%%%"); //$NON-NLS-1$ //$NON-NLS-2$
// 计算转换进度
caculateProcessed(segment);
}
/**
* 计算转换进度
* @param str
* 要写入 xliff 或 skeleton 的源文件中的字符串 ;
*/
private void caculateProcessed(String str) {
// 是否取消操作
if (this.monitor.isCanceled()) {
throw new OperationCanceledException(Messages.getString("rc.cancel"));
}
int workedTask = 0;
try {
workedTask = cpb.calculateProcessed(str.getBytes(srcEncoding).length);
} catch (UnsupportedEncodingException e) {
// ignore the exception
e.printStackTrace();
}
if (workedTask > 0) {
this.monitor.worked(workedTask);
}
}
/**
* Parses the rc.
* @throws IOException
* Signals that an I/O exception has occurred.
*/
private void parseRC() throws IOException {
char character;
while (buffer.ready()) {
character = (char) buffer.read();
if (character == '#') { // directives
parseDirective();
} else if (character == '/') { // comments
// comment /* or //
parseComment(); // Keep the state
} else if (!blankChar(character)) {
parseStatement(character);
} else {
writeSkeleton(character);
}
}
}
/**
* Parses the comment.
* @throws IOException
* Signals that an I/O exception has occurred.
*/
private void parseComment() throws IOException {
writeSkeleton("/"); //Last character read //$NON-NLS-1$
boolean bLargeComment;
char prevChar = ' ';
char character;
if (buffer.ready()) {
character = (char) buffer.read();
writeSkeleton(character);
bLargeComment = character == '*'; // Large comment /* */
// Add the comment to the skeleton
while (buffer.ready()) {
character = (char) buffer.read();
writeSkeleton(character);
if (bLargeComment && prevChar == '*' && character == '/') {
break;
} else if (!bLargeComment && (character == '\n' || character == '\r')) {
break;
}
prevChar = character;
}
}
}
/**
* Parses the statement.
* @param initial
* the initial
* @throws IOException
* Signals that an I/O exception has occurred.
*/
private void parseStatement(char initial) throws IOException {
String statement = String.valueOf(initial);
writeSkeleton(initial);
statement = statement.concat(parseWords(" ,\n\r\t", true, false)); //$NON-NLS-1$
if (statement.trim().equals("STRINGTABLE")) { //$NON-NLS-1$
parseStringTable();
} else if (statement.trim().equals("DIALOG") || statement.trim().equals("DIALOGEX")) { //$NON-NLS-1$ //$NON-NLS-2$
parseDialog();
} else if (statement.trim().equals("MENU") || statement.trim().equals("MENUEX")) { //$NON-NLS-1$ //$NON-NLS-2$
parseMenu();
} else if (statement.trim().equals("POPUP")) { //$NON-NLS-1$
parsePopup();
} else if (statement.trim().equals("DLGINIT")) { //$NON-NLS-1$
parseDlgInit();
} else if (beginBlock(statement.trim())) { // BEGIN
blockStack = 0;
parseBlock();
}
}
/**
* Parses the directive.
* @throws IOException
* Signals that an I/O exception has occurred.
*/
private void parseDirective() throws IOException {
char character = ' ';
writeSkeleton('#');
String statement = parseWords(" \t", true, false); //$NON-NLS-1$
if (statement.trim().equals("define")) { //$NON-NLS-1$
parseDefine();
} else {
while (buffer.ready() && character != '\r' && character != '\n') {
character = (char) buffer.read();
writeSkeleton(character);
}
}
}
/**
* Parses the define.
* @throws IOException
* Signals that an I/O exception has occurred.
*/
private void parseDefine() throws IOException {
String word = ""; //$NON-NLS-1$
while (buffer.ready()) {
stack = ""; //$NON-NLS-1$
word = parseWords(" \n\t\r,\"L", false, true); //$NON-NLS-1$
if (word.trim().equals("\"")) { //$NON-NLS-1$
captureString(true);
} else { // is END or ID
writeSkeleton(stack);
if (word.equals("\r") || word.equals("\n")) { //$NON-NLS-1$ //$NON-NLS-2$
break;
}
}
}
}
/**
* Parses the block.
* @throws IOException
* Signals that an I/O exception has occurred.
*/
private void parseBlock() throws IOException {
blockStack++;
String statement = ""; //$NON-NLS-1$
while (blockStack != 0 && buffer.ready()) {
statement = parseWords(" \n\t\r", true, false); //$NON-NLS-1$
if (beginBlock(statement.trim())) {
blockStack++;
} else if (endBlock(statement.trim())) {
blockStack--;
}
}
}
/**
* Parses the dialog.
* @throws IOException
* Signals that an I/O exception has occurred.
*/
private void parseDialog() throws IOException {
parseDialogContent();
parseControlBlock();
}
/**
* Parses the dialog content.
* @throws IOException
* Signals that an I/O exception has occurred.
*/
private void parseDialogContent() throws IOException {
String word = " "; //$NON-NLS-1$
while (!beginBlock(word)) {
word = parseWords(" \n\t\r(),", true, false); //$NON-NLS-1$
if (word.trim().equals("CAPTION")) { //$NON-NLS-1$
captureString(false);
}
}
}
/**
* Parses the control block.
* @throws IOException
* Signals that an I/O exception has occurred.
*/
private void parseControlBlock() throws IOException {
boolean isEnd = false;
parseWords(" (),\r\n\t", true, false); //$NON-NLS-1$
do {
lastWord = lastWord.trim();
if (lastWord.equals("CONTROL") || lastWord.equals("LTEXT") || lastWord.equals("CTEXT") || lastWord.equals("RTEXT") || lastWord.equals("AUTO3STATE") || //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
lastWord.equals("AUTOCHECKBOX") || lastWord.equals("AUTORADIOBUTTON") || lastWord.equals("CHECKBOX") || lastWord.equals("PUSHBOX") || //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
lastWord.equals("PUSHBUTTON") || lastWord.equals("DEFPUSHBUTTON") || lastWord.equals("RADIOBUTTON") || lastWord.equals("STATE3") || //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
lastWord.equals("USERBUTTON") || lastWord.equals("GROUPBOX")) { //$NON-NLS-1$ //$NON-NLS-2$
isEnd = parseControlTypeI();
} else if (lastWord.equals("EDITTEXT") || lastWord.equals("BEDIT") || lastWord.equals("IEDIT") || lastWord.equals("HEDIT") || //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
lastWord.equals("COMBOBOX") || lastWord.equals("LISTBOX") || lastWord.equals("SCROLLBAR") || lastWord.equals("ICON")) { //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
isEnd = parseControlTypeI();
} else {
parseWords(" (),\r\t\n", true, false); //$NON-NLS-1$
}
if (isEnd) { // End of block in last control
break;
}
} while (true);
}
// return true if it has a block in the control
/**
* Parses the control type i.
* @return true, if successful
* @throws IOException
* Signals that an I/O exception has occurred.
*/
private boolean parseControlTypeI() throws IOException {
char cIni = ' ';
while (blankChar(cIni) && buffer.ready()) {
cIni = (char) buffer.read();
if (cIni != '"' && cIni != 'L') {
writeSkeleton(cIni);
}
}
// first parameter optional string
if (cIni == '"') {
captureString(true);
} else {
if (cIni == 'L') { // String type L"String"
writeSkeleton(cIni);
cIni = (char) buffer.read();
if (cIni == '"') {
captureString(true);
} else { // don't have string
writeSkeleton(cIni);
}
}
}
String word = " "; //$NON-NLS-1$
boolean hasBlock = false;
while (!isEndControlStatement(word)) {
word = parseWords(" \t(),\r\n", true, false).trim(); //$NON-NLS-1$
if (beginBlock(word)) { // begin an optional data block in the
// control
hasBlock = true;
}
}
return !hasBlock && endBlock(word); // end of control block?
}
/**
* Write conditional.
* @param character
* the character
* @param write
* the write
* @throws IOException
* Signals that an I/O exception has occurred.
*/
private void writeConditional(char character, boolean write) throws IOException {
if (write) {
writeSkeleton(character);
} else {
stack += String.valueOf(character);
}
}
/**
* Parses the comment.
* @param write
* the write
* @param large
* the large
* @throws IOException
* Signals that an I/O exception has occurred.
*/
private void parseComment(boolean write, boolean large) throws IOException {
writeConditional('/', write); // Last character read
if (large) {
writeConditional('*', write);
} else {
writeConditional('/', write);
}
char prevChar = ' ';
char character;
// Add the comment to the skeleton
while (buffer.ready()) {
character = (char) buffer.read();
writeConditional(character, write);
if (large && prevChar == '*' && character == '/') {
break;
} else if (!large && (character == '\n' || character == '\r')) {
break;
}
prevChar = character;
}
}
/**
* Parses the words.
* @param separators
* the separators
* @param write
* the write
* @param withSeparator
* the with separator
* @return the string
* @throws IOException
* Signals that an I/O exception has occurred.
*/
private String parseWords(String separators, boolean write, boolean withSeparator) throws IOException {
String word = ""; //$NON-NLS-1$
char lastChar;
char character = 'a'; // initial value any character not in
// separators
while (buffer.ready() && separators.indexOf(character) == -1) {
lastChar = character;
character = (char) buffer.read();
if (character == '/') {
lastChar = character;
character = (char) buffer.read();
if (character == '/') {
parseComment(write, false);
break;
} else if (character == '*') { // skip comments
parseComment(write, true);
break;
} else { // write the last two characters
if (write) {
writeSkeleton(lastChar);
writeSkeleton(character);
} else {
stack += String.valueOf(lastChar);
stack += String.valueOf(character);
}
word = word.concat(String.valueOf(lastChar));
if (separators.indexOf(character) == -1 || withSeparator) { // return with the separator
// or not
word = word.concat(String.valueOf(character));
}
}
} else if (character == '\\') {
lastChar = character;
character = (char) buffer.read();
if (character != '\r' || character != '\n') {
if (write) { // must write and \character
writeSkeleton(lastChar);
writeSkeleton(character);
while (blankChar(character) && character != ' ') {
lastChar = character;
character = (char) buffer.read();
writeSkeleton(character);
}
word = word.concat(String.valueOf(character));
} else { // not write and \ character
stack += String.valueOf(lastChar);
stack += String.valueOf(character);
while (blankChar(character)) {
lastChar = character;
character = (char) buffer.read();
stack += String.valueOf(character);
}
word = word.concat(String.valueOf(character));
}
} else {
if (write) {
writeSkeleton(lastChar);
writeSkeleton(character);
} else {
stack += String.valueOf(lastChar);
stack += String.valueOf(character);
}
word = word.concat(String.valueOf(lastChar));
if (separators.indexOf(character) == -1 || withSeparator) { // return with the separator
// or not
word = word.concat(String.valueOf(character));
}
}
} else { // not is a special character (comment or \)
if (write) {
writeSkeleton(character);
} else {
stack += String.valueOf(character);
}
if (separators.indexOf(character) == -1 || withSeparator) { // return
// with
// the
// separator
// or
// not
word = word.concat(String.valueOf(character));
}
}
}
lastWord = word;
return word;
}
/**
* Capture string.
* @param startNow
* the start now
* @throws IOException
* Signals that an I/O exception has occurred.
*/
private void captureString(boolean startNow) throws IOException {
int quotes = 0;
if (startNow) {
quotes = 1; // now in the string
}
char character = ' ';
char lastChar;
String word = ""; //$NON-NLS-1$
while (buffer.ready() && quotes < 2) {
lastChar = character;
character = (char) buffer.read();
if (quotes == 0) { // not in the string yet
if (character == '"') { // begining of string
quotes++;
} else { // not in the string yet
writeSkeleton(character);
}
} else { // is in the string
if (character == '"') { // end of string Careful can be the
// \" escape character
if (word.equals("")) { //$NON-NLS-1$
writeSkeleton('"');
writeSkeleton('"');
} else { // string is empty string
writeSegment(word);
}
quotes++;
} else { // midle of string
if (character == '\\') { // if is escape character
lastChar = character;
character = (char) buffer.read();
if (character == '\n' || character == '\r') {
while (blankChar(character) && character != ' ') {
lastChar = character;
character = (char) buffer.read();
}
if (character == '"') { // if end of string in
// first character of
// the next line
if (word.equals("")) { //$NON-NLS-1$
writeSkeleton('"');
writeSkeleton('"');
} else { // string is empty string
writeSegment(word);
}
} else { // normal character in the line below \
word = word.concat(String.valueOf(character));
}
} else { // Normal escape character
word = word.concat(String.valueOf(lastChar));
word = word.concat(String.valueOf(character));
}
} else { // Normal character
word = word.concat(String.valueOf(character));
}
}
}
}
}
/**
* Parses the string table.
* @throws IOException
* Signals that an I/O exception has occurred.
*/
private void parseStringTable() throws IOException {
String word = " "; //$NON-NLS-1$
while (!beginBlock(word)) {
word = parseWords(" \n\t\r,", true, false); //$NON-NLS-1$
}
while (!endBlock(word)) {
stack = ""; //$NON-NLS-1$
word = parseWords(" \n\t\r,\"L", false, true); //$NON-NLS-1$
if (word.trim().equals("\"")) { //$NON-NLS-1$
captureString(true);
} else { // is END or ID
writeSkeleton(stack);
}
}
}
/**
* Parses the menu.
* @throws IOException
* Signals that an I/O exception has occurred.
*/
private void parseMenu() throws IOException {
String word = " "; //$NON-NLS-1$
while (!beginBlock(word)) {
word = parseWords(" \n\t\r,", true, false); //$NON-NLS-1$
}
parseMenuBlock();
}
/**
* Parses the menu block.
* @throws IOException
* Signals that an I/O exception has occurred.
*/
private void parseMenuBlock() throws IOException {
String word = " "; //$NON-NLS-1$
while (!endBlock(word)) {
word = parseWords(" ,\n\t\r\"", false, true); //$NON-NLS-1$
if (word.trim().equals("MENUITEM")) { //$NON-NLS-1$
writeSkeleton(stack);
stack = ""; //$NON-NLS-1$
word = parseWords(" ,\n\t\r\"L", false, true); //$NON-NLS-1$
if (word.trim().equals("\"")) { //$NON-NLS-1$
stack = ""; //$NON-NLS-1$
captureString(true);
} else { // SEPARATOR
writeSkeleton(stack);
stack = ""; //$NON-NLS-1$
}
} else if (word.trim().equals("POPUP")) { //$NON-NLS-1$
writeSkeleton(stack);
stack = ""; //$NON-NLS-1$
parsePopup();
} else if (word.trim().equals("\"")) { //$NON-NLS-1$
stack = ""; //$NON-NLS-1$
captureString(true);
} else {
writeSkeleton(stack);
stack = ""; //$NON-NLS-1$
}
}
}
/**
* Parses the popup.
* @throws IOException
* Signals that an I/O exception has occurred.
*/
private void parsePopup() throws IOException {
String word = " "; //$NON-NLS-1$
while (!beginBlock(word)) {
stack = ""; //$NON-NLS-1$
word = parseWords(" \n\t\r,\"L", false, true); //$NON-NLS-1$
if (word.trim().equals("\"")) { //$NON-NLS-1$
captureString(true);
} else { // is END or ID
writeSkeleton(stack);
}
}
stack = ""; //$NON-NLS-1$
parseMenuBlock();
}
/**
* Parses the dlg init.
* @throws IOException
* Signals that an I/O exception has occurred.
*/
private void parseDlgInit() throws IOException {
String word = ""; //$NON-NLS-1$
while (buffer.ready() && !beginBlock(word)) {
word = parseWords(" \n\t\r,", true, false); //$NON-NLS-1$
}
parseDlgInitBlock();
}
/**
* Parses the dlg init block.
* @throws IOException
* Signals that an I/O exception has occurred.
*/
private void parseDlgInitBlock() throws IOException {
String word = ""; //$NON-NLS-1$
int position = 0; // parse position in the dlginitblock
int dataLength = 0;
stack = ""; //$NON-NLS-1$
while (buffer.ready() && !endBlock(word)) {
word = parseWords(" \n\t\r,", false, false).trim(); //$NON-NLS-1$
if (!word.equals("")) { //$NON-NLS-1$
if (word.equals("0") && position == 0) { //$NON-NLS-1$
break;
}
switch (position) {
case 0: // id
dataLength = 0;
position++;
break;
case 1: // type
if (word.equals("0x403") || word.equals("0x1234")) { //$NON-NLS-1$ //$NON-NLS-2$
position++;
} else {
position = 6;
}
writeSkeleton(stack);
stack = ""; //$NON-NLS-1$
break;
case 2: // length
if (validateNumber(word)) {
dataLength = Integer.parseInt(word); // *****Controlar
// si no es
// un n�mero
position++;
} else {
position = 6;
}
break;
case 3: // end of align 0
position++;
break;
case 4: // first time data
if (word.charAt(0) == '\"') { // case "/000"
position = 0;
writeSkeleton(stack);
stack = ""; //$NON-NLS-1$
break;
}
stack = ""; //$NON-NLS-1$
writeSkeleton("###" + segId + "###,0 \r\n"); //$NON-NLS-1$ //$NON-NLS-2$
position++; // go to the next case now without break
case 5: // midle of data
extractString(word, dataLength);
position = 0;
stack = ""; //$NON-NLS-1$
break;
case 6: // not string
writeSkeleton(stack);
stack = ""; //$NON-NLS-1$
break;
default:
break;
}
}
}
writeSkeleton(stack);
stack = ""; //$NON-NLS-1$
}
/**
* Extract string.
* @param ini
* the ini
* @param dataLength
* the data length
* @throws IOException
* Signals that an I/O exception has occurred.
*/
private void extractString(String ini, int dataLength) throws IOException {
byte[] array = new byte[dataLength];
String word = ""; //$NON-NLS-1$
int i = 1;
int length = 0;
Integer tmpNum = Integer.decode(ini);
array[length++] = (byte) tmpNum.intValue();
array[length++] = (byte) (tmpNum.intValue() >> 8);
tmpNum = null;
while (i < dataLength / 2 && buffer.ready()) {
word = parseWords(",\"", false, false).trim(); //$NON-NLS-1$
if (word.charAt(1) == 'x' && word.length() > 3) {
tmpNum = Integer.decode(word);
array[length++] = (byte) tmpNum.intValue();
array[length++] = (byte) (tmpNum.intValue() >> 8);
tmpNum = null;
}
i++;
}
if (dataLength % 2 > 0) {
while (!word.equals("\"000\"")) { //$NON-NLS-1$
word = parseWords(",\n\t\r ", false, false); //$NON-NLS-1$
}
}
writeSegment(new String(array, "UTF-8")); //$NON-NLS-1$
}
}
/**
* Validate number.
* @param num
* the num
* @return true, if successful
*/
private static boolean validateNumber(String num) {
try {
Integer.parseInt(num);
return true;
} catch (Exception e) {
return false;
}
}
/**
* Checks if is end control statement.
* @param word
* the word
* @return true, if is end control statement
*/
private static boolean isEndControlStatement(String word) {
// list of all posible controls and END keyword
String[] controls = new String[] { "END", "CONTROL", "LTEXT", "CTEXT", "RTEXT", "AUTO3STATE", "AUTOCHECKBOX", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$
"AUTORADIOBUTTON", "CHECKBOX", "PUSHBOX", "PUSHBUTTON", "DEFPUSHBUTTON", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
"RADIOBUTTON", "STATE3", "USERBUTTON", "GROUPBOX", "EDITTEXT", "BEDIT", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$
"IEDIT", "HEDIT", "COMBOBOX", "LISTBOX", "SCROLLBAR", "ICON" }; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$
for (int i = 0; i < controls.length; i++) {
if (controls[i].equals(word)) {
return true;
}
}
return false;
}
/**
* Blank char.
* @param c
* the c
* @return true, if successful
*/
private static boolean blankChar(char c) {
return c == ' ' || c == '\n' || c == '\t' || c == '\r';
}
/**
* Begin block.
* @param word
* the word
* @return true, if successful
*/
private static boolean beginBlock(String word) {
return word.trim().equals("BEGIN") || word.trim().equals("{"); //$NON-NLS-1$ //$NON-NLS-2$
}
/**
* End block.
* @param word
* the word
* @return true, if successful
*/
private static boolean endBlock(String word) {
return word.trim().equals("END") || word.trim().equals("}"); //$NON-NLS-1$ //$NON-NLS-2$
}
}
| 32,681 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
Xliff2Rc.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.rc/src/net/heartsome/cat/converter/rc/Xliff2Rc.java | /**
* Xliff2Rc.java
*
* Version information :
*
* Date:Jan 14, 2010
*
* Copyright notice :
*/
package net.heartsome.cat.converter.rc;
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.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.xml.parsers.ParserConfigurationException;
import net.heartsome.cat.converter.Converter;
import net.heartsome.cat.converter.ConverterException;
import net.heartsome.cat.converter.rc.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.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xml.sax.SAXException;
/**
* The Class Xliff2Rc.
* @author John Zhu
*/
public class Xliff2Rc implements Converter {
private static final Logger LOGGER = LoggerFactory.getLogger(Xliff2Rc.class);
/** The Constant TYPE_VALUE. */
public static final String TYPE_VALUE = "winres";
/** The Constant TYPE_NAME_VALUE. */
public static final String TYPE_NAME_VALUE = Messages.getString("rc.TYPE_NAME_VALUE");
/** The Constant NAME_VALUE. */
public static final String NAME_VALUE = "XLIFF to RC 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 {
Xliff2RcImpl converter = new Xliff2RcImpl();
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 Xliff2RcImpl.
* @author John Zhu
* @version
* @since JDK1.6
*/
class Xliff2RcImpl {
// 骨架文件的字符编码
private static final String UTF_8 = "UTF-8";
/** The input. */
private InputStreamReader input;
/** The buffer. */
private BufferedReader buffer;
/** The skl file. */
private String sklFile;
/** The xliff file. */
private String xliffFile;
/** The line. */
private String line;
/** The segments. */
private Hashtable<String, Element> segments;
/** The output. */
private FileOutputStream output;
/** The catalogue. */
private String catalogue;
/** The dlg text. */
private Hashtable<String, Object> dlgText;
/** The dest temp. */
private String destTemp;
/** The encoding. */
private String encoding;
/** The output file. */
private String outputFile;
private boolean isInfoEnabled = LOGGER.isInfoEnabled();
/**
* 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>();
dlgText = new Hashtable<String, Object>();
sklFile = params.get(Converter.ATTR_SKELETON_FILE);
xliffFile = params.get(Converter.ATTR_XLIFF_FILE);
catalogue = params.get(Converter.ATTR_CATALOGUE);
encoding = params.get(Converter.ATTR_SOURCE_ENCODING);
String attrIsPreviewMode = params.get(Converter.ATTR_IS_PREVIEW_MODE);
/* 是否为预览翻译模式 */
boolean isPreviewMode = attrIsPreviewMode != null && attrIsPreviewMode.equals(Converter.TRUE);
try {
// 把转换过程分为四个部分共 7 个任务,其中加载 xliff 文件占 1,处理 dlgInitExists 占 2,替换过程占 2,处理 dlgInitLengths 占 2。
monitor.beginTask("", 7);
infoLogger.logConversionFileInfo(catalogue, null, xliffFile, sklFile);
monitor.subTask(Messages.getString("rc.Xliff2Rc.task2"));
infoLogger.startLoadingXliffFile();
File tempFile = File.createTempFile("tempRC", ".temp"); //$NON-NLS-1$ //$NON-NLS-2$
destTemp = tempFile.getAbsolutePath();
output = new FileOutputStream(destTemp);
loadSegments();
infoLogger.endLoadingXliffFile();
monitor.worked(1);
// 是否取消操作
if (monitor.isCanceled()) {
throw new OperationCanceledException(Messages.getString("rc.cancel"));
}
monitor.subTask(Messages.getString("rc.Xliff2Rc.task3"));
long startTime = 0;
if (isInfoEnabled) {
startTime = System.currentTimeMillis();
LOGGER.info(Messages.getString("rc.Xliff2Rc.logger1"), startTime);
}
dlgInitExists(params);
long endTime = 0;
if (isInfoEnabled) {
endTime = System.currentTimeMillis();
LOGGER.info(Messages.getString("rc.Xliff2Rc.logger2"), endTime);
LOGGER.info(Messages.getString("rc.Xliff2Rc.logger3"), endTime - startTime);
}
monitor.worked(2);
IProgressMonitor replaceMonitor = Progress.getSubMonitor(monitor, 2);
try {
// 是否取消操作
if (replaceMonitor.isCanceled()) {
throw new OperationCanceledException(Messages.getString("rc.cancel"));
}
infoLogger.startReplacingSegmentSymbol();
CalculateProcessedBytes cpb = ConverterUtils.getCalculateProcessedBytes(sklFile);
replaceMonitor.beginTask(Messages.getString("rc.Xliff2Rc.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("rc.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 = target.getText();
if (isPreviewMode || !"".equals(tgtStr.trim())) { //$NON-NLS-1$
writeString(converDlgInit(tgtStr, code));
} else {
// process source
writeString(converDlgInit(source.getText(), code));
}
} else {
// process source
writeString(converDlgInit(source.getText(), code));
}
} else {
ConverterUtils.throwConverterException(Activator.PLUGIN_ID, MessageFormat.format(
Messages.getString("rc.Xliff2Rc.msg1"), code));
}
index = line.indexOf("%%%"); //$NON-NLS-1$
if (index == -1) {
writeString(line);
}
} // end while
} else {
writeString(line);
}
line = buffer.readLine();
}
infoLogger.endReplacingSegmentSymbol();
} finally {
replaceMonitor.done();
}
output.close();
buffer.close();
monitor.subTask(Messages.getString("rc.Xliff2Rc.task5"));
if (isInfoEnabled) {
startTime = System.currentTimeMillis();
LOGGER.info(Messages.getString("rc.Xliff2Rc.logger4"), startTime);
}
dlgInitLengths(params);
if (isInfoEnabled) {
endTime = System.currentTimeMillis();
LOGGER.info(Messages.getString("rc.Xliff2Rc.logger5"), endTime);
LOGGER.info(Messages.getString("rc.Xliff2Rc.logger6"), endTime - startTime);
}
monitor.worked(2);
tempFile.delete();
result.put(Converter.ATTR_TARGET_FILE, outputFile);
} catch (OperationCanceledException e) {
throw e;
} catch (Exception e) {
if (Converter.DEBUG_MODE) {
e.printStackTrace();
}
ConverterUtils.throwConverterException(Activator.PLUGIN_ID, Messages.getString("rc.Xliff2Rc.msg2"), e);
} finally {
monitor.done();
}
infoLogger.endConversion();
return result;
}
/**
* Conver dlg init.
* @param word
* the word
* @param code
* the code
* @return the string
* @throws Exception
* the exception
*/
private String converDlgInit(String word, String code) throws Exception {
if (dlgText.containsKey(code)) {
return decode(word, code);
}
return new String("\"" + word + "\""); //$NON-NLS-1$ //$NON-NLS-2$
}
/**
* Decode.
* @param word
* the word
* @param code
* the code
* @return the string
* @throws Exception
* the exception
*/
private String decode(String word, String code) throws Exception {
dlgText.remove(code);
byte[] utf16Bytes = word.getBytes("UTF-8"); //$NON-NLS-1$
String byteWord = ""; //$NON-NLS-1$
Byte par = new Byte("00"); //$NON-NLS-1$
int length = utf16Bytes.length;
for (int i = 0; i < length; i = i + 1) {
if (i % 2 == 0) {
par = new Byte(utf16Bytes[i]);
} else {
Byte impar = new Byte(utf16Bytes[i]);
byteWord = byteWord
+ " 0x" + Integer.toHexString(impar.intValue()) + Integer.toHexString(par.intValue()) + ", "; //$NON-NLS-1$ //$NON-NLS-2$
}
}
if (utf16Bytes.length % 2 == 0) {
byteWord = byteWord + "\"\\000\" "; //$NON-NLS-1$
} else {
if (length > 0) {
byteWord = byteWord + " 0x00" + Integer.toHexString(par.intValue()) + ", "; //$NON-NLS-1$ //$NON-NLS-2$
}
byteWord = byteWord + " "; //$NON-NLS-1$
}
length++;
dlgText.put(code, "" + length);
return byteWord;
}
/**
* Load segments.
* @throws SAXException
* the SAX exception
* @throws IOException
* Signals that an I/O exception has occurred.
* @throws ParserConfigurationException
* the parser configuration exception
*/
private void loadSegments() throws SAXException, IOException, ParserConfigurationException {
SAXBuilder builder = new SAXBuilder();
builder.setEntityResolver(new Catalogue(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 encoded.
* @param string
* the string
* @throws IOException
* Signals that an I/O exception has occurred.
*/
private void writeStringEncoded(String string) throws IOException {
output.write(string.getBytes(encoding));
}
/**
* 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$
}
/**
* Dlg init exists.
* @param params
* the params
* @throws Exception
* the exception
*/
private void dlgInitExists(Map<String, String> params) throws Exception {
input = new InputStreamReader(new FileInputStream(sklFile), "UTF-8"); //$NON-NLS-1$
buffer = new BufferedReader(input);
line = buffer.readLine();
while (line != null) {
if (line.indexOf("###") != -1) { //$NON-NLS-1$
// contains dlginit length
int index = line.indexOf("###"); //$NON-NLS-1$
while (index != -1) {
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) {
dlgText.put(code, new Integer(0));
} else {
ConverterUtils.throwConverterException(Activator.PLUGIN_ID, MessageFormat.format(
Messages.getString("rc.Xliff2Rc.msg1"), code));
}
index = line.indexOf("###"); //$NON-NLS-1$
} // end while
}
line = buffer.readLine();
}
}
/**
* Dlg init lengths.
* @param params
* the params
* @throws IOException
* Signals that an I/O exception has occurred.
*/
private void dlgInitLengths(Map<String, String> params) throws IOException {
outputFile = params.get(Converter.ATTR_TARGET_FILE);
output = new FileOutputStream(outputFile);
input = new InputStreamReader(new FileInputStream(destTemp), "UTF-8"); //$NON-NLS-1$
buffer = new BufferedReader(input);
line = buffer.readLine();
while (line != null) {
line = line + "\n"; //$NON-NLS-1$
if (line.indexOf("###") != -1) { //$NON-NLS-1$
// contains dlginit length
int index = line.indexOf("###"); //$NON-NLS-1$
while (index != -1) {
String start = line.substring(0, index);
writeStringEncoded(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$
writeStringEncoded((String) dlgText.get(code));
index = line.indexOf("###"); //$NON-NLS-1$
if (index == -1) {
writeStringEncoded(line);
}
} // end while
} else {
writeStringEncoded(line);
}
line = buffer.readLine();
}
output.close();
}
}
} | 15,464 | 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.rc/src/net/heartsome/cat/converter/rc/resource/Messages.java | /**
* Messages.java
*
* Version information :
*
* Date:Jan 14, 2010
*
* Copyright notice :
*/
package net.heartsome.cat.converter.rc.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.rc.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,016 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
Xliff2JavaScriptTest.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.javascript/testSrc/net/heartsome/cat/converter/javascript/test/Xliff2JavaScriptTest.java | package net.heartsome.cat.converter.javascript.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.javascript.Xliff2JavaScript;
import org.junit.Before;
import org.junit.Test;
public class Xliff2JavaScriptTest {
public static Xliff2JavaScript converter = new Xliff2JavaScript();
private static String tgtFile = "rc/Test_zh-CN.js";
private static String xlfFile = "rc/Test.js.xlf";
private static String sklFile = "rc/Test.js.skl";
@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_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,500 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
JavaScript2XliffTest.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.javascript/testSrc/net/heartsome/cat/converter/javascript/test/JavaScript2XliffTest.java | package net.heartsome.cat.converter.javascript.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.javascript.JavaScript2Xliff;
import org.junit.Before;
import org.junit.Test;
public class JavaScript2XliffTest {
public static JavaScript2Xliff converter = new JavaScript2Xliff();
private static String srcFile = "rc/Test.js";
private static String xlfFile = "rc/Test.js.xlf";
private static String sklFile = "rc/Test.js.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
public void testConvert() throws ConverterException {
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$
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());
}
}
| 1,556 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
Jscript2xliffImplTestTest.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.javascript/testSrc/net/heartsome/cat/converter/javascript/test/Jscript2xliffImplTestTest.java | package net.heartsome.cat.converter.javascript.test;
import java.util.Hashtable;
import java.util.Vector;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
public class Jscript2xliffImplTestTest {
Hashtable<String, String> params;
@Before
public void setUp() throws Exception {
params = new Hashtable<String, String>();
params.put("srcLang", "en");
params.put("skeleton", "test");
params.put("srcEncoding", "utf-8");
}
// 单行注释前不存在有效代码
@Test
public void testRunWithSingleComment_1() {
params.put("source", "//alert(\"Error Handled\")");
Vector<String> result = Jscript2xliffImplTest.run(params);
Assert.assertEquals(0, Long.parseLong(result.firstElement()));
}
// 单行注释前存在有效代码
@Test
public void testRunWithSingleComment_2() {
params.put("source",
"alert(\"Error Handled\") //alert(\"Error Handled\")");
Vector<String> result = Jscript2xliffImplTest.run(params);
Assert.assertEquals(1, Long.parseLong(result.firstElement()));
}
// 单行注释前存在可翻译的单行注释符
@Test
public void testRunWithSingleComment_3() {
params.put("source",
"alert(\"Error // Handled\"); //alert(\"Error Handled\")");
Vector<String> result = Jscript2xliffImplTest.run(params);
Assert.assertEquals(1, Long.parseLong(result.firstElement()));
}
// 单行注释和多行注释字符在同一行
@Test
public void testRunWithSingleComment_4() {
params.put("source",
"alert(\"Error // Handled\"); //*/alert(\"Error Handled\")");
Vector<String> result = Jscript2xliffImplTest.run(params);
Assert.assertEquals(1, Long.parseLong(result.firstElement()));
}
// 多行注释前和后不存在有效代码
@Test
public void testRunWithMultiRowComment_1() {
params.put("source", "/*\nalert(\"Error Handled\")\n*/");
Vector<String> result = Jscript2xliffImplTest.run(params);
Assert.assertEquals(0, Long.parseLong(result.firstElement()));
}
// 多行注释前和后存在有效代码
@Test
public void testRunWithMultiRowComment_2() {
params
.put(
"source",
"alert(\"Error Handled\");/*\nalert(\"Error Handled\");\n*/alert(\"Error Handled\")");
Vector<String> result = Jscript2xliffImplTest.run(params);
Assert.assertEquals(2, Long.parseLong(result.firstElement()));
}
// 多行注释前的有效代码存在注释字符
@Test
public void testRunWithMultiRowComment_3() {
params
.put(
"source",
"alert(\"Error // /* */Handled\");/*\nalert(\"Error Handled\")\n*/alert(\"Error Handled\")");
Vector<String> result = Jscript2xliffImplTest.run(params);
Assert.assertEquals(2, Long.parseLong(result.firstElement()));
}
// 多行注释和单行注释在同一行,且多行注释在前
@Test
public void testRunWithMultiRowComment_4() {
params
.put(
"source",
"alert(\"Error Handled\"); /* Error Handled */ alert(\"Error Handled\"); //alert(\"Error Handled\")");
Vector<String> result = Jscript2xliffImplTest.run(params);
Assert.assertEquals(2, Long.parseLong(result.firstElement()));
}
// 多行注释中嵌套了多行注释的开始符
@Test
public void testRunWithMultiRowComment_5() {
params.put("source",
"alert(\"Error Handled\"); /* Error Handled // /* */");
Vector<String> result = Jscript2xliffImplTest.run(params);
Assert.assertEquals(1, Long.parseLong(result.firstElement()));
}
// 多行注释开始符后紧接反斜杠,混淆多行注释的开始和结束
@Test
public void testRunWithMultiRowComment_6() {
params.put("source",
"alert(\"Error Handled\"); /*/ Error Handled // /* */");
Vector<String> result = Jscript2xliffImplTest.run(params);
Assert.assertEquals(1, Long.parseLong(result.firstElement()));
}
// 多行注释没有结束符
@Test
public void testRunWithMultiRowComment_7_WithoutClosed() {
params.put("source",
"alert(\"Error Handled\"); /*/ Error Handled // /* ");
Vector<String> result = Jscript2xliffImplTest.run(params);
Assert.assertEquals(1, Long.parseLong(result.firstElement()));
}
// “纯”双引号
@Test
public void testRunWithQuote_1() {
params.put("source", "alert(\"Error Handled\");");
Vector<String> result = Jscript2xliffImplTest.run(params);
Assert.assertEquals(1, Long.parseLong(result.firstElement()));
}
// “纯”单引号
@Test
public void testRunWithQuote_2() {
params.put("source", "alert('Error Handled');");
Vector<String> result = Jscript2xliffImplTest.run(params);
Assert.assertEquals(1, Long.parseLong(result.firstElement()));
}
// 双引号中嵌单引号
@Test
public void testRunWithQuote_3() {
params.put("source", "alert(\"Error 'abc' Handled\");");
Vector<String> result = Jscript2xliffImplTest.run(params);
Assert.assertEquals(1, Long.parseLong(result.firstElement()));
}
// 单引号中嵌双引号
@Test
public void testRunWithQuote_4() {
params.put("source", "alert('Error \"abc\" Handled')");
Vector<String> result = Jscript2xliffImplTest.run(params);
Assert.assertEquals(1, Long.parseLong(result.firstElement()));
}
// 双引号中嵌转义的双引号
@Test
public void testRunWithQuote_5() {
params.put("source", "alert(\"Error \\\"abc\\\" Handled\");");
Vector<String> result = Jscript2xliffImplTest.run(params);
Assert.assertEquals(1, Long.parseLong(result.firstElement()));
}
// 单引号中嵌转义的单引号
@Test
public void testRunWithQuote_6() {
params.put("source", "alert('Error \\\'abc\\\' Handled')");
Vector<String> result = Jscript2xliffImplTest.run(params);
Assert.assertEquals(1, Long.parseLong(result.firstElement()));
}
// 双引号中嵌单引号及转义的双引号
@Test
public void testRunWithQuote_7() {
params.put("source", "alert(\"Error 'abc' \\\"abc\\\" Handled\");");
Vector<String> result = Jscript2xliffImplTest.run(params);
Assert.assertEquals(1, Long.parseLong(result.firstElement()));
}
// 双引号中嵌单引号,且双引号之前存在被转义的单引号
@Test
public void testRunWithQuote_8() {
params.put("source", "ale\\'test\\'rt(\"Error 'abc' Handled\");");
Vector<String> result = Jscript2xliffImplTest.run(params);
Assert.assertEquals(1, Long.parseLong(result.firstElement()));
}
// 单引号中嵌入转义的单引号和双引号
@Test
public void testRunWithQuote_9() {
params.put("source", "alert('Error \"abc\" \\\'abc\\\' Handled')");
Vector<String> result = Jscript2xliffImplTest.run(params);
Assert.assertEquals(1, Long.parseLong(result.firstElement()));
}
// 双引号中包含转义的反斜杠
@Test
public void testRunWithQuote_10() {
params.put("source", "alert(\"\\\\\")");
Vector<String> result = Jscript2xliffImplTest.run(params);
Assert.assertEquals(1, Long.parseLong(result.firstElement()));
}
// 单引号中包含转义的反斜杠
@Test
public void testRunWithQuote_11() {
params.put("source", "alert('\\\\')");
Vector<String> result = Jscript2xliffImplTest.run(params);
Assert.assertEquals(1, Long.parseLong(result.firstElement()));
}
// 单引号中结束
@Test
public void testRunWithQuote_12() {
params.put("source", "var type='abc'");
Vector<String> result = Jscript2xliffImplTest.run(params);
Assert.assertEquals(1, Long.parseLong(result.firstElement()));
}
// 无引号
@Test
public void testRunWithoutQuote() {
params.put("source", "alert()");
Vector<String> result = Jscript2xliffImplTest.run(params);
Assert.assertEquals(0, Long.parseLong(result.firstElement()));
}
// 引号内的字符串跨行
@Test
public void testRunWithNewline() {
params.put("source", "alert('Error \\\nHandled') //sdfldsjsdklj");
Vector<String> result = Jscript2xliffImplTest.run(params);
Assert.assertEquals(1, Long.parseLong(result.firstElement()));
}
// 引号内的字符串跨行但没有"\"标识
@Test
public void testRunWithNewlineWithoutClosed() {
params.put("source", "alert('Error \nHandled') //sdfldsjsdklj");
Vector<String> result = Jscript2xliffImplTest.run(params);
Assert.assertEquals(0, Long.parseLong(result.firstElement()));
}
// 避免错误的字符串导致死循环的情况
@Test
public void testRunWithBadString_1() {
params.put("source", "\\\'quote 'test' ok?");
Vector<String> result = Jscript2xliffImplTest.run(params);
Assert.assertEquals(1, Long.parseLong(result.firstElement()));
}
// 测试人员在测试时发现的问题
@Test
public void testRunWithBadString_2() {
params
.put(
"source",
"addPreprocessHandler( 'designMode != \"On\"', 'designMode != \"on\"', true, function(t){indexOf.call=call;return indexOf.call(t.text, 'kevinroth.com')>-1;} );");
Vector<String> result = Jscript2xliffImplTest.run(params);
Assert.assertEquals(3, Long.parseLong(result.firstElement()));
}
// 测试人员在测试时发现的问题:正则表达式中存有奇数个引号的情况
@Test
public void testRunWithBadString_3() {
params.put("source",
"e.element.text.match(/minorVersion\\s*:\\s*'(0|X)/)");
Vector<String> result = Jscript2xliffImplTest.run(params);
Assert.assertEquals(0, Long.parseLong(result.firstElement()));
}
// 测试人员在测试时发现的问题:正则表达式中存有注释字符,如 //
@Test
public void testRunWithBadString_4() {
params.put("source", "actionSubstring.replace(/\\//g,'%252F');");
Vector<String> result = Jscript2xliffImplTest.run(params);
Assert.assertEquals(1, Long.parseLong(result.firstElement()));
}
// 测试人员在测试时发现的问题:区分正斜杠为正则表达式的开始和除号
@Test
public void testRunWithSlash_1() {
params.put("source", "var type=100/10");
Vector<String> result = Jscript2xliffImplTest.run(params);
Assert.assertEquals(0, Long.parseLong(result.firstElement()));
}
// 测试人员在测试时发现的问题:区分正斜杠为正则表达式的开始和除号
@Test
public void testRunWithSlash_2() {
params
.put(
"source",
"var type=100 /*tes\nt*/\n/10;/*multi comment*/var type2=20\n/2;\nalert(type)\nvar type=/a'[\\\n/]\\\n/\nalert(type+'abc')");
Vector<String> result = Jscript2xliffImplTest.run(params);
Assert.assertEquals(1, Long.parseLong(result.firstElement()));
}
}
| 10,252 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
Jscript2xliffImplTest.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.javascript/testSrc/net/heartsome/cat/converter/javascript/test/Jscript2xliffImplTest.java | package net.heartsome.cat.converter.javascript.test;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.StringReader;
import java.util.Hashtable;
import java.util.Map;
import java.util.Vector;
import net.heartsome.cat.converter.javascript.Jscript2xliffAbstract;
public class Jscript2xliffImplTest extends Jscript2xliffAbstract {
public Jscript2xliffImplTest(Map<String, String> params) {
inputFile = params.get("source"); //$NON-NLS-1$
sourceLanguage = params.get("srcLang"); //$NON-NLS-1$
skeletonFile = params.get("skeleton"); //$NON-NLS-1$
// fixed a bug 1293 by john.
encoding = params.get("srcEncoding"); //$NON-NLS-1$
input = new StringReader(inputFile);
buffer = new BufferedReader(input);
output = new ByteArrayOutputStream();
skeleton = new ByteArrayOutputStream();
}
public static Vector<String> run(Hashtable<String, String> params) {
System.out.println("##############################################");
Vector<String> result = new Vector<String>();
Jscript2xliffAbstract js2Xliff = new Jscript2xliffImplTest(params);
try {
js2Xliff.run(null);
} catch (Exception e) {
System.out.println("??????????????????????????????????????????");
System.out.println("error:转换文件失败。");
System.out.println("??????????????????????????????????????????");
e.printStackTrace();
}
System.out.println("-----------------------------------------------");
System.out.println(js2Xliff.output.toString());
System.out.println("-----------------------------------------------");
System.out.println(js2Xliff.skeleton.toString());
System.out.println("-----------------------------------------------");
result.add(String.valueOf(js2Xliff.segId));
System.out.println("##############################################");
return result;
}
}
| 1,834 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
Xliff2JavaScript.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.javascript/src/net/heartsome/cat/converter/javascript/Xliff2JavaScript.java | /**
* Xliff2JavaScript.java
*
* Version information :
*
* Date:Jan 14, 2010
*
* Copyright notice :
*/
package net.heartsome.cat.converter.javascript;
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 javax.xml.parsers.ParserConfigurationException;
import net.heartsome.cat.converter.Converter;
import net.heartsome.cat.converter.ConverterException;
import net.heartsome.cat.converter.javascript.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.xml.sax.SAXException;
/**
* The Class Xliff2JavaScript.
* @author John Zhu
* @version
* @since JDK1.6
*/
public class Xliff2JavaScript implements Converter {
/** The Constant TYPE_VALUE. */
public static final String TYPE_VALUE = "javascript";
/** The Constant TYPE_NAME_VALUE. */
public static final String TYPE_NAME_VALUE = Messages.getString("javascript.TYPE_NAME_VALUE");
/** The Constant NAME_VALUE. */
public static final String NAME_VALUE = "XLIFF to JavaScript 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 {
Xliff2JavaScriptImpl converter = new Xliff2JavaScriptImpl();
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 Xliff2JavaScriptImpl.
* @author John Zhu
* @version
* @since JDK1.6
*/
class Xliff2JavaScriptImpl {
private static final String UTF_8 = "UTF-8";
/** The input. */
private InputStreamReader input;
/** The buffer. */
private BufferedReader buffer;
/** The skl file. */
private String sklFile;
/** The xliff file. */
private String xliffFile;
/** The line. */
private String line;
/** The segments. */
private Hashtable<String, Element> segments;
/** The output. */
private FileOutputStream output;
/** The catalogue. */
private String catalogue;
// 计算替换进度的对象
private CalculateProcessedBytes cpb;
// 替换过程的进度监视器
private IProgressMonitor replaceMonitor;
// skeleton 文件编码
private String encoding;
/**
* 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);
catalogue = params.get(Converter.ATTR_CATALOGUE);
String outputFile = params.get(Converter.ATTR_TARGET_FILE);
encoding = params.get(Converter.ATTR_SOURCE_ENCODING);
String attrIsPreviewMode = params.get(Converter.ATTR_IS_PREVIEW_MODE);
/* 是否为预览翻译模式 */
boolean isPreviewMode = attrIsPreviewMode != null && attrIsPreviewMode.equals(Converter.TRUE);
try {
infoLogger.logConversionFileInfo(catalogue, null, xliffFile, sklFile);
// 把转换过程分为二大部分其 10 个任务,其中加载 xliff 文件占 4,替换过程占 6。
monitor.beginTask("", 10);
monitor.subTask(Messages.getString("javascript.Xliff2JavaScript.task2"));
infoLogger.startLoadingXliffFile();
output = new FileOutputStream(outputFile);
loadSegments();
infoLogger.endLoadingXliffFile();
monitor.worked(4);
// 是否取消操作
if (monitor.isCanceled()) {
throw new OperationCanceledException(Messages.getString("javascript.cancel"));
}
try {
infoLogger.startReplacingSegmentSymbol();
cpb = ConverterUtils.getCalculateProcessedBytes(sklFile);
replaceMonitor = Progress.getSubMonitor(monitor, 6);
replaceMonitor.beginTask(Messages.getString("javascript.Xliff2JavaScript.task3"), 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) {
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) {
// 替换字符
String replaceCode = code;
Element target = segment.getChild("target"); //$NON-NLS-1$
Element source = segment.getChild("source"); //$NON-NLS-1$
if (target != null) {
String tgtStr = target.getText();
if (isPreviewMode || !"".equals(tgtStr.trim())) {
writeString(tgtStr, true, replaceCode);
} else {
writeString(source.getText(), true, replaceCode);
}
} else {
writeString(source.getText(), true, replaceCode);
}
} else {
ConverterUtils.throwConverterException(Activator.PLUGIN_ID,
MessageFormat.format(Messages.getString("javascript.Xliff2JavaScript.msg1"), code));
}
index = line.indexOf("%%%"); //$NON-NLS-1$
if (index == -1) {
writeString(line);
}
} // end while
} else {
//
// non translatable portion
//
writeString(line);
}
line = buffer.readLine();
}
infoLogger.endReplacingSegmentSymbol();
} finally {
replaceMonitor.done();
}
output.close();
result.put(Converter.ATTR_TARGET_FILE, outputFile);
infoLogger.endConversion();
} catch (OperationCanceledException e) {
throw e;
} catch (Exception e) {
if (Converter.DEBUG_MODE) {
e.printStackTrace();
}
ConverterUtils.throwConverterException(Activator.PLUGIN_ID, Messages.getString("javascript.Xliff2JavaScript.msg2"), e);
} finally {
monitor.done();
}
return result;
}
/**
* Load segments.
* @throws SAXException
* the SAX exception
* @throws IOException
* Signals that an I/O exception has occurred.
* @throws ParserConfigurationException
* the parser configuration exception
*/
private void loadSegments() throws SAXException, IOException, ParserConfigurationException {
SAXBuilder builder = new SAXBuilder();
builder.setEntityResolver(new Catalogue(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 {
writeString(string, false, null);
}
/**
* Write string.
* @param string
* the string
* @param isSegment
* 标识当前所写内容,ture 标识当前所写内容为 segment,false 标识当前所定内容为原骨架文件中的内容。
* @param replaceCode
* skeleton 文件中的segment 标识符
* @throws IOException
* Signals that an I/O exception has occurred.
*/
private void writeString(String string, boolean isSegment, String replaceCode) throws IOException {
byte[] bytes = string.getBytes(encoding);
output.write(bytes);
// 是否取消操作
if (replaceMonitor.isCanceled()) {
throw new OperationCanceledException(Messages.getString("javascript.cancel"));
}
// 在计算已处理的字节时,需要用 skeleton 文件的源编码进行解码
if (!isSegment) {
cpb.calculateProcessed(replaceMonitor, string, UTF_8);
} else {
replaceCode = "%%%" + replaceCode + "%%%";
cpb.calculateProcessed(replaceMonitor, replaceCode, UTF_8);
}
}
}
} | 10,368 | 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.javascript/src/net/heartsome/cat/converter/javascript/Activator.java | /**
* Activator.java
*
* Version information :
*
* Date:Jan 14, 2010
*
* Copyright notice :
*/
package net.heartsome.cat.converter.javascript;
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 plug-in ID
/** The Constant PLUGIN_ID. */
public static final String PLUGIN_ID = "net.heartsome.cat.converter.javascript";
// The shared instance
/** The plugin. */
private static Activator plugin;
/** The java script2 xliff sr. */
private ServiceRegistration javaScript2XliffSR;
/** The xliff2 java script sr. */
private ServiceRegistration xliff2JavaScriptSR;
/**
* 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 converter services
Converter javaScript2Xliff = new JavaScript2Xliff();
Properties properties = new Properties();
properties.put(Converter.ATTR_NAME, JavaScript2Xliff.NAME_VALUE);
properties.put(Converter.ATTR_TYPE, JavaScript2Xliff.TYPE_VALUE);
properties.put(Converter.ATTR_TYPE_NAME, JavaScript2Xliff.TYPE_NAME_VALUE);
javaScript2XliffSR = ConverterRegister.registerPositiveConverter(context, javaScript2Xliff, properties);
Converter xliff2JavaScript = new Xliff2JavaScript();
properties = new Properties();
properties.put(Converter.ATTR_NAME, Xliff2JavaScript.TYPE_NAME_VALUE);
properties.put(Converter.ATTR_TYPE, Xliff2JavaScript.TYPE_VALUE);
properties.put(Converter.ATTR_TYPE_NAME, Xliff2JavaScript.TYPE_NAME_VALUE);
xliff2JavaScriptSR = ConverterRegister.registerReverseConverter(context, xliff2JavaScript, 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 (javaScript2XliffSR != null) {
javaScript2XliffSR.unregister();
}
if (xliff2JavaScriptSR != null) {
xliff2JavaScriptSR.unregister();
}
plugin = null;
}
/**
* Returns the shared instance.
* @return the shared instance
*/
public static Activator getDefault() {
return plugin;
}
}
| 2,674 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
JavaScript2Xliff.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.javascript/src/net/heartsome/cat/converter/javascript/JavaScript2Xliff.java | /**
* JavaScript2Xliff.java
*
* Version information :
*
* Date:Jan 14, 2010
*
* Copyright notice :
*/
package net.heartsome.cat.converter.javascript;
import java.util.Map;
import net.heartsome.cat.converter.Converter;
import net.heartsome.cat.converter.ConverterException;
import net.heartsome.cat.converter.javascript.resource.Messages;
import org.eclipse.core.runtime.IProgressMonitor;
/**
* The Class JavaScript2Xliff.
* @author John Zhu
* @version
* @since JDK1.6
*/
public class JavaScript2Xliff implements Converter {
/** The Constant TYPE_VALUE. */
public static final String TYPE_VALUE = "javascript";
/** The Constant TYPE_NAME_VALUE. */
public static final String TYPE_NAME_VALUE = Messages.getString("javascript.TYPE_NAME_VALUE");
/** The Constant NAME_VALUE. */
public static final String NAME_VALUE = "JavaScript 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 {
return Jscript2xliffImpl.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;
}
} | 1,793 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
Jscript2xliffAbstract.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.javascript/src/net/heartsome/cat/converter/javascript/Jscript2xliffAbstract.java | package net.heartsome.cat.converter.javascript;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.OutputStream;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;
import java.util.Stack;
import net.heartsome.cat.converter.Converter;
import net.heartsome.cat.converter.javascript.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;
/**
* Jscript 转 xliff 的抽象实现
* @author cheney
* @since JDK1.6
*/
public abstract class Jscript2xliffAbstract {
/**
* 输入字符流
*/
protected Reader input;
/**
* 输出文件流
*/
public OutputStream output; // 设置为 public 是为了方便测试
/**
* 骨架输出文件流
*/
public OutputStream skeleton; // 设置为 public 是为了方便测试
/**
* 输出字符流
*/
protected BufferedReader buffer;
/**
* 源文件
*/
protected String inputFile;
/**
* xliff 文件
*/
protected String xliffFile;
/**
* 骨架文件
*/
protected String skeletonFile;
/**
* 源语言
*/
protected String sourceLanguage;
protected String targetLanguage;
/**
* segment ID
*/
public int segId; // 设置为 public 是为了方便测试
/**
* 源文件的字符编码
*/
protected String encoding;
// 从当前行中截取并进行处理的字符串
private String processingStr = "";
// 缓存当前行中未处理的字符串
private String cacheStr = "";
// 标识当前行是否包含单行注释
private boolean isSingleCom = false;
/**
* 当前行单行注释开始的索引
*/
int singleComIndex = -1;
// 标识当前行是包含在多行注释中
private boolean isMultiRowComStart = false;
// 当前行多行注释的开始索引
private int multiRowComStartIndex = -1;
// 标识当前行是否包含多行注释的结束
private boolean isMultiRowComEnd = false;
// 当前行多行注释的结束索引
private int multiRowComEndIndex = -1;
// 在处理的过程中缓存的最后一个有效字符,排除空白字符和注释
private char validCacheChar = '-';
/** The is suite. */
protected boolean isSuite;
/** The qt tool id. */
protected String qtToolId;
/**
* @param monitor
* 进度监视器
*/
public Map<String, String> run(IProgressMonitor monitor) throws Exception {
monitor = Progress.getMonitor(monitor);
Map<String, String> result = new HashMap<String, String>();
try {
// 计算总任务数
CalculateProcessedBytes cpb = ConverterUtils.getCalculateProcessedBytes(inputFile);
monitor.beginTask(Messages.getString("javascript.Jscript2xliffAbstract.task1"), cpb.getTotalTask());
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\" " + //$NON-NLS-1$
"xmlns:hs=\"" + Converter.HSNAMESPACE + "\" " + //$NON-NLS-1$ //$NON-NLS-2$
"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=\"javascript\">\n"); //$NON-NLS-1$
} else {
writeString("<file original=\"" + inputFile //$NON-NLS-1$
+ "\" source-language=\"" + sourceLanguage //$NON-NLS-1$
+ "\" datatype=\"javascript\">\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\">" + encoding //$NON-NLS-1$
+ "</hs:prop></hs:prop-group>\n"); //$NON-NLS-1$
writeString("</header>\n"); //$NON-NLS-1$
writeString("<body>\n"); //$NON-NLS-1$
String line = buffer.readLine();
// 计算转换进度
cpb.calculateProcessed(monitor, line, encoding);
while (line != null) {
// 取消转换操作
if (monitor.isCanceled()) {
throw new OperationCanceledException(Messages.getString("javascript.cancel"));
}
line = line + "\n"; //$NON-NLS-1$
if (isMultiRowComStart) {
// 表明当前行在多行注释中或是多行注释的结束行(包含 */)
line = processMultiRowCom(line);
if (line == null) {
// 如果返回的字符串为 NULL,则表明整行都为注释
line = buffer.readLine();
// 计算转换进度
cpb.calculateProcessed(monitor, line, encoding);
continue;
} else if (line.equals("\n")) {
// 只剩下换行符,则直接写骨架
writeSkeleton(line);
line = buffer.readLine();
// 计算转换进度
cpb.calculateProcessed(monitor, line, encoding);
continue;
}
}
// 检查当前行是否包含注释
checkForComment(line);
// 缓存当前将要处理的字符串
String cacheTemp = processingStr;
// 处理 processingStr 字符串
processingStr = checkForQuote(processingStr);
// 缓存当前要处理字符串中最后一个有效字符(排除空白字符)
validCacheChar = cacheLastValidChar(cacheTemp);
// 如果不存在跨行的情况,则此时 processingStr 应该为空
if (processingStr.length() > 0) {
// 检查此行是否以 \ 结尾,需排除所添加的换行符,同时考虑到 processing 是截取的字符串而不是以换行符结束
char inverseSecondChar = 'a';
if (processingStr.length() > 1) {
inverseSecondChar = processingStr.charAt(processingStr.length() - 2);
}
if (cacheStr != null || inverseSecondChar != '\\') {
ConverterUtils.throwConverterException(Activator.PLUGIN_ID,
Messages.getString("javascript.Jscript2xliffAbstract.msg1"));
}
// 存在引号中的字符串跨行的情况
String nextLine = buffer.readLine();
if (nextLine == null) {
ConverterUtils.throwConverterException(Activator.PLUGIN_ID,
Messages.getString("javascript.Jscript2xliffAbstract.msg2"));
}
// 计算转换进度
cpb.calculateProcessed(monitor, nextLine, encoding);
line = processingStr + nextLine;
continue;
}
// 处理 cacheStr 字符串
if (cacheStr != null) {
// 此行包含注释字符串
if (isSingleCom) {
// 把注释字符串写入骨架
writeSkeleton(cacheStr);
isSingleCom = false;
singleComIndex = -1;
}
if (isMultiRowComStart) {
if (isMultiRowComEnd) {
writeSkeleton(line.substring(multiRowComStartIndex, multiRowComEndIndex + 1));
// 去除所添加的换行符
line = line.substring(multiRowComEndIndex + 1, line.length() - 1);
isMultiRowComStart = false;
multiRowComStartIndex = -1;
isMultiRowComEnd = false;
multiRowComEndIndex = -1;
continue;
} else {
writeSkeleton(cacheStr);
}
}
}
line = buffer.readLine();
// 计算转换进度
cpb.calculateProcessed(monitor, line, encoding);
}
// 多行注释没有结束
if (isMultiRowComStart) {
ConverterUtils.throwConverterException(Activator.PLUGIN_ID, Messages.getString("javascript.Jscript2xliffAbstract.msg2"));
}
writeString("</body>\n"); //$NON-NLS-1$
writeString("</file>\n"); //$NON-NLS-1$
writeString("</xliff>"); //$NON-NLS-1$
result.put(Converter.ATTR_XLIFF_FILE, xliffFile);
} catch (Exception e) {
throw e;
} finally {
try {
if (skeleton != null) {
skeleton.close();
}
if (input != null) {
input.close();
}
if (output != null) {
output.close();
}
} catch (Exception e2) {
// ignore the exception
e2.printStackTrace();
}
monitor.done();
}
return result;
}
/**
* 缓存当前要处理字符串中最后一个有效字符(排除空白字符和注释)
* @param processingStr2
* @return
*/
private char cacheLastValidChar(String str) {
char result = '-';
int length = str.length();
for (int i = length - 1; i > -1; i--) {
char temp = str.charAt(i);
if (Character.isWhitespace(temp)) {
continue;
}
result = temp;
break;
}
return result;
}
/**
* 检查是否包含可抽取的文本
* @param line
* @return
* @throws UnsupportedEncodingException
* @throws IOException
*/
private String checkForQuote(String line) throws IOException {
Stack<Character> quoteStack = new Stack<Character>();
Stack<Character> squareBrackets = new Stack<Character>();
while (line.length() > 0) {
int quoteStartIndex = -1;
int quoteEndIndex = -1;
int length = line.length();
for (int i = 0; i < length; i++) {
char temp = line.charAt(i);
// 在查找正则表达式的结束时,需要忽略正则表达式中括号中出现的正斜杠
if (temp == '[' || temp == ']') {
if (!quoteStack.empty() && quoteStack.peek().charValue() == '/') {
// 排除转义的情况
boolean isEscape = checkIsEscape(line, i);
if (isEscape) {
continue;
}
// 在正则表达式开始且在结束之前出现了中括号
if (squareBrackets.empty()) {
if (temp == '[') {
squareBrackets.push(new Character(temp));
}
} else {
if (temp == ']') {
squareBrackets.pop();
}
}
}
}
// 排除正则表达式中括号中的正斜杠
if (temp == '/' && !squareBrackets.empty()) {
continue;
}
// 需要排除代码中的正则表达式,形如:e.element.text.match(/minorVersion\s*:\s*'(0|X)/)
if (temp == '"' || temp == '\'' || temp == '/') {
// 排除转义的情况
boolean isEscape = checkIsEscape(line, i);
if (isEscape) {
continue;
}
if (quoteStack.empty()) {
if (temp == '"' || temp == '\'') {
quoteStartIndex = i;
// 把最先找到的匹配字符压入堆栈
quoteStack.push(new Character(temp));
} else {
// 判断找到的正斜杠是正则表达式的开始还是除号
if (isPerlRegStart(line, i)) {
quoteStack.push(new Character(temp));
}
}
} else {
// 检查找到的引号是否与堆栈中的相匹配
Character character = quoteStack.peek();
char expectedChar = character.charValue();
if (expectedChar == temp) {
if (expectedChar == '"' || expectedChar == '\'') {
quoteEndIndex = i;
// 找到匹配引号的结束后跳出当前循环,对可抽取的字符进行处理
break;
} else {
// 找到匹配的正斜杠,把此字符弹出后,继续查找下一个双引号、单引号或正斜杠
quoteStack.pop();
// 如果缓存中括号的堆栈不为空,则清空此堆栈
if (!squareBrackets.empty()) {
squareBrackets.pop();
}
}
}
}
}
}
if (!quoteStack.empty() && quoteStartIndex != -1 && quoteEndIndex != -1) {
// 找到匹配的引号开始和结束
line = processQuoteStr(line, quoteStack.peek().charValue(), quoteStartIndex, quoteEndIndex);
// 弹出匹配的引号结束符
quoteStack.pop();
} else {
if (!quoteStack.empty()) {
// 没有找到匹配的结束符,需要把当前行与下一行连接后进行处理
break;
} else {
// 没有需要处理的可抽取文本,直接写骨架
writeSkeleton(line);
line = "";
}
}
}
return line;
}
/**
* 判断找到的正斜杠是正则表达式的开始还是除号 正则和除法有哪些区别?从语境上说,原则性的区别就是除法的前面 是被除数,正则的前面不是。而成为被除数的可能无非是以下3种 : 数字、变量、括号内的运算结果。
* @param line
* 包含正斜杠的字符串
* @param index
* 第一个正斜杠的索引
* @return 是正则表达式的开始则返回 true,否则返回 false
*/
private boolean isPerlRegStart(String line, int index) {
boolean isRegStart = false;
boolean isFind = false; // 标识在正斜杠之前找到了能识识此正斜杠类型的字符
for (int i = index - 1; i > -1; i--) {
// 忽略空空
char cc = line.charAt(i);
if (Character.isWhitespace(cc)) {
continue;
}
isFind = true;
// 前面一个非空白字符若是字母、数字、下划线或右括号则除号,否则为正则表达式
isRegStart = (!isLetterOrDigitOrUnderlineOrDollorOrRightParenthese(cc));
break;
}
if (!isFind) {
isRegStart = (!isLetterOrDigitOrUnderlineOrDollorOrRightParenthese(validCacheChar));
}
return isRegStart;
}
/**
* 判断此字符是否是字母、数字、下划线、美元符、右括号或右中括号(数组)
* @param cc
* @return 是就返回 true,否则返回 false
*/
private boolean isLetterOrDigitOrUnderlineOrDollorOrRightParenthese(char cc) {
if (Character.isLetterOrDigit(cc) || cc == '_' || cc == '$' || cc == ')' || cc == ']') {
return true;
} else {
return false;
}
}
/**
* 处理可抽取字符
* @param line
* @param quote
* 引号字符
* @param quoteStartIndex
* 引号的开始索引
* @param quoteEndIndex
* 引号的结束索引
* @return 引号结束索引后的字符
* @throws UnsupportedEncodingException
* @throws IOException
*/
private String processQuoteStr(String line, char quote, int quoteStartIndex, int quoteEndIndex) throws IOException {
String start = line.substring(0, quoteStartIndex + 1);
String quoteStr = line.substring(quoteStartIndex + 1, quoteEndIndex);
String remainStr = line.substring(quoteEndIndex + 1);
writeSkeleton(start);
writeSegment(quoteStr);
writeSkeleton("" + quote);
return remainStr;
}
/**
* 检查待处理的行是否包含注释,给相应的标识位赋值
* @param line
*/
private void checkForComment(String line) {
isSingleCom = false;
singleComIndex = -1;
isMultiRowComStart = false;
multiRowComStartIndex = -1;
isMultiRowComEnd = false;
multiRowComEndIndex = -1;
Stack<Character> quoteStack = new Stack<Character>();
int length = line.length();
for (int i = 0; i < length; i++) {
char temp = line.charAt(i);
if (temp == '"' || temp == '\'') {
// 排除转义的情况
boolean isEscape = checkIsEscape(line, i);
if (isEscape) {
continue;
}
if (quoteStack.empty()) {
// 把最先找到的引号压入堆栈
quoteStack.push(new Character(temp));
} else {
// 检查找到的引号是否与堆栈中的引号相匹配,匹配则弹出堆栈中的引号
Character character = quoteStack.peek();
if (character.charValue() == temp) {
quoteStack.pop();
}
}
}
if (temp == '/' && (i + 1) < length) {
// 排除转义的情况
boolean isEscape = checkIsEscape(line, i);
if (isEscape) {
continue;
}
char nextChar = line.charAt(i + 1);
if (quoteStack.empty() && (!isSingleCom) && (!isMultiRowComStart)) {
if (nextChar == '/') {
// 此行包含单行注释
processingStr = line.substring(0, i);
cacheStr = line.substring(i, line.length());
isSingleCom = true;
singleComIndex = i;
} else if (nextChar == '*') {
// 此行包含多行注释
processingStr = line.substring(0, i);
cacheStr = line.substring(i, line.length());
isMultiRowComStart = true;
multiRowComStartIndex = i;
}
}
}
if (isMultiRowComStart) {
// 进一步判断多行注释开始符后是否存在多行注释的结束符,需要注释如下情况:/*/
if (temp == '*' && (i + 1) < length && (i != multiRowComStartIndex + 1)) {
char nextChar = line.charAt(i + 1);
if (nextChar == '/') {
isMultiRowComEnd = true;
multiRowComEndIndex = i + 1;
}
}
}
if (isSingleCom || (isMultiRowComStart && isMultiRowComEnd)) {
// 如果查找到单行注释的或多行注释的开始和结束标识,则跳出循环不再查找注释标识
break;
}
}
if (!(isSingleCom || isMultiRowComStart)) {
// 如果当前行不包含注释
processingStr = line;
cacheStr = null;
}
}
/**
* 判断 line 中 index 指引的字符是否为转义字符
* @param line
* @param index
* @return
*/
private boolean checkIsEscape(String line, int index) {
boolean result = false;
// 排除转义的情况,且需要考虑引号之前的反斜杠也被转义的情况
int j = index;
int backslashCount = 0;
while (j > 0 && j < line.length()) {
j--;
if (line.charAt(j) == '\\') {
backslashCount++;
} else {
break;
}
}
// 如果 backslashCount 为奇数,则证明此引号为转义字符
if (backslashCount % 2 != 0) {
result = true;
}
return result;
}
/**
* 处理多行注释
* @param line
* @return
* @throws UnsupportedEncodingException
* @throws IOException
*/
private String processMultiRowCom(String line) throws IOException {
String result = null;
int length = line.length();
int index = line.indexOf("*/");
String comment = line; // 需写入骨架的字符串
if (index > -1) {
comment = line.substring(0, index + 2);
isMultiRowComStart = false;
multiRowComStartIndex = -1;
isMultiRowComEnd = false;
multiRowComEndIndex = -1;
if ((index + 2) <= length) {
// 多行注释结束符后还存有待处理字符
result = line.substring(index + 2);
}
}
writeSkeleton(comment);
return result;
}
/**
* @param string
*/
private void writeSegment(String segment) throws IOException {
if (segment.equals("")) {
return;
} //$NON-NLS-1$
writeString(" <trans-unit id=\"" + segId //$NON-NLS-1$
+ "\" xml:space=\"preserve\">\n" + " <source xml:lang=\"" //$NON-NLS-1$ //$NON-NLS-2$
+ sourceLanguage + "\">" + TextUtil.cleanString(segment) + "</source>\n" //$NON-NLS-1$ //$NON-NLS-2$
+ " </trans-unit>\n"); //$NON-NLS-1$
writeSkeleton("%%%" + segId++ + "%%%"); //$NON-NLS-1$ //$NON-NLS-2$
}
/**
* @param string
* @throws IOException
* ;
*/
private void writeString(String string) throws IOException {
output.write(string.getBytes("utf-8")); //$NON-NLS-1$
}
/**
* @param string
* @throws IOException
* ;
*/
private void writeSkeleton(String string) throws IOException {
skeleton.write(string.getBytes("utf-8")); //$NON-NLS-1$
}
}
| 19,457 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
Jscript2xliffImpl.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.javascript/src/net/heartsome/cat/converter/javascript/Jscript2xliffImpl.java | package net.heartsome.cat.converter.javascript;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.Map;
import net.heartsome.cat.converter.Converter;
import net.heartsome.cat.converter.ConverterException;
import net.heartsome.cat.converter.javascript.resource.Messages;
import net.heartsome.cat.converter.util.ConverterUtils;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.OperationCanceledException;
/**
*Jscript 转 xliff 的具体实现
* @author cheney
* @since JDK1.6
*/
class Jscript2xliffImpl extends Jscript2xliffAbstract {
/**
* 构造函数
* @param params
* 转换所需的配置信息
* @throws FileNotFoundException
* 如果所需转换的文件找不到,则抛此异常
* @throws UnsupportedEncodingException
* 如果以平台不支持的编码读取文件字符流时,则抛此异常
*/
public Jscript2xliffImpl(Map<String, String> params) throws FileNotFoundException, UnsupportedEncodingException {
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);
// fixed a bug 1293 by john.
encoding = params.get(Converter.ATTR_SOURCE_ENCODING);
input = new InputStreamReader(new FileInputStream(inputFile), encoding);
buffer = new BufferedReader(input);
output = new FileOutputStream(xliffFile);
skeleton = new FileOutputStream(skeletonFile);
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;
}
/**
* 转换
* @param params
* 转换所需的配置信息
* @param monitor
* 监视器
* @return 转换后的 xliff 文件
* @throws ConverterException
* 在转换过程中出错,则抛此异常 ;
*/
public static Map<String, String> run(Map<String, String> params, IProgressMonitor monitor)
throws ConverterException {
Map<String, String> result = null;
try {
result = new Jscript2xliffImpl(params).run(monitor);
} 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("javascript.Jscript2xliffImpl.msg"), e);
}
return result;
}
}
| 2,848 | 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.javascript/src/net/heartsome/cat/converter/javascript/resource/Messages.java | /**
* Messages.java
*
* Version information :
*
* Date:Jan 14, 2010
*
* Copyright notice :
*/
package net.heartsome.cat.converter.javascript.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.javascript.resource.javascript"; //$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,034 | 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.rap.ui.example/src/net/heartsome/cat/converter/rap/ui/Activator.java | package net.heartsome.cat.converter.rap.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 {
// The plug-in ID
public static final String PLUGIN_ID = "net.heartsome.cat.converter.rap.ui";
// The shared instance
private static Activator plugin;
/**
* 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);
plugin = this;
}
/*
* (non-Javadoc)
* @see org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext)
*/
public void stop(BundleContext context) throws Exception {
plugin = 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);
}
}
| 1,376 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
Application.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.rap.ui.example/src/net/heartsome/cat/converter/rap/ui/Application.java | package net.heartsome.cat.converter.rap.ui;
import net.heartsome.cat.convert.ui.ApplicationWorkbenchAdvisor;
import org.eclipse.rwt.RWT;
import org.eclipse.rwt.lifecycle.IEntryPoint;
import org.eclipse.rwt.lifecycle.UICallBack;
import org.eclipse.rwt.service.SessionStoreEvent;
import org.eclipse.rwt.service.SessionStoreListener;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.application.WorkbenchAdvisor;
/**
* This class controls all aspects of the application's execution
* and is contributed through the plugin.xml.
*/
public class Application implements IEntryPoint {
public int createUI() {
final Display display = PlatformUI.createDisplay();
UICallBack.activate(String.valueOf(display.hashCode()));
RWT.getSessionStore().addSessionStoreListener(new SessionStoreListener() {
public void beforeDestroy(SessionStoreEvent event) {
UICallBack.deactivate(String.valueOf(display.hashCode()));
}
});
WorkbenchAdvisor advisor = new ApplicationWorkbenchAdvisor();
return PlatformUI.createAndRunWorkbench( display, advisor );
}
}
| 1,129 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
Xliff2XmlTest.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.xml/testSrc/net/heartsome/cat/converter/xml/test/Xliff2XmlTest.java | package net.heartsome.cat.converter.xml.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.xml.Xliff2Xml;
import org.junit.Before;
import org.junit.Test;
public class Xliff2XmlTest {
public static Xliff2Xml converter = new Xliff2Xml();
private static String xlfFile = "rc/Test.xml.xlf";
private static String sklFile = "rc/Test.xml.skl";
private static String tgtFile = "rc/Test_en-US.xml";
@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);
args.put(Converter.ATTR_XLIFF_FILE, xlfFile);
args.put(Converter.ATTR_SKELETON_FILE, sklFile);
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());
}
}
| 1,532 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
Xml2XliffTest.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.xml/testSrc/net/heartsome/cat/converter/xml/test/Xml2XliffTest.java | package net.heartsome.cat.converter.xml.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.xml.Xml2Xliff;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.Test;
public class Xml2XliffTest {
public static Xml2Xliff converter = new Xml2Xliff();
private static String srcFile = "rc/Test.xml";
private static String xlfFile = "rc/Test.xml.xlf";
private static String sklFile = "rc/Test.xml.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, "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, 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, "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, 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, "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 testConvertMissingIsGen() 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, "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());
}
@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, "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);
args.put(Converter.ATTR_IS_GENERIC, Converter.TRUE);
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,886 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
Xliff2Xml.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.xml/src/net/heartsome/cat/converter/xml/Xliff2Xml.java | /**
* Xliff2Xml.java
*
* Version information :
*
* Date:Jan 14, 2010
*
* Copyright notice :
*/
package net.heartsome.cat.converter.xml;
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.Enumeration;
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.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.cat.converter.xml.resource.Messages;
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.runtime.IProgressMonitor;
import org.eclipse.core.runtime.OperationCanceledException;
import org.w3c.dom.Node;
import org.xml.sax.SAXException;
/**
* The Class Xliff2Xml.
* @author John Zhu
*/
public class Xliff2Xml implements Converter {
/** The Constant TYPE_VALUE. */
public static final String TYPE_VALUE = "xml";
/** The Constant TYPE_NAME_VALUE. */
public static final String TYPE_NAME_VALUE = Messages.getString("xml.TYPE_NAME_VALUE");
/** The Constant NAME_VALUE. */
public static final String NAME_VALUE = "XLIFF to XML 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 {
Xliff2XmlImpl converter = new Xliff2XmlImpl();
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 Xliff2XmlImpl.
* @author John Zhu
* @version
* @since JDK1.6
*/
class Xliff2XmlImpl {
private static final String UTF_8 = "UTF-8";
/** The input. */
private InputStreamReader input;
/** The buffer. */
private BufferedReader buffer;
/** The skl file. */
private String sklFile;
/** The xliff file. */
private String xliffFile;
/** The line. */
private String line;
/** The segments. */
private Hashtable<String, Element> segments;
/** The output. */
private FileOutputStream output;
/** The encoding. */
private String encoding;
/** The catalogue. */
private Catalogue catalogue;
/** The entities. */
private Hashtable<String, String> entities;
/** The in design. */
private boolean inDesign = false;
/** The in attribute. */
private boolean inAttribute;
// 计算替换进度的对象
private CalculateProcessedBytes cpb;
// 替换过程的进度监视器
private IProgressMonitor replaceMonitor;
/**
* 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 isInDesign = params.get(Converter.ATTR_IS_INDESIGN);
String outputFile = params.get(Converter.ATTR_TARGET_FILE);
if (isInDesign != null) {
inDesign = true;
}
encoding = params.get(Converter.ATTR_SOURCE_ENCODING);
String attrIsPreviewMode = params.get(Converter.ATTR_IS_PREVIEW_MODE);
/* 是否为预览翻译模式 */
boolean isPreviewMode = attrIsPreviewMode != null && attrIsPreviewMode.equals(Converter.TRUE);
try {
infoLogger.logConversionFileInfo(null, null, xliffFile, sklFile);
// 把转换过程分为两大部分共 10 个任务,其中加载 xliff 文件占 4,替换过程占 6。
monitor.beginTask("", 10);
monitor.subTask(Messages.getString("xml.Xliff2Xml.task1"));
infoLogger.startLoadingXliffFile();
catalogue = new Catalogue(catalogueFile);
output = new FileOutputStream(outputFile);
loadSegments();
infoLogger.endLoadingXliffFile();
monitor.worked(4);
// 是否取消
if (monitor.isCanceled()) {
throw new OperationCanceledException(Messages.getString("xml.cancel"));
}
try {
infoLogger.startReplacingSegmentSymbol();
cpb = ConverterUtils.getCalculateProcessedBytes(sklFile);
replaceMonitor = Progress.getSubMonitor(monitor, 6);
replaceMonitor.beginTask(Messages.getString("xml.Xliff2Xml.task2"), 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) {
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) {
inAttribute = segment.getAttributeValue("restype", "").equals("x-attribute"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
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())) {
writeString(tgtStr, true, code);
} else {
writeString(extractText(source), true, code);
}
} else {
writeString(extractText(source), true, code);
}
} else {
ConverterUtils.throwConverterException(Activator.PLUGIN_ID,
MessageFormat.format(Messages.getString("xml.Xliff2Xml.msg1"), code));
}
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();
output = null;
if (inDesign) {
removeSeparators(outputFile, catalogue);
}
result.put(Converter.ATTR_TARGET_FILE, outputFile);
infoLogger.endConversion();
} 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("xml.Xliff2Xml.msg2"), e);
} finally {
monitor.done();
}
return result;
}
/**
* Removes the separators.
* @param outputFile
* the output file
* @param catalogue2
* the catalogue2
* @throws SAXException
* the SAX exception
* @throws IOException
* Signals that an I/O exception has occurred.
*/
private void removeSeparators(String outputFile, Catalogue catalogue2) throws SAXException, IOException {
SAXBuilder builder = new SAXBuilder();
builder.setEntityResolver(catalogue2);
Document doc = builder.build(outputFile);
Element root = doc.getRootElement();
recurse(root);
XMLOutputter outputter = new XMLOutputter();
outputter.preserveSpace(true);
output = new FileOutputStream(outputFile);
outputter.output(doc, output);
output.close();
}
/**
* Extract text.
* @param element
* the element
* @return the string
*/
private String extractText(Element element) {
String result = ""; //$NON-NLS-1$
List<Node> content = element.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);
String ph = extractText(e);
result = result + ph;
break;
case Node.TEXT_NODE:
if (element.getName().equals("ph")) { //$NON-NLS-1$
result = result + n.getNodeValue();
} else {
if (inAttribute) {
result = result + addEntities(n.getNodeValue()).replaceAll("\"", """); //$NON-NLS-1$ //$NON-NLS-2$
} else {
result = result + addEntities(n.getNodeValue());
}
}
break;
default:
break;
}
}
return result;
}
/**
* Adds the entities.
* @param string
* the string
* @return the string
*/
private String addEntities(String string) {
int index = string.indexOf("&"); //$NON-NLS-1$
while (index != -1) {
int smcolon = string.indexOf(";", index); //$NON-NLS-1$
if (smcolon == -1) {
// no semicolon. there is no chance it is an entity
string = string.substring(0, index) + "&" //$NON-NLS-1$
+ string.substring(index + 1);
index++;
} else {
int space = string.indexOf(" ", index); //$NON-NLS-1$
if (space == -1) {
String name = string.substring(index + 1, smcolon);
if (entities.containsKey(name)) {
// it is an entity, jump to the semicolon
index = smcolon;
} else {
string = string.substring(0, index) + "&" //$NON-NLS-1$
+ string.substring(index + 1);
index++;
}
} else {
// check if space appears before the semicolon
if (space < smcolon) {
// not an entity!
string = string.substring(0, index) + "&" //$NON-NLS-1$
+ string.substring(index + 1);
index++;
} else {
String name = string.substring(index + 1, smcolon);
if (entities.containsKey(name)) {
// it is a known entity, jump to the semicolon
index = smcolon;
} else {
string = string.substring(0, index) + "&" //$NON-NLS-1$
+ string.substring(index + 1);
index++;
}
}
}
}
if (index < string.length() && index >= 0) {
index = string.indexOf("&", index); //$NON-NLS-1$
} else {
index = -1;
}
}
StringTokenizer tok = new StringTokenizer(string, "<>", true); //$NON-NLS-1$
StringBuffer buff = new StringBuffer();
while (tok.hasMoreElements()) {
String str = tok.nextToken();
if (str.equals("<")) { //$NON-NLS-1$
buff.append("<"); //$NON-NLS-1$
} else if (str.equals(">")) { //$NON-NLS-1$
buff.append(">"); //$NON-NLS-1$
} else {
buff.append(str);
}
}
string = buff.toString();
// now replace common text with
// the entities declared in the DTD
Enumeration<String> enu = entities.keys();
while (enu.hasMoreElements()) {
String key = enu.nextElement();
String value = entities.get(key);
if (!value.equals("") && !key.equals("amp") && !key.equals("lt") //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
&& !key.equals("gt") && !key.equals("quot") && !key.equals("apos")) { //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
string = replaceEntities(string, value, "&" + key + ";"); //$NON-NLS-1$ //$NON-NLS-2$
}
}
enu = null;
tok = null;
buff = null;
return string;
}
/**
* Write string.
* @param string
* the string
* @throws IOException
* Signals that an I/O exception has occurred.
*/
private void writeString(String string) throws IOException {
writeString(string, false, encoding);
}
/**
* Write string.
* @param string
* the string
* @param isSegment
* 标识当前所写内容,ture 标识当前所写内容为 segment,false 标识当前所定内容为原骨架文件中的内容。
* @param replaceCode
* skeleton 文件中的segment 标识符
* @throws IOException
* Signals that an I/O exception has occurred.
*/
private void writeString(String string, boolean isSegment, String replaceCode) throws IOException {
byte[] bytes = string.getBytes(encoding);
output.write(bytes);
// 是否取消操作
if (replaceMonitor.isCanceled()) {
throw new OperationCanceledException(Messages.getString("xml.cancel"));
}
// 在计算已处理的字节时,需要用 skeleton 文件的源编码进行解码
if (!isSegment) {
cpb.calculateProcessed(replaceMonitor, string, UTF_8);
} else {
replaceCode = "%%%" + replaceCode + "%%%";
cpb.calculateProcessed(replaceMonitor, replaceCode, UTF_8);
}
}
/**
* 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$
}
entities = new Hashtable<String, String>();
Element header = root.getChild("file").getChild("header"); //$NON-NLS-1$ //$NON-NLS-2$
List<Element> groups = header.getChildren("hs:prop-group"); //$NON-NLS-1$
if (groups != null) {
Iterator<Element> g = groups.iterator();
while (g.hasNext()) {
Element group = g.next();
if (group.getAttributeValue("name").equals("entities")) { //$NON-NLS-1$ //$NON-NLS-2$
List<Element> props = group.getChildren("hs:prop"); //$NON-NLS-1$
Iterator<Element> p = props.iterator();
while (p.hasNext()) {
Element prop = p.next();
entities.put(prop.getAttributeValue("prop-type"), prop //$NON-NLS-1$
.getText());
}
}
if (group.getAttributeValue("name").equals("encoding")) { //$NON-NLS-1$ //$NON-NLS-2$
String stored = group.getChild("hs:prop").getText(); //$NON-NLS-1$
if (!stored.equals(encoding)) {
encoding = stored;
}
}
}
}
}
}
/**
* Replace token.
* @param string
* the string
* @param token
* the token
* @param newText
* the new text
* @return the string
*/
protected static String replaceToken(String string, String token, String newText) {
int index = string.indexOf(token);
while (index != -1) {
string = string.substring(0, index) + newText + string.substring(index + token.length());
index = string.indexOf(token, index + newText.length());
}
return string;
}
/**
* Recurse.
* @param e
* the e
*/
private static void recurse(Element e) {
List<Node> content = e.getContent();
for (int i = 0; i < content.size(); i++) {
Node n = content.get(i);
switch (n.getNodeType()) {
case Node.TEXT_NODE:
String text = n.getNodeValue();
if (text.startsWith("c_")) { //$NON-NLS-1$
text = "c_" + text.substring(2).replaceAll("_", "~sep~"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
}
break;
case Node.ELEMENT_NODE:
recurse(new Element(n));
break;
default:
break;
}
}
}
/**
* Replace entities.
* @param string
* the string
* @param token
* the token
* @param entity
* the entity
* @return the string
*/
private static String replaceEntities(String string, String token, String entity) {
int index = string.indexOf(token);
while (index != -1) {
String before = string.substring(0, index);
String after = string.substring(index + token.length());
// check if we are not inside an entity
int amp = before.lastIndexOf("&"); //$NON-NLS-1$
if (amp == -1) {
// we are not in an entity
string = before + entity + after;
} else {
boolean inEntity = true;
for (int i = amp; i < before.length(); i++) {
char c = before.charAt(i);
if (Character.isWhitespace(c) || ";.@$*()[]{},/?\\\"\'+=-^".indexOf(c) != -1) { //$NON-NLS-1$
inEntity = false;
break;
}
}
if (inEntity) {
// check for a colon in "after"
int colon = after.indexOf(";"); //$NON-NLS-1$
if (colon == -1) {
// we are not in an entity
string = before + entity + after;
} else {
// verify is there is something that breaks the entity
// before
for (int i = 0; i < colon; i++) {
char c = after.charAt(i);
if (Character.isWhitespace(c) || "&.@$*()[]{},/?\\\"\'+=-^".indexOf(c) != -1) { //$NON-NLS-1$
inEntity = false;
break;
}
}
}
} else {
// we are not in an entity
string = before + entity + after;
}
}
if (index < string.length()) {
index = string.indexOf(token, index + 1);
}
}
return string;
}
}
| 19,162 | 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.xml/src/net/heartsome/cat/converter/xml/Activator.java | /**
* Activator.java
*
* Version information :
*
* Date:Jan 14, 2010
*
* Copyright notice :
*/
package net.heartsome.cat.converter.xml;
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 plug-in ID
/** The Constant PLUGIN_ID. */
public static final String PLUGIN_ID = "net.heartsome.cat.converter.xml";
// The shared instance
/** The plugin. */
private static Activator plugin;
/** The xml2 xliff sr. */
private ServiceRegistration xml2XliffSR;
/** The xliff2 xml sr. */
private ServiceRegistration xliff2XmlSR;
/**
* 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 convert service
Converter xml2Xliff = new Xml2Xliff();
Properties properties = new Properties();
properties.put(Converter.ATTR_NAME, Xml2Xliff.NAME_VALUE);
properties.put(Converter.ATTR_TYPE, Xml2Xliff.TYPE_VALUE);
properties.put(Converter.ATTR_TYPE_NAME, Xml2Xliff.TYPE_NAME_VALUE);
xml2XliffSR = ConverterRegister.registerPositiveConverter(context, xml2Xliff, properties);
Converter xliff2Xml = new Xliff2Xml();
properties = new Properties();
properties.put(Converter.ATTR_NAME, Xliff2Xml.NAME_VALUE);
properties.put(Converter.ATTR_TYPE, Xliff2Xml.TYPE_VALUE);
properties.put(Converter.ATTR_TYPE_NAME, Xliff2Xml.TYPE_NAME_VALUE);
xliff2XmlSR = ConverterRegister.registerReverseConverter(context, xliff2Xml, 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 (xml2XliffSR != null) {
xml2XliffSR.unregister();
}
if (xliff2XmlSR != null) {
xliff2XmlSR.unregister();
}
plugin = null;
}
/**
* Returns the shared instance.
* @return the shared instance
*/
public static Activator getDefault() {
return plugin;
}
}
| 2,613 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
AutoConfiguration.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.xml/src/net/heartsome/cat/converter/xml/AutoConfiguration.java | /**
* AutoConfiguration.java
*
* Version information :
*
* Date:Jan 14, 2010
*
* Copyright notice :
*/
package net.heartsome.cat.converter.xml;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import javax.xml.parsers.ParserConfigurationException;
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.w3c.dom.Node;
import org.xml.sax.SAXException;
/**
* The Class AutoConfiguration.
* @author John Zhu
* @version
* @since JDK1.6
*/
public class AutoConfiguration {
/** The segment. */
private Hashtable<String, String> segment;
/**
* Run.
* @param input
* the input
* @param out
* the out
* @param catalogue
* the catalogue
* @throws SAXException
* the SAX exception
* @throws IOException
* Signals that an I/O exception has occurred.
* @throws ParserConfigurationException
* the parser configuration exception
*/
public void run(String input, String out, String catalogue) throws SAXException, IOException,
ParserConfigurationException {
SAXBuilder builder = new SAXBuilder();
builder.setEntityResolver(new Catalogue(catalogue));
Document d = builder.build(input);
Element r = d.getRootElement();
segment = new Hashtable<String, String>();
recurse(r);
Document doc = new Document(null, "ini-file", "-//HEARTSOME//Converters 2.0.0//EN", "configuration.dtd"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
Element root = doc.getRootElement();
Enumeration<String> keys = segment.keys();
while (keys.hasMoreElements()) {
Element e = new Element("tag", doc); //$NON-NLS-1$
String key = keys.nextElement();
e.setText(key);
e.setAttribute("hard-break", "segment"); //$NON-NLS-1$ //$NON-NLS-2$
root.addContent(e);
root.addContent("\n"); //$NON-NLS-1$
}
XMLOutputter outputter = new XMLOutputter();
FileOutputStream output = new FileOutputStream(out);
outputter.output(doc, output);
output.close();
}
/**
* Recurse.
* @param r
* the r
*/
private void recurse(Element r) {
String text = ""; //$NON-NLS-1$
List<Node> content = r.getContent();
Iterator<Node> i = content.iterator();
while (i.hasNext()) {
Node n = i.next();
if (n.getNodeType() == Node.TEXT_NODE) {
text = text + n.getNodeValue().trim();
}
if (n.getNodeType() == Node.ELEMENT_NODE) {
Element e = new Element(n);
recurse(e);
}
}
if (!text.equals("") && !segment.contains(r.getName())) { //$NON-NLS-1$
segment.put(r.getName(), r.getName());
}
}
}
| 2,903 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
Xml2Xliff.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.xml/src/net/heartsome/cat/converter/xml/Xml2Xliff.java | /**
* Xml2Xliff.java
*
* Version information :
*
* Date:Jan 14, 2010
*
* Copyright notice :
*/
package net.heartsome.cat.converter.xml;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Enumeration;
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 javax.xml.parsers.ParserConfigurationException;
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.xml.resource.Messages;
import net.heartsome.util.CRC16;
import net.heartsome.util.TextUtil;
import net.heartsome.xml.Attribute;
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.runtime.IProgressMonitor;
import org.eclipse.core.runtime.OperationCanceledException;
import org.w3c.dom.CDATASection;
import org.w3c.dom.EntityReference;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.ProcessingInstruction;
import org.xml.sax.SAXException;
import com.wutka.dtd.DTD;
import com.wutka.dtd.DTDParser;
/**
* The Class Xml2Xliff.
* @author John Zhu
*/
public class Xml2Xliff implements Converter {
/** The Constant TYPE_VALUE. */
public static final String TYPE_VALUE = "xml";
/** The Constant TYPE_NAME_VALUE. */
public static final String TYPE_NAME_VALUE = Messages.getString("xml.TYPE_NAME_VALUE");
/** The Constant NAME_VALUE. */
public static final String NAME_VALUE = "XML 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 {
Xml2XliffImpl converter = new Xml2XliffImpl();
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 Xml2XliffImpl.
* @author John Zhu
* @version
* @since JDK1.6
*/
class Xml2XliffImpl {
/** The input file. */
private String inputFile;
/** The xliff file. */
private String xliffFile;
/** The skeleton file. */
private String skeletonFile;
/** The source language. */
private String sourceLanguage;
private String targetLanguage;
/** The src encoding. */
private String srcEncoding;
/** The input. */
private FileInputStream input;
/** The output. */
private FileOutputStream output;
/** The skeleton. */
private FileOutputStream skeleton;
/** The seg id. */
private int segId;
/** The tag id. */
private int tagId;
/** The segments. */
private List<String> segments;
/** The starts segment. */
private Hashtable<String, String> startsSegment;
/** The translatable attributes. */
private Hashtable<String, Vector<String>> translatableAttributes;
/** The inline. */
private Hashtable<String, String> inline;
/** The ctypes. */
private Hashtable<String, String> ctypes;
/** The keep formating. */
private Hashtable<String, String> keepFormating;
/** The seg by element. */
private boolean segByElement;
/** The segmenter. */
private StringSegmenter segmenter;
/** The catalogue. */
private String catalogue;
/** The program folder. */
private String programFolder;
/** The root element. */
private String rootElement;
/** The entities. */
private Hashtable<String, String> entities;
/** The entities map. */
private String entitiesMap;
/** The root. */
private Element root;
/** The text. */
private String text;
/** The stack. */
private Stack<String> stack;
/** The translatable. */
private String translatable = ""; //$NON-NLS-1$
/** The in design. */
private boolean inDesign = false;
/** The ignore. */
private Hashtable<String, String> ignore;
// /** The generic. */
// private boolean generic;
/** The in attribute. */
private boolean inAttribute;
/** The is resx. */
private boolean isResx;
/** The start text. */
private String startText;
/** The end text. */
private String endText;
/** The is suite. */
private boolean isSuite;
/** The qt tool id. */
private String qtToolID;
/** The format. */
private String format;
/**
* 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);
// 把转换分成四个部分:写 xliff 文件头,构建 tables,构建列表,处理列表。
monitor.beginTask("", 4);
monitor.subTask(Messages.getString("xml.Xml2Xliff.task1"));
Map<String, String> result = new HashMap<String, String>();
segId = 1;
stack = new Stack<String>();
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);
catalogue = params.get(Converter.ATTR_CATALOGUE);
programFolder = params.get(Converter.ATTR_PROGRAM_FOLDER);
if (programFolder == null) {
programFolder = Converter.PROGRAM_FOLDER_DEFAULT_VALUE;
}
String elementSegmentation = params.get(Converter.ATTR_SEG_BY_ELEMENT);
String initSegmenter = params.get(Converter.ATTR_SRX);
String isInDesign = params.get(Converter.ATTR_IS_INDESIGN);
format = params.get(Converter.ATTR_FORMAT);
if (format == null || "".equals(format)) {
format = TYPE_VALUE;
}
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;
if (isInDesign != null) {
inDesign = true;
} else {
inDesign = false;
}
if (params.get(Converter.ATTR_IS_RESX) != null) {
isResx = true;
} else {
isResx = false;
}
// 如果根据文件找不相应的 ini file,则自动生成一个。
// String isGeneric = params.get(Converter.ATTR_IS_GENERIC);
// if (isGeneric != null && isGeneric.equals(Converter.TRUE)) {
// generic = true;
// } else {
// generic = false;
// }
try {
boolean autoConfiguration = false;
String iniFile = getIniFile(inputFile);
File f = new File(iniFile);
if (!f.exists()) {
// if (!generic) {
// ConverterUtils.throwConverterException(Activator.PLUGIN_ID, MessageFormat.format(Messages
// .getString("Xml2Xliff.10"), f.getName()));
// }
AutoConfiguration autoConfigurator = new AutoConfiguration();
autoConfigurator.run(inputFile, f.getAbsolutePath(), catalogue);
autoConfiguration = true;
}
if (elementSegmentation == null) {
segByElement = false;
} else {
if (Converter.TRUE.equals(elementSegmentation)) {
segByElement = true;
} else {
segByElement = false;
}
}
if (!segByElement) {
segmenter = new StringSegmenter(initSegmenter, sourceLanguage, catalogue);
}
String detected = getEncoding(inputFile);
if (!srcEncoding.equals(detected)) {
System.out.println("Changed encoding to " + detected); //$NON-NLS-1$
srcEncoding = detected;
}
input = new FileInputStream(inputFile);
skeleton = new FileOutputStream(skeletonFile);
output = new FileOutputStream(xliffFile);
writeHeader();
monitor.worked(1);
int size = input.available();
byte[] array = new byte[size];
if (size != input.read(array)) {
ConverterUtils.throwConverterException(Activator.PLUGIN_ID, Messages.getString("xml.Xml2Xliff.msg1"));
}
String file = new String(array, srcEncoding);
// remove xml declaration and doctype
int begin = file.indexOf("<" + rootElement); //$NON-NLS-1$
if (begin != -1) {
if (file.charAt(0) == '<') {
writeSkeleton(file.substring(0, begin));
} else {
writeSkeleton(file.substring(1, begin));
}
file = file.substring(begin);
}
file = null;
array = null;
buildTables(iniFile, Progress.getSubMonitor(monitor, 1));
if (autoConfiguration) {
f.delete();
}
buildList(Progress.getSubMonitor(monitor, 1));
processList(Progress.getSubMonitor(monitor, 1));
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("xml.Xml2Xliff.msg2"), e);
} finally {
monitor.done();
}
return result;
}
/**
* Gets the ini file.
* @param fileName
* the file name
* @return the ini file
* @throws SAXException
* the SAX exception
* @throws IOException
* Signals that an I/O exception has occurred.
* @throws ParserConfigurationException
* the parser configuration exception
* @throws ConverterException
* the converter exception
*/
public String getIniFile(String fileName) throws SAXException, IOException, ParserConfigurationException,
ConverterException {
SAXBuilder builder = new SAXBuilder();
Catalogue cat = new Catalogue(catalogue);
builder.setEntityResolver(cat);
/*
* set expandEntities to false if automatic inclusion of referenced documents is not desired. It is enabled
* by default, but may change later upon request.
*/
// builder.expandEntities(false);
Document doc = builder.build(fileName);
entities = new Hashtable<String, String>();
NamedNodeMap map = doc.getEntities();
entitiesMap = ""; //$NON-NLS-1$
if (map != null) {
int ents = map.getLength();
for (int i = 0; i < ents; i++) {
Node n = map.item(i);
String value = n.getNodeValue();
if (value == null) {
Node first = n.getFirstChild();
if (first != null) {
value = first.getNodeValue();
}
}
if (value != null) {
entities.put("&" + n.getNodeName() + ";", value); //$NON-NLS-1$ //$NON-NLS-2$
}
n = null;
}
Enumeration<String> en = entities.keys();
while (en.hasMoreElements()) {
String key = en.nextElement();
entitiesMap = entitiesMap + " <prop prop-type=\"" //$NON-NLS-1$
+ key.substring(1, key.length() - 1) + "\">" //$NON-NLS-1$
+ cleanEntity(entities.get(key)) + "</prop>\n"; //$NON-NLS-1$
}
map = null;
}
// Add predefined standard entities
entities.put(">", ">"); //$NON-NLS-1$ //$NON-NLS-2$
entities.put("<", "<"); //$NON-NLS-1$ //$NON-NLS-2$
entities.put("&", "&"); //$NON-NLS-1$ //$NON-NLS-2$
entities.put("'", "'"); //$NON-NLS-1$ //$NON-NLS-2$
entities.put(""", "\""); //$NON-NLS-1$ //$NON-NLS-2$
root = doc.getRootElement();
rootElement = root.getName();
// check for ResX before anything else
// this requires a fixed ini name
if (root.getName().equals("root")) { //$NON-NLS-1$
List<Element> dataElements = root.getChildren("data"); //$NON-NLS-1$
if (dataElements.size() > 0) {
for (int i = 0; i < dataElements.size(); i++) {
Element g = (dataElements.get(i)).getChild("translate"); //$NON-NLS-1$
if (g != null) {
isResx = true;
break;
}
}
if (isResx) {
return programFolder + "ini/config_resx.xml"; //$NON-NLS-1$
}
}
}
String pub = doc.getPublicId();
String sys = doc.getSystemId();
if (sys != null) {
// remove path from systemId
if (sys.indexOf("/") != -1 && sys.lastIndexOf("/") < sys.length()) { //$NON-NLS-1$ //$NON-NLS-2$
sys = sys.substring(sys.lastIndexOf("/") + 1); //$NON-NLS-1$
}
if (sys.indexOf("\\") != -1 && sys.lastIndexOf("/") < sys.length()) { //$NON-NLS-1$ //$NON-NLS-2$
sys = sys.substring(sys.lastIndexOf("\\") + 1); //$NON-NLS-1$
}
}
Document d = builder.build(catalogue);
Element r = d.getRootElement();
List<Element> dtds = r.getChildren("dtd"); //$NON-NLS-1$
Iterator<Element> i = dtds.iterator();
while (i.hasNext()) {
Element dtd = i.next();
if (pub != null) {
if (dtd.getAttributeValue("publicId", "").equals(pub)) { //$NON-NLS-1$ //$NON-NLS-2$
String s = getRootElement(dtd.getText());
if (s != null) {
System.out
.println("Detected configuration file using PUBLIC ID : ini/config_" + s + ".xml"); //$NON-NLS-1$ //$NON-NLS-2$
return programFolder + "ini/config_" + s + ".xml"; //$NON-NLS-1$ //$NON-NLS-2$
}
}
}
if (sys != null) {
if (dtd.getAttributeValue("systemId", "").equals(sys)) { //$NON-NLS-1$ //$NON-NLS-2$
String s = getRootElement(dtd.getText());
if (s != null) {
System.out
.println("Detected configuration file using SYSTEM ID : ini/config_" + s + ".xml"); //$NON-NLS-1$ //$NON-NLS-2$
return programFolder + "ini/config_" + s + ".xml"; //$NON-NLS-1$ //$NON-NLS-2$
}
}
if (dtd.getAttributeValue("systemId", "").endsWith(sys)) { //$NON-NLS-1$ //$NON-NLS-2$
String s = getRootElement(dtd.getText());
if (s != null) {
System.out
.println("Detected configuration file using DTD name in SYSTEM ID : ini/config_" + s + ".xml"); //$NON-NLS-1$ //$NON-NLS-2$
return programFolder + "ini/config_" + s + ".xml"; //$NON-NLS-1$ //$NON-NLS-2$
}
}
}
}
if (rootElement.indexOf(":") != -1) { //$NON-NLS-1$
System.out.println("Detected configuration file using namespace: " //$NON-NLS-1$
+ rootElement.substring(0, rootElement.indexOf(":"))); //$NON-NLS-1$
return programFolder + "ini/config_" //$NON-NLS-1$
+ rootElement.substring(0, rootElement.indexOf(":")) //$NON-NLS-1$
+ ".xml"; //$NON-NLS-1$
}
System.out.println("Detected configuration file using root element: " + rootElement); //$NON-NLS-1$
return programFolder + "ini/config_" + rootElement + ".xml"; //$NON-NLS-1$ //$NON-NLS-2$
}
/**
* Clean entity.
* @param s
* the s
* @return the string
*/
private String cleanEntity(String s) {
int control = s.indexOf("&"); //$NON-NLS-1$
while (control != -1) {
int sc = s.indexOf(";", control); //$NON-NLS-1$
if (sc == -1) {
// no semicolon, it's not an entity
s = s.substring(0, control) + "&" //$NON-NLS-1$
+ s.substring(control + 1);
} else {
// may be an entity
String candidate = s.substring(control, sc) + ";"; //$NON-NLS-1$
if (!candidate.equals("&")) { //$NON-NLS-1$
String entity = entities.get(candidate);
if (entity != null) {
s = s.substring(0, control) + entity + s.substring(sc + 1);
} else if (candidate.startsWith("&#x")) { //$NON-NLS-1$
// it's a character in hexadecimal format
int c = Integer.parseInt(candidate.substring(3, candidate.length() - 1), 16);
s = s.substring(0, control) + (char) c + s.substring(sc + 1);
} else if (candidate.startsWith("&#")) { //$NON-NLS-1$
// it's a character
int c = Integer.parseInt(candidate.substring(2, candidate.length() - 1));
s = s.substring(0, control) + (char) c + s.substring(sc + 1);
} else {
s = s.substring(0, control) + "&" //$NON-NLS-1$
+ s.substring(control + 1);
}
}
}
if (control < s.length()) {
control++;
}
control = s.indexOf("&", control); //$NON-NLS-1$
}
control = s.indexOf("<"); //$NON-NLS-1$
while (control != -1) {
s = s.substring(0, control) + "<" + s.substring(control + 1); //$NON-NLS-1$
if (control < s.length()) {
control++;
}
control = s.indexOf("<", control); //$NON-NLS-1$
}
control = s.indexOf(">"); //$NON-NLS-1$
while (control != -1) {
s = s.substring(0, control) + ">" + s.substring(control + 1); //$NON-NLS-1$
if (control < s.length()) {
control++;
}
control = s.indexOf(">", control); //$NON-NLS-1$
}
return s;
}
/**
* Gets the root element.
* @param string
* the string
* @return the root element
* @throws ConverterException
* the converter exception
*/
private String getRootElement(String string) throws ConverterException {
String result = null;
File dtd = new File(string);
try {
DTDParser parser = new DTDParser(dtd);
DTD d = parser.parse(true);
if (d != null) {
if (d.rootElement != null) {
result = d.rootElement.getName();
}
}
} catch (IOException e) {
if (Converter.DEBUG_MODE) {
e.printStackTrace();
}
ConverterUtils.throwConverterException(Activator.PLUGIN_ID, Messages.getString("xml.Xml2Xliff.msg3"), e);
}
return result;
}
/**
* Write header.
* @throws IOException
* Signals that an I/O exception has occurred.
*/
private void writeHeader() throws IOException {
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=\"" + cleanString(inputFile) + "\" source-language=\"" //$NON-NLS-1$ //$NON-NLS-2$
+ sourceLanguage
+ "\" target-language=\"" + targetLanguage + "\" datatype=\"" + format + "\">\n"); //$NON-NLS-1$ //$NON-NLS-2$
} else {
writeString("<file original=\"" + cleanString(inputFile) + "\" source-language=\"" //$NON-NLS-1$ //$NON-NLS-2$
+ sourceLanguage + "\" datatype=\"" + format + "\">\n"); //$NON-NLS-1$ //$NON-NLS-2$
}
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\">" //$NON-NLS-1$
+ srcEncoding + "</hs:prop></hs:prop-group>\n"); //$NON-NLS-1$
if (!entitiesMap.equals("")) { //$NON-NLS-1$
writeString(" <hs:prop-group name=\"entities\">\n" + entitiesMap //$NON-NLS-1$
+ " </hs:prop-group>\n"); //$NON-NLS-1$
}
writeString("</header>\n"); //$NON-NLS-1$
writeString("<body>\n"); //$NON-NLS-1$
}
/**
* Process list.
* @throws SAXException
* the SAX exception
* @throws IOException
* Signals that an I/O exception has occurred.
*/
private void processList(IProgressMonitor monitor) throws IOException, SAXException {
// 设置任务数量
monitor.beginTask(Messages.getString("xml.Xml2Xliff.task2"), segments.size());
monitor.subTask("");
for (int i = 0; i < segments.size(); i++) {
// 检查是否取消操作
if (monitor.isCanceled()) {
throw new OperationCanceledException(Messages.getString("xml.cancel"));
}
monitor.worked(1);
String txt = segments.get(i);
if (txt.startsWith("" + '\u007F' + "" + '\u007F')) { //$NON-NLS-1$ //$NON-NLS-2$
// send directly to skeleton
writeSkeleton(txt.substring(2));
continue;
}
if (txt.startsWith("" + '\u0080')) { //$NON-NLS-1$
inAttribute = true;
txt = txt.substring(1);
} else {
inAttribute = false;
}
if (inDesign && !txt.trim().equals("")) { //$NON-NLS-1$
if (txt.startsWith("c_") && !txt.substring(2).trim().equals("")) { //$NON-NLS-1$ //$NON-NLS-2$
writeSkeleton("c_"); //$NON-NLS-1$
txt = txt.substring(2);
txt.replaceAll("~sep~", "_"); //$NON-NLS-1$ //$NON-NLS-2$
} else {
writeSkeleton(txt);
continue;
}
}
if (segByElement) {
writeSegment(txt);
} else {
// 将单纯的格式信息提前写入骨架以减少标记。
int inx = txt.indexOf("?>");
while (inDesign && txt.startsWith("<?") && inx != -1) {
writeSkeleton(txt.substring(0, inx + 2));
txt = txt.substring(inx + 2);
inx = txt.indexOf("?>");
}
String[] segs = segmenter.segment(txt);
for (int h = 0; h < segs.length; h++) {
String seg = segs[h];
boolean isStartWith2028 = seg.startsWith("" + '\u2028');
boolean isStartWith2029 = seg.startsWith("" + '\u2029');
while (isStartWith2028 || isStartWith2029) {
if (isStartWith2028) {
writeSkeleton("" + '\u2028'); //$NON-NLS-1$
} else {
writeSkeleton("" + '\u2029'); //$NON-NLS-1$
}
seg = seg.substring(1);
isStartWith2028 = seg.startsWith("" + '\u2028');
isStartWith2029 = seg.startsWith("" + '\u2029');
}
writeSegment(seg);
}
}
}
monitor.done();
}
/**
* Write segment.
* @param segment
* the segment
* @throws SAXException
* the SAX exception
* @throws IOException
* Signals that an I/O exception has occurred.
*/
private void writeSegment(String segment) throws IOException, SAXException {
tagId = 0;
String restype = ""; //$NON-NLS-1$
String tagged = addTags(segment);
if (!containsText(tagged)) {
writeSkeleton(segment);
return;
}
if (inAttribute) {
restype = " restype=\"x-attribute\""; //$NON-NLS-1$
}
String seg = " <trans-unit id=\"" + segId //$NON-NLS-1$
+ "\" xml:space=\"preserve\" approved=\"no\" " //$NON-NLS-1$
+ restype + ">\n" //$NON-NLS-1$
+ " <source xml:lang=\"" + sourceLanguage + "\">" //$NON-NLS-1$ //$NON-NLS-2$
+ tagged + "</source>\n </trans-unit>\n"; //$NON-NLS-1$
writeString(tidy(seg));
writeSkeleton(startText + "%%%" + segId++ + "%%%\n" + endText); //$NON-NLS-1$ //$NON-NLS-2$
}
/**
* Tidy.
* @param seg
* the seg
* @return the string
* @throws SAXException
* the SAX exception
* @throws IOException
* Signals that an I/O exception has occurred.
*/
private String tidy(String seg) throws SAXException, IOException {
startText = ""; //$NON-NLS-1$
endText = ""; //$NON-NLS-1$
List<Node> start = new ArrayList<Node>();
List<Node> end = new ArrayList<Node>();
List<Node> txt = new ArrayList<Node>();
SAXBuilder b = new SAXBuilder();
Document d = b.build(new ByteArrayInputStream(seg.getBytes("utf-8"))); //$NON-NLS-1$
Element r = d.getRootElement();
Element s = r.getChild("source"); //$NON-NLS-1$
if (s.getChildren().size() == 0) {
return seg;
}
List<Node> content = s.getContent();
int i = 0;
// skip initial tags
for (i = 0; i < content.size(); i++) {
Node n = content.get(i);
if (n.getNodeType() == Node.TEXT_NODE) {
if (!n.getNodeValue().trim().equals("")) { //$NON-NLS-1$
// txt.add(n);
break;
}
start.add(n);
} else {
start.add(n);
}
}
// skip text nodes
for (; i < content.size(); i++) {
Node n = content.get(i);
if (n.getNodeType() != Node.TEXT_NODE) {
// end.add(n);
break;
}
txt.add(n);
}
// skip final tags
for (; i < content.size(); i++) {
Node n = content.get(i);
if (n.getNodeType() == Node.TEXT_NODE) {
if (!n.getNodeValue().trim().equals("")) { //$NON-NLS-1$
break;
}
end.add(n);
} else {
end.add(n);
}
}
if (i == content.size()) {
// OK, tags are only at start and end
for (i = 0; i < start.size(); i++) {
Node n = start.get(i);
if (n.getNodeType() == Node.TEXT_NODE) {
startText += n.getNodeValue();
}
if (n.getNodeType() == Node.ELEMENT_NODE) {
startText += (new Element(n).getText()).toString();
}
}
for (i = 0; i < end.size(); i++) {
Node n = end.get(i);
if (n.getNodeType() == Node.TEXT_NODE) {
endText += n.getNodeValue();
}
if (n.getNodeType() == Node.ELEMENT_NODE) {
endText += (new Element(n).getText()).toString();
}
}
s.setContent(txt);
}
return r.toString();
}
/**
* Contains text.
* @param tagged
* the tagged
* @return true, if contains text
*/
private boolean containsText(String tagged) {
int start = tagged.indexOf("<ph"); //$NON-NLS-1$
int end = tagged.indexOf("</ph>"); //$NON-NLS-1$
while (start != -1) {
tagged = tagged.substring(0, start) + tagged.substring(end + 5);
start = tagged.indexOf("<ph"); //$NON-NLS-1$
end = tagged.indexOf("</ph>"); //$NON-NLS-1$
}
tagged = tagged.trim();
if (tagged.length() == 0) {
return false;
}else{
return true;
}
// 修改将数字以及其他的字符显示出来
// for (int i = 0; i < tagged.length(); i++) {
// int c = tagged.charAt(i);
// if ("$€£¥¢(){}0123456789%.,-‐‑‒—―".indexOf(c) == -1) { //$NON-NLS-1$
// return true;
// }
// /*
// * if (c < 8192 || c > 8303) { return true; }
// */
// }
// return false;
}
/**
* Normalize.
* @param string
* the string
* @return the string
*/
private String normalize(String string) {
string = string.replace('\n', ' ');
string = string.replace('\t', ' ');
string = string.replace('\r', ' ');
string = string.replace('\f', ' ');
String rs = ""; //$NON-NLS-1$
int length = string.length();
for (int i = 0; i < length; i++) {
char ch = string.charAt(i);
if (!Character.isSpaceChar(ch)) {
rs = rs + ch;
} else {
rs = rs + " "; //$NON-NLS-1$
while (i < (length - 1) && Character.isSpaceChar(string.charAt(i + 1))) {
i++;
}
}
}
return rs;
}
/**
* Adds the tags.
* @param src
* the src
* @return the string
* @throws IOException
* Signals that an I/O exception has occurred.
*/
private String addTags(String src) throws IOException {
String result = ""; //$NON-NLS-1$
int start = src.indexOf("<"); //$NON-NLS-1$
int end = src.indexOf(">"); //$NON-NLS-1$
while (start != -1) {
if (start > 0) {
result = result + cleanString(src.substring(0, start));
src = src.substring(start);
start = src.indexOf("<"); //$NON-NLS-1$
end = src.indexOf(">"); //$NON-NLS-1$
}
String element = src.substring(start, end + 1);
// if(element.length() == 0){
// break;
// }
String tagged = tag(element);
result = result + tagged;
src = src.substring(end + 1);
start = src.indexOf("<"); //$NON-NLS-1$
end = src.indexOf(">"); //$NON-NLS-1$
}
result = result + cleanString(src);
return result;
}
/**
* Tag.
* @param element
* the element
* @return the string
* @throws IOException
* Signals that an I/O exception has occurred.
*/
private String tag(String element) throws IOException {
String result = ""; //$NON-NLS-1$
String type = getType(element);
if (translatableAttributes.containsKey(type)) {
result = extractAttributes(type, element);
} else {
String ctype = ""; //$NON-NLS-1$
if (ctypes.containsKey(type)) {
ctype = " ctype=\"" + ctypes.get(type) + "\""; //$NON-NLS-1$ //$NON-NLS-2$
}
result = "<ph id=\"" + tagId++ + "\"" + ctype + ">" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ cleanString(element) + "</ph>"; //$NON-NLS-1$
}
return result;
}
/**
* Clean string.
* @param s
* the s
* @return the string
* @throws IOException
* Signals that an I/O exception has occurred.
*/
private String cleanString(String s) throws IOException {
int control = s.indexOf("&"); //$NON-NLS-1$
while (control != -1) {
int sc = s.indexOf(";", control); //$NON-NLS-1$
if (sc == -1) {
// no semicolon, it's not an entity
s = s.substring(0, control) + "&" //$NON-NLS-1$
+ s.substring(control + 1);
} else {
// may be an entity
String candidate = s.substring(control, sc) + ";"; //$NON-NLS-1$
if (!candidate.equals("&")) { //$NON-NLS-1$
String entity = entities.get(candidate);
if (entity != null) {
s = s.substring(0, control) + entity + s.substring(sc + 1);
} else {
s = s.substring(0, control) + "%%%ph id=\"" + tagId++ //$NON-NLS-1$
+ "\"%%%&" + candidate.substring(1) //$NON-NLS-1$
+ "%%%/ph%%%" + s.substring(sc + 1); //$NON-NLS-1$
}
}
// remarked by john. fixed a bug 1107 by john.
// } else {
// // it is an "&"
// s = s.substring(0, control) + "&" //$NON-NLS-1$
// + s.substring(control + 1);
// }
}
if (control < s.length()) {
control++;
}
control = s.indexOf("&", control); //$NON-NLS-1$
}
control = s.indexOf("<"); //$NON-NLS-1$
while (control != -1) {
s = s.substring(0, control) + "<" + s.substring(control + 1); //$NON-NLS-1$
if (control < s.length()) {
control++;
}
control = s.indexOf("<", control); //$NON-NLS-1$
}
control = s.indexOf(">"); //$NON-NLS-1$
while (control != -1) {
s = s.substring(0, control) + ">" + s.substring(control + 1); //$NON-NLS-1$
if (control < s.length()) {
control++;
}
control = s.indexOf(">", control); //$NON-NLS-1$
}
s = s.replaceAll("%%%/ph%%%", "</ph>"); //$NON-NLS-1$ //$NON-NLS-2$
s = s.replaceAll("%%%ph", "<ph"); //$NON-NLS-1$ //$NON-NLS-2$
s = s.replaceAll("\"%%%&", "\">&"); //$NON-NLS-1$ //$NON-NLS-2$
return XMLOutputter.validChars(s);
}
/**
* 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 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$
}
/**
* Extract attributes.
* @param type
* the type
* @param element
* the element
* @return the string
* @throws IOException
* Signals that an I/O exception has occurred.
*/
private String extractAttributes(String type, String element) throws IOException {
String ctype = ""; //$NON-NLS-1$
if (ctypes.containsKey(type)) {
ctype = " ctype=\"" + ctypes.get(type) + "\""; //$NON-NLS-1$ //$NON-NLS-2$
}
String result = "<ph id=\"" + tagId++ + "\"" + ctype + ">"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
element = cleanString(element);
Vector<String> v = translatableAttributes.get(type);
StringTokenizer tokenizer = new StringTokenizer(element, "&= \t\n\r\f/", //$NON-NLS-1$
true);
while (tokenizer.hasMoreTokens()) {
String token = tokenizer.nextToken();
if (!v.contains(token)) {
result = result + token;
} else {
result = result + token;
String s = tokenizer.nextToken();
while (s.equals("=") || s.equals(" ")) { //$NON-NLS-1$ //$NON-NLS-2$
result = result + s;
s = tokenizer.nextToken();
}
// s contains the first word of the attribute
if (((s.startsWith("\"") && s.endsWith("\"")) || (s //$NON-NLS-1$ //$NON-NLS-2$
.startsWith("'") && s.endsWith("'"))) //$NON-NLS-1$ //$NON-NLS-2$
&& s.length() > 1) {
// the value is one word and it is quoted
result = result + s.substring(0, 1) + "</ph>" //$NON-NLS-1$
+ s.substring(1, s.length() - 1) + "<ph id=\"" //$NON-NLS-1$
+ tagId++ + "\">" + s.substring(s.length() - 1); //$NON-NLS-1$
} else {
if (s.startsWith("\"") || s.startsWith("'")) { //$NON-NLS-1$ //$NON-NLS-2$
// attribute value is quoted, but it has more than
// one
// word
String quote = s.substring(0, 1);
result = result + s.substring(0, 1) + "</ph>" //$NON-NLS-1$
+ s.substring(1);
s = tokenizer.nextToken();
do {
result = result + s;
if (tokenizer.hasMoreElements()) {
s = tokenizer.nextToken();
}
} while (s.indexOf(quote) == -1);
String left = s.substring(0, s.indexOf(quote));
String right = s.substring(s.indexOf(quote));
result = result + left + "<ph id=\"" + tagId++ + "\">" //$NON-NLS-1$ //$NON-NLS-2$
+ right;
} else {
// attribute is not quoted, it can only be one word
result = result + "</ph>" + s + "<ph id=\"" + tagId++ //$NON-NLS-1$ //$NON-NLS-2$
+ "\">"; //$NON-NLS-1$
}
}
}
}
result = result + "</ph>"; //$NON-NLS-1$
return result;
}
/**
* Builds the tables.
* @param iniFile
* the ini file
* @throws SAXException
* the SAX exception
* @throws IOException
* Signals that an I/O exception has occurred.
* @throws ParserConfigurationException
* the parser configuration exception
*/
private void buildTables(String iniFile, IProgressMonitor monitor) throws SAXException, IOException,
ParserConfigurationException {
SAXBuilder builder = new SAXBuilder();
builder.setEntityResolver(new Catalogue(catalogue));
Document doc = builder.build(iniFile);
Element rt = doc.getRootElement();
List<Element> tags = rt.getChildren("tag"); //$NON-NLS-1$
startsSegment = new Hashtable<String, String>();
translatableAttributes = new Hashtable<String, Vector<String>>();
ignore = new Hashtable<String, String>();
ctypes = new Hashtable<String, String>();
keepFormating = new Hashtable<String, String>();
inline = new Hashtable<String, String>();
// 设置任务数量
int size = tags.size();
monitor.beginTask(Messages.getString("xml.Xml2Xliff.task3"), size);
monitor.subTask("");
Iterator<Element> i = tags.iterator();
while (i.hasNext()) {
// 检查取消操作
if (monitor.isCanceled()) {
throw new OperationCanceledException(Messages.getString("xml.cancel"));
}
monitor.worked(1);
Element t = i.next();
if (t.getAttributeValue("hard-break", "inline").equals("yes") || t.getAttributeValue("hard-break", "inline").equals("segment")) { //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$
startsSegment.put(t.getText(), "yes"); //$NON-NLS-1$
} else if (t.getAttributeValue("hard-break", "inline").equals("no") || t.getAttributeValue("hard-break", "inline").equals("inline")) { //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$
inline.put(t.getText(), "yes"); //$NON-NLS-1$
} else {
ignore.put(t.getText(), "yes"); //$NON-NLS-1$
}
if (t.getAttributeValue("keep-format", "no").equals("yes")) { //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
keepFormating.put(t.getText(), "yes"); //$NON-NLS-1$
}
String attributes = t.getAttributeValue("attributes", ""); //$NON-NLS-1$ //$NON-NLS-2$
if (!attributes.equals("")) { //$NON-NLS-1$
StringTokenizer tokenizer = new StringTokenizer(attributes, ";"); //$NON-NLS-1$
int count = tokenizer.countTokens();
Vector<String> v = new Vector<String>(count);
for (int j = 0; j < count; j++) {
v.add(tokenizer.nextToken());
}
translatableAttributes.put(t.getText(), v);
}
String ctype = t.getAttributeValue("ctype", ""); //$NON-NLS-1$ //$NON-NLS-2$
if (!ctype.equals("")) { //$NON-NLS-1$
ctypes.put(t.getText(), ctype);
}
t = null;
}
tags = null;
rt = null;
doc = null;
builder = null;
monitor.done();
}
/**
* Builds the list.
* @throws Exception
* the exception
*/
private void buildList(IProgressMonitor monitor) throws Exception {
monitor.beginTask(Messages.getString("xml.Xml2Xliff.task4"), IProgressMonitor.UNKNOWN);
monitor.subTask("");
segments = new ArrayList<String>();
text = ""; //$NON-NLS-1$
Node n = root.getElement();
parseNode(n);
segments.add(text);
monitor.done();
}
/**
* Parses the node.
* @param n
* the n
* @throws Exception
* the exception
*/
private void parseNode(Node n) throws Exception {
switch (n.getNodeType()) {
case Node.ATTRIBUTE_NODE:
throw new Exception(Messages.getString("xml.Xml2Xliff.msg4") + n); //$NON-NLS-1$
case Node.CDATA_SECTION_NODE:
segments.add(text);
CDATASection cdata = (CDATASection) n;
segments.add("" + '\u007F' + '\u007F' + "<![CDATA[" + cdata.getNodeValue() + "]]>"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
translatable = ""; //$NON-NLS-1$
text = ""; //$NON-NLS-1$
break;
case Node.COMMENT_NODE:
segments.add(text);
segments.add("" + '\u007F' + '\u007F' + "<!--" + n.getNodeValue() + "-->"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
translatable = ""; //$NON-NLS-1$
text = ""; //$NON-NLS-1$
break;
case Node.DOCUMENT_FRAGMENT_NODE:
throw new Exception(Messages.getString("xml.Xml2Xliff.msg5") + n); //$NON-NLS-1$
case Node.DOCUMENT_NODE:
throw new Exception(Messages.getString("xml.Xml2Xliff.msg6") + n); //$NON-NLS-1$
case Node.DOCUMENT_TYPE_NODE:
throw new Exception(Messages.getString("xml.Xml2Xliff.msg7") + n); //$NON-NLS-1$
case Node.ELEMENT_NODE:
Element e = new Element(n);
if (startsSegment.containsKey(e.getName())) {
segments.add(text);
text = ""; //$NON-NLS-1$
translatable = ""; //$NON-NLS-1$
stack = null;
stack = new Stack<String>();
stack.push(e.getName());
if (!keepFormating.containsKey(e.getName())
&& !e.getAttributeValue("xml:space", "default").equals("preserve")) { //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
normalizeElement(e);
}
}
if (ignore.containsKey(e.getName())) {
segments.add(text);
segments.add("" + '\u007F' + "" + '\u007F' + e.toString()); //$NON-NLS-1$ //$NON-NLS-2$
text = ""; //$NON-NLS-1$
translatable = ""; //$NON-NLS-1$
stack = null;
stack = new Stack<String>();
return;
}
if (stack.size() == 0 && e.getChildren().size() == 0
&& !translatableAttributes.containsKey(e.getName())) {
if (inline.containsKey(e.getName()) && !e.getText().equals("")) { //$NON-NLS-1$
segments.add(text);
text = ""; //$NON-NLS-1$
translatable = ""; //$NON-NLS-1$
stack = null;
stack = new Stack<String>();
stack.push(e.getName());
if (!keepFormating.containsKey(e.getName())
&& !e.getAttributeValue("xml:space", "default").equals("preserve")) { //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
normalizeElement(e);
}
} else {
segments.add(text);
text = ""; //$NON-NLS-1$
translatable = ""; //$NON-NLS-1$
segments.add('\u007F' + "" + '\u007F' + e.toString()); //$NON-NLS-1$
break;
}
}
if (stack.size() > 0 && !startsSegment.containsKey(e.getName())) {
stack.push(e.getName());
}
List<Attribute> attributes = e.getAttributes();
text = text + "<" + e.getName(); //$NON-NLS-1$
if (attributes.size() > 0) {
for (int i = 0; i < attributes.size(); i++) {
Attribute a = attributes.get(i);
Vector<String> attr = translatableAttributes.get(e.getName());
if (translatableAttributes.containsKey(e.getName()) && attr.contains(a.getName())) {
//
// This is a translatable attribute and all quotes
// should be escaped at reverse conversion time
//
if (!text.startsWith("" + '\u007F' + '\u007F')) { //$NON-NLS-1$
text = "" + '\u007F' + '\u007F' + text; //$NON-NLS-1$
}
segments.add(text + " " + a.getName() + "=\""); //$NON-NLS-1$ //$NON-NLS-2$
segments.add('\u0080' + cleanAttribute(a.getValue()));
segments.add("" + '\u007F' + '\u007F' + "\""); //$NON-NLS-1$ //$NON-NLS-2$
text = ""; //$NON-NLS-1$
translatable = ""; //$NON-NLS-1$
} else {
if (!inline.containsKey(e.getName())
&& !text.startsWith("" + '\u007F' + '\u007F') && translatable.length() == 0) { //$NON-NLS-1$
text = "" + '\u007F' + '\u007F' + text; //$NON-NLS-1$
}
text = text + " " + a.getName() + "=\"" + cleanAttribute(a.getValue()) + "\""; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
}
}
}
List<Node> content = e.getContent();
if (content.size() == 0) {
if (text.equals("")) { //$NON-NLS-1$
text = "" + '\u007F' + '\u007F' + "/>"; //$NON-NLS-1$ //$NON-NLS-2$
} else {
text = text + "/>"; //$NON-NLS-1$
}
} else {
if (!inline.containsKey(e.getName())) {
if (!text.equals("")) { //$NON-NLS-1$
segments.add(text + ">"); //$NON-NLS-1$
text = ""; //$NON-NLS-1$
} else {
segments.add("" + '\u007F' + '\u007F' + ">"); //$NON-NLS-1$ //$NON-NLS-2$
}
translatable = ""; //$NON-NLS-1$
} else {
if (!text.equals("")) { //$NON-NLS-1$
text = text + ">"; //$NON-NLS-1$
} else {
segments.add("" + '\u007F' + '\u007F' + ">"); //$NON-NLS-1$ //$NON-NLS-2$
translatable = ""; //$NON-NLS-1$
}
}
for (int i = 0; i < content.size(); i++) {
parseNode(content.get(i));
}
if (startsSegment.containsKey(e.getName())) {
segments.add(text);
text = ""; //$NON-NLS-1$
translatable = ""; //$NON-NLS-1$
}
if (!text.equals("")) { //$NON-NLS-1$
text = text + "</" + e.getName() + ">"; //$NON-NLS-1$ //$NON-NLS-2$
} else {
segments.add("" + '\u007F' + '\u007F' + "</" + e.getName() + ">"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
}
}
if (stack.size() > 0) {
stack.pop();
}
break;
case Node.ENTITY_NODE:
throw new Exception(Messages.getString("xml.Xml2Xliff.msg8") + n); //$NON-NLS-1$
case Node.ENTITY_REFERENCE_NODE:
EntityReference er = (EntityReference) n;
String name = "&" + er.getNodeName() + ';'; //$NON-NLS-1$
if (entities.containsKey(name)) {
text = text + entities.get(name);
} else {
text = text + name;
}
break;
case Node.NOTATION_NODE:
throw new Exception(Messages.getString("xml.Xml2Xliff.msg9") + n); //$NON-NLS-1$
case Node.PROCESSING_INSTRUCTION_NODE:
ProcessingInstruction pi = (ProcessingInstruction) n;
if (inDesign && !translatable.trim().equals("")) { //$NON-NLS-1$
text = text + "<?" + pi.getNodeName() + " " + pi.getData() + "?>"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
} else {
segments.add(text);
segments.add("" + '\u007F' + '\u007F' + "<?" + pi.getNodeName() + " " + pi.getData() + "?>"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
text = ""; //$NON-NLS-1$
translatable = ""; //$NON-NLS-1$
}
break;
case Node.TEXT_NODE:
String value = n.getNodeValue();
value = value.replaceAll("&", "&"); //$NON-NLS-1$ //$NON-NLS-2$
value = value.replaceAll("<", "<"); //$NON-NLS-1$ //$NON-NLS-2$
value = value.replaceAll(">", ">"); //$NON-NLS-1$ //$NON-NLS-2$
text = text + value;
if (value.trim().length() > 0) {
translatable = translatable + value;
}
if (value.trim().length() > 0 && text.startsWith("" + '\u007F' + '\u007F')) { //$NON-NLS-1$
for (int j = 0; j < stack.size(); j++) {
if (startsSegment.containsKey(stack.get(j))) {
text = text.substring(2);
break;
}
}
}
break;
default:
break;
}
}
/**
* Normalize element.
* @param e
* the e
*/
private void normalizeElement(Element e) {
List<Node> l = e.getContent();
Iterator<Node> i = l.iterator();
List<Node> normal = new Vector<Node>();
while (i.hasNext()) {
Node n = i.next();
if (n.getNodeType() == Node.TEXT_NODE) {
String value = n.getNodeValue();
value = normalize(value);
n.setNodeValue(value);
}
if (n.getNodeType() == Node.ELEMENT_NODE) {
Element e1 = new Element(n);
if (!keepFormating.containsKey(e1.getName())
&& !e1.getAttributeValue("xml:space", "default").equals("preserve")) { //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
normalizeElement(e1);
n = e1.getElement();
}
}
normal.add(n);
}
e.setContent(normal);
}
/**
* Clean attribute.
* @param value
* the value
* @return the string
*/
private String cleanAttribute(String value) {
if (stack.size() > 1 && !text.startsWith("" + '\u007F' + '\u007F')) { //$NON-NLS-1$
// this is an inline element and will be placed in <ph>
value = value.replaceAll("&", "&amp;"); //$NON-NLS-1$ //$NON-NLS-2$
} else {
value = value.replaceAll("&", "&"); //$NON-NLS-1$ //$NON-NLS-2$
}
value = value.replaceAll(">", ">"); //$NON-NLS-1$ //$NON-NLS-2$
value = value.replaceAll("<", "<"); //$NON-NLS-1$ //$NON-NLS-2$
value = value.replaceAll("\"", """); //$NON-NLS-1$ //$NON-NLS-2$
return value;
}
/**
* Gets the type.
* @param string
* the string
* @return the type
*/
private String getType(String string) {
String result = ""; //$NON-NLS-1$
if (string.startsWith("<![CDATA[")) {return "![CDATA[";} //$NON-NLS-1$ //$NON-NLS-2$
if (string.startsWith("<!--")) {return "!--";} //$NON-NLS-1$ //$NON-NLS-2$
if (string.startsWith("<?")) {return "?";} //$NON-NLS-1$ //$NON-NLS-2$
if (!string.equals("")) { //$NON-NLS-1$
// skip initial "<"
string = string.substring(1);
}
for (int i = 0; i < string.length(); i++) {
char c = string.charAt(i);
if (c == ' ' || c == '\n' || c == '\f' || c == '\t' || c == '\r' || c == '>') {
break;
}
result = result + c;
}
if (result.endsWith("/") && result.length() > 1) { //$NON-NLS-1$
result = result.substring(0, result.length() - 1);
}
return result;
}
/**
* Gets the encoding.
* @param fileName
* the file name
* @return the encoding
* @throws Exception
* the exception
*/
public String getEncoding(String fileName) throws Exception {
// 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
// return UTF-8 as default
String result = "UTF-8"; //$NON-NLS-1$
FileReader in = new FileReader(fileName);
BufferedReader buffer = new BufferedReader(in);
String line = buffer.readLine();
in.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$
}
}
}
return result;
}
}
} | 51,302 | 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.xml/src/net/heartsome/cat/converter/xml/resource/Messages.java | /**
* Messages.java
*
* Version information :
*
* Date:Jan 14, 2010
*
* Copyright notice :
*/
package net.heartsome.cat.converter.xml.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.xml.resource.xml"; //$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 |
CommentBean.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.wordfast3/src/net/heartsome/cat/converter/wordfast3/CommentBean.java | package net.heartsome.cat.converter.wordfast3;
/**
* 批注的 pojo 类
* @author robert 2012-12-13
*/
public class CommentBean {
/** 标注的作者,对应 creationid */
private String user;
/** 标注的添加时间 对应 creationdate */
private String date;
/** 标注的类型,对应 type */
private String type;
/** 标注的文件 */
private String commentText;
/** wf 文件的批注节点的所有属性的字符串 */
private String commentAttrStr;
public CommentBean(){}
public CommentBean(String user, String date, String type, String commentText, String commentAttrStr){
this.user = user;
this.date = date;
this.type = type;
this.commentText = commentText;
this.commentAttrStr = commentAttrStr;
}
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 getCommentText() {
return commentText;
}
public void setCommentText(String commentText) {
this.commentText = commentText;
}
public String getCommentAttrStr() {
return commentAttrStr;
}
public void setCommentAttrStr(String commentAttrStr) {
this.commentAttrStr = commentAttrStr;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
| 1,389 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
Xliff2Wf.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.wordfast3/src/net/heartsome/cat/converter/wordfast3/Xliff2Wf.java | package net.heartsome.cat.converter.wordfast3;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.text.MessageFormat;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import org.eclipse.core.runtime.IProgressMonitor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.ximpleware.AutoPilot;
import com.ximpleware.VTDGen;
import com.ximpleware.VTDNav;
import com.ximpleware.XMLModifier;
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.wordfast3.resource.Messages;
import net.heartsome.xml.vtdimpl.VTDUtils;
public class Xliff2Wf implements Converter {
/** The Constant TYPE_VALUE. */
public static final String TYPE_VALUE = "txml";
/** The Constant TYPE_NAME_VALUE. */
public static final String TYPE_NAME_VALUE = Messages.getString("utils.FileFormatUtils.WF");
/** The Constant NAME_VALUE. */
public static final String NAME_VALUE = "XLIFF to TXML Conveter";
public static final Logger LOGGER = LoggerFactory.getLogger(Xliff2Wf.class);
@Override
public Map<String, String> convert(Map<String, String> args,
IProgressMonitor monitor) throws ConverterException {
Xliff2WfImpl xliff2DuImpl = new Xliff2WfImpl();
return xliff2DuImpl.run(args, monitor);
}
@Override
public String getName() {
return NAME_VALUE;
}
@Override
public String getType() {
return TYPE_VALUE;
}
@Override
public String getTypeName() {
return TYPE_NAME_VALUE;
}
class Xliff2WfImpl{
/** 逆转换的结果文件 */
private String outputFile;
/** 骨架文件的解析游标 */
private VTDNav outputVN;
/** 骨架文件的修改类实例 */
private XMLModifier outputXM;
/** 骨架文件的查询实例 */
private AutoPilot outputAP;
/** hsxliff文件的解析游标 */
private VTDNav hsxlfVN;
/** The encoding. */
private String encoding;
public Map<String, String> run(Map<String, String> params, IProgressMonitor monitor) throws ConverterException {
monitor = Progress.getMonitor(monitor);
// 把转换过程分为两大部分共 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);
ananysisXlfTU();
outputXM.output(outputFile);
} catch (Exception e) {
e.printStackTrace();
LOGGER.error("", e);
String errorTip = Messages.getString("xlf2wf.msg1") + "\n" + e.getMessage();
ConverterUtils.throwConverterException(Activator.PLUGIN_ID, errorTip, e);
}finally{
monitor.done();
}
result.put(Converter.ATTR_TARGET_FILE, outputFile);
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);
}else {
String errorInfo = MessageFormat.format(Messages.getString("wf.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)) {
hsxlfVN = vg.getNav();
}else {
String errorInfo = MessageFormat.format(Messages.getString("wf.parse.msg1"),
new Object[]{new File(xliffFile).getName()});
throw new Exception(errorInfo);
}
}
/**
* 分析xliff文件的每一个 trans-unit 节点
* @throws Exception
*/
private void ananysisXlfTU() throws Exception {
AutoPilot ap = new AutoPilot(hsxlfVN);
AutoPilot childAP = new AutoPilot(hsxlfVN);
VTDUtils vu = new VTDUtils(hsxlfVN);
String xpath = "/xliff/file/body//trans-unit";
String srcXpath = "./source";
String tgtXpath = "./target";
ap.selectXPath(xpath);
int attrIdx = -1;
//trans-unit的id,对应 wf 双语文件的占位符如%%%1%%% 。
String segId = "";
TuBean tuBean = null;
while (ap.evalXPath() != -1) {
if ((attrIdx = hsxlfVN.getAttrVal("id")) == -1) {
continue;
}
tuBean = new TuBean();
segId = hsxlfVN.toString(attrIdx);
//处理source节点
hsxlfVN.push();
childAP.selectXPath(srcXpath);
if (childAP.evalXPath() != -1) {
String srcContent = vu.getElementContent();
srcContent = srcContent == null ? "" : srcContent;
tuBean.setSrcContent(analysisTag(srcContent));
}
hsxlfVN.pop();
//处理target节点
String status = ""; //状态,针对target节点,空字符串为未翻译
hsxlfVN.push();
String tgtContent = null;
childAP.selectXPath(tgtXpath);
if (childAP.evalXPath() != -1) {
tgtContent = vu.getElementContent();
if ((attrIdx = hsxlfVN.getAttrVal("state")) != -1) {
status = hsxlfVN.toString(attrIdx);
}
}
tgtContent = tgtContent == null ? "" : tgtContent;
tuBean.setTgtContent(analysisTag(tgtContent));
hsxlfVN.pop(); //回到trans-unit节点下
// //判断是否处于锁定状态
// if ((attrIdx = hsxlfVN.getAttrVal("translate")) != -1) {
// if ("no".equalsIgnoreCase(hsxlfVN.toString(attrIdx))) {
// tgtBean.setLocked(true);
// }
// }
// //判断是否处于批准状态,若是签发,就没有必要判断了,因为签发了的一定就批准了的
// if (!"signed-off".equalsIgnoreCase(status)) {
// if ((attrIdx = hsxlfVN.getAttrVal("approved")) != -1) {
// if ("yes".equalsIgnoreCase(hsxlfVN.toString(attrIdx))) {
// status = "approved"; //批准
// }
// }
// }
//
// //如果是锁定了的。在deja vu里面的完成翻译状态变成未完成翻译。
// if (tgtBean.isLocked()) {
// status = "needs-translation";
// }else {
// //将状态切换成du xliff的格式
// if ("approved".equals(status) || "signed-off".equals(status)) {
// status = "finish";
// }else {
// status = "needs-translation";
// }
//
// //判断是否有疑问这个属性
// if (!"finish".equals(status)) {
// if ((attrIdx = hsxlfVN.getAttrVal("hs:needs-review")) != -1) {
// if ("yes".equals(hsxlfVN.toString(attrIdx))) {
// status = "needs-review-translation";
// }
// }
// }
// }
//
// tgtBean.setStatus(status);
//获取批注
getNotes(hsxlfVN, tuBean);
replaceSegment(segId, tuBean);
}
}
/**
* 替换掉骨架文件中的占位符
* @param segId
* @param srcBean
* @param tgtbeBean
*/
private void replaceSegment(String segId, TuBean tuBean) throws Exception {
String segStr = "%%%" + segId + "%%%";
String segXpath = "/txml/translatable/descendant::segment[source/text()='" + segStr + "' or target/text()='" + segStr + "']";
String srcXpath = "./source";
String tgtXapth = "./target";
AutoPilot childAp = new AutoPilot(outputVN);
outputAP.selectXPath(segXpath);
if (outputAP.evalXPath() != -1) {
StringBuffer addedSb = new StringBuffer();
// 开始处理源文
outputVN.push();
childAp.selectXPath(srcXpath);
if (childAp.evalXPath() != -1) {
int textIdx = outputVN.getText();
outputXM.updateToken(textIdx, tuBean.getSrcContent().getBytes("utf-8"));
}
outputVN.pop();
// 开始处理译文
String tgtContent = tuBean.getTgtContent();
if (tgtContent != null && !"".equals(tgtContent)) {
boolean tgtExsit = false;
outputVN.push();
childAp.selectXPath(tgtXapth);
if (childAp.evalXPath() != -1) {
int textIdx = outputVN.getText();
outputXM.updateToken(textIdx, tgtContent.getBytes("utf-8"));
tgtExsit = true;
}
outputVN.pop();
if (!tgtExsit) {
String tgtFrag = "<target>" + tgtContent + "</target>";
addedSb.append(tgtFrag);
}
}
// 开始处理批注信息
List<CommentBean> commentList = tuBean.getCommentList();
if (commentList != null && commentList.size() > 0) {
StringBuffer commentSB = new StringBuffer();
commentSB.append("<comments>");
for(CommentBean bean : commentList){
String user = bean.getUser();
String date = bean.getDate();
String type = bean.getType();
String commentText = bean.getCommentText();
if (date == null || "".equals(date)) {
date = "000-00-00";
}
date = getUTCDateStr(date);
commentSB.append("<comment creationid=\"" + user + "\" creationdate=\"" + date + "\" type=\"" + type + "\">");
commentSB.append(commentText);
commentSB.append("</comment>");
}
commentSB.append("</comments>");
addedSb.append(commentSB);
}
outputXM.insertBeforeTail(addedSb.toString().getBytes("utf-8"));
}
}
private void getNotes(VTDNav vn, TuBean tuBean) throws Exception {
List<CommentBean> commentList = new LinkedList<CommentBean>();
vn.push();
AutoPilot ap = new AutoPilot(vn);
String xpath = "./note";
ap.selectXPath(xpath);
String commentText = "";
int attrIdx = -1;
while(ap.evalXPath() != -1){
attrIdx = vn.getAttrVal("from");
String user = "";
String date = "";
String type = "text";
if (attrIdx != -1) {
user = vn.toRawString(attrIdx);
}
if (vn.getText() != -1) {
String r8NoteText = vn.toString(vn.getText());
if (r8NoteText.indexOf(":") != -1) {
commentText += r8NoteText.substring(r8NoteText.indexOf(":") + 1, r8NoteText.length());
date = r8NoteText.substring(0, r8NoteText.indexOf(":"));
}else {
commentText += r8NoteText;
}
}
commentList.add(new CommentBean(user, date, type, commentText, null));
}
if (commentText.length() > 0) {
commentText = commentText.substring(0, commentText.length() - 1);
}
tuBean.setCommentList(commentList);
vn.pop();
}
}
//----------------------------------------------------Xliff2DuImpl 结束标志--------------------------------------------//
/**
* 将一个文件的数据复制到另一个文件
* @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) {
String comment = "this is a comment;\n";
System.out.println(comment.substring(0, comment.length() - 1));
System.out.println(getUTCDateStr("0000-00-00"));
}
/**
* 转换时间
* @param strDate
* @return
*/
public static String getUTCDateStr(String strDate) {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
ParsePosition pos = new ParsePosition(0);
Date str2Date = formatter.parse(strDate, pos);
SimpleDateFormat formatter_1 = new SimpleDateFormat("yyyyMMdd'T'HHmmss'Z'");
return formatter_1.format(str2Date);
}
/**
* 将 wf 文件中的 ut 标记换成 ph 标记
* @param text
* @return
*/
private static String analysisTag(String text){
//<ut type="content" x="1"><fontformat color="0#0#0"><b></ut>
text = text.replace("<ph ", "<ut ");
text = text.replace("ph>", "ut>");
return text;
}
}
| 12,367 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
TuBean.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.wordfast3/src/net/heartsome/cat/converter/wordfast3/TuBean.java | package net.heartsome.cat.converter.wordfast3;
import java.util.List;
/**
* wordFast 的 txml 文件与 hsxliff 文件的翻译单元的 pojo 类
* @author robert 2012-12-13
*/
public class TuBean {
private String srcContent;
private String tgtContent;
/** 匹配率 */
private String match;
private List<CommentBean> commentList;
public TuBean(){}
public TuBean(String srcContent, String tgtContent, String match, List<CommentBean> commentList){
this.srcContent = srcContent;
this.tgtContent = tgtContent;
this.match = match;
this.commentList = commentList;
}
public String getSrcContent() {
return srcContent;
}
public void setSrcContent(String srcContent) {
this.srcContent = srcContent;
}
public String getTgtContent() {
return tgtContent;
}
public void setTgtContent(String tgtContent) {
this.tgtContent = tgtContent;
}
public String getMatch() {
return match;
}
public void setMatch(String match) {
this.match = match;
}
public List<CommentBean> getCommentList() {
return commentList;
}
public void setCommentList(List<CommentBean> commentList) {
this.commentList = commentList;
}
}
| 1,159 | 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.wordfast3/src/net/heartsome/cat/converter/wordfast3/TagBean.java | package net.heartsome.cat.converter.wordfast3;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* 标记的 pojo 类
* @author robert 2012-12-19
*/
public class TagBean {
private String content;
private String frag;
private Map<String, String> attributesMap = new LinkedHashMap<String, String>();
public TagBean(){}
public TagBean(String content, String frag, Map<String, String> attributesMap){
this.content = content;
this.frag = frag;
this.attributesMap = attributesMap;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getFrag() {
return frag;
}
public void setFrag(String frag) {
this.frag = frag;
}
public Map<String, String> getAttributesMap() {
return attributesMap;
}
public void setAttributesMap(Map<String, String> attributesMap) {
this.attributesMap = attributesMap;
}
}
| 930 | 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.wordfast3/src/net/heartsome/cat/converter/wordfast3/Activator.java | package net.heartsome.cat.converter.wordfast3;
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.BundleContext;
import org.osgi.framework.ServiceRegistration;
/**
* Wordfast Pro 双语 XML 文件 (TXML) Wordfast Pro bilingual XML file (TXML)
*/
public class Activator extends AbstractUIPlugin {
// The plug-in ID
public static final String PLUGIN_ID = "net.heartsome.cat.converter.wordfast3"; //$NON-NLS-1$
// The shared instance
private static Activator plugin;
/** wordFast3文件转换至xliff文件的服务注册器 */
@SuppressWarnings("rawtypes")
private ServiceRegistration wf2XliffSR;
/** xliff文件转换至wordFast3文件的服务注册器 */
@SuppressWarnings("rawtypes")
private ServiceRegistration xliff2WfSR;
/**
* 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 wf2Xliff = new Wf2Xliff();
Properties properties = new Properties();
properties.put(Converter.ATTR_NAME, Wf2Xliff.NAME_VALUE);
properties.put(Converter.ATTR_TYPE, Wf2Xliff.TYPE_VALUE);
properties.put(Converter.ATTR_TYPE_NAME, Wf2Xliff.TYPE_NAME_VALUE);
wf2XliffSR = ConverterRegister.registerPositiveConverter(context, wf2Xliff, properties);
Converter xliff2Wf = new Xliff2Wf();
properties = new Properties();
properties.put(Converter.ATTR_NAME, Xliff2Wf.NAME_VALUE);
properties.put(Converter.ATTR_TYPE, Xliff2Wf.TYPE_VALUE);
properties.put(Converter.ATTR_TYPE_NAME, Xliff2Wf.TYPE_NAME_VALUE);
xliff2WfSR = ConverterRegister.registerReverseConverter(context, xliff2Wf, properties);
}
/*
* (non-Javadoc)
* @see org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext)
*/
public void stop(BundleContext context) throws Exception {
if (wf2XliffSR != null) {
wf2XliffSR.unregister();
wf2XliffSR = null;
}
if (xliff2WfSR != null) {
xliff2WfSR.unregister();
xliff2WfSR = null;
}
plugin = null;
}
/**
* Returns the shared instance
*
* @return the shared instance
*/
public static Activator getDefault() {
return plugin;
}
}
| 2,378 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
Wf2Xliff.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.wordfast3/src/net/heartsome/cat/converter/wordfast3/Wf2Xliff.java | package net.heartsome.cat.converter.wordfast3;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.MessageFormat;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
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.util.ConverterUtils;
import net.heartsome.cat.converter.util.Progress;
import net.heartsome.cat.converter.wordfast3.resource.Messages;
import net.heartsome.util.CRC16;
import net.heartsome.util.TextUtil;
import net.heartsome.xml.vtdimpl.VTDUtils;
import org.eclipse.core.runtime.IProgressMonitor;
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;
public class Wf2Xliff implements Converter{
/** The Constant TYPE_VALUE. */
public static final String TYPE_VALUE = "txml";
/** The Constant TYPE_NAME_VALUE. */
public static final String TYPE_NAME_VALUE = Messages.getString("utils.FileFormatUtils.WF");
/** The Constant NAME_VALUE. */
public static final String NAME_VALUE = "TXML to XLIFF Conveter";
public static final Logger LOGGER = LoggerFactory.getLogger(Wf2Xliff.class);
@Override
public Map<String, String> convert(Map<String, String> args,
IProgressMonitor monitor) throws ConverterException {
Wf2XliffImpl converter = new Wf2XliffImpl();
return converter.run(args, monitor);
}
@Override
public String getName() {
return NAME_VALUE;
}
@Override
public String getType() {
return TYPE_VALUE;
}
@Override
public String getTypeName() {
return TYPE_NAME_VALUE;
}
class Wf2XliffImpl{
/** 源文件 */
private String inputFile;
/** 转换成的XLIFF文件(临时文件) */
private String xliffFile;
/** 骨架文件(临时文件) */
private String skeletonFile;
/** 源语言 */
private String userSourceLang;
/** 目标语言 */
private String targetLang;
/** 转换的编码格式 */
private String srcEncoding;
/** 将数据输出到XLIFF文件的输出流 */
private FileOutputStream output;
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);
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();
writeHeader();
analyzeNodes();
writeString("</body>\n");
writeString("</file>\n");
writeString("</xliff>");
sklXM.output(skeletonFile);
// 下一步是处理译文中的标记与源文中标记 不完全一致(属性的位置不一致,但是内容都是一样) 的情况。
// 比如:<ph x="1" type="unknown">&lt;p&gt;</ph> 与 <ph type="unknown" x="1" >&lt;p&gt;</ph>
makeTagTheSame();
}catch (Exception e) {
e.printStackTrace();
String errorTip = Messages.getString("wf2Xlf.msg1") + "\n" + e.getMessage();
ConverterUtils.throwConverterException(Activator.PLUGIN_ID, errorTip, e);
LOGGER.error("", e);
}finally{
try {
output.close();
} catch (Exception e2) {
e2.printStackTrace();
String errorTip = Messages.getString("wf2Xlf.msg1") + "\n" + e2.getMessage();
ConverterUtils.throwConverterException(Activator.PLUGIN_ID, errorTip, e2);
}
monitor.done();
}
return result;
}
/**
* 解析骨架文件,此时的骨架文件的内容就是源文件的内容
* @throws Exception
*/
private void parseSkeletonFile() throws Exception{
String errorInfo = "";
VTDGen vg = new VTDGen();
if (vg.parseFile(skeletonFile, true)) {
sklVN = vg.getNav();
sklXM = new XMLModifier(sklVN);
}else {
errorInfo = MessageFormat.format(Messages.getString("wf.parse.msg1"),
new Object[]{new File(inputFile).getName()});
throw new Exception(errorInfo);
}
}
private void writeString(String string) throws IOException {
output.write(string.getBytes("utf-8")); //$NON-NLS-1$
}
/**
* 写下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: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");
}
/**
* 分析每一个节点
* @throws Exception
*/
private void analyzeNodes() throws Exception{
AutoPilot ap = new AutoPilot(sklVN);
AutoPilot childAP = new AutoPilot(sklVN);
VTDUtils vu = new VTDUtils(sklVN);
String xpath = "/txml/translatable/descendant::segment";
String srxXpath = "./source";
String tgtXpath = "./target";
String commentXpath = "./comments/comment";
ap.selectXPath(xpath);
int attrIdx = -1;
//xliff 文件的 trans-unit 节点的 id 值
int segId = 0;
while (ap.evalXPath() != -1) {
TuBean tuBean = new TuBean();
sklVN.push();
childAP.selectXPath(srxXpath);
while (childAP.evalXPath() != -1) {
String srcContent = vu.getElementContent();
if (srcContent != null && !"".equals(srcContent)) {
tuBean.setSrcContent(analysisTag(srcContent));
//开始填充占位符
insertPlaceHolder(vu, segId);
}
}
sklVN.pop();
sklVN.push();
childAP.selectXPath(tgtXpath);
while (childAP.evalXPath() != -1) {
String tgtContent = vu.getElementContent();
if (tgtContent != null && !"".equals(tgtContent)) {
tuBean.setTgtContent(analysisTag(tgtContent));
}
attrIdx = sklVN.getAttrVal("score");
if (attrIdx != -1) {
String match = sklVN.toRawString(attrIdx);
tuBean.setMatch(match);
}
insertPlaceHolder(vu, segId);
}
sklVN.pop();
// 开始处理批注信息
sklVN.push();
childAP.selectXPath(commentXpath);
List<CommentBean> commnentList = new LinkedList<CommentBean>();
while(childAP.evalXPath() != -1){
// 获取添加者
String user = "";
attrIdx = sklVN.getAttrVal("creationid");
if (attrIdx != -1) {
user = sklVN.toRawString(attrIdx);
}
// 获取添加时间
String date = "";
attrIdx = sklVN.getAttrVal("creationdate");
if (attrIdx != -1) {
date = sklVN.toRawString(attrIdx);
}
// 获取批注类型
String type = "";
attrIdx = sklVN.getAttrVal("type");
if (attrIdx != -1) {
type = sklVN.toRawString(attrIdx);
}
// 获取批注类容
String commentText = "";
attrIdx = sklVN.getText();
if (attrIdx != -1) {
commentText = sklVN.toRawString(attrIdx);
}
commnentList.add(new CommentBean(user, date, type, commentText, null));
}
sklVN.pop();
// 删除所有的批注
sklVN.push();
childAP.selectXPath("./comments");
if (childAP.evalXPath() != -1) {
sklXM.remove();
}
sklVN.pop();
tuBean.setCommentList(commnentList);
writeSegment(tuBean, segId);
segId ++;
}
}
/**
* 给剔去翻译内容后的骨架文件填充占位符
* @throws Exception
*/
private void insertPlaceHolder(VTDUtils vu, int seg) throws Exception{
String mrkHeader = vu.getElementHead();
String nodeName = vu.getCurrentElementName();
String newMrkStr = mrkHeader + "%%%"+ seg +"%%%" + "</" + nodeName + ">";
sklXM.remove();
sklXM.insertAfterElement(newMrkStr.getBytes(srcEncoding));
}
/**
* 向XLIFF文件输入新生成的trans-unit节点
* @param srcContent
* @param tgtContent
* @param segId
* @throws Exception
*/
private void writeSegment(TuBean bean, int segId) throws Exception{
String srcContent = bean.getSrcContent();
String tgtContent = bean.getTgtContent();
List<CommentBean> commentList = bean.getCommentList();
srcContent = srcContent == null ? "" : srcContent;
tgtContent = tgtContent == null ? "" : tgtContent;
StringBuffer tuSB = new StringBuffer();
String tgtStatusStr = "";
String tuAttrStr = "";
// boolean isApproved = false;
// //具体的意思及与R8的转换请查看tgtBean.getStatus()的注释。
// if ("needs-translation".equals(status) || "".equals(status)) {
// if (tgtBean.getContent() != null && tgtBean.getContent().length() >= 1) {
// tgtStatusStr += " state=\"new\"";
// }
// }else if ("finish".equals(status)) {
// isApproved = true;
// tgtStatusStr += " state=\"translated\"";
// }else if ("needs-review-translation".equals(status)) {
// //疑问
// tuAttrStr += " hs:needs-review=\"yes\"";
// }
// tuAttrStr += isApproved ? " approved=\"yes\"" : "";
// tuAttrStr += tgtBean.isLocked() ? " translate=\"no\"" : "";
//
// tuSB.append(" <trans-unit" + tuAttrStr + " 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" + tgtStatusStr + " xml:lang=\"" +
// ((targetLang == null || "".equals(targetLang)) ? userSourceLang : targetLang) + "\">"
// + tgtContent + "</target>\n");
// }
// tuSB.append(" </trans-unit>\n");
if (!"".equals(tgtContent)) {
tgtStatusStr = " state=\"new\"";
}
String match = bean.getMatch();
if (match != null && !"".equals(match)) {
//hs:quality="101"
tgtStatusStr += " hs:quality=\"" + match + "\"";
}
tuSB.append(" <trans-unit" + tuAttrStr + " id=\"" + segId + "\" xml:space=\"preserve\" >\n");
tuSB.append(" <source xml:lang=\"" + userSourceLang + "\">" + srcContent + "</source>\n");
tuSB.append(" <target" + tgtStatusStr + " xml:lang=\"" +
((targetLang == null || "".equals(targetLang)) ? userSourceLang : targetLang) + "\">"
+ tgtContent + "</target>\n");
for(CommentBean commentBean : commentList){
String user = commentBean.getUser();
String date = commentBean.getDate();
date = getR8dateStrFromUTC(date);
String commentText = commentBean.getCommentText();
String hsCommentText = date + ":" + commentText;
tuSB.append(" <note from='" + user + "'>" + hsCommentText + "</note>");
}
tuSB.append(" </trans-unit>\n");
writeString(tuSB.toString());
}
/**
* 将译文与源文的标记整成一样的。
* @throws Exception
*/
private void makeTagTheSame() throws Exception{
VTDGen vg = new VTDGen();
if (!vg.parseFile(xliffFile, true)) {
String errorInfo = MessageFormat.format(Messages.getString("wf.parse.msg1"),
new Object[]{new File(inputFile).getName()});
throw new Exception(errorInfo);
}
VTDNav tagVN = vg.getNav();
AutoPilot tagAP = new AutoPilot(tagVN);
AutoPilot childAP = new AutoPilot(tagVN);
VTDUtils vu = new VTDUtils(tagVN);
XMLModifier xm = new XMLModifier(tagVN);
String xpath = "/xliff/file/body/descendant::trans-unit";
String srcPhXpath = "./source/ph";
String tgtPhXpath = "./target/ph";
String tgtXpath = "./target";
tagAP.selectXPath(xpath);
List<TagBean> tagList = new ArrayList<TagBean>();
tu:while(tagAP.evalXPath() != -1){
// 如果译文为空,不进行本次操作
boolean needContinu = false;
tagVN.push();
childAP.selectXPath(tgtXpath);
if (childAP.evalXPath() != -1) {
// 如果 ph 标记个数为0,不进行本次操作
if (vu.getChildElementsCount() <= 0) {
needContinu = true;
}
}else {
needContinu = true;
}
tagVN.pop();
if (needContinu) {
continue;
}
// 读取 源文,取出其中的标记
tagVN.push();
childAP.selectXPath(srcPhXpath);
while (childAP.evalXPath() != -1) {
String content = vu.getElementContent();
String frag = vu.getElementFragment();
Map<String, String> attributesMap = getElementAttributs(tagVN);
tagList.add(new TagBean(content, frag, attributesMap));
}
tagVN.pop();
// 如果源文中也没有标记,那么退出本次循环
if (tagList.size() <= 0) {
continue;
}
// 循环译文中的每一个标记
tagVN.push();
childAP.selectXPath(tgtPhXpath);
while(childAP.evalXPath() != -1){
// 如果源文中的标记都没得了。就没求的比头了。
if (tagList.size() <= 0) {
tagVN.pop();
continue tu;
}
String frag = vu.getElementFragment();
if (!fragEquls(frag, tagList)) {
analysisNotEqualsTag(xm, vu, tagVN, tagList);
}
}
tagVN.pop();
}
xm.output(xliffFile);
}
/**
* 验证是否相等
* @param frag
* @param tagList
* @return
*/
private boolean fragEquls(String frag , List<TagBean> tagList){
for (TagBean bean : tagList) {
if (frag.equals(bean.getFrag())) {
tagList.remove(bean);
return true;
}
}
return false;
}
/**
* 如果译文中的标记 fragment 在源文中找不到。那我们就开始比较是否属性错位了。如果错位,然后就然后。
* @param xm
* @param tagVN
* @param tagList
*/
private void analysisNotEqualsTag(XMLModifier xm, VTDUtils vu, VTDNav vn, List<TagBean> tagList) throws Exception{
vn.push();
Map<String, String> curAtrriMap = getElementAttributs(vn);
String curContent = vu.getElementContent();
boolean attriEquals = true; // 标记的属性是否相等
tagBeanFor:for (TagBean bean : tagList) {
Map<String, String> attriMap = bean.getAttributesMap();
if (curAtrriMap.size() != attriMap.size()) {
continue;
}
for (Entry<String, String> entry : attriMap.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
if (!(curAtrriMap.get(key) != null && value.equals(curAtrriMap.get(key)))) {
attriEquals = false;
continue tagBeanFor;
}
}
// 如果这个标记在源文中也存在(只是属性顺序不同),则开始删除目标中此标记,重新插入
String content = bean.getContent();
if (curContent.equals(content) && attriEquals) {
xm.remove();
xm.insertAfterElement(bean.getFrag().getBytes("UTF-8"));
tagList.remove(bean);
break tagBeanFor;
}
}
vn.pop();
}
}
//----------------------------------------------------Wf2XliffImpl 结束标志--------------------------------------------//
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();
}
/**
* 转换时间
* @param strDate
* @return
*/
private static String getR8dateStrFromUTC(String _UTCDate) {
SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd'T'HHmmss'Z'");
ParsePosition pos = new ParsePosition(0);
Date str2Date = formatter.parse(_UTCDate, pos);
SimpleDateFormat formatter_1 = new SimpleDateFormat("yyyy-MM-dd");
return formatter_1.format(str2Date);
}
/**
* 将 wf 文件中的 ut 标记换成 ph 标记
* @param text
* @return
*/
private static String analysisTag(String text){
//<ut type="content" x="1"><fontformat color="0#0#0"><b></ut>
text = text.replace("<ut ", "<ph ");
text = text.replace("ut>", "ph>");
return text;
}
public static void main(String[] args) {
String text = "<ut type=\"content\" x=\"1\"><fontformat color=\"0#0#0\"><b></ut>";
System.out.println(analysisTag(text));
LinkedHashMap<String, String> table = new LinkedHashMap<String, String>();
table.put("1", "11");
table.put("2", "22");
table.put("3", "33");
table.put("4", "4");
table.put("5", "11");
table.put("6", "22");
table.put("7", "33");
table.put("8", "4");
for(Entry<String, String> entry : table.entrySet()){
System.out.println(entry.getKey());
}
}
/**
* <div style='color:red;'>这个方法是从 VTDUtils 类中考贝的,主要是要有一定的顺序</div>
* @param vn
* @return
* @throws XPathParseException
* @throws XPathEvalException
* @throws NavException
*/
private Map<String, String> getElementAttributs(VTDNav vn)
throws XPathParseException, XPathEvalException, NavException {
vn.push();
Map<String, String> attributes = new LinkedHashMap<String, String>();
AutoPilot apAttributes = new AutoPilot(vn);
apAttributes.selectXPath("@*");
int inx = -1;
while ((inx = apAttributes.evalXPath()) != -1) {
String name = vn.toString(inx);
inx = vn.getAttrVal(name);
String value = inx != -1 ? vn.toString(inx) : "";
attributes.put(name, value);
}
apAttributes.resetXPath();
if (attributes.isEmpty()) {
attributes = null;
}
vn.pop();
return attributes;
}
}
| 19,718 | 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.wordfast3/src/net/heartsome/cat/converter/wordfast3/resource/Messages.java | /**
* Messages.java
*
* Version information :
*
* Date:Jan 14, 2010
*
* Copyright notice :
*/
package net.heartsome.cat.converter.wordfast3.resource;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
/**
* The Class Messages.
* @author robert 2012-12-13
* @version
* @since JDK1.6
*/
public final class Messages {
/** The Constant BUNDLE_NAME. */
private static final String BUNDLE_NAME = "net.heartsome.cat.converter.wordfast3.resource.wf"; //$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,033 | 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/src/net/heartsome/cat/converter/Activator.java | /**
* Activator.java
*
* Version information :
*
* Date:Jan 14, 2010
*
* Copyright notice :
*/
package net.heartsome.cat.converter;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
/**
* The Class Activator.
* @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";
/**
* (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 {
}
/**
* (non-Javadoc)
* @see org.osgi.framework.BundleActivator#stop(org.osgi.framework.BundleContext)
* @param context
* @throws Exception
*/
public void stop(BundleContext context) throws Exception {
}
}
| 958 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
ConverterException.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter/src/net/heartsome/cat/converter/ConverterException.java | /**
* ConverterException.java
*
* Version information :
*
* Date:Jan 14, 2010
*
* Copyright notice :
*/
package net.heartsome.cat.converter;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IStatus;
/**
* The Class ConverterException. 转换器在转换的过程中发生错误时,抛出的需检测异常。 此类继承自<code>CoreException</code>,<code>CoreException</code>
* 位于插件 org.eclipse.equinox.common 的 org.eclipse.core.runtime 包内。 插件 org.eclipse.equinox.common 内的的类是不依赖 OSGI
* 平台的,所以转换器接口及其实现依赖此类,并不会使转换器实现依赖于特定的 eclipse 平台或 OSGI 平台。但转换器内部的错误异常转化为<code>CoreException</code>
* 的子类实例进行抛出,可以方便客户端代码(UI 和相关逻辑层)以 eclipse 平台统一的方式进行处理。 转换器在转换的过程中,以会遇到不同种类的异常,具体的异常可在此类的基础上进行扩展。
* @author cheney
* @version
* @since JDK1.6
*/
public class ConverterException extends CoreException {
/** The Constant serialVersionUID. */
private static final long serialVersionUID = 1L;
/**
* Instantiates a new converter exception.
* @param status
* the status
*/
public ConverterException(IStatus status) {
super(status);
}
}
| 1,401 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
StringSegmenter.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter/src/net/heartsome/cat/converter/StringSegmenter.java | /**
* StringSegmenter.java
*
* Version information :
*
* Date:Jan 14, 2010
*
* Copyright notice :
*/
package net.heartsome.cat.converter;
import java.io.IOException;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Vector;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.xml.parsers.ParserConfigurationException;
import net.heartsome.cat.converter.resource.Messages;
import net.heartsome.cat.converter.util.ConverterUtils;
import net.heartsome.xml.Catalogue;
import net.heartsome.xml.Document;
import net.heartsome.xml.Element;
import net.heartsome.xml.SAXBuilder;
import org.xml.sax.SAXException;
/**
* The Class StringSegmenter.
* @author John Zhu
* @version
* @since JDK1.6
*/
public class StringSegmenter {
/** The rules. */
Vector<Element> rules;
/** The tags. */
Hashtable<String, String> tags;
// private StringSegmenter() {
// // do not allow instantiation without parameters
// }
/**
* Instantiates a new string segmenter.
* @param srxFile
* the srx file
* @param language
* the language
* @param catalogFile
* the catalog file
* @throws SAXException
* the SAX exception
* @throws IOException
* Signals that an I/O exception has occurred.
* @throws ParserConfigurationException
* the parser configuration exception
* @throws ConverterException
* the converter exception
*/
public StringSegmenter(String srxFile, String language, String catalogFile) throws SAXException, IOException,
ParserConfigurationException, ConverterException {
if (srxFile == null || "".equals(srxFile)) {
ConverterUtils.throwConverterException(Activator.PLUGIN_ID, Messages.getString("converter.StringSegmenter.msg1"));
}
if (catalogFile == null || "".equals(catalogFile)) {
ConverterUtils.throwConverterException(Activator.PLUGIN_ID, Messages.getString("converter.StringSegmenter.msg2"));
}
SAXBuilder builder = new SAXBuilder();
Catalogue catalogue = new Catalogue(catalogFile);
builder.setValidating(true);
builder.setEntityResolver(catalogue);
Document doc = builder.build(srxFile);
Element root = doc.getRootElement();
Element body = root.getChild("body"); //$NON-NLS-1$
Hashtable<String, String> rulenames = new Hashtable<String, String>();
rules = new Vector<Element>();
// check if there are map rules for this language
Element maprules = body.getChild("maprules"); //$NON-NLS-1$
if (maprules != null) {
List<Element> map = maprules.getChildren();
Iterator<Element> it = map.iterator();
while (it.hasNext()) {
Element maprule = it.next();
List<Element> langmap = maprule.getChildren();
for (int i = 0; i < langmap.size(); i++) {
Element languagemap = langmap.get(i);
if (Pattern.matches(languagemap.getAttributeValue("languagepattern", ""), language)) { //$NON-NLS-1$ //$NON-NLS-2$
rulenames.put(languagemap.getAttributeValue("languagerulename", "--no value--"), ""); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
}
}
}
}
if (rulenames.size() < 1) {
// no rules to load
MessageFormat mf = new MessageFormat(Messages.getString("converter.StringSegmenter.msg3"));
Object[] args = { language };
System.err.println(mf.format(args));
args = null;
return;
}
// now get the rules
Element languagerules = body.getChild("languagerules"); //$NON-NLS-1$
if (languagerules != null) {
List<Element> langrules = languagerules.getChildren("languagerule"); //$NON-NLS-1$
Iterator<Element> it = langrules.iterator();
while (it.hasNext()) {
Element languagerule = it.next();
if (rulenames.containsKey(languagerule.getAttributeValue("languagerulename", "--no name--"))) { //$NON-NLS-1$ //$NON-NLS-2$
List<Element> rulelist = languagerule.getChildren("rule"); //$NON-NLS-1$
for (int i = 0; i < rulelist.size(); i++) {
rules.add(rulelist.get(i));
}
}
}
}
}
/**
* Segment.
* @param string
* the string
* @return the string[]
*/
public String[] segment(String string) {
if (string.trim().equals("") || rules.size() == 0) { //$NON-NLS-1$
String[] result = new String[1];
result[0] = string;
return result;
}
Vector<String> strings = new Vector<String>();
tags = new Hashtable<String, String>();
strings.add(prepareString(string));
// now segment the strings
int rulessize = rules.size();
for (int i = 0; i < rulessize; i++) {
Element rule = rules.get(i);
boolean breaks = rule.getAttributeValue("break", "yes").equalsIgnoreCase("yes"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
Element before = rule.getChild("beforebreak"); //$NON-NLS-1$
Element after = rule.getChild("afterbreak"); //$NON-NLS-1$
String beforexp = ""; //$NON-NLS-1$
if (before != null) {
beforexp = before.getText();
}
String afterxp = ""; //$NON-NLS-1$
if (after != null) {
afterxp = after.getText();
}
if (breaks) {
// This rule tries to break segments
Vector<String> temp = new Vector<String>();
for (int j = 0; j < strings.size(); j++) {
String[] parts = split(strings.get(j), beforexp, afterxp);
for (int k = 0; k < parts.length; k++) {
temp.add(parts[k]);
}
}
strings = null;
strings = temp;
} else {
// strings = connect3(strings,beforexp,afterxp);
// This rule marks exceptions, like abbreviations
Vector<String> temp = new Vector<String>();
String current = strings.get(0);
for (int j = 1; j < strings.size(); j++) {
String next = strings.get(j);
if (endsWith(current, beforexp) && startsWith(next, afterxp)) {
current = current + next;
} else {
temp.add(current);
current = next;
}
}
temp.add(current);
strings = null;
strings = temp;
}
}
String[] result = new String[strings.size()];
for (int h = 0; h < strings.size(); h++) {
result[h] = cleanup(strings.get(h));
}
return analysisBlank(result);
}
// private Vector<String> connect3(Vector<String> strings, String beforexp,
// String afterxp) {
// Vector<String> temp = new Vector<String>();
// StringBuilder sb = new StringBuilder();
// ArrayList<String[]> stringsList = new ArrayList<String[]>();
// String[] stringsData;
// for (int i = 0; i < strings.size(); i++) {
// stringsData = new String[2];
// stringsData[0] = "" + sb.length();
// stringsData[1] = "" + (sb.length() + strings.get(i).length());
// sb.append(strings.get(i));
// stringsList.add(stringsData);
// }
// Pattern p = Pattern.compile(beforexp);
// Matcher m;
// int start = 0;
// int curEnd = 0;
// boolean addFlag = false;
// for (int j = 0; j < stringsList.size();) {
// for (int i = strings.size() - 1; i >= 0; i--) {
// if (Integer.parseInt(stringsList.get(i)[0]) <= start) {
// break;
// }
// curEnd = Integer.parseInt(stringsList.get(i)[1]);
// m = p.matcher(sb.substring(start, curEnd));
// if (m.matches()) {
// int end = start + m.end();
// if (startsWith(sb.substring(end), afterxp)) {
// if (end == curEnd) {
// if (i == strings.size() - 1) {
// temp.add(sb.substring(start, end));
// start = curEnd;
// addFlag = true;
// j = i + 1;
// break;
// } else {
// temp.add(sb.substring(start, end)
// + strings.get(i + 1));
// start = Integer
// .parseInt(stringsList.get(i + 1)[1]);
// addFlag = true;
// j = i + 2;
// break;
// }
// } else {
// temp.add(sb.substring(start, start + end));
// if (i == strings.size() - 1) {
// temp.add(sb.substring(end));
// addFlag = true;
// j = i + 1;
// break;
// } else {
// temp.add(sb.substring(end, Integer
// .parseInt(stringsList.get(i + 1)[0])));
// addFlag = true;
// start = Integer
// .parseInt(stringsList.get(i + 1)[0]);
// break;
// }
// }
// }
// }
// }
// if (!addFlag) {
// start = Integer.parseInt(stringsList.get(j)[1]);
// temp.add(strings.get(j));
// j++;
// }
// addFlag = false;
// }
// return temp;
// }
/**
* Cleanup.
* @param string
* the string
* @return the string
*/
private String cleanup(String string) {
Enumeration<String> keys = tags.keys();
while (keys.hasMoreElements()) {
String key = keys.nextElement();
int index = string.indexOf(key);
if (index != -1) {
string = string.substring(0, index) + tags.get(key) + string.substring(index + 1);
}
}
return string;
}
/**
* 处理分段后,有空格单独成段的问题 --robert 2013-05-24
* @param result
* @return
*/
private String[] analysisBlank(String[] result){
List<String> resultList = new ArrayList<String>();
String curStr = "";
String nextStr = "";
for (int i = 0; i < result.length; i++) {
curStr = result[i];
if (i + 1 < result.length) {
nextStr = result[i + 1];
// 若下一个分段为空格,就将之合并至上一个分段。
if (nextStr.length() > 0 && nextStr.trim().length() == 0) {
resultList.add(curStr + nextStr);
i ++;
continue;
}
}
resultList.add(curStr);
}
return resultList.toArray(new String[resultList.size()]);
}
/**
* Prepare string.
* @param string
* the string
* @return the string
*/
private String prepareString(String string) {
int start = string.indexOf("<ph"); //$NON-NLS-1$
int end = string.indexOf("</ph>"); //$NON-NLS-1$
int k = 0;
while (start != -1 && end != -1) {
if (start > end) {
break;
}
String tag = string.substring(start, end + 5);
string = string.substring(0, start) + (char) ('\uE000' + k) + string.substring(end + 5);
tags.put("" + (char) ('\uE000' + k), tag); //$NON-NLS-1$
k++;
start = string.indexOf("<ph"); //$NON-NLS-1$
end = string.indexOf("</ph>"); //$NON-NLS-1$
}
StringBuffer buffer = new StringBuffer();
StringBuffer element = new StringBuffer();
int length = string.length();
boolean inElement = false;
for (int i = 0; i < length; i++) {
char c = string.charAt(i);
if (c == '<' && string.indexOf(">", i) != -1) { //$NON-NLS-1$
inElement = true;
int a = string.indexOf("<", i + 1); //$NON-NLS-1$
int b = string.indexOf(">", i + 1); //$NON-NLS-1$
if (a != -1 && a < b) {
inElement = false;
}
if (i < length - 1 && !Character.isLetter(string.charAt(i + 1)) && string.charAt(i + 1) != '/') {
inElement = false;
}
}
if (inElement) {
element.append(c);
} else {
buffer.append(c);
}
if (c == '>' && inElement) {
inElement = false;
tags.put("" + (char) ('\uE000' + k), element.toString()); //$NON-NLS-1$
buffer.append((char) ('\uE000' + k));
element = null;
element = new StringBuffer();
k++;
}
}
return buffer.toString();
}
/**
* Ends with.
* @param string
* the string
* @param exp
* the exp
* @return true, if successful
*/
private boolean endsWith(String string, String exp) {
Pattern p = Pattern.compile(exp);
Matcher m = p.matcher(string);
String[] pieces = split(string, exp);
// if ( pieces.length == 1 && m.lookingAt()) {
// return false;
// }
if (pieces.length == 1) {
while (m.find()) {
if (string.endsWith(m.group())) {
return true;
}
}
return false;
}
String last = pieces[pieces.length - 1];
String[] parts = string.split(exp);
if (parts.length == 0) {
parts = new String[1];
parts[0] = ""; //$NON-NLS-1$
}
String lastPart = parts[parts.length - 1];
boolean result = !lastPart.equals(last);
return result;
}
/**
* Split.
* @param string
* the string
* @param beforexp
* the beforexp
* @param afterxp
* the afterxp
* @return the string[]
*/
private String[] split(String string, String beforexp, String afterxp) {
String[] strings = split(string, beforexp);
if (strings.length == 1 || afterxp.equals("")) { //$NON-NLS-1$
return strings;
}
Vector<String> parts = new Vector<String>();
String current = strings[0];
for (int i = 1; i < strings.length; i++) {
if (startsWith(strings[i], afterxp)) {
parts.add(current);
current = strings[i];
} else {
current = current + strings[i];
}
}
parts.add(current);
String[] result = new String[parts.size()];
for (int i = 0; i < parts.size(); i++) {
result[i] = parts.get(i);
}
return result;
}
/**
* Starts with.
* @param string
* the string
* @param exp
* the exp
* @return true, if successful
*/
private boolean startsWith(String string, String exp) {
Pattern p = Pattern.compile(exp);
Matcher m = p.matcher(string);
if (m.lookingAt()) {
return true;
}
return false;
}
/**
* Split.
* @param string
* the string
* @param exp
* the exp
* @return the string[]
*/
private String[] split(String string, String exp) {
Pattern p = Pattern.compile(exp);
if (exp.equals("") || p.split(string).length == 1) { //$NON-NLS-1$
String[] result = new String[1];
result[0] = string;
return result;
}
Vector<CharSequence> parts = new Vector<CharSequence>();
while (p.split(string).length != 1) {
String[] halves = p.split(string, 2);
parts.add(string.subSequence(0, string.lastIndexOf(halves[1])));
string = halves[1];
}
if (!string.equals("")) { //$NON-NLS-1$
parts.add(string);
}
String[] result = new String[parts.size()];
for (int i = 0; i < parts.size(); i++) {
result[i] = (String) parts.get(i);
}
return result;
}
/**
* The main method.
* @param args
* the arguments
* @throws SAXException
* the SAX exception
* @throws IOException
* Signals that an I/O exception has occurred.
* @throws ParserConfigurationException
* the parser configuration exception
* @throws ConverterException
* the converter exception
*/
public static void main(String[] args) throws SAXException, IOException, ParserConfigurationException,
ConverterException {
StringSegmenter segmenter = new StringSegmenter("srx/default_rules.srx", "en", //$NON-NLS-1$ //$NON-NLS-2$
"catalogue/catalogue.xml"); //$NON-NLS-1$
// String[] result = segmenter.segment("The exemplary <ph>distinction of</ph> Heartsome's translation " + //$NON-NLS-1$
// "service is rare and unique in the industry. It is intentional and purposefully " + //$NON-NLS-1$
// "dedicated to servicing clients that are avowedly discerning in the value of " + //$NON-NLS-1$
// "quality translation. These clients expect our services to measurably add value " + //$NON-NLS-1$
// "in a manner that will serve to complete their competitive advantage. We are " + //$NON-NLS-1$
// "possibly the one and only translation service in the industry capable of adding " + //$NON-NLS-1$
// "recognition, credence and value to brand consciousness and exclusivity."); //$NON-NLS-1$
// for (int i=0 ; i<result.length ; i++) {
// System.out.println(i + ". " + result[i]); //$NON-NLS-1$
// }
segmenter
.endsWith(
"Ks.",
"RegR|AR|RR|KzlR|KmzlR|KommR|KR|ÖkR|MedR|MR|OMedR|OMR|VetR|Techn\\.R|BauR h\\.c\\.|BergR h\\.c\\.|ForstR h\\.c\\.|HR|Prof\\.|Ksch\\.|Ks\\.|Univ\\.Prof\\.|(OSt|St|OS|S)R");
}
}
| 15,931 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
Converter.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter/src/net/heartsome/cat/converter/Converter.java | /**
* Converter.java
*
* Version information :
*
* Date:Jan 14, 2010
*
* Copyright notice :
*/
package net.heartsome.cat.converter;
import java.util.Map;
import org.eclipse.core.runtime.IProgressMonitor;
/**
* The Interface Converter. 转换器接口,所有转换器实现都需要实现此接口。 具体的转换器实现,在以 OSGI 服务进行注册的时候,需要指定所支持的 <code>TYPE</code><code
* ,</code>
* CONVERT_DIRECTION</code>。否则注册的服务不会被使用。如果不是在 OSGI 环境中使用,则需要实现相应的工厂方法实例化具体的实现类,避免客户端代码直接实例化具体实现类。.
* @author cheney
* @version
* @since JDK1.6
*/
public interface Converter {
/** The Constant DEBUG_MODE. */
boolean DEBUG_MODE = true;
/** The Constant HSSCHEMALOCATION. */
String HSSCHEMALOCATION = "http://www.heartsome.net.cn/2008/XLFExtension XLFExtension.xsd";
/** The Constant HSNAMESPACE. */
String HSNAMESPACE = "http://www.heartsome.net.cn/2008/XLFExtension";
/** 转换器所支持的转换类型(文件格式). */
String ATTR_TYPE = "type";
/** 所支持的文件类型名称。. */
String ATTR_TYPE_NAME = "type.name";
/** 转换器的名字. */
String ATTR_NAME = "name";
/** 转换的方向。正向或反向。. */
String ATTR_DIRECTION = "direction";
/** 正向转换. */
String DIRECTION_POSITIVE = "positive";
/** 反向转换. */
String DIRECTION_REVERSE = "reverse";
/** 源文件路径. */
String ATTR_SOURCE_FILE = "source.file";
/** XLIFF文件路径. */
String ATTR_XLIFF_FILE = "xliff.file";
/** 源文件语言. */
String ATTR_SOURCE_LANGUAGE = "source.lang";
/** 目标语言. */
String ATTR_TARGET_LANGUAGE = "target.lang";
/** 源文件编码. */
String ATTR_SOURCE_ENCODING = "source.encoding";
/** 骨架文件路径. */
String ATTR_SKELETON_FILE = "skeleton.file";
/** 目标文件路径. */
String ATTR_TARGET_FILE = "target.file";
/** catalogue 的文件路径. */
String ATTR_CATALOGUE = "catalogue.file";
/** 分段规则文件路径. */
String ATTR_SRX = "srx.file";
/** 是否以 element 进行分割. */
String ATTR_SEG_BY_ELEMENT = "seg_by_element";
/** The Constant TRUE. */
String TRUE = "true";
/** The Constant FALSE. */
String FALSE = "false";
/** The Constant ATTR_IS_SUITE. */
String ATTR_IS_SUITE = "isSuite";
/** The Constant ATTR_QT_TOOLID. */
String ATTR_QT_TOOLID = "QT_TOOLID";
/** The Constant QT_TOOLID_DEFAULT_VALUE. */
String QT_TOOLID_DEFAULT_VALUE = "XLFEditor auto-Quick Translation";
/** The Constant ATTR_INI_FILE. */
String ATTR_INI_FILE = "ini.file";
/** The Constant ATTR_LOCK_XTRANS. */
String ATTR_LOCK_XTRANS = "lock_xtrans";
/** The Constant ATTR_LOCK_100. */
String ATTR_LOCK_100 = "lock_100";
/** The Constant ATTR_LOCK_101. */
String ATTR_LOCK_101 = "lock_101";
/** The Constant ATTR_LOCK_REPEATED. */
String ATTR_LOCK_REPEATED = "lock_repeated";
/** The Constant ATTR_IS_INDESIGN. */
String ATTR_IS_INDESIGN = "isInDesign";
/** The Constant ATTR_IS_RESX. */
String ATTR_IS_RESX = "isResx";
/** The Constant ATTR_IS_GENERIC. */
String ATTR_IS_GENERIC = "isGeneric";
/** The Constant ATTR_PROGRAM_FOLDER. 配置文件目录 */
String ATTR_PROGRAM_FOLDER = "program.folder";
/** The Constant PROGRAM_FOLDER_DEFAULT_VALUE. 默认配置文件目录 */
String PROGRAM_FOLDER_DEFAULT_VALUE = "./";
/** The Constant ATTR_FORMAT. 文件类型 */
String ATTR_FORMAT = "source.format";
/** The Constant ATTR_IS_TAGGEDRTF. 是否为 TaggedRTF 格式 */
String ATTR_IS_TAGGEDRTF = "isTaggedRTF";
/** 是否按 CR/LF 分段 */
String ATTR_BREAKONCRLF = "breakOnCRLF";
/** 将骨架嵌入 xliff 文件 */
String ATTR_EMBEDSKL = "embedSkl";
/** ini 目录路径 */
String ATTR_INIDIR = "iniDir";
/** 是否为预览翻译模式 */
String ATTR_IS_PREVIEW_MODE = "isPreviewMode";
// TODO
/*
* 此接口需要进一步进行完善,传入参数 Map 所需要指定的 key,返回 Map 中所需要指定的 key。
*/
/**
* Convert.
* @param args
* 转换文件所需要的特定参数,如源文件路径、目标文件路径等。不能为<code>NULL</code>
* @param monitor
* 监视转换过程的进度,<code>IProgressMonitor</code>位于 org.eclipse.equinox.common 插件中。此插件中的类不依赖特定 eclispe 平台或 OSGI
* 平台的特定类,见<code>ConverterException</code>及相关 API 的说明。允许为 <code>NULL</code>
* @return 转换结果。如目标文件路径等
* @throws ConverterException
* 在转换的过程中发生错误,则抛出<code>ConverterException</code>
*/
Map<String, String> convert(Map<String, String> args, IProgressMonitor monitor) throws ConverterException;
/**
* Gets the name.
* @return 返回转换器的名字
*/
String getName();
/**
* Gets the type.
* @return 返回转换器支持的文件类型
*/
String getType();
/**
* Gets the type name.
* @return 返回转换器支持的文件类型名称
*/
String getTypeName();
}
| 5,152 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
ConverterTracker.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter/src/net/heartsome/cat/converter/util/ConverterTracker.java | /**
* ConverterTracker.java
*
* Version information :
*
* Date:Jan 14, 2010
*
* Copyright notice :
*/
package net.heartsome.cat.converter.util;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import net.heartsome.cat.converter.Converter;
import org.osgi.framework.BundleContext;
import org.osgi.framework.Constants;
import org.osgi.framework.Filter;
import org.osgi.framework.InvalidSyntaxException;
import org.osgi.framework.ServiceReference;
import org.osgi.util.tracker.ServiceTracker;
import org.osgi.util.tracker.ServiceTrackerCustomizer;
/**
* The Class ConverterTracker. 跟踪目前所支持的转换器列表,并进行动态更新。 客户端需要继承此类,并实现<code>convert</code>方法处理转换和转换结果。在
* <code>convert</code>方法里,可以通过 <code>getConvert</code>方法得到当前所需的转换器.
* @author cheney
* @version
* @since JDK1.6
*/
public abstract class ConverterTracker extends AbstractModelObject {
/* set this to true to compile in debug messages */
/** The Constant DEBUG. */
protected static final boolean DEBUG = false;
/** The selected type. */
protected String selectedType = "";
/** The support types. */
private List<ConverterBean> supportTypes;
/** The converter service tracker. */
private ServiceTracker converterServiceTracker;
/** The context. */
private BundleContext context;
/** The direction. */
protected String direction;
/**
* The Constructor.
* @param bundleContext
* 插件所在的 bundle context
* @param direction
* 取<code>Converter.DIRECTION_POSITIVE</code>或 <code>Converter.DIRECTION_REVERSE</code>
*/
public ConverterTracker(BundleContext bundleContext, String direction) {
this.direction = direction;
supportTypes = new ArrayList<ConverterBean>();
this.context = bundleContext;
String filterStr = new AndFilter(new EqFilter(Constants.OBJECTCLASS, Converter.class.getName()), new EqFilter(
Converter.ATTR_DIRECTION, direction)).toString();
Filter filter = null;
try {
filter = context.createFilter(filterStr);
} catch (InvalidSyntaxException e) {
// ignore the exception
e.printStackTrace();
}
if (filter != null) {
converterServiceTracker = new ServiceTracker(context, filter, new ConverterCustomizer());
}
converterServiceTracker.open();
}
/**
* Gets the support types.
* @return the support types
*/
public List<ConverterBean> getSupportTypes() {
return supportTypes;
}
/**
* Sets the support types.
* @param supportTypes
* the new support types
*/
public void setSupportTypes(List<ConverterBean> supportTypes) {
this.supportTypes = supportTypes;
firePropertyChange("supportTypes", null, null);
}
/**
* Gets the selected type.
* @return the selected type
*/
public String getSelectedType() {
return selectedType;
}
/**
* Sets the selected type.
* @param selectedType
* the new selected type
*/
public void setSelectedType(String selectedType) {
String oldReverseSelected = this.selectedType;
this.selectedType = selectedType;
firePropertyChange("selectedType", oldReverseSelected, this.selectedType);
System.out.println("current selected:" + this.selectedType);
}
/**
* 获得当前转换器的转换方向
* @return ;
*/
public String getDirection() {
return direction;
}
/**
* Close.
*/
public void close() {
// destroy resources
converterServiceTracker.close();
}
/**
* Convert.
* @param parameters
* 转换所需要的参数 Map
* @return the map< string, string>
*/
public abstract Map<String, String> convert(Map<String, String> parameters);
/**
* 根据当前选择的转换器类型和转换方向值获得对应的转换器。.
* @return 返回当前选择的转换器类型,及初始化此 model 的转换方向的值对应的转换器。如果 type 对应的转换器不存在,则返回 <code>NULL</code>
*/
public Converter getConverter() {
return getConverter(selectedType);
};
/**
* 根据指定的<code>type</code>获得对应的转换器 *.
* @param type
* 指定的 type
* @return 返回 type 值,及初始化此 model 的转换方向的值对应的转换器。如果 type 对应的转换器不存在,则返回 <code>NULL</code>
*/
public Converter getConverter(String type) {
Converter converter = null;
if (type != null & direction != null) {
ServiceReference[] serviceReferences = converterServiceTracker.getServiceReferences();
for (int i = 0; i < serviceReferences.length; i++) {
String converterType = (String) serviceReferences[i].getProperty(Converter.ATTR_TYPE);
String converterDirection = (String) serviceReferences[i].getProperty(Converter.ATTR_DIRECTION);
if (type.equals(converterType) && direction.equals(converterDirection)) {
converter = (Converter) converterServiceTracker.getService(serviceReferences[i]);
break;
}
}
}
return converter;
}
/**
* The Class ConverterCustomizer.
* @author John Zhu
* @version
* @since JDK1.6
*/
private class ConverterCustomizer 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) context.getService(reference);
if (DEBUG) {
System.out.println("-----------------------------------------");
System.out.println("adding a converter service:" + converter.getName());
}
synchronized (supportTypes) {
String type = converter.getType();
boolean isExist = false;
for (ConverterBean bean : supportTypes) {
if (type.equals(bean.getName())) {
isExist = true;
break;
}
}
if (!isExist) {
ConverterBean bean = new ConverterBean(converter.getType(), converter.getTypeName());
supportTypes.add(bean);
setSupportTypes(supportTypes);
}
}
if (DEBUG) {
System.out.println("-----------------------------------------");
}
return converter;
}
/**
* (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) {
Converter converter = (Converter) context.getService(reference);
if (DEBUG) {
System.out.println("-----------------------------------------");
System.out.println("removing a converter service:" + converter.getName());
}
synchronized (supportTypes) {
String type = converter.getType();
Iterator<ConverterBean> it = supportTypes.iterator();
while (it.hasNext()) {
ConverterBean bean = it.next();
if (type.equals(bean.getName())) {
it.remove();
setSupportTypes(supportTypes);
}
}
}
if (DEBUG) {
System.out.println("-----------------------------------------");
}
context.ungetService(reference);
}
}
}
| 7,659 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
ConverterBean.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter/src/net/heartsome/cat/converter/util/ConverterBean.java | /**
* ConverterBean.java
*
* Version information :
*
* Date:Jan 14, 2010
*
* Copyright notice :
*/
package net.heartsome.cat.converter.util;
/**
* The Class ConverterBean.
* @author John Zhu
* @version
* @since JDK1.6
*/
public class ConverterBean {
/** The name. */
private final String name;
/** The description. */
private final String description;
/** The filter extensions */
// TODO 此初始化值应当被删除,并且删除 ConverterBean(String name, String description) 构造方法。
// 在删除之前应该将每个转换器插件中调用的 ConverterBean 构造方法改为 ConverterBean(String name, String description, String[]
// filterExtensions),这可能需要在转换器接口添加一个字段
private String[] extensions = {};
/**
* Instantiates a new converter bean.
* @param name
* the name
* @param description
* the description
*/
public ConverterBean(String name, String description) {
this.name = name;
this.description = description;
}
/**
* Instantiates a new converter bean.
* @param name
* 名字
* @param description
* 描述
* @param filterExtensions
* 过滤后缀名
*/
public ConverterBean(String name, String description, String[] extensions) {
this.name = name;
this.description = description;
this.extensions = extensions;
}
/**
* Gets the name.
* @return the name
*/
public String getName() {
return name;
}
/**
* Gets the description.
* @return the description
*/
public String getDescription() {
return description;
}
/**
* Gets the extensions.
* @return the description
*/
public String[] getExtensions() {
return extensions;
}
/**
* (non-Javadoc)
* @see java.lang.Object#toString()
* @return
*/
@Override
public String toString() {
return description;
}
/**
* (non-Javadoc)
* @see java.lang.Object#equals()
* @return
*/
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (!(obj instanceof ConverterBean)) {
return false;
}
ConverterBean bean = (ConverterBean) obj;
if (name == null) {
if (bean.name != null) {
return false;
}
} else if (!name.equals(bean.name)) {
return false;
}
return false;
}
/**
* 得到文件过滤条件名。
* @return ;
*/
public String getFilterNames() {
String temp = getFilterExtensionString(",");
return description + " Files [" + temp + "]";
}
/**
* 得到文件过滤拓展名。
* @return ;
*/
public String getFilterExtensions() {
return getFilterExtensionString(";");
}
/**
* 得到文件过滤拓展名的字符串。
* @param sep
* 分隔符
* @return ;
*/
private String getFilterExtensionString(String sep) {
String temp = "";
for (int i = 0; i < extensions.length; i++) {
temp += extensions[i];
if (i != extensions.length - 1) {
temp += sep;
}
}
return temp;
}
}
| 3,031 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
CalculateProcessedBytes.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter/src/net/heartsome/cat/converter/util/CalculateProcessedBytes.java | package net.heartsome.cat.converter.util;
import java.io.File;
import java.io.UnsupportedEncodingException;
import org.eclipse.core.runtime.IProgressMonitor;
/**
* 在按行对文件进行处理的过程中,把文件的读取和处理统一模拟分成 100 个任务,根据当前已处理的字节数计算出当前文件的处理进度。如果文件的总数节数小于或等于 总任务量,则总任务数即为其总字节数。
* @author cheney
* @since JDK1.6
*/
public class CalculateProcessedBytes {
/**
* 默认的模拟任务量
*/
public static final int DEFAULT_TOTAL_TASK = 100;
private long totalSize;
private int totalTask;
// 每个任务的工作量(所需要处理的字节数)
private long oneTaskSize;
// 每次计算时,剩余的不足一个任务工作量的字节数
private long remainSize;
// TODO 在处理大文件时,可以考虑扩大模拟的任务量,以缩小每个任务所需要处理的字节量。
/**
* @param totalSize
* 字节总数
* @param totalTask
* 总任务量
*/
public CalculateProcessedBytes(long totalSize, int totalTask) {
initialize(totalSize, totalTask);
}
/**
* 初始化总字节数和总任务数
* @param totalSize
* 总字节数
* @param totalTask
* 总任务数 ;
*/
private void initialize(long totalSize, int totalTask) {
if (totalSize < 0) {
totalSize = 0;
}
if (totalTask < 0) {
totalTask = 0;
}
this.totalSize = totalSize;
this.totalTask = totalTask;
if (totalSize <= totalTask) {
this.totalTask = (int) totalSize;
}
oneTaskSize = this.totalSize / this.totalTask;
}
/**
* @param totalSize
* 字节总数
*/
public CalculateProcessedBytes(long totalSize) {
this(totalSize, DEFAULT_TOTAL_TASK);
}
/**
* @param filePath
* 文件路径
*/
public CalculateProcessedBytes(String filePath) {
// 计算总任务数
File temp = new File(filePath);
long totalSize = 0;
if (temp.exists()) {
totalSize = temp.length();
}
if (totalSize == 0) {
totalSize = 1;
}
initialize(totalSize, DEFAULT_TOTAL_TASK);
}
/**
* @return 返回总任务量;
*/
public int getTotalTask() {
return totalTask;
}
/**
* 根据所接收的字节数,计算这些字节数所占的任务量。在处理的过程中,需要把之前处理的字节数剩余量(即上一次处理的字节数中不足一个任务工作量的字节数)加进来一起进行计算。
* @param size
* @return ;
*/
public int calculateProcessed(long size) {
remainSize += size;
int tasks = (int) (remainSize / oneTaskSize);
remainSize %= oneTaskSize;
return tasks;
}
/**
* 计算当前的转换进度
* @param monitor
* IProgressMonitor
* @param line
* 当前处理的行;
* @param encoding
* 所处理字符串的字符编码,允许为 NULL,如果为 NULL 则使用平台默认的编码
*/
public void calculateProcessed(IProgressMonitor monitor, String line, String encoding) {
if (line != null) {
int size = 0;
try {
if (encoding != null) {
size = line.getBytes(encoding).length;
} else {
size = line.getBytes().length;
}
// 加上换行符所占的一个字节
size += 1;
} catch (UnsupportedEncodingException e) {
// ignore the exception
e.printStackTrace();
}
if (size > 0) {
int workedTask = calculateProcessed(size);
if (workedTask > 0) {
monitor.worked(workedTask);
}
}
}
}
}
| 3,566 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
EqFilter.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter/src/net/heartsome/cat/converter/util/EqFilter.java | /**
* EqFilter.java
*
* Version information :
*
* Date:Jan 14, 2010
*
* Copyright notice :
*/
package net.heartsome.cat.converter.util;
/**
* The Class EqFilter.
* @author John Zhu
* @version
* @since JDK1.6
*/
public class EqFilter extends FilterBuilder {
/** The name. */
private final String name;
/** The value. */
private final String value;
/**
* Instantiates a new eq filter.
* @param name
* the name
* @param value
* the value
*/
public EqFilter(String name, String value) {
this.name = name;
this.value = value;
}
/**
* (non-Javadoc)
* @see net.heartsome.cat.converter.util.FilterBuilder#append(java.lang.StringBuilder)
* @param builder
* @return
*/
@Override
public StringBuilder append(StringBuilder builder) {
return builder.append('(').append(name).append('=').append(value).append(')');
}
}
| 885 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
FilterBuilder.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter/src/net/heartsome/cat/converter/util/FilterBuilder.java | /**
* FilterBuilder.java
*
* Version information :
*
* Date:Jan 14, 2010
*
* Copyright notice :
*/
package net.heartsome.cat.converter.util;
/**
* The Class FilterBuilder.
* @author John Zhu
* @version
* @since JDK1.6
*/
public abstract class FilterBuilder {
/**
* (non-Javadoc)
* @see java.lang.Object#toString()
* @return
*/
@Override
public final String toString() {
return append(new StringBuilder()).toString();
}
/**
* Append.
* @param builder
* the builder
* @return the string builder
*/
public abstract StringBuilder append(StringBuilder builder);
}
| 613 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
AndFilter.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter/src/net/heartsome/cat/converter/util/AndFilter.java | /**
* AndFilter.java
*
* Version information :
*
* Date:Jan 14, 2010
*
* Copyright notice :
*/
package net.heartsome.cat.converter.util;
/**
* The Class AndFilter.
* @author John Zhu
* @version
* @since JDK1.6
*/
public class AndFilter extends FilterBuilder {
/** The filters. */
private final FilterBuilder[] filters;
/**
* Instantiates a new and filter.
* @param filters
* the filters
*/
public AndFilter(FilterBuilder... filters) {
this.filters = filters;
}
/**
* (non-Javadoc)
* @see net.heartsome.cat.converter.util.FilterBuilder#append(java.lang.StringBuilder)
* @param buffer
* @return
*/
@Override
public StringBuilder append(StringBuilder buffer) {
StringBuilder builder = new StringBuilder();
builder.append("(&");
for (int i = 0; i < filters.length; i++) {
filters[i].append(builder);
}
builder.append(')');
return builder;
}
/**
* The main method.
* @param args
* the arguments
*/
public static void main(String[] args) {
System.out.println(new AndFilter(new EqFilter("name", "value"), new EqFilter("key1", "value1")).toString());
}
}
| 1,145 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
ConverterRegister.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter/src/net/heartsome/cat/converter/util/ConverterRegister.java | /**
* ConverterRegister.java
*
* Version information :
*
* Date:Jan 14, 2010
*
* Copyright notice :
*/
package net.heartsome.cat.converter.util;
import java.util.Dictionary;
import java.util.Hashtable;
import java.util.Properties;
import net.heartsome.cat.converter.Converter;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceRegistration;
/**
* The Class ConverterRegister.
* @author John Zhu
* @version
* @since JDK1.5
*/
public final class ConverterRegister {
/**
* Instantiates a new converter register.
*/
private ConverterRegister() {
// prevent instance
}
/**
* 注册正向转换的转换器帮助类.
* @param context
* the context
* @param convert
* the convert
* @param properties
* the properties
* @return the service registration
*/
public static ServiceRegistration registerPositiveConverter(BundleContext context, Converter convert,
Properties properties) {
properties.put(Converter.ATTR_DIRECTION, Converter.DIRECTION_POSITIVE);
return context.registerService(Converter.class.getName(), convert, getDictByProperties(properties));
}
/**
* 注册反向转换的转换器帮助类.
* @param context
* the context
* @param convert
* the convert
* @param properties
* the properties
* @return the service registration
*/
public static ServiceRegistration registerReverseConverter(BundleContext context, Converter convert,
Properties properties) {
properties.put(Converter.ATTR_DIRECTION, Converter.DIRECTION_REVERSE);
return context.registerService(Converter.class.getName(), convert, getDictByProperties(properties));
}
private static Dictionary<String, Object> getDictByProperties(Properties properties){
Dictionary<String,Object> dict = new Hashtable<String, Object>();
for (Object key : properties.keySet()){
String strKey = (String)key;
Object strValue = properties.get(strKey);
dict.put(strKey, strValue);
}
return dict;
}
}
| 2,048 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
ReverseConversionInfoLogRecord.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter/src/net/heartsome/cat/converter/util/ReverseConversionInfoLogRecord.java | package net.heartsome.cat.converter.util;
import java.io.File;
import net.heartsome.cat.converter.resource.Messages;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* 在逆转换过程中,记录日志的帮助类
* @author cheney
* @since JDK1.6
*/
public class ReverseConversionInfoLogRecord {
private static final Logger LOGGER = LoggerFactory.getLogger(ReverseConversionInfoLogRecord.class);
// 文件转换的开始时间
private long startTime;
// 转换过程中,某一转换阶段的开始时间
private long tempStartTime;
// 转换过程中,某一转换阶段的结束时间
private long tempEndTime;
// 文件转换的结束时间
private long endTime;
/**
* 记录转换开始的相关信息 ;
*/
public void startConversion() {
if (LOGGER.isInfoEnabled()) {
startTime = System.currentTimeMillis();
LOGGER.info(Messages.getString("util.ReverseConversionInfoLogRecord.logger1"), startTime);
}
}
/**
* 记录转换过程中涉及的相关文件信息
* @param catalogueFile
* catalogue 文件路径
* @param iniFile
* ini 文件路径
* @param xliffFile
* xliff 文件路径
* @param skeletonFile
* 骨架文件路径 ;
*/
public void logConversionFileInfo(String catalogueFile, String iniFile, String xliffFile, String skeletonFile) {
if (LOGGER.isInfoEnabled()) {
long fileSize = 0;
if (catalogueFile != null) {
File temp = new File(catalogueFile);
if (temp.exists()) {
fileSize = temp.length();
LOGGER.info(Messages.getString("util.ReverseConversionInfoLogRecord.logger2"), fileSize);
}
}
fileSize = 0;
if (iniFile != null) {
File temp = new File(iniFile);
if (temp.exists()) {
fileSize = temp.length();
LOGGER.info(Messages.getString("util.ReverseConversionInfoLogRecord.logger3"), fileSize);
}
}
fileSize = 0;
if (xliffFile != null) {
File temp = new File(xliffFile);
if (temp.exists()) {
fileSize = temp.length();
LOGGER.info(Messages.getString("util.ReverseConversionInfoLogRecord.logger4"), fileSize);
}
}
fileSize = 0;
if (skeletonFile != null) {
File temp = new File(skeletonFile);
if (temp.exists()) {
fileSize = temp.length();
LOGGER.info(Messages.getString("util.ReverseConversionInfoLogRecord.logger5"), fileSize);
}
}
}
}
/**
* 记录开始加载 catalogue 文件的相关信息 ;
*/
public void startLoadingCatalogueFile() {
if (LOGGER.isInfoEnabled()) {
tempStartTime = System.currentTimeMillis();
LOGGER.info(Messages.getString("util.ReverseConversionInfoLogRecord.logger6"), tempStartTime);
}
}
/**
* 记录加载完 catalogue 文件的相关信息 ;
*/
public void endLoadingCatalogueFile() {
if (LOGGER.isInfoEnabled()) {
tempEndTime = System.currentTimeMillis();
LOGGER.info(Messages.getString("util.ReverseConversionInfoLogRecord.logger7"), tempEndTime);
LOGGER.info(Messages.getString("util.ReverseConversionInfoLogRecord.logger8"), tempEndTime - tempStartTime);
}
}
/**
* 记录开始加载 ini 文件的相关信息 ;
*/
public void startLoadingIniFile() {
if (LOGGER.isInfoEnabled()) {
tempStartTime = System.currentTimeMillis();
LOGGER.info(Messages.getString("util.ReverseConversionInfoLogRecord.logger9"), tempStartTime);
}
}
/**
* 记录加载完 ini 文件的相关信息 ;
*/
public void endLoadingIniFile() {
if (LOGGER.isInfoEnabled()) {
tempEndTime = System.currentTimeMillis();
LOGGER.info(Messages.getString("util.ReverseConversionInfoLogRecord.logger10"), tempEndTime);
LOGGER.info(Messages.getString("util.ReverseConversionInfoLogRecord.logger11"), tempEndTime - tempStartTime);
}
}
/**
* 记录开始加载 xliff 文件的相关信息 ;
*/
public void startLoadingXliffFile() {
if (LOGGER.isInfoEnabled()) {
tempStartTime = System.currentTimeMillis();
LOGGER.info(Messages.getString("util.ReverseConversionInfoLogRecord.logger12"), tempStartTime);
}
}
/**
* 记录加载完 xliff 文件的相关信息 ;
*/
public void endLoadingXliffFile() {
if (LOGGER.isInfoEnabled()) {
tempEndTime = System.currentTimeMillis();
LOGGER.info(Messages.getString("util.ReverseConversionInfoLogRecord.logger13"), tempEndTime);
LOGGER.info(Messages.getString("util.ReverseConversionInfoLogRecord.logger14"), tempEndTime - tempStartTime);
}
}
/**
* 记录开始替换 skeleton 文件中的 segment 标志符相关信息 ;
*/
public void startReplacingSegmentSymbol() {
if (LOGGER.isInfoEnabled()) {
tempStartTime = System.currentTimeMillis();
LOGGER.info(Messages.getString("util.ReverseConversionInfoLogRecord.logger15"), tempStartTime);
}
}
/**
* 记录替换完 skeleton 文件中的 segment 标志符相关信息 ;
*/
public void endReplacingSegmentSymbol() {
if (LOGGER.isInfoEnabled()) {
tempEndTime = System.currentTimeMillis();
LOGGER.info(Messages.getString("util.ReverseConversionInfoLogRecord.logger16"), tempEndTime);
LOGGER.info(Messages.getString("util.ReverseConversionInfoLogRecord.logger17"), tempEndTime - tempStartTime);
}
}
/**
* 记录转换完成相关信息 ;
*/
public void endConversion() {
if (LOGGER.isInfoEnabled()) {
endTime = System.currentTimeMillis();
LOGGER.info(Messages.getString("util.ReverseConversionInfoLogRecord.logger18"), endTime);
LOGGER.info(Messages.getString("util.ReverseConversionInfoLogRecord.logger19"), endTime - startTime);
}
}
}
| 5,547 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
ConverterUtils.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter/src/net/heartsome/cat/converter/util/ConverterUtils.java | /**
* ConverterUtils.java
*
* Version information :
*
* Date:Jan 14, 2010
*
* Copyright notice :
*/
package net.heartsome.cat.converter.util;
import net.heartsome.cat.converter.ConverterException;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.OperationCanceledException;
import org.eclipse.core.runtime.Status;
/**
* The Class ConverterUtils. 转换工具类,用于转换中需要用到的一些辅助的静态方法.
* @author John Zhu
* @version
* @since JDK1.6
*/
public class ConverterUtils {
/**
* Instantiates a new data constant.
*/
protected ConverterUtils() {
throw new UnsupportedOperationException(); // prevents calls from subclass
}
/**
* Throw converter exception.
* @param plugin
* the plugin
* @param message
* the message
* @param e
* the e
* @throws ConverterException
* the converter exception
* @author John Zhu
*/
public static void throwConverterException(String plugin, String message, Throwable e) throws ConverterException {
if (e instanceof OperationCanceledException) {
return;
}
IStatus status = new Status(IStatus.ERROR, plugin, IStatus.ERROR, message, e);
ConverterException ce = new ConverterException(status);
throw ce;
}
/**
* Throw converter exception.
* @param plugin
* the plugin
* @param message
* the message
* @throws ConverterException
* the converter exception
* @author John Zhu
* @exception ConverterException
*/
public static void throwConverterException(String plugin, String message) throws ConverterException {
throwConverterException(plugin, message, null);
}
/**
* 获得当前已处理字节数的计算对象
* @param totalSize
* 字节总数
* @return ;
*/
public static CalculateProcessedBytes getCalculateProcessedBytes(long totalSize) {
return new CalculateProcessedBytes(totalSize);
}
/**
* 获得处理指定文件进度的计算对象
* @param filePath
* 文件路径
* @return ;
*/
public static CalculateProcessedBytes getCalculateProcessedBytes(String filePath) {
return new CalculateProcessedBytes(filePath);
}
/**
* 获得记录逆转换过程中的信息记录对象
* @return ;
*/
public static ReverseConversionInfoLogRecord getReverseConversionInfoLogRecord() {
return new ReverseConversionInfoLogRecord();
}
/**
* 验证源文件类型是否是 OpenOffice 和 MSOffice 2007。
* @param typeName
* @return ;
*/
public static boolean isOpenOfficeOrMSOffice2007(String type) {
if (type == null) {
return false;
}
return type.contains("openoffice") || type.contains("msoffice2007") ||type.contains("msoffice2003") ;
}
}
| 2,771 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
AbstractModelObject.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter/src/net/heartsome/cat/converter/util/AbstractModelObject.java | /**
* AbstractModelObject.java
*
* Version information :
*
* Date:Jan 14, 2010
*
* Copyright notice :
*/
package net.heartsome.cat.converter.util;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
// Minimal JavaBeans support
/**
* The Class AbstractModelObject.
* @author John Zhu
* @version
* @since JDK1.6
*/
public abstract class AbstractModelObject {
/** The property change support. */
private PropertyChangeSupport propertyChangeSupport = new PropertyChangeSupport(this);
/**
* Adds the property change listener.
* @param listener
* the listener
*/
public void addPropertyChangeListener(PropertyChangeListener listener) {
propertyChangeSupport.addPropertyChangeListener(listener);
}
/**
* Adds the property change listener.
* @param propertyName
* the property name
* @param listener
* the listener
*/
public void addPropertyChangeListener(String propertyName, PropertyChangeListener listener) {
propertyChangeSupport.addPropertyChangeListener(propertyName, listener);
}
/**
* Removes the property change listener.
* @param listener
* the listener
*/
public void removePropertyChangeListener(PropertyChangeListener listener) {
propertyChangeSupport.removePropertyChangeListener(listener);
}
/**
* Removes the property change listener.
* @param propertyName
* the property name
* @param listener
* the listener
*/
public void removePropertyChangeListener(String propertyName, PropertyChangeListener listener) {
propertyChangeSupport.removePropertyChangeListener(propertyName, listener);
}
/**
* Fire property change.
* @param propertyName
* the property name
* @param oldValue
* the old value
* @param newValue
* the new value
*/
protected void firePropertyChange(String propertyName, Object oldValue, Object newValue) {
propertyChangeSupport.firePropertyChange(propertyName, oldValue, newValue);
}
}
| 2,043 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
Progress.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter/src/net/heartsome/cat/converter/util/Progress.java | package net.heartsome.cat.converter.util;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.SubProgressMonitor;
/**
* 管理 progress monitor 的帮助类
* @author cheney
*/
public final class Progress {
/**
* 私有构建函数,防止类会外部实例化
*/
private Progress() {
}
/**
* 对 monitor 进行检查,如果为 <code>NULL</code> 则返回<code>NullProgressMonitor</code>
* @param monitor
* @return ;
*/
public static IProgressMonitor getMonitor(IProgressMonitor monitor) {
return monitor == null ? new NullProgressMonitor() : monitor;
}
/**
* 返回<code>SubProgressMonitor</code>
* @param parent
* @param ticks
* @return ;
*/
public static IProgressMonitor getSubMonitor(IProgressMonitor parent, int ticks) {
return new SubProgressMonitor(getMonitor(parent), ticks, SubProgressMonitor.PREPEND_MAIN_LABEL_TO_SUBTASK);
}
/**
* 返回<code>NullProgressMonitor</code>
* @return ;
*/
public static IProgressMonitor getMonitor() {
return new NullProgressMonitor();
}
}
| 1,123 | 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/src/net/heartsome/cat/converter/resource/Messages.java | package net.heartsome.cat.converter.resource;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
/**
* 国际化工具类
* @author peason
* @version
* @since JDK1.6
*/
public class Messages {
private static final String BUNDLE_NAME = "net.heartsome.cat.converter.resource.message";
private static ResourceBundle BUNDLE = ResourceBundle.getBundle(BUNDLE_NAME);
public static String getString(String key) {
try {
return BUNDLE.getString(key);
} catch (MissingResourceException e) {
return key;
}
}
}
| 556 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
Resx2XliffTest.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.resx/testSrc/net/heartsome/cat/converter/resx/test/Resx2XliffTest.java | package net.heartsome.cat.converter.resx.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.resx.Resx2Xliff;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.Test;
public class Resx2XliffTest {
public static Resx2Xliff converter = new Resx2Xliff();
private static String srcFile = "rc/Test.resx";
private static String sklFile = "rc/Test.resx.skl";
private static String xlfFile = "rc/Test.resx.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, "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, 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, "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, 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, "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());
}
@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, "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);
args.put(Converter.ATTR_IS_RESX, Converter.TRUE);
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,894 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
Xliff2ResxTest.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.resx/testSrc/net/heartsome/cat/converter/resx/test/Xliff2ResxTest.java | package net.heartsome.cat.converter.resx.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.resx.Xliff2Resx;
import org.junit.Before;
import org.junit.Test;
public class Xliff2ResxTest {
public static Xliff2Resx converter = new Xliff2Resx();
private static String tgtFile = "rc/Test_en-US.resx";
private static String sklFile = "rc/Test.resx.skl";
private static String xlfFile = "rc/Test.resx.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);
args.put(Converter.ATTR_XLIFF_FILE, xlfFile);
args.put(Converter.ATTR_SKELETON_FILE, sklFile);
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());
}
}
| 1,535 | 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.resx/src/net/heartsome/cat/converter/resx/Activator.java | /**
* Activator.java
*
* Version information :
*
* Date:Jan 14, 2010
*
* Copyright notice :
*/
package net.heartsome.cat.converter.resx;
import java.util.Properties;
import net.heartsome.cat.converter.Converter;
import net.heartsome.cat.converter.util.AndFilter;
import net.heartsome.cat.converter.util.ConverterRegister;
import net.heartsome.cat.converter.util.EqFilter;
import net.heartsome.cat.converter.xml.Xliff2Xml;
import net.heartsome.cat.converter.xml.Xml2Xliff;
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.resx";
// 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 xml converter service
String positiveFilter = new AndFilter(new EqFilter(Constants.OBJECTCLASS, Converter.class.getName()),
new EqFilter(Converter.ATTR_TYPE, Xml2Xliff.TYPE_VALUE), new EqFilter(Converter.ATTR_DIRECTION,
Converter.DIRECTION_POSITIVE)).toString();
positiveTracker = new ServiceTracker(context, context.createFilter(positiveFilter), new XmlPositiveCustomizer());
positiveTracker.open();
String reverseFilter = new AndFilter(new EqFilter(Constants.OBJECTCLASS, Converter.class.getName()),
new EqFilter(Converter.ATTR_TYPE, Xliff2Xml.TYPE_VALUE), new EqFilter(Converter.ATTR_DIRECTION,
Converter.DIRECTION_REVERSE)).toString();
reverseTracker = new ServiceTracker(context, context.createFilter(reverseFilter), new XmlReverseCustomize());
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 xML converter.
* @param direction
* the direction
* @return the xML converter
*/
public static Converter getXMLConverter(String direction) {
if (Converter.DIRECTION_POSITIVE.equals(direction)) {
return new Xml2Xliff();
} else {
return new Xliff2Xml();
}
}
/**
* The Class XmlPositiveCustomizer.
* @author John Zhu
* @version
* @since JDK1.6
*/
private class XmlPositiveCustomizer 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 Resx2Xliff(converter);
Properties properties = new Properties();
properties.put(Converter.ATTR_NAME, Resx2Xliff.NAME_VALUE);
properties.put(Converter.ATTR_TYPE, Resx2Xliff.TYPE_VALUE);
properties.put(Converter.ATTR_TYPE_NAME, Resx2Xliff.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 XmlReverseCustomize.
* @author John Zhu
* @version
* @since JDK1.6
*/
private class XmlReverseCustomize 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 Xliff2Resx(converter);
Properties properties = new Properties();
properties.put(Converter.ATTR_NAME, Xliff2Resx.NAME_VALUE);
properties.put(Converter.ATTR_TYPE, Xliff2Resx.TYPE_VALUE);
properties.put(Converter.ATTR_TYPE_NAME, Xliff2Resx.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);
}
}
}
| 6,998 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
Xliff2Resx.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.resx/src/net/heartsome/cat/converter/resx/Xliff2Resx.java | /**
* Xliff2Resx.java
*
* Version information :
*
* Date:Jan 14, 2010
*
* Copyright notice :
*/
package net.heartsome.cat.converter.resx;
/**
* @author Pablo
*
*/
import java.io.File;
import java.io.FileOutputStream;
import java.util.HashMap;
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.resx.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.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.runtime.IProgressMonitor;
import org.eclipse.core.runtime.OperationCanceledException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Node;
/**
* The Class Xliff2Resx.
* @author John Zhu
*/
public class Xliff2Resx implements Converter {
private static final Logger LOGGER = LoggerFactory.getLogger(Xliff2Resx.class);
/** The Constant TYPE_VALUE. */
public static final String TYPE_VALUE = "resx";
/** The Constant TYPE_NAME_VALUE. */
public static final String TYPE_NAME_VALUE = Messages.getString("resx.TYPE_NAME_VALUE");
/** The Constant NAME_VALUE. */
public static final String NAME_VALUE = "XLIFF to ResX Conveter";
// 内部实现所依赖的转换器
/** The dependant converter. */
private Converter dependantConverter;
/**
* for test to initialize depend on converter.
*/
public Xliff2Resx() {
dependantConverter = Activator.getXMLConverter(Converter.DIRECTION_REVERSE);
}
/**
* 运行时把所依赖的转换器,在初始化的时候通过构造函数注入。.
* @param converter
* the converter
*/
public Xliff2Resx(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 {
Xliff2ResxImpl converter = new Xliff2ResxImpl();
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 Xliff2ResxImpl.
* @author John Zhu
* @version
* @since JDK1.6
*/
class Xliff2ResxImpl {
/** The xml resx. */
private Document xmlResx; // Temporary xml for the conversion
/** The input file. */
private String inputFile;
/**
* 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 个任务,其中委派其它转换器进行转换占 5,读中间 xliff 文件占 2,处理所读取的 xliff 文件占 1,写 xliff 文件占 2。
monitor.beginTask("", 10);
// 委派进行转换
result = dependantConverter.convert(params, Progress.getSubMonitor(monitor, 5));
inputFile = params.get(Converter.ATTR_TARGET_FILE);
if (inputFile == null || "".equals(inputFile)) {
ConverterUtils.throwConverterException(Activator.PLUGIN_ID,
Messages.getString("resx.Xliff2Resx.msg1"));
}
File tgtFile = new File(inputFile);
if (!tgtFile.exists()) {
ConverterUtils.throwConverterException(Activator.PLUGIN_ID,
Messages.getString("resx.Xliff2Resx.msg1"));
}
String catalogue = params.get(Converter.ATTR_CATALOGUE);
// 是否取消操作
if (monitor.isCanceled()) {
throw new OperationCanceledException(Messages.getString("resx.cancel"));
}
monitor.subTask(Messages.getString("resx.Xliff2Resx.task2"));
long startTime = 0;
if (LOGGER.isInfoEnabled()) {
startTime = System.currentTimeMillis();
LOGGER.info(Messages.getString("resx.Xliff2Resx.logger1"), startTime);
}
xmlResx = openXml(inputFile, catalogue);
long endTime = 0;
if (LOGGER.isInfoEnabled()) {
endTime = System.currentTimeMillis();
LOGGER.info(Messages.getString("resx.Xliff2Resx.logger2"), endTime);
LOGGER.info(Messages.getString("resx.Xliff2Resx.logger3"), endTime - startTime);
}
monitor.worked(2);
// 是否取消操作
if (monitor.isCanceled()) {
throw new OperationCanceledException(Messages.getString("resx.cancel"));
}
monitor.subTask(Messages.getString("resx.Xliff2Resx.task3"));
if (LOGGER.isInfoEnabled()) {
startTime = System.currentTimeMillis();
LOGGER.info(Messages.getString("resx.Xliff2Resx.logger4"), startTime);
}
Element root = xmlResx.getRootElement();
List<Element> lstNodes = root.getChildren();
for (int i = 0; i < lstNodes.size(); i++) {
Element node = lstNodes.get(i);
List<Node> lstChilds = node.getContent();
for (int j = 0; j < lstChilds.size(); j++) {
if (lstChilds.get(j).getNodeType() == Node.ELEMENT_NODE) {
Element child = new Element(lstChilds.get(j));
if (isConvNode(child)) {
Element newChild = new Element("value", xmlResx); //$NON-NLS-1$
newChild.clone(child, xmlResx);
lstChilds.set(j, newChild.getElement());
}
}
}
node.setContent(lstChilds);
}
if (LOGGER.isInfoEnabled()) {
endTime = System.currentTimeMillis();
LOGGER.info(Messages.getString("resx.Xliff2Resx.logger5"), endTime);
LOGGER.info(Messages.getString("resx.Xliff2Resx.logger6"), endTime - startTime);
}
monitor.worked(1);
// 是否取消操作
if (monitor.isCanceled()) {
throw new OperationCanceledException(Messages.getString("resx.cancel"));
}
monitor.subTask(Messages.getString("resx.Xliff2Resx.task4"));
if (LOGGER.isInfoEnabled()) {
startTime = System.currentTimeMillis();
LOGGER.info(Messages.getString("resx.Xliff2Resx.logger7"), startTime);
}
saveXml(xmlResx, inputFile);
if (LOGGER.isInfoEnabled()) {
endTime = System.currentTimeMillis();
LOGGER.info(Messages.getString("resx.Xliff2Resx.logger8"), endTime);
LOGGER.info(Messages.getString("resx.Xliff2Resx.logger9"), endTime - startTime);
}
monitor.worked(2);
} catch (Exception e) {
if (Converter.DEBUG_MODE) {
e.printStackTrace();
}
ConverterUtils.throwConverterException(Activator.PLUGIN_ID, Messages.getString("resx.Xliff2Resx.msg1"),
e);
} finally {
monitor.done();
}
infoLogger.endConversion();
return result;
}
}
/**
* Checks if is conv node.
* @param node
* the node
* @return true, if is conv node
*/
private static boolean isConvNode(Element node) {
return node.getName().equals("translate"); //$NON-NLS-1$
}
/**
* Open xml.
* @param filename
* the filename
* @param catalogue
* the catalogue
* @return the document
* @throws Exception
* the exception
*/
private static Document openXml(String filename, String catalogue) throws Exception {
SAXBuilder builder = new SAXBuilder();
builder.setEntityResolver(new Catalogue(catalogue));
return builder.build(filename);
}
// Save the xml to a file
/**
* Save xml.
* @param xmlDoc
* the xml doc
* @param xmlFile
* the xml file
* @throws Exception
* the exception
*/
private static void saveXml(Document xmlDoc, String xmlFile) throws Exception {
XMLOutputter outputter = new XMLOutputter();
outputter.preserveSpace(true);
FileOutputStream soutput = new FileOutputStream(xmlFile);
outputter.output(xmlDoc, soutput);
soutput.close();
}
}
| 8,989 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
Resx2Xliff.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.resx/src/net/heartsome/cat/converter/resx/Resx2Xliff.java | /**
* Resx2Xliff.java
*
* Version information :
*
* Date:Jan 14, 2010
*
* Copyright notice :
*/
package net.heartsome.cat.converter.resx;
import java.io.File;
import java.io.FileOutputStream;
import java.util.HashMap;
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.resx.resource.Messages;
import net.heartsome.cat.converter.util.ConverterUtils;
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.runtime.IProgressMonitor;
import org.eclipse.core.runtime.OperationCanceledException;
import org.w3c.dom.Node;
/**
* The Class Resx2Xliff.
* @author John Zhu
*/
public class Resx2Xliff implements Converter {
/** The Constant TYPE_VALUE. */
public static final String TYPE_VALUE = "resx";
/** The Constant TYPE_NAME_VALUE. */
public static final String TYPE_NAME_VALUE = Messages.getString("resx.TYPE_NAME_VALUE");
/** The Constant NAME_VALUE. */
public static final String NAME_VALUE = "ResX to XLIFF Conveter";
// 内部实现所依赖的转换器
/** The dependant converter. */
private Converter dependantConverter;
/**
* for test to initialize depend on converter.
*/
public Resx2Xliff() {
dependantConverter = Activator.getXMLConverter(Converter.DIRECTION_POSITIVE);
}
/**
* 运行时把所依赖的转换器,在初始化的时候通过构造函数注入。.
* @param converter
* the converter
*/
public Resx2Xliff(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 {
Resx2XliffImpl converter = new Resx2XliffImpl();
args.put(Converter.ATTR_FORMAT, TYPE_VALUE);
args.put(Converter.ATTR_IS_RESX, Converter.TRUE);
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 Resx2XliffImpl.
* @author John Zhu
* @version
* @since JDK1.6
*/
class Resx2XliffImpl {
/** The xml resx. */
private Document xmlResx; // Temporary xml for the conversion
/** The input file. */
private String inputFile;
/**
* 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 {
// 把转换过程分为四部分:构建源文件的 dom tree,处理内容节点,输出临时的 xml 文件,委托其它转换器对 xml 文件进行转换。
monitor.beginTask("", 4);
inputFile = params.get(Converter.ATTR_SOURCE_FILE);
String catalogue = params.get(Converter.ATTR_CATALOGUE);
// 检查是否取消操作
if (monitor.isCanceled()) {
throw new OperationCanceledException(Messages.getString("resx.cancel"));
}
monitor.subTask(Messages.getString("resx.Resx2Xliff.task2"));
xmlResx = openXml(inputFile, catalogue);
monitor.worked(1);
Element root = xmlResx.getRootElement();
List<Element> lstNodes = root.getChildren();
// 处理各个内容节点
IProgressMonitor subMonitor = Progress.getSubMonitor(monitor, 1);
subMonitor.beginTask(Messages.getString("resx.Resx2Xliff.task3"), lstNodes.size());
subMonitor.subTask("");
for (int i = 0; i < lstNodes.size(); i++) {
// 检查是否取消操作
if (subMonitor.isCanceled()) {
throw new OperationCanceledException(Messages.getString("resx.cancel"));
}
Element node = lstNodes.get(i);
if (node.getName().equals("data")) { //$NON-NLS-1$
if (isTrans(node) && !isSkipCommand(node)) {
List<Node> lstChilds = node.getContent();
for (int j = 0; j < lstChilds.size(); j++) {
Node childNode = lstChilds.get(j);
if (childNode.getNodeType() == Node.ELEMENT_NODE) {
Element eChild = new Element(childNode);
if (eChild.getName().equals("value")) { //$NON-NLS-1$
Element newChild = new Element("translate", xmlResx); //$NON-NLS-1$
newChild.clone(eChild, xmlResx);
lstChilds.set(j, newChild.getElement());
}
}
}
node.setContent(lstChilds);
}
}
subMonitor.worked(1);
}
subMonitor.done();
File tempFile = File.createTempFile("tempResx", ".tmp"); //$NON-NLS-1$ //$NON-NLS-2$
inputFile = tempFile.getAbsolutePath();
// 输出 xliff 文件
if (monitor.isCanceled()) {
throw new OperationCanceledException(Messages.getString("resx.cancel"));
}
monitor.subTask(Messages.getString("resx.Resx2Xliff.task4"));
saveXml(xmlResx, inputFile);
monitor.worked(1);
params.put(Converter.ATTR_SOURCE_FILE, inputFile);
params.put(Converter.ATTR_IS_RESX, Converter.TRUE);
result = dependantConverter.convert(params, Progress.getSubMonitor(monitor, 1));
tempFile.delete();
} catch (OperationCanceledException e) {
throw e;
} catch (Exception e) {
if (Converter.DEBUG_MODE) {
e.printStackTrace();
}
ConverterUtils.throwConverterException(Activator.PLUGIN_ID, Messages.getString("resx.Resx2Xliff.msg1"), e);
} finally {
monitor.done();
}
return result;
}
/**
* Open xml.
* @param filename
* the filename
* @param catalogue
* the catalogue
* @return the document
* @throws Exception
* the exception
*/
private Document openXml(String filename, String catalogue) throws Exception {
SAXBuilder builder = new SAXBuilder();
builder.setEntityResolver(new Catalogue(catalogue));
return builder.build(filename);
}
// Save the xml to a file
/**
* Save xml.
* @param xmlDoc
* the xml doc
* @param xmlFile
* the xml file
* @throws Exception
* the exception
*/
private void saveXml(Document xmlDoc, String xmlFile) throws Exception {
XMLOutputter outputter = new XMLOutputter();
outputter.preserveSpace(true);
FileOutputStream soutput = new FileOutputStream(xmlFile);
outputter.output(xmlDoc, soutput);
soutput.close();
}
}
/*
* Each data row contains a name, and value. The row also contains a type or mimetype. Type corresponds to a .NET
* class that support text/value conversion. Classes that don't support this are serialized and stored with the
* mimetype set.
*/
/**
* Checks if is trans.
* @param node
* the node
* @return true, if is trans
*/
private static boolean isTrans(Element node) {
if (node.getAttribute("mimetype") != null) { //$NON-NLS-1$
if (!node.getAttributeValue("mimetype").trim().equals("")) { //$NON-NLS-1$ //$NON-NLS-2$
return false;
}
}
return true;
}
/**
* Checks if is skip command.
* @param node
* the node
* @return true, if is skip command
*/
private static boolean isSkipCommand(Element node) {
// Search for the _skip command in comment tag
List<Element> children = node.getChildren("comment"); //$NON-NLS-1$
for (int i = 0; i < children.size(); i++) {
if (children.get(i).getText().equalsIgnoreCase("_skip")) { //$NON-NLS-1$
return true;
}
}
return false;
}
} | 8,574 | 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.resx/src/net/heartsome/cat/converter/resx/resource/Messages.java | /**
* Messages.java
*
* Version information :
*
* Date:Jan 14, 2010
*
* Copyright notice :
*/
package net.heartsome.cat.converter.resx.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.resx.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,020 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
ApplicationWorkbenchWindowAdvisor.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.convert.ui.example/src/net/heartsome/cat/convert/ui/ApplicationWorkbenchWindowAdvisor.java | package net.heartsome.cat.convert.ui;
import org.eclipse.swt.graphics.Point;
import org.eclipse.ui.application.ActionBarAdvisor;
import org.eclipse.ui.application.IActionBarConfigurer;
import org.eclipse.ui.application.IWorkbenchWindowConfigurer;
import org.eclipse.ui.application.WorkbenchWindowAdvisor;
public class ApplicationWorkbenchWindowAdvisor extends WorkbenchWindowAdvisor {
public ApplicationWorkbenchWindowAdvisor(IWorkbenchWindowConfigurer configurer) {
super(configurer);
}
public ActionBarAdvisor createActionBarAdvisor(
IActionBarConfigurer configurer) {
return new ApplicationActionBarAdvisor(configurer);
}
public void preWindowOpen() {
IWorkbenchWindowConfigurer configurer = getWindowConfigurer();
configurer.setInitialSize(new Point(400, 300));
configurer.setShowCoolBar(false);
configurer.setShowStatusLine(false);
configurer.setTitle("OSGI Services Demo");
}
@Override
public void postWindowOpen() {
super.postWindowOpen();
getWindowConfigurer().getWindow().getShell().setMaximized(true);
}
}
| 1,053 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
View.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.convert.ui.example/src/net/heartsome/cat/convert/ui/View.java | package net.heartsome.cat.convert.ui;
import java.util.Map;
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.MessageDialog;
import org.eclipse.jface.viewers.ComboViewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
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.Label;
import org.eclipse.ui.part.ViewPart;
public class View extends ViewPart {
public static final String ID = "net.heartsome.cat.convert.ui.view";
private ConverterViewModel positiveConverterViewModel;
private ConverterViewModel reverseConverterViewModel;
private ComboViewer positiveSupportList;
private ComboViewer reverseSupportList;
public void createPartControl(Composite parent) {
positiveConverterViewModel = new ConverterViewModel(Activator
.getContext(), Converter.DIRECTION_POSITIVE);
reverseConverterViewModel = new ConverterViewModel(Activator
.getContext(), Converter.DIRECTION_REVERSE);
GridLayout layout = new GridLayout(2, true);
parent.setLayout(layout);
Composite left = new Composite(parent, SWT.NONE);
left.setLayout(new GridLayout(2, false));
GridData gridData = new GridData();
gridData.horizontalAlignment = SWT.FILL;
gridData.grabExcessHorizontalSpace = true;
left.setLayoutData(gridData);
positiveSupportList = createConvertControl(
"Convert from Suport format to Xliff", left, true);
Composite right = new Composite(parent, SWT.NONE);
right.setLayout(new GridLayout(2, false));
gridData = new GridData();
gridData.horizontalAlignment = SWT.FILL;
gridData.grabExcessHorizontalSpace = true;
right.setLayoutData(gridData);
reverseSupportList = createConvertControl(
"Convert from Xliff to Support format", right, false);
bindValue();
}
private ComboViewer createConvertControl(String title, Composite composite,
boolean isPositive) {
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);
final Button button = new Button(composite, SWT.BORDER);
button.setText("Convert");
GridData buttonData = new GridData();
buttonData.horizontalAlignment = SWT.FILL;
button.setLayoutData(buttonData);
if (isPositive) {
button.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
String type = positiveConverterViewModel.getSelectedType();
if (type != null && !type.equals("")) {
Map<String, String> result = positiveConverterViewModel
.convert(null);
if (result != null) {
MessageDialog.openInformation(button.getShell(),
"Convert", "used '" + result.get("name")
+ "' to convert.");
} else {
MessageDialog
.openWarning(button.getShell(), "Warning",
"Can't find selected Converter.");
}
}
}
});
} else {
button.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
String type = reverseConverterViewModel.getSelectedType();
if (type != null && !type.equals("")) {
Map<String, String> result = reverseConverterViewModel
.convert(null);
if (result != null) {
MessageDialog.openInformation(button.getShell(),
"Convert", "used '" + result.get("name")
+ "' to convert.");
} else {
MessageDialog
.openWarning(button.getShell(), "Warning",
"Can't find selected Converter.");
}
}
}
});
}
return supportList;
}
private void bindValue() {
DataBindingContext dbc = new DataBindingContext();
ConverterUtil.bindValue(dbc, positiveSupportList,
positiveConverterViewModel);
ConverterUtil.bindValue(dbc, reverseSupportList,
reverseConverterViewModel);
}
/**
* Passing the focus request to the viewer's control.
*/
public void setFocus() {
}
@Override
public void dispose() {
super.dispose();
positiveConverterViewModel.close();
reverseConverterViewModel.close();
}
} | 5,008 | 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.convert.ui.example/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 {
// The plug-in ID
public static final String PLUGIN_ID = "net.heartsome.cat.convert.ui";
// The shared instance
private static Activator plugin;
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);
plugin = this;
Activator.context = context;
}
/*
* (non-Javadoc)
*
* @see
* org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext
* )
*/
public void stop(BundleContext context) throws Exception {
plugin = 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);
}
public static BundleContext getContext() {
return context;
}
}
| 1,545 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
ApplicationActionBarAdvisor.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.convert.ui.example/src/net/heartsome/cat/convert/ui/ApplicationActionBarAdvisor.java | package net.heartsome.cat.convert.ui;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.ui.IWorkbenchActionConstants;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.actions.ActionFactory;
import org.eclipse.ui.actions.ActionFactory.IWorkbenchAction;
import org.eclipse.ui.application.ActionBarAdvisor;
import org.eclipse.ui.application.IActionBarConfigurer;
/**
* An action bar advisor is responsible for creating, adding, and disposing of
* the actions added to a workbench window. Each window will be populated with
* new actions.
*/
public class ApplicationActionBarAdvisor extends ActionBarAdvisor {
// Actions - important to allocate these only in makeActions, and then use
// them
// in the fill methods. This ensures that the actions aren't recreated
// when fillActionBars is called with FILL_PROXY.
private IWorkbenchAction exitAction;
private IWorkbenchAction preferenceAction;
public ApplicationActionBarAdvisor(IActionBarConfigurer configurer) {
super(configurer);
}
protected void makeActions(final IWorkbenchWindow window) {
// Creates the actions and registers them.
// Registering is needed to ensure that key bindings work.
// The corresponding commands keybindings are defined in the plugin.xml
// file.
// Registering also provides automatic disposal of the actions when
// the window is closed.
exitAction = ActionFactory.QUIT.create(window);
register(exitAction);
preferenceAction=ActionFactory.PREFERENCES.create(window);
register(preferenceAction);
}
protected void fillMenuBar(IMenuManager menuBar) {
MenuManager fileMenu = new MenuManager("&File",
IWorkbenchActionConstants.M_FILE);
menuBar.add(fileMenu);
fileMenu.add(exitAction);
MenuManager editMenu = new MenuManager("&Edit",
IWorkbenchActionConstants.M_EDIT);
menuBar.add(editMenu);
editMenu.add(preferenceAction);
}
}
| 1,946 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
Perspective.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.convert.ui.example/src/net/heartsome/cat/convert/ui/Perspective.java | package net.heartsome.cat.convert.ui;
import org.eclipse.ui.IPageLayout;
import org.eclipse.ui.IPerspectiveFactory;
public class Perspective implements IPerspectiveFactory {
public void createInitialLayout(IPageLayout layout) {
String editorArea = layout.getEditorArea();
layout.setEditorAreaVisible(false);
layout.setFixed(true);
layout.addStandaloneView(View.ID, false, IPageLayout.LEFT, 1.0f, editorArea);
}
}
| 431 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
Application.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.convert.ui.example/src/net/heartsome/cat/convert/ui/Application.java | package net.heartsome.cat.convert.ui;
import org.eclipse.equinox.app.IApplication;
import org.eclipse.equinox.app.IApplicationContext;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.PlatformUI;
/**
* This class controls all aspects of the application's execution
*/
public class Application implements IApplication {
/* (non-Javadoc)
* @see org.eclipse.equinox.app.IApplication#start(org.eclipse.equinox.app.IApplicationContext)
*/
public Object start(IApplicationContext context) {
Display display = PlatformUI.createDisplay();
try {
int returnCode = PlatformUI.createAndRunWorkbench(display, new ApplicationWorkbenchAdvisor());
if (returnCode == PlatformUI.RETURN_RESTART) {
return IApplication.EXIT_RESTART;
}
return IApplication.EXIT_OK;
} finally {
display.dispose();
}
}
/* (non-Javadoc)
* @see org.eclipse.equinox.app.IApplication#stop()
*/
public void stop() {
final IWorkbench workbench = PlatformUI.getWorkbench();
if (workbench == null)
return;
final Display display = workbench.getDisplay();
display.syncExec(new Runnable() {
public void run() {
if (!display.isDisposed())
workbench.close();
}
});
}
}
| 1,238 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
ApplicationWorkbenchAdvisor.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.convert.ui.example/src/net/heartsome/cat/convert/ui/ApplicationWorkbenchAdvisor.java | package net.heartsome.cat.convert.ui;
import org.eclipse.ui.application.IWorkbenchWindowConfigurer;
import org.eclipse.ui.application.WorkbenchAdvisor;
import org.eclipse.ui.application.WorkbenchWindowAdvisor;
public class ApplicationWorkbenchAdvisor extends WorkbenchAdvisor {
private static final String PERSPECTIVE_ID = "net.heartsome.cat.convert.ui.perspective";
public WorkbenchWindowAdvisor createWorkbenchWindowAdvisor(
IWorkbenchWindowConfigurer configurer) {
return new ApplicationWorkbenchWindowAdvisor(configurer);
}
public String getInitialWindowPerspectiveId() {
return PERSPECTIVE_ID;
}
}
| 621 | 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.convert.ui.example/src/net/heartsome/cat/convert/ui/model/ConverterUtil.java | package net.heartsome.cat.convert.ui.model;
import net.heartsome.cat.converter.util.ConverterBean;
import org.eclipse.core.databinding.DataBindingContext;
import org.eclipse.core.databinding.beans.BeansObservables;
import org.eclipse.core.databinding.observable.value.IObservableValue;
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;
public class ConverterUtil {
private ConverterUtil() {
// TODO Auto-generated constructor stub
}
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, "name", ConverterBean.class);
context.bindValue(observableValue, BeansObservables
.observeValue(model,
"selectedType"));
}
}
| 2,046 | 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.convert.ui.example/src/net/heartsome/cat/convert/ui/model/ConverterViewModel.java | package net.heartsome.cat.convert.ui.model;
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.ConverterTracker;
import org.osgi.framework.BundleContext;
public class ConverterViewModel extends ConverterTracker {
public ConverterViewModel(BundleContext bundleContext, String direction) {
super(bundleContext, direction);
}
@Override
public Map<String, String> convert(Map<String, String> parameters) {
Converter converter=getConverter();
if (converter != null) {
System.out.println(""+converter.getName());
try {
converter.convert(null, null);
} catch (ConverterException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Map<String,String> result=new HashMap<String, String>(1);
result.put("name", converter.getName());
return result;
}
return null;
}
}
| 960 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
ApplicationWorkbenchWindowAdvisor.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.ui.application/src/net/heartsome/cat/converter/ui/application/ApplicationWorkbenchWindowAdvisor.java | package net.heartsome.cat.converter.ui.application;
import org.eclipse.swt.graphics.Point;
import org.eclipse.ui.application.ActionBarAdvisor;
import org.eclipse.ui.application.IActionBarConfigurer;
import org.eclipse.ui.application.IWorkbenchWindowConfigurer;
import org.eclipse.ui.application.WorkbenchWindowAdvisor;
/**
* Configures the initial size and appearance of a workbench window.
*/
public class ApplicationWorkbenchWindowAdvisor extends WorkbenchWindowAdvisor {
/**
* 构造函数
* @param configurer
*/
public ApplicationWorkbenchWindowAdvisor(IWorkbenchWindowConfigurer configurer) {
super(configurer);
}
/**
* (non-Javadoc)
* @see org.eclipse.ui.application.WorkbenchWindowAdvisor#createActionBarAdvisor(org.eclipse.ui.application.IActionBarConfigurer)
*/
public ActionBarAdvisor createActionBarAdvisor(IActionBarConfigurer configurer) {
return new ApplicationActionBarAdvisor(configurer);
}
/**
* (non-Javadoc)
* @see org.eclipse.ui.application.WorkbenchWindowAdvisor#preWindowOpen()
*/
public void preWindowOpen() {
IWorkbenchWindowConfigurer configurer = getWindowConfigurer();
configurer.setInitialSize(new Point(400, 300));
configurer.setShowCoolBar(false);
configurer.setShowStatusLine(false);
configurer.setTitle("RAP Converter Application");
}
@Override
public void postWindowOpen() {
super.postWindowOpen();
getWindowConfigurer().getWindow().getShell().setMaximized(true);
}
}
| 1,457 | 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.application/src/net/heartsome/cat/converter/ui/application/Activator.java | package net.heartsome.cat.converter.ui.application;
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 {
/**
* 插件 ID
*/
public static final String PLUGIN_ID = "net.heartsome.cat.converter.ui.application";
// The shared instance
private static Activator plugin;
/**
* 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);
plugin = this;
}
/**
* (non-Javadoc)
*
* @see org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext)
*/
public void stop(BundleContext context) throws Exception {
plugin = 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);
}
}
| 1,411 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
ApplicationActionBarAdvisor.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.ui.application/src/net/heartsome/cat/converter/ui/application/ApplicationActionBarAdvisor.java | package net.heartsome.cat.converter.ui.application;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.ui.IWorkbenchActionConstants;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.actions.ActionFactory;
import org.eclipse.ui.actions.ActionFactory.IWorkbenchAction;
import org.eclipse.ui.application.ActionBarAdvisor;
import org.eclipse.ui.application.IActionBarConfigurer;
/**
* Creates, adds and disposes actions for the menus and action bars of each workbench window.
*/
public class ApplicationActionBarAdvisor extends ActionBarAdvisor {
private IWorkbenchAction exitAction;
private IWorkbenchAction preferenceAction;
/**
* 构造函数
* @param configurer
*/
public ApplicationActionBarAdvisor(IActionBarConfigurer configurer) {
super(configurer);
}
@Override
protected void makeActions(IWorkbenchWindow window) {
exitAction = ActionFactory.QUIT.create(window);
register(exitAction);
preferenceAction = ActionFactory.PREFERENCES.create(window);
register(preferenceAction);
}
@Override
protected void fillMenuBar(IMenuManager menuBar) {
MenuManager fileMenu = new MenuManager("&File", IWorkbenchActionConstants.M_FILE);
menuBar.add(fileMenu);
fileMenu.add(exitAction);
MenuManager editMenu = new MenuManager("&Edit", IWorkbenchActionConstants.M_EDIT);
menuBar.add(editMenu);
editMenu.add(preferenceAction);
}
}
| 1,438 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
Perspective.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.ui.application/src/net/heartsome/cat/converter/ui/application/Perspective.java | package net.heartsome.cat.converter.ui.application;
import org.eclipse.ui.IPageLayout;
import org.eclipse.ui.IPerspectiveFactory;
/**
* Configures the perspective layout. This class is contributed through the plugin.xml.
*/
public class Perspective implements IPerspectiveFactory {
/**
* (non-Javadoc)
* @see org.eclipse.ui.IPerspectiveFactory#createInitialLayout(org.eclipse.ui.IPageLayout)
*/
public void createInitialLayout(IPageLayout layout) {
}
}
| 467 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
Application.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.ui.application/src/net/heartsome/cat/converter/ui/application/Application.java | package net.heartsome.cat.converter.ui.application;
import org.eclipse.rwt.lifecycle.IEntryPoint;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.application.WorkbenchAdvisor;
/**
* This class controls all aspects of the application's execution and is contributed through the plugin.xml.
*/
public class Application implements IEntryPoint {
@Override
public int createUI() {
Display display = PlatformUI.createDisplay();
WorkbenchAdvisor advisor = new ApplicationWorkbenchAdvisor();
return PlatformUI.createAndRunWorkbench(display, advisor);
}
}
| 608 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
ApplicationWorkbenchAdvisor.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.ui.application/src/net/heartsome/cat/converter/ui/application/ApplicationWorkbenchAdvisor.java | package net.heartsome.cat.converter.ui.application;
import org.eclipse.ui.application.IWorkbenchWindowConfigurer;
import org.eclipse.ui.application.WorkbenchAdvisor;
import org.eclipse.ui.application.WorkbenchWindowAdvisor;
/**
* This workbench advisor creates the window advisor, and specifies the perspective id for the initial window.
*/
public class ApplicationWorkbenchAdvisor extends WorkbenchAdvisor {
private static final String PERSPECTIVE_ID = "net.heartsome.cat.converter.ui.application.perspective";
@Override
public WorkbenchWindowAdvisor createWorkbenchWindowAdvisor(IWorkbenchWindowConfigurer configurer) {
return new ApplicationWorkbenchWindowAdvisor(configurer);
}
@Override
public String getInitialWindowPerspectiveId() {
return PERSPECTIVE_ID;
}
}
| 785 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
FileDialogFactoryFacadeImpl.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.ui.rap/src/net/heartsome/cat/convert/ui/dialog/FileDialogFactoryFacadeImpl.java | package net.heartsome.cat.convert.ui.dialog;
import org.eclipse.swt.widgets.Shell;
/**
* RAP 环境中的文件对话框工厂门面实现
* @author cheney
* @since JDK1.6
*/
public class FileDialogFactoryFacadeImpl extends FileDialogFactoryFacade {
// 返回文件上传对话框
@Override
protected IConversionItemDialog createFileDialogInternal(Shell shell, int styled) {
return createFileUploadDialog(shell, styled);
}
// 返回文件上传对话框
@Override
protected IConversionItemDialog createWorkspaceDialogInternal(Shell shell, int styled) {
return createFileUploadDialog(shell, styled);
}
/**
* 创建文件上传对话框实例并返回
* @param shell
* @param styled
* @return ;
*/
private IConversionItemDialog createFileUploadDialog(Shell shell, int styled) {
return new FileUploadConversionItemDialog(shell);
}
}
| 867 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
FileUploadConversionItemDialog.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.ui.rap/src/net/heartsome/cat/convert/ui/dialog/FileUploadConversionItemDialog.java | package net.heartsome.cat.convert.ui.dialog;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import net.heartsome.cat.convert.ui.model.DefaultConversionItem;
import net.heartsome.cat.convert.ui.model.IConversionItem;
import org.eclipse.core.runtime.Path;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.dialogs.TitleAreaDialog;
import org.eclipse.jface.layout.GridLayoutFactory;
import org.eclipse.jface.layout.LayoutConstants;
import org.eclipse.rwt.widgets.Upload;
import org.eclipse.rwt.widgets.UploadAdapter;
import org.eclipse.rwt.widgets.UploadEvent;
import org.eclipse.rwt.widgets.UploadItem;
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.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Shell;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* 文件上传对话框
* @author cheney
*/
class FileUploadConversionItemDialog implements IConversionItemDialog {
private static final Logger LOGGER = LoggerFactory.getLogger(FileUploadConversionItemDialog.class);
private FileUploadDialog dialog;
private IConversionItem conversionItem;
/**
* 构建函数
* @param shell
*/
public FileUploadConversionItemDialog(Shell shell) {
dialog = new FileUploadDialog(shell);
}
@Override
public int open() {
int result = dialog.open();
UploadItem uploadItem = null;
if (result == IDialogConstants.OK_ID) {
uploadItem = dialog.getLastUploadItem();
if (uploadItem != null) {
InputStream is = uploadItem.getFileInputStream();
// 把文件流写到临时目录中
if (is != null) {
File file = null;
OutputStream os = null;
try {
file = File.createTempFile("conversion", "co");
os = new FileOutputStream(file);
byte[] buffer = new byte[2048];
int length = -1;
while ((length = is.read(buffer)) != -1) {
os.write(buffer, 0, length);
}
os.flush();
} catch (FileNotFoundException e) {
if (LOGGER.isErrorEnabled()) {
LOGGER.error("文件不存在。", e);
}
} catch (IOException e) {
if (LOGGER.isErrorEnabled()) {
LOGGER.error("操作文件失败。", e);
}
} finally {
try {
if (os != null) {
os.close();
}
if (is != null) {
is.close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
conversionItem = new DefaultConversionItem(new Path(file.getAbsolutePath()));
return IDialogConstants.OK_ID;
}
}
}
return IDialogConstants.CANCEL_ID;
}
@Override
public IConversionItem getConversionItem() {
if (conversionItem == null) {
conversionItem = DefaultConversionItem.EMPTY_CONVERSION_ITEM;
}
return conversionItem;
}
/**
* 文件上传对话框的具体实现
* @author cheney
* @since JDK1.6
*/
private static class FileUploadDialog extends TitleAreaDialog {
private Upload upload;
// 最后上传成功的 upload item
private UploadItem lastUploadItem;
private Shell shell;
/**
* 构造函数
* @param parentShell
*/
public FileUploadDialog(Shell parentShell) {
super(parentShell);
setTitle("上传文件");
// setMessage("请选择需要上传的文件");
}
@Override
protected Control createDialogArea(Composite parent) {
shell = parent.getShell();
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 uploadComposite = new Composite(contents, SWT.NONE);
uploadComposite.setLayout(new GridLayout());
gridData = new GridData();
gridData.horizontalAlignment = SWT.FILL;
gridData.grabExcessHorizontalSpace = true;
uploadComposite.setLayoutData(gridData);
upload = new Upload(uploadComposite, SWT.BORDER, Upload.SHOW_UPLOAD_BUTTON | Upload.SHOW_PROGRESS);
gridData = new GridData();
gridData.horizontalAlignment = SWT.FILL;
gridData.grabExcessHorizontalSpace = true;
upload.setLayoutData(gridData);
upload.addUploadListener(new UploadAdapter() {
@Override
public void uploadFinished(UploadEvent uploadEvent) {
if (uploadEvent.isFinished()) {
MessageDialog.openInformation(shell, "上传成功", "文件上传成功");
// 确保关闭之前的文件 IO
if (lastUploadItem != null) {
InputStream is = lastUploadItem.getFileInputStream();
if (is != null) {
try {
is.close();
} catch (IOException e) {
// ignore the exception
if (LOGGER.isErrorEnabled()) {
LOGGER.error("关闭上传的文件流失败。", e);
}
}
}
}
lastUploadItem = upload.getUploadItem();
}
}
});
Dialog.applyDialogFont(parentComposite);
Point defaultMargins = LayoutConstants.getMargins();
GridLayoutFactory.fillDefaults().numColumns(2).margins(defaultMargins.x, defaultMargins.y).generateLayout(
contents);
return contents;
}
/**
* 获得最后一次上传的 upload item
* @return
*/
public UploadItem getLastUploadItem() {
return lastUploadItem;
}
}
}
| 5,775 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
JobFactoryFacadeImpl.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.ui.rap/src/net/heartsome/cat/convert/ui/job/JobFactoryFacadeImpl.java | package net.heartsome.cat.convert.ui.job;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.rwt.lifecycle.UICallBack;
import org.eclipse.swt.widgets.Display;
/**
* 创建执行文件转换的 job
* @author cheney
*/
public class JobFactoryFacadeImpl extends JobFactoryFacade {
@Override
protected Job createJobInternal(final Display display, final String name, final JobRunnable runnable) {
Job job = new Job(name) {
final IStatus[] result = new IStatus[1];
@Override
protected IStatus run(final IProgressMonitor monitor) {
// 允许后台线程访问 session 级别的用户数据
UICallBack.runNonUIThreadWithFakeContext(display, new Runnable() {
@Override
public void run() {
result[0] = runnable.run(monitor);
}
});
return result[0];
}
};
return job;
}
}
| 928 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
Properties2XliffTest.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.javaproperties/testSrc/net/heartsome/cat/converter/javaproperties/test/Properties2XliffTest.java | package net.heartsome.cat.converter.javaproperties.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.javaproperties.Properties2Xliff;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.Test;
public class Properties2XliffTest {
public static Properties2Xliff converter = new Properties2Xliff();
private static String srcFile = "rc/Test.properties";
private static String xlfFile = "rc/Test.properties.xlf";
private static String sklFile = "rc/Test.properties.skl";
@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,738 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
Xliff2PropertiesTest.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.javaproperties/testSrc/net/heartsome/cat/converter/javaproperties/test/Xliff2PropertiesTest.java | package net.heartsome.cat.converter.javaproperties.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.javaproperties.Xliff2Properties;
import org.junit.Before;
import org.junit.Test;
public class Xliff2PropertiesTest {
public static Xliff2Properties converter = new Xliff2Properties();
private static String tgtFile = "rc/Test_zh-CN.properties";
private static String xlfFile = "rc/Test.properties.xlf";
private static String sklFile = "rc/Test.properties.skl";
@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_ENCODING, "UTF-8"); //$NON-NLS-1$
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,597 | 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.javaproperties/src/net/heartsome/cat/converter/javaproperties/Activator.java | /**
* Activator.java
*
* Version information :
*
* Date:Jan 14, 2010
*
* Copyright notice :
*/
package net.heartsome.cat.converter.javaproperties;
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.javaproperties";
/** The plugin. The shared instance */
private static Activator plugin;
/** The properties2 xliff sr. */
private ServiceRegistration properties2XliffSR;
/** The xliff2 properties sr. */
private ServiceRegistration xliff2PropertiesSR;
/**
* 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 properties2Xliff = new Properties2Xliff();
Properties properties = new Properties();
properties.put(Converter.ATTR_NAME, Properties2Xliff.NAME_VALUE);
properties.put(Converter.ATTR_TYPE, Properties2Xliff.TYPE_VALUE);
properties.put(Converter.ATTR_TYPE_NAME, Properties2Xliff.TYPE_NAME_VALUE);
properties2XliffSR = ConverterRegister.registerPositiveConverter(context, properties2Xliff, properties);
Converter xliff2Properties = new Xliff2Properties();
properties = new Properties();
properties.put(Converter.ATTR_NAME, Xliff2Properties.NAME_VALUE);
properties.put(Converter.ATTR_TYPE, Xliff2Properties.TYPE_VALUE);
properties.put(Converter.ATTR_TYPE_NAME, Xliff2Properties.TYPE_NAME_VALUE);
xliff2PropertiesSR = ConverterRegister.registerReverseConverter(context, xliff2Properties, 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 (properties2XliffSR != null) {
properties2XliffSR.unregister();
}
if (xliff2PropertiesSR != null) {
xliff2PropertiesSR.unregister();
}
plugin = null;
}
/**
* Returns the shared instance.
* @return the shared instance
*/
public static Activator getDefault() {
return plugin;
}
}
| 2,769 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
Xliff2Properties.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.javaproperties/src/net/heartsome/cat/converter/javaproperties/Xliff2Properties.java | /**
* Xliff2Properties.java
*
* Version information :
*
* Date:Jan 14, 2010
*
* Copyright notice :
*/
package net.heartsome.cat.converter.javaproperties;
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.javaproperties.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 Xliff2Properties.
* @author John Zhu
* @version
* @since JDK1.6
*/
public class Xliff2Properties implements Converter {
/** The Constant TYPE_VALUE. */
public static final String TYPE_VALUE = "javalistresourcebundle";
/** The Constant TYPE_NAME_VALUE. */
public static final String TYPE_NAME_VALUE = Messages.getString("javaproperties.TYPE_NAME_VALUE");
/** The Constant NAME_VALUE. */
public static final String NAME_VALUE = "XLIFF to Java Properties Conveter";
/**
* (non-Javadoc).
* @param args
* the args
* @param monitor
* the monitor
* @return the map< string, string>
* @throws ConverterException
* the converter exception
* @see net.heartsome.cat.converter.Converter#convert(java.util.Map, org.eclipse.core.runtime.IProgressMonitor)
*/
public Map<String, String> convert(Map<String, String> args, IProgressMonitor monitor) throws ConverterException {
Xliff2PropertiesImpl converter = new Xliff2PropertiesImpl();
return converter.run(args, monitor);
}
/**
* (non-Javadoc).
* @return the name
* @see net.heartsome.cat.converter.Converter#getName()
*/
public String getName() {
return NAME_VALUE;
}
/**
* (non-Javadoc).
* @return the type
* @see net.heartsome.cat.converter.Converter#getType()
*/
public String getType() {
return TYPE_VALUE;
}
/**
* (non-Javadoc).
* @return the type name
* @see net.heartsome.cat.converter.Converter#getTypeName()
*/
public String getTypeName() {
return TYPE_NAME_VALUE;
}
/**
* The Class Xliff2PropertiesImpl.
* @author John Zhu
* @version
* @since JDK1.6
*/
class Xliff2PropertiesImpl {
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;
// 计算替换进度的对象
private CalculateProcessedBytes cpb;
// 替换过程的进度监视器
private IProgressMonitor replaceMonitor;
/**
* 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 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 {
infoLogger.logConversionFileInfo(catalogueFile, null, xliffFile, sklFile);
// 把转换过程的进度分为 10,其中加载 catalogue 占 2,加载 xliff 文件占 3,替换过程占 5。
monitor.beginTask("", 10);
monitor.subTask(Messages.getString("javaproperties.Xliff2Properties.task1"));
try {
infoLogger.startLoadingCatalogueFile();
if (catalogueFile != null) {
catalogue = new Catalogue(catalogueFile);
}
infoLogger.endLoadingCatalogueFile();
monitor.worked(2);
// 是否取消操作
if (monitor.isCanceled()) {
throw new OperationCanceledException(Messages.getString("javaproperties.cancel"));
}
infoLogger.startLoadingIniFile();
output = new FileOutputStream(outputFile);
loadSegments(Progress.getSubMonitor(monitor, 3));
infoLogger.endLoadingXliffFile();
} catch (OperationCanceledException e) {
throw e;
} catch (Exception e1) {
if (Converter.DEBUG_MODE) {
e1.printStackTrace();
}
ConverterUtils.throwConverterException(Activator.PLUGIN_ID,
Messages.getString("javaproperties.Xliff2Properties.msg1"), e1);
}
try {
// 初始化计算替换进度的对象O
cpb = ConverterUtils.getCalculateProcessedBytes(sklFile);
replaceMonitor = Progress.getSubMonitor(monitor, 5);
replaceMonitor.beginTask(Messages.getString("javaproperties.Xliff2Properties.task2"), cpb.getTotalTask());
replaceMonitor.subTask("");
infoLogger.startReplacingSegmentSymbol();
input = new InputStreamReader(new FileInputStream(sklFile), "UTF-8"); //$NON-NLS-1$
buffer = new BufferedReader(input);
line = buffer.readLine();
while (line != null) {
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())) {
writeString(tgtStr, true, code);
} else {
writeString(extractText(source), true, code);
}
} else {
writeString(extractText(source), true, code);
}
} else {
MessageFormat mf = new MessageFormat(Messages.getString("javaproperties.Xliff2Properties.msg0")); //$NON-NLS-1$
Object[] args = { "" + code }; //$NON-NLS-1$
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();
}
infoLogger.endReplacingSegmentSymbol();
output.close();
result.put(Converter.ATTR_TARGET_FILE, outputFile);
infoLogger.endConversion();
} catch (OperationCanceledException e) {
throw e;
} catch (Exception e) {
if (Converter.DEBUG_MODE) {
e.printStackTrace();
}
ConverterUtils.throwConverterException(Activator.PLUGIN_ID,
Messages.getString("javaproperties.Xliff2Properties.msg2"), e);
} finally {
replaceMonitor.done();
}
} finally {
// 保证 monitor 的 done 被调用
monitor.done();
}
return result;
}
/**
* Load segments.
* @throws SAXException
* the SAX exception
* @throws IOException
* Signals that an I/O exception has occurred.
*/
private void loadSegments(IProgressMonitor monitor) throws SAXException, IOException {
try {
monitor.beginTask(Messages.getString("javaproperties.Xliff2Properties.msg3"), IProgressMonitor.UNKNOWN);
monitor.subTask("");
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()) {
// 是否取消操作
if (monitor.isCanceled()) {
throw new OperationCanceledException(Messages.getString("javaproperties.cancel"));
}
Element unit = i.next();
segments.put(unit.getAttributeValue("id"), unit); //$NON-NLS-1$
}
} finally {
monitor.done();
}
}
/**
* Write string.
* @param string
* the string
* @throws IOException
* Signals that an I/O exception has occurred.
*/
private void writeString(String string) throws IOException {
writeString(string, false, null);
}
/**
* Write string.
* @param string
* the string
* @param isSegment
* 标识当前所写内容,ture 标识当前所写内容为 segment,false 标识当前所定内容为原骨架文件中的内容。
* @param replaceCode
* skeleton 文件中的segment 标识符
* @throws IOException
* Signals that an I/O exception has occurred.
*/
private void writeString(String string, boolean isSegment, String replaceCode) throws IOException {
byte[] bytes = string.getBytes(encoding);
output.write(bytes);
// 是否取消操作
if (replaceMonitor.isCanceled()) {
throw new OperationCanceledException(Messages.getString("javaproperties.cancel"));
}
// 在计算已处理的字节时,需要用 skeleton 文件的源编码进行解码
if (!isSegment) {
cpb.calculateProcessed(replaceMonitor, string, UTF_8);
} else {
replaceCode = "%%%" + replaceCode + "%%%";
cpb.calculateProcessed(replaceMonitor, replaceCode, UTF_8);
}
}
}
/**
* Extract text.
* @param target
* the target
* @return the string
*/
private static 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 cleanChars(result);
}
/**
* Clean chars.
* @param string
* the string
* @return the string
*/
private static String cleanChars(String string) {
String result = ""; //$NON-NLS-1$
int size = string.length();
for (int i = 0; i < size; i++) {
char c = string.charAt(i);
if (c <= 255) {
result = result + c;
} else {
result = result + toHex(c);
}
}
return result;
}
/**
* To hex.
* @param c
* the c
* @return the string
*/
private static String toHex(char c) {
String hex = Integer.toHexString(c);
while (hex.length() < 4) {
hex = "0" + hex; //$NON-NLS-1$
}
return "\\u" + hex; //$NON-NLS-1$
}
}
| 12,837 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
Properties2Xliff.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.javaproperties/src/net/heartsome/cat/converter/javaproperties/Properties2Xliff.java | /**
* Properties2Xliff.java
*
* Version information :
*
* Date:Jan 14, 2010
*
* Copyright notice :
*/
package net.heartsome.cat.converter.javaproperties;
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.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import net.heartsome.cat.converter.Converter;
import net.heartsome.cat.converter.ConverterException;
import net.heartsome.cat.converter.StringSegmenter;
import net.heartsome.cat.converter.javaproperties.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 Properties2Xliff.
* @author John Zhu
* @version
* @since JDK1.6
*/
public class Properties2Xliff implements Converter {
/** The Constant TYPE_VALUE. */
public static final String TYPE_VALUE = "javalistresourcebundle";
/** The Constant TYPE_NAME_VALUE. */
public static final String TYPE_NAME_VALUE = Messages.getString("javaproperties.TYPE_NAME_VALUE");
/** The Constant NAME_VALUE. */
public static final String NAME_VALUE = "Java Properties to XLIFF Conveter";
/**
* (non-Javadoc).
* @param args
* the args
* @param monitor
* the monitor
* @return the map< string, string>
* @throws ConverterException
* the converter exception
* @see net.heartsome.cat.converter.Converter#convert(java.util.Map, org.eclipse.core.runtime.IProgressMonitor)
*/
public Map<String, String> convert(Map<String, String> args, IProgressMonitor monitor) throws ConverterException {
Properties2XliffImpl converter = new Properties2XliffImpl();
return converter.run(args, monitor);
}
/**
* (non-Javadoc).
* @return the name
* @see net.heartsome.cat.converter.Converter#getName()
*/
public String getName() {
return NAME_VALUE;
}
/**
* (non-Javadoc).
* @return the type
* @see net.heartsome.cat.converter.Converter#getType()
*/
public String getType() {
return TYPE_VALUE;
}
/**
* (non-Javadoc).
* @return the type name
* @see net.heartsome.cat.converter.Converter#getTypeName()
*/
public String getTypeName() {
return TYPE_NAME_VALUE;
}
/**
* The Class Properties2XliffImpl.
* @author John Zhu
* @version
* @since JDK1.6
*/
class Properties2XliffImpl {
/** 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;
/**
* 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>();
segId = 0;
inputFile = params.get(Converter.ATTR_SOURCE_FILE);
xliffFile = params.get(Converter.ATTR_XLIFF_FILE);
skeletonFile = params.get(Converter.ATTR_SKELETON_FILE);
targetLanguage = params.get(Converter.ATTR_TARGET_LANGUAGE);
sourceLanguage = params.get(Converter.ATTR_SOURCE_LANGUAGE);
String srcEncoding = params.get(Converter.ATTR_SOURCE_ENCODING);
String catalogue = params.get(Converter.ATTR_CATALOGUE);
String elementSegmentation = params.get(Converter.ATTR_SEG_BY_ELEMENT);
boolean isSuite = false;
if (Converter.TRUE.equalsIgnoreCase(params.get(Converter.ATTR_IS_SUITE))) {
isSuite = true;
}
String qtToolID = params.get(Converter.ATTR_QT_TOOLID) != null ? params.get(Converter.ATTR_QT_TOOLID)
: Converter.QT_TOOLID_DEFAULT_VALUE;
if (elementSegmentation == null) {
segByElement = false;
} else {
if (elementSegmentation.equals(Converter.TRUE)) {
segByElement = true;
} else {
segByElement = false;
}
}
source = "";
try {
// 计算总任务数
File temp = new File(inputFile);
long totalSize = 0;
if (temp.exists()) {
totalSize = temp.length();
}
CalculateProcessedBytes cpb = ConverterUtils.getCalculateProcessedBytes(totalSize);
monitor.beginTask(Messages.getString("javaproperties.Properties2Xliff.task1"), cpb.getTotalTask());
monitor.subTask("");
// if (segByElement == false) {
if (!segByElement) {
String initSegmenter = params.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\" " + //$NON-NLS-1$
"xmlns:hs=\"" + Converter.HSNAMESPACE + "\" " + //$NON-NLS-1$ //$NON-NLS-2$
"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=\"" + 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\" >" //$NON-NLS-1$
+ srcEncoding + "</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);
// 写一个正则表达式,专门去除前面的空格 robert 2012-11-13
String regex = "=\\s*";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = null;
String line;
while ((line = buffer.readLine()) != null) {
// 检查是否已取消转换操作
if (monitor.isCanceled()) {
throw new OperationCanceledException(Messages.getString("javaproperties.cancel"));
}
// 计算转换进度
int size = line.getBytes(srcEncoding).length;
if (size > 0) {
int workedTask = cpb.calculateProcessed(size + 1);
if (workedTask > 0) {
monitor.worked(workedTask);
}
}
if (line.trim().length() == 0) {
// no text in this line
// segment separator
writeSkeleton(line + "\n"); //$NON-NLS-1$
} else if (line.trim().startsWith("#")) { //$NON-NLS-1$
// this line is a comment
// send to skeleton
writeSkeleton(line + "\n"); //$NON-NLS-1$
} else {
String tmp = line;
if (line.endsWith("\\")) { //$NON-NLS-1$
do {
line = buffer.readLine();
// 计算转换进度
int tempSize = line.getBytes(srcEncoding).length;
if (tempSize > 0) {
int tempWorkedTask = cpb.calculateProcessed(tempSize);
if (tempWorkedTask > 0) {
monitor.worked(tempWorkedTask);
}
}
tmp += "\n" + line; //$NON-NLS-1$
} while (line != null && line.endsWith("\\")); //$NON-NLS-1$
}
matcher = pattern.matcher(tmp);
String matcherResult = "=";
if (matcher.find()) {
matcherResult = matcher.group();
}
int index = tmp.indexOf(matcherResult); //$NON-NLS-1$
if (index != -1) {
String key = tmp.substring(0, index + matcherResult.length());
writeSkeleton(key);
source = tmp.substring(index + matcherResult.length());
writeSegment();
writeSkeleton("\n"); //$NON-NLS-1$
} else {
// this line may be wrong, send to skeleton
// and continue
writeSkeleton(tmp);
}
}
}
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("javaproperties.Properties2Xliff.msg1"), e);
} finally {
monitor.done();
}
return result;
}
/**
* 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 == false) {
if (!segByElement) {
segments = segmenter.segment(fixChars(source));
} else {
segments = new String[1];
segments[0] = fixChars(source);
}
for (int i = 0; i < segments.length; i++) {
if (!segments[i].trim().equals("")) { //$NON-NLS-1$
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$
} else {
writeSkeleton(segments[i]);
}
}
source = ""; //$NON-NLS-1$
}
}
/**
* Fix chars.
* @param line
* the line
* @return the string
*/
private static String fixChars(String line) {
int start = line.indexOf("\\u"); //$NON-NLS-1$
while (start != -1) {
if (line.substring(start + 2, start + 6).toLowerCase()
.matches("[\\dabcdef][\\dabcdef][\\dabcdef][\\dabcdef]")) { //$NON-NLS-1$
line = line.substring(0, start) + toChar(line.substring(start + 2, start + 6))
+ line.substring(start + 6);
}
start = line.indexOf("\\u", start + 1); //$NON-NLS-1$
}
return line;
}
/**
* To char.
* @param string
* the string
* @return the string
*/
private static String toChar(String string) {
int hex = Integer.parseInt(string, 16);
char result = (char) hex;
return "" + result; //$NON-NLS-1$
}
}
| 13,064 | 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.javaproperties/src/net/heartsome/cat/converter/javaproperties/resource/Messages.java | /**
* Messages.java
*
* Version information :
*
* Date:Jan 14, 2010
*
* Copyright notice :
*/
package net.heartsome.cat.converter.javaproperties.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.javaproperties.resource.javaproperties"; //$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,046 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
Inx2XliffTest.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.inx/testSrc/net/heartsome/cat/converter/inx/test/Inx2XliffTest.java | package net.heartsome.cat.converter.inx.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.inx.Inx2Xliff;
import org.junit.AfterClass;
import org.junit.Test;
public class Inx2XliffTest {
public static Inx2Xliff converter = new Inx2Xliff();
private static String srcFile1 = "rc/Test.inx";
private static String sklFile1 = "rc/Test.inx.skl";
private static String xlfFile1 = "rc/Test.inx.xlf";
private static String srcFile2 = "rc/Test10M.inx";
private static String xlfFile2 = "rc/Test10M.inx.xlf";
private static String sklFile2 = "rc/Test10M.inx.skl";
private static String srcFile3 = "rc/TestSC.inx";
private static String xlfFile3 = "rc/TestSC.inx.xlf";
private static String sklFile3 = "rc/TestSC.inx.skl";
public void setUp() {
File skl = new File(sklFile1);
if (skl.exists()) {
skl.delete();
}
File xlf = new File(xlfFile1);
if (xlf.exists()) {
xlf.delete();
}
skl = new File(sklFile2);
if (skl.exists()) {
skl.delete();
}
xlf = new File(xlfFile2);
if (xlf.exists()) {
xlf.delete();
}
skl = new File(sklFile3);
if (skl.exists()) {
skl.delete();
}
xlf = new File(xlfFile3);
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, srcFile1); //$NON-NLS-1$
args.put(Converter.ATTR_XLIFF_FILE, xlfFile1); //$NON-NLS-1$
args.put(Converter.ATTR_SKELETON_FILE, sklFile1); //$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");
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, srcFile1); //$NON-NLS-1$
args.put(Converter.ATTR_XLIFF_FILE, xlfFile1); //$NON-NLS-1$
args.put(Converter.ATTR_SKELETON_FILE, sklFile1); //$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");
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 testConvert() throws ConverterException {
String rootFolder = "/data/john/Workspaces/CAT/HSTS7/";
Map<String, String> args = new HashMap<String, String>();
args.put(Converter.ATTR_SOURCE_FILE, srcFile1); //$NON-NLS-1$
args.put(Converter.ATTR_XLIFF_FILE, xlfFile1); //$NON-NLS-1$
args.put(Converter.ATTR_SKELETON_FILE, sklFile1); //$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");
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());
// 10M INX
args = new HashMap<String, String>();
args.put(Converter.ATTR_SOURCE_FILE, srcFile2); //$NON-NLS-1$
args.put(Converter.ATTR_XLIFF_FILE, xlfFile2); //$NON-NLS-1$
args.put(Converter.ATTR_SKELETON_FILE, sklFile2); //$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");
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());
// zh-CN INX
args = new HashMap<String, String>();
args.put(Converter.ATTR_SOURCE_FILE, srcFile3); //$NON-NLS-1$
args.put(Converter.ATTR_XLIFF_FILE, xlfFile3); //$NON-NLS-1$
args.put(Converter.ATTR_SKELETON_FILE, sklFile3); //$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());
}
}
| 6,014 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
Xliff2InxTest.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.inx/testSrc/net/heartsome/cat/converter/inx/test/Xliff2InxTest.java | package net.heartsome.cat.converter.inx.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.inx.Xliff2Inx;
import org.junit.Test;
public class Xliff2InxTest {
public static Xliff2Inx converter = new Xliff2Inx();
private static String tgtFile1 = "rc/Test_en-US.inx";
private static String sklFile1 = "rc/Test.inx.skl";
private static String xlfFile1 = "rc/Test.inx.xlf";
private static String tgtFile2 = "rc/Test10M_en-US.inx";
private static String xlfFile2 = "rc/Test10M.inx.xlf";
private static String sklFile2 = "rc/Test10M.inx.skl";
private static String tgtFile3 = "rc/TestSC_en-US.inx";
private static String xlfFile3 = "rc/TestSC.inx.xlf";
private static String sklFile3 = "rc/TestSC.inx.skl";
public void setUp() {
File tgt = new File(tgtFile1);
if (tgt.exists()) {
tgt.delete();
}
tgt = new File(tgtFile2);
if (tgt.exists()) {
tgt.delete();
}
tgt = new File(tgtFile3);
if (tgt.exists()) {
tgt.delete();
}
}
@Test(timeout = 60000)
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, tgtFile1);
args.put(Converter.ATTR_XLIFF_FILE, xlfFile1);
args.put(Converter.ATTR_SKELETON_FILE, sklFile1);
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());
// 10M Inx
args = new HashMap<String, String>();
args.put(Converter.ATTR_TARGET_FILE, tgtFile2);
args.put(Converter.ATTR_XLIFF_FILE, xlfFile2);
args.put(Converter.ATTR_SKELETON_FILE, sklFile2);
args.put(Converter.ATTR_SOURCE_ENCODING, "UTF-8");
args.put(Converter.ATTR_CATALOGUE, rootFolder
+ "catalogue/catalogue.xml");
result = converter.convert(args, null);
target = result.get(Converter.ATTR_TARGET_FILE);
assertNotNull(target);
tgtFile = new File(target);
assertNotNull(tgtFile);
assertTrue(tgtFile.exists());
// zh-CN Inx
args = new HashMap<String, String>();
args.put(Converter.ATTR_TARGET_FILE, tgtFile3);
args.put(Converter.ATTR_XLIFF_FILE, xlfFile3);
args.put(Converter.ATTR_SKELETON_FILE, sklFile3);
args.put(Converter.ATTR_SOURCE_ENCODING, "UTF-8");
args.put(Converter.ATTR_CATALOGUE, rootFolder
+ "catalogue/catalogue.xml");
result = converter.convert(args, null);
target = result.get(Converter.ATTR_TARGET_FILE);
assertNotNull(target);
tgtFile = new File(target);
assertNotNull(tgtFile);
assertTrue(tgtFile.exists());
}
}
| 3,040 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
Xliff2Inx.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.inx/src/net/heartsome/cat/converter/inx/Xliff2Inx.java | /**
* Xliff2Inx.java
*
* Version information :
*
* Date:Jan 14, 2010
*
* Copyright notice :
*/
package net.heartsome.cat.converter.inx;
import java.util.Map;
import net.heartsome.cat.converter.Converter;
import net.heartsome.cat.converter.ConverterException;
import net.heartsome.cat.converter.inx.resource.Messages;
import org.eclipse.core.runtime.IProgressMonitor;
/**
* The Class Xliff2Inx.
* @author John Zhu
* @author Pablo
* @version
* @since JDK1.6
*/
public class Xliff2Inx implements Converter {
/** The Constant TYPE_VALUE. */
public static final String TYPE_VALUE = "x-inx";
/** The Constant TYPE_NAME_VALUE. */
public static final String TYPE_NAME_VALUE = Messages.getString("inx.TYPE_NAME_VALUE");
/** The Constant NAME_VALUE. */
public static final String NAME_VALUE = "XLIFF to INX Conveter";
// 内部实现所依赖的转换器
/** The dependant converter. */
private Converter dependantConverter;
/**
* for test to initialize depend on converter.
*/
public Xliff2Inx() {
dependantConverter = Activator.getXMLConverter(Converter.DIRECTION_REVERSE);
}
/**
* 运行时把所依赖的转换器,在初始化的时候通过构造函数注入。.
* @param converter
* the converter
*/
public Xliff2Inx(Converter converter) {
dependantConverter = converter;
}
/**
* (non-Javadoc).
* @param args
* the args
* @param monitor
* the monitor
* @return the map< string, string>
* @throws ConverterException
* the converter exception
* @see net.heartsome.cat.converter.Converter#convert(java.util.Map, org.eclipse.core.runtime.IProgressMonitor)
*/
public Map<String, String> convert(Map<String, String> args, IProgressMonitor monitor) throws ConverterException {
args.put(Converter.ATTR_IS_INDESIGN, Converter.TRUE);
return dependantConverter.convert(args, monitor);
}
/**
* (non-Javadoc).
* @return the name
* @see net.heartsome.cat.converter.Converter#getName()
*/
public String getName() {
return NAME_VALUE;
}
/**
* (non-Javadoc).
* @return the type
* @see net.heartsome.cat.converter.Converter#getType()
*/
public String getType() {
return TYPE_VALUE;
}
/**
* (non-Javadoc).
* @return the type name
* @see net.heartsome.cat.converter.Converter#getTypeName()
*/
public String getTypeName() {
return TYPE_NAME_VALUE;
}
}
| 2,499 | 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.inx/src/net/heartsome/cat/converter/inx/Activator.java | /**
* Activator.java
*
* Version information :
*
* Date:Jan 14, 2010
*
* Copyright notice :
*/
package net.heartsome.cat.converter.inx;
import java.util.Properties;
import net.heartsome.cat.converter.Converter;
import net.heartsome.cat.converter.util.AndFilter;
import net.heartsome.cat.converter.util.ConverterRegister;
import net.heartsome.cat.converter.util.EqFilter;
import net.heartsome.cat.converter.xml.Xliff2Xml;
import net.heartsome.cat.converter.xml.Xml2Xliff;
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.inx";
// 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 xml converter service
String positiveFilter = new AndFilter(new EqFilter(Constants.OBJECTCLASS, Converter.class.getName()),
new EqFilter(Converter.ATTR_TYPE, Xml2Xliff.TYPE_VALUE), new EqFilter(Converter.ATTR_DIRECTION,
Converter.DIRECTION_POSITIVE)).toString();
positiveTracker = new ServiceTracker(context, context.createFilter(positiveFilter), new XmlPositiveCustomizer());
positiveTracker.open();
String reverseFilter = new AndFilter(new EqFilter(Constants.OBJECTCLASS, Converter.class.getName()),
new EqFilter(Converter.ATTR_TYPE, Xliff2Xml.TYPE_VALUE), new EqFilter(Converter.ATTR_DIRECTION,
Converter.DIRECTION_REVERSE)).toString();
reverseTracker = new ServiceTracker(context, context.createFilter(reverseFilter), new XmlReverseCustomize());
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 xML converter.
* @param direction
* the direction
* @return the xML converter
*/
public static Converter getXMLConverter(String direction) {
if (Converter.DIRECTION_POSITIVE.equals(direction)) {
return new Xml2Xliff();
} else {
return new Xliff2Xml();
}
}
/**
* The Class XmlPositiveCustomizer.
* @author John Zhu
* @version
* @since JDK1.6
*/
private class XmlPositiveCustomizer 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 inx2Xliff = new Inx2Xliff(converter);
Properties properties = new Properties();
properties.put(Converter.ATTR_NAME, Inx2Xliff.NAME_VALUE);
properties.put(Converter.ATTR_TYPE, Inx2Xliff.TYPE_VALUE);
properties.put(Converter.ATTR_TYPE_NAME, Inx2Xliff.TYPE_NAME_VALUE);
ServiceRegistration registration = ConverterRegister.registerPositiveConverter(bundleContext, inx2Xliff,
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 XmlReverseCustomize.
* @author John Zhu
* @version
* @since JDK1.6
*/
private class XmlReverseCustomize 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 xliff2Inx = new Xliff2Inx(converter);
Properties properties = new Properties();
properties.put(Converter.ATTR_NAME, Xliff2Inx.NAME_VALUE);
properties.put(Converter.ATTR_TYPE, Xliff2Inx.TYPE_VALUE);
properties.put(Converter.ATTR_TYPE_NAME, Xliff2Inx.TYPE_NAME_VALUE);
ServiceRegistration registration = ConverterRegister.registerReverseConverter(bundleContext, xliff2Inx,
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);
}
}
}
| 6,946 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
Inx2Xliff.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.inx/src/net/heartsome/cat/converter/inx/Inx2Xliff.java | /**
* Inx2Xliff.java
*
* Version information :
*
* Date:Jan 14, 2010
*
* Copyright notice :
*/
package net.heartsome.cat.converter.inx;
import java.util.Map;
import net.heartsome.cat.converter.Converter;
import net.heartsome.cat.converter.ConverterException;
import net.heartsome.cat.converter.inx.resource.Messages;
import org.eclipse.core.runtime.IProgressMonitor;
/**
* The Class Inx2Xliff.
* @author John Zhu
* @version
* @since JDK1.6
*/
public class Inx2Xliff implements Converter {
/** The Constant TYPE_VALUE. */
public static final String TYPE_VALUE = "x-inx";
/** The Constant TYPE_NAME_VALUE. */
public static final String TYPE_NAME_VALUE = Messages.getString("inx.TYPE_NAME_VALUE");
/** The Constant NAME_VALUE. */
public static final String NAME_VALUE = "INX to XLIFF Conveter";
// 内部实现所依赖的转换器
/** The dependant converter. */
private Converter dependantConverter;
/**
* for test to initialize depend on converter.
*/
public Inx2Xliff() {
dependantConverter = Activator.getXMLConverter(Converter.DIRECTION_POSITIVE);
}
/**
* 运行时把所依赖的转换器,在初始化的时候通过构造函数注入。.
* @param converter
* the converter
*/
public Inx2Xliff(Converter converter) {
dependantConverter = converter;
}
/**
* (non-Javadoc).
* @param args
* the args
* @param monitor
* the monitor
* @return the map< string, string>
* @throws ConverterException
* the converter exception
* @see net.heartsome.cat.converter.Converter#convert(java.util.Map, org.eclipse.core.runtime.IProgressMonitor)
*/
public Map<String, String> convert(Map<String, String> args, IProgressMonitor monitor) throws ConverterException {
args.put(Converter.ATTR_IS_INDESIGN, Converter.TRUE);
args.put(Converter.ATTR_FORMAT, TYPE_VALUE);
return dependantConverter.convert(args, monitor);
}
/**
* (non-Javadoc).
* @return the name
* @see net.heartsome.cat.converter.Converter#getName()
*/
public String getName() {
return NAME_VALUE;
}
/**
* (non-Javadoc).
* @return the type
* @see net.heartsome.cat.converter.Converter#getType()
*/
public String getType() {
return TYPE_VALUE;
}
/**
* (non-Javadoc).
* @return the type name
* @see net.heartsome.cat.converter.Converter#getTypeName()
*/
public String getTypeName() {
return TYPE_NAME_VALUE;
}
} | 2,528 | 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.inx/src/net/heartsome/cat/converter/inx/resource/Messages.java | /**
* Messages.java
*
* Version information :
*
* Date:Jan 14, 2010
*
* Copyright notice :
*/
package net.heartsome.cat.converter.inx.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.inx.resource.inx"; //$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,014 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
Xliff2HtmlTest.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.html/testSrc/net/heartsome/cat/converter/html/test/Xliff2HtmlTest.java | package net.heartsome.cat.converter.html.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.html.Xliff2Html;
import org.junit.Before;
import org.junit.Test;
public class Xliff2HtmlTest {
public static Xliff2Html converter = new Xliff2Html();
private static String tgtFile = "rc/Test_en-US.html";
private static String xlfFile = "rc/Test.html.xlf";
private static String sklFile = "rc/Test.html.skl";
@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);
args.put(Converter.ATTR_XLIFF_FILE, xlfFile);
args.put(Converter.ATTR_SKELETON_FILE, sklFile);
args.put(Converter.ATTR_SOURCE_ENCODING, "UTF-8");
args.put(Converter.ATTR_CATALOGUE, rootFolder
+ "catalogue/catalogue.xml");
args.put(Converter.ATTR_INI_FILE, rootFolder + "ini/init_html.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,550 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
Html2XliffTest.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.html/testSrc/net/heartsome/cat/converter/html/test/Html2XliffTest.java | package net.heartsome.cat.converter.html.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.html.Html2Xliff;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.Test;
public class Html2XliffTest {
public static Html2Xliff converter = new Html2Xliff();
private static String srcFile = "rc/Test.html";
private static String xlfFile = "rc/Test.html.xlf";
private static String sklFile = "rc/Test.html.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, "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_INI_FILE, rootFolder + "ini/init_html.xml");
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, "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_INI_FILE, rootFolder + "ini/init_html.xml");
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, "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_INI_FILE,rootFolder + "ini/init_html.xml");
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, "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_INI_FILE, rootFolder + "ini/init_html.xml");
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,905 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
Html2Xliff.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.html/src/net/heartsome/cat/converter/html/Html2Xliff.java | /**
* Html2Xliff.java
*
* Version information :
*
* Date:Jan 14, 2010
*
* Copyright notice :
*/
package net.heartsome.cat.converter.html;
import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
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 java.util.Vector;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.xml.parsers.ParserConfigurationException;
import net.heartsome.cat.converter.Converter;
import net.heartsome.cat.converter.ConverterException;
import net.heartsome.cat.converter.StringSegmenter;
import net.heartsome.cat.converter.html.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.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 Html2Xliff.
* @author John Zhu
* @version
* @since JDK1.6
*/
public class Html2Xliff implements Converter {
/** The Constant TYPE_VALUE. */
public static final String TYPE_VALUE = "html";
/** The Constant TYPE_NAME_VALUE. */
public static final String TYPE_NAME_VALUE = Messages.getString("html.TYPE_NAME_VALUE");
/** The Constant NAME_VALUE. */
public static final String NAME_VALUE = "Html to XLIFF Conveter";
/**
* Gets the node type.
* @param string
* the string
* @return the node type
*/
private static String getNodeType(String string) {
String result = ""; //$NON-NLS-1$
if (string.startsWith("<![CDATA[")) { //$NON-NLS-1$
return "![CDATA["; //$NON-NLS-1$
}
if (string.startsWith("<![IGNORE[")) { //$NON-NLS-1$
return "![IGNORE["; //$NON-NLS-1$
}
if (string.startsWith("<![INCLUDE[")) { //$NON-NLS-1$
return "![INCLUDE["; //$NON-NLS-1$
}
if (string.startsWith("<!--")) { //$NON-NLS-1$
return "!--"; //$NON-NLS-1$
}
if (string.startsWith("<?")) { //$NON-NLS-1$
return "?"; //$NON-NLS-1$
}
if (!string.equals("")) { //$NON-NLS-1$
// skip initial "<"
string = string.substring(1);
}
for (int i = 0; i < string.length(); i++) {
char c = string.charAt(i);
if (c == ' ' || c == '\n' || c == '\f' || c == '\t' || c == '\r' || c == '>') {
break;
}
result = result + c;
}
if (result.endsWith("/") && result.length() > 1) { //$NON-NLS-1$
result = result.substring(0, result.length() - 1);
}
return result.toLowerCase();
}
/**
* Contains text.
* @param string
* the string
* @return true, if successful
*/
private static boolean containsText(String string) {
StringBuffer buffer = new StringBuffer();
int length = string.length();
boolean inTag = false;
for (int i = 0; i < length; i++) {
char c = string.charAt(i);
if (string.substring(i).startsWith("<ph")) { //$NON-NLS-1$
inTag = true;
}
if (string.substring(i).startsWith("</ph>")) { //$NON-NLS-1$
inTag = false;
i = i + 4;
continue;
}
if (!inTag) {
buffer.append(c);
}
}
return !buffer.toString().trim().equals(""); //$NON-NLS-1$
}
/**
* Normalize.
* @param string
* the string
* @return the string
*/
private static String normalize(String string) {
string = string.replace('\n', ' ');
string = string.replace('\t', ' ');
string = string.replace('\r', ' ');
string = string.replace('\f', ' ');
String rs = ""; //$NON-NLS-1$
int length = string.length();
for (int i = 0; i < length; i++) {
char ch = string.charAt(i);
if (!Character.isSpaceChar(ch)) {
rs = rs + ch;
} else {
rs = rs + " "; //$NON-NLS-1$
while (i < length - 1 && Character.isSpaceChar(string.charAt(i + 1))) {
i++;
}
}
}
return rs;
}
/**
* (non-Javadoc).
* @param args
* the args
* @param monitor
* the monitor
* @return the map< string, string>
* @throws ConverterException
* the converter exception
* @see net.heartsome.cat.converter.Converter#convert(java.util.Map, org.eclipse.core.runtime.IProgressMonitor)
*/
public Map<String, String> convert(Map<String, String> args, IProgressMonitor monitor) throws ConverterException {
Html2XliffImpl converter = new Html2XliffImpl();
// 需要添加指定 ini file
String iniDir = args.get(Converter.ATTR_INIDIR);
String iniFile = iniDir + System.getProperty("file.separator") + "init_html.xml";
args.put(Converter.ATTR_INI_FILE, iniFile);
return converter.run(args, monitor);
}
/**
* (non-Javadoc).
* @return the name
* @see net.heartsome.cat.converter.Converter#getName()
*/
public String getName() {
return NAME_VALUE;
}
/**
* (non-Javadoc).
* @return the type
* @see net.heartsome.cat.converter.Converter#getType()
*/
public String getType() {
return TYPE_VALUE;
}
/**
* (non-Javadoc).
* @return the type name
* @see net.heartsome.cat.converter.Converter#getTypeName()
*/
public String getTypeName() {
return TYPE_NAME_VALUE;
}
/**
* The Class Html2XliffImpl.
* @author John Zhu
* @version
* @since JDK1.6
*/
class Html2XliffImpl {
/** The input file. */
private String inputFile;
/** The xliff file. */
private String xliffFile;
/** The skeleton file. */
private String skeletonFile;
/** The source language. */
private String sourceLanguage;
private String targetLanguage;
/** The src encoding. */
private String srcEncoding;
/** The input. */
private FileInputStream input;
/** The output. */
private FileOutputStream output;
/** The skeleton. */
private FileOutputStream skeleton;
/** The seg id. */
private int segId;
/** The tag id. */
private int tagId;
/** The segments. */
private List<String> segments;
/** The starts segment. */
private Hashtable<String, String> startsSegment;
/** The translatable attributes. */
private Hashtable<String, Vector<String>> translatableAttributes;
/** The entities. */
private Hashtable<String, String> entities;
/** The ctypes. */
private Hashtable<String, String> ctypes;
/** The keep formating. */
private Hashtable<String, String> keepFormating;
/** The seg by element. */
private boolean segByElement;
/** The keep format. */
private boolean keepFormat;
/** The segmenter. */
private StringSegmenter segmenter;
/** The catalogue. */
private String catalogue;
/** The first. */
private String first;
/** The last. */
private String last;
/** 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);
// 把转换分成四个部分:写 xliff 文件头,构建 tables,构建列表,处理列表。
monitor.beginTask("", 4);
monitor.subTask(Messages.getString("html.Html2Xliff.beginTask"));
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);
sourceLanguage = params.get(Converter.ATTR_SOURCE_LANGUAGE);
targetLanguage = params.get(Converter.ATTR_TARGET_LANGUAGE);
srcEncoding = params.get(Converter.ATTR_SOURCE_ENCODING);
String iniFile = params.get(Converter.ATTR_INI_FILE);
try {
if (iniFile == null || "".equals(iniFile)) {
ConverterUtils.throwConverterException(Activator.PLUGIN_ID,
Messages.getString("html.Html2Xliff.msg3"));
}
catalogue = params.get(Converter.ATTR_CATALOGUE);
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;
String elementSegmentation = params.get(Converter.ATTR_SEG_BY_ELEMENT);
if (elementSegmentation == null) {
segByElement = false;
} else {
if (elementSegmentation.equals(Converter.TRUE)) {
segByElement = true;
} else {
segByElement = false;
}
}
if (!segByElement) {
String initSegmenter = params.get(Converter.ATTR_SRX);
segmenter = new StringSegmenter(initSegmenter, sourceLanguage, catalogue);
}
input = new FileInputStream(inputFile);
skeleton = new FileOutputStream(skeletonFile);
output = new FileOutputStream(xliffFile);
writeHeader();
monitor.worked(1);
int size = input.available();
byte[] array = new byte[size];
if (size != input.read(array)) {
ConverterUtils.throwConverterException(Activator.PLUGIN_ID,
Messages.getString("html.Html2Xliff.msg1")); //$NON-NLS-1$
}
String file = new String(array, srcEncoding);
array = null;
buildTables(iniFile, Progress.getSubMonitor(monitor, 1));
buildList(file, Progress.getSubMonitor(monitor, 1));
file = null;
processList(Progress.getSubMonitor(monitor, 1));
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("html.Html2Xliff.msg4"),
e);
} finally {
monitor.done();
}
return result;
}
/**
* Write header.
* @throws IOException
* Signals that an I/O exception has occurred.
*/
private void writeHeader() throws IOException {
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\" " //$NON-NLS-1$
+ "xmlns:hs=\"" //$NON-NLS-1$
+ 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 (!targetLanguage.equals("")) {
writeString("<file original=\"" //$NON-NLS-1$
+ cleanString(inputFile)
+ "\" source-language=\"" //$NON-NLS-1$
+ sourceLanguage
+ "\" target-language=\"" + targetLanguage + "\" datatype=\"" + TYPE_VALUE + "\">\n"); //$NON-NLS-1$
} else {
writeString("<file original=\"" //$NON-NLS-1$
+ cleanString(inputFile) + "\" source-language=\"" //$NON-NLS-1$
+ sourceLanguage + "\" 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\" >" //$NON-NLS-1$
+ srcEncoding + "</hs:prop></hs:prop-group>\n"); //$NON-NLS-1$
writeString("</header>\n"); //$NON-NLS-1$
writeString("<body>\n"); //$NON-NLS-1$
}
/**
* Process list.
* @throws ParserConfigurationException
* * @throws SAXException the SAX exception
* @throws IOException
* Signals that an I/O exception has occurred.
* @throws SAXException
* the SAX exception
*/
private void processList(IProgressMonitor monitor) throws IOException, SAXException {
monitor.beginTask(Messages.getString("html.Html2Xliff.task2"), segments.size());
monitor.subTask("");
for (int i = 0; i < segments.size(); i++) {
if (monitor.isCanceled()) {
throw new OperationCanceledException(Messages.getString("html.cancel"));
}
monitor.worked(1);
String text = segments.get(i);
if (isTranslateable(text)) {
extractSegment(text);
} else {
// send directly to skeleton
writeSkeleton(text);
}
}
monitor.done();
}
/**
* Extract segment.
* @param seg
* the seg
* @throws ParserConfigurationException
* * @throws SAXException the SAX exception
* @throws IOException
* Signals that an I/O exception has occurred.
* @throws SAXException
* the SAX exception
*/
private void extractSegment(String seg) throws IOException, SAXException {
// start by making a smaller list
List<String> miniList = new ArrayList<String>();
int start = seg.indexOf("<"); //$NON-NLS-1$
int end = seg.indexOf(">"); //$NON-NLS-1$
String text = ""; //$NON-NLS-1$
while (start != -1) {
if (start > 0) {
// add initial text
miniList.add(seg.substring(0, start));
seg = seg.substring(start);
start = seg.indexOf("<"); //$NON-NLS-1$
end = seg.indexOf(">"); //$NON-NLS-1$
}
// add the tag
if (end < seg.length()) {
miniList.add(seg.substring(start, end + 1));
seg = seg.substring(end + 1);
start = seg.indexOf("<"); //$NON-NLS-1$
end = seg.indexOf(">"); //$NON-NLS-1$
} else {
miniList.add(seg);
start = -1;
}
}
if (seg.length() > 0) {
// add trailing characters
miniList.add(seg);
}
int size = miniList.size();
int i;
// separate initial text
String initial = ""; //$NON-NLS-1$
for (i = 0; i < size; i++) {
text = miniList.get(i);
if (!isTranslateable(text)) {
initial = initial + text;
} else {
break;
}
}
// get translatable
String translatable = text;
for (i++; i < size; i++) {
translatable = translatable + miniList.get(i);
}
// get trailing text
String trail = ""; //$NON-NLS-1$
int j;
for (j = size - 1; j > 0; j--) {
String t = miniList.get(j);
if (!isTranslateable(t)) {
trail = t + trail;
} else {
break;
}
}
// remove trailing from translatable
start = translatable.lastIndexOf(trail);
if (start != -1) {
translatable = translatable.substring(0, start);
}
writeSkeleton(initial);
String tagged = addTags(translatable);
if (containsText(tagged)) {
translatable = tagged;
if (segByElement) {
String[] frags = translatable.split("\u2029"); //$NON-NLS-1$
for (int m = 0; m < frags.length; m++) {
writeSegment(frags[m]);
}
} else {
String[] frags = translatable.split("\u2029"); //$NON-NLS-1$
for (int m = 0; m < frags.length; m++) {
String[] segs = segmenter.segment(frags[m]);
for (int h = 0; h < segs.length; h++) {
writeSegment(segs[h]);
}
}
}
} else {
writeSkeleton(translatable);
}
writeSkeleton(trail);
}
/**
* Write segment.
* @param segment
* the segment
* @throws ParserConfigurationException
* * @throws SAXException the SAX exception
* @throws IOException
* Signals that an I/O exception has occurred.
* @throws SAXException
* the SAX exception
*/
private void writeSegment(String segment) throws IOException, SAXException {
segment = segment.replaceAll("\u2029", ""); //$NON-NLS-1$ //$NON-NLS-2$
String pure = removePH(segment);
if (pure.trim().equals("")) { //$NON-NLS-1$
writeSkeleton(phContent(segment));
return;
}
if (segment.trim().equals("")) { //$NON-NLS-1$
writeSkeleton(segment);
return;
}
first = ""; //$NON-NLS-1$
last = ""; //$NON-NLS-1$
segment = segmentCleanup(segment);
writeSkeleton(first);
tagId = 0;
writeString(" <trans-unit id=\"" //$NON-NLS-1$
+ segId + "\" xml:space=\"preserve\" approved=\"no\">\n" //$NON-NLS-1$
+ " <source xml:lang=\"" //$NON-NLS-1$
+ sourceLanguage + "\">"); //$NON-NLS-1$
if (keepFormat) {
writeString(segment);
} else {
writeString(normalize(segment));
}
writeString("</source>\n </trans-unit>\n"); //$NON-NLS-1$
writeSkeleton("%%%" + segId++ + "%%%\n" + last); //$NON-NLS-1$ //$NON-NLS-2$
}
/**
* Segment cleanup.
* @param segment
* the segment
* @return the string
* @throws SAXException
* the SAX exception
* @throws IOException
* Signals that an I/O exception has occurred.
*/
private String segmentCleanup(String segment) throws SAXException, IOException {
ByteArrayInputStream stream = new ByteArrayInputStream(("<x>" + segment + "</x>").getBytes("UTF-8")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
SAXBuilder b = new SAXBuilder();
Document d = b.build(stream);
Element e = d.getRootElement();
List<Node> content = e.getContent();
Iterator<Node> it = content.iterator();
int count = 0;
while (it.hasNext()) {
Node n = it.next();
if (n.getNodeType() == Node.ELEMENT_NODE) {
count++;
}
}
if (count == 1) {
Node n = content.get(0);
if (n.getNodeType() == Node.ELEMENT_NODE) {
first = phContent(new Element(n).toString());
content.remove(0);
} else {
n = content.get(content.size() - 1);
if (n.getNodeType() == Node.ELEMENT_NODE) {
last = phContent(new Element(n).toString());
content.remove(content.size() - 1);
}
}
}
if (count == 2) {
Node n = content.get(0);
Node s = content.get(content.size() - 1);
if (n.getNodeType() == Node.ELEMENT_NODE && s.getNodeType() == Node.ELEMENT_NODE) {
if (n.getNodeType() == Node.ELEMENT_NODE) {
first = new Element(n).getText();
content.remove(n);
last = new Element(s).getText();
content.remove(s);
}
}
}
e.setContent(content);
String es = e.toString();
return es.substring(3, es.length() - 4);
}
/**
* Ph content.
* @param segment
* the segment
* @return the string
* @throws SAXException
* the SAX exception
* @throws IOException
* Signals that an I/O exception has occurred.
*/
private String phContent(String segment) throws SAXException, IOException {
ByteArrayInputStream stream = new ByteArrayInputStream(("<x>" + segment + "</x>").getBytes("UTF-8")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
SAXBuilder b = new SAXBuilder();
Document d = b.build(stream);
Element e = d.getRootElement();
List<Node> content = e.getContent();
Iterator<Node> it = content.iterator();
String result = ""; //$NON-NLS-1$
while (it.hasNext()) {
Node n = it.next();
if (n.getNodeType() == Node.ELEMENT_NODE) {
result = result + new Element(n).getText();
}
if (n.getNodeType() == Node.TEXT_NODE) {
result = result + n.getNodeValue();
}
}
return result;
}
/**
* Removes the ph.
* @param segment
* the segment
* @return the string
* @throws SAXException
* the SAX exception
* @throws IOException
* Signals that an I/O exception has occurred.
*/
private String removePH(String segment) throws SAXException, IOException {
ByteArrayInputStream stream = new ByteArrayInputStream(("<x>" + segment + "</x>").getBytes("UTF-8")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
SAXBuilder b = new SAXBuilder();
Document d = b.build(stream);
Element e = d.getRootElement();
List<Node> content = e.getContent();
Iterator<Node> it = content.iterator();
String result = ""; //$NON-NLS-1$
while (it.hasNext()) {
Node n = it.next();
if (n.getNodeType() == Node.TEXT_NODE) {
result = result + n.getNodeValue();
}
}
return result;
}
/**
* Adds the tags.
* @param src
* the src
* @return the string
*/
private String addTags(String src) {
String result = ""; //$NON-NLS-1$
int start = src.indexOf("<"); //$NON-NLS-1$
int end = src.indexOf(">"); //$NON-NLS-1$
while (start != -1) {
if (start > 0) {
result = result + cleanString(src.substring(0, start));
src = src.substring(start);
start = src.indexOf("<"); //$NON-NLS-1$
end = src.indexOf(">"); //$NON-NLS-1$
}
String element = src.substring(start, end + 1);
// check if we don't fall in a trap
// from Adobe GoLive
int errors = element.indexOf("<", 1); //$NON-NLS-1$
if (errors != -1) {
// there is a "<" inside quotes
// must move manually until the end
// of the element avoiding angle brackets
// within quotes
boolean exit = false;
boolean inQuotes = false;
StringBuffer buffer = new StringBuffer();
buffer.append("<"); //$NON-NLS-1$
int k = 0;
while (!exit) {
k++;
char c = src.charAt(start + k);
if (c == '\"') {
inQuotes = !inQuotes;
}
buffer.append(c);
if (!inQuotes && c == '>') {
exit = true;
}
}
element = buffer.toString();
end = start + buffer.toString().length();
start = end;
}
String tagged = tag(element);
result = result + tagged;
src = src.substring(end + 1);
start = src.indexOf("<"); //$NON-NLS-1$
end = src.indexOf(">"); //$NON-NLS-1$
}
result = result + cleanString(src);
return result;
}
/**
* Tag.
* @param element
* the element
* @return the string
*/
private String tag(String element) {
String result = ""; //$NON-NLS-1$
String type = getNodeType(element);
if (translatableAttributes.containsKey(type)) {
result = extractAttributes(type, element);
if (result.indexOf("\u2029") == -1) { //$NON-NLS-1$
String ctype = ""; //$NON-NLS-1$
if (ctypes.containsKey(type)) {
ctype = " ctype=\"" + ctypes.get(type) + "\""; //$NON-NLS-1$ //$NON-NLS-2$
}
result = "<ph id=\"" //$NON-NLS-1$
+ tagId++ + "\"" //$NON-NLS-1$
+ ctype + ">" //$NON-NLS-1$
+ cleanString(element) + "</ph>"; //$NON-NLS-1$
}
} else {
String ctype = ""; //$NON-NLS-1$
if (ctypes.containsKey(type)) {
ctype = " ctype=\"" + ctypes.get(type) + "\""; //$NON-NLS-1$ //$NON-NLS-2$
}
result = "<ph id=\"" //$NON-NLS-1$
+ tagId++ + "\"" //$NON-NLS-1$
+ ctype + ">" //$NON-NLS-1$
+ cleanString(element) + "</ph>"; //$NON-NLS-1$
}
return result;
}
/**
* Clean string.
* @param s
* the s
* @return the string
*/
private String cleanString(String s) {
int control = s.indexOf("&"); //$NON-NLS-1$
while (control != -1) {
int sc = s.indexOf(";", control); //$NON-NLS-1$
if (sc == -1) {
// no semicolon, it's not an entity
s = s.substring(0, control) + "&" + s.substring(control + 1); //$NON-NLS-1$
} else {
// may be an entity
String candidate = s.substring(control, sc) + ";"; //$NON-NLS-1$
if (!(candidate.equals("&") || candidate.equals(">") || candidate.equals("<"))) { //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
String entity = entities.get(candidate);
if (entity != null) {
s = s.substring(0, control) + entity + s.substring(sc + 1);
} else {
s = s.substring(0, control) + "%%%ph id=\"" //$NON-NLS-1$
+ tagId++ + "\"%%%&" //$NON-NLS-1$
+ candidate.substring(1) + "%%%/ph%%%" //$NON-NLS-1$
+ s.substring(sc + 1);
}
}
}
if (control < s.length()) {
control++;
}
control = s.indexOf("&", control); //$NON-NLS-1$
}
control = s.indexOf("<"); //$NON-NLS-1$
while (control != -1) {
s = s.substring(0, control) + "<" + s.substring(control + 1); //$NON-NLS-1$
if (control < s.length()) {
control++;
}
control = s.indexOf("<", control); //$NON-NLS-1$
}
control = s.indexOf(">"); //$NON-NLS-1$
while (control != -1) {
s = s.substring(0, control) + ">" + s.substring(control + 1); //$NON-NLS-1$
if (control < s.length()) {
control++;
}
control = s.indexOf(">", control); //$NON-NLS-1$
}
s = s.replaceAll("%%%/ph%%%", "</ph>"); //$NON-NLS-1$ //$NON-NLS-2$
s = s.replaceAll("%%%ph", "<ph"); //$NON-NLS-1$ //$NON-NLS-2$
s = s.replaceAll("\"%%%&", "\">&"); //$NON-NLS-1$ //$NON-NLS-2$
return s;
}
/**
* 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 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$
}
/**
* Checks if is translateable.
* @param string
* the string
* @return true, if is translateable
*/
private boolean isTranslateable(String string) {
keepFormat = false;
//
// remove CDATA sections
//
int startComment = string.indexOf("<![CDATA["); //$NON-NLS-1$
int endComment = string.indexOf("]]>"); //$NON-NLS-1$
while (startComment != -1 || endComment != -1) {
if (startComment != -1) {
if (endComment == -1) {
string = string.substring(0, startComment);
} else {
if (startComment < endComment) {
string = string.substring(0, startComment) + string.substring(endComment + 3);
} else {
string = string.substring(endComment + 3, startComment);
}
}
} else {
if (endComment != -1) {
string = string.substring(endComment + 3);
}
}
startComment = string.indexOf("<![CDATA["); //$NON-NLS-1$
endComment = string.indexOf("]]>"); //$NON-NLS-1$
}
//
// remove IGNORE sections
//
startComment = string.indexOf("<![IGNORE["); //$NON-NLS-1$
endComment = string.indexOf("]]>"); //$NON-NLS-1$
while (startComment != -1 || endComment != -1) {
if (startComment != -1) {
if (endComment == -1) {
string = string.substring(0, startComment);
} else {
if (startComment < endComment) {
string = string.substring(0, startComment) + string.substring(endComment + 3);
} else {
string = string.substring(endComment + 3, startComment);
}
}
} else {
if (endComment != -1) {
string = string.substring(endComment + 3);
}
}
startComment = string.indexOf("<![IGNORE["); //$NON-NLS-1$
endComment = string.indexOf("]]>"); //$NON-NLS-1$
}
//
// remove IGNORE sections
//
startComment = string.indexOf("<![INCLUDE["); //$NON-NLS-1$
endComment = string.indexOf("]]>"); //$NON-NLS-1$
while (startComment != -1 || endComment != -1) {
if (startComment != -1) {
if (endComment == -1) {
string = string.substring(0, startComment);
} else {
if (startComment < endComment) {
string = string.substring(0, startComment) + string.substring(endComment + 3);
} else {
string = string.substring(endComment + 3, startComment);
}
}
} else {
if (endComment != -1) {
string = string.substring(endComment + 3);
}
}
startComment = string.indexOf("<![INCLUDE["); //$NON-NLS-1$
endComment = string.indexOf("]]>"); //$NON-NLS-1$
}
//
// remove XML style comments
//
startComment = string.indexOf("<!--"); //$NON-NLS-1$
endComment = string.indexOf("-->"); //$NON-NLS-1$
while (startComment != -1 || endComment != -1) {
if (startComment != -1) {
if (endComment == -1) {
string = string.substring(0, startComment);
} else {
if (startComment < endComment) {
string = string.substring(0, startComment) + string.substring(endComment + 3);
} else {
string = string.substring(endComment + 3, startComment);
}
}
} else {
if (endComment != -1) {
string = string.substring(endComment + 3);
}
}
startComment = string.indexOf("<!--"); //$NON-NLS-1$
endComment = string.indexOf("-->"); //$NON-NLS-1$
}
//
// remove Processing Instruction
//
startComment = string.indexOf("<?"); //$NON-NLS-1$
endComment = string.indexOf("?>"); //$NON-NLS-1$
while (startComment != -1 || endComment != -1) {
if (startComment != -1) {
if (endComment == -1) {
string = string.substring(0, startComment);
} else {
string = string.substring(0, startComment) + string.substring(endComment + 2);
}
} else {
if (endComment != -1) {
string = string.substring(endComment + 2);
}
}
startComment = string.indexOf("<?"); //$NON-NLS-1$
endComment = string.indexOf("?>"); //$NON-NLS-1$
}
//
// remove C style comments
//
startComment = string.indexOf("/*"); //$NON-NLS-1$
endComment = string.indexOf("*/"); //$NON-NLS-1$
while (startComment != -1 || endComment != -1) {
if (startComment != -1) {
if (endComment == -1) {
string = string.substring(0, startComment);
} else {
if (startComment < endComment) {
string = string.substring(0, startComment) + string.substring(endComment + 2);
} else {
string = string.substring(endComment + 2, startComment);
}
}
} else {
if (endComment != -1) {
string = string.substring(endComment + 2);
}
}
startComment = string.indexOf("/*"); //$NON-NLS-1$
endComment = string.indexOf("*/"); //$NON-NLS-1$
}
//
// Start checking
//
int start = string.indexOf("<"); //$NON-NLS-1$
int end = string.indexOf(">"); //$NON-NLS-1$
String type;
String text = ""; //$NON-NLS-1$
while (start != -1) {
if (start > 0) {
text = text + cleanString(string.substring(0, start));
string = string.substring(start);
start = string.indexOf("<"); //$NON-NLS-1$
end = string.indexOf(">"); //$NON-NLS-1$
}
type = getNodeType(string.substring(start, end));
keepFormat = keepFormating.containsKey(type);
if (type.equals("script") || type.equals("style")) { //$NON-NLS-1$ //$NON-NLS-2$
return false;
}
// check for translatable attributes
if (translatableAttributes.containsKey(type)) {
return true;
}
if (type.startsWith("/")) { //$NON-NLS-1$
if (translatableAttributes.containsKey(type.substring(1))) {
return true;
}
}
if (end < string.length()) {
string = string.substring(end + 1);
} else {
string = string.substring(end);
}
start = string.indexOf("<"); //$NON-NLS-1$
end = string.indexOf(">"); //$NON-NLS-1$
}
text = text + cleanString(string);
// look for non-white space
for (int i = 0; i < text.length(); i++) {
char c = text.charAt(i);
if (c == ' ' || c == '\n' || c == '\f' || c == '\t' || c == '\r' || c == '\u00A0' || c == '\u2007'
|| c == '\u202F' || c == '\uFEFF' || c == '>') {
continue;
}
return true;
}
return false;
}
/**
* Extract attributes.
* @param type
* the type
* @param element
* the element
* @return the string
*/
private String extractAttributes(String type, String element) {
String ctype = ""; //$NON-NLS-1$
if (ctypes.containsKey(type)) {
ctype = " ctype=\"" + ctypes.get(type) + "\""; //$NON-NLS-1$ //$NON-NLS-2$
}
String result = "<ph id=\"" + tagId++ + "\"" + ctype + ">"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
element = cleanString(element);
Vector<String> v = translatableAttributes.get(type);
StringTokenizer tokenizer = new StringTokenizer(element, "&= \t\n\r\f/", true); //$NON-NLS-1$
while (tokenizer.hasMoreTokens()) {
String token = tokenizer.nextToken();
if (!v.contains(token.toLowerCase())) {
result = result + token;
} else {
result = result + token;
String s = tokenizer.nextToken();
while (s.equals("=") || s.equals(" ")) { //$NON-NLS-1$ //$NON-NLS-2$
result = result + s;
s = tokenizer.nextToken();
}
// s contains the first word of the atttribute
if ((s.startsWith("\"") && s.endsWith("\"") //$NON-NLS-1$ //$NON-NLS-2$
|| s.startsWith("'") && s.endsWith("'")) //$NON-NLS-1$ //$NON-NLS-2$
&& s.length() > 1) {
// the value is one word and it is quoted
result = result + s.substring(0, 1) + "</ph>\u2029" //$NON-NLS-1$
+ s.substring(1, s.length() - 1) + "\u2029<ph id=\"" //$NON-NLS-1$
+ tagId++ + "\">" //$NON-NLS-1$
+ s.substring(s.length() - 1);
} else {
if (s.startsWith("\"") || s.startsWith("'")) { //$NON-NLS-1$ //$NON-NLS-2$
// attribute value is quoted, but it has more than
// one
// word
String quote = s.substring(0, 1);
result = result + s.substring(0, 1) + "</ph>\u2029" + s.substring(1); //$NON-NLS-1$
s = tokenizer.nextToken();
do {
result = result + s;
s = tokenizer.nextToken();
} while (s.indexOf(quote) == -1);
String left = s.substring(0, s.indexOf(quote));
String right = s.substring(s.indexOf(quote));
result = result + left + "\u2029<ph id=\"" + tagId++ + "\">" + right; //$NON-NLS-1$ //$NON-NLS-2$
} else {
// attribute is not quoted, it can only be one word
result = result + "</ph>\u2029" + s + "\u2029<ph id=\"" + tagId++ + "\">"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
}
}
}
}
result = result + "</ph>"; //$NON-NLS-1$
return result;
}
/**
* Builds the tables.
* @param iniFile
* the ini file
* @throws SAXException
* the SAX exception
* @throws IOException
* Signals that an I/O exception has occurred.
* @throws ParserConfigurationException
* the parser configuration exception
*/
private void buildTables(String iniFile, IProgressMonitor monitor) throws SAXException, IOException,
ParserConfigurationException {
SAXBuilder builder = new SAXBuilder();
Catalogue cat = new Catalogue(catalogue);
builder.setEntityResolver(cat);
Document doc = builder.build(iniFile);
Element root = doc.getRootElement();
List<Element> tags = root.getChildren("tag"); //$NON-NLS-1$
startsSegment = new Hashtable<String, String>();
translatableAttributes = new Hashtable<String, Vector<String>>();
entities = new Hashtable<String, String>();
ctypes = new Hashtable<String, String>();
keepFormating = new Hashtable<String, String>();
int size = tags.size();
monitor.beginTask(Messages.getString("html.Html2Xliff.task3"), size);
monitor.subTask("");
Iterator<Element> i = tags.iterator();
while (i.hasNext()) {
if (monitor.isCanceled()) {
// 用户取消操作
throw new OperationCanceledException(Messages.getString("html.cancel"));
}
monitor.worked(1);
Element t = i.next();
if (t.getAttributeValue("hard-break", "inline").equals("segment")) { //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
startsSegment.put(t.getText(), "yes"); //$NON-NLS-1$
}
if (t.getAttributeValue("keep-format", "no").equals("yes")) { //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
keepFormating.put(t.getText(), "yes"); //$NON-NLS-1$
}
String attributes = t.getAttributeValue("attributes", ""); //$NON-NLS-1$ //$NON-NLS-2$
if (!attributes.equals("")) { //$NON-NLS-1$
StringTokenizer tokenizer = new StringTokenizer(attributes, ";"); //$NON-NLS-1$
int count = tokenizer.countTokens();
Vector<String> v = new Vector<String>(count);
for (int j = 0; j < count; j++) {
v.add(tokenizer.nextToken());
}
translatableAttributes.put(t.getText(), v);
}
String ctype = t.getAttributeValue("ctype", ""); //$NON-NLS-1$ //$NON-NLS-2$
if (!ctype.equals("")) { //$NON-NLS-1$
ctypes.put(t.getText(), ctype);
}
t = null;
}
tags = null;
List<Element> ents = root.getChildren("entity"); //$NON-NLS-1$
Iterator<Element> it = ents.iterator();
while (it.hasNext()) {
Element e = it.next();
entities.put("&" + e.getAttributeValue("name") + ";", e.getText()); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
}
root = null;
doc = null;
builder = null;
monitor.done();
}
/**
* Builds the list.
* @param file
* the file
* @throws Exception
* the exception
*/
private void buildList(String file, IProgressMonitor monitor) throws Exception {
monitor.beginTask(Messages.getString("html.Html2Xliff.task4"), IProgressMonitor.UNKNOWN);
monitor.subTask("");
segments = new ArrayList<String>();
int start = file.indexOf("<"); //$NON-NLS-1$
int end = file.indexOf(">"); //$NON-NLS-1$
String type;
String text = ""; //$NON-NLS-1$
if (start > 0) {
segments.add(file.substring(0, start));
file = file.substring(start);
start = file.indexOf("<"); //$NON-NLS-1$
end = file.indexOf(">"); //$NON-NLS-1$
}
// 由于 HTML 中可能存在诸如:<a href="http://www.hao123.com/video">更多>></a> 这种包含转义字符的文本,因此使用下面的表达式匹配 HTML 标记。
Pattern pattern = Pattern.compile("<[^<>]+>");
// 记录 text 在替换之前的长度,text 要将 <, > 替换成 <, >
int len = 0;
while (start != -1) {
if (monitor.isCanceled()) {
// 用户取消操作
throw new OperationCanceledException(Messages.getString("html.cancel"));
}
if (file.substring(start, start + 3).equals("<![")) { //$NON-NLS-1$
end = file.indexOf("]]>") + 2; //$NON-NLS-1$
}
if (end < start || end < 0 || start < 0) {
throw new Exception(Messages.getString("html.Html2Xliff.msg2")); //$NON-NLS-1$
}
String element = file.substring(start, end + 1);
// check if the element is OK or has strange stuff
// from Adobe GoLive 5
int errors = element.indexOf("<", 1); //$NON-NLS-1$
if (errors != -1 && !element.startsWith("<![")) { //$NON-NLS-1$
// there is a "<" inside quotes
// must move manually until the end
// of the element avoiding angle brackets
// within quotes
boolean exit = false;
boolean inQuotes = false;
StringBuffer buffer = new StringBuffer();
buffer.append("<"); //$NON-NLS-1$
int k = 0;
while (!exit) {
k++;
char c = file.charAt(start + k);
if (c == '\"') {
inQuotes = !inQuotes;
}
buffer.append(c);
if (!inQuotes && c == '>') {
exit = true;
}
}
element = buffer.toString();
end = start + buffer.toString().length();
start = end;
}
type = getNodeType(element);
if (type.equals("![INCLUDE[") || type.equals("![IGNORE[") || type.equals("![CDATA[")) { //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
// it's an SGML section, send it to skeleton
// and keep looking for segments
segments.add(text);
text = ""; //$NON-NLS-1$
len = 0;
end = file.indexOf("]]>"); //$NON-NLS-1$
segments.add(file.substring(start, end + 3));
file = file.substring(end + 3);
start = file.indexOf("<"); //$NON-NLS-1$
end = file.indexOf(">"); //$NON-NLS-1$
if (start != -1) {
text = file.substring(0, start);
len = text.length();
}
continue;
}
if (startsSegment.containsKey(type)) {
segments.add(text);
file = file.substring(len);
start = start - len;
end = end - len;
text = ""; //$NON-NLS-1$
len = text.length();
}
if (type.startsWith("/") && startsSegment.containsKey(type.substring(1))) { //$NON-NLS-1$
segments.add(text);
file = file.substring(len);
start = start - len;
end = end - len;
text = ""; //$NON-NLS-1$
len = text.length();
}
if (type.equals("script") || type.equals("style")) { //$NON-NLS-1$ //$NON-NLS-2$
// send the whole element to the list
segments.add(text);
file = file.substring(len);
text = ""; //$NON-NLS-1$
len = text.length();
if (!element.endsWith("/>")) { //$NON-NLS-1$
end = file.toLowerCase().indexOf("/" + type + ">"); //$NON-NLS-1$ //$NON-NLS-2$
String script = file.substring(0, end + 2 + type.length());
if (script.indexOf("<!--") != -1 && script.indexOf("-->") == -1) { //$NON-NLS-1$ //$NON-NLS-2$
// there are nested scripts inside this one
end = file.toLowerCase().indexOf("/" + type + ">", file.indexOf("-->") + 3); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
script = file.substring(0, end + 2 + type.length());
}
segments.add(script);
file = file.substring(end + 2 + type.length());
} else {
segments.add(element);
file = file.substring(element.length());
}
start = file.indexOf("<"); //$NON-NLS-1$
end = file.indexOf(">"); //$NON-NLS-1$
if (start != -1) {
text = file.substring(0, start);
len = text.length();
}
continue;
}
if (type.equals("!--")) { //$NON-NLS-1$
// it's a comment, send it to skeleton
// and keep looking for segments
segments.add(text);
file = file.substring(len);
text = ""; //$NON-NLS-1$
len = text.length();
end = file.indexOf("-->"); //$NON-NLS-1$
String comment = file.substring(0, end + 3);
segments.add(comment);
file = file.substring(end + 3);
start = file.indexOf("<"); //$NON-NLS-1$
end = file.indexOf(">"); //$NON-NLS-1$
if (start != -1) {
text = file.substring(0, start);
len = text.length();
}
continue;
}
text = text + element;
len += element.length();
if (end < file.length()) { // there may be text to extract
Matcher matcher = pattern.matcher(file);
int startIndex = 0;
while (matcher.find()) {
startIndex = matcher.start();
if (startIndex > end) {
break;
}
}
if (startIndex > end) {
String strTmpText = file.substring(end + 1, startIndex);
len += strTmpText.length();
strTmpText = strTmpText.replaceAll("<", "<");
strTmpText = strTmpText.replaceAll(">", ">");
text += strTmpText;
}
}
Matcher matcher = pattern.matcher(file);
int start2 = start;
while (matcher.find()) {
start = matcher.start();
end = matcher.end();
if (start > start2) {
break;
}
}
end--;
if (end > file.length()) {
end = file.length();
}
if (start <= start2) {
start = -1;
}
}
segments.add(text);
monitor.done();
}
}
}
| 43,749 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
Xliff2Html.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.html/src/net/heartsome/cat/converter/html/Xliff2Html.java | /**
* Xliff2Html.java
*
* Version information :
*
* Date:Jan 14, 2010
*
* Copyright notice :
*/
package net.heartsome.cat.converter.html;
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.html.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 Xliff2Html.
* @author John Zhu
* @version
* @since JDK1.6
*/
public class Xliff2Html implements Converter {
/** The Constant TYPE_VALUE. */
public static final String TYPE_VALUE = "html";
/** The Constant TYPE_NAME_VALUE. */
public static final String TYPE_NAME_VALUE = Messages.getString("html.TYPE_NAME_VALUE");
/** The Constant NAME_VALUE. */
public static final String NAME_VALUE = "XLIFF to Html Conveter";
/**
* (non-Javadoc).
* @param args
* the args
* @param monitor
* the monitor
* @return the map< string, string>
* @throws ConverterException
* the converter exception
* @see net.heartsome.cat.converter.Converter#convert(java.util.Map, org.eclipse.core.runtime.IProgressMonitor)
*/
public Map<String, String> convert(Map<String, String> args, IProgressMonitor monitor) throws ConverterException {
Xliff2HtmlImpl converter = new Xliff2HtmlImpl();
// 需要添加指定 ini file
String iniDir = args.get(Converter.ATTR_INIDIR);
String iniFile = iniDir + System.getProperty("file.separator") + "init_html.xml";
args.put(Converter.ATTR_INI_FILE, iniFile);
return converter.run(args, monitor);
}
/**
* (non-Javadoc).
* @return the name
* @see net.heartsome.cat.converter.Converter#getName()
*/
public String getName() {
return NAME_VALUE;
}
/**
* (non-Javadoc).
* @return the type
* @see net.heartsome.cat.converter.Converter#getType()
*/
public String getType() {
return TYPE_VALUE;
}
/**
* (non-Javadoc).
* @return the type name
* @see net.heartsome.cat.converter.Converter#getTypeName()
*/
public String getTypeName() {
return TYPE_NAME_VALUE;
}
/**
* The Class Xliff2HtmlImpl.
* @author John Zhu
* @version
* @since JDK1.6
*/
class Xliff2HtmlImpl {
/** The input. */
private InputStreamReader input;
/** The buffer. */
private BufferedReader buffer;
/** The skl file. */
private String sklFile;
/** The xliff file. */
private String xliffFile;
/** The line. */
private String line;
/** The segments. */
private Hashtable<String, Element> segments;
/** The output. */
private FileOutputStream output;
/** The encoding. */
private String encoding;
/** The entities. */
private Hashtable<String, String> entities;
/** The catalogue. */
private Catalogue catalogue;
// 计算替换进度的对象
private CalculateProcessedBytes cpb;
// 替换过程的进度监视器
private IProgressMonitor replaceMonitor;
/**
* 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 iniFile = params.get(Converter.ATTR_INI_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);
if (iniFile == null || "".equals(iniFile)) {
ConverterUtils.throwConverterException(Activator.PLUGIN_ID, Messages.getString("html.Xliff2Html.msg1"));
}
try {
infoLogger.logConversionFileInfo(catalogueFile, iniFile, xliffFile, sklFile);
// 经过对不同大小的文件进行测试后,可以对转换过程进行如下划分。把整个转换过程分为 10,其中加载 catalogue 文件占 2,加载 ini文件占 1,加载 xliff 文件占 3,替换过程占 4。
monitor.beginTask("", 10);
monitor.subTask(Messages.getString("html.Xliff2Html.task2"));
infoLogger.startLoadingCatalogueFile();
if (catalogueFile != null) {
catalogue = new Catalogue(catalogueFile);
}
infoLogger.endLoadingCatalogueFile();
monitor.worked(2);
// 是否取消操作
if (monitor.isCanceled()) {
throw new OperationCanceledException(Messages.getString("html.cancel"));
}
monitor.subTask(Messages.getString("html.Xliff2Html.task3"));
infoLogger.startLoadingIniFile();
loadEntities(iniFile);
infoLogger.endLoadingIniFile();
monitor.worked(1);
// 是否取消操作
if (monitor.isCanceled()) {
throw new OperationCanceledException(Messages.getString("html.cancel"));
}
infoLogger.startLoadingXliffFile();
output = new FileOutputStream(outputFile);
loadSegments(Progress.getSubMonitor(monitor, 3));
infoLogger.endLoadingXliffFile();
infoLogger.startReplacingSegmentSymbol();
try {
// 初始化计算替换进度的对象
cpb = ConverterUtils.getCalculateProcessedBytes(sklFile);
replaceMonitor = Progress.getSubMonitor(monitor, 4);
replaceMonitor.beginTask(Messages.getString("html.Xliff2Html.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) {
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) {
// 替换字符
String replaceCode = code;
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())) {
writeString(tgtStr, true, replaceCode);
} else {
writeString(extractText(source), true, replaceCode);
}
} else {
writeString(extractText(source), true, replaceCode);
}
} else {
ConverterUtils.throwConverterException(Activator.PLUGIN_ID,
MessageFormat.format(Messages.getString("html.Xliff2Html.msg2"), code));
}
index = line.indexOf("%%%"); //$NON-NLS-1$
if (index == -1) {
writeString(line);
}
} // end while
} else {
//
// non translatable portion
//
writeString(line);
}
line = buffer.readLine();
}
} finally {
// 保证 monitor 的 done 方法被调用
replaceMonitor.done();
}
infoLogger.endReplacingSegmentSymbol();
result.put(Converter.ATTR_TARGET_FILE, outputFile);
infoLogger.endConversion();
} catch (OperationCanceledException e) {
throw e;
} catch (Exception e) {
if (Converter.DEBUG_MODE) {
e.printStackTrace();
}
ConverterUtils.throwConverterException(Activator.PLUGIN_ID, Messages.getString("html.Xliff2Html.msg3"), e);
} finally {
if (output != null) {
try {
output.close();
} catch (IOException e) {
// ignore the exception
}
}
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 addEntities(result);
}
/**
* Load entities.
* @param iniFile
* the ini file
* @throws SAXException
* the SAX exception
* @throws IOException
* Signals that an I/O exception has occurred.
*/
private void loadEntities(String iniFile) throws SAXException, IOException {
SAXBuilder builder = new SAXBuilder();
if (catalogue != null) {
builder.setEntityResolver(catalogue);
}
Document doc = builder.build(iniFile);
Element root = doc.getRootElement();
entities = new Hashtable<String, String>();
List<Element> ents = root.getChildren("entity"); //$NON-NLS-1$
Iterator<Element> it = ents.iterator();
while (it.hasNext()) {
Element e = it.next();
entities.put(e.getText(), "&" + e.getAttributeValue("name") + ";"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
}
root = null;
doc = null;
builder = null;
}
/**
* Adds the entities.
* @param text
* the text
* @return the string
*/
private String addEntities(String text) {
StringBuffer result = new StringBuffer();
boolean inTag = false;
int start = text.indexOf("<"); //$NON-NLS-1$
int end = text.indexOf(">"); //$NON-NLS-1$
if (end != -1) {
if (start == -1) {
inTag = true;
} else {
if (end < start) {
inTag = true;
}
}
}
for (int i = 0; i < text.length(); i++) {
char c = text.charAt(i);
if (c == '<') {
inTag = true;
}
if (c == '>') {
inTag = false;
}
if (!inTag && entities.containsKey("" + c)) { //$NON-NLS-1$
if (c == '&' && text.charAt(i + 1) == '#') {
// check if it is an escaped entity
// like: &#x2018;
int scolon = text.indexOf(";", i); //$NON-NLS-1$
if (scolon == -1) {
// not an escaped entity
result.append(entities.get("" + c)); //$NON-NLS-1$
} else {
// check for space before the semicolon
int space = text.indexOf(" ", i); //$NON-NLS-1$
if (space == -1) {
// no space before the semicolon
// it is an escaped entity
result.append(c);
} else {
if (space > scolon) {
// space is after semicolon
// it is an escaped entity
result.append(c);
} else {
// not an escaped entity
result.append(entities.get("" + c)); //$NON-NLS-1$
}
}
}
} else {
result.append(entities.get("" + c)); //$NON-NLS-1$
}
} else {
result.append(c);
}
}
return result.toString();
}
/**
* Write string.
* @param string
* the string
* @throws IOException
* Signals that an I/O exception has occurred.
*/
private void writeString(String string) throws IOException {
writeString(string, false, null);
}
/**
* Write string.
* @param string
* the string
* @param isSegment
* 标识当前所写内容,ture 标识当前所写内容为 segment,false 标识当前所定内容为原骨架文件中的内容。
* @param replaceCode
* skeleton 文件中的segment 标识符
* @throws IOException
* Signals that an I/O exception has occurred.
*/
private void writeString(String string, boolean isSegment, String replaceCode) throws IOException {
byte[] bytes = string.getBytes(encoding);
output.write(bytes);
// 是否取消操作
if (replaceMonitor.isCanceled()) {
throw new OperationCanceledException(Messages.getString("html.cancel"));
}
if (!isSegment) {
cpb.calculateProcessed(replaceMonitor, string, encoding);
} else {
replaceCode = "%%%" + replaceCode + "%%%";
cpb.calculateProcessed(replaceMonitor, replaceCode, encoding);
}
}
/**
* Load segments.
* @throws SAXException
* the SAX exception
* @throws IOException
* Signals that an I/O exception has occurred.
*/
private void loadSegments(IProgressMonitor monitor) throws SAXException, IOException {
try {
// 在加载 xliff 文件时,构建 dom tree 的进度无法控制,所以在此取任务总量为未知。
monitor.beginTask(Messages.getString("html.Xliff2Html.msg4"), IProgressMonitor.UNKNOWN);
monitor.subTask("");
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()) {
// 是否取消操作
if (monitor.isCanceled()) {
throw new OperationCanceledException(Messages.getString("html.cancel"));
}
Element unit = i.next();
segments.put(unit.getAttributeValue("id"), unit); //$NON-NLS-1$
}
} finally {
monitor.done();
}
}
}
}
| 15,398 | 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.html/src/net/heartsome/cat/converter/html/Activator.java | /**
* Activator.java
*
* Version information :
*
* Date:Jan 14, 2010
*
* Copyright notice :
*/
package net.heartsome.cat.converter.html;
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.
*/
public class Activator implements BundleActivator {
// The plug-in ID
/** The Constant PLUGIN_ID. */
public static final String PLUGIN_ID = "net.heartsome.cat.converter.html";
// The shared instance
/** The plugin. */
private static Activator plugin;
/** The html2 xliff sr. */
private ServiceRegistration html2XliffSR;
/** The xliff2 html sr. */
private ServiceRegistration xliff2HtmlSR;
/**
* 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 converter service
Converter html2Xliff = new Html2Xliff();
Properties properties = new Properties();
properties.put(Converter.ATTR_NAME, Html2Xliff.NAME_VALUE);
properties.put(Converter.ATTR_TYPE, Html2Xliff.TYPE_VALUE);
properties.put(Converter.ATTR_TYPE_NAME, Html2Xliff.TYPE_NAME_VALUE);
html2XliffSR = ConverterRegister.registerPositiveConverter(context, html2Xliff, properties);
Converter xliff2Html = new Xliff2Html();
properties = new Properties();
properties.put(Converter.ATTR_TYPE, Xliff2Html.TYPE_VALUE);
properties.put(Converter.ATTR_TYPE_NAME, Xliff2Html.TYPE_NAME_VALUE);
properties.put(Converter.ATTR_NAME, Xliff2Html.NAME_VALUE);
xliff2HtmlSR = ConverterRegister.registerReverseConverter(context, xliff2Html, 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 (html2XliffSR != null) {
html2XliffSR.unregister();
html2XliffSR = null;
}
if (xliff2HtmlSR != null) {
xliff2HtmlSR.unregister();
xliff2HtmlSR = null;
}
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 |
Messages.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.html/src/net/heartsome/cat/converter/html/resource/Messages.java | /**
* Messages.java
*
* Version information :
*
* Date:Jan 14, 2010
*
* Copyright notice :
*/
package net.heartsome.cat.converter.html.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.html.resource.html"; //$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,016 | 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.msoffice2007/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.msoffice2007/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 |
Xliff2MSOffice.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.msoffice2007/src/net/heartsome/cat/converter/msoffice2007/Xliff2MSOffice.java | /**
* Xliff2MSOffice.java
*
* Version information :
*
* Date:Jan 14, 2010
*
* Copyright notice :
*/
package net.heartsome.cat.converter.msoffice2007;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
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.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;
import net.heartsome.cat.converter.Converter;
import net.heartsome.cat.converter.ConverterException;
import net.heartsome.cat.converter.msoffice2007.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.util.StringConverter;
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.runtime.IProgressMonitor;
import org.eclipse.core.runtime.OperationCanceledException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* The Class Xliff2MSOffice.
* @author John Zhu
* @version
* @since JDK1.6
*/
public class Xliff2MSOffice implements Converter {
private static final Logger LOGGER = LoggerFactory.getLogger(Xliff2MSOffice.class);
/** The Constant TYPE_VALUE. */
public static final String TYPE_VALUE = "x-msoffice2007";
/** The Constant TYPE_NAME_VALUE. */
public static final String TYPE_NAME_VALUE = Messages.getString("msoffice2007.TYPE_NAME_VALUE");
/** The Constant NAME_VALUE. */
public static final String NAME_VALUE = "XLIFF to MS Office 2007 Conveter";
// 内部实现所依赖的转换器
/** The dependant converter. */
private Converter dependantConverter;
/**
* for test to initialize depend on converter.
*/
public Xliff2MSOffice() {
dependantConverter = Activator.getXMLConverter(Converter.DIRECTION_REVERSE);
}
/**
* 运行时把所依赖的转换器,在初始化的时候通过构造函数注入。.
* @param converter
* the converter
*/
public Xliff2MSOffice(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 {
Xliff2MSOfficeImpl converter = new Xliff2MSOfficeImpl();
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 John Zhu
* @version
* @since JDK1.6
*/
class Xliff2MSOfficeImpl {
/** The files table. */
private Hashtable<String, String> filesTable;
/** The is embedded. */
private boolean isEmbedded = false;
/** The catalogue. */
private String catalogue;
private boolean isInfoEnabled = LOGGER.isInfoEnabled();
/**
* Builds the doc.
* @param filename
* the filename
* @return the document
* @throws Exception
* the exception
*/
public Document buildDoc(String filename) throws Exception {
SAXBuilder builder = new SAXBuilder();
builder.setEntityResolver(new Catalogue(catalogue));
Document doc = builder.build(filename);
return doc;
}
/**
* Creates the empty doc.
* @param filename
* the filename
* @return the document
* @throws Exception
* the exception
*/
public Document createEmptyDoc(String filename) throws Exception {
File file = new File(filename);
FileOutputStream fos = new FileOutputStream(file);
OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF-8"); //$NON-NLS-1$
BufferedWriter bw = new BufferedWriter(osw);
bw.write("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n"); //$NON-NLS-1$
bw.write("<xliff version=\"1.2\" xmlns=\"urn:oasis:names:tc:xliff:document:1.2\" \n" //$NON-NLS-1$
+ "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" \n" //$NON-NLS-1$
+ "xmlns:hs=\"" + Converter.HSNAMESPACE + "\" \n" //$NON-NLS-1$ //$NON-NLS-2$
+ "xsi:schemaLocation=\"urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd \n" //$NON-NLS-1$
+ Converter.HSSCHEMALOCATION + "\">\n"); //$NON-NLS-1$
bw.write("</xliff>\n"); //$NON-NLS-1$
bw.flush();
bw.close();
osw.close();
fos.close();
bw = null;
osw = null;
fos = null;
return buildDoc(filename);
}
/**
* Save file.
* @param element
* the element
* @throws Exception
* the exception
*/
private void saveFile(Element element) throws Exception {
File xliff = File.createTempFile("tmp", ".xlf"); //$NON-NLS-1$ //$NON-NLS-2$
Document doc = createEmptyDoc(xliff.getAbsolutePath());
Element root = doc.getRootElement();
root.setAttribute("version", "1.2"); //$NON-NLS-1$ //$NON-NLS-2$
Element file = new Element("file", doc); //$NON-NLS-1$
file.clone(element, doc);
root.addContent(file);
List<Element> groups = file.getChild("header").getChildren("hs:prop-group"); //$NON-NLS-1$ //$NON-NLS-2$
Iterator<Element> i = groups.iterator();
while (i.hasNext()) {
Element group = i.next();
if (group.getAttributeValue("name").equals("document")) { //$NON-NLS-1$ //$NON-NLS-2$
filesTable.put(group.getChild("hs:prop").getText(), xliff.getAbsolutePath()); //$NON-NLS-1$
}
}
if (file.getChild("header").getChild("skl").getChild("external-file") == null) { //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
// embedded skeleton
file.getChild("header").getChild("skl").addContent(new Element("external-file", doc)); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
isEmbedded = true;
}
file
.getChild("header").getChild("skl").getChild("external-file").setAttribute("href", xliff.getAbsolutePath() + ".skl"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
XMLOutputter outputter = new XMLOutputter();
FileOutputStream output = new FileOutputStream(xliff.getAbsolutePath());
outputter.output(doc, output);
output.close();
outputter = null;
}
/**
* 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>();
String xliffFile = args.get(Converter.ATTR_XLIFF_FILE);
String outputFile = args.get(Converter.ATTR_TARGET_FILE);
catalogue = args.get(Converter.ATTR_CATALOGUE);
filesTable = new Hashtable<String, String>();
try {
// 把转换过程分为三部分共 20 个任务,其中分离出各个 xliff 文件占 8,分离出 skeleton 文件占 2,生成目标文件占 10。
monitor.beginTask(Messages.getString("msoffice2007.Xliff2MSOffice.task1"), 20);
infoLogger.logConversionFileInfo(catalogue, null, xliffFile, null);
IProgressMonitor separateMonitor = Progress.getSubMonitor(monitor, 8);
long startTime = 0;
try {
if (isInfoEnabled) {
startTime = System.currentTimeMillis();
LOGGER.info(Messages.getString("msoffice2007.Xliff2MSOffice.logger1"), startTime);
}
SAXBuilder builder = new SAXBuilder();
Document doc = builder.build(xliffFile);
Element root = doc.getRootElement();
List<Element> files = root.getChildren("file"); //$NON-NLS-1$
separateMonitor.beginTask(Messages.getString("msoffice2007.Xliff2MSOffice.task2"), files.size());
Iterator<Element> it = files.iterator();
while (it.hasNext()) {
saveFile(it.next());
// 是否取消操作
if (separateMonitor.isCanceled()) {
throw new OperationCanceledException(Messages.getString("msoffice2007.cancel"));
}
separateMonitor.worked(1);
}
} finally {
separateMonitor.done();
}
long endTime = 0;
if (isInfoEnabled) {
endTime = System.currentTimeMillis();
LOGGER.info(Messages.getString("msoffice2007.Xliff2MSOffice.logger2"), endTime);
LOGGER.info(Messages.getString("msoffice2007.Xliff2MSOffice.logger3"), endTime - startTime);
}
monitor.subTask(Messages.getString("msoffice2007.Xliff2MSOffice.task3"));
if (isInfoEnabled) {
startTime = System.currentTimeMillis();
LOGGER.info(Messages.getString("msoffice2007.Xliff2MSOffice.logger4"), startTime);
}
String skeleton = args.get(Converter.ATTR_SKELETON_FILE);
if (isEmbedded) {
File t = File.createTempFile("tmp", ".skl"); //$NON-NLS-1$ //$NON-NLS-2$
StringConverter.decodeFile(skeleton, t.getAbsolutePath());
skeleton = t.getAbsolutePath();
}
if (isInfoEnabled) {
endTime = System.currentTimeMillis();
LOGGER.info(Messages.getString("msoffice2007.Xliff2MSOffice.logger5"), endTime);
LOGGER.info(Messages.getString("msoffice2007.Xliff2MSOffice.logger6"), endTime - startTime);
}
monitor.worked(2);
IProgressMonitor conversionMonitor = Progress.getSubMonitor(monitor, 10);
try {
ZipFile zipFile = new ZipFile(skeleton);
int totalTask = zipFile.size();
conversionMonitor.beginTask(Messages.getString("msoffice2007.Xliff2MSOffice.task4"), totalTask);
if (isInfoEnabled) {
startTime = System.currentTimeMillis();
LOGGER.info(Messages.getString("msoffice2007.Xliff2MSOffice.logger7"), startTime);
}
ZipInputStream in = new ZipInputStream(new FileInputStream(skeleton));
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(outputFile));
ZipEntry entry = null;
while ((entry = in.getNextEntry()) != null) {
// 标识是否委派其它转换器进行了处理
boolean isDelegate = false;
// 是否取消
if (conversionMonitor.isCanceled()) {
throw new OperationCanceledException(Messages.getString("msoffice2007.cancel"));
}
String messagePattern = Messages.getString("msoffice2007.Xliff2MSOffice.msg1");
String message = MessageFormat.format(messagePattern, new Object[] { entry.getName() });
conversionMonitor.subTask(message);
if (entry.getName().matches(".*\\.[xX][mM][lL]\\.skl")) { //$NON-NLS-1$
String name = entry.getName().substring(0, entry.getName().lastIndexOf(".skl")); //$NON-NLS-1$
File tmp = new File(filesTable.get(name) + ".skl"); //$NON-NLS-1$
FileOutputStream output = new FileOutputStream(tmp.getAbsolutePath());
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
output.write(buf, 0, len);
}
output.close();
Hashtable<String, String> table = new Hashtable<String, String>();
table.put(Converter.ATTR_XLIFF_FILE, filesTable.get(name));
table.put(Converter.ATTR_TARGET_FILE, filesTable.get(name) + ".xml");
table.put(Converter.ATTR_CATALOGUE, catalogue);
table.put(Converter.ATTR_SKELETON_FILE, filesTable.get(name) + ".skl");
Map<String, String> res = dependantConverter.convert(table, Progress.getSubMonitor(
conversionMonitor, 1));
isDelegate = true;
if (res.get(Converter.ATTR_TARGET_FILE) == null) {
ConverterUtils.throwConverterException(Activator.PLUGIN_ID,
Messages.getString("msoffice2007.Xliff2MSOffice.msg2"));
}
ZipEntry content = new ZipEntry(name);
content.setMethod(ZipEntry.DEFLATED);
out.putNextEntry(content);
FileInputStream input = new FileInputStream(filesTable.get(name) + ".xml"); //$NON-NLS-1$
while ((len = input.read(buf)) > 0) {
out.write(buf, 0, len);
}
out.closeEntry();
input.close();
tmp.delete();
File xml = new File(filesTable.get(name) + ".xml"); //$NON-NLS-1$
xml.delete();
File xlf = new File(filesTable.get(name));
xlf.delete();
} else {
File tmp = File.createTempFile("entry", ".tmp"); //$NON-NLS-1$ //$NON-NLS-2$
FileOutputStream output = new FileOutputStream(tmp.getAbsolutePath());
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
output.write(buf, 0, len);
}
output.close();
ZipEntry content = new ZipEntry(entry.getName());
content.setMethod(ZipEntry.DEFLATED);
out.putNextEntry(content);
FileInputStream input = new FileInputStream(tmp.getAbsolutePath());
while ((len = input.read(buf)) > 0) {
out.write(buf, 0, len);
}
out.closeEntry();
input.close();
tmp.delete();
}
if (!isDelegate) {
conversionMonitor.worked(1);
}
}
out.close();
} finally {
conversionMonitor.done();
}
if (isInfoEnabled) {
endTime = System.currentTimeMillis();
LOGGER.info(Messages.getString("msoffice2007.Xliff2MSOffice.logger8"), endTime);
LOGGER.info(Messages.getString("msoffice2007.Xliff2MSOffice.logger9"), endTime - startTime);
}
if (isEmbedded) {
File f = new File(skeleton);
f.delete();
}
result.put(Converter.ATTR_TARGET_FILE, outputFile);
} 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("msoffice2007.Xliff2MSOffice.msg3"),
e);
} finally {
monitor.done();
}
infoLogger.endConversion();
return result;
}
}
}
| 14,620 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
MSOffice2Xliff.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.msoffice2007/src/net/heartsome/cat/converter/msoffice2007/MSOffice2Xliff.java | /**
* MSOffice2Xliff.java
*
* Version information :
*
* Date:Jan 14, 2010
*
* Copyright notice :
*/
package net.heartsome.cat.converter.msoffice2007;
import java.io.ByteArrayInputStream;
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.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Stack;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;
import net.heartsome.cat.converter.Converter;
import net.heartsome.cat.converter.ConverterException;
import net.heartsome.cat.converter.StringSegmenter;
import net.heartsome.cat.converter.msoffice2007.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 MSOffice2Xliff.
* @author John Zhu
* @version
* @since JDK1.6
*/
public class MSOffice2Xliff implements Converter {
/** The Constant TYPE_VALUE. */
public static final String TYPE_VALUE = "x-msoffice2007";
/** The Constant TYPE_NAME_VALUE. */
public static final String TYPE_NAME_VALUE = Messages.getString("msoffice2007.TYPE_NAME_VALUE");
/** The Constant NAME_VALUE. */
public static final String NAME_VALUE = "MS Office 2007 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 {
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 John Zhu
* @version
* @since JDK1.6
*/
class MSOffice2XliffImpl {
/** The qt tool id. */
private String qtToolID = null;
/** The src file. */
private String srcFile;
/** The skeleton. */
private String skeleton;
/** The merged. */
private Document merged;
/** The merged root. */
private Element mergedRoot;
/** The zip out. */
private ZipOutputStream zipOut;
/** The zip in. */
private ZipInputStream zipIn;
/** 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 text. */
private String text = ""; //$NON-NLS-1$
/** The in body. */
boolean inBody = false;
/** The out. */
private FileOutputStream out;
/** The skel. */
private FileOutputStream skel;
/** The segnum. */
private int segnum;
/** The seg by element. */
private boolean segByElement;
/** The segmenter. */
private StringSegmenter segmenter;
/** The src encoding. */
private String srcEncoding;
/** The is suite. */
private boolean isSuite;
/** The srx. */
private String srx;
/**
* Convert content.
* @param params
* the params
* @return the map< string, string>
* @throws ConverterException
* the converter exception
*/
public Map<String, String> convertContent(Map<String, String> params) throws ConverterException {
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);
segnum = 0;
try {
// if (segByElement == false) {
if (!segByElement) {
segmenter = new StringSegmenter(srx, sourceLanguage, catalogue);
}
SAXBuilder builder = new SAXBuilder();
Document doc = builder.build(inputFile);
Element root = doc.getRootElement();
out = new FileOutputStream(xliffFile);
skel = new FileOutputStream(skeletonFile);
writeHeader();
recurse(root);
writeOut("</body>\n</file>\n</xliff>"); //$NON-NLS-1$
out.close();
skel.close();
result.put(Converter.ATTR_XLIFF_FILE, xliffFile);
} catch (Exception e) {
if (Converter.DEBUG_MODE) {
e.printStackTrace();
}
ConverterUtils.throwConverterException(Activator.PLUGIN_ID, Messages.getString("msoffice2007.MSOffice2Xliff.msg1"),
e);
}
return result;
}
/**
* 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);
Map<String, String> result = new HashMap<String, String>();
srcFile = args.get(Converter.ATTR_SOURCE_FILE);
String xliff = args.get(Converter.ATTR_XLIFF_FILE);
skeleton = 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);
String elementSegmentation = args.get(Converter.ATTR_SEG_BY_ELEMENT);
srx = args.get(Converter.ATTR_SRX);
srcEncoding = args.get(Converter.ATTR_SOURCE_ENCODING);
if (elementSegmentation == null) {
segByElement = false;
} else {
if (elementSegmentation.equals(Converter.TRUE)) {
segByElement = true;
} else {
segByElement = false;
}
}
try {
// 把总任务分为压缩文件中的条目个数+1;其中最后一个任务为 library3 写合并后的 xliff 文件。
ZipFile zipFile = new ZipFile(srcFile);
int size = zipFile.size();
int totalTask = size + 1;
monitor.beginTask(Messages.getString("msoffice2007.MSOffice2Xliff.task1"), totalTask);
merged = new Document(null, "xliff", null, null); //$NON-NLS-1$
mergedRoot = merged.getRootElement();
mergedRoot.setAttribute("version", "1.2"); //$NON-NLS-1$ //$NON-NLS-2$
mergedRoot.setAttribute("xmlns", "urn:oasis:names:tc:xliff:document:1.2"); //$NON-NLS-1$ //$NON-NLS-2$
mergedRoot.setAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance"); //$NON-NLS-1$ //$NON-NLS-2$
mergedRoot.setAttribute("xmlns:hs", Converter.HSNAMESPACE); //$NON-NLS-1$
mergedRoot
.setAttribute(
"xsi:schemaLocation", "urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd " + Converter.HSSCHEMALOCATION); //$NON-NLS-1$ //$NON-NLS-2$
zipOut = new ZipOutputStream(new FileOutputStream(skeleton));
zipIn = new ZipInputStream(new FileInputStream(srcFile));
ZipEntry entry = null;
while ((entry = zipIn.getNextEntry()) != null) {
// 检查是否取消操作
if (monitor.isCanceled()) {
throw new OperationCanceledException(Messages.getString("msoffice2007.cancel"));
}
String messagePattern = Messages.getString("msoffice2007.MSOffice2Xliff.task2");
String message = MessageFormat.format(messagePattern, new Object[] { entry.getName() });
monitor.setTaskName(message);
if (entry.getName().matches(".*\\.[xX][mM][lL]")) { //$NON-NLS-1$
File f = new File(entry.getName());
String name = f.getName();
String tmpFileName = name.substring(0, name.lastIndexOf(".")); //$NON-NLS-1$
if (tmpFileName.length() < 3) {
tmpFileName += "_tmp"; //$NON-NLS-1$
}
File tmp = File.createTempFile(tmpFileName, ".xml"); //$NON-NLS-1$
FileOutputStream output = new FileOutputStream(tmp.getAbsolutePath());
byte[] buf = new byte[1024];
int len;
while ((len = zipIn.read(buf)) > 0) {
output.write(buf, 0, len);
}
output.close();
try {
Hashtable<String, String> table = new Hashtable<String, String>();
table.put(Converter.ATTR_SOURCE_FILE, tmp.getAbsolutePath());
table.put(Converter.ATTR_XLIFF_FILE, tmp.getAbsolutePath() + ".xlf"); //$NON-NLS-1$
table.put(Converter.ATTR_SKELETON_FILE, tmp.getAbsolutePath() + ".skl"); //$NON-NLS-1$
boolean hasError = false;
Map<String, String> res = null;
try {
res = convertContent(table);
} catch (ConverterException ce) {
hasError = true;
}
if (res == null || res.get(Converter.ATTR_XLIFF_FILE) == null) {
hasError = true;
}
if (!hasError) {
if (countSegments(tmp.getAbsolutePath() + ".xlf") > 0) { //$NON-NLS-1$
updateXliff(tmp.getAbsolutePath() + ".xlf", entry.getName()); //$NON-NLS-1$
addFile(tmp.getAbsolutePath() + ".xlf"); //$NON-NLS-1$
ZipEntry content = new ZipEntry(entry.getName() + ".skl"); //$NON-NLS-1$
content.setMethod(ZipEntry.DEFLATED);
zipOut.putNextEntry(content);
FileInputStream input = new FileInputStream(tmp.getAbsolutePath() + ".skl"); //$NON-NLS-1$
byte[] array = new byte[1024];
while ((len = input.read(array)) > 0) {
zipOut.write(array, 0, len);
}
zipOut.closeEntry();
input.close();
} else {
saveEntry(entry, tmp.getAbsolutePath());
}
File skl = new File(tmp.getAbsolutePath() + ".skl"); //$NON-NLS-1$
skl.delete();
File xlf = new File(tmp.getAbsolutePath() + ".xlf"); //$NON-NLS-1$
xlf.delete();
} else {
saveEntry(entry, tmp.getAbsolutePath());
}
} catch (Exception e) {
if (Converter.DEBUG_MODE) {
e.printStackTrace();
}
// do nothing
saveEntry(entry, tmp.getAbsolutePath());
}
tmp.delete();
} else {
// not an XML file
File tmp = File.createTempFile("zip", ".tmp"); //$NON-NLS-1$ //$NON-NLS-2$
FileOutputStream output = new FileOutputStream(tmp.getAbsolutePath());
byte[] buf = new byte[1024];
int len;
while ((len = zipIn.read(buf)) > 0) {
output.write(buf, 0, len);
}
output.close();
saveEntry(entry, tmp.getAbsolutePath());
tmp.delete();
}
monitor.worked(1);
}
zipOut.close();
// output final XLIFF
// fixed a bug 572 by john. keep a well-format of xliff. add a
// empty
// file into xliff if root have not file element.
List<Element> files = mergedRoot.getChildren("file"); //$NON-NLS-1$
if (files.size() == 0) {
Element file = new Element("file", merged); //$NON-NLS-1$
file.setAttribute("original", srcFile); //$NON-NLS-1$
file.setAttribute("source-language", sourceLanguage); //$NON-NLS-1$
file.setAttribute("datatype", TYPE_VALUE); //$NON-NLS-1$
Element header = new Element("header", merged); //$NON-NLS-1$
Element body = new Element("body", merged); //$NON-NLS-1$
file.addContent(header);
file.addContent("\n"); //$NON-NLS-1$
file.addContent(body);
mergedRoot.addContent(file);
header = null;
body = null;
file = null;
}
files = null;
// 生成 xliff 文件
if (monitor.isCanceled()) {
throw new OperationCanceledException(Messages.getString("msoffice2007.cancel"));
}
monitor.subTask(Messages.getString("msoffice2007.MSOffice2Xliff.task3"));
XMLOutputter outputter = new XMLOutputter();
outputter.preserveSpace(true);
FileOutputStream output = new FileOutputStream(xliff);
outputter.output(merged, output);
output.close();
result.put(Converter.ATTR_XLIFF_FILE, xliff);
monitor.worked(1);
} catch (OperationCanceledException e) {
throw e;
} catch (Exception e) {
if (Converter.DEBUG_MODE) {
e.printStackTrace();
}
ConverterUtils.throwConverterException(Activator.PLUGIN_ID, Messages.getString("msoffice2007.MSOffice2Xliff.msg2"),
e);
} finally {
monitor.done();
}
return result;
}
/**
* Write header.
* @throws IOException
* Signals that an I/O exception has occurred.
*/
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 (!targetLanguage.equals("")) {
writeOut("<file datatype=\"x-office\" original=\"" + cleanString(inputFile) + "\" source-language=\"" + sourceLanguage + "\" target-language=\"" + targetLanguage + "\">\n"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
}else {
writeOut("<file datatype=\"x-office\" original=\"" + cleanString(inputFile) + "\" source-language=\"" + sourceLanguage + "\">\n"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
}
writeOut("<header>\n"); //$NON-NLS-1$
writeOut("<skl>\n"); //$NON-NLS-1$
if (isSuite) {
writeOut("<external-file crc=\"" + CRC16.crc16(TextUtil.cleanString(skeleton).getBytes("UTF-8")) + "\" href=\"" + cleanString(skeletonFile) + "\"/>\n"); //$NON-NLS-1$ //$NON-NLS-2$
} else {
writeOut("<external-file href=\"" + cleanString(skeletonFile) + "\"/>\n"); //$NON-NLS-1$ //$NON-NLS-2$
}
writeOut("</skl>\n"); //$NON-NLS-1$
writeOut(" <tool tool-id=\"" + qtToolID + "\" tool-name=\"HSStudio\"/>\n"); //$NON-NLS-1$ //$NON-NLS-2$
writeOut(" <hs:prop-group name=\"encoding\"><hs:prop prop-type=\"encoding\">" //$NON-NLS-1$
+ srcEncoding + "</hs:prop></hs:prop-group>\n"); //$NON-NLS-1$
writeOut("</header>\n<body>\n"); //$NON-NLS-1$
writeOut("\n"); //$NON-NLS-1$
}
/**
* Save entry.
* @param entry
* the entry
* @param name
* the name
* @throws IOException
* Signals that an I/O exception has occurred.
*/
private void saveEntry(ZipEntry entry, String name) throws IOException {
ZipEntry content = new ZipEntry(entry.getName());
content.setMethod(ZipEntry.DEFLATED);
zipOut.putNextEntry(content);
FileInputStream input = new FileInputStream(name);
byte[] array = new byte[1024];
int len;
while ((len = input.read(array)) > 0) {
zipOut.write(array, 0, len);
}
zipOut.closeEntry();
input.close();
}
/**
* Write segment.
* @param sourceText
* the source text
* @throws IOException
* Signals that an I/O exception has occurred.
* @throws SAXException
* the SAX exception
*/
private void writeSegment(String sourceText) throws IOException, SAXException {
String s = "<source xml:lang=\"" + sourceLanguage + "\">" + sourceText + "</source>"; //$NON-NLS-1$ //$NON-NLS-2$
SAXBuilder b = new SAXBuilder();
Document d = b.build(new ByteArrayInputStream(s.getBytes("UTF-8"))); //$NON-NLS-1$
Element source = d.getRootElement();
List<Node> content = source.getContent();
String start = ""; //$NON-NLS-1$
String end = ""; //$NON-NLS-1$
List<Element> tags = source.getChildren("ph"); //$NON-NLS-1$
if (tags.size() == 1) {
if (content.get(0).getNodeType() == Node.ELEMENT_NODE) {
Element e = tags.get(0);
start = e.getText();
content.remove(0);
source.setContent(content);
} else if (content.get(content.size() - 1).getNodeType() == Node.ELEMENT_NODE) {
Element e = tags.get(0);
end = e.getText();
content.remove(content.size() - 1);
source.setContent(content);
}
} else if (tags.size() > 1) {
if (content.get(0).getNodeType() == Node.ELEMENT_NODE
&& content.get(content.size() - 1).getNodeType() == Node.ELEMENT_NODE) {
// check if it is possible to send
// initial and trailing tag to skeleton
Element first = new Element(content.get(0));
Element last = new Element(content.get(content.size() - 1));
String test = first.getText() + last.getText();
if (checkPairs(test)) {
start = first.getText();
end = last.getText();
content.remove(content.size() - 1);
content.remove(0);
source.setContent(content);
}
}
}
writeSkel(start);
if (containsText(source)) {
List<Element> phs = source.getChildren("ph"); //$NON-NLS-1$
for (int i = 0; i < phs.size(); i++) {
phs.get(i).setAttribute("id", "" + (i + 1)); //$NON-NLS-1$ //$NON-NLS-2$
}
writeOut("<trans-unit id=\"" + segnum + "\">\n"); //$NON-NLS-1$ //$NON-NLS-2$
writeOut(source.toString());
writeOut("\n</trans-unit>\n\n"); //$NON-NLS-1$
writeSkel("%%%" + segnum++ + "%%%\n"); //$NON-NLS-1$ //$NON-NLS-2$
} else {
Iterator<Node> i = source.getContent().iterator();
while (i.hasNext()) {
Node n = i.next();
if (n.getNodeType() == Node.TEXT_NODE) {
writeSkel(cleanString(n.getNodeValue()));
} else {
Element e = new Element(n);
writeSkel(e.getText());
}
}
}
writeSkel(end);
}
/**
* Check pairs.
* @param test
* the test
* @return true, if successful
*/
private boolean checkPairs(String test) {
String[] parts = test.trim().split("<"); //$NON-NLS-1$
Stack<String> stack = new Stack<String>();
for (int i = 0; i < parts.length; i++) {
if (parts[i].length() > 0) {
String[] subparts = parts[i].split("[\\s]|[>]"); //$NON-NLS-1$
if (subparts[0].startsWith("/")) { //$NON-NLS-1$
if (stack.size() == 0) {
return false;
} else {
String last = stack.pop();
if (!last.equals(subparts[0].substring(1))) {
return false;
}
}
} else {
stack.push(subparts[0]);
}
}
}
if (stack.size() == 0) {
return true;
}
return false;
}
/**
* Contains text.
* @param source
* the source
* @return true, if successful
*/
private boolean containsText(Element source) {
List<Node> content = source.getContent();
String string = ""; //$NON-NLS-1$
Iterator<Node> i = content.iterator();
while (i.hasNext()) {
Node n = i.next();
if (n.getNodeType() == Node.TEXT_NODE) {
string = string + n.getNodeValue();
}
}
return !string.trim().equals(""); //$NON-NLS-1$
}
/**
* Write out.
* @param string
* the string
* @throws IOException
* Signals that an I/O exception has occurred.
*/
private void writeOut(String string) throws IOException {
out.write(string.getBytes("UTF-8")); //$NON-NLS-1$
}
/**
* Recurse.
* @param e
* the e
* @throws IOException
* Signals that an I/O exception has occurred.
* @throws SAXException
* the SAX exception
*/
private void recurse(Element e) throws IOException, SAXException {
writeSkel("<" + e.getName()); //$NON-NLS-1$
List<Attribute> atts = e.getAttributes();
Iterator<Attribute> at = atts.iterator();
while (at.hasNext()) {
Attribute a = at.next();
writeSkel(" " + a.getName() + "=\"" + a.getValue() + "\""); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
}
writeSkel(">"); //$NON-NLS-1$
List<Element> children = e.getChildren();
Iterator<Element> i = children.iterator();
while (i.hasNext()) {
Element child = i.next();
if (child.getName().matches("[a-z]:p") || child.getName().matches("t")) { //$NON-NLS-1$ //$NON-NLS-2$
recursePara(child);
} else {
recurse(child);
}
}
writeSkel("</" + e.getName() + ">"); //$NON-NLS-1$ //$NON-NLS-2$
}
/**
* Write skel.
* @param string
* the string
* @throws IOException
* Signals that an I/O exception has occurred.
*/
private void writeSkel(String string) throws IOException {
skel.write(string.getBytes("UTF-8")); //$NON-NLS-1$
}
/**
* Recurse para.
* @param e
* the e
* @throws IOException
* Signals that an I/O exception has occurred.
* @throws SAXException
* the SAX exception
*/
private void recursePara(Element e) throws IOException, SAXException {
// send the opening tag to skeleton
writeSkel("<" + e.getName()); //$NON-NLS-1$
List<Attribute> atts = e.getAttributes();
Iterator<Attribute> ia = atts.iterator();
while (ia.hasNext()) {
Attribute a = ia.next();
writeSkel(" " + a.getName() + "=\"" + a.getValue() + "\""); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
}
writeSkel(">"); //$NON-NLS-1$
// send initial elements that don't have text to skeleton
List<Element> content = e.getChildren();
int i = 0;
for (; i < content.size(); i++) {
Element child = content.get(i);
if (hasTextElement(child)) {
break;
}
writeSkel(child.toString());
}
// fixed a bug by john. can not extrace text from docx and pptx
if (e.getName().matches("([a-z]:)?t")) { //$NON-NLS-1$
text = cleanString(e.getText());
} else {
if (content.size() - i == 1) {
recursePara(content.get(i));
} else {
// get the text from the remaining elements
for (; i < content.size(); i++) {
recursePhrase(content.get(i));
}
}
}
text = text.replaceAll("</ph><ph>", ""); //$NON-NLS-1$ //$NON-NLS-2$
// if (segByElement == true) {
if (segByElement) {
writeSegment(text);
} else {
String[] segs = segmenter.segment(text);
for (int h = 0; h < segs.length; h++) {
String seg = segs[h];
writeSegment(seg);
}
}
text = ""; //$NON-NLS-1$
// send closing tag to skeleton
writeSkel("</" + e.getName() + ">"); //$NON-NLS-1$ //$NON-NLS-2$
}
/**
* Checks for text element.
* @param e
* the e
* @return true, if successful
*/
private boolean hasTextElement(Element e) {
// fixed a bug by john. can not extrace text from docx and pptx
if (e.getName().matches("([a-z]:)?t")) { //$NON-NLS-1$
return true;
}
boolean containsText = false;
List<Element> children = e.getChildren();
for (int i = 0; i < children.size(); i++) {
containsText = containsText || hasTextElement(children.get(i));
}
return containsText;
}
/**
* Recurse phrase.
* @param e
* the e
* @throws IOException
* Signals that an I/O exception has occurred.
*/
private void recursePhrase(Element e) throws IOException {
text = text + "<ph><" + e.getName(); //$NON-NLS-1$
List<Attribute> atts = e.getAttributes();
Iterator<Attribute> ia = atts.iterator();
while (ia.hasNext()) {
Attribute a = ia.next();
text = text + " " + a.getName() + "=\"" + a.getValue() + "\""; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
}
text = text + "></ph>"; //$NON-NLS-1$
// fixed a bug by john. can not extrace text from docx and pptx
if (e.getName().matches("([a-z]:)?t")) { //$NON-NLS-1$
text = text + cleanString(e.getText());
} else {
List<Element> children = e.getChildren();
for (int i = 0; i < children.size(); i++) {
recursePhrase(children.get(i));
}
}
text = text + "<ph></" + e.getName() + " ></ph>"; //$NON-NLS-1$ //$NON-NLS-2$
}
/**
* Count segments.
* @param string
* the string
* @return the int
* @throws SAXException
* the SAX exception
* @throws IOException
* Signals that an I/O exception has occurred.
*/
private int countSegments(String string) throws SAXException, IOException {
SAXBuilder builder = new SAXBuilder();
Document doc = builder.build(string);
Element root = doc.getRootElement();
return root.getChild("file").getChild("body").getChildren("trans-unit").size(); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
}
/**
* Adds the file.
* @param xliff
* the xliff
* @throws SAXException
* the SAX exception
* @throws IOException
* Signals that an I/O exception has occurred.
*/
private void addFile(String xliff) throws SAXException, IOException {
SAXBuilder builder = new SAXBuilder();
Document doc = builder.build(xliff);
Element root = doc.getRootElement();
Element file = root.getChild("file"); //$NON-NLS-1$
Element newFile = new Element("file", merged); //$NON-NLS-1$
newFile.clone(file, merged);
mergedRoot.addContent(newFile);
File f = new File(xliff);
f.delete();
}
/**
* Update xliff.
* @param xliff
* the xliff
* @param original
* the original
* @throws SAXException
* the SAX exception
* @throws IOException
* Signals that an I/O exception has occurred.
*/
private void updateXliff(String xliff, String original) throws SAXException, IOException {
SAXBuilder builder = new SAXBuilder();
Document doc = builder.build(xliff);
Element root = doc.getRootElement();
Element file = root.getChild("file"); //$NON-NLS-1$
file.setAttribute("datatype", TYPE_VALUE); //$NON-NLS-1$
file.setAttribute("original", TextUtil.cleanString(inputFile)); //$NON-NLS-1$
Element header = file.getChild("header"); //$NON-NLS-1$
Element elePropGroup = new Element("hs:prop-group", doc); //$NON-NLS-1$
elePropGroup.setAttribute("name", "document"); //$NON-NLS-1$ //$NON-NLS-2$
Element originalProp = new Element("hs:prop", doc); //$NON-NLS-1$
originalProp.setAttribute("prop-type", "original"); //$NON-NLS-1$ //$NON-NLS-2$
originalProp.setText(original);
header.addContent("\n"); //$NON-NLS-1$
elePropGroup.addContent(originalProp);
Element srcFileProp = new Element("hs:prop", doc); //$NON-NLS-1$
srcFileProp.setAttribute("prop-type", "sourcefile"); //$NON-NLS-1$ //$NON-NLS-2$
srcFileProp.setText(srcFile);
header.addContent("\n"); //$NON-NLS-1$
elePropGroup.addContent(srcFileProp);
header.addContent(elePropGroup);
Element ext = header.getChild("skl").getChild("external-file"); //$NON-NLS-1$ //$NON-NLS-2$
ext.setAttribute("href", TextUtil.cleanString(skeleton)); //$NON-NLS-1$
if (isSuite) {
ext.setAttribute("crc", "" + CRC16.crc16(TextUtil.cleanString(skeleton).getBytes("UTF-8"))); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
}
XMLOutputter outputter = new XMLOutputter();
FileOutputStream output = new FileOutputStream(xliff);
outputter.output(doc, output);
output.close();
}
}
/**
* Clean string.
* @param string
* the string
* @return the string
*/
private static String cleanString(String string) {
string = string.replaceAll("&", "&"); //$NON-NLS-1$ //$NON-NLS-2$
string = string.replaceAll("<", "<"); //$NON-NLS-1$ //$NON-NLS-2$
string = string.replaceAll(">", ">"); //$NON-NLS-1$ //$NON-NLS-2$
return string;
}
}
| 28,132 | 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.msoffice2007/src/net/heartsome/cat/converter/msoffice2007/Activator.java | /**
* Activator.java
*
* Version information :
*
* Date:Jan 14, 2010
*
* Copyright notice :
*/
package net.heartsome.cat.converter.msoffice2007;
import java.util.Properties;
import net.heartsome.cat.converter.Converter;
import net.heartsome.cat.converter.util.AndFilter;
import net.heartsome.cat.converter.util.ConverterRegister;
import net.heartsome.cat.converter.util.EqFilter;
import net.heartsome.cat.converter.xml.Xliff2Xml;
import net.heartsome.cat.converter.xml.Xml2Xliff;
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 plug-in ID
/** The Constant PLUGIN_ID. */
public static final String PLUGIN_ID = "net.heartsome.cat.converter.msoffice2007";
// 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 xml converter service
String positiveFilter = new AndFilter(new EqFilter(Constants.OBJECTCLASS, Converter.class.getName()),
new EqFilter(Converter.ATTR_TYPE, Xml2Xliff.TYPE_VALUE), new EqFilter(Converter.ATTR_DIRECTION,
Converter.DIRECTION_POSITIVE)).toString();
positiveTracker = new ServiceTracker(context, context.createFilter(positiveFilter), new XmlPositiveCustomizer());
positiveTracker.open();
String reverseFilter = new AndFilter(new EqFilter(Constants.OBJECTCLASS, Converter.class.getName()),
new EqFilter(Converter.ATTR_TYPE, Xliff2Xml.TYPE_VALUE), new EqFilter(Converter.ATTR_DIRECTION,
Converter.DIRECTION_REVERSE)).toString();
reverseTracker = new ServiceTracker(context, context.createFilter(reverseFilter), new XmlReverseCustomize());
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 xML converter.
* @param direction
* the direction
* @return the xML converter
*/
public static Converter getXMLConverter(String direction) {
if (Converter.DIRECTION_POSITIVE.equals(direction)) {
return new Xml2Xliff();
} else {
return new Xliff2Xml();
}
}
/**
* The Class XmlPositiveCustomizer.
* @author John Zhu
* @version
* @since JDK1.6
*/
private class XmlPositiveCustomizer 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 msOffice2Xliff = new MSOffice2Xliff();
Properties properties = new Properties();
properties.put(Converter.ATTR_NAME, MSOffice2Xliff.NAME_VALUE);
properties.put(Converter.ATTR_TYPE, MSOffice2Xliff.TYPE_VALUE);
properties.put(Converter.ATTR_TYPE_NAME, MSOffice2Xliff.TYPE_NAME_VALUE);
ServiceRegistration registration = ConverterRegister.registerPositiveConverter(bundleContext,
msOffice2Xliff, 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 XmlReverseCustomize.
* @author John Zhu
* @version
* @since JDK1.6
*/
private class XmlReverseCustomize 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 xliff2MSOffice = new Xliff2MSOffice(converter);
Properties properties = new Properties();
properties.put(Converter.ATTR_NAME, Xliff2MSOffice.NAME_VALUE);
properties.put(Converter.ATTR_TYPE, Xliff2MSOffice.TYPE_VALUE);
properties.put(Converter.ATTR_TYPE_NAME, Xliff2MSOffice.TYPE_NAME_VALUE);
ServiceRegistration registration = ConverterRegister.registerReverseConverter(bundleContext,
xliff2MSOffice, 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);
}
}
}
| 6,958 | 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.msoffice2007/src/net/heartsome/cat/converter/msoffice2007/resource/Messages.java | /**
* Messages.java
*
* Version information :
*
* Date:Jan 14, 2010
*
* Copyright notice :
*/
package net.heartsome.cat.converter.msoffice2007.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.msoffice2007.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,036 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
DummyInputValidator.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/others/org.eclipse.swtbot.mockdialogs/src/org/eclipse/swtbot/mockdialogs/factory/DummyInputValidator.java | package org.eclipse.swtbot.mockdialogs.factory;
/*******************************************************************************
* Copyright (c) 2009 Jan Petranek.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
*******************************************************************************/
import org.eclipse.jface.dialogs.IInputValidator;
/**
* The DummyInputValidator will accept any input.
*
* @author Jan Petranek
*
*/
public class DummyInputValidator implements IInputValidator {
/**
* Always accepts the input.
*
* @param newText
* text to accept
* @return always returns null
* @see org.eclipse.jface.dialogs.IInputValidator#isValid(java.lang.String)
*/
public String isValid(String newText) {
return null;
}
}
| 969 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
NativeDialogFactory.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/others/org.eclipse.swtbot.mockdialogs/src/org/eclipse/swtbot/mockdialogs/factory/NativeDialogFactory.java | package org.eclipse.swtbot.mockdialogs.factory;
/*******************************************************************************
* Copyright (c) 2009 Jan Petranek.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
*******************************************************************************/
import org.eclipse.jface.dialogs.InputDialog;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;
/**
* The Class NativeDialogFactory is a configurable Dialog factory.
*
* By default, it handles user dialogs with native dialogs (SWT).
* When the state is set to TESTING, it displays stand-in dialogs.
* Those stand-ins may be way simpler than the native widgets,
* but they are accessible by SWTBot.
*
* @author Jan Petranek
*/
public class NativeDialogFactory {
/** The Log4j logger instance. */
// static final Logger logger = Logger.getLogger(NativeDialogFactory.class);
/**
* The Enumeration DialogState, used to indicate the mode of operation.
*/
public enum OperationMode {
/** The DEFAULT state, for normal operation. */
DEFAULT,
/** The TESTING state, used to indicate SWTBot-Testing needs stand-in dialogs. */
TESTING
};
/** The mode of operation. */
private static OperationMode mode = OperationMode.DEFAULT;
/**
* Sets the operation mode.
*
* @param state the desired operation mode
*/
public static void setMode(OperationMode mode) {
NativeDialogFactory.mode = mode;
}
/**
* Gets the operation mode.
*
* @return the current operation mode
*/
public static OperationMode getMode() {
return mode;
}
/**
* Shows a file selection dialog.
*
* In default mode, this displays a native file selection dialog.
* In testing mode, a simple InputDialog is displayed, where the path can be entered as a String.
*
* @param shell the parent shell
* @param text title for the file selection dialog
* @param style the style of the file dialog, applies only to native dialogs (SWT.SAVE| SWT.OPEN | SWT.MULTI)
*
* @return a String with the selected file name. It is still up to the user to check, if the
* filename is valid. When the user has aborted the file selection, this returns null.
*
*/
public static String fileSelectionDialog(Shell shell, String text, int style) {
OperationMode mode = getMode();
switch (mode) {
case DEFAULT: {
// File standard dialog
FileDialog fileDialog = new FileDialog(shell, style);
fileDialog.setText(text);
return fileDialog.open();
}
case TESTING: {
InputDialog fileDialog = new InputDialog(shell, text,
"Select a file", "", new DummyInputValidator());
fileDialog.open();
return fileDialog.getValue();
}
default:
final String msg = "Reached default case in NativeDialogFactory.fileSelectionDialog, this is a bug, unknown state "
+ getMode();
// logger.warn(msg);
System.err.println(msg);
throw new RuntimeException(msg);
}
}
/**
* Show message box.
*
* In default mode, a native MessageBox is used.
* In testing mode, we use a MessageDialog, showing the same title and message.
*
* @param messageText the text of the message
* @param title the title
* @param iconStyle the icon style
* @param shell the parent shell
*/
public static void showMessageBox(Shell shell, String messageText,
final String title, final int iconStyle) {
if (shell == null) {
// logger
// .fatal("Shell not yet instantiated, cannot display error message");
System.err.println("Shell not yet instantiated, cannot display error message");
} else {
switch (getMode()) {
case DEFAULT: {
MessageBox messageBox = new MessageBox(shell, iconStyle);
messageBox.setMessage(messageText);
messageBox.setText(title);
messageBox.open();
break;
}
case TESTING: {
// ignore the iconStyle, this only creates trouble when testing.
MessageDialog messagDialog = new MessageDialog(shell, title,
null, messageText, MessageDialog.NONE,
new String[] { "OK" }, 0);
messagDialog.open();
break;
}
default:
final String msg = "Reached default case in NativeDialogFactory, this is a bug, unknown state "
+ getMode();
// logger.warn(msg);
System.err.println(msg);
throw new RuntimeException(msg);
}
}
}
}
| 4,603 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.