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 |
---|---|---|---|---|---|---|---|---|---|---|---|
OffLineEncrypt.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/base_plugins/net.heartsome.cat.ts.help/src/net/heartsome/license/encrypt/OffLineEncrypt.java | package net.heartsome.license.encrypt;
public class OffLineEncrypt {
public final static byte[] publicKey = new byte[] { 48, -127, -97, 48, 13, 6, 9, 42, -122, 72, -122, -9, 13, 1, 1,
1, 5, 0, 3, -127, -115, 0, 48, -127, -119, 2, -127, -127, 0, -105, -102, 76, 88, 104, 64, 113, 23, 22, 40,
-104, -53, -73, -93, -71, -72, 89, -52, -51, 56, -106, 12, -111, -83, -104, -113, -119, 21, -100, -16, -94,
-3, -75, 82, -117, -62, 51, -12, -34, 9, 14, -118, 119, -50, -37, 11, -89, 11, -122, 82, 33, -26, 34, -84,
-63, -4, -23, 43, 39, 15, 16, 79, 86, 102, 30, -62, -120, -50, -98, -62, 58, -40, 87, -51, 82, 73, -26,
-51, 73, 11, -56, 1, -36, 110, -101, -36, -80, -52, 76, 95, -52, -17, -65, -49, -114, 43, 3, -78, 120, 84,
88, -74, -111, -43, -93, 18, 31, 40, -93, 80, 94, -49, -32, -5, -85, -117, -112, 2, 66, 39, 38, 20, -46,
-122, 22, 2, 45, -105, 2, 3, 1, 0, 1 };
}
| 888 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
Encrypt.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/base_plugins/net.heartsome.cat.ts.help/src/net/heartsome/license/encrypt/Encrypt.java | package net.heartsome.license.encrypt;
public interface Encrypt {
byte[] getPublicKey();
byte[] getPrivateKey();
byte[] encrypt(byte[] publicKeyArray, byte[] srcBytes);
byte[] decrypt(byte[] privateKeyArray, byte[] srcBytes);
}
| 236 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
EncryptRSA.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/base_plugins/net.heartsome.cat.ts.help/src/net/heartsome/license/encrypt/EncryptRSA.java | package net.heartsome.license.encrypt;
import java.io.ByteArrayOutputStream;
import java.security.Key;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import javax.crypto.Cipher;
public class EncryptRSA implements Encrypt {
// 非对称加密密钥算法
private static final String algorithm = "RSA";
// 密钥长度,用来初始化
private static final int key_size = 1024;
// 公钥
private final byte[] publicKey;
// 私钥
private final byte[] privateKey;
public EncryptRSA() {
SecureRandom sr = new SecureRandom();
KeyPairGenerator kpg = null;
try {
kpg = KeyPairGenerator.getInstance(algorithm);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
kpg.initialize(key_size, sr);
KeyPair kp = kpg.generateKeyPair();
Key keyPublic = kp.getPublic();
publicKey = keyPublic.getEncoded();
Key keyPrivate = kp.getPrivate();
privateKey = keyPrivate.getEncoded();
}
/**
* 加密
*
* @param publicKeyArray
* @param srcBytes
* @return
*/
public byte[] encrypt(byte[] publicKeyArray, byte[] srcBytes) {
try {
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicKeyArray);
KeyFactory kf = KeyFactory.getInstance(algorithm);
PublicKey keyPublic = kf.generatePublic(keySpec);
Cipher cipher;
cipher = Cipher.getInstance(algorithm,
new org.bouncycastle.jce.provider.BouncyCastleProvider());
cipher.init(Cipher.ENCRYPT_MODE, keyPublic);
int blockSize = cipher.getBlockSize();
int outputSize = cipher.getOutputSize(srcBytes.length);
int leavedSize = srcBytes.length % blockSize;
int blocksSize = leavedSize != 0 ? srcBytes.length / blockSize + 1
: srcBytes.length / blockSize;
byte[] raw = new byte[outputSize * blocksSize];
int i = 0;
while (srcBytes.length - i * blockSize > 0) {
if (srcBytes.length - i * blockSize > blockSize)
cipher.doFinal(srcBytes, i * blockSize, blockSize, raw, i
* outputSize);
else
cipher.doFinal(srcBytes, i * blockSize, srcBytes.length - i
* blockSize, raw, i * outputSize);
i++;
}
return raw;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 解密
*
* @param privateKeyArray
* @param srcBytes
* @return
*/
public byte[] decrypt(byte[] privateKeyArray, byte[] srcBytes) {
try {
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(privateKeyArray);
KeyFactory kf = KeyFactory.getInstance(algorithm);
PrivateKey keyPrivate = kf.generatePrivate(keySpec);
Cipher cipher = Cipher.getInstance(algorithm,
new org.bouncycastle.jce.provider.BouncyCastleProvider());
cipher.init(Cipher.DECRYPT_MODE, keyPrivate);
int blockSize = cipher.getBlockSize();
ByteArrayOutputStream bout = new ByteArrayOutputStream(blockSize);
int j = 0;
while (srcBytes.length - j * blockSize > 0) {
byte[] temp = cipher.doFinal(srcBytes, j * blockSize, blockSize);
bout.write(temp);
j++;
}
return bout.toByteArray();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public byte[] getPublicKey() {
return publicKey;
}
public byte[] getPrivateKey() {
return privateKey;
}
}
| 3,464 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
InstallKeyEncrypt.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/base_plugins/net.heartsome.cat.ts.help/src/net/heartsome/license/encrypt/InstallKeyEncrypt.java | package net.heartsome.license.encrypt;
import net.heartsome.license.ProtectionFactory;
public class InstallKeyEncrypt {
private final static byte[] publicKey = new byte[] {48,-127,-97,48,13,6,9,42,-122,72,-122,-9,13,1,1,1,5,0,3,
-127,-115,0,48,-127,-119,2,-127,-127,0,-126,84,87,97,-103,60,114,-92,-21,23,111,34,-45,61,8,
-39,-18,-95,96,-99,-4,-15,-51,52,-82,91,-108,-102,87,-37,-8,34,23,-16,98,-100,38,-7,82,-13,
67,47,96,-102,-128,-48,21,-106,-94,23,119,-77,-46,72,-89,-44,64,-11,81,127,26,-38,-59,26,102,
-58,-89,104,-117,88,87,-93,-9,110,-21,-102,-24,-72,-23,-41,45,7,-35,-72,-105,-98,-27,-114,-74,
-49,-35,-93,-85,66,111,-72,-4,58,-116,-93,-102,27,-49,-25,32,75,4,-2,-95,112,-60,-103,32,43,31,
60,18,-89,24,-85,-63,-95,73,-115,13,22,-102,-25,2,3,1,0,1};
private final static byte[] privateKey = new byte[] {48,-126,2,118,2,1,0,48,13,6,9,42,-122,72,-122,-9,13,1,1,
1,5,0,4,-126,2,96,48,-126,2,92,2,1,0,2,-127,-127,0,-126,84,87,97,-103,60,114,-92,-21,23,111,
34,-45,61,8,-39,-18,-95,96,-99,-4,-15,-51,52,-82,91,-108,-102,87,-37,-8,34,23,-16,98,-100,38,
-7,82,-13,67,47,96,-102,-128,-48,21,-106,-94,23,119,-77,-46,72,-89,-44,64,-11,81,127,26,-38,
-59,26,102,-58,-89,104,-117,88,87,-93,-9,110,-21,-102,-24,-72,-23,-41,45,7,-35,-72,-105,-98,
-27,-114,-74,-49,-35,-93,-85,66,111,-72,-4,58,-116,-93,-102,27,-49,-25,32,75,4,-2,-95,112,
-60,-103,32,43,31,60,18,-89,24,-85,-63,-95,73,-115,13,22,-102,-25,2,3,1,0,1,2,-127,-128,78,
45,-21,-48,-25,12,4,-75,123,52,-82,125,20,124,11,96,55,-82,100,119,-63,49,7,104,-81,-94,-50,
12,-101,-31,-97,2,76,-101,-19,123,64,65,-43,-119,-119,102,-43,43,57,84,25,111,39,-62,-82,18,
-105,116,-17,-1,-6,11,110,-100,-79,110,68,71,66,-54,27,-119,-66,25,-60,-57,27,-36,44,48,95,
-49,-34,97,85,22,116,88,-109,-73,-55,-106,56,-6,-45,16,-85,72,-84,-120,126,-41,-26,10,58,61,
-83,-21,-86,51,44,-51,-65,-82,-51,-69,124,105,-86,11,-69,83,-82,-70,78,116,13,-13,-82,111,
-121,33,2,65,0,-13,-81,-101,117,47,-74,84,88,-98,49,-117,99,-75,-82,-122,-19,-86,-11,-118,
-19,103,-118,-94,-39,-9,87,18,-39,12,7,126,9,-16,-67,-104,77,-80,-91,112,-125,-88,-59,32,
120,-96,-120,-18,-123,36,-25,-105,-99,12,96,91,90,0,0,-108,67,95,-18,-15,-79,2,65,0,-120,
-22,82,59,-32,75,-106,-88,120,99,-5,-10,87,104,89,-38,85,27,-45,-17,-77,4,81,78,55,30,-65,
2,35,-63,-54,-33,65,-113,83,57,-82,105,-29,107,-98,114,1,103,106,12,120,26,-110,14,-72,-26,
116,-4,-22,24,72,27,-94,-44,21,66,36,23,2,64,14,-47,65,-63,-87,106,11,-52,-21,-87,-107,-111,
53,-115,-20,52,109,109,-54,-55,-50,-66,-10,82,12,-95,37,-53,62,-39,1,-57,-10,-12,-128,91,80,
-1,110,77,3,41,33,101,84,85,-97,51,71,96,49,-82,-31,-2,-59,-17,62,10,-54,-7,33,-49,52,-79,2,
65,0,-120,88,80,-20,47,-63,22,-105,78,-52,-62,-19,-34,-67,-100,61,64,-28,37,122,94,-37,-67,
-36,22,40,24,47,25,76,-77,-85,0,-82,-86,66,-106,-35,-4,12,0,13,-88,56,67,-13,-122,-25,110,
-20,26,85,-27,-54,-73,-108,-42,-70,46,-68,-27,46,-88,-95,2,64,72,69,76,-106,-91,82,-34,-14,
-15,-115,119,-51,-7,-12,46,34,79,44,-89,32,123,46,-100,-5,-35,-72,96,-33,-2,93,31,-94,-3,15,
-56,-109,-8,112,-116,67,68,-125,63,73,-78,-93,65,-110,29,5,-23,-15,80,9,-52,-125,-67,-81,-40,
76,70,104,51,-59};
public static byte[] encrypt(byte[] srcBytes) {
return ProtectionFactory.getEncrypt().encrypt(publicKey, srcBytes);
}
public static byte[] decrypt(byte[] srcBytes) {
return ProtectionFactory.getEncrypt().decrypt(privateKey,srcBytes);
}
}
| 3,450 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
IService.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/base_plugins/net.heartsome.cat.ts.help/src/net/heartsome/license/webservice/IService.java | package net.heartsome.license.webservice;
public interface IService{
public byte[] getServerPublicKey() throws Exception;
public String buyLicense(String username, String email,String productInfo);
/**
* 激活许可证
* @param info 客户端信息,包括许可证号、硬件指纹、安装码
* @param clientPublicKey 客户端公钥
* @return 激活信息
*/
public String activeLicense(String info, byte[] clientPublicKey) throws Exception;
/**
* 激活许可证
* @param info 客户端信息,包括许可证号、硬件指纹、安装码
* @param clientPublicKey 客户端公钥
* @param osType 操作系统
* @return 激活信息
*/
public String activeLicense(String info, byte[] clientPublicKey, String osType) throws Exception;
/**
* 校验许可证
* @param info 客户端信息,包括许可证号、最新的硬件指纹
* @param clientPublicKey 客户端公钥
* @return 校验信息
*/
public String checkLicense(String info, byte[] clientPublicKey) throws Exception;
/**
* 注销许可证
* @param info 客户端信息,包括许可证号、最新的硬件指纹
* @param clientPublicKey 客户端公钥
* @return 注销信息
*/
public String logoutLicense(String info, byte[] clientPublicKey) throws Exception;
/**
* 获取试用许可证的截止日期
* @param key
* @return
*/
public String getTempEndDate(String key, byte[] clientPublicKey) throws Exception;
} | 1,489 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
ServiceUtil.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/base_plugins/net.heartsome.cat.ts.help/src/net/heartsome/license/webservice/ServiceUtil.java | package net.heartsome.license.webservice;
import java.net.MalformedURLException;
import net.heartsome.license.LicenseReader;
import net.heartsome.license.ProtectionFactory;
import net.heartsome.license.constants.Constants;
import net.heartsome.license.encrypt.Encrypt;
import net.heartsome.license.encrypt.InstallKeyEncrypt;
import net.heartsome.license.generator.IKeyGenerator;
import net.heartsome.license.generator.KeyGeneratorImpl;
import net.heartsome.license.utils.FileUtils;
import net.heartsome.license.utils.StringUtils;
import java.lang.reflect.Proxy;
import org.codehaus.xfire.XFireFactory;
import org.codehaus.xfire.client.XFireProxy;
import org.apache.commons.httpclient.protocol.Protocol;
import org.apache.commons.httpclient.protocol.ProtocolSocketFactory;
import org.codehaus.xfire.client.Client;
import org.codehaus.xfire.client.XFireProxyFactory;
import org.codehaus.xfire.service.Service;
import org.codehaus.xfire.service.binding.ObjectServiceFactory;
import org.codehaus.xfire.transport.http.CommonsHttpMessageSender;
import org.codehaus.xfire.transport.http.EasySSLProtocolSocketFactory;
import org.codehaus.xfire.util.dom.DOMOutHandler;
import org.eclipse.swt.widgets.ProgressBar;
public class ServiceUtil {
private static final String SERVICE_URL ="https://lic.heartsome.net/hswebservices/licenses";
private static final String SERVICE_NAMESPACE = "licenses.XFire";
private static final String SERVICE_NAME = "licenses";
private static final String HTTP_TYPE = "https";
private static final int PORT = 443;
public static IService getService() throws MalformedURLException {
// Service srvcModel = new ObjectServiceFactory().create(IService.class);
// XFireProxyFactory factory = new XFireProxyFactory(XFireFactory
// .newInstance().getXFire());
//
// IService srvc = (IService) factory.create(srvcModel, Constants.CONNECT_URL);
// return srvc;
ProtocolSocketFactory easy = new EasySSLProtocolSocketFactory();
Protocol protocol = new Protocol(HTTP_TYPE, easy, PORT);
Protocol.registerProtocol(HTTP_TYPE, protocol);
Service serviceModel = new ObjectServiceFactory().create(IService.class,
SERVICE_NAME, SERVICE_NAMESPACE, null);
IService service = (IService) new XFireProxyFactory().create(serviceModel, SERVICE_URL);
Client client = ((XFireProxy)Proxy.getInvocationHandler(service)).getClient();
client.addOutHandler(new DOMOutHandler());
client.setProperty(CommonsHttpMessageSender.GZIP_ENABLED, Boolean.FALSE);
client.setProperty(CommonsHttpMessageSender.DISABLE_EXPECT_CONTINUE, "1");
client.setProperty(CommonsHttpMessageSender.HTTP_TIMEOUT, "0");
return service;
}
public static int active(String licenseId, ProgressBar bar) throws Exception {
boolean result = FileUtils.writeFile(new byte[] {'1','1'}, ProtectionFactory.getFileName(0, Constants.PRODUCTID));
if (!result) {
return Constants.EXCEPTION_INT8;
} else {
FileUtils.removeFile(ProtectionFactory.getFileName(0, Constants.PRODUCTID));
}
IService srvc = ServiceUtil.getService();
bar.setSelection(1);
String series = ProtectionFactory.getSeries();
if (series == null || "".equals(series)) {
return Constants.EXCEPTION_INT5;
}
byte[] serverPublicKey = srvc.getServerPublicKey();
bar.setSelection(2);
IKeyGenerator gen = new KeyGeneratorImpl();
byte[] k = gen.generateKey(licenseId, series, serverPublicKey);
if (k == null) {
return Constants.EXCEPTION_INT9;
}
bar.setSelection(3);
Encrypt en = ProtectionFactory.getEncrypt();
bar.setSelection(4);
String str = srvc.activeLicense(StringUtils.toHexString(k), en.getPublicKey(), ProtectionFactory.getPlatform());
bar.setSelection(5);
bar.setSelection(6);
byte[] b = StringUtils.toBytes(str);
bar.setSelection(7);
b = en.decrypt(en.getPrivateKey(), b);
if (b == null) {
return Constants.EXCEPTION_INT7;
}
bar.setSelection(8);
String info = new String(b);
if (Constants.RETURN_INVALIDLICENSE.equals(info)) {
return Constants.RETURN_INVALIDLICENSE_INT;
} else if (Constants.RETURN_INVALIDBUNDLE.equals(info)) {
return Constants.RETURN_INVALIDBUNDLE_INT;
} else if (Constants.RETURN_DBEXCEPTION.equals(info)) {
return Constants.EXCEPTION_INT13;
} else if (Constants.RETURN_MUTILTEMPBUNDLE.equals(info)) {
return Constants.RETURN_MUTILTEMPBUNDLE_INT;
} else if (Constants.RETURN_EXPIREDLICENSE.equals(info)) {
return Constants.RETURN_EXPIREDLICENSE_INT;
} else if (Constants.RETURN_STOPLICENSE.equals(info)) {
return Constants.RETURN_STOPLICENSE_INT;
} else {
result = FileUtils.writeFile(b, ProtectionFactory.getFileName(1, Constants.PRODUCTID));
if (!result) {
return Constants.EXCEPTION_INT12;
}
bar.setSelection(9);
b = InstallKeyEncrypt.encrypt(StringUtils.handle(gen.getInstallKey(), 1, 3, 2).getBytes());
if (b == null) {
return Constants.EXCEPTION_INT10;
}
result = FileUtils.writeFile(b, ProtectionFactory.getFileName(2, Constants.PRODUCTID));
if (!result) {
return Constants.EXCEPTION_INT11;
}
bar.setSelection(10);
System.getProperties().setProperty("TSState", "true");
return Constants.ACTIVE_OK_INT;
}
}
public static int check(String licenseId, String macCode, byte[] b) throws Exception {
IService srvc = ServiceUtil.getService();
byte[] serverPublicKey = srvc.getServerPublicKey();
IKeyGenerator gen = new KeyGeneratorImpl();
byte[] k = gen.generateKey(licenseId, macCode, new String(b), serverPublicKey);
if (k == null) {
return Constants.EXCEPTION_INT9;
}
Encrypt en = ProtectionFactory.getEncrypt();
String str = srvc.checkLicense(StringUtils.toHexString(k), en.getPublicKey());
b = StringUtils.toBytes(str);
b = en.decrypt(en.getPrivateKey(), b);
if (b == null) {
return Constants.EXCEPTION_INT7;
}
String info = new String(b);
if (Constants.RETURN_CHECKSUCESS.equals(info)) {
return Constants.STATE_VALID;
} else if (Constants.RETURN_EXPIREDLICENSE.equals(info)) {
return Constants.STATE_EXPIRED;
} else if (Constants.RETURN_MACCODEERR.equals(info)) {
return Constants.EXCEPTION_INT15;
} else {
return Constants.STATE_INVALID;
}
}
public static int cancel() throws Exception {
byte[] t = FileUtils.readFile(ProtectionFactory.getFileName(1, Constants.PRODUCTID));
if (t == null) {
return Constants.LOGOUT_FAIL;
}
t = new LicenseReader().getLicenseInfo(t);
if (t == null) {
return Constants.LOGOUT_FAIL;
}
t = StringUtils.reverse(new String(t), 1, 5, 2).getBytes();
IService srvc = ServiceUtil.getService();
byte[] serverPublicKey = srvc.getServerPublicKey();
Encrypt en = ProtectionFactory.getEncrypt();
String str = srvc.logoutLicense(StringUtils.toHexString(en.encrypt(serverPublicKey, t)), en.getPublicKey());
byte[] b = StringUtils.toBytes(str);
b = en.decrypt(en.getPrivateKey(), b);
String info = new String(b);
if (Constants.RETURN_LOGOUTSUCESS.equals(info)) {
return FileUtils.removeFile() ? Constants.LOGOUT_SUCCESS : Constants.LOGOUT_FAIL;
} else if (Constants.RETURN_INVALIDLICENSE.equals(info)) {
return FileUtils.removeFile() ? Constants.LOGOUT_SUCCESS : Constants.LOGOUT_FAIL;
} else {
return Constants.LOGOUT_FAIL;
}
}
public static String getTempEndDate(String key) throws Exception {
if (key == null) {
return null;
}
IService srvc = ServiceUtil.getService();
byte[] serverPublicKey = srvc.getServerPublicKey();
Encrypt en = ProtectionFactory.getEncrypt();
String str = srvc.getTempEndDate(StringUtils.toHexString(en.encrypt(serverPublicKey, key.getBytes())), en.getPublicKey());
byte[] b = StringUtils.toBytes(str);
b = en.decrypt(en.getPrivateKey(), b);
key = new String(b);
if (Constants.RETURN_NULLTEMPENDDATE.equals(key)) {
return null;
} else {
return key;
}
}
}
| 7,936 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
Constants.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/base_plugins/net.heartsome.cat.ts.help/src/net/heartsome/license/constants/Constants.java | package net.heartsome.license.constants;
public class Constants {
// 信息的分隔符,和ws服务器的分隔符保持一致,两处需要同时修改。net.heartsome.r8.webservice.utils.Constants
public final static String SEPARATOR = "#&";
public final static String RETURN_INVALIDLICENSE = "It is a invalid License";
public final static int RETURN_INVALIDLICENSE_INT = 1;
public final static String RETURN_INVALIDBUNDLE = "It is a invalid Bundle License";
public final static int RETURN_INVALIDBUNDLE_INT = 2;
public final static String RETURN_DBEXCEPTION = "Update database exception";
public final static String RETURN_STOPLICENSE = "It is a stop License";
public final static int RETURN_STOPLICENSE_INT = 3;
public final static int ACTIVE_OK_INT = 4;
public final static String RETURN_MUTILTEMPBUNDLE = "Mutil Active Trial License";
public final static int RETURN_MUTILTEMPBUNDLE_INT = 5;
public final static String RETURN_EXPIREDLICENSE = "Your license has expired";
public final static int RETURN_EXPIREDLICENSE_INT = 6;
public final static String RETURN_MACCODEERR = "MacCode is invalid";
public final static String RETURN_CHECKSUCESS = "Check is Sucess";
public final static int EXCEPTION_INT1 = 21;
public final static String EXCEPTION_STRING1 = "LIC001";
public final static int EXCEPTION_INT2 = 22;
public final static String EXCEPTION_STRING2 = "LIC002";
public final static int EXCEPTION_INT3 = 23;
public final static String EXCEPTION_STRING3 = "LIC003";
public final static int EXCEPTION_INT4 = 24;
public final static String EXCEPTION_STRING4 = "LIC004";
public final static int EXCEPTION_INT5 = 25;
public final static String EXCEPTION_STRING5 = "LIC005";
public final static int EXCEPTION_INT6 = 26;
public final static String EXCEPTION_STRING6 = "LIC006";
public final static int EXCEPTION_INT7 = 27;
public final static String EXCEPTION_STRING7 = "LIC007";
public final static int EXCEPTION_INT8 = 28;
public final static String EXCEPTION_STRING8 = "LIC008";
public final static int EXCEPTION_INT9 = 29;
public final static String EXCEPTION_STRING9 = "LIC009";
public final static int EXCEPTION_INT10 = 30;
public final static String EXCEPTION_STRING10 = "LIC010";
public final static int EXCEPTION_INT11 = 31;
public final static String EXCEPTION_STRING11 = "LIC011";
public final static int EXCEPTION_INT12 = 32;
public final static String EXCEPTION_STRING12 = "LIC012";
public final static int EXCEPTION_INT13 = 33;
public final static String EXCEPTION_STRING13 = "LIC013";
public final static int EXCEPTION_INT14 = 34;
public final static String EXCEPTION_STRING14 = "LIC014";
public final static int EXCEPTION_INT15 = 35;
public final static String EXCEPTION_STRING15 = "LIC015";
public final static int EXCEPTION_INT16 = 36;
public final static String EXCEPTION_STRING16 = "LIC016";
public final static int EXCEPTION_INT17 = 37;
public final static String EXCEPTION_STRING17 = "LIC017";
public final static int CANCEL = -1;
public final static int STATE_FILE_NOT_EXSIT = 0;
public final static int STATE_NOT_ACTIVATED = 1;
public final static int STATE_VALID = 2;
public final static int STATE_INVALID = 3;
public final static int STATE_EXPIRED = 4;
public final static String RETURN_LOGOUTSUCESS = "Logout is sucess";
public final static int LOGOUT_SUCCESS = 1;
public final static int LOGOUT_FAIL = 2;
public final static String PRODUCTID = System.getProperty("TSVersion");
public final static String TYPE_TMEP = "0";
public final static String TYPE_BUSINESS = "1";
public final static String CONNECT_URL = "http://192.168.0.191:8080/r8/licenses";
public final static String RETURN_NULLTEMPENDDATE = "TempEndDate is null";
}
| 3,751 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
Messages.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/base_plugins/net.heartsome.cat.ts.help/src/net/heartsome/license/resource/Messages.java | package net.heartsome.license.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.license.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;
}
}
}
| 544 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
Activator.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/database/net.heartsome.cat.database.oracle/src/net/heartsome/cat/database/oracle/Activator.java | package net.heartsome.cat.database.oracle;
import net.heartsome.cat.database.DBServiceProvider;
import org.eclipse.core.runtime.Plugin;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceRegistration;
/**
* The activator class controls the plug-in life cycle
*/
public class Activator extends Plugin {
// The plug-in ID
public static final String PLUGIN_ID = "net.heartsome.cat.database.oracle";
// The shared instance
private static Activator plugin;
// The oracle service registration
private ServiceRegistration<DBServiceProvider> oracleServiceRegistration;
/**
* 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;
DbServiceProviderImpl service = new DbServiceProviderImpl();
oracleServiceRegistration = context.registerService(DBServiceProvider.class, service, null);
}
/*
* (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);
oracleServiceRegistration.unregister();
}
/**
* Returns the shared instance
*
* @return the shared instance
*/
public static Activator getDefault() {
return plugin;
}
}
| 1,439 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
TMDatabaseImpl.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/database/net.heartsome.cat.database.oracle/src/net/heartsome/cat/database/oracle/TMDatabaseImpl.java | package net.heartsome.cat.database.oracle;
import java.net.URL;
import java.sql.CallableStatement;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;
import java.sql.Types;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.Vector;
import net.heartsome.cat.common.bean.TmxContexts;
import net.heartsome.cat.common.bean.TmxProp;
import net.heartsome.cat.common.bean.FuzzySearchResult;
import net.heartsome.cat.common.bean.MetaData;
import net.heartsome.cat.common.bean.TmxSegement;
import net.heartsome.cat.common.bean.TmxTU;
import net.heartsome.cat.common.bean.TranslationUnitAnalysisResult;
import net.heartsome.cat.common.util.CommonFunction;
import net.heartsome.cat.common.util.DateUtils;
import net.heartsome.cat.common.util.TextUtil;
import net.heartsome.cat.database.Constants;
import net.heartsome.cat.database.DBConfig;
import net.heartsome.cat.database.DBOperator;
import net.heartsome.cat.database.TranslationMemoryTools;
import net.heartsome.cat.database.Utils;
import net.heartsome.cat.database.bean.ExportFilterBean;
import net.heartsome.cat.database.bean.ExportFilterComponentBean;
import net.heartsome.cat.database.bean.FuzzySearchResults;
import net.heartsome.cat.database.bean.TranslationUnitAnalysisResults;
import oracle.jdbc.OracleCallableStatement;
import oracle.jdbc.OraclePreparedStatement;
import org.eclipse.core.runtime.Platform;
import org.osgi.framework.Bundle;
/**
* @author terry
* @version
* @since JDK1.6
*/
public class TMDatabaseImpl extends DBOperator {
/**
* 构造函数
*/
public TMDatabaseImpl() {
Bundle buddle = Platform.getBundle(Activator.PLUGIN_ID);
URL fileUrl = buddle.getEntry(Constants.DBCONFIG_PATH);
dbConfig = new DBConfig(fileUrl);
}
@Override
public void setMetaData(MetaData metaData) {
super.setMetaData(metaData);
dbConfig.setMetaData(metaData);
}
// TODO =========================TMX部分(开始)=========================
/**
* 将TMX的header接点的主要属性写入到mheader表中
* @throws SQLException
*/
public String insertHeader(Hashtable<String, String> params) throws SQLException {
CallableStatement stmt = null;
try {
String sql = dbConfig.getOperateDbSQL("insert-mheader");
stmt = conn.prepareCall(sql);
int i = 1;
stmt.setString(i++, params.get("CREATIONTOOL"));
stmt.setString(i++, params.get("CTVERSION"));
stmt.setString(i++, params.get("TMF"));
stmt.setString(i++, params.get("SRCLANG"));
stmt.setString(i++, params.get("ADMINLANG"));
stmt.setString(i++, params.get("DATATYPE"));
stmt.setString(i++, params.get("SEGTYPE"));
stmt.setString(i++, params.get("CREATIONID"));
stmt.setString(i++, params.get("CREATIONDATE"));
stmt.setString(i++, params.get("CHANGEID"));
stmt.setString(i++, params.get("CHANGEDATE"));
stmt.setString(i++, params.get("ENCODING"));
stmt.registerOutParameter(i++, Types.INTEGER);
stmt.execute();
return stmt.getString(i - 1);
} finally {
if (stmt != null) {
stmt.close();
}
}
}
/**
* 将数据插入HEADERNODE表
* @param params
* ;
* @throws SQLException
*/
public void insertHeaderNode(Hashtable<String, String> params) throws SQLException {
PreparedStatement stmt = null;
try {
String sql = dbConfig.getOperateDbSQL("insert-mheadernode");
stmt = conn.prepareStatement(sql);
int i = 1;
stmt.setInt(i++, Integer.parseInt(params.get("HEADERID")));
stmt.setString(i++, params.get("NODENAME"));
stmt.setString(i++, params.get("NODETYPE"));
stmt.setString(i++, params.get("CONTENT"));
stmt.executeUpdate();
} finally {
if (stmt != null) {
stmt.close();
}
}
}
/**
* 将数据写入到MTU表中
* @param params
* @return
* @throws SQLException
* ;
*/
public String insertTU(Hashtable<String, String> params) throws SQLException {
CallableStatement stmt = null;
ResultSet rs = null;
try {
String sql = dbConfig.getOperateDbSQL("insert-tu");
stmt = conn.prepareCall(sql);
int i = 1;
stmt.setInt(i++, Integer.parseInt(params.get("HEADERID")));
stmt.setString(i++, params.get("TUID"));
stmt.setString(i++, params.get("CREATIONID"));
stmt.setTimestamp(i++, DateUtils.getTimestampFromUTC(params.get("CREATIONDATE")));
stmt.setString(i++, params.get("CHANGEID"));
stmt.setTimestamp(i++, DateUtils.getTimestampFromUTC(params.get("CHANGEDATE")));
stmt.setString(i++, params.get("CREATIONTOOL"));
stmt.setString(i++, params.get("CREATIONTOOLVERSION"));
stmt.setString(i++, params.get("CLIENT"));
stmt.setString(i++, params.get("PROJECTREF"));
stmt.setString(i++, params.get("JOBREF"));
stmt.registerOutParameter(i++, Types.INTEGER);
stmt.execute();
return stmt.getString(i - 1);
} finally {
if (rs != null) {
rs.close();
}
if (stmt != null) {
stmt.close();
}
}
}
/**
* 插入数据到TEXTDATA表,更新LANGS表和MATRIX_LANG表
* @param params
* @return 插入TEXTDATA表记录的ID
* @throws SQLException
*/
public String insertTextData(String type, String groupId, String hash, String pureText, String content,
String lang, String preContext, String nextContext) throws SQLException {
/*
* 步骤 1.添加记录到TEXTDATA表 2.查看LANGS表是否有刚才添加的语言,没有则需要增加一条记录,然后需要创建相对应的matrix表 3.添加记录到Matrix表
*/
String textDataId = null;
PreparedStatement stmt = null;
try {
String langCode = Utils.langToCode(lang).toUpperCase();
String sql = dbConfig.getOperateDbSQL("get-lang-bycode");
if (!langCaches.contains(lang)) {
Map<Integer, Map<String, String>> langRs = query(sql, new Object[] { lang });
if (langRs.size() == 0) { // 说明对应的Matrix表还没有创建
sql = dbConfig.getOperateDbSQL("insert-lang");
stmt = conn.prepareStatement(sql);
stmt.setString(1, lang);
stmt.executeUpdate();
stmt.close();
// 创建表
List<String> createMatrixTables = dbConfig.getCreateMatrixTables();
for (String i : createMatrixTables) {
i = i.replaceAll("__LANG__", langCode);
stmt = conn.prepareStatement(i);
stmt.execute();
stmt.close();
}
// 创建索引
List<String> createMatrixIndex = dbConfig.getCreateMatrixIndexes();
for (String i : createMatrixIndex) {
i = i.replaceAll("__LANG__", langCode);
stmt = conn.prepareStatement(i);
stmt.execute();
stmt.close();
}
langCaches.add(lang);
}
}
if (pureText != null && lang != null && content != null) {
sql = dbConfig.getOperateDbSQL("insert-textdata");
OracleCallableStatement callStmt = (OracleCallableStatement) conn.prepareCall(sql);
int i = 1;
callStmt.setString(i++, type);
callStmt.setInt(i++, Integer.parseInt(groupId));
callStmt.setInt(i++, Integer.parseInt(hash));
callStmt.setStringForClob(i++, pureText);
callStmt.setStringForClob(i++, content);
callStmt.setString(i++, lang);
callStmt.setString(i++, preContext);
callStmt.setString(i++, nextContext);
callStmt.registerOutParameter(i++, Types.INTEGER);
callStmt.execute();
textDataId = callStmt.getString(i - 1);
callStmt.close();
int[] ngrams = generateNgrams(lang, pureText);
if (ngrams.length > 0) {
String insertMatrix = dbConfig.getMatrixSQL("insert");
insertMatrix = insertMatrix.replaceAll("__LANG__", langCode);
stmt = conn.prepareStatement(insertMatrix);
for (int j = 0; j < ngrams.length; j++) {
stmt.setInt(1, Integer.parseInt(textDataId));
stmt.setInt(2, ngrams[j]);
stmt.setShort(3, (short) ngrams.length);
stmt.addBatch();
}
stmt.executeBatch();
stmt.close();
}
}
} finally {
if (stmt != null) {
stmt.close();
}
}
return textDataId;
}
@Override
public int insertTU(int headerId, String tuId, String creationId, String creationDate, String changeId,
String changeDate, String creationTool, String creationToolVersion, String client, String projectRef,
String jobRef) throws SQLException {
CallableStatement stmt = null;
ResultSet rs = null;
try {
String sql = dbConfig.getOperateDbSQL("insert-tu");
if (null == conn) {
return -1;
}
stmt = conn.prepareCall(sql);
int i = 1;
stmt.setInt(i++, headerId);
stmt.setString(i++, tuId);
stmt.setString(i++, creationId);
stmt.setTimestamp(i++, DateUtils.getTimestampFromUTC(creationDate));
stmt.setString(i++, changeId);
stmt.setTimestamp(i++, DateUtils.getTimestampFromUTC(changeDate));
stmt.setString(i++, creationTool);
stmt.setString(i++, creationToolVersion);
stmt.setString(i++, client);
stmt.setString(i++, projectRef);
stmt.setString(i++, jobRef);
stmt.registerOutParameter(i, Types.INTEGER);
stmt.executeUpdate();
return stmt.getInt(i);
} finally {
if (rs != null) {
rs.close();
}
if (stmt != null) {
stmt.close();
}
}
}
@Override
public String insertTextData(String type, int groupId, String hash, String pureText, String content, String lang,
String preContext, String nextContext) throws SQLException {
/*
* 步骤 1.添加记录到TEXTDATA表 2.查看LANGS表是否有刚才添加的语言,没有则需要增加一条记录,然后需要创建相对应的matrix表 3.添加记录到Matrix表
*/
String textDataId = null;
CallableStatement stmt = null;
try {
String langCode = Utils.langToCode(lang).toUpperCase();
String sql = dbConfig.getOperateDbSQL("get-lang-bycode");
if (!langCaches.contains(lang)) {
Map<Integer, Map<String, String>> langRs = query(sql, new Object[] { lang });
if (langRs.size() == 0) { // 说明对应的Matrix表还没有创建
sql = dbConfig.getOperateDbSQL("insert-lang");
stmt = conn.prepareCall(sql);
stmt.setString(1, lang);
stmt.executeUpdate();
stmt.close();
// 创建表
List<String> createMatrixTables = dbConfig.getCreateMatrixTables();
for (String i : createMatrixTables) {
i = i.replaceAll("__LANG__", langCode);
stmt = conn.prepareCall(i);
stmt.execute();
stmt.close();
}
// 创建索引
List<String> createMatrixIndex = dbConfig.getCreateMatrixIndexes();
for (String i : createMatrixIndex) {
i = i.replaceAll("__LANG__", langCode);
stmt = conn.prepareCall(i);
stmt.execute();
stmt.close();
}
langCaches.add(lang);
}
}
if (pureText != null && lang != null && content != null) {
sql = dbConfig.getOperateDbSQL("insert-textdata");
stmt = conn.prepareCall(sql);
int i = 1;
stmt.setString(i++, type);
stmt.setInt(i++, groupId);
stmt.setInt(i++, Integer.parseInt(hash));
stmt.setString(i++, pureText);
stmt.setString(i++, content);
stmt.setString(i++, lang);
stmt.setString(i++, preContext);
stmt.setString(i++, nextContext);
stmt.registerOutParameter(i, Types.VARCHAR);
stmt.execute();
textDataId = stmt.getString(i);
stmt.close();
int[] ngrams = generateNgrams(lang, pureText);
if (ngrams.length > 0) {
String insertMatrix = dbConfig.getMatrixSQL("insert");
insertMatrix = insertMatrix.replaceAll("__LANG__", langCode);
stmt = conn.prepareCall(insertMatrix);
for (int j = 0; j < ngrams.length; j++) {
stmt.setInt(1, Integer.parseInt(textDataId));
stmt.setInt(2, ngrams[j]);
stmt.setShort(3, (short) ngrams.length);
stmt.addBatch();
}
stmt.executeBatch();
stmt.close();
}
}
} finally {
if (stmt != null) {
stmt.close();
}
}
return textDataId;
}
/**
* 将数据插入TMXPROPS表
* @param params
* ;
* @throws SQLException
*/
public void insertTMXProp(Map<String, String> params) throws SQLException {
OraclePreparedStatement stmt = null;
try {
String sql = dbConfig.getOperateDbSQL("insert-tmxprops");
stmt = (OraclePreparedStatement) conn.prepareStatement(sql);
int i = 1;
stmt.setString(i++, params.get("PARENTNAME"));
stmt.setInt(i++, Integer.parseInt(params.get("PARENTID")));
stmt.setString(i++, params.get("TYPE"));
stmt.setString(i++, params.get("LANG"));
stmt.setString(i++, params.get("ENCODING"));
stmt.setStringForClob(i++, params.get("CONTENT"));
stmt.executeUpdate();
} finally {
if (stmt != null) {
stmt.close();
}
}
}
/**
* 将数据插入TMXNOTES表
* @param params
* ;
* @throws SQLException
*/
public void insertTMXNote(Hashtable<String, String> params) throws SQLException {
PreparedStatement stmt = null;
try {
String sql = dbConfig.getOperateDbSQL("insert-tmxnotes");
stmt = conn.prepareStatement(sql);
int i = 1;
stmt.setString(i++, params.get("PARENTNAME"));
stmt.setInt(i++, Integer.parseInt(params.get("PARENTID")));
stmt.setString(i++, params.get("CONTENT"));
stmt.setString(i++, params.get("CREATIONID"));
stmt.setString(i++, params.get("CREATIONDATE"));
stmt.setString(i++, params.get("CHANGEID"));
stmt.setString(i++, params.get("CHANGEDATE"));
stmt.setString(i++, params.get("ENCODING"));
stmt.setString(i++, params.get("LANG"));
stmt.executeUpdate();
} finally {
if (stmt != null) {
stmt.close();
}
}
}
/**
* 将数据写入到Extra表中
* @param type
* @param eleName
* @param eleContent
* @param pName
* @param pId
* @throws SQLException
* ;
*/
public void insertTMXExtra(String type, String eleName, String eleContent, String pName, String pId)
throws SQLException {
PreparedStatement stmt = null;
try {
String sql = dbConfig.getOperateDbSQL("insert-tmxextra");
stmt = conn.prepareStatement(sql);
int i = 1;
stmt.setString(i++, pName);
stmt.setInt(i++, Integer.parseInt(pId));
stmt.setString(i++, type);
stmt.setString(i++, eleName);
stmt.setString(i++, eleContent);
stmt.executeUpdate();
} finally {
if (stmt != null) {
stmt.close();
}
}
}
// TODO =========================TMX部分(结束)=========================
// TODO ================tbx(开始)==================
/**
* 写MartifHeader节点内容
* @param hContent
* 整个节点的内容
* @param hIdAttr
* MartifHeader节点的ID属性;
* @return
* @throws SQLException
*/
public int insertBMartifHeader(String hContent, String hIdAttr) throws SQLException {
CallableStatement stmt = null;
try {
String sql = dbConfig.getOperateDbSQL("insert-bmartifheader");
stmt = conn.prepareCall(sql);
stmt.setString(1, hIdAttr);
stmt.setString(2, hContent);
stmt.registerOutParameter(3, Types.INTEGER);
stmt.execute();
return stmt.getInt(3);
} finally {
if (stmt != null) {
stmt.close();
}
}
}
/**
* 写BAttribute的内容
* @param attrs
* @param parentName
* @param parentId
* @throws SQLException
* ;
*/
public void insertBAttribute(Map<String, String> attrs, String parentName, int parentId) throws SQLException {
if (attrs != null) {
PreparedStatement stmt = null;
String sql = dbConfig.getOperateDbSQL("insert-battribute");
Iterator<Entry<String, String>> iter = attrs.entrySet().iterator();
try {
while (iter.hasNext()) {
Entry<String, String> entry = iter.next();
String attrName = entry.getKey();
String attrValue = entry.getValue();
stmt = conn.prepareStatement(sql);
stmt.setInt(1, parentId);
stmt.setString(2, attrName);
stmt.setString(3, attrValue);
stmt.setString(4, parentName);
stmt.addBatch();
}
stmt.executeBatch();
stmt.clearBatch();
} finally {
if (stmt != null) {
stmt.close();
}
}
}
}
/**
* 写BRefObjectList内容
* @param roblContent
* @param roblIdAttr
* @param headerId
* @return
* @throws SQLException
* ;
*/
public int insertBRefobjectlist(String roblContent, String roblIdAttr, int headerId) throws SQLException {
PreparedStatement stmt = null;
try {
String sql = dbConfig.getOperateDbSQL("insert-brefobjectlist");
stmt = conn.prepareStatement(sql);
stmt.setInt(1, headerId);
stmt.setString(2, roblIdAttr);
stmt.setString(3, roblContent);
stmt.execute();
} finally {
if (stmt != null) {
stmt.close();
}
}
return 0;
}
/**
* 写TermEntry内容
* @param teContent
* @param teIdAttr
* @param headerId
* @return
* @throws SQLException
* ;
*/
public int insertBTermentry(String teContent, String teIdAttr, int headerId) throws SQLException {
CallableStatement stmt = null;
try {
String sql = dbConfig.getOperateDbSQL("insert-btermentry");
stmt = conn.prepareCall(sql);
stmt.setInt(1, headerId);
stmt.setString(2, teIdAttr);
stmt.setString(3, teContent);
stmt.registerOutParameter(4, Types.INTEGER);
stmt.execute();
return stmt.getInt(4);
} finally {
if (stmt != null) {
stmt.close();
}
}
}
@Override
public void start() throws SQLException, ClassNotFoundException {
String driver = dbConfig.getDriver();
Class.forName(driver);
String url = Utils.replaceParams(dbConfig.getDbURL(), metaData);
Properties prop = Utils.replaceParams(dbConfig.getConfigProperty(), metaData);
conn = DriverManager.getConnection(url, prop);
conn.setAutoCommit(false);
}
/**
* 实现匹配算法,查询matrix_lang表
* @param srcLang
* @param similarity
* @param ngrams
* @return
* @throws SQLException
* ;
*/
private List<String> getCandidatesTextDataPks4Oracle(String srcLang, int similarity, int[] ngrams)
throws SQLException {
List<String> result = new ArrayList<String>();
if (!this.langCaches.contains(srcLang)) {
if (!hasLangInDB(srcLang)) {
return result;
}
langCaches.add(srcLang);
}
int size = ngrams.length;
int min = size * similarity / 100;
int max = size * 100 / similarity;
String set = "" + ngrams[0]; //$NON-NLS-1$
for (int i = 1; i < size; i++) {
set = set + "," + ngrams[i]; //$NON-NLS-1$
}
String select = dbConfig.getMatrixSQL("search");
select = select.replaceAll("__SET__", set); //$NON-NLS-1$
select = select.replaceAll("__LANG__", srcLang.replace("-", "").toUpperCase()); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
PreparedStatement stmt = null;
ResultSet rs = null;
try {
stmt = conn.prepareStatement(select);
stmt.setInt(1, min);
stmt.setInt(2, max);
stmt.setInt(3, min);
stmt.setInt(4, max);
rs = stmt.executeQuery();
while (rs.next()) {
result.add(rs.getString(1));
}
} finally {
if (stmt != null) {
stmt.close();
}
if (rs != null) {
rs.close();
}
}
return result;
}
@Override
public Vector<Hashtable<String, String>> findMatch_1(String puretext, String fullText, String srcLang, String tgtLang,
int minSimilarity, boolean caseSensitive, int matchUpperLimit, int contextSize, String preHash,
String nextHash, boolean isIngoreTarget) throws SQLException {
Vector<Hashtable<String, String>> result = new Vector<Hashtable<String, String>>();
int[] ngrams = generateNgrams(srcLang, puretext);
int size = ngrams.length;
if (size == 0) {
return result;
}
// long l1 = System.currentTimeMillis();
List<String> tpkids = getCandidatesTextDataPks4Oracle(srcLang, minSimilarity, ngrams);
// System.out.println("查MATEX_LANG表:" + (System.currentTimeMillis() - l1));
// long l = System.currentTimeMillis();
// 过虑拆分条件,解决Oracle中where xx in (参数) 参数不越过1000个
StringBuffer bf = new StringBuffer();
List<String> tmpTpkids = new ArrayList<String>();
for (int i = 0; i < tpkids.size(); i++) {
String tpkid = tpkids.get(i);
bf.append(",");
bf.append(tpkid);
if ((i + 1) % 100 == 0) {
tmpTpkids.add(bf.toString().substring(1));
bf = new StringBuffer();
}
}
if (bf.toString().equals("")) {
return result;
}
tmpTpkids.add(bf.toString().substring(1));
bf = new StringBuffer();
bf.append("TPKID IN (" + tmpTpkids.get(0) + ")");
for (int i = 1; i < tmpTpkids.size(); i++) {
bf.append(" OR TPKID IN (" + tmpTpkids.get(i) + ")");
}
String textDataSql = dbConfig.getOperateDbSQL("getTMMatch1");
textDataSql = textDataSql.replace("__WHERE__", bf.toString());
PreparedStatement stmt = conn.prepareStatement(textDataSql);
stmt.setString(1, srcLang);
stmt.setString(2, tgtLang);
ResultSet rs = stmt.executeQuery();
Map<Integer, Map<String, String>> tuSrc = new HashMap<Integer, Map<String, String>>();
Map<Integer, Map<String, String>> tuTgt = new HashMap<Integer, Map<String, String>>();
while (rs.next()) {
Integer groupId = rs.getInt("GROUPID");
String lang = rs.getString("LANG");
String pureText = rs.getString("PURE");
String content = rs.getString("CONTENT");
String creationId = rs.getString("CREATIONID");
creationId = creationId == null ? "" : creationId;
String creationDate = "";
Timestamp tempCdate = rs.getTimestamp("CREATIONDATE");
if (tempCdate != null) {
creationDate = DateUtils.formatToUTC(tempCdate.getTime());
}
String changeDate = "";
Timestamp tempChangeDate = rs.getTimestamp("CHANGEDATE");
if (tempChangeDate != null) {
changeDate = DateUtils.formatToUTC(tempChangeDate.getTime());
}
String changeid = rs.getString("CHANGEID");
changeid = changeid == null ? "" : changeid;
String projectRef = rs.getString("PROJECTREF");
projectRef = projectRef == null ? "" : projectRef;
String jobRef = rs.getString("JOBREF");
jobRef = jobRef == null ? "" : jobRef;
String client = rs.getString("CLIENT");
client = client == null ? "" : client;
if (lang.equalsIgnoreCase(srcLang)) {
int distance;
if (caseSensitive) {
if(isIngoreTarget){
distance = similarity(puretext, pureText);
}else {
distance = similarity(fullText, content);
}
} else {
if(isIngoreTarget){
distance = similarity(puretext.toLowerCase(), pureText.toLowerCase());
}else {
distance = similarity(fullText.toLowerCase(), content.toLowerCase());
}
}
if (distance == 100 && CommonFunction.checkEdition("U")) {
String preContext = rs.getString("PRECONTEXT");
preContext = preContext == null ? "" : preContext;
String nextContext = rs.getString("NEXTCONTEXT");
nextContext = nextContext == null ? "" : nextContext;
if (preContext != null && nextContext != null) {
String[] preContexts = preContext.split(",");
String[] nextContexts = nextContext.split(",");
if (preContexts.length > contextSize) {
preContext = ""; //$NON-NLS-1$
for (int i = 0; i < contextSize; i++) {
preContext += "," + preContexts[i]; //$NON-NLS-1$
}
if (!"".equals(preContext)) { //$NON-NLS-1$
preContext = preContext.substring(1);
}
}
if (nextContexts.length > contextSize) {
nextContext = ""; //$NON-NLS-1$
for (int i = 0; i < contextSize; i++) {
nextContext += "," + nextContexts[i]; //$NON-NLS-1$
}
if (!"".equals(nextContext)) { //$NON-NLS-1$
nextContext = nextContext.substring(1);
}
}
if (preHash.equals(preContext) && nextHash.equals(nextContext)) {
distance = 101;
}
}
}
if (distance >= minSimilarity) {
Map<String, String> srcMap = new HashMap<String, String>();
srcMap.put("srcLang", lang);
srcMap.put("srcText", pureText);
srcMap.put("srcContent", content);
srcMap.put("srcCreationId", creationId);
srcMap.put("srcCreationDate", creationDate);
srcMap.put("srcChangeId", changeid);
srcMap.put("srcChangeDate", changeDate);
srcMap.put("srcProjectRef", projectRef);
srcMap.put("srcJobRef", jobRef);
srcMap.put("srcClient", client);
srcMap.put("similarity", distance + "");
tuSrc.put(groupId, srcMap);
}
}
if (lang.equalsIgnoreCase(tgtLang)) {
Map<String, String> tgtMap = new HashMap<String, String>();
tgtMap.put("tgtLang", lang);
tgtMap.put("tgtText", pureText);
tgtMap.put("tgtContent", content);
tgtMap.put("tgtCreationId", creationId);
tgtMap.put("tgtCreationDate", creationDate);
tgtMap.put("tgtChangeId", changeid);
tgtMap.put("tgtChangeDate", changeDate);
tgtMap.put("tgtProjectRef", projectRef);
tgtMap.put("tgtJobRef", jobRef);
tgtMap.put("tgtClient", client);
tuTgt.put(groupId, tgtMap);
}
}
stmt.close();
String dbName = getMetaData().getDatabaseName();
if (tuSrc.size() > 0) {
Iterator<Entry<Integer, Map<String, String>>> itr = tuSrc.entrySet().iterator();
while (itr.hasNext()) {
Entry<Integer, Map<String, String>> entry = itr.next();
Integer key = entry.getKey();
Map<String, String> srcMap = entry.getValue();
Map<String, String> tgtMap = tuTgt.get(key);
if (tgtMap == null) {
continue;
}
Hashtable<String, String> tu = new Hashtable<String, String>();
tu.putAll(srcMap);
tu.putAll(tgtMap);
tu.put("dbName", dbName); // 应用于origin属性
result.add(tu);
}
}
int resultSize = result.size();
if (resultSize > 1) {
Collections.sort(result, new FindMatchComparator());
}
while (resultSize > matchUpperLimit) {
resultSize--;
result.remove(resultSize);
}
// System.out.println(bf.toString());
return result;
}
@Override
public void fuzzySearch(String pureText, String fullText, String srcLang, String tgtLang, int minSimilarity,
boolean caseSensitive, int matchUpperLimit, int contextSize, String preHash, String nextHash,
boolean isIngoreTarget, FuzzySearchResults searchResults, int tagPelanty) throws SQLException {
int[] ngrams = generateNgrams(srcLang, pureText);
int size = ngrams.length;
if (size == 0) {
return;
}
List<String> tpkids = getCandidatesTextDataPks4Oracle(srcLang, minSimilarity, ngrams);
// 过虑拆分条件,解决Oracle中where xx in (参数) 参数不越过1000个
StringBuffer bf = new StringBuffer();
List<String> tmpTpkids = new ArrayList<String>();
for (int i = 0; i < tpkids.size(); i++) {
String tpkid = tpkids.get(i);
bf.append(",");
bf.append(tpkid);
if ((i + 1) % 100 == 0) {
tmpTpkids.add(bf.toString().substring(1));
bf = new StringBuffer();
}
}
if (bf.toString().equals("")) {
return;
}
tmpTpkids.add(bf.toString().substring(1));
bf = new StringBuffer();
bf.append("TPKID IN (" + tmpTpkids.get(0) + ")");
for (int i = 1; i < tmpTpkids.size(); i++) {
bf.append(" OR TPKID IN (" + tmpTpkids.get(i) + ")");
}
String tag = TranslationMemoryTools.getInnerTagContent(fullText);
String textDataSql = dbConfig.getOperateDbSQL("fuzzySearch");
textDataSql = textDataSql.replace("__WHERE__", bf.toString());
Statement stm = null;
ResultSet rs = null;
Statement tmpStm = null;
try {
stm = conn.createStatement();
tmpStm = conn.createStatement();
rs = stm.executeQuery(textDataSql);
// SELECT TPKID ,GROUPID, PURE, CONTENT, PRECONTEXT, NEXTCONTEXT FROM TEXTDATA WHERE TPKID IN (__SET__)
String targetSql = dbConfig.getOperateDbSQL("fuzzySearch-target").replace("__LANG__", tgtLang);
String dbName = getMetaData().getDatabaseName();
while (rs.next()) {
String _pureText = rs.getString(3);
String _fullText = rs.getString(4);
int similarity = 0;
if (caseSensitive) {
similarity = similarity(pureText, _pureText);
} else {
similarity = similarity(pureText.toLowerCase(), _pureText.toLowerCase());
}
String _tag = TranslationMemoryTools.getInnerTagContent(_fullText);
if (!isIngoreTarget && !tag.equals(_tag)) {
// 标记内容不相等,则执行罚分
similarity -= tagPelanty;
}
if (similarity < minSimilarity) {
continue;
}
int tuId = rs.getInt(2);
String targetSqlTemp = targetSql.replace("__GROUPID__", tuId + "");
// PURE, CONTENT, CREATIONID, CREATIONDATE, CHANGEID, CHANGEDATE ,PROJECTREF
ResultSet rs1 = null;
try {
rs1 = tmpStm.executeQuery(targetSqlTemp);
if (rs1.next()) {
TmxSegement source = new TmxSegement(_pureText, _fullText, srcLang);
source.setDbPk(rs.getInt(1));
_pureText = rs1.getString(2);
_fullText = rs1.getString(3);
if (_pureText == null || _pureText.equals("") || _fullText == null || _fullText.equals("")) {
continue;
}
TmxSegement target = new TmxSegement(_pureText, _fullText, tgtLang);
target.setDbPk(rs1.getInt(1));
TmxTU tu = new TmxTU(source, target);
FuzzySearchResult searchRs = new FuzzySearchResult(tu);
if (searchResults.contains(searchRs)) {
continue;
}
String creationId = rs1.getString(4);
creationId = creationId == null ? "" : creationId;
String creationDate = "";
Timestamp tempCdate = rs1.getTimestamp(5);
if (tempCdate != null) {
creationDate = DateUtils.formatToUTC(tempCdate.getTime());
}
String changeid = rs1.getString(6);
changeid = changeid == null ? "" : changeid;
String changeDate = "";
Timestamp tempChangeDate = rs1.getTimestamp(7);
if (tempChangeDate != null) {
changeDate = DateUtils.formatToUTC(tempChangeDate.getTime());
}
String projectRef = rs1.getString(8);
projectRef = projectRef == null ? "" : projectRef;
tu.setCreationDate(creationDate);
tu.setCreationUser(creationId);
tu.setChangeDate(changeDate);
tu.setChangeUser(changeid);
List<TmxProp> attrs = getTuMprops(tuId, "TU");
tu.setProps(attrs);
String preContext = rs.getString(5);
String nextContext = rs.getString(6);
tu.appendContext(TmxContexts.PRE_CONTEXT_NAME, preContext);
tu.appendContext(TmxContexts.NEXT_CONTEXT_NAME, nextContext);
if (similarity == 100 && CommonFunction.checkEdition("U")) {
preContext = preContext == null ? "" : preContext;
nextContext = nextContext == null ? "" : nextContext;
if (preContext != null && nextContext != null) {
String[] preContexts = preContext.split(",");
String[] nextContexts = nextContext.split(",");
if (preContexts.length > contextSize) {
preContext = ""; //$NON-NLS-1$
for (int i = 0; i < contextSize; i++) {
preContext += "," + preContexts[i]; //$NON-NLS-1$
}
if (!"".equals(preContext)) { //$NON-NLS-1$
preContext = preContext.substring(1);
}
}
if (nextContexts.length > contextSize) {
nextContext = ""; //$NON-NLS-1$
for (int i = 0; i < contextSize; i++) {
nextContext += "," + nextContexts[i]; //$NON-NLS-1$
}
if (!"".equals(nextContext)) { //$NON-NLS-1$
nextContext = nextContext.substring(1);
}
}
if (preHash.equals(preContext) && nextHash.equals(nextContext)) {
similarity = 101;
}
}
}
searchRs.setDbName(dbName);
searchRs.setSimilarity(similarity);
searchRs.setDbOp(this);
searchRs.getTu().setTmId(tuId);
searchResults.add(searchRs);
}
} finally {
if (rs1 != null) {
rs1.close();
}
}
}
} finally {
if (rs != null) {
rs.close();
}
if (stm != null) {
stm.close();
}
if (tmpStm != null){
tmpStm.close();
}
}
}
@Override
public void translationUnitAnalysis(String pureText, String fullText, String srcLang, String tgtLang,
int minSimilarity, boolean caseSensitive, int matchUpperLimit, int contextSize, String preHash,
String nextHash, boolean isIngoreTarget, TranslationUnitAnalysisResults analysisResults, int tagPelanty)
throws SQLException {
int[] ngrams = generateNgrams(srcLang, pureText);
int size = ngrams.length;
if (size == 0) {
return;
}
List<String> tpkids = getCandidatesTextDataPks4Oracle(srcLang, minSimilarity, ngrams);
// 过虑拆分条件,解决Oracle中where xx in (参数) 参数不越过1000个
StringBuffer bf = new StringBuffer();
List<String> tmpTpkids = new ArrayList<String>();
for (int i = 0; i < tpkids.size(); i++) {
String tpkid = tpkids.get(i);
bf.append(",");
bf.append(tpkid);
if ((i + 1) % 100 == 0) {
tmpTpkids.add(bf.toString().substring(1));
bf = new StringBuffer();
}
}
if (bf.toString().equals("")) {
return;
}
tmpTpkids.add(bf.toString().substring(1));
bf = new StringBuffer();
bf.append("A.TPKID IN (" + tmpTpkids.get(0) + ")");
for (int i = 1; i < tmpTpkids.size(); i++) {
bf.append(" OR A.TPKID IN (" + tmpTpkids.get(i) + ")");
}
String tag = TranslationMemoryTools.getInnerTagContent(fullText);
String textDataSql = dbConfig.getOperateDbSQL("fuzzySearch-wordsFA");
textDataSql = textDataSql.replace("__WHERE__", bf.toString());
textDataSql = textDataSql.replace("__TARGETLANG__", tgtLang);
Statement stm = null;
ResultSet rs = null;
Statement tmpStm = null;
try {
stm = conn.createStatement();
tmpStm = conn.createStatement();
rs = stm.executeQuery(textDataSql);
// SELECT GROUPID, PURE, CONTENT, PRECONTEXT, NEXTCONTEXT FROM TEXTDATA WHERE TPKID IN (__SET__)
String dbName = getMetaData().getDatabaseName();
while (rs.next()) {
String _pureText = rs.getString(3);
String _fullText = rs.getString(4);
int similarity = 0;
if (caseSensitive) {
similarity = similarity(pureText, _pureText);
} else {
similarity = similarity(pureText.toLowerCase(), _pureText.toLowerCase());
}
String _tag = TranslationMemoryTools.getInnerTagContent(_fullText);
if (!isIngoreTarget && !tag.equals(_tag)) {
// 标记内容不相等,则执行罚分
similarity -= tagPelanty;
}
if (similarity < minSimilarity) {
continue;
}
if (similarity == 100 && CommonFunction.checkEdition("U")) {
String preContext = rs.getString(5);
String nextContext = rs.getString(6);
preContext = preContext == null ? "" : preContext;
nextContext = nextContext == null ? "" : nextContext;
if (preContext != null && nextContext != null) {
String[] preContexts = preContext.split(",");
String[] nextContexts = nextContext.split(",");
if (preContexts.length > contextSize) {
preContext = ""; //$NON-NLS-1$
for (int i = 0; i < contextSize; i++) {
preContext += "," + preContexts[i]; //$NON-NLS-1$
}
if (!"".equals(preContext)) { //$NON-NLS-1$
preContext = preContext.substring(1);
}
}
if (nextContexts.length > contextSize) {
nextContext = ""; //$NON-NLS-1$
for (int i = 0; i < contextSize; i++) {
nextContext += "," + nextContexts[i]; //$NON-NLS-1$
}
if (!"".equals(nextContext)) { //$NON-NLS-1$
nextContext = nextContext.substring(1);
}
}
if (preHash.equals(preContext) && nextHash.equals(nextContext)) {
similarity = 101;
}
}
}
TranslationUnitAnalysisResult r = new TranslationUnitAnalysisResult(similarity, dbName);
analysisResults.add(r);
}
} finally {
if (rs != null) {
rs.close();
}
if (stm != null) {
stm.close();
}
if (tmpStm != null){
tmpStm.close();
}
}
}
@Override
public String generationExportTMXFilter(String tableName, ExportFilterBean filterBean) {
String connector = filterBean.getFilterConnector();
List<ExportFilterComponentBean> filterOption = filterBean.getFilterOption();
Map<String, Character> tuMatch = Utils.getFilterMatchMTU("MTU");
Map<String, Character> mNoteDateMatch = Utils.getFilterMatchMTU("MNOTE");
Map<String, Character> textDateMatch = Utils.getFilterMatchMTU("TEXTDATA");
StringBuffer bf = new StringBuffer();
for (int i = 0; i < filterOption.size(); i++) {
ExportFilterComponentBean bean = filterOption.get(i);
Character fieldType = null;
String field = bean.getMatchDbField();
String op = bean.getExpressionMatchDb();
String value = bean.getFilterVlaue();
if ("MTU".equals(tableName)) { // 添加 "A.","B.","C."请参考查询SQL
fieldType = tuMatch.get(field);
field = "A." + field;
} else if ("MNOTE".equals(tableName)) {
fieldType = mNoteDateMatch.get(field);
field = "B." + field;
} else if ("TEXTDATA".equals(tableName)) {
fieldType = textDateMatch.get(field);
field = "C." + field;
}
if (fieldType == null) {
continue;
}
bf.append(field);
bf.append(" " + op + " ");
switch (fieldType) {
case '1': // 文本内容,包含/不包含内容
if (op.equals("like") || op.equals("not like")) {
bf.append(" '%" + value + "%' ");
} else {
bf.append("' " + value + "' ");
}
bf.append(connector + " ");
break;
case '2': // 日期类型
bf.append(" to_date('" + value + "','yyyy-mm-dd hh24:mi:ss') ");
bf.append(connector + " ");
break;
default:
return "";
}
}
String result = bf.toString();
if (result.equals("")) {
return result;
}
return result.substring(0, result.lastIndexOf(connector));
}
/**
* (non-Javadoc)
* @see net.heartsome.cat.database.DBOperator#replaceTMOrTBConditionSql(java.lang.String, java.lang.String, boolean,
* boolean, boolean, java.lang.String, java.lang.String[])
*/
public String replaceTMOrTBConditionSql(String sql, String strSearch, boolean isCaseSensitive,
boolean isApplyRegular, boolean isIgnoreMark, String srcLang, String[] arrFilter) {
strSearch = strSearch == null ? "" : strSearch;
StringBuffer strCondition = new StringBuffer();
if (srcLang != null) {
strCondition.append(" AND A.LANG='" + srcLang + "'");
} else {
return null;
}
if (isApplyRegular) {
// ‘c’ 说明在进行匹配时区分大小写(缺省值);
// 'i' 说明在进行匹配时不区分大小写;
strCondition.append(" AND REGEXP_LIKE(" + (isIgnoreMark ? "A.PURE" : "A.CONTENT") + ",'"
+ TextUtil.replaceRegextSqlWithMOP(strSearch) + "','" + (isCaseSensitive ? "c" : "i") + "')");
} else if (isCaseSensitive) {
strCondition.append(" AND " + (isIgnoreMark ? "A.PURE" : "A.CONTENT") + " LIKE '%"
+ TextUtil.cleanStringByLikeWithOracle(strSearch) + "%' escape '\\\\'");
} else {
// Oracle 默认区分大小写,使用 upper 函数将其转换成大写查询
strCondition.append(" AND upper(" + (isIgnoreMark ? "A.PURE" : "A.CONTENT") + ") LIKE '%"
+ TextUtil.cleanStringByLikeWithOracle(strSearch).toUpperCase() + "%' escape '\\\\'");
}
if (arrFilter != null) {
StringBuffer strFilter = new StringBuffer(arrFilter[1] + " '%"
+ TextUtil.cleanStringByLikeWithOracle(arrFilter[2]).toUpperCase() + "%' escape '\\\\'");
// 过滤条件要加在源语言中
if (arrFilter[0].equalsIgnoreCase(srcLang)) {
sql = Utils.replaceString(sql, "__TABLE_TEXTDATA__", "");
strFilter.insert(0, " AND upper(A.PURE) ");
strCondition.append(strFilter.toString());
} else {
sql = Utils.replaceString(sql, "__TABLE_TEXTDATA__", " ," + getMetaData().getDatabaseName()
+ "_TEXTDATA B ");
strCondition.append(" AND A.GROUPID=B.GROUPID AND B.TYPE='M' AND B.LANG='" + arrFilter[0] + "'");
strFilter.insert(0, " AND upper(B.PURE) ");
strCondition.append(strFilter.toString());
}
} else {
sql = Utils.replaceString(sql, "__TABLE_TEXTDATA__", "");
}
sql = Utils.replaceString(sql, "__CONDITION__", strCondition.toString());
return sql;
}
}
| 39,895 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
MetaDataImpl.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/database/net.heartsome.cat.database.oracle/src/net/heartsome/cat/database/oracle/MetaDataImpl.java | package net.heartsome.cat.database.oracle;
import net.heartsome.cat.common.bean.MetaData;
public class MetaDataImpl extends MetaData{
@Override
public boolean dataPathSupported() {
return false;
}
}
| 209 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
OperateDBImpl.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/database/net.heartsome.cat.database.oracle/src/net/heartsome/cat/database/oracle/OperateDBImpl.java | package net.heartsome.cat.database.oracle;
import java.net.URL;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import net.heartsome.cat.common.bean.MetaData;
import net.heartsome.cat.database.Constants;
import net.heartsome.cat.database.DBConfig;
import net.heartsome.cat.database.SystemDBOperator;
import net.heartsome.cat.database.Utils;
import net.heartsome.cat.database.oracle.resource.Messages;
import org.eclipse.core.runtime.Platform;
import org.osgi.framework.Bundle;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class OperateDBImpl extends SystemDBOperator {
private Logger logger = LoggerFactory.getLogger(this.getClass());
public OperateDBImpl() {
metaData = new MetaDataImpl();
Bundle buddle = Platform.getBundle(Activator.PLUGIN_ID);
URL fileUrl = buddle.getEntry(Constants.DBCONFIG_PATH);
dbConfig = new DBConfig(fileUrl);
metaData.setServerName(dbConfig.getDefaultServer());
metaData.setPort(dbConfig.getDefaultPort());
metaData.setDbType(dbConfig.getDefaultType());
}
/**
* 检查系统库是否已经创建
* @return true 已创建, false 没有创建
*/
@Override
public boolean checkSysDb() {
MetaData data = null;
try {
data = (MetaData) metaData.clone();
data.setDatabaseName(Constants.HSSYSDB);
} catch (CloneNotSupportedException e) {
logger.warn("", e);
return false;
}
Connection conn = null;
Statement stmt = null;
String driver = dbConfig.getDriver();
String url = Utils.replaceParams(dbConfig.getDbURL(), data);
Properties prop = Utils.replaceParams(dbConfig.getConfigProperty(), data);
try {
conn = getConnection(driver, url, prop);
stmt = conn.createStatement();
stmt.execute("SELECT DBNAME, QUALITY, USERS FROM HSCATSYSDB");
} catch (ClassNotFoundException e) {
logger.warn(Messages.getString("oracle.OperateDBImpl.logger1"), e);
return false;
} catch (SQLException e) {
return false;
} finally {
freeConnection(stmt, conn);
}
return true;
}
@Override
public int createDB() throws SQLException {
dbConfig.setMetaData(metaData);
List<String> createTables = dbConfig.getCreateTables();
createTables.addAll(dbConfig.getCreateIndexs());
return benchOperate(createTables);
}
/**
* 创建系统库
* @return
* @throws SQLException
*/
public int createSysDb() throws SQLException {
List<String> createTables = dbConfig.getCreateSysTables();
return benchOperate(createTables);
}
private int benchOperate(List<String> createTables) {
Connection conn = null;
Statement stmt = null;
String driver = dbConfig.getDriver();
String url = Utils.replaceParams(dbConfig.getDbURL(),metaData);
Properties prop = Utils.replaceParams(dbConfig.getConfigProperty(), metaData);
try {
conn = getConnection(driver, url, prop);
conn.setAutoCommit(false);
stmt = conn.createStatement();
if (createTables != null) {
for (String i : createTables) {
stmt.execute(i);
}
}
conn.commit();
} catch (ClassNotFoundException e) {
return Constants.FAILURE;
} catch (SQLException e) {
try {
if (conn != null && !conn.isClosed()) {
conn.rollback();
}
} catch (SQLException e1) {
logger.warn("", e1);
}
e.printStackTrace();
} finally {
freeConnection(stmt, conn);
}
return Constants.SUCCESS;
}
@Override
public void dropDb(String dbName) throws SQLException {
ArrayList<String> dropSql = new ArrayList<String>();
dropSql.add(dbConfig.getOperateDbSQL("drop-1").replace("__DATABASE_NAME__", dbName));
dropSql.add(dbConfig.getOperateDbSQL("drop-2").replace("__DATABASE_NAME__", dbName));
dropSql.add(dbConfig.getOperateDbSQL("drop-3").replace("__DATABASE_NAME__", dbName));
dropSql.add(dbConfig.getOperateDbSQL("drop-4").replace("__DATABASE_NAME__", dbName));
dropSql.add(dbConfig.getOperateDbSQL("drop-5").replace("__DATABASE_NAME__", dbName));
dropSql.add(dbConfig.getOperateDbSQL("drop-6").replace("__DATABASE_NAME__", dbName));
dropSql.add(dbConfig.getOperateDbSQL("drop-7").replace("__DATABASE_NAME__", dbName));
dropSql.add(dbConfig.getOperateDbSQL("drop-8").replace("__DATABASE_NAME__", dbName));
dropSql.add(dbConfig.getOperateDbSQL("drop-9").replace("__DATABASE_NAME__", dbName));
dropSql.add(dbConfig.getOperateDbSQL("drop-10").replace("__DATABASE_NAME__", dbName));
dropSql.add(dbConfig.getOperateDbSQL("drop-11").replace("__DATABASE_NAME__", dbName));
dropSql.add(dbConfig.getOperateDbSQL("drop-12").replace("__DATABASE_NAME__", dbName));
dropSql.add(dbConfig.getOperateDbSQL("drop-13").replace("__DATABASE_NAME__", dbName));
dropSql.add(dbConfig.getOperateDbSQL("drop-14").replace("__DATABASE_NAME__", dbName));
dropSql.addAll(dropMatrixDb(dbName)); //获取删除matrix_lang表的SQL
benchOperate(dropSql);
}
/**
* 删除matrix_lang表
* ;
*/
private List<String> dropMatrixDb(String dbName){
List<String> dropSql = new ArrayList<String>();
String sql = dbConfig.getOperateDbSQL("drop-matrix").replace("__DATABASE_NAME__", dbName);
String getLangSql = dbConfig.getOperateDbSQL("get-langs").replace("__DATABASE_NAME__", dbName);
Connection conn = null;
Statement stmt = null;
String driver = dbConfig.getDriver();
String url = Utils.replaceParams(dbConfig.getDbURL(),metaData);
Properties prop = Utils.replaceParams(dbConfig.getConfigProperty(), metaData);
try {
conn = getConnection(driver, url, prop);
stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(getLangSql);
while(rs.next()){
dropSql.add(sql.replace("__LANG__", Utils.langToCode(rs.getString(1)).toUpperCase()));
}
}catch (Exception e) {
e.printStackTrace();
} finally{
freeConnection(stmt, conn);
}
return dropSql;
}
@Override
protected Connection getConnection(String driver, String url, Properties prop) throws ClassNotFoundException,
SQLException {
Class.forName(driver);
return DriverManager.getConnection(url, prop);
}
@Override
public boolean checkDbExistOnServer() {
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
try {
MetaData data = (MetaData) metaData.clone();
data.setDatabaseName(Constants.HSSYSDB);
String url = Utils.replaceParams(dbConfig.getDbURL(), data);
String driver = dbConfig.getDriver();
Properties prop = Utils.replaceParams(dbConfig.getConfigProperty(), data);
conn = getConnection(driver, url, prop);
String getDbList = "SELECT DBNAME, QUALITY, USERS FROM HSCATSYSDB WHERE DBNAME=?";
stmt = conn.prepareStatement(getDbList);
stmt.setString(1,metaData.getDatabaseName());
rs = stmt.executeQuery();
if(rs.next()){
return true;
}else {
return false;
}
} catch (CloneNotSupportedException e) {
logger.error("", e);
} catch (ClassNotFoundException e) {
logger.error("", e);
} catch (SQLException e) {
logger.error("", e);
} finally {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
logger.warn("", e);
}
}
freeConnection(stmt, conn);
}
return true;
}
}
| 7,270 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
DbServiceProviderImpl.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/database/net.heartsome.cat.database.oracle/src/net/heartsome/cat/database/oracle/DbServiceProviderImpl.java | package net.heartsome.cat.database.oracle;
import net.heartsome.cat.database.DBServiceProvider;
import net.heartsome.cat.database.SystemDBOperator;
import net.heartsome.cat.database.DBOperator;
public class DbServiceProviderImpl implements DBServiceProvider{
public SystemDBOperator getOperateDBInstance() {
return new OperateDBImpl();
}
public DBOperator getTmDatabaseInstance() {
return new TMDatabaseImpl();
}
}
| 428 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
Messages.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/database/net.heartsome.cat.database.oracle/src/net/heartsome/cat/database/oracle/resource/Messages.java | package net.heartsome.cat.database.oracle.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.database.oracle.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 + '!';
}
}
}
| 911 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
TmTransParamsBean.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/database/net.heartsome.cat.database.tm/src/net/heartsome/cat/database/tm/TmTransParamsBean.java | /**
* TmTransParamsBean.java
*
* Version information :
*
* Date:2012-4-28
*
* Copyright notice :
* 本文件及其附带的相关文件包含机密信息,仅限瀚特盛科技有限公司指定的,与本项目有关的内部人员和客户联络人员查阅和使用。
* 如果您不是本保密声明中指定的收件者,请立即销毁本文件,禁止对本文件或根据本文件中的内容采取任何其他行动,
* 包括但不限于:泄露本文件中的信息、以任何方式制作本文件全部或部分内容之副本、将本文件或其相关副本提供给任何其他人。
*/
package net.heartsome.cat.database.tm;
import java.beans.PropertyChangeEvent;
import net.heartsome.cat.database.bean.TMPreferenceConstants;
import net.heartsome.cat.database.ui.tm.Activator;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.util.IPropertyChangeListener;
/**
* 记忆库匹配参数
* @author jason
* @version
* @since JDK1.6
*/
public class TmTransParamsBean implements IPropertyChangeListener {
private int maxMatchSize = 0;
private int contextSize = 0;
private int minSimilarity = 0;
private int tagPenalty = 2;
private boolean isCaseSensitive = false;
private boolean isIgnoreTag = false;
private int tmUpdateStrategy = 0;
private IPreferenceStore preferenceStore;
private int matchSortStrategry = 0;
public TmTransParamsBean() {
preferenceStore = Activator.getDefault().getPreferenceStore();
preferenceStore.addPropertyChangeListener(this);
loadPreference();
}
public TmTransParamsBean(int maxMatchSize, boolean isIgnoreTag, int minSimilarity, boolean isCaseSensitive,
int contextSize, int tagPenalty) {
this.maxMatchSize = maxMatchSize;
this.contextSize = contextSize;
this.minSimilarity = minSimilarity;
this.isCaseSensitive = isCaseSensitive;
this.isIgnoreTag = isIgnoreTag;
this.tagPenalty = tagPenalty;
}
public void propertyChange(PropertyChangeEvent event) {
loadPreference();
}
private void loadPreference() {
this.isCaseSensitive = preferenceStore.getBoolean(TMPreferenceConstants.CASE_SENSITIVE);
this.isIgnoreTag = preferenceStore.getBoolean(TMPreferenceConstants.IGNORE_MARK);
this.minSimilarity = preferenceStore.getInt(TMPreferenceConstants.MIN_MATCH);
this.maxMatchSize = preferenceStore.getInt(TMPreferenceConstants.MAX_MATCH_NUMBER);
this.contextSize = preferenceStore.getInt(TMPreferenceConstants.CONTEXT_MATCH);
this.tmUpdateStrategy = preferenceStore.getInt(TMPreferenceConstants.TM_UPDATE);
this.matchSortStrategry = preferenceStore.getInt(TMPreferenceConstants.MATCH_PERCENTAGE_SORT_WITH_EQUAL);
this.tagPenalty = preferenceStore.getInt(TMPreferenceConstants.TAG_PENALTY);
}
/** @return the maxMatchSize */
public int getMaxMatchSize() {
return maxMatchSize;
}
/**
* @param maxMatchSize
* the maxMatchSize to set
*/
public void setMaxMatchSize(int maxMatchSize) {
this.maxMatchSize = maxMatchSize;
}
/** @return the contextSize */
public int getContextSize() {
return contextSize;
}
/**
* @param contextSize
* the contextSize to set
*/
public void setContextSize(int contextSize) {
this.contextSize = contextSize;
}
/** @return the minSimilarity */
public int getMinSimilarity() {
return minSimilarity;
}
/**
* @param minSimilarity
* the minSimilarity to set
*/
public void setMinSimilarity(int minSimilarity) {
this.minSimilarity = minSimilarity;
}
/** @return the isCaseSensitive */
public boolean isCaseSensitive() {
return isCaseSensitive;
}
/**
* @param isCaseSensitive
* the isCaseSensitive to set
*/
public void setCaseSensitive(boolean isCaseSensitive) {
this.isCaseSensitive = isCaseSensitive;
}
/** @return the isIgnoreTaget */
public boolean isIgnoreTag() {
return isIgnoreTag;
}
/**
* @param isIgnoreTaget
* the isIgnoreTaget to set
*/
public void setIgnoreTaget(boolean isIgnoreTaget) {
this.isIgnoreTag = isIgnoreTaget;
}
/** @return the tmUpdateStrategy */
public int getTmUpdateStrategy() {
return tmUpdateStrategy;
}
/**
* @param tmUpdateStrategy
* the tmUpdateStrategy to set
*/
public void setTmUpdateStrategy(int tmUpdateStrategy) {
this.tmUpdateStrategy = tmUpdateStrategy;
}
/**
* @param isIgnoreTag
* the isIgnoreTag to set
*/
public void setIgnoreTag(boolean isIgnoreTag) {
this.isIgnoreTag = isIgnoreTag;
}
public void propertyChange(org.eclipse.jface.util.PropertyChangeEvent event) {
loadPreference();
}
/** @return the matchSortStrategry */
public int getMatchSortStrategry() {
return matchSortStrategry;
}
/** @return the tagPenalty */
public int getTagPenalty() {
return tagPenalty;
}
/**
* @param tagPelanty
* the tagPenalty to set
*/
public void setTagPenalty(int tagPelanty) {
this.tagPenalty = tagPelanty;
}
/**
* @param matchSortStrategry
* the matchSortStrategry to set
*/
public void setMatchSortStrategry(int matchSortStrategry) {
this.matchSortStrategry = matchSortStrategry;
}
public void clearResources() {
if (preferenceStore != null) {
this.preferenceStore.removePropertyChangeListener(this);
}
}
}
| 5,278 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
TmDbOperatorManager.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/database/net.heartsome.cat.database.tm/src/net/heartsome/cat/database/tm/TmDbOperatorManager.java | /**
* DbConnectionManager.java
*
* Version information :
*
* Date:2012-4-26
*
* Copyright notice :
* 本文件及其附带的相关文件包含机密信息,仅限瀚特盛科技有限公司指定的,与本项目有关的内部人员和客户联络人员查阅和使用。
* 如果您不是本保密声明中指定的收件者,请立即销毁本文件,禁止对本文件或根据本文件中的内容采取任何其他行动,
* 包括但不限于:泄露本文件中的信息、以任何方式制作本文件全部或部分内容之副本、将本文件或其相关副本提供给任何其他人。
*/
package net.heartsome.cat.database.tm;
import java.sql.SQLException;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;
import net.heartsome.cat.common.bean.DatabaseModelBean;
import net.heartsome.cat.database.DBOperator;
import net.heartsome.cat.database.service.DatabaseService;
import net.heartsome.cat.database.tm.resource.Messages;
import net.heartsome.cat.ts.core.IProjectConfigChangedListener;
import net.heartsome.cat.ts.core.file.ProjectConfiger;
import net.heartsome.cat.ts.core.file.ProjectConfigerFactory;
import org.eclipse.core.resources.IProject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* 数据库连接管理器
* @author jason
* @version
* @since JDK1.6
*/
public class TmDbOperatorManager implements IProjectConfigChangedListener {
public final static Logger logger = LoggerFactory.getLogger(TmDbOperatorManager.class);
private IProject currentProj;
private ProjectConfiger projConfiger;
private List<DBOperator> dbOpList;
/** 默认记忆库名称,匹配排序时需要使用 */
private String defaultDbInfo;
public TmDbOperatorManager() {
dbOpList = new ArrayList<DBOperator>();
}
/**
* 设置项目信息
* @param project
* ;
*/
public void setProject(IProject project) {
if (currentProj == null) {
currentProj = project;
} else if (project != null && !project.getName().equals(currentProj.getName())) {
currentProj = project;
} else {
return;
}
if (currentProj != null) {
projConfiger = ProjectConfigerFactory.getProjectConfiger(currentProj);
projConfiger.addChangeListener(this);
loadTmDbConn();
}
}
public IProject getProject() {
return currentProj;
}
public void handProjectConfigChangedEvent() {
loadTmDbConn();
}
/**
* 加载连接 ;
*/
private void loadTmDbConn() {
releaseTmDbConn(); // 加载连接前先释放已经存在连接
if (projConfiger != null) {
List<DatabaseModelBean> tmDbConfigList = projConfiger.getAllTmDbs();
for (int i = 0; i < tmDbConfigList.size(); i++) {
DatabaseModelBean dmb = tmDbConfigList.get(i);
DBOperator db = DatabaseService.getDBOperator(dmb.toDbMetaData());
if(null == db){
continue;
}
try {
db.start();
if (dmb.isDefault()) {
defaultDbInfo = dmb.getDbName();
this.dbOpList.add(0, db);
} else {
this.dbOpList.add(db);
}
} catch (Exception e) {
logger.error(MessageFormat.format(Messages.getString("tm.TmDbOperatorManager.logger1"),
dmb.getDbType(), dmb.getDbName()), e);
}
}
}
}
/**
* 释放连接 ;
*/
private void releaseTmDbConn() {
for (DBOperator dbop : dbOpList) {
try {
if (dbop != null) {
dbop.end();
}
} catch (SQLException e) {
logger.error(Messages.getString("tm.TmDbOperatorManager.logger2")
+ dbop.getMetaData().getDatabaseName(), e);
continue; // 继续释放其他数据库资源
}
}
dbOpList.clear();
defaultDbInfo = null;
}
public List<DBOperator> getDbOperatorList() {
return this.dbOpList;
}
/**
* 释放资源 ;
*/
public void clearResources() {
releaseTmDbConn();
currentProj = null;
defaultDbInfo = null;
if (projConfiger != null) {
projConfiger.removeChangeListener(this);
}
projConfiger = null;
}
/**
* Get default translation memory database name
* @return ;
*/
public String getDefaultDbName() {
return this.defaultDbInfo;
}
}
| 4,085 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
TmMatcher.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/database/net.heartsome.cat.database.tm/src/net/heartsome/cat/database/tm/match/TmMatcher.java | /**
* TmTranslation.java
*
* Version information :
*
* Date:2012-4-28
*
* Copyright notice :
* 本文件及其附带的相关文件包含机密信息,仅限瀚特盛科技有限公司指定的,与本项目有关的内部人员和客户联络人员查阅和使用。
* 如果您不是本保密声明中指定的收件者,请立即销毁本文件,禁止对本文件或根据本文件中的内容采取任何其他行动,
* 包括但不限于:泄露本文件中的信息、以任何方式制作本文件全部或部分内容之副本、将本文件或其相关副本提供给任何其他人。
*/
package net.heartsome.cat.database.tm.match;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Hashtable;
import java.util.List;
import java.util.Vector;
import net.heartsome.cat.common.bean.FuzzySearchResult;
import net.heartsome.cat.common.bean.TmxContexts;
import net.heartsome.cat.common.bean.TmxSegement;
import net.heartsome.cat.common.bean.TranslationUnitAnalysisResult;
import net.heartsome.cat.common.util.DateUtils;
import net.heartsome.cat.database.DBOperator;
import net.heartsome.cat.database.Utils;
import net.heartsome.cat.database.bean.FuzzySearchResults;
import net.heartsome.cat.database.bean.TMPreferenceConstants;
import net.heartsome.cat.database.bean.TranslationUnitAnalysisResults;
import net.heartsome.cat.database.tm.TmDbOperatorManager;
import net.heartsome.cat.database.tm.TmTransParamsBean;
import net.heartsome.cat.database.tm.resource.Messages;
import net.heartsome.cat.ts.tm.match.extension.AbstractTmMatch;
import net.heartsome.cat.ts.tm.match.extension.ITmMatch;
import org.eclipse.core.resources.IProject;
/**
* @author jason
* @version
* @since JDK1.6
*/
public class TmMatcher extends AbstractTmMatch implements ITmMatch {
private TmDbOperatorManager tmDbOperatorManager;
private TmTransParamsBean transParameters;
public TmMatcher() {
transParameters = new TmTransParamsBean();
tmDbOperatorManager = new TmDbOperatorManager();
}
public boolean checkTmMatcher(IProject project) {
this.setProject(project);
if (tmDbOperatorManager.getDbOperatorList().size() == 0) {
return false;
}
return true;
}
/**
* (non-Javadoc)
* @see net.heartsome.cat.ts.ui.translation.ITmMatch.ITmTranslation#setProject(org.eclipse.core.resources.IProject)
*/
public void setProject(IProject project) {
tmDbOperatorManager.setProject(project);
}
/**
* (non-Javadoc)
* @see net.heartsome.cat.ts.ui.translation.ITmMatch.ITmTranslation#getMaxMatchSize()
*/
public int getMaxMatchSize() {
return transParameters.getMaxMatchSize();
}
/** (non-Javadoc)
* @see net.heartsome.cat.ts.tm.match.extension.ITmMatch#getTagPenalty()
*/
public int getTagPenalty() {
return transParameters.getTagPenalty();
}
/**
* (non-Javadoc)
* @see net.heartsome.cat.ts.ui.translation.ITmMatch.ITmTranslation#findMatch()
*/
public Vector<Hashtable<String, String>> findMatch() {
Vector<Hashtable<String, String>> matchsVector = new Vector<Hashtable<String, String>>();
List<DBOperator> dbList = tmDbOperatorManager.getDbOperatorList();
if (dbList.size() == 0) {
return matchsVector;
}
String pureText = tuInfoBean.getSrcPureText();
String fullText = tuInfoBean.getSrcFullText();
String srcLang = Utils.convertLangCode(tuInfoBean.getSrcLanguage());
String tgtLang = Utils.convertLangCode(tuInfoBean.getTgtLangugage());
String preContext = tuInfoBean.getPreContext();
String nextContext = tuInfoBean.getNextContext();
int maxMatchSize = transParameters.getMaxMatchSize();
int contextSize = transParameters.getContextSize();
int minSimilarity = transParameters.getMinSimilarity();
boolean isCaseSensitive = transParameters.isCaseSensitive();
boolean isIgnoreTag = transParameters.isIgnoreTag();
if (pureText == null || pureText.equals("") || srcLang == null || srcLang.equals("") || tgtLang == null
|| tgtLang.equals("")) {
return matchsVector;
}
for (int i = 0; i < dbList.size(); i++) {
try {
matchsVector.addAll(dbList.get(i).findMatch_1(pureText, fullText, srcLang, tgtLang, minSimilarity,
isCaseSensitive, maxMatchSize, contextSize, preContext, nextContext, isIgnoreTag));
} catch (SQLException e) {
logger.error(Messages.getString("match.TmMatcher.logger1"), e);
continue;
}
}
if (matchsVector.size() > 1) {
Collections.sort(matchsVector, new FindMatchComparator());
checkMaxMatchSize(matchsVector);
}
return matchsVector;
}
public List<FuzzySearchResult> fuzzySearch() {
int maxMatchSize = transParameters.getMaxMatchSize();
int contextSize = transParameters.getContextSize();
int minSimilarity = transParameters.getMinSimilarity();
int tagPelanty = transParameters.getTagPenalty();
boolean isCaseSensitive = transParameters.isCaseSensitive();
boolean isIgnoreTag = transParameters.isIgnoreTag();
FuzzySearchResults results = new FuzzySearchResults(tmDbOperatorManager.getDefaultDbName(),
transParameters.getMatchSortStrategry(), maxMatchSize);
List<DBOperator> dbList = tmDbOperatorManager.getDbOperatorList();
if (dbList.size() == 0) {
return results.getSearchResult();
}
String pureText = tuInfoBean.getSrcPureText();
String fullText = tuInfoBean.getSrcFullText();
String srcLang = Utils.convertLangCode(tuInfoBean.getSrcLanguage());
String tgtLang = Utils.convertLangCode(tuInfoBean.getTgtLangugage());
String preContext = tuInfoBean.getPreContext();
String nextContext = tuInfoBean.getNextContext();
if (pureText == null || pureText.equals("") || srcLang == null || srcLang.equals("") || tgtLang == null
|| tgtLang.equals("")) {
return results.getSearchResult();
}
for (int i = 0; i < dbList.size(); i++) {
try {
dbList.get(i).fuzzySearch(pureText, fullText, srcLang, tgtLang, minSimilarity, isCaseSensitive,
maxMatchSize, contextSize, preContext, nextContext, isIgnoreTag, results, tagPelanty);
results.sort();
results.clearResults();
} catch (SQLException e) {
logger.error(Messages.getString("match.TmMatcher.logger1"), e);
continue;
}
}
results.sort();
results.clearResults();
return results.getSearchResult();
}
public List<TranslationUnitAnalysisResult> translationUnitAnalysis() {
int maxMatchSize = transParameters.getMaxMatchSize();
int contextSize = transParameters.getContextSize();
int minSimilarity = transParameters.getMinSimilarity();
int tagPelanty = transParameters.getTagPenalty();
boolean isCaseSensitive = transParameters.isCaseSensitive();
boolean isIgnoreTag = transParameters.isIgnoreTag();
TranslationUnitAnalysisResults results = new TranslationUnitAnalysisResults(
tmDbOperatorManager.getDefaultDbName(), transParameters.getMatchSortStrategry(), maxMatchSize);
List<DBOperator> dbList = tmDbOperatorManager.getDbOperatorList();
if (dbList.size() == 0) {
return results.getAnaylysisResults();
}
String pureText = tuInfoBean.getSrcPureText();
String fullText = tuInfoBean.getSrcFullText();
String srcLang = Utils.convertLangCode(tuInfoBean.getSrcLanguage());
String tgtLang = Utils.convertLangCode(tuInfoBean.getTgtLangugage());
String preContext = tuInfoBean.getPreContext();
String nextContext = tuInfoBean.getNextContext();
if (pureText == null || pureText.equals("") || srcLang == null || srcLang.equals("") || tgtLang == null
|| tgtLang.equals("")) {
return results.getAnaylysisResults();
}
for (int i = 0; i < dbList.size(); i++) {
try {
dbList.get(i).translationUnitAnalysis(pureText, fullText, srcLang, tgtLang, minSimilarity,
isCaseSensitive, maxMatchSize, contextSize, preContext, nextContext, isIgnoreTag, results,
tagPelanty);
results.sort();
results.clearResults();
} catch (SQLException e) {
logger.error(Messages.getString("match.TmMatcher.logger1"), e);
continue;
}
}
results.sort();
results.clearResults();
return results.getAnaylysisResults();
}
/**
* 查找匹配结果排序器, 按匹配率由高到低排序
* @author Jason
* @version
* @since JDK1.6
*/
private final class FindMatchComparator implements Comparator<Hashtable<String, String>> {
private int matchSortStrategry = 0;
public FindMatchComparator() {
matchSortStrategry = transParameters.getMatchSortStrategry();
}
public int compare(Hashtable<String, String> a, Hashtable<String, String> b) {
Integer a1 = Integer.parseInt(a.get("similarity"));
Integer b1 = Integer.parseInt(b.get("similarity"));
if (a1 < b1) {
return 1;
} else if (a1 == b1) {
if (matchSortStrategry == TMPreferenceConstants.DEFAULT_DB_PRECEDENCE) {
// sort by default database
String dbName = b.get("dbName");
if (dbName.equals(tmDbOperatorManager.getDefaultDbName())) {
return -1;
}
} else if (matchSortStrategry == TMPreferenceConstants.DATE_REVERSE_PRECEDENCE) {
// sort by update date
String t1Str = a.get("tgtChangeDate");
String t2Str = b.get("tgtChangeDate");
if (t1Str.length() != 0 && t2Str.length() != 0) {
Timestamp t1 = DateUtils.getTimestampFromUTC(t1Str);
Timestamp t2 = DateUtils.getTimestampFromUTC(t2Str);
return t2.compareTo(t1);
} else if (t1Str.length() == 0 && t2Str.length() != 0) {
return -1;
}
}
return 0;
} else {
return -1;
}
}
}
/**
* 保留最大上限匹配数量
* @param tmpVector
* ;
*/
private void checkMaxMatchSize(List<?> tmpVector) {
int size = tmpVector.size();
while (size > transParameters.getMaxMatchSize()) {
size--;
tmpVector.remove(size);
}
}
public int getContextSize() {
return transParameters.getContextSize();
}
public void clearResource() {
tmDbOperatorManager.clearResources();
transParameters.clearResources();
super.tuInfoBean.resetTuInfo();
}
public void clearDbResource() {
tmDbOperatorManager.clearResources();
}
public void setCustomeMatchParameters(int maxMatchSize, boolean isIgnoreTag, int minSimilarity,
boolean isCaseSensitive, int contextSize, int tagPenalty) {
this.transParameters.clearResources();
this.transParameters = new TmTransParamsBean(maxMatchSize, isIgnoreTag, minSimilarity, isCaseSensitive,
contextSize, tagPenalty);
}
public void setCustomeMatchParameters(int maxMatchSize, int minSimilarity) {
boolean pIsIgnoreTag = this.transParameters.isIgnoreTag();
int pContextSize = this.transParameters.getContextSize();
boolean pIsCaseSensitive = this.transParameters.isCaseSensitive();
int tagPenalty = this.transParameters.getTagPenalty();
this.transParameters.clearResources();
this.transParameters = new TmTransParamsBean(maxMatchSize, pIsIgnoreTag, minSimilarity, pIsCaseSensitive,
pContextSize, tagPenalty);
}
public boolean isIgnoreTag() {
return this.transParameters.isIgnoreTag();
}
public int getMinMatchQuality() {
return this.transParameters.getMinSimilarity();
}
public void deleteFuzzyResult(FuzzySearchResult fr) throws Exception {
Object obj = fr.getDbOp();
if (obj == null) {
throw new Exception(Messages.getString("match.TmMatcher.deleteFuzzyResult.msg1"));
}
DBOperator dbOp = (DBOperator) obj;
boolean needEnd = false;
Statement stmt = null;
ResultSet rs = null;
try {
if (dbOp.isClosed()) {
needEnd = true;
dbOp.start();
}
int tuDbPk = fr.getTu().getTmId();
int srcDbPk = fr.getTu().getSource().getDbPk();
int tgtDbPk = fr.getTu().getTarget().getDbPk();
String sql = "SELECT COUNT(*) FROM TEXTDATA WHERE GROUPID = " + tuDbPk + " AND TYPE = 'M'";
Connection conn = dbOp.getConnection();
if (conn == null || conn.isClosed()) {
throw new Exception(Messages.getString("match.TmMatcher.deleteFuzzyResult.msg2"));
}
stmt = conn.createStatement();
rs = stmt.executeQuery(sql);
int count = 0;
if (rs.next()) {
count = rs.getInt(1);
}
rs.close();
stmt.close();
if (count == 0) {
throw new Exception(Messages.getString("match.TmMatcher.deleteFuzzyResult.msg3"));
} else if (count > 2) {
// 删除对应的语言
dbOp.beginTransaction();
dbOp.deleteAllTuvRelations(Arrays.asList(tgtDbPk), fr.getTu().getTarget().getLangCode());
sql = "UPDATE MTU SET CHANGEID = '" + fr.getTu().getChangeUser() + "', CHANGEDATE = '"
+ DateUtils.getTimestampFromUTC(fr.getTu().getChangeDate()) + "' WHERE MTUPKID = " + tuDbPk;
stmt = conn.createStatement();
stmt.executeUpdate(sql);
dbOp.commit();
} else {
// 删除整个 TU
dbOp.beginTransaction();
stmt = conn.createStatement();
sql = "DELETE FROM MTU WHERE MTUPKID = " + tuDbPk;
stmt.addBatch(sql);
sql = "DELETE FROM MPROP WHERE PARENTNAME = 'TU' AND PARENTID = " + tuDbPk;
stmt.addBatch(sql);
sql = "DELETE FROM MNOTE WHERE PARENTNAME = 'TU' AND PARENTID = " + tuDbPk;
stmt.addBatch(sql);
sql = "DELETE FROM MEXTRA WHERE PARENTNAME = 'TU' AND PARENTID = " + +tuDbPk;
stmt.executeBatch();
dbOp.deleteAllTuvRelations(Arrays.asList(srcDbPk), fr.getTu().getSource().getLangCode());
dbOp.deleteAllTuvRelations(Arrays.asList(tgtDbPk), fr.getTu().getTarget().getLangCode());
dbOp.commit();
}
} catch (Exception e) {
logger.error("delete TM in db error", e);
try {
dbOp.rollBack();
} catch (SQLException e1) {
logger.error("delete tm DB rollback error", e);
}
throw e;
} finally {
if (stmt != null) {
try {
stmt.close();
} catch (SQLException e) {
logger.error("delete TM stmt close error", e);
}
}
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
logger.error("delete TM ResultSet close error", e);
}
}
if (needEnd) {
try {
dbOp.end();
} catch (SQLException e) {
logger.error("delete TM DB close conneciton error", e);
}
}
if (needEnd) {
try {
if (dbOp != null) {
dbOp.end();
}
} catch (SQLException e) {
logger.error("delete TM DB close conneciton error", e);
}
}
}
}
public void updateFuzzyResult(FuzzySearchResult fr) throws Exception {
Object obj = fr.getDbOp();
if (obj == null) {
throw new Exception(Messages.getString("match.TmMatcher.updateFuzzyResult.msg1"));
}
DBOperator dbOp = (DBOperator) obj;
boolean needEnd = false;
PreparedStatement stmt = null;
try {
if (dbOp.isClosed()) {
needEnd = true;
dbOp.start();
}
int tuDbPk = fr.getTu().getTmId();
int srcDbPk = fr.getTu().getSource().getDbPk();
int tgtDbPk = fr.getTu().getTarget().getDbPk();
Connection conn = dbOp.getConnection();
if (conn == null || conn.isClosed()) {
throw new Exception(Messages.getString("match.TmMatcher.updateFuzzyResult.msg2"));
}
dbOp.beginTransaction();
dbOp.deleteAllTuvRelations(Arrays.asList(srcDbPk), fr.getTu().getSource().getLangCode());
dbOp.deleteAllTuvRelations(Arrays.asList(tgtDbPk), fr.getTu().getTarget().getLangCode());
TmxContexts contexts = fr.getTu().getContexts();
saveTuv(dbOp, tuDbPk, fr.getTu().getSource(), contexts == null ? null : contexts.getPreContext(),
contexts == null ? null : contexts.getNextContext());
saveTuv(dbOp, tuDbPk, fr.getTu().getTarget(), null, null);
String sql = "UPDATE MTU SET CHANGEID = ?, CHANGEDATE = ? WHERE MTUPKID = ? ";
stmt = conn.prepareStatement(sql);
int i = 1;
stmt.setString(i++, fr.getTu().getChangeUser());
stmt.setTimestamp(i++, DateUtils.getTimestampFromUTC(fr.getTu().getChangeDate()));
stmt.setInt(i++, tuDbPk);
stmt.executeUpdate();
dbOp.commit();
} catch (Exception e) {
logger.error("delete TM in db error", e);
try {
dbOp.rollBack();
} catch (SQLException e1) {
logger.error("delete tm DB rollback error", e);
}
throw e;
} finally {
// 修复 Bug #3064 编辑匹配--更换记忆库后再编辑原记忆库匹配,出现异常.连接释放问题
// sqlite 必须先要释放 Statement 然后再关闭连接
if (stmt != null) {
try {
stmt.close();
} catch (SQLException e) {
logger.error("delete TM stmt close error", e);
}
}
if (needEnd) {
try {
if (dbOp != null) {
dbOp.end();
}
} catch (SQLException e) {
logger.error("delete TB DB close conneciton error", e);
}
}
}
}
private void saveTuv(DBOperator dbOp, int tuPk, TmxSegement tuv, String preContext, String nextContext)
throws Exception {
String pureText = tuv.getPureText();
String hash = pureText == null ? null : pureText.hashCode() + "";
try {
dbOp.insertTextData("M", tuPk, hash, pureText, tuv.getFullText(), Utils.convertLangCode(tuv.getLangCode()),
preContext == null ? "" : preContext, nextContext == null ? "" : nextContext);
} catch (Exception e) {
throw e;
}
}
// public static void main(String[] arg) throws SQLException, ClassNotFoundException{
// String driver = "com.mysql.jdbc.Driver";
// String url = "jdbc:mysql://127.0.0.1:3306/test5";
// String name = "root";
// String pw = "root";
//
// Class.forName(driver);
// Connection conn = DriverManager.getConnection(url,name,pw);
//
// TmxTU tu = new TmxTU();
// tu.setTmId(1);
// TmxSegement source = new TmxSegement();
// source.setDbPk(1);
// source.setLangCode("en-US");
// TmxSegement target = new TmxSegement();
// target.setDbPk(2);
// target.setLangCode("zh-CN");
// tu.setSource(source);
// tu.setTarget(target);
// FuzzySearchResult fr = new FuzzySearchResult(tu);
//
// TmMatcher tm = new TmMatcher();
// tm.deleteFuzzyResult(fr, conn);
// }
}
| 17,815 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
TmImporter.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/database/net.heartsome.cat.database.tm/src/net/heartsome/cat/database/tm/importer/TmImporter.java | /**
* TmImporter.java
*
* Version information :
*
* Date:2012-5-4
*
* Copyright notice :
* 本文件及其附带的相关文件包含机密信息,仅限瀚特盛科技有限公司指定的,与本项目有关的内部人员和客户联络人员查阅和使用。
* 如果您不是本保密声明中指定的收件者,请立即销毁本文件,禁止对本文件或根据本文件中的内容采取任何其他行动,
* 包括但不限于:泄露本文件中的信息、以任何方式制作本文件全部或部分内容之副本、将本文件或其相关副本提供给任何其他人。
*/
package net.heartsome.cat.database.tm.importer;
import java.sql.SQLException;
import java.text.MessageFormat;
import net.heartsome.cat.common.bean.DatabaseModelBean;
import net.heartsome.cat.common.core.exception.ImportException;
import net.heartsome.cat.database.DBOperator;
import net.heartsome.cat.database.service.DatabaseService;
import net.heartsome.cat.database.tm.TmTransParamsBean;
import net.heartsome.cat.database.tm.resource.Messages;
import net.heartsome.cat.ts.core.IProjectConfigChangedListener;
import net.heartsome.cat.ts.core.file.ProjectConfiger;
import net.heartsome.cat.ts.core.file.ProjectConfigerFactory;
import net.heartsome.cat.ts.tm.importer.extension.ITmImporter;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.runtime.IProgressMonitor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author jason
* @version
* @since JDK1.6
*/
public class TmImporter implements ITmImporter, IProjectConfigChangedListener {
public static final Logger logger = LoggerFactory.getLogger(TmImporter.class);
private ProjectConfiger projConfiger;
private IProject currentProj;
private DBOperator dbOp;
private TmTransParamsBean transParameters = new TmTransParamsBean();
/**
*
*/
public TmImporter() {
}
/**
* (non-Javadoc)
* @throws ImportException
* @see net.heartsome.cat.ts.tm.importer.extension.ITmImporter#executeImport(java.lang.String)
*/
public int executeImport(String tmxContent, String srcLang, IProgressMonitor monitor) throws ImportException {
if (dbOp != null) {
int strategy = transParameters.getTmUpdateStrategy();
// TODO 检查上下文
int result = DatabaseService.importTmxWithString(dbOp, tmxContent, monitor, strategy, false, srcLang);
} else {
return IMPORT_STATE_NODB;
}
return IMPORT_STATE_SUCCESSED;
}
public void setProject(IProject project) {
if (project == null) {
clearResources();
return;
}
if (currentProj == null) {
currentProj = project;
} else if (project != null && !project.getName().equals(currentProj.getName())) {
currentProj = project;
} else {
return;
}
if (currentProj != null) {
projConfiger = ProjectConfigerFactory.getProjectConfiger(currentProj);
projConfiger.addChangeListener(this);
loadTmDbConn();
}
}
public void handProjectConfigChangedEvent() {
loadTmDbConn();
}
/**
* 释放连接 ;
*/
private void releaseTmDbConn() {
if (dbOp != null) {
try {
dbOp.end();
} catch (SQLException e) {
logger.error(Messages.getString("importer.TmImporter.logger1") + dbOp.getMetaData().getDatabaseName(),
e);
}
}
dbOp = null;
}
/**
* 加载连接 ;
*/
private void loadTmDbConn() {
releaseTmDbConn(); // 加载连接前先释放已经存在连接
if (projConfiger != null) {
DatabaseModelBean dmb = projConfiger.getDefaultTMDb();
if (dmb != null) {
this.dbOp = DatabaseService.getDBOperator(dmb.toDbMetaData());
try {
dbOp.start();
} catch (Exception e) {
logger.error(MessageFormat.format(Messages.getString("importer.TmImporter.logger2"),
dmb.getDbType(), dmb.getDbName()), e);
dbOp = null;
}
}
}
}
public void clearResources() {
this.releaseTmDbConn();
if (projConfiger != null)
projConfiger.removeChangeListener(this);
// if (transParameters != null)
// transParameters.clearResources();
currentProj = null;
}
public int getContextSize() {
return transParameters.getContextSize();
}
public boolean checkImporter() {
if (dbOp != null) {
return true;
}
return false;
}
}
| 4,204 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
Messages.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/database/net.heartsome.cat.database.tm/src/net/heartsome/cat/database/tm/resource/Messages.java | package net.heartsome.cat.database.tm.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.database.tm.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 + '!';
}
}
}
| 903 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
TbDbOperatorManager.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/database/net.heartsome.cat.database.tb/src/net/heartsome/cat/database/tb/TbDbOperatorManager.java | /**
* TermDbOperatorManager.java
*
* Version information :
*
* Date:2012-5-2
*
* Copyright notice :
* 本文件及其附带的相关文件包含机密信息,仅限瀚特盛科技有限公司指定的,与本项目有关的内部人员和客户联络人员查阅和使用。
* 如果您不是本保密声明中指定的收件者,请立即销毁本文件,禁止对本文件或根据本文件中的内容采取任何其他行动,
* 包括但不限于:泄露本文件中的信息、以任何方式制作本文件全部或部分内容之副本、将本文件或其相关副本提供给任何其他人。
*/
package net.heartsome.cat.database.tb;
import java.sql.SQLException;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;
import net.heartsome.cat.common.bean.DatabaseModelBean;
import net.heartsome.cat.database.DBOperator;
import net.heartsome.cat.database.service.DatabaseService;
import net.heartsome.cat.database.tb.resource.Messages;
import net.heartsome.cat.ts.core.IProjectConfigChangedListener;
import net.heartsome.cat.ts.core.file.ProjectConfiger;
import net.heartsome.cat.ts.core.file.ProjectConfigerFactory;
import org.eclipse.core.resources.IProject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* 术语库连接管理器
* @author jason
* @version
* @since JDK1.6
*/
public class TbDbOperatorManager implements IProjectConfigChangedListener {
public final static Logger logger = LoggerFactory.getLogger(TbDbOperatorManager.class);
private IProject currentProj;
private ProjectConfiger projConfiger;
private List<DBOperator> dbOpList;
public TbDbOperatorManager() {
dbOpList = new ArrayList<DBOperator>();
}
/**
* 设置项目信息
* @param project
* ;
*/
public void setProject(IProject project) {
if (currentProj == null) {
currentProj = project;
} else if (project != null && !project.getName().equals(currentProj.getName())) {
currentProj = project;
} else {
return;
}
if (currentProj != null) {
projConfiger = ProjectConfigerFactory.getProjectConfiger(currentProj);
projConfiger.addChangeListener(this);
loadTmDbConn();
}
}
public void handProjectConfigChangedEvent() {
loadTmDbConn();
}
/**
* 加载连接 ;
*/
private void loadTmDbConn() {
releaseTmDbConn(); // 加载连接前先释放已经存在连接
if (projConfiger != null) {
List<DatabaseModelBean> tmDbConfigList = projConfiger.getTermBaseDbs(false);
for (int i = 0; i < tmDbConfigList.size(); i++) {
DatabaseModelBean dmb = tmDbConfigList.get(i);
DBOperator db = DatabaseService.getDBOperator(dmb.toDbMetaData());
if(null == db){
continue;
}
try {
db.start();
} catch (Exception e) {
logger.error(MessageFormat.format(Messages.getString("tb.TbDbOperatorManager.logger1"),
dmb.getDbType(), dmb.getDbName()), e);
continue;
}
this.dbOpList.add(db);
}
}
}
/**
* 释放连接 ;
*/
private void releaseTmDbConn() {
for (DBOperator dbop : dbOpList) {
try {
if (dbop != null) {
dbop.end();
}
} catch (SQLException e) {
logger.error(Messages.getString("tb.TbDbOperatorManager.logger2")
+ dbop.getMetaData().getDatabaseName(), e);
continue; // 继续释放其他数据库资源
}
}
dbOpList.clear();
}
public void clearResource() {
currentProj = null;
if (projConfiger != null) {
projConfiger.removeChangeListener(this);
}
releaseTmDbConn();
}
public List<DBOperator> getDbOperatorList() {
return this.dbOpList;
}
}
| 3,592 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
TbParameters.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/database/net.heartsome.cat.database.tb/src/net/heartsome/cat/database/tb/TbParameters.java | /**
* TBParameters.java
*
* Version information :
*
* Date:2012-5-7
*
* Copyright notice :
* 本文件及其附带的相关文件包含机密信息,仅限瀚特盛科技有限公司指定的,与本项目有关的内部人员和客户联络人员查阅和使用。
* 如果您不是本保密声明中指定的收件者,请立即销毁本文件,禁止对本文件或根据本文件中的内容采取任何其他行动,
* 包括但不限于:泄露本文件中的信息、以任何方式制作本文件全部或部分内容之副本、将本文件或其相关副本提供给任何其他人。
*/
package net.heartsome.cat.database.tb;
import net.heartsome.cat.database.bean.TBPreferenceConstants;
import net.heartsome.cat.database.ui.tb.Activator;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.util.IPropertyChangeListener;
import org.eclipse.jface.util.PropertyChangeEvent;
/**
* @author jason
* @version
* @since JDK1.6
*/
public class TbParameters implements IPropertyChangeListener {
private IPreferenceStore ps;
private int tbUpdateStrategy = 0;
private static TbParameters instance;
public static TbParameters getInstance() {
if (instance == null) {
instance = new TbParameters();
}
return instance;
}
private TbParameters() {
ps = Activator.getDefault().getPreferenceStore();
ps.addPropertyChangeListener(this);
loadPerference();
}
public void propertyChange(PropertyChangeEvent event) {
loadPerference();
}
private void loadPerference() {
tbUpdateStrategy = ps.getInt(TBPreferenceConstants.TB_UPDATE);
}
/** @return the tbUpdateStrategy */
public int getTbUpdateStrategy() {
return tbUpdateStrategy;
}
}
| 1,716 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
TbMatch.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/database/net.heartsome.cat.database.tb/src/net/heartsome/cat/database/tb/match/TbMatch.java | /**
* TermMatch.java
*
* Version information :
*
* Date:2012-5-2
*
* Copyright notice :
* 本文件及其附带的相关文件包含机密信息,仅限瀚特盛科技有限公司指定的,与本项目有关的内部人员和客户联络人员查阅和使用。
* 如果您不是本保密声明中指定的收件者,请立即销毁本文件,禁止对本文件或根据本文件中的内容采取任何其他行动,
* 包括但不限于:泄露本文件中的信息、以任何方式制作本文件全部或部分内容之副本、将本文件或其相关副本提供给任何其他人。
*/
package net.heartsome.cat.database.tb.match;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;
import java.util.StringTokenizer;
import java.util.TreeMap;
import java.util.Vector;
import net.heartsome.cat.database.DBOperator;
import net.heartsome.cat.database.NGrams;
import net.heartsome.cat.database.bean.TBPreferenceConstants;
import net.heartsome.cat.database.tb.TbDbOperatorManager;
import net.heartsome.cat.database.ui.tb.Activator;
import net.heartsome.cat.ts.tb.match.extension.AbstractTbMatch;
import net.heartsome.cat.ts.tb.match.extension.ITbMatch;
import org.eclipse.core.resources.IProject;
/**
* 术语库匹配实现
* @author jason
* @version
* @since JDK1.6
*/
public class TbMatch extends AbstractTbMatch implements ITbMatch {
private TbDbOperatorManager termDbOpManager = new TbDbOperatorManager();
/**
*
*/
public TbMatch() {
}
/**
* (non-Javadoc)
* @see net.heartsome.cat.ts.ITbMatch.term.extensionpoint.ITermMatch#setProject(org.eclipse.core.resources.IProject)
*/
public void setProject(IProject project) {
termDbOpManager.setProject(project);
}
/**
* (non-Javadoc)
* @see net.heartsome.cat.ts.ITbMatch.term.extensionpoint.ITermMatch#getTransUnitTerms()
*/
public Vector<Hashtable<String, String>> getTransUnitTerms() {
Vector<Hashtable<String, String>> terms = new Vector<Hashtable<String, String>>();
List<DBOperator> dbOperatorList = termDbOpManager.getDbOperatorList();
for (int i = 0; i < dbOperatorList.size(); i++) {
try {
terms.addAll(dbOperatorList.get(i).findAllTermsByText(super.srcPureText, super.srcLanguage,
super.tgtLanguage));
} catch (Exception e) {
e.printStackTrace();
}
}
if (terms == null || terms.size() <= 0) {
return terms;
}
// 删除所有的特殊字符 -robert//\f\t\u2028\u2029,.;\"\':<>?!()[]{}=+-/*\u00AB\u00BB\u201C\u201D\u201E\uFF00\u2003
// srcPureText =
// srcPureText.replaceAll("[^\\w\\s\\.\\,\\;\\\"\\'\\:\\<\\>\\?\\!\\(\\)\\[\\]\\{\\}\\=\\+\\/\\*&@#$%_~`-]",
// " ");
// 注释以上代码解决德语、俄语中带注音字符部分被忽略掉的问题
cleanTerms(srcPureText, srcLanguage, terms, super.isSort);
resetCleanTerms(terms);
boolean caseSencitive = Activator.getDefault().getPreferenceStore()
.getBoolean(TBPreferenceConstants.TB_CASE_SENSITIVE);
if (!caseSencitive) {
doWithQueryResultsCaseSensitive(terms, srcPureText);
}
if (isSort) {
return sortTerms(terms, srcLanguage);
} else {
return terms;
}
}
/**
* 清理非亚洲语系中不能匹配整个单词及重复出现的术语。
*/
public static void cleanTerms(String source, String srcLang, Vector<Hashtable<String, String>> terms, boolean isSort) {
Vector<String> srcWord = buildWordList(source.toLowerCase(), srcLang);
for (int i = 0; i < terms.size(); i++) {
Hashtable<String, String> term = terms.get(i);
String key = term.get("srcWord");
Vector<String> keyWord = buildWordList(key.toLowerCase(), srcLang);
// 其他文字,要进行进一步判断,如果判断不成功,删除该术语匹配
if (!srcLang.toLowerCase().matches("zh.*|ja.*|ko.*|th.*|he.*")) {
if (!termAnalysis(srcWord, keyWord)) {
terms.remove(i);
i--;
}
}
// 如果要排序的话,获取术语单词数与字数,方便排序时进行比较,以及在自动翻译中计算匹配率,避免重复取出来文本来计算。
if (isSort) {
term.put("WordSize", String.valueOf(keyWord.size()));
term.put("CharLength", String.valueOf(key.length()));
term.put("index", "" + source.indexOf(key));
}
// 下面判断重复的术语的情况,与下面所有的术语项进行匹配,若有相同的,就删除。 备注:注释该过滤代码,--robert 2012-06-18
// for (int j = i + 1; j < terms.size(); j++) {
// Hashtable<String, String> term_j = terms.get(j);
// if (term.get("srcWord").equals(term_j.get("srcWord"))
// && term.get("tgtWord").equals(term_j.get("tgtWord"))) {
// terms.remove(j);
// j--;
// }
// }
}
}
private static Vector<String> buildWordList(String source, String srcLang) {
Vector<String> result = new Vector<String>();
StringTokenizer tk = new StringTokenizer(source, NGrams.SEPARATORS, true);
while (tk.hasMoreTokens()) {
result.add(tk.nextToken());
}
return result;
}
public static boolean termAnalysis(Vector<String> srcWord, Vector<String> termWords) {
int termSize = termWords.size();
if (termSize == 0) {
return false;
}
if (termSize == 1) {
if (srcWord.indexOf(termWords.get(0).toLowerCase()) != -1) {
return true;
} else {
return false;
}
}
int sIndex = srcWord.indexOf(termWords.get(0).toLowerCase(), 0);
while (sIndex != -1 && sIndex + termSize - 1 < srcWord.size()) { // 有开始并且长度够
// 从术语长度处取结尾单词比较是否相同
if (srcWord.get(sIndex + termSize - 1).equalsIgnoreCase(termWords.get(termSize - 1))) {
boolean isTerm = true;
for (int i = 1, size = termSize - 1; i < size; i++) {
if (!srcWord.get(sIndex + i).equalsIgnoreCase(termWords.get(i))) {
isTerm = false;
break;
}
}
if (isTerm) {
return true;
}
}
sIndex = srcWord.indexOf(termWords.get(0).toLowerCase(), sIndex + 1);
}
return false;
}
/**
* 对术语按字数或单词数进行从长到短的降序排列,方便正确替换。
*/
public static Vector<Hashtable<String, String>> sortTerms(Vector<Hashtable<String, String>> terms, String srcLang) {
Vector<Hashtable<String, String>> result = new Vector<Hashtable<String, String>>();
int maxLength = 0;
TreeMap<Integer, Vector<Hashtable<String, String>>> termMap = new TreeMap<Integer, Vector<Hashtable<String, String>>>();
// 先按术语在原文中的顺序排序
for (Hashtable<String, String> term : terms) {
int index = Integer.parseInt(term.get("index"));
if (termMap.get(index) == null) {
termMap.put(index, new Vector<Hashtable<String, String>>());
}
termMap.get(index).add(term);
}
Hashtable<Integer, Vector<Hashtable<String, String>>> groupTerms = new Hashtable<Integer, Vector<Hashtable<String, String>>>();
for (Entry<Integer, Vector<Hashtable<String, String>>> entry : termMap.entrySet()) {
groupTerms.clear();
Vector<Hashtable<String, String>> termVector = entry.getValue();
// 按单词数量来排序
for (int i = 0, size = termVector.size(); i < size; i++) {
Hashtable<String, String> term = termVector.get(i);
int termSize = Integer.parseInt(term.get("WordSize"));
if (termSize > maxLength) {
maxLength = termSize;
}
Vector<Hashtable<String, String>> sameSizeTerms = groupTerms.get(termSize);
if (sameSizeTerms == null) {
sameSizeTerms = new Vector<Hashtable<String, String>>();
}
sameSizeTerms.add(term);
groupTerms.put(termSize, sameSizeTerms);
}
// 按字符数量来排序
for (int key = maxLength; key > 0; key--) {
Vector<Hashtable<String, String>> partOfTerms = groupTerms.get(key);
if (partOfTerms == null) {
continue;
}
// 如果同样单词数量的术语只有一个,则无须按字符长度再排序
if (partOfTerms.size() == 1) {
result.addAll(partOfTerms);
continue;
}
// 当同样单词数量的术语超过一个时,按字符长度再排序
Hashtable<Integer, Vector<Hashtable<String, String>>> charsGroupTerms = new Hashtable<Integer, Vector<Hashtable<String, String>>>();
int maxChars = 0;
for (int i = 0, size = partOfTerms.size(); i < size; i++) {
Hashtable<String, String> term = partOfTerms.get(i);
int charCount = Integer.parseInt(term.get("CharLength"));
maxChars = maxChars > charCount ? maxChars : charCount;
Vector<Hashtable<String, String>> tmpTerms = charsGroupTerms.get(charCount);
if (tmpTerms == null) {
tmpTerms = new Vector<Hashtable<String, String>>();
}
tmpTerms.add(term);
charsGroupTerms.put(charCount, tmpTerms);
}
for (int charKey = maxChars; charKey > 0; charKey--) {
Vector<Hashtable<String, String>> charPartOfTerms = charsGroupTerms.get(charKey);
if (charPartOfTerms == null) {
continue;
}
result.addAll(charPartOfTerms);
}
}
}
return result;
}
public void clearResources() {
srcPureText = "";
srcLanguage = "";
tgtLanguage = "";
isSort = false;
termDbOpManager.clearResource();
}
private static void resetCleanTerms(Vector<Hashtable<String, String>> terms) {
for (Hashtable<String, String> term : terms) {
String srcWord = term.get("srcWord");
String tgtWord = term.get("tgtWord");
String srcWord_new = resetCleanString(srcWord);
String tgtWord_new = resetCleanString(tgtWord);
if (!srcWord_new.equals(srcWord)) {
term.put("srcWord", srcWord_new);
}
if (!tgtWord_new.equals(tgtWord)) {
term.put("tgtWord", tgtWord_new);
}
}
}
private static String resetCleanString(String string) {
string = string.replaceAll("<", "<");
string = string.replaceAll(">", ">");
// string = string.replaceAll(""", "\"");
string = string.replaceAll("&", "&");
return string;
}
public boolean checkTbMatcher(IProject project) {
this.setProject(project);
if (termDbOpManager.getDbOperatorList().size() == 0) {
return false;
}
return true;
}
/**
* 如果结果要区分大小写
* @param terms
* @param caseSensitive
* ;
*/
private void doWithQueryResultsCaseSensitive(Vector<Hashtable<String, String>> terms, String pureText) {
Iterator<Hashtable<String, String>> iterator = terms.iterator();
while(iterator.hasNext()){
Hashtable<String, String> item = iterator.next();
String srcWord = item.get("srcWord");
if (!pureText.contains(srcWord)) {
iterator.remove();
}
}
}
}
| 10,523 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
TbImporter.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/database/net.heartsome.cat.database.tb/src/net/heartsome/cat/database/tb/importer/TbImporter.java | /**
* TbImporter.java
*
* Version information :
*
* Date:2012-5-7
*
* Copyright notice :
* 本文件及其附带的相关文件包含机密信息,仅限瀚特盛科技有限公司指定的,与本项目有关的内部人员和客户联络人员查阅和使用。
* 如果您不是本保密声明中指定的收件者,请立即销毁本文件,禁止对本文件或根据本文件中的内容采取任何其他行动,
* 包括但不限于:泄露本文件中的信息、以任何方式制作本文件全部或部分内容之副本、将本文件或其相关副本提供给任何其他人。
*/
package net.heartsome.cat.database.tb.importer;
import java.sql.SQLException;
import java.text.MessageFormat;
import java.util.List;
import net.heartsome.cat.common.bean.DatabaseModelBean;
import net.heartsome.cat.common.core.exception.ImportException;
import net.heartsome.cat.database.DBOperator;
import net.heartsome.cat.database.service.DatabaseService;
import net.heartsome.cat.database.tb.TbDbOperatorManager;
import net.heartsome.cat.database.tb.TbParameters;
import net.heartsome.cat.database.tb.resource.Messages;
import net.heartsome.cat.document.ImportAbstract;
import net.heartsome.cat.ts.core.IProjectConfigChangedListener;
import net.heartsome.cat.ts.core.file.ProjectConfiger;
import net.heartsome.cat.ts.core.file.ProjectConfigerFactory;
import net.heartsome.cat.ts.tb.importer.extension.ITbImporter;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.runtime.IProgressMonitor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author jason
* @version
* @since JDK1.6
*/
public class TbImporter implements ITbImporter, IProjectConfigChangedListener {
private final static Logger logger = LoggerFactory.getLogger(TbDbOperatorManager.class);
private ProjectConfiger projConfiger;
private IProject currentProj;
private DBOperator dbOp;
private TbParameters tbParas = TbParameters.getInstance();
/**
*
*/
public TbImporter() {
}
public boolean checkImporter() {
if (dbOp != null) {
return true;
}
return false;
}
/**
* (non-Javadoc)
* @see net.heartsome.cat.ts.tb.importer.extension.ITbImporter#setProject(org.eclipse.core.resources.IProject)
*/
public void setProject(IProject project) {
if (project == null) {
clearResources();
return;
}
if (currentProj == null) {
currentProj = project;
} else if (project != null && !project.getName().equals(currentProj.getName())) {
currentProj = project;
} else {
return;
}
if (currentProj != null) {
projConfiger = ProjectConfigerFactory.getProjectConfiger(currentProj);
projConfiger.addChangeListener(this);
loadTmDbConn();
}
}
public void handProjectConfigChangedEvent() {
loadTmDbConn();
}
/**
* 加载连接 ;
*/
private void loadTmDbConn() {
releaseTmDbConn(); // 加载连接前先释放已经存在连接
if (projConfiger != null) {
List<DatabaseModelBean> termdbList = projConfiger.getTermBaseDbs(true);
if (termdbList.size() == 0) {
return;
}
DatabaseModelBean dmb = termdbList.get(0);
if (dmb != null) {
this.dbOp = DatabaseService.getDBOperator(dmb.toDbMetaData());
try {
dbOp.start();
} catch (Exception e) {
logger.error(MessageFormat.format(Messages.getString("importer.TbImporter.logger1"),
dmb.getDbType(), dmb.getDbName()), e);
dbOp = null;
}
}
}
}
/**
* 释放连接 ;
*/
private void releaseTmDbConn() {
if (dbOp != null) {
try {
if (dbOp != null) {
dbOp.end();
}
} catch (SQLException e) {
logger.error(Messages.getString("importer.TbImporter.logger2") + dbOp.getMetaData().getDatabaseName(),
e);
}
dbOp = null;
}
}
/**
* (non-Javadoc)
* @throws ImportException
* @see net.heartsome.cat.ts.tb.importer.extension.ITbImporter#executeImport(java.lang.String, java.lang.String)
*/
public int executeImport(String tbxStr, String srcLang, IProgressMonitor monitor) throws ImportException {
if (dbOp != null) {
int result = DatabaseService.importTbxWithString(tbxStr, monitor, dbOp, tbParas.getTbUpdateStrategy(),
srcLang);
if (result == ImportAbstract.SUCCESS) {
return ITbImporter.IMPORT_STATE_SUCCESSED;
}
} else {
return ITbImporter.IMPORT_STATE_NODB;
}
return ITbImporter.IMPORT_STATE_FAILED;
}
public void clearResources() {
this.releaseTmDbConn();
if (projConfiger != null)
projConfiger.removeChangeListener(this);
currentProj = null;
}
}
| 4,529 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
Messages.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/database/net.heartsome.cat.database.tb/src/net/heartsome/cat/database/tb/resource/Messages.java | package net.heartsome.cat.database.tb.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.database.tb.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 + '!';
}
}
}
| 903 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
Activator.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/database/net.heartsome.cat.database.sqlite/src/net/heartsome/cat/database/sqlite/Activator.java | package net.heartsome.cat.database.sqlite;
import net.heartsome.cat.database.DBServiceProvider;
import org.eclipse.core.runtime.Plugin;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceRegistration;
public class Activator extends Plugin {
/** The plug-in ID */
public static final String PLUGIN_ID = "net.heartsome.cat.database.sqlite";
/** The shared instance */
private static Activator plugin;
private ServiceRegistration<DBServiceProvider> sqliteServiceRegistration;
/**
* 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;
DbServiceProviderImpl service = new DbServiceProviderImpl();
sqliteServiceRegistration = context.registerService(DBServiceProvider.class, service, null);
}
/*
* (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);
sqliteServiceRegistration.unregister();
}
/**
* Returns the shared instance
*
* @return the shared instance
*/
public static Activator getDefault() {
return plugin;
}
}
| 1,350 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
TMDatabaseImpl.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/database/net.heartsome.cat.database.sqlite/src/net/heartsome/cat/database/sqlite/TMDatabaseImpl.java | package net.heartsome.cat.database.sqlite;
import java.io.File;
import java.net.URL;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.IdentityHashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.Vector;
import java.util.regex.Pattern;
import net.heartsome.cat.common.bean.FuzzySearchResult;
import net.heartsome.cat.common.bean.TmxContexts;
import net.heartsome.cat.common.bean.TmxProp;
import net.heartsome.cat.common.bean.TmxSegement;
import net.heartsome.cat.common.bean.TmxTU;
import net.heartsome.cat.common.bean.TranslationUnitAnalysisResult;
import net.heartsome.cat.common.util.CommonFunction;
import net.heartsome.cat.common.util.DateUtils;
import net.heartsome.cat.database.Constants;
import net.heartsome.cat.database.DBConfig;
import net.heartsome.cat.database.DBOperator;
import net.heartsome.cat.database.TranslationMemoryTools;
import net.heartsome.cat.database.Utils;
import net.heartsome.cat.database.bean.FuzzySearchResults;
import net.heartsome.cat.database.bean.TranslationUnitAnalysisResults;
import org.eclipse.core.runtime.Platform;
import org.osgi.framework.Bundle;
import org.sqlite.Function;
import org.sqlite.SQLiteConfig;
import org.sqlite.SQLiteConfig.SynchronousMode;
/**
* @author peason
* @version
* @since JDK1.6
*/
public class TMDatabaseImpl extends DBOperator {
public TMDatabaseImpl() {
Bundle buddle = Platform.getBundle(Activator.PLUGIN_ID);
URL fileUrl = buddle.getEntry(Constants.DBCONFIG_PATH);
dbConfig = new DBConfig(fileUrl);
}
@Override
public void start() throws SQLException, ClassNotFoundException {
File file = new File(metaData.getDataPath()+File.separator+metaData.getDatabaseName());
if(!file.exists()){
throw new SQLException("File not found");
}
SQLiteConfig conf = new SQLiteConfig();
conf.setSynchronous(SynchronousMode.OFF);
String url = Utils.replaceParams(dbConfig.getDbURL(), metaData);
url = url.replace("__FILE_SEPARATOR__", File.separator);
String driver = dbConfig.getDriver();
Class.forName(driver);
Properties prop = Utils.replaceParams(dbConfig.getConfigProperty(), metaData);
SQLiteConfig config = new SQLiteConfig(prop);
config.setSynchronous(SynchronousMode.OFF);
conn = DriverManager.getConnection(url, config.toProperties());
// conn.setAutoCommit(false);
}
@Override
public void rollBack() throws SQLException {
Statement stmt = null;
if (null == conn) {
return;
}
try {
stmt = conn.createStatement();
stmt.execute("rollback;");
} finally {
if (stmt != null) {
stmt.close();
}
}
}
@Override
public void beginTransaction() throws SQLException {
Statement stmt = null;
try {
if (null == conn) {
return;
}
stmt = conn.createStatement();
if (null == stmt) {
return;
}
stmt.setQueryTimeout(30);
stmt.execute("begin immediate;");
} finally {
if (stmt != null) {
stmt.close();
}
}
}
@Override
public void commit() throws SQLException {
Statement stmt = null;
try {
if (null == conn) {
return;
}
stmt = conn.createStatement();
stmt.execute("commit;");
} finally {
if (stmt != null) {
stmt.close();
}
}
}
@Override
public void fuzzySearch(String pureText, String fullText, String srcLang, String tgtLang, int minSimilarity,
boolean caseSensitive, int matchUpperLimit, int contextSize, String preHash, String nextHash,
boolean isIngoreTarget, FuzzySearchResults searchResults, int tagPelanty) throws SQLException {
int[] ngrams = generateNgrams(srcLang, pureText);
int size = ngrams.length;
if (size == 0) {
return;
}
// long l1 = System.currentTimeMillis();
int min = size * minSimilarity / 100;
int max = size * 100 / minSimilarity;
Map<String, Integer> tpkids = getCandidatesTextDataPks(srcLang, min, max, ngrams);
// System.out.println("查MATEX_LANG表:"+(System.currentTimeMillis() - l1));
// 构建SQL
Iterator<Entry<String, Integer>> it = tpkids.entrySet().iterator();
StringBuffer bf = new StringBuffer();
// long l = System.currentTimeMillis();
while (it.hasNext()) {
Entry<String, Integer> entry = it.next();
String tpkid = entry.getKey();
float c = entry.getValue();
if (c >= min && c <= max) {
bf.append(",");
bf.append(tpkid);
}
}
if (bf.toString().equals("")) {
return;
}
String tag = TranslationMemoryTools.getInnerTagContent(fullText);
String textDataSql = dbConfig.getOperateDbSQL("fuzzySearch");
textDataSql = textDataSql.replace("__SET__", bf.toString().substring(1));
Statement stm = null;
ResultSet rs = null;
Statement tmpStm = null;
try {
stm = conn.createStatement();
tmpStm = conn.createStatement();
rs = stm.executeQuery(textDataSql);
// SELECT TPKID, GROUPID, PURE, CONTENT, PRECONTEXT, NEXTCONTEXT FROM TEXTDATA WHERE TPKID IN (__SET__)
String targetSql = dbConfig.getOperateDbSQL("fuzzySearch-target").replace("__LANG__", tgtLang);
String dbName = getMetaData().getDatabaseName();
while (rs.next()) {
String _pureText = rs.getString(3);
String _fullText = rs.getString(4);
int similarity = 0;
if (caseSensitive) {
similarity = similarity(pureText, _pureText);
} else {
similarity = similarity(pureText.toLowerCase(), _pureText.toLowerCase());
}
String _tag = TranslationMemoryTools.getInnerTagContent(_fullText);
if (!isIngoreTarget && !tag.equals(_tag)) {
// 标记内容不相等,则执行罚分
similarity -= tagPelanty;
}
if (similarity < minSimilarity) {
continue;
}
int tuId = rs.getInt(2);
String temptargetSql = targetSql.replace("__GROUPID__", tuId + "");
// PURE, CONTENT, CREATIONID, CREATIONDATE, CHANGEID, CHANGEDATE ,PROJECTREF
ResultSet rs1 = null;
try {
rs1 = tmpStm.executeQuery(temptargetSql);
if (rs1.next()) {
TmxSegement source = new TmxSegement(_pureText, _fullText, srcLang);
source.setDbPk(rs.getInt(1));
_pureText = rs1.getString(2);
_fullText = rs1.getString(3);
if (_pureText == null || _pureText.equals("") || _fullText == null || _fullText.equals("")) {
continue;
}
TmxSegement target = new TmxSegement(_pureText, _fullText, tgtLang);
target.setDbPk(rs1.getInt(1));
TmxTU tu = new TmxTU(source, target);
FuzzySearchResult searchRs = new FuzzySearchResult(tu);
if (searchResults.contains(searchRs)) {
continue;
}
String creationId = rs1.getString(4);
creationId = creationId == null ? "" : creationId;
String creationDate = "";
Timestamp tempCdate = rs1.getTimestamp(5);
if (tempCdate != null) {
creationDate = DateUtils.formatToUTC(tempCdate.getTime());
}
String changeid = rs1.getString(6);
changeid = changeid == null ? "" : changeid;
String changeDate = "";
Timestamp tempChangeDate = rs1.getTimestamp(7);
if (tempChangeDate != null) {
changeDate = DateUtils.formatToUTC(tempChangeDate.getTime());
}
String projectRef = rs1.getString(8);
projectRef = projectRef == null ? "" : projectRef;
tu.setCreationDate(creationDate);
tu.setCreationUser(creationId);
tu.setChangeDate(changeDate);
tu.setChangeUser(changeid);
List<TmxProp> attrs = getTuMprops(tuId, "TU");
tu.setProps(attrs);
String preContext = rs.getString(5);
String nextContext = rs.getString(6);
tu.appendContext(TmxContexts.PRE_CONTEXT_NAME, preContext);
tu.appendContext(TmxContexts.NEXT_CONTEXT_NAME, nextContext);
if (similarity == 100 && CommonFunction.checkEdition("U")) {
if (preContext != null && nextContext != null) {
String[] preContexts = preContext.split(",");
String[] nextContexts = nextContext.split(",");
if (preContexts.length > contextSize) {
preContext = ""; //$NON-NLS-1$
for (int i = 0; i < contextSize; i++) {
preContext += "," + preContexts[i]; //$NON-NLS-1$
}
if (!"".equals(preContext)) { //$NON-NLS-1$
preContext = preContext.substring(1);
}
}
if (nextContexts.length > contextSize) {
nextContext = ""; //$NON-NLS-1$
for (int i = 0; i < contextSize; i++) {
nextContext += "," + nextContexts[i]; //$NON-NLS-1$
}
if (!"".equals(nextContext)) { //$NON-NLS-1$
nextContext = nextContext.substring(1);
}
}
if (preHash.equals(preContext) && nextHash.equals(nextContext)) {
similarity = 101;
}
}
}
searchRs.setDbName(dbName);
searchRs.setSimilarity(similarity);
searchRs.setDbOp(this);
searchRs.getTu().setTmId(tuId);
searchResults.add(searchRs);
}
} finally {
if (rs1 != null) {
rs1.close();
}
}
}
} finally {
if (rs != null) {
rs.close();
}
if (stm != null) {
stm.close();
}
if (tmpStm != null) {
tmpStm.close();
}
}
}
/**
* (non-Javadoc)
* @see net.heartsome.cat.database.DBOperator#findAllTermsByText(java.lang.String, java.lang.String,
* java.lang.String)
*/
@Override
public Vector<Hashtable<String, String>> findAllTermsByText(String srcPureText, String srcLang, String tarLang)
throws SQLException {
Vector<Hashtable<String, String>> terms = new Vector<Hashtable<String, String>>();
if (srcPureText == null) {
return terms;
}
// 此处理需要特殊处理衍生的拉丁字母,由于SQLite 的upper方法这些衍生拉丁字母不起作用。
srcPureText = srcPureText.toUpperCase().trim();
String _srcPureText = SQLiteUtils.lowerNonAscii(srcPureText, Locale.ENGLISH);
if (_srcPureText.equals(srcPureText)) {
// 没有衍生拉丁字母 如é
findTrems(srcPureText, srcLang, tarLang, terms);
} else {
findTrems(_srcPureText, srcLang, tarLang, terms);
findTrems(srcPureText, srcLang, tarLang, terms);
}
return terms;
}
private void findTrems(String srcPureText, String srcLang, String tarLang, Vector<Hashtable<String, String>> result)
throws SQLException {
Vector<Hashtable<String, String>> terms = new Vector<Hashtable<String, String>>();
// 构建SQL
String getTermSql = dbConfig.getOperateDbSQL("getTerm");
PreparedStatement stmt = conn.prepareStatement(getTermSql);
stmt.setString(1, tarLang);
stmt.setString(2, srcLang + "," + tarLang);
stmt.setString(3, tarLang + "," + srcLang);
stmt.setString(4, srcLang);
stmt.setString(5, srcPureText);
/*
* SELECT A.TPKID, A.PURE, B.PURE FROM TEXTDATA A LEFT JOIN TEXTDATA B ON A.GROUPID=B.GROUPID AND B.LANG=? AND
* B.TYPE='B' WHERE A.TYPE='B' AND A.LANG=? AND LOCATE(A.PURE, ?) AND B.PURE IS NOT NULL;
*/
ResultSet rs = stmt.executeQuery();
TO: while (rs.next()) {
String tuid = rs.getString(1);
String srcWord = rs.getString(2);
String tgtWord = rs.getString(3);
String property = rs.getString(4);
for (Hashtable<String, String> temp : result) {
String _srcWord = temp.get("srcWord");
String _tgtWord = temp.get("tgtWord");
if (srcWord.equals(_srcWord) && tgtWord.equals(_tgtWord)) {
continue TO;
}
}
Hashtable<String, String> tu = new Hashtable<String, String>();
tu.put("tuid", tuid);
tu.put("srcLang", srcLang);
tu.put("srcWord", srcWord);
tu.put("tgtLang", tarLang);
tu.put("tgtWord", tgtWord);
tu.put("property", property == null ? "" : property);
terms.add(tu);
}
rs.close();
stmt.close();
result.addAll(terms);
}
/**
* (non-Javadoc)
* @see net.heartsome.cat.database.DBOperator#replaceTMOrTBConditionSql(java.lang.String, java.lang.String, boolean,
* boolean, boolean, java.lang.String, java.lang.String[])
*/
public String replaceTMOrTBConditionSql(String sql, String strSearch, boolean isCaseSensitive,
boolean isApplyRegular, boolean isIgnoreMark, String srcLang, String[] arrFilter) {
strSearch = strSearch == null ? "" : strSearch;
StringBuffer strCondition = new StringBuffer();
if (srcLang != null) {
strCondition.append(" AND A.LANG='" + srcLang + "'");
} else {
return null;
}
try {
Function.create(conn, "sqliteRegexp", new Function() {
protected void xFunc() {
try {
if (args() == 2) {
String input = value_text(0);
String regex = value_text(1);
if (Pattern.matches(regex, input)) {
result(1);
} else {
result(0);
}
} else {
error("");
}
} catch (SQLException e) {
e.printStackTrace();
}
}
});
} catch (SQLException e) {
e.printStackTrace();
}
if (isApplyRegular) {
strCondition.append(" AND sqliteRegexp('" + (isIgnoreMark ? "A.PURE" : "A.CONTENT") + "','" + strSearch
+ "')==1");
} else {
strCondition.append(" AND " + (isIgnoreMark ? "A.PURE" : "A.CONTENT") + " LIKE '%"
+ /*TextUtil.cleanStringByLikeWithMsSql(*/strSearch/*)*/ + "%'");
}
if (arrFilter != null) {
StringBuffer strFilter = new StringBuffer(arrFilter[1] + " '%"
+ /*TextUtil.cleanStringByLikeWithMsSql(*/arrFilter[2]/*)*/ + "%'");
// 过滤条件要加在源语言中
if (arrFilter[0].equalsIgnoreCase(srcLang)) {
sql = Utils.replaceString(sql, "__TABLE_TEXTDATA__", "");
strFilter.insert(0, " AND A.PURE ");
strCondition.append(strFilter.toString());
} else {
sql = Utils.replaceString(sql, "__TABLE_TEXTDATA__", " ,TEXTDATA B ");
strCondition.append(" AND A.GROUPID=B.GROUPID AND B.TYPE='M' AND B.LANG='" + arrFilter[0] + "'");
strFilter.insert(0, " AND B.PURE ");
strCondition.append(strFilter.toString());
}
} else {
sql = Utils.replaceString(sql, "__TABLE_TEXTDATA__", "");
}
sql = Utils.replaceString(sql, "__CONDITION__", strCondition.toString());
return sql;
}
@Override
public void translationUnitAnalysis(String pureText, String fullText, String srcLang, String tgtLang,
int minSimilarity, boolean caseSensitive, int matchUpperLimit, int contextSize, String preHash,
String nextHash, boolean isIngoreTarget, TranslationUnitAnalysisResults analysisResults, int tagPelanty)
throws SQLException {
int[] ngrams = generateNgrams(srcLang, pureText);
int size = ngrams.length;
if (size == 0) {
return;
}
// long l1 = System.currentTimeMillis();
int min = size * minSimilarity / 100;
int max = size * 100 / minSimilarity;
Map<String, Integer> tpkids = getCandidatesTextDataPks(srcLang, min, max, ngrams);
// System.out.println("查MATEX_LANG表:"+(System.currentTimeMillis() - l1));
// 构建SQL
Iterator<Entry<String, Integer>> it = tpkids.entrySet().iterator();
StringBuffer bf = new StringBuffer();
// long l = System.currentTimeMillis();
while (it.hasNext()) {
Entry<String, Integer> entry = it.next();
String tpkid = entry.getKey();
float c = entry.getValue();
if (c >= min && c <= max) {
bf.append(",");
bf.append(tpkid);
}
}
if (bf.toString().equals("")) {
return;
}
String tag = TranslationMemoryTools.getInnerTagContent(fullText);
String textDataSql = dbConfig.getOperateDbSQL("fuzzySearch-wordsFA");
textDataSql = textDataSql.replace("__SET__", bf.toString().substring(1));
textDataSql = textDataSql.replace("__TARGETLANG__", tgtLang);
Statement stm = null;
ResultSet rs = null;
Statement tmpStm = null;
try {
stm = conn.createStatement();
tmpStm = conn.createStatement();
rs = stm.executeQuery(textDataSql);
// SELECT GROUPID, PURE, CONTENT, PRECONTEXT, NEXTCONTEXT FROM TEXTDATA WHERE TPKID IN (__SET__)
String dbName = getMetaData().getDatabaseName();
while (rs.next()) {
String _pureText = rs.getString(3);
String _fullText = rs.getString(4);
int similarity = 0;
if (caseSensitive) {
similarity = similarity(pureText, _pureText);
} else {
similarity = similarity(pureText.toLowerCase(), _pureText.toLowerCase());
}
String _tag = TranslationMemoryTools.getInnerTagContent(_fullText);
if (!isIngoreTarget && !tag.equals(_tag)) {
// 标记内容不相等,则执行罚分
similarity -= tagPelanty;
}
if (similarity < minSimilarity) {
continue;
}
if (similarity == 100 && CommonFunction.checkEdition("U")) {
String preContext = rs.getString(5);
String nextContext = rs.getString(6);
if (preContext != null && nextContext != null) {
String[] preContexts = preContext.split(",");
String[] nextContexts = nextContext.split(",");
if (preContexts.length > contextSize) {
preContext = ""; //$NON-NLS-1$
for (int i = 0; i < contextSize; i++) {
preContext += "," + preContexts[i]; //$NON-NLS-1$
}
if (!"".equals(preContext)) { //$NON-NLS-1$
preContext = preContext.substring(1);
}
}
if (nextContexts.length > contextSize) {
nextContext = ""; //$NON-NLS-1$
for (int i = 0; i < contextSize; i++) {
nextContext += "," + nextContexts[i]; //$NON-NLS-1$
}
if (!"".equals(nextContext)) { //$NON-NLS-1$
nextContext = nextContext.substring(1);
}
}
if (preHash.equals(preContext) && nextHash.equals(nextContext)) {
similarity = 101;
}
}
}
TranslationUnitAnalysisResult r = new TranslationUnitAnalysisResult(similarity, dbName);
analysisResults.add(r);
}
} finally {
if (rs != null) {
rs.close();
}
if (stm != null) {
stm.close();
}
if (tmpStm != null) {
tmpStm.close();
}
}
}
@Override
public HashMap<String, IdentityHashMap<String, String>> getTermBaseResult(String strSearch,
boolean isCaseSensitive, boolean isApplyRegular, boolean isIgnoreMark, String strLang,
List<String> lstLangs, int intMatchQuality) {
if (!isCaseSensitive) {
HashMap<String, IdentityHashMap<String, String>> mapTermBase = new HashMap<String, IdentityHashMap<String, String>>();
String lo = strSearch.toLowerCase();
mapTermBase.putAll(super.getTermBaseResult(lo, isCaseSensitive, isApplyRegular, isIgnoreMark, strLang,
lstLangs, intMatchQuality));
String up = strSearch.toUpperCase();
mapTermBase.putAll(super.getTermBaseResult(up, isCaseSensitive, isApplyRegular, isIgnoreMark, strLang,
lstLangs, intMatchQuality));
return mapTermBase;
} else {
return super.getTermBaseResult(strSearch, isCaseSensitive, isApplyRegular, isIgnoreMark, strLang, lstLangs,
intMatchQuality);
}
}
}
| 18,765 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
SQLiteUtils.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/database/net.heartsome.cat.database.sqlite/src/net/heartsome/cat/database/sqlite/SQLiteUtils.java | package net.heartsome.cat.database.sqlite;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* SQLite 相关工具类
* @author Jason
* @version
* @since JDK1.6
*/
public class SQLiteUtils {
private static final Pattern UPPER = Pattern.compile("[\\p{javaUpperCase}&&[^\\p{Upper}]]+");
/**
* select upper(term) from terms where term="Accusé";
* SQLite upper() function apparently ignores special characters – it had been uppercasing everything except our é,
* causing our dictionary query to fail.
* @param str
* @param locale
* @return ;
*/
public static String lowerNonAscii(String str, Locale locale) {
StringBuilder buffer = new StringBuilder();
Matcher matcher = UPPER.matcher(str);
int start = 0;
while (matcher.find()) {
String nonMatch = str.substring(start, matcher.start());
String match = str.substring(matcher.start(), matcher.end()).toLowerCase(locale);
buffer.append(nonMatch).append(match);
start = matcher.end();
}
String tail = str.substring(start, str.length());
return buffer.append(tail).toString();
}
public static void main(String[] args) {
String test = "BĒ /BEː/ ";
System.out.println(test + " > " + lowerNonAscii(test, Locale.ENGLISH));
}
}
| 1,315 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
MetaDataImpl.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/database/net.heartsome.cat.database.sqlite/src/net/heartsome/cat/database/sqlite/MetaDataImpl.java | package net.heartsome.cat.database.sqlite;
import net.heartsome.cat.common.bean.MetaData;
public class MetaDataImpl extends MetaData{
public boolean instanceSupported() {
return false;
}
public boolean portSupported() {
return false;
}
public boolean serverNameSupported() {
return false;
}
public boolean passwordSupported() {
return false;
}
public boolean userNameSupported() {
return false;
}
}
| 429 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
OperateSystemDBImpl.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/database/net.heartsome.cat.database.sqlite/src/net/heartsome/cat/database/sqlite/OperateSystemDBImpl.java | package net.heartsome.cat.database.sqlite;
import java.io.File;
import java.net.URL;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import net.heartsome.cat.common.bean.MetaData;
import net.heartsome.cat.database.Constants;
import net.heartsome.cat.database.DBConfig;
import net.heartsome.cat.database.SystemDBOperator;
import net.heartsome.cat.database.Utils;
import net.heartsome.cat.database.sqlite.resource.Messages;
import org.eclipse.core.runtime.Platform;
import org.osgi.framework.Bundle;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sqlite.SQLiteConfig;
public class OperateSystemDBImpl extends SystemDBOperator {
private static final Logger LOGGER = LoggerFactory.getLogger(OperateSystemDBImpl.class);
private Connection conn = null;
public OperateSystemDBImpl() {
metaData = new MetaDataImpl();
Bundle buddle = Platform.getBundle(Activator.PLUGIN_ID);
URL fileUrl = buddle.getEntry(Constants.DBCONFIG_PATH);
dbConfig = new DBConfig(fileUrl);
metaData.setDbType(dbConfig.getDefaultType());
}
/**
* (non-Javadoc)
* @see net.heartsome.cat.database.SystemDBOperator#createDB()
*/
public int createDB() throws SQLException {
List<String> createTables = dbConfig.getCreateTables();
createTables.addAll(dbConfig.getCreateIndexs());
return createDB(createTables, metaData);
}
/**
* 创建数据表
* @param createTables
* @param metaData
* @return
* @throws SQLException
* ;
*/
private int createDB(List<String> createTables, MetaData metaData) throws SQLException {
createDirs();
Statement stmt = null;
String driver = dbConfig.getDriver();
String url = Utils.replaceParams(dbConfig.getDbURL(), metaData);
url = url.replace("__FILE_SEPARATOR__", File.separator);
Properties prop = Utils.replaceParams(dbConfig.getConfigProperty(), metaData);
try {
conn = getConnection(driver, url, prop);
stmt = conn.createStatement();
if (createTables != null) {
stmt.execute("begin immediate;");
for (String i : createTables) {
String step = Utils.replaceParams(i, metaData);
stmt.executeUpdate(step);
}
stmt.execute("commit;");
}
} catch (ClassNotFoundException e) {
LOGGER.error("", e);
e.printStackTrace();
return Constants.FAILURE;
} catch (SQLException e) {
LOGGER.error("", e);
try {
if (conn != null && !conn.isClosed()) {
stmt.execute("rollback;");
}
} catch (SQLException e1) {
throw e1;
}
throw e;
} finally {
freeConnection(stmt, conn);
}
return Constants.SUCCESS;
}
/**
* (non-Javadoc)
* @see net.heartsome.cat.database.SystemDBOperator#createSysDb()
*/
public int createSysDb() throws SQLException {
MetaData data = null;
try {
data = (MetaData) metaData.clone();
data.setDatabaseName(Constants.HSSYSDB);
} catch (CloneNotSupportedException e) {
LOGGER.warn("", e);
return Constants.FAILURE;
}
List<String> createTables = dbConfig.getCreateSysTables();
return createDB(createTables, data);
}
/**
* (non-Javadoc)
* @see net.heartsome.cat.database.SystemDBOperator#checkDbConnection()
*/
public boolean checkDbConnection() {
return true;
}
/**
* 检查 dbName 是否存在
* @param dbName
* @return ;
*/
private boolean checkDBIsExist(String dbName) {
String path = metaData.getDataPath() + File.separator + dbName;
File file = new File(path);
return file.exists() && file.isFile();
}
/**
* (non-Javadoc)
* @see net.heartsome.cat.database.SystemDBOperator#checkSysDb()
*/
public boolean checkSysDb() {
return true;
// return checkDBIsExist(Constants.HSSYSDB);
}
public void addSysDb(String dbName, String quality, int type) {
MetaData data = null;
try {
data = (MetaData) metaData.clone();
data.setDatabaseName(Constants.HSSYSDB);
} catch (CloneNotSupportedException e) {
LOGGER.warn("", e);
return;
}
String driver = dbConfig.getDriver();
String url = Utils.replaceParams(dbConfig.getDbURL(), data);
url = url.replace("__FILE_SEPARATOR__", File.separator);
Properties prop = Utils.replaceParams(dbConfig.getConfigProperty(), data);
PreparedStatement stmt = null;
try {
conn = getConnection(driver, url, prop);
String insertDb = Utils.replaceParams(dbConfig.getInsertSysDb(), data);
stmt = conn.prepareStatement(insertDb);
stmt.setString(1, dbName);
stmt.setString(2, quality);
stmt.setInt(3, type);
stmt.execute();
} catch (ClassNotFoundException e) {
LOGGER.warn("", e);
} catch (SQLException e) {
LOGGER.warn("", e);
} finally {
freeConnection(stmt, conn);
}
}
/**
* 删除系统库中保存的指定的数据库
* @param dbName
* @throws SQLException
*/
public void removeSysDb(String dbName) throws SQLException {
PreparedStatement pstmt = null;
String driver = dbConfig.getDriver();
metaData.setDatabaseName(Constants.HSSYSDB);
String url = Utils.replaceParams(dbConfig.getDbURL(), metaData);
url = url.replace("__FILE_SEPARATOR__", File.separator);
Properties prop = Utils.replaceParams(dbConfig.getConfigProperty(), metaData);
// 删除系统表中的数据
prop = Utils.replaceParams(dbConfig.getConfigProperty(), metaData);
try {
conn = getConnection(driver, url, prop);
String removeDb = dbConfig.getRemoveSysDb();
pstmt = conn.prepareStatement(removeDb);
pstmt.setString(1, dbName);
pstmt.execute();
} catch (ClassNotFoundException e) {
LOGGER.warn("", e);
} finally {
freeConnection(pstmt, conn);
}
}
/**
* 得到系统库中的存储的数据库名称
* @return
* @throws SQLException
*/
public List<String> getSysDbNames(int type) {
MetaData data = null;
try {
data = (MetaData) metaData.clone();
data.setDatabaseName(Constants.HSSYSDB);
} catch (CloneNotSupportedException e) {
LOGGER.warn("", e);
return null;
}
String driver = dbConfig.getDriver();
String url = Utils.replaceParams(dbConfig.getDbURL(), data);
url = url.replace("__FILE_SEPARATOR__", File.separator);
Properties prop = Utils.replaceParams(dbConfig.getConfigProperty(), data);
PreparedStatement stmt = null;
ResultSet rs = null;
List<String> result = new ArrayList<String>();
try {
conn = getConnection(driver, url, prop);
String sql = dbConfig.getSysDbList();
stmt = conn.prepareStatement(sql);
stmt.setInt(1, type);
rs = stmt.executeQuery();
while (rs.next()) {
result.add(rs.getString("DBNAME"));
}
} catch (ClassNotFoundException e) {
LOGGER.warn("", e);
} catch (SQLException e) {
LOGGER.warn("", e);
} finally {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
LOGGER.warn("", e);
}
}
freeConnection(stmt, conn);
}
return result;
}
/**
* (non-Javadoc)
* @see net.heartsome.cat.database.SystemDBOperator#dropDb(java.lang.String)
*/
public void dropDb(String dbName) throws SQLException {
if (checkDBIsExist(dbName)) {
boolean isDelete = new File(metaData.getDataPath() + File.separator + dbName).delete();
if (!isDelete) {
throw new SQLException(Messages.getString("sqlite.OperateSystemDBImpl.errorMsg1"));
}
}
}
/**
* (non-Javadoc)
* @see net.heartsome.cat.database.SystemDBOperator#checkDbExistOnServer()
*/
public boolean checkDbExistOnServer() {
return checkDBIsExist(metaData.getDatabaseName());
}
/**
* (non-Javadoc)
* @see net.heartsome.cat.database.SystemDBOperator#getConnection(java.lang.String, java.lang.String,
* java.util.Properties)
*/
protected synchronized Connection getConnection(String driver, String url, Properties p)
throws ClassNotFoundException, SQLException {
if (conn != null && !conn.isClosed()) {
if (!conn.getAutoCommit()) {
conn.commit();
}
conn.close();
}
Class.forName(driver);
SQLiteConfig config = new SQLiteConfig(p);
return config.createConnection(url);
}
protected void freeConnection(Statement stmt, Connection conn) {
if (stmt != null) {
try {
stmt.close();
} catch (SQLException e) {
LOGGER.warn("", e);
}
}
try {
if (conn != null && !conn.isClosed()) {
if (!conn.getAutoCommit()) {
conn.commit();
}
conn.close();
}
} catch (SQLException e) {
LOGGER.warn("", e);
}
}
/**
* 创建库时,创建目录如果目录不存在
* ;
*/
private void createDirs(){
String filePath = metaData.getDataPath();
if(null == filePath || filePath.isEmpty()){
return ;
}
File file = new File(filePath);
if(!file.exists()){
file.mkdirs();
}
}
}
| 8,743 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
DbServiceProviderImpl.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/database/net.heartsome.cat.database.sqlite/src/net/heartsome/cat/database/sqlite/DbServiceProviderImpl.java | package net.heartsome.cat.database.sqlite;
import net.heartsome.cat.database.DBOperator;
import net.heartsome.cat.database.DBServiceProvider;
import net.heartsome.cat.database.SystemDBOperator;
/**
*
* @author peason
* @version
* @since JDK1.6
*/
public class DbServiceProviderImpl implements DBServiceProvider {
public DBOperator getTmDatabaseInstance() {
return new TMDatabaseImpl();
}
public SystemDBOperator getOperateDBInstance() {
return new OperateSystemDBImpl();
}
}
| 498 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
Messages.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/database/net.heartsome.cat.database.sqlite/src/net/heartsome/cat/database/sqlite/resource/Messages.java | package net.heartsome.cat.database.sqlite.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.database.sqlite.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 + '!';
}
}
}
| 871 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
Activator.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/database/net.heartsome.cat.database.ui/src/net/heartsome/cat/database/ui/Activator.java | package net.heartsome.cat.database.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 {
/** 插件的 ID */
public static final String PLUGIN_ID = "net.heartsome.cat.database.ui";
/** 插件的上下文 */
public static BundleContext context;
// 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;
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;
}
/**
* 提供一个图片文件对插件的相对路径,返回该图片的描述信息。
* @param path
* 图片资源对插件的相对路径。
* @return the image descriptor
*/
public static ImageDescriptor getImageDescriptor(String path) {
return imageDescriptorFromPlugin(PLUGIN_ID, path);
}
}
| 1,505 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
DatabaseManagerDbListBean.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/database/net.heartsome.cat.database.ui/src/net/heartsome/cat/database/ui/bean/DatabaseManagerDbListBean.java | /**
* DatabaseManagerDbListBean.java
*
* Version information :
*
* Date:Dec 2, 2011
*
* Copyright notice :
* 本文件及其附带的相关文件包含机密信息,仅限瀚特盛科技有限公司指定的,与本项目有关的内部人员和客户联络人员查阅和使用。
* 如果您不是本保密声明中指定的收件者,请立即销毁本文件,禁止对本文件或根据本文件中的内容采取任何其他行动,
* 包括但不限于:泄露本文件中的信息、以任何方式制作本文件全部或部分内容之副本、将本文件或其相关副本提供给任何其他人。
*/
package net.heartsome.cat.database.ui.bean;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
/**
* @author Jason
* @version
* @since JDK1.6
*/
public class DatabaseManagerDbListBean implements PropertyChangeListener {
private String index;
private String dbName;
private String langs;
private PropertyChangeSupport propertyChangeSupport = new PropertyChangeSupport(this);
/** @return the index */
public String getIndex() {
return index;
}
/**
* @param index
* the index to set
*/
public void setIndex(String index) {
propertyChangeSupport.firePropertyChange("index", this.index, this.index = index);
}
/** @return the dbName */
public String getDbName() {
return dbName;
}
/**
* @param dbName
* the dbName to set
*/
public void setDbName(String dbName) {
propertyChangeSupport.firePropertyChange("dbName", this.dbName, this.dbName = dbName);
}
/** @return the langs ,所有code以逗号连接,可能在语言的前后包含有空格*/
public String getLangs() {
return langs;
}
/**
* @param langs
* the langs to set
*/
public void setLangs(String langs) {
propertyChangeSupport.firePropertyChange("langs", this.langs, this.langs = langs);
}
public void propertyChange(PropertyChangeEvent arg0) {
}
public void addPropertyChangeListener(String propertyName, PropertyChangeListener listener) {
propertyChangeSupport.addPropertyChangeListener(propertyName, listener);
}
public void removePropertyChangeListener(PropertyChangeListener listener) {
propertyChangeSupport.removePropertyChangeListener(listener);
}
}
| 2,331 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
ExportFilterSettingDialog.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/database/net.heartsome.cat.database.ui/src/net/heartsome/cat/database/ui/dialog/ExportFilterSettingDialog.java | /**
* ExportFilterSettingDialog.java
*
* Version information :
*
* Date:Dec 7, 2011
*
* Copyright notice :
* 本文件及其附带的相关文件包含机密信息,仅限瀚特盛科技有限公司指定的,与本项目有关的内部人员和客户联络人员查阅和使用。
* 如果您不是本保密声明中指定的收件者,请立即销毁本文件,禁止对本文件或根据本文件中的内容采取任何其他行动,
* 包括但不限于:泄露本文件中的信息、以任何方式制作本文件全部或部分内容之副本、将本文件或其相关副本提供给任何其他人。
*/
package net.heartsome.cat.database.ui.dialog;
import java.util.ArrayList;
import java.util.List;
import net.heartsome.cat.database.bean.ExportFilterBean;
import net.heartsome.cat.database.bean.ExportFilterComponentBean;
import net.heartsome.cat.database.ui.core.ExportFilterStoreConfiger;
import net.heartsome.cat.database.ui.resource.Messages;
import org.eclipse.core.runtime.Assert;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.ScrolledComposite;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ExportFilterSettingDialog extends Dialog {
public static final Logger logger = LoggerFactory.getLogger(ExportFilterSettingDialog.class);
private Text filterNameText;
private Composite dynaComposite;
private Button isAllCbtn;
private Button isAnyCbtn;
private String ruleType = "TMX"; // 默认为TMX
private ExportFilterBean currentFilter;
private ExportFilterStoreConfiger filterStore;
/**
* 创建对话框
* @param parentShell
* @param ruleType
* 过滤规则设置用途,必须为"TMX"或者"TBX"
*/
public ExportFilterSettingDialog(Shell parentShell, String ruleType) {
super(parentShell);
Assert.isLegal(ruleType.equals("TMX") || ruleType.equals("TBX"),
Messages.getString("dialog.ExportFilterSettingDialog.msg1"));
this.ruleType = ruleType;
}
@Override
protected void configureShell(Shell newShell) {
super.configureShell(newShell);
newShell.setText(Messages.getString("dialog.ExportFilterSettingDialog.title"));
}
protected boolean isResizable() {
return true;
}
/**
* Create contents of the dialog.
* @param parent
*/
@Override
protected Control createDialogArea(Composite parent) {
Composite container = (Composite) super.createDialogArea(parent);
container.setLayout(new GridLayout(1, false));
Composite composite = new Composite(container, SWT.NONE);
composite.setLayout(new GridLayout(2, false));
composite.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
Label filterNameLabel = new Label(composite, SWT.NONE);
filterNameLabel.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
filterNameLabel.setText(Messages.getString("dialog.ExportFilterSettingDialog.filterNameLabel"));
filterNameText = new Text(composite, SWT.BORDER);
filterNameText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
Composite optionComposite = new Composite(container, SWT.NONE);
optionComposite.setLayout(new GridLayout(2, false));
optionComposite.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
isAllCbtn = new Button(optionComposite, SWT.RADIO);
isAllCbtn.setSize(152, 26);
isAllCbtn.setText(Messages.getString("dialog.ExportFilterSettingDialog.isAllCbtn"));
isAllCbtn.setSelection(true);
isAnyCbtn = new Button(optionComposite, SWT.RADIO);
isAnyCbtn.setText(Messages.getString("dialog.ExportFilterSettingDialog.isAnyCbtn"));
ScrolledComposite scrolledComposite = new ScrolledComposite(container, SWT.V_SCROLL | SWT.BORDER);
scrolledComposite.setAlwaysShowScrollBars(false);
scrolledComposite.setLayoutData(new GridData(GridData.FILL_BOTH));
scrolledComposite.setExpandHorizontal(true);
scrolledComposite.setExpandVertical(true);
dynaComposite = new Composite(scrolledComposite, SWT.NONE);
dynaComposite.setBackground(Display.getDefault().getSystemColor((SWT.COLOR_WHITE)));
scrolledComposite.setContent(dynaComposite);
scrolledComposite.setMinSize(dynaComposite.computeSize(SWT.DEFAULT, SWT.DEFAULT));
GridLayout gl_dynaComposite = new GridLayout(1, false);
dynaComposite.setLayout(gl_dynaComposite);
ExportFilterComposite exportFilterComponent = new ExportFilterComposite(dynaComposite, SWT.None, ruleType);
exportFilterComponent.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
exportFilterComponent.setDeleteButtonEnabled(false);
dynaComposite.setData("currentNumber", 1);
scrolledComposite.setMinSize(dynaComposite.computeSize(SWT.DEFAULT, SWT.DEFAULT));
initData();
return container;
}
private void initData() {
if (this.currentFilter != null) {
Control[] c = dynaComposite.getChildren();
for (int i = 0; i < c.length; i++) {
c[i].dispose();
}
filterNameText.setText(currentFilter.getFilterName());
String filterConnector = currentFilter.getFilterConnector();
if (filterConnector.equals("AND")) {
isAllCbtn.setSelection(true);
isAnyCbtn.setSelection(false);
} else {
isAllCbtn.setSelection(false);
isAnyCbtn.setSelection(true);
}
List<ExportFilterComponentBean> optionList = currentFilter.getFilterOption();
if (optionList.size() > 0) {
ExportFilterComponentBean bean = optionList.get(0);
ExportFilterComposite exportFilterComponent = new ExportFilterComposite(dynaComposite, SWT.None,
ruleType, bean);
exportFilterComponent.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
exportFilterComponent.setDeleteButtonEnabled(false);
dynaComposite.setData("currentNumber", 1);
for (int i = 1; i < optionList.size(); i++) {
bean = optionList.get(i);
exportFilterComponent.addComponent(dynaComposite, bean);
}
}
}
}
@Override
protected void okPressed() {
String filterName = this.filterNameText.getText();
if (filterName == null || filterName.equals("")) {
MessageDialog.openInformation(getShell(), Messages.getString("dialog.ExportFilterSettingDialog.msgTitle"),
Messages.getString("dialog.ExportFilterSettingDialog.msg2"));
return;
}
String filterConnector = "AND";
if (isAnyCbtn.getSelection()) {
filterConnector = "OR";
}
List<ExportFilterComponentBean> filterList = new ArrayList<ExportFilterComponentBean>();
Control[] c = dynaComposite.getChildren();
for (int i = 0; i < c.length; i++) {
if (c[i] instanceof ExportFilterComposite) {
ExportFilterComposite comp = (ExportFilterComposite) c[i];
ExportFilterComponentBean bean = comp.getValue();
if (bean.getFilterVlaue() != null && !bean.getFilterVlaue().equals("")) {
filterList.add(bean);
}
}
}
if (currentFilter != null) { // 编辑状态,策略:删除原有的内容,重新执行添加
filterStore.deleteFilterRuleByName(currentFilter.getFilterName(), currentFilter.getFilterType());
}
if (filterStore.isFilterNameExist(filterName, getRuleType())) {
MessageDialog.openInformation(getShell(), Messages.getString("dialog.ExportFilterSettingDialog.msgTitle"),
Messages.getString("dialog.ExportFilterSettingDialog.msg3"));
return;
}
if (filterList.size() == 0) {
logger.error(Messages.getString("dialog.ExportFilterSettingDialog.logger1"));
MessageDialog.openInformation(getShell(), Messages.getString("dialog.ExportFilterSettingDialog.msgTitle"),
Messages.getString("dialog.ExportFilterSettingDialog.msg4"));
return;
}
currentFilter = new ExportFilterBean();
currentFilter.setFilterName(filterName);
currentFilter.setFilterOption(filterList);
currentFilter.setFilterType(getRuleType());
currentFilter.setFilterConnector(filterConnector);
filterStore.saveFilterRule(currentFilter);
super.okPressed();
}
/**
* 获取设置结果
*/
public ExportFilterBean getSettingResult() {
return this.currentFilter;
}
/**
* 设置当前需要编辑的Filter;
* @param currentFilter
* ;
*/
public void setCurrentFilter(ExportFilterBean currentFilter) {
this.currentFilter = currentFilter;
}
/**
* 获取过滤规则类型TMX/TBX
* @return "TMX" - 为TMX过滤规则 "TBX"-为TBX过滤规则
*/
public String getRuleType() {
return ruleType;
}
/**
* @param filterStore
* the filterStore to set
*/
public void setFilterStore(ExportFilterStoreConfiger filterStore) {
this.filterStore = filterStore;
}
/**
* Create contents of the button bar.
* @param parent
*/
@Override
protected void createButtonsForButtonBar(Composite parent) {
createButton(parent, IDialogConstants.OK_ID, IDialogConstants.OK_LABEL, true);
createButton(parent, IDialogConstants.CANCEL_ID, IDialogConstants.CANCEL_LABEL, false);
}
/**
* Return the initial size of the dialog.
*/
@Override
protected Point getInitialSize() {
return new Point(580, 448);
}
}
| 9,462 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
ExportFilterComposite.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/database/net.heartsome.cat.database.ui/src/net/heartsome/cat/database/ui/dialog/ExportFilterComposite.java | package net.heartsome.cat.database.ui.dialog;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import net.heartsome.cat.database.bean.ExportFilterComponentBean;
import net.heartsome.cat.database.ui.resource.Messages;
import org.eclipse.jface.viewers.ArrayContentProvider;
import org.eclipse.jface.viewers.ComboViewer;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.ScrolledComposite;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.DateTime;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Text;
public class ExportFilterComposite extends Composite implements Listener {
private ExportFilterComponentBean baseDataBean;
private String[] filterNames;
private Control valueText;
private ComboViewer conditionComboViewer;
private ComboViewer opratorComboViewer;
private Button addButton;
private Button deleteButton;
private Composite dynaComposite;
private String ruleType;
/**
* Create the composite.
* @param parent
* @param style
*/
public ExportFilterComposite(Composite parent, int style, String ruleType) {
super(parent, style);
this.ruleType = ruleType;
this.baseDataBean = new ExportFilterComponentBean(ruleType);
this.filterNames = baseDataBean.getFilterNames();
this.createContent();
this.initData();
}
public ExportFilterComposite(Composite parent, int style, String ruleType, ExportFilterComponentBean baseDataBean) {
super(parent, style);
this.ruleType = ruleType;
this.baseDataBean = baseDataBean;
this.filterNames = baseDataBean.getFilterNames();
this.createContent();
this.initData();
}
public void handleEvent(Event event) {
Composite parent = this.getParent();
Composite topParent = parent.getParent();
if (event.widget == addButton) { // add button
ExportFilterComponentBean bean = new ExportFilterComponentBean(this.ruleType);
bean.setOptionName(this.baseDataBean.getOptionName());
bean.setCurrentExpression(this.baseDataBean.getCurrentExpression());
addComponent(parent, bean);
} else if (event.widget == deleteButton) { // delete button
this.dispose();
Integer number = (Integer) parent.getData("currentNumber") - 1;
parent.setData("currentNumber", number);
if (number == 1) {
Control c = parent.getChildren()[0];
if (c instanceof ExportFilterComposite) {
ExportFilterComposite temp = (ExportFilterComposite) c;
temp.setDeleteButtonEnabled(false);
}
}
}
if (topParent instanceof ScrolledComposite) {
((ScrolledComposite) topParent).setMinSize(parent.computeSize(SWT.DEFAULT, SWT.DEFAULT));
}
parent.layout(true);
}
/**
* 增加一个组件
* @param parent
* 组件容器
* @param bean
* {@link ExportFilterComponentBean};
*/
public void addComponent(Composite parent, ExportFilterComponentBean bean) {
Integer number = (Integer) parent.getData("currentNumber") + 1;
parent.setData("currentNumber", number);
if (number == 2) {
Control c = parent.getChildren()[0];
if (c instanceof ExportFilterComposite) {
ExportFilterComposite temp = (ExportFilterComposite) c;
temp.setDeleteButtonEnabled(true);
}
}
ExportFilterComposite tempComponent = new ExportFilterComposite(parent, SWT.None, this.ruleType, bean);
tempComponent.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
}
/**
* 初始化数据
*/
private void initData() {
// 过滤规则名称 此方法设置选中将不会触发viewer的selectionChanged事件
String[] options = baseDataBean.getFilterNames();
String currentOption = baseDataBean.getOptionName();
for (int i = 0; i < options.length; i++) {
if (currentOption.equals(options[i])) {
conditionComboViewer.getCombo().select(i);
break;
}
}
// conditionComboViewer.setSelection(new StructuredSelection(baseDataBean.getOptionName()));
// 过滤条件
opratorComboViewer.setSelection(new StructuredSelection(baseDataBean.getCurrentExpression()));
handlerFilterChangedEvent();
}
/** 创建控件 */
private void createContent() {
setBackground(Display.getDefault().getSystemColor(SWT.COLOR_WHITE));
GridLayout gridLayout = new GridLayout(5, false);
gridLayout.horizontalSpacing = 2;
gridLayout.marginWidth = 0;
gridLayout.marginHeight = 0;
setLayout(gridLayout);
conditionComboViewer = new ComboViewer(this, SWT.NONE | SWT.READ_ONLY);
Combo conditionCombo = conditionComboViewer.getCombo();
GridData gdConditionCombo = new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1);
gdConditionCombo.widthHint = 200;
conditionCombo.setLayoutData(gdConditionCombo);
conditionComboViewer.setContentProvider(new ArrayContentProvider());
conditionComboViewer.setInput(filterNames);
conditionComboViewer.addSelectionChangedListener(new ISelectionChangedListener() {
public void selectionChanged(SelectionChangedEvent event) {
IStructuredSelection sel = (IStructuredSelection) event.getSelection();
if (sel.isEmpty()) {
return;
}
baseDataBean.setOptionName((String) sel.getFirstElement());
handlerFilterChangedEvent();
opratorComboViewer.setInput(baseDataBean.getCurrentFilterExpressions());
opratorComboViewer.getCombo().select(0); // 默认选中第一个
baseDataBean.setCurrentExpression(opratorComboViewer.getCombo().getText());
}
});
opratorComboViewer = new ComboViewer(this, SWT.NONE | SWT.READ_ONLY);
Combo opratorCombo = opratorComboViewer.getCombo();
GridData gd_opratorCombo = new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1);
gd_opratorCombo.widthHint = 100;
opratorCombo.setLayoutData(gd_opratorCombo);
opratorComboViewer.setContentProvider(new ArrayContentProvider());
opratorComboViewer.setInput(this.baseDataBean.getCurrentFilterExpressions());
opratorComboViewer.addSelectionChangedListener(new ISelectionChangedListener() {
public void selectionChanged(SelectionChangedEvent event) {
IStructuredSelection sel = (IStructuredSelection) event.getSelection();
if (sel.isEmpty()) {
return;
}
baseDataBean.setCurrentExpression((String) sel.getFirstElement());
}
});
dynaComposite = new Composite(this, SWT.NONE);
dynaComposite.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
GridLayout gldynaComposite = new GridLayout(1, false);
gldynaComposite.marginWidth = 0;
gldynaComposite.marginHeight = 0;
dynaComposite.setLayout(gldynaComposite);
valueText = new Text(dynaComposite, SWT.BORDER);
valueText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
addButton = new Button(this, SWT.NONE);
GridData gdAddButton = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1);
gdAddButton.widthHint = 25;
addButton.setLayoutData(gdAddButton);
addButton.setText("+");
addButton.addListener(SWT.Selection, this);
deleteButton = new Button(this, SWT.NONE);
GridData gdDeletebutton = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1);
gdDeletebutton.widthHint = 25;
deleteButton.setLayoutData(gdDeletebutton);
deleteButton.setText("-");
deleteButton.addListener(SWT.Selection, this);
}
/**
* 处理过滤条件发生变化时动态创建组件 ;
*/
private void handlerFilterChangedEvent() {
String optionName = baseDataBean.getOptionName();
String value = baseDataBean.getFilterVlaue();
if (optionName.equals(Messages.getString("dialog.ExportFilterComposite.creationDate"))
|| optionName.equals(Messages.getString("dialog.ExportFilterComposite.changeDate"))) {
if (!valueText.isDisposed()) {
valueText.dispose();
}
DateTime valueTextDateTime = new DateTime(dynaComposite, SWT.DATE | SWT.BORDER);
if (value != null) {
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
try {
Calendar c = Calendar.getInstance();
c.setTime(df.parse(value));
valueTextDateTime.setDate(c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DATE));
} catch (Exception ex) {
ex.printStackTrace();
}
}
valueText = valueTextDateTime;
} else {
if (!valueText.isDisposed()) {
valueText.dispose();
}
valueText = new Text(dynaComposite, SWT.BORDER);
if (value != null) {
((Text) valueText).setText(value);
}
}
valueText.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));
dynaComposite.layout(true);
}
/**
* 设置增加按钮是否可用
* @param enabled
* true-可用,false-不可用;
*/
public void setAddButtonEnabled(boolean enabled) {
this.addButton.setEnabled(enabled);
}
/**
* 设置删除按钮是否可用
* @param enabled
* true-可用,false-不可用;
*/
public void setDeleteButtonEnabled(boolean enabled) {
this.deleteButton.setEnabled(enabled);
}
/**
* 获取当前过滤条件的值
* @return ;
*/
public ExportFilterComponentBean getValue() {
if (valueText instanceof Text) {
this.baseDataBean.setFilterVlaue(((Text) valueText).getText());
}
else if (valueText instanceof DateTime) {
DateTime temp = (DateTime) valueText;
StringBuffer bf = new StringBuffer();
bf.append(temp.getYear());
bf.append("-");
DecimalFormat df = new DecimalFormat("00");
bf.append(df.format(temp.getMonth() + 1));
bf.append("-");
bf.append(df.format(temp.getDay()));
bf.append(" 00:00:00"); // 补全时间
this.baseDataBean.setFilterVlaue(bf.toString());
}
return this.baseDataBean;
}
}
| 10,000 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
DatabaseConfiger.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/database/net.heartsome.cat.database.ui/src/net/heartsome/cat/database/ui/core/DatabaseConfiger.java | /**
* DatabaseConfiger.java
*
* Version information :
*
* Date:Dec 1, 2011
*
* Copyright notice :
* 本文件及其附带的相关文件包含机密信息,仅限瀚特盛科技有限公司指定的,与本项目有关的内部人员和客户联络人员查阅和使用。
* 如果您不是本保密声明中指定的收件者,请立即销毁本文件,禁止对本文件或根据本文件中的内容采取任何其他行动,
* 包括但不限于:泄露本文件中的信息、以任何方式制作本文件全部或部分内容之副本、将本文件或其相关副本提供给任何其他人。
*/
package net.heartsome.cat.database.ui.core;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import net.heartsome.cat.common.bean.DatabaseModelBean;
import net.heartsome.cat.common.bean.MetaData;
import net.heartsome.cat.database.ui.resource.Messages;
import net.heartsome.xml.vtdimpl.VTDUtils;
import org.eclipse.core.resources.ResourcesPlugin;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import cn.org.tools.utils.encrypt.DESImpl;
import com.ximpleware.AutoPilot;
import com.ximpleware.ModifyException;
import com.ximpleware.NavException;
import com.ximpleware.ParseException;
import com.ximpleware.TranscodeException;
import com.ximpleware.VTDGen;
import com.ximpleware.XMLModifier;
import com.ximpleware.XPathEvalException;
import com.ximpleware.XPathParseException;
/**
* 数据库服务器配置文件管理
* @author Jason
* @version
* @since JDK1.6
*/
public class DatabaseConfiger {
private VTDUtils vu;
private File serverConfigFile;
private AutoPilot ap;
private static final Logger logger = LoggerFactory.getLogger(DatabaseConfiger.class);
/**
* 构造器,如果文件不存在先构建文件,再用vtd解析.
*/
public DatabaseConfiger() {
initResource();
VTDGen vg = new VTDGen();
try {
if (vg.parseFile(serverConfigFile.getPath(), true)) {
vu = new VTDUtils(vg.getNav());
ap = new AutoPilot(vu.getVTDNav());
} else {
throw new ParseException();
}
} catch (NavException e) {
logger.error("", e);
} catch (ParseException e) {
logger.error("", e);
}
}
/**
* 初始化资源。主要判断存储的文件存不存在,如果不存在则创建
*/
private void initResource() {
String path = checkConfigDirectory(".config");
File dbListFile = new File(path + System.getProperty("file.separator") + ".servers");
if (!dbListFile.exists() || dbListFile.isDirectory()) {
try {
FileOutputStream fos = new FileOutputStream(dbListFile);
BufferedOutputStream bos = new BufferedOutputStream(fos);
StringBuffer bf = new StringBuffer();
bf.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
bf.append("<servers>");
bf.append("</servers>");
bos.write(bf.toString().getBytes());
bos.close();
fos.close();
} catch (IOException e) {
logger.error(Messages.getString("core.DatabaseConfiger.logger1"), e);
}
}
this.serverConfigFile = dbListFile;
}
/**
* 检查配置文件存放目录.如果不存在则创建
* @param cfgDirName
* 需要检查目录的名称
* @return ;
*/
private String checkConfigDirectory(String cfgDirName) {
String workspacePath = ResourcesPlugin.getWorkspace().getRoot().getLocation().toString();
workspacePath = workspacePath + System.getProperty("file.separator") + cfgDirName;
File dbListFolder = new File(workspacePath);
if (!dbListFolder.exists() || dbListFolder.isFile()) {
dbListFolder.mkdirs();
}
return workspacePath;
}
/**
* 更新指定id的server配置信息
* @param id
* @param serverBean
* ;
*/
public void updateServerConfigById(String id, DatabaseModelBean serverBean) {
String newValue = generateServerNode(serverBean.getDbType(), serverBean);
XMLModifier xm = vu.update("/servers/server[@id='" + id + "']", newValue);
try {
vu.bind(xm.outputAndReparse());
saveToFile(xm, serverConfigFile);
} catch (Exception e) {
logger.error(Messages.getString("core.DatabaseConfiger.logger2"), e);
}
}
/**
* 删除指定id的服务器配置信息
* @param id
* 服务器配置信息id;
*/
public void deleteServerById(String id) {
if (id != null && !id.equals("")) {
try {
XMLModifier xm = vu.delete("/servers/server[@id='" + id + "']");
vu.bind(xm.outputAndReparse());
saveToFile(xm, serverConfigFile);
} catch (Exception e) {
logger.error(Messages.getString("core.DatabaseConfiger.logger3"), e);
}
}
}
/**
* 添加一个全新的服务器到配置文件
* @param serverBean
* ;
*/
public void addServerConfig(DatabaseModelBean serverBean) {
serverBean.setId(this.generateServerId());
String content = generateServerNode(serverBean.getDbType(), serverBean);
if (!content.equals("")) {
try {
XMLModifier xm = vu.insert("/servers/text()", content.toString());
vu.bind(xm.outputAndReparse());
saveToFile(xm, serverConfigFile);
} catch (Exception e) {
logger.error("", e);
}
ap.resetXPath();
}
}
/**
* 获取数据库服务器配置文件中保存的所有服务器信息
* @return Map<数据库类型,List<数据库配置信息> 参考{@link DatabaseModelBean};
*/
public Map<String, List<DatabaseModelBean>> getAllServerConfig() {
Map<String, List<DatabaseModelBean>> map = new HashMap<String, List<DatabaseModelBean>>();
try {
AutoPilot tempAp = new AutoPilot(vu.getVTDNav());
tempAp.selectXPath("/servers/server");
while (tempAp.evalXPath() != -1) {
String type = vu.getCurrentElementAttribut("type", "");
if (map.containsKey(type)) {
continue;
} else {
map.put(type, getServersConfigByType(type));
}
}
} catch (XPathParseException e) {
logger.error("", e);
} catch (XPathEvalException e) {
logger.error("", e);
} catch (NavException e) {
logger.error("", e);
}
return map;
}
/**
* 获取指定类型数据库的所有服务器配置信息
* @param type
* 数据库类型
* @return ;
*/
public List<DatabaseModelBean> getServersConfigByType(String type) {
List<DatabaseModelBean> list = new ArrayList<DatabaseModelBean>();
try {
vu.getVTDNav().push();
ap.selectXPath("/servers/server[@type='" + type + "']");
while (ap.evalXPath() != -1) {
DatabaseModelBean dbm = new DatabaseModelBean();
dbm.setId(vu.getCurrentElementAttribut("id", ""));
dbm.setItlDBLocation(vu.getChildContent("location"));
dbm.setInstance(vu.getChildContent("instance"));
dbm.setHost(vu.getChildContent("host"));
dbm.setPort(vu.getChildContent("port"));
dbm.setUserName(vu.getChildContent("user"));
dbm.setPassword(DESImpl.decrypt(vu.getChildContent("password")));
dbm.setDbType(type);
list.add(dbm);
}
ap.resetXPath();
vu.getVTDNav().pop();
} catch (XPathParseException e) {
logger.error("", e);
} catch (XPathEvalException e) {
logger.error("", e);
} catch (NavException e) {
logger.error("", e);
}
return list;
}
/**
* 生成配置文件中的<server>节点
* @param type
* 数据库类型
* @param serverBean
* 服务器配置信息
* @return 生成的内容文本;
*/
private String generateServerNode(String type, DatabaseModelBean serverBean) {
StringBuffer content = new StringBuffer();
content.append("<server type='" + type + "' id='" + serverBean.getId() + "'>");
content.append("<location>");
content.append(serverBean.getItlDBLocation());
content.append("</location>");
content.append("<instance>");
content.append(serverBean.getInstance());
content.append("</instance>");
content.append("<host>");
content.append(serverBean.getHost());
content.append("</host>");
content.append("<port>");
content.append(serverBean.getPort());
content.append("</port>");
content.append("<user>");
content.append(serverBean.getUserName());
content.append("</user>");
content.append("<password>");
content.append(DESImpl.encrypt(serverBean.getPassword()));
content.append("</password>");
content.append("</server>");
return content.toString();
}
/**
* 生成Server配置ID
* @return 一个字符串,当前操作系统中唯一 ;
*/
public String generateServerId() {
StringBuffer bf = new StringBuffer();
bf.append(System.currentTimeMillis());
bf.append(new Random().nextInt(10000));
return bf.toString();
}
/**
* 判断是否存在相同的服务器.存在则返加id
* @param xpath
* 需要查询的Server的xpath
* @return ;
*/
private String existServer(String xpath) {
try {
ap = new AutoPilot(vu.getVTDNav());
ap.selectXPath("/servers/server[" + xpath + "]");
if (ap.evalXPath() != -1) {
return vu.getCurrentElementAttribut("id", "");
}
} catch (Exception e) {
logger.error(Messages.getString("core.DatabaseConfiger.logger4"), e);
}
return "";
}
/**
* 根据当前的数据库类型,生成XPATH,并调用{@link DatabaseConfiger}中判断服务器在配置文件中是否存在
* @param bean
* 需要检查是否存在的服务器配置信息
* @param metaData
* 数据库元数据
* @return 存在返回当前配置信息在文件中的id;
*/
public String isServerExist(DatabaseModelBean bean, MetaData metaData) {
List<String> xpaths = new ArrayList<String>();
if (metaData.dataPathSupported()) {
xpaths.add("location='" + bean.getItlDBLocation() + "'");
}
if (metaData.serverNameSupported()) {
xpaths.add("host='" + bean.getHost() + "'");
}
if (metaData.portSupported()) {
xpaths.add("port='" + bean.getPort() + "'");
}
if (metaData.instanceSupported()) {
xpaths.add("instance='" + bean.getInstance() + "'");
}
StringBuffer bf = new StringBuffer();
for (int i = 0; i < xpaths.size(); i++) {
bf.append(xpaths.get(i));
if (i != xpaths.size() - 1) {
bf.append(" and ");
}
}
return existServer(bf.toString());
}
/**
* 保存文件
* @param xm
* XMLModifier对象
* @param fileName
* 文件名
* @return 是否保存成功;
*/
private boolean saveToFile(XMLModifier xm, File file) {
try {
FileOutputStream fos = new FileOutputStream(file);
BufferedOutputStream bos = new BufferedOutputStream(fos);
xm.output(bos); // 写入文件
bos.close();
fos.close();
return true;
} catch (ModifyException e) {
logger.error("", e);
e.printStackTrace();
} catch (TranscodeException e) {
logger.error("", e);
e.printStackTrace();
} catch (IOException e) {
logger.error("", e);
e.printStackTrace();
}
return false;
}
} | 10,877 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
DbValidator.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/database/net.heartsome.cat.database.ui/src/net/heartsome/cat/database/ui/core/DbValidator.java | /**
* DbValidator.java
*
* Version information :
*
* Date:2012-8-14
*
* Copyright notice :
* 本文件及其附带的相关文件包含机密信息,仅限瀚特盛科技有限公司指定的,与本项目有关的内部人员和客户联络人员查阅和使用。
* 如果您不是本保密声明中指定的收件者,请立即销毁本文件,禁止对本文件或根据本文件中的内容采取任何其他行动,
* 包括但不限于:泄露本文件中的信息、以任何方式制作本文件全部或部分内容之副本、将本文件或其相关副本提供给任何其他人。
*/
package net.heartsome.cat.database.ui.core;
import net.heartsome.cat.database.ui.resource.Messages;
/**
* @author Jason
* @version
* @since JDK1.6
*/
public class DbValidator {
public static String valiateDbName(String dbName){
if(dbName == null){
return Messages.getString("dialog.inputdbname.msg2");
}
if(!dbName.matches("^([a-zA-Z])([a-zA-Z0-9_]){3,14}$")){
return Messages.getString("dialog.inputdbname.msg1");
}
return null;
}
public static void main(String[] args) {
String t = "aaa";
System.out.println(valiateDbName(t));
}
}
| 1,194 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
ExportFilterStoreConfiger.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/database/net.heartsome.cat.database.ui/src/net/heartsome/cat/database/ui/core/ExportFilterStoreConfiger.java | /**
* ExportFilterStoreConfiger.java
*
* Version information :
*
* Date:Feb 16, 2012
*
* Copyright notice :
* 本文件及其附带的相关文件包含机密信息,仅限瀚特盛科技有限公司指定的,与本项目有关的内部人员和客户联络人员查阅和使用。
* 如果您不是本保密声明中指定的收件者,请立即销毁本文件,禁止对本文件或根据本文件中的内容采取任何其他行动,
* 包括但不限于:泄露本文件中的信息、以任何方式制作本文件全部或部分内容之副本、将本文件或其相关副本提供给任何其他人。
*/
package net.heartsome.cat.database.ui.core;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import net.heartsome.cat.database.bean.ExportFilterBean;
import net.heartsome.cat.database.bean.ExportFilterComponentBean;
import net.heartsome.cat.database.ui.resource.Messages;
import net.heartsome.xml.vtdimpl.VTDUtils;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.Assert;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.ximpleware.AutoPilot;
import com.ximpleware.ModifyException;
import com.ximpleware.NavException;
import com.ximpleware.ParseException;
import com.ximpleware.TranscodeException;
import com.ximpleware.VTDGen;
import com.ximpleware.XMLModifier;
import com.ximpleware.XPathEvalException;
import com.ximpleware.XPathParseException;
/**
* @author Jason
* @version
* @since JDK1.6
*/
public class ExportFilterStoreConfiger {
private VTDUtils vu;
private File filterConfigFile;
private AutoPilot ap;
private static final Logger logger = LoggerFactory.getLogger(ExportFilterStoreConfiger.class);
public ExportFilterStoreConfiger() {
initResource();
VTDGen vg = new VTDGen();
try {
if (vg.parseFile(filterConfigFile.getPath(), true)) {
vu = new VTDUtils(vg.getNav());
ap = new AutoPilot(vu.getVTDNav());
} else {
throw new ParseException();
}
} catch (NavException e) {
logger.error("", e);
} catch (ParseException e) {
logger.error("", e);
}
}
/**
* 初始化资源。主要判断存储的文件存不存在,如果不存在则创建
*/
private void initResource() {
String path = checkConfigDirectory(".config");
File dbListFile = new File(path + System.getProperty("file.separator") + ".exportFilter");
if (!dbListFile.exists() || dbListFile.isDirectory()) {
try {
FileOutputStream fos = new FileOutputStream(dbListFile);
BufferedOutputStream bos = new BufferedOutputStream(fos);
StringBuffer bf = new StringBuffer();
bf.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
bf.append("<filter>");
bf.append("<tmx>");
bf.append("</tmx>");
bf.append("<tbx>");
bf.append("</tbx>");
bf.append("</filter>");
bos.write(bf.toString().getBytes());
bos.close();
fos.close();
} catch (IOException e) {
logger.error(Messages.getString("core.ExportFilterStoreConfiger.logger1"), e);
}
}
this.filterConfigFile = dbListFile;
}
/**
* 检查配置文件存放目录.如果不存在则创建
* @param cfgDirName
* 需要检查目录的名称
* @return ;
*/
private String checkConfigDirectory(String cfgDirName) {
String workspacePath = ResourcesPlugin.getWorkspace().getRoot().getLocation().toString();
workspacePath = workspacePath + System.getProperty("file.separator") + cfgDirName;
File dbListFolder = new File(workspacePath);
if (!dbListFolder.exists() || dbListFolder.isFile()) {
dbListFolder.mkdirs();
}
return workspacePath;
}
public void saveFilterRule(ExportFilterBean filter) {
String content = generateContent(filter);
if (!content.equals("")) {
try {
XMLModifier xm = vu.insert("/filter/" + filter.getFilterType() + "/text()", content.toString());
vu.bind(xm.outputAndReparse());
saveToFile(xm, filterConfigFile);
} catch (Exception e) {
logger.error("", e);
}
ap.resetXPath();
}
}
/**
* 检查filterName是否已经存在
* @param filterName
* @param ruleType
* "TMX" 或者 "TBX"
* @return ;
*/
public boolean isFilterNameExist(String filterName, String ruleType) {
Assert.isLegal(ruleType.equals("TMX") || ruleType.equals("TBX"), Messages.getString("core.ExportFilterStoreConfiger.msg1"));
try {
AutoPilot tempAp = new AutoPilot(vu.getVTDNav());
tempAp.selectXPath("/filter/" + ruleType + "/content[@name='" + filterName + "']");
if (tempAp.evalXPath() != -1) {
return true;
}
} catch (XPathParseException e) {
logger.error("", e);
} catch (XPathEvalException e) {
logger.error("", e);
} catch (NavException e) {
logger.error("", e);
}
return false;
}
/**
* 获取过滤规则
* @param ruleType
* "TMX" 或者 "TBX"
* @return 空的集合或者带有内容的集合;
*/
public List<ExportFilterBean> getFilterRule(String ruleType) {
Assert.isLegal(ruleType.equals("TMX") || ruleType.equals("TBX"), Messages.getString("core.ExportFilterStoreConfiger.msg1"));
List<ExportFilterBean> filterList = new ArrayList<ExportFilterBean>();
try {
AutoPilot tempAp = new AutoPilot(vu.getVTDNav());
tempAp.selectXPath("/filter/" + ruleType + "/content");
while (tempAp.evalXPath() != -1) {
Hashtable<String, String> attrs = vu.getCurrentElementAttributs();
ExportFilterBean bean = new ExportFilterBean();
bean.setFilterType(ruleType);
bean.setFilterName(attrs.get("name"));
bean.setFilterConnector(attrs.get("type"));
AutoPilot ap = new AutoPilot(vu.getVTDNav());
ap.selectXPath("./option");
List<ExportFilterComponentBean> cBeanList = new ArrayList<ExportFilterComponentBean>();
while (ap.evalXPath() != -1) {
Hashtable<String, String> oAttrs = vu.getCurrentElementAttributs();
ExportFilterComponentBean cBean = new ExportFilterComponentBean(ruleType);
cBean.setOptionName(oAttrs.get("name"));
cBean.setCurrentExpression(oAttrs.get("operator"));
cBean.setFilterVlaue(oAttrs.get("value"));
cBeanList.add(cBean);
}
if (cBeanList.size() == 0) { // 没有条件的规则无意义
// deleteFilterRuleByName(bean.getFilterName(),ruleType);
continue;
}
bean.setFilterOption(cBeanList);
filterList.add(bean);
}
} catch (XPathParseException e) {
logger.error("", e);
} catch (XPathEvalException e) {
logger.error("", e);
} catch (NavException e) {
logger.error("", e);
}
return filterList;
}
/**
* 删除指定名称的规则
* @param filterName
* 规则名称
* @param ruleType
* "TMX" 或者 "TBX";
*/
public void deleteFilterRuleByName(String filterName, String ruleType) {
Assert.isLegal(!"TMX".equals(ruleType) || !"TBX".equals(ruleType));
if (filterName != null && !filterName.equals("")) {
try {
XMLModifier xm = vu.delete("/filter/" + ruleType + "/content[@name='" + filterName + "']");
vu.bind(xm.outputAndReparse());
saveToFile(xm, filterConfigFile);
} catch (Exception e) {
logger.error(Messages.getString("core.ExportFilterStoreConfiger.logger2"), e);
}
}
}
private String generateContent(ExportFilterBean filter) {
StringBuffer bf = new StringBuffer();
bf.append("<content name=\"" + filter.getFilterName() + "\" type=\"" + filter.getFilterConnector() + "\">");
List<ExportFilterComponentBean> options = filter.getFilterOption();
for (Iterator<ExportFilterComponentBean> iterator = options.iterator(); iterator.hasNext();) {
ExportFilterComponentBean bean = iterator.next();
bf.append("<option name=\"" + bean.getOptionName() + "\" operator=\"" + bean.getCurrentExpression()
+ "\" value=\"" + bean.getFilterVlaue() + "\"/>");
}
bf.append("</content>");
return bf.toString();
}
/**
* 保存文件
* @param xm
* XMLModifier对象
* @param fileName
* 文件名
* @return 是否保存成功;
*/
private boolean saveToFile(XMLModifier xm, File file) {
try {
FileOutputStream fos = new FileOutputStream(file);
BufferedOutputStream bos = new BufferedOutputStream(fos);
xm.output(bos); // 写入文件
bos.close();
fos.close();
return true;
} catch (ModifyException e) {
logger.error("", e);
e.printStackTrace();
} catch (TranscodeException e) {
logger.error("", e);
e.printStackTrace();
} catch (IOException e) {
logger.error("", e);
e.printStackTrace();
}
return false;
}
}
| 8,668 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
ImageConstants.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/database/net.heartsome.cat.database.ui/src/net/heartsome/cat/database/ui/core/ImageConstants.java | /**
* ImageConstants.java
*
* Version information :
*
* Date:2012-4-23
*
* Copyright notice :
*/
package net.heartsome.cat.database.ui.core;
/**
* @author jason
* @version
* @since JDK1.6
*/
public interface ImageConstants {
// 数据库管理模块
String ORACLE = "images/database/db-manage/oracle.png";
String MYSQL = "images/database/db-manage/mysql.png";
String POSTGRESQL = "images/database/db-manage/postgresql.png";
String SQLSERVER = "images/database/db-manage/sqlserver.png";
String INTERNALDB = "images/database/db-manage/internaldb.png";
String IP = "images/database/db-manage/ip.png";
// 新建向导
String CHECKED = "images/database/new-project/checked.gif";
String UNCHECKED = "images/database/new-project/unchecked.gif";
}
| 765 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
Messages.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/database/net.heartsome.cat.database.ui/src/net/heartsome/cat/database/ui/resource/Messages.java | package net.heartsome.cat.database.ui.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.database.ui.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 + '!';
}
}
}
| 903 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
Activator.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/database/net.heartsome.cat.database.ui.tb/src/net/heartsome/cat/database/ui/tb/Activator.java | package net.heartsome.cat.database.ui.tb;
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.database.ui.tb"; //$NON-NLS-1$
// 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;
}
/**
* 提供一个图片文件对插件的相对路径,返回该图片的描述信息。
* @param path
* 图片资源对插件的相对路径。
* @return the image descriptor
*/
public static ImageDescriptor getImageDescriptor(String path) {
return imageDescriptorFromPlugin(PLUGIN_ID, path);
}
}
| 1,428 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
Utils.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/database/net.heartsome.cat.database.ui.tb/src/net/heartsome/cat/database/ui/tb/Utils.java | /**
* Utils.java
*
* Version information :
*
* Date:2013-4-23
*
* Copyright notice :
* 本文件及其附带的相关文件包含机密信息,仅限瀚特盛科技有限公司指定的,与本项目有关的内部人员和客户联络人员查阅和使用。
* 如果您不是本保密声明中指定的收件者,请立即销毁本文件,禁止对本文件或根据本文件中的内容采取任何其他行动,
* 包括但不限于:泄露本文件中的信息、以任何方式制作本文件全部或部分内容之副本、将本文件或其相关副本提供给任何其他人。
*/
package net.heartsome.cat.database.ui.tb;
import java.io.File;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import net.heartsome.cat.common.bean.DatabaseModelBean;
import net.heartsome.cat.database.Constants;
import net.heartsome.cat.database.DBOperator;
import net.heartsome.cat.database.service.DatabaseService;
import net.heartsome.cat.database.ui.tb.resource.Messages;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author Jason
* @version
* @since JDK1.6
*/
public class Utils {
public static Logger LOGGER = LoggerFactory.getLogger(Utils.class);
public static Map<DatabaseModelBean, String> convertFile2TbModel(File f, boolean loadLang) throws Exception {
String path = f.getParent();
String name = f.getName();
System.out.println(path + " " + name);
DatabaseModelBean selectedVal = new DatabaseModelBean();
selectedVal.setDbName(name);
selectedVal.setDbType(Constants.DBTYPE_SQLITE);
selectedVal.setItlDBLocation(path);
String lang = "";
DBOperator dbOp = DatabaseService.getDBOperator(selectedVal.toDbMetaData());
Statement stmt = null;
ResultSet rs = null;
try {
dbOp.start();
stmt = dbOp.getConnection().createStatement();
rs = stmt.executeQuery("SELECT name FROM sqlite_master WHERE type='table' ORDER BY name");
List<String> tables = new ArrayList<String>();
while (rs.next()) {
String tname = rs.getString(1);
if (tname.toUpperCase().startsWith("MATRIX_")) {
continue;
} else {
tables.add(tname);
}
}
List<String> l = Arrays.asList("BATTRIBUTE", "BMARTIFHEADER", "BNODE", "BREFOBJECTLIST", "BTERMENTRY",
"LANG", "MEXTRA", "MHEADER", "MHEADERNODE", "MNOTE", "MPROP", "MTU", "TEXTDATA");
if (!tables.containsAll(l)) {
String message = Messages.getString("tb.dialog.addFileTb.error.msg1");
throw new Exception(message);
}
if (loadLang) {
List<String> langs = dbOp.getLanguages();
for (int j = 0; j < langs.size(); j++) {
lang += langs.get(j);
if (j != langs.size() - 1) {
lang += ",";
}
}
}
Map<DatabaseModelBean, String> result = new HashMap<DatabaseModelBean, String>();
result.put(selectedVal, lang);
return result;
} catch (Exception ex) {
LOGGER.error("", ex);
String message = Messages.getString("tb.dialog.addFileTb.error.msg2");
message = MessageFormat.format(message, name);
throw new Exception(message);
} finally {
try {
if (dbOp != null) {
dbOp.end();
}
} catch (SQLException ex) {
LOGGER.error("", ex);
}
}
}
}
| 3,454 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
ImageConstants.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/database/net.heartsome.cat.database.ui.tb/src/net/heartsome/cat/database/ui/tb/ImageConstants.java | /**
* ImageConstants.java
*
* Version information :
*
* Date:2012-5-3
*
* Copyright notice :
* 本文件及其附带的相关文件包含机密信息,仅限瀚特盛科技有限公司指定的,与本项目有关的内部人员和客户联络人员查阅和使用。
* 如果您不是本保密声明中指定的收件者,请立即销毁本文件,禁止对本文件或根据本文件中的内容采取任何其他行动,
* 包括但不限于:泄露本文件中的信息、以任何方式制作本文件全部或部分内容之副本、将本文件或其相关副本提供给任何其他人。
*/
package net.heartsome.cat.database.ui.tb;
/**
* 图片资源常量
* @author jason
* @version
* @since JDK1.6
*/
public interface ImageConstants {
String CHECKED = "images/database/new-project/checked.gif";
String UNCHECKED = "images/database/new-project/unchecked.gif";
/** 搜索术语对话框中选择语言按钮的图片 */
public static final String CONCORDANCE_SELECT_LANG = "images/dialog/change-lang.png";
// 数据库管理模块
public static final String ORACLE = "images/database/db-manage/oracle.png";
public static final String MYSQL = "images/database/db-manage/mysql.png";
public static final String POSTGRESQL = "images/database/db-manage/postgresql.png";
public static final String SQLSERVER = "images/database/db-manage/sqlserver.png";
public static final String INTERNALDB = "images/database/db-manage/internaldb.png";
public static final String IP = "images/database/db-manage/ip.png";
public static final String SQLITE = "images/database/db-manage/sqlite.png";
}
| 1,632 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
TbxImportWizard.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/database/net.heartsome.cat.database.ui.tb/src/net/heartsome/cat/database/ui/tb/wizard/TbxImportWizard.java | /**
* ImportWizard.java
*
* Version information :
*
* Date:Oct 20, 2011
*
* Copyright notice :
* 本文件及其附带的相关文件包含机密信息,仅限瀚特盛科技有限公司指定的,与本项目有关的内部人员和客户联络人员查阅和使用。
* 如果您不是本保密声明中指定的收件者,请立即销毁本文件,禁止对本文件或根据本文件中的内容采取任何其他行动,
* 包括但不限于:泄露本文件中的信息、以任何方式制作本文件全部或部分内容之副本、将本文件或其相关副本提供给任何其他人。
*/
package net.heartsome.cat.database.ui.tb.wizard;
import java.lang.reflect.InvocationTargetException;
import net.heartsome.cat.common.bean.DatabaseModelBean;
import net.heartsome.cat.database.ui.tb.resource.Messages;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.wizard.Wizard;
/**
* @author Jason
* @version
* @since JDK1.6
*/
public class TbxImportWizard extends Wizard {
private TbxImportWizardTbxPage tbxPage;
private DatabaseModelBean dbModel;
public TbxImportWizard(DatabaseModelBean dbModel) {
this.dbModel = dbModel;
setNeedsProgressMonitor(true);
setWindowTitle(Messages.getString("wizard.TbxImportWizard.title"));
}
@Override
public void addPages() {
tbxPage = new TbxImportWizardTbxPage(this.dbModel);
addPage(tbxPage);
}
@Override
public boolean performFinish() {
final String tbxFile = tbxPage.getTBXFile();
if (tbxFile == null || tbxFile.equals("")) {
tbxPage.setErrorMessage(Messages.getString("wizard.TbxImportWizard.msg"));
return false;
}
IRunnableWithProgress runnable = new IRunnableWithProgress() {
public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
tbxPage.executeImport(tbxFile, monitor);
}
};
try {
getContainer().run(true, true, runnable);
} catch (InvocationTargetException e) {
e.printStackTrace();
return false;
} catch (InterruptedException e) {
e.printStackTrace();
return false;
}
return true;
}
}
| 2,169 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
NewTermDbWizard.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/database/net.heartsome.cat.database.ui.tb/src/net/heartsome/cat/database/ui/tb/wizard/NewTermDbWizard.java | /**
* NewTMBWizard.java
*
* Version information :
*
* Date:Oct 20, 2011
*
* Copyright notice :
* 本文件及其附带的相关文件包含机密信息,仅限瀚特盛科技有限公司指定的,与本项目有关的内部人员和客户联络人员查阅和使用。
* 如果您不是本保密声明中指定的收件者,请立即销毁本文件,禁止对本文件或根据本文件中的内容采取任何其他行动,
* 包括但不限于:泄露本文件中的信息、以任何方式制作本文件全部或部分内容之副本、将本文件或其相关副本提供给任何其他人。
*/
package net.heartsome.cat.database.ui.tb.wizard;
import java.lang.reflect.InvocationTargetException;
import net.heartsome.cat.common.bean.DatabaseModelBean;
import net.heartsome.cat.database.Constants;
import net.heartsome.cat.database.SystemDBOperator;
import net.heartsome.cat.database.ui.tb.resource.Messages;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.wizard.Wizard;
import org.eclipse.ui.INewWizard;
import org.eclipse.ui.IWorkbench;
/**
* @author Jason
* @version
* @since JDK1.6
*/
public class NewTermDbWizard extends Wizard implements INewWizard {
private NewTermDbBaseInfoPage createDbPage;
private NewTermDbImportPage importPage;
/**
*
*/
public NewTermDbWizard() {
setWindowTitle(Messages.getString("wizard.NewTermDbWizard.title"));
}
@Override
public void addPages() {
createDbPage = new NewTermDbBaseInfoPage();
addPage(createDbPage);
importPage = new NewTermDbImportPage(createDbPage);
addPage(importPage);
setNeedsProgressMonitor(true);
}
/**
* (non-Javadoc)
* @see org.eclipse.ui.IWorkbenchWizard#init(org.eclipse.ui.IWorkbench,
* org.eclipse.jface.viewers.IStructuredSelection)
*/
public void init(IWorkbench workbench, IStructuredSelection selection) {
}
@Override
public boolean canFinish() {
return super.canFinish();
}
/**
* (non-Javadoc)
* @see org.eclipse.jface.wizard.Wizard#performFinish()
*/
@Override
public boolean performFinish() {
final String tbxFile = importPage.getTBXFile();
final SystemDBOperator dbOp = createDbPage.getCurrDbOp();
if (dbOp.getDBConfig().getDefaultType().equals(Constants.DBTYPE_SQLITE)) {
String dbName = dbOp.getMetaData().getDatabaseName();
dbName += ".hstb";
dbOp.getMetaData().setDatabaseName(dbName);
}
IRunnableWithProgress runnable = new IRunnableWithProgress() {
public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
importPage.performFinish(tbxFile, dbOp, monitor);
}
};
try {
getContainer().run(true, true, runnable);
} catch (InvocationTargetException e) {
e.printStackTrace();
return false;
} catch (InterruptedException e) {
e.printStackTrace();
return false;
}
return true;
}
public DatabaseModelBean getCreateDb() {
DatabaseModelBean db = createDbPage.getDbModel();
if (db.getDbType().equals(Constants.DBTYPE_SQLITE)) {
String dbName = db.getDbName();
dbName += ".hstb";
db.setDbName(dbName);
}
return db;
}
}
| 3,241 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
TermDbManagerImportWizardDialog.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/database/net.heartsome.cat.database.ui.tb/src/net/heartsome/cat/database/ui/tb/wizard/TermDbManagerImportWizardDialog.java | package net.heartsome.cat.database.ui.tb.wizard;
import net.heartsome.cat.common.ui.wizard.TSWizardDialog;
import net.heartsome.cat.database.ui.tb.preference.TBDatabasePage;
import net.heartsome.cat.database.ui.tb.resource.Messages;
import net.heartsome.cat.ts.ui.util.PreferenceUtil;
import org.eclipse.jface.wizard.IWizard;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.PlatformUI;
/**
* 导入 TBX 向导框
* @author peason
* @version
* @since JDK1.6
*/
public class TermDbManagerImportWizardDialog extends TSWizardDialog {
private Button btnSetting;
public TermDbManagerImportWizardDialog(Shell parentShell, IWizard newWizard) {
super(parentShell, newWizard);
}
@Override
protected void createButtonsForButtonBar(Composite parent) {
btnSetting = createButton(parent, -1, Messages.getString("wizard.TermDbManagerImportWizardTbxPage.settingBtn"),
true);
super.createButtonsForButtonBar(parent);
btnSetting.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
PreferenceUtil.openPreferenceDialog(PlatformUI.getWorkbench().getActiveWorkbenchWindow(),
TBDatabasePage.ID);
}
});
}
@Override
public void updateButtons() {
super.updateButtons();
btnSetting.setVisible(getCurrentPage() instanceof NewTermDbImportPage
|| getCurrentPage() instanceof TbxImportWizardTbxPage
|| getCurrentPage() instanceof TermDbManagerImportWizardTbxPage);
}
}
| 1,633 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
NewTermDbImportPage.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/database/net.heartsome.cat.database.ui.tb/src/net/heartsome/cat/database/ui/tb/wizard/NewTermDbImportPage.java | /**
* NewDatabaseWizardImportPage.java
*
* Version information :
*
* Date:Oct 28, 2011
*
* Copyright notice :
* 本文件及其附带的相关文件包含机密信息,仅限瀚特盛科技有限公司指定的,与本项目有关的内部人员和客户联络人员查阅和使用。
* 如果您不是本保密声明中指定的收件者,请立即销毁本文件,禁止对本文件或根据本文件中的内容采取任何其他行动,
* 包括但不限于:泄露本文件中的信息、以任何方式制作本文件全部或部分内容之副本、将本文件或其相关副本提供给任何其他人。
*/
package net.heartsome.cat.database.ui.tb.wizard;
import net.heartsome.cat.common.bean.MetaData;
import net.heartsome.cat.common.core.exception.ImportException;
import net.heartsome.cat.database.SystemDBOperator;
import net.heartsome.cat.database.bean.TBPreferenceConstants;
import net.heartsome.cat.database.service.DatabaseService;
import net.heartsome.cat.database.ui.tb.Activator;
import net.heartsome.cat.database.ui.tb.resource.Messages;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.SubProgressMonitor;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.wizard.WizardPage;
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.Display;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;
/**
* 导入TBX文件向导页
* @author Jason
* @version
* @since JDK1.6
*/
public class NewTermDbImportPage extends WizardPage {
private Text tbxFileText;
private final NewTermDbBaseInfoPage createDbPage;
/**
* Create the wizard.
*/
public NewTermDbImportPage(NewTermDbBaseInfoPage createDbPage) {
super("importWizardPage");
this.createDbPage = createDbPage;
setTitle(Messages.getString("wizard.NewTermDbImportPage.title"));
setDescription(Messages.getString("wizard.NewTermDbImportPage.desc"));
}
/**
* Create contents of the wizard.
* @param parent
*/
public void createControl(Composite parent) {
Composite container = new Composite(parent, SWT.NULL);
setControl(container);
container.setLayout(new GridLayout(3, false));
Label lblTbx = new Label(container, SWT.NONE);
lblTbx.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
lblTbx.setText(Messages.getString("wizard.NewTermDbImportPage.lblTbx"));
tbxFileText = new Text(container, SWT.BORDER);
tbxFileText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
tbxFileText.setEditable(false);
Button tbxFileBorwserBtn = new Button(container, SWT.NONE);
tbxFileBorwserBtn.setText(Messages.getString("wizard.NewTermDbImportPage.tbxFileBorwserBtn"));
tbxFileBorwserBtn.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
FileDialog dlg = new FileDialog(getShell());
String[] filterExt = { "*.tbx", "*.xlsx", "*.txt" };
dlg.setFilterExtensions(filterExt);
String path = dlg.open();
if (path != null) {
tbxFileText.setText(path);
}
}
});
}
/**
* 创建数据库,并导入文件
* @param tbxFile
* TBX文件
* @param dbOp
* @param monitor
* @throws InterruptedException
* ;
*/
public void performFinish(String tbxFile, SystemDBOperator dbOp, IProgressMonitor monitor)
throws InterruptedException {
if (tbxFile != null) {
monitor.beginTask(Messages.getString("wizard.NewTermDbImportPage.task1"), 1000);
}
String message = createDbPage.canCreateDb(new SubProgressMonitor(monitor, 100));
if (message != null) {
final String _message = message;
Display.getDefault().asyncExec(new Runnable() {
public void run() {
setErrorMessage(_message);
}
});
throw new InterruptedException();
}
message = createDbPage.executeCreateDB(dbOp, new SubProgressMonitor(monitor, 100));
if (message != null) {
final String _message = message;
Display.getDefault().asyncExec(new Runnable() {
public void run() {
setErrorMessage(_message);
}
});
throw new InterruptedException();
}
if (tbxFile != null) {
executeImport(tbxFile, dbOp.getMetaData(), new SubProgressMonitor(monitor, 800));
}
monitor.done();
}
/**
* 执行导入
* @param tmxFile
* @param tbxFile
* @param dbMetaData
* @param monitor
* ;
*/
public void executeImport(String tbxFile, MetaData dbMetaData, IProgressMonitor monitor) {
if (monitor == null) {
monitor = new NullProgressMonitor();
}
monitor.setTaskName(Messages.getString("wizard.NewTermDbImportPage.task2"));
monitor.beginTask("", 1);
int tbxResult = -10;
String message = "";
if (tbxFile != null) {
try {
tbxResult = DatabaseService.importTbxWithFile(tbxFile, new SubProgressMonitor(monitor, 100),
dbMetaData, getTbxImportStrategy());
} catch (ImportException e) {
message = e.getMessage();
}
if (!message.equals("")) {
final String _message = message;
Display.getDefault().asyncExec(new Runnable() {
public void run() {
setErrorMessage(_message);
}
});
}
}
StringBuffer resultMessage = new StringBuffer();
if (tbxResult != DatabaseService.SUCCESS) {
if (tbxResult == DatabaseService.FAILURE_1) {
resultMessage.append(Messages.getString("wizard.NewTermDbImportPage.msg1"));
} else if (tbxResult == DatabaseService.FAILURE_2) {
resultMessage.append(Messages.getString("wizard.NewTermDbImportPage.msg2"));
} else if (tbxResult == DatabaseService.FAILURE_3) {
resultMessage.append(Messages.getString("wizard.NewTermDbImportPage.msg3"));
} else if (tbxResult == DatabaseService.FAILURE_4) {
resultMessage.append(Messages.getString("wizard.NewTermDbImportPage.msg4"));
} else if (tbxResult == DatabaseService.FAILURE) {
resultMessage.append(Messages.getString("wizard.NewTermDbImportPage.msg5"));
} else if (tbxResult == DatabaseService.CANCEL) {
resultMessage.append(Messages.getString("wizard.NewTermDbImportPage.msg6"));
}
if (!resultMessage.toString().equals("")) {
final String _message = resultMessage.toString();
Display.getDefault().asyncExec(new Runnable() {
public void run() {
setErrorMessage(_message);
}
});
}
}
monitor.done();
}
public String getTBXFile() {
String file = tbxFileText.getText().trim();
if (file == null || file.length() == 0) {
return null;
}
return file;
}
/**
* 从首选项中读取TBX导入策略
* @return ;
*/
public int getTbxImportStrategy() {
IPreferenceStore ps = Activator.getDefault().getPreferenceStore();
return ps.getInt(TBPreferenceConstants.TB_UPDATE);
}
}
| 7,053 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
NewTermDbBaseInfoPage.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/database/net.heartsome.cat.database.ui.tb/src/net/heartsome/cat/database/ui/tb/wizard/NewTermDbBaseInfoPage.java | /**
* NewTermDbBaseInfoPage.java
*
* Version information :
*
* Date:Oct 25, 2011
*
* Copyright notice :
* 本文件及其附带的相关文件包含机密信息,仅限瀚特盛科技有限公司指定的,与本项目有关的内部人员和客户联络人员查阅和使用。
* 如果您不是本保密声明中指定的收件者,请立即销毁本文件,禁止对本文件或根据本文件中的内容采取任何其他行动,
* 包括但不限于:泄露本文件中的信息、以任何方式制作本文件全部或部分内容之副本、将本文件或其相关副本提供给任何其他人。
*/
package net.heartsome.cat.database.ui.tb.wizard;
import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.sql.SQLException;
import java.util.List;
import net.heartsome.cat.common.bean.DatabaseModelBean;
import net.heartsome.cat.common.bean.MetaData;
import net.heartsome.cat.database.Constants;
import net.heartsome.cat.database.SystemDBOperator;
import net.heartsome.cat.database.bean.TBPreferenceConstants;
import net.heartsome.cat.database.service.DatabaseService;
import net.heartsome.cat.database.ui.core.DatabaseConfiger;
import net.heartsome.cat.database.ui.core.DbValidator;
import net.heartsome.cat.database.ui.tb.Activator;
import net.heartsome.cat.database.ui.tb.resource.Messages;
import org.eclipse.core.databinding.DataBindingContext;
import org.eclipse.core.databinding.beans.BeanProperties;
import org.eclipse.core.databinding.observable.value.IObservableValue;
import org.eclipse.core.databinding.validation.MultiValidator;
import org.eclipse.core.databinding.validation.ValidationStatus;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.OperationCanceledException;
import org.eclipse.jface.databinding.swt.WidgetProperties;
import org.eclipse.jface.databinding.wizard.WizardPageSupport;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.viewers.ArrayContentProvider;
import org.eclipse.jface.viewers.ComboViewer;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.wizard.IWizardPage;
import org.eclipse.jface.wizard.WizardPage;
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.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.DirectoryDialog;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author Jason
* @version
* @since JDK1.6
*/
public class NewTermDbBaseInfoPage extends WizardPage {
private static final Logger logger = LoggerFactory.getLogger(NewTermDbBaseInfoPage.class);
private ComboViewer dbTypeComboViewer;
private Text dbNameText;
private Text instanceText;
private Text locationText;
private Button borwserBtn;
private Text hostText;
private Text portText;
private Text usernameText;
private Text passwordText;
private DatabaseModelBean dbModel;
private IPreferenceStore pStore;
private List<SystemDBOperator> dbTypeList;
/** @return the dbModel */
public DatabaseModelBean getDbModel() {
return dbModel;
}
/**
* 当数据库类型改变时 用于保存当前操作的数据库对象
* @see #dbTypeChangeEvent(SystemDBOperator)
*/
private SystemDBOperator dbOp;
private MetaData dbMetaData;
/**
* Create the wizard.
*/
public NewTermDbBaseInfoPage() {
super("newTermDbConnectionInfo");
setTitle(Messages.getString("wizard.NewTermDbBaseInfoPage.title"));
setDescription(Messages.getString("wizard.NewTermDbBaseInfoPage.desc"));
setImageDescriptor(Activator.getImageDescriptor("images/dialog/new-termdb-logo.png"));
dbModel = new DatabaseModelBean();
dbTypeList = DatabaseService.getSystemDbOperaterList();
pStore = Activator.getDefault().getPreferenceStore();
String dbType = pStore.getString(TBPreferenceConstants.TB_RM_DBTYPE);
if (dbType != null && !dbType.equals("")) {
for (SystemDBOperator dbOp : dbTypeList) {
if (dbOp.getMetaData().getDbType().equals(dbType)) {
this.dbOp = dbOp;
break;
}
}
if (this.dbOp != null) {
dbModel.setDbType(dbType);
dbModel.setInstance(pStore.getString(TBPreferenceConstants.TB_RM_INSTANCE));
dbModel.setHost(pStore.getString(TBPreferenceConstants.TB_RM_SERVER));
dbModel.setPort(pStore.getString(TBPreferenceConstants.TB_RM_PORT));
dbModel.setUserName(pStore.getString(TBPreferenceConstants.TB_RM_USERNAME));
dbModel.setItlDBLocation(pStore.getString(TBPreferenceConstants.TB_RM_PATH));
this.dbMetaData = dbOp.getMetaData();
dbMetaData.setInstance(dbModel.getInstance());
dbMetaData.setServerName(dbModel.getHost());
dbMetaData.setPort(dbModel.getPort());
dbMetaData.setUserName(dbModel.getUserName());
dbMetaData.setDataPath(dbModel.getItlDBLocation());
}
}
setPageComplete(false);
}
/**
* Create contents of the wizard.
* @param parent
*/
public void createControl(Composite parent) {
Composite container = new Composite(parent, SWT.NULL);
container.setLayout(new GridLayout(1, false));
setControl(container);
int labelWidth = 100;
GridData gdLabel = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1);
gdLabel.widthHint = labelWidth;
Group dbGroup1 = new Group(container, SWT.NONE);
dbGroup1.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1));
dbGroup1.setLayout(new GridLayout(2, false));
dbGroup1.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false, 4, 1));
dbGroup1.setText(Messages.getString("wizard.NewTermDbBaseInfoPage.dbGroup1"));
Label label = new Label(dbGroup1, SWT.RIGHT);
label.setLayoutData(gdLabel);
label.setText(Messages.getString("wizard.NewTermDbBaseInfoPage.lblType"));
dbTypeComboViewer = new ComboViewer(dbGroup1, SWT.READ_ONLY);
Combo combo = dbTypeComboViewer.getCombo();
combo.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
// //
label = new Label(dbGroup1, SWT.RIGHT);
label.setLayoutData(gdLabel);
label.setText(Messages.getString("wizard.NewTermDbBaseInfoPage.dbNameText"));
dbNameText = new Text(dbGroup1, SWT.BORDER);
dbNameText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
label = new Label(dbGroup1, SWT.RIGHT);
label.setLayoutData(gdLabel);
label.setText(Messages.getString("wizard.NewTermDbBaseInfoPage.instanceText"));
instanceText = new Text(dbGroup1, SWT.BORDER);
instanceText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
dbTypeComboViewer.setContentProvider(new ArrayContentProvider());
dbTypeComboViewer.setInput(dbTypeList);
dbTypeComboViewer.setLabelProvider(new LabelProvider() {
public String getText(Object element) {
SystemDBOperator dbOp = (SystemDBOperator) element;
String dbType = dbOp.getDBConfig().getDefaultType();
if (dbType.equals(Constants.DBTYPE_MYSQL)) {
dbType = Constants.DBTYPE_MYSQL_FOR_UI;
} else if (dbType.equals(Constants.DBTYPE_MSSQL2005)) {
dbType = Constants.DBTYPE_MSSQL2005_FOR_UI;
} else if (dbType.equals(Constants.DBTYPE_SQLITE)) {
dbType = Messages.getString("tb.dbtype.sqlite");
}
return dbType;
}
});
dbTypeComboViewer.addSelectionChangedListener(new ISelectionChangedListener() {
public void selectionChanged(SelectionChangedEvent event) {
ISelection selection = event.getSelection();
if (selection != null && selection instanceof IStructuredSelection) {
IStructuredSelection sel = (IStructuredSelection) selection;
Object selObj = sel.getFirstElement();
if (selObj != null && selObj instanceof SystemDBOperator) {
SystemDBOperator selDbOp = (SystemDBOperator) selObj;
dbTypeChangeEvent(selDbOp);
}
}
}
});
Group dbGroup = new Group(container, SWT.NONE);
dbGroup.setLayout(new GridLayout(5, false));
dbGroup.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false, 4, 1));
dbGroup.setText(Messages.getString("wizard.NewTermDbBaseInfoPage.dbGroup"));
label = new Label(dbGroup, SWT.RIGHT);
label.setLayoutData(gdLabel);
label.setText(Messages.getString("wizard.NewTermDbBaseInfoPage.hostText"));
hostText = new Text(dbGroup, SWT.BORDER);
hostText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
label = new Label(dbGroup, SWT.RIGHT);
label.setLayoutData(gdLabel);
label.setText(Messages.getString("wizard.NewTermDbBaseInfoPage.portText"));
portText = new Text(dbGroup, SWT.BORDER);
new Label(dbGroup, SWT.NONE);
label = new Label(dbGroup, SWT.RIGHT);
label.setLayoutData(gdLabel);
label.setText(Messages.getString("wizard.NewTermDbBaseInfoPage.locationText"));
locationText = new Text(dbGroup, SWT.BORDER);
locationText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 3, 1));
locationText.setEnabled(false);
borwserBtn = new Button(dbGroup, SWT.NONE);
borwserBtn.setText(Messages.getString("wizard.NewTermDbBaseInfoPage.borwserBtn"));
borwserBtn.setEnabled(false);
borwserBtn.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent event) {
DirectoryDialog dlg = new DirectoryDialog(getShell());
String path = dlg.open();
if (path != null) {
locationText.setText(path);
}
}
});
Group authorityGroup = new Group(container, SWT.NONE);
authorityGroup.setLayout(new GridLayout(2, false));
authorityGroup.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 4, 1));
authorityGroup.setText(Messages.getString("wizard.NewTermDbBaseInfoPage.authorityGroup"));
label = new Label(authorityGroup, SWT.RIGHT);
label.setLayoutData(gdLabel);
label.setText(Messages.getString("wizard.NewTermDbBaseInfoPage.usernameText"));
usernameText = new Text(authorityGroup, SWT.BORDER);
usernameText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
label = new Label(authorityGroup, SWT.RIGHT);
label.setLayoutData(gdLabel);
label.setText(Messages.getString("wizard.NewTermDbBaseInfoPage.passwordText"));
passwordText = new Text(authorityGroup, SWT.BORDER | SWT.PASSWORD);
passwordText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
initDataBindings();
if (this.dbOp != null) {
dbTypeComboViewer.setSelection(new StructuredSelection(this.dbOp));
} else {
dbTypeComboViewer.setSelection(new StructuredSelection(dbTypeList.get(0)));
}
IStatus state = validator();
if (!state.isOK()) {
setErrorMessage(state.getMessage());
setPageComplete(false);
}
}
/**
* 当数据库类型发生改变时,实始化当选择类型的
* @param changedDbOp
* ;
*/
private void dbTypeChangeEvent(SystemDBOperator changedDbOp) {
dbOp = changedDbOp;
dbMetaData = dbOp.getMetaData();
dbModel.setDbType(dbOp.getDBConfig().getDefaultType());
if (dbMetaData.databaseNameSupported()) {
dbNameText.setEnabled(true);
// fix bug2672
String dbname = dbMetaData.getDatabaseName();
// if (dbname.equals("")) {
// // 如果设置的内容都是"",则不会触发binding的验证方法。所以先设置成test,再修改为""
// dbNameText.setText("test"/* dbMetaData.getDatabaseName() */);
// }
dbNameText.setText(dbname);
} else {
dbNameText.setEnabled(false);
dbNameText.setText("");
}
if (dbMetaData.dataPathSupported()) {
locationText.setEnabled(true);
borwserBtn.setEnabled(true);
locationText.setText(locationText.getText());
} else {
locationText.setEnabled(false);
borwserBtn.setEnabled(false);
locationText.setText("");
}
if (dbMetaData.serverNameSupported()) {
hostText.setEnabled(true);
hostText.setText(dbMetaData.getServerName());
} else {
hostText.setEnabled(false);
hostText.setText("");
}
if (dbMetaData.instanceSupported()) {
instanceText.setEnabled(true);
instanceText.setText(dbMetaData.getInstance());
} else {
instanceText.setEnabled(false);
instanceText.setText("");
}
if (dbMetaData.portSupported()) {
portText.setEnabled(true);
portText.setText(dbMetaData.getPort());
} else {
portText.setEnabled(false);
portText.setText("");
}
if (dbMetaData.userNameSupported()) {
usernameText.setEnabled(true);
usernameText.setText(dbMetaData.getUserName());
} else {
usernameText.setEnabled(false);
usernameText.setText("");
}
if (dbMetaData.passwordSupported()) {
passwordText.setEnabled(true);
passwordText.setText(dbMetaData.getPassword());
} else {
passwordText.setEnabled(false);
passwordText.setText("");
}
}
protected void initDataBindings() {
DataBindingContext bindingContext = new DataBindingContext();
WizardPageSupport.create(this, bindingContext);
IObservableValue widgetValue = WidgetProperties.text(SWT.Modify).observe(dbNameText);
final IObservableValue dbNameModelValue = BeanProperties.value("dbName").observe(dbModel);
bindingContext.bindValue(widgetValue, dbNameModelValue, null, null);
widgetValue = WidgetProperties.text(SWT.Modify).observe(instanceText);
final IObservableValue instanceModelValue = BeanProperties.value("instance").observe(dbModel);
bindingContext.bindValue(widgetValue, instanceModelValue, null, null);
widgetValue = WidgetProperties.text(SWT.Modify).observe(hostText);
final IObservableValue hostModelValue = BeanProperties.value("host").observe(dbModel);
bindingContext.bindValue(widgetValue, hostModelValue, null, null);
widgetValue = WidgetProperties.text(SWT.Modify).observe(portText);
final IObservableValue protModelValue = BeanProperties.value("port").observe(dbModel);
bindingContext.bindValue(widgetValue, protModelValue, null, null);
widgetValue = WidgetProperties.text(SWT.Modify).observe(locationText);
final IObservableValue locationModelValue = BeanProperties.value("itlDBLocation").observe(dbModel);
bindingContext.bindValue(widgetValue, locationModelValue, null, null);
//
widgetValue = WidgetProperties.text(SWT.Modify).observe(usernameText);
final IObservableValue usernameModelValue = BeanProperties.value("userName").observe(dbModel);
bindingContext.bindValue(widgetValue, usernameModelValue, null, null);
widgetValue = WidgetProperties.text(SWT.Modify).observe(passwordText);
final IObservableValue passwordModelValue = BeanProperties.value("password").observe(dbModel);
bindingContext.bindValue(widgetValue, passwordModelValue, null, null);
MultiValidator myValidator = new MultiValidator() {
@Override
protected IStatus validate() {
dbNameModelValue.getValue();
instanceModelValue.getValue();
hostModelValue.getValue();
protModelValue.getValue();
locationModelValue.getValue();
usernameModelValue.getValue();
passwordModelValue.getValue();
return validator();
}
};
bindingContext.addValidationStatusProvider(myValidator);
}
/**
* 输入验证器 ;
*/
private IStatus validator() {
// 选择数据库类型的时候初始化dbMetaDate
if (null == dbMetaData) {
return ValidationStatus.error(Messages.getString("wizard.NewTermDbBaseInfoPage.msg1"));
}
//
String dbName = dbModel.getDbName();
String instance = dbModel.getInstance();
String host = dbModel.getHost();
String port = dbModel.getPort();
String location = dbModel.getItlDBLocation();
String username = dbModel.getUserName();
String password = dbModel.getPassword();
if (dbName == null || dbName.trim().length() == 0) {
return ValidationStatus.error(Messages.getString("wizard.NewTermDbBaseInfoPage.msg2"));
}
String vRs = DbValidator.valiateDbName(dbName);
if (vRs != null) {
return ValidationStatus.error(vRs);
}
if (dbMetaData.instanceSupported()) {
if (instance == null || instance.trim().length() == 0) {
return ValidationStatus.error(Messages.getString("wizard.NewTermDbBaseInfoPage.instancemsg"));
}
dbMetaData.setInstance(instance == null ? "" : instance);
}
if (dbMetaData.dataPathSupported()) {
if (location == null || location.trim().length() == 0) {
return ValidationStatus.error(Messages.getString("wizard.NewTermDbBaseInfoPage.msg3"));
}
File f = new File(location);
if (!f.isDirectory() || !f.exists()) {
return ValidationStatus.error(Messages.getString("wizard.NewTermDbBaseInfoPage.msg11"));
}
}
if (dbMetaData.serverNameSupported()) {
if (host == null || host.trim().length() == 0) {
return ValidationStatus.error(Messages.getString("wizard.NewTermDbBaseInfoPage.msg4"));
}
}
if (dbMetaData.portSupported()) {
if (port == null || !port.matches("[0-9]+")) {
return ValidationStatus.error(Messages.getString("wizard.NewTermDbBaseInfoPage.msg5"));
}
}
if (dbMetaData.userNameSupported()) {
if (username == null || username.trim().length() == 0) {
return ValidationStatus.error(Messages.getString("wizard.NewTermDbBaseInfoPage.msg6"));
}
}
dbMetaData.setDatabaseName(dbName == null ? "" : dbName);
dbMetaData.setDataPath(location == null ? "" : location);
dbMetaData.setServerName(host == null ? "" : host);
dbMetaData.setPort(port == null ? "" : port);
dbMetaData.setUserName(username == null ? "" : username);
dbMetaData.setPassword(password == null ? "" : password); // 密码可以为空
return ValidationStatus.ok();
}
/**
* 获取数据库操作对象
* @return ;
*/
public SystemDBOperator getCurrDbOp() {
return dbOp;
}
/**
* 检查服务器型数据库
* @return ;
*/
public String checkDb4Server(IProgressMonitor monitor) {
if (monitor == null) {
monitor = new NullProgressMonitor();
}
monitor.beginTask("", 3);
monitor.setTaskName(Messages.getString("wizard.NewTermDbBaseInfoPage.task1"));
String message = null;
if (!dbOp.checkDbConnection()) {
message = Messages.getString("wizard.NewTermDbBaseInfoPage.msg7");
return message;
}
if (!dbOp.checkSysDb()) { // 检查是否创建了系统库,没创建则创建
try {
dbOp.createSysDb();
} catch (Exception e) {
logger.error(Messages.getString("wizard.NewTermDbBaseInfoPage.logger1"));
message = Messages.getString("wizard.NewTermDbBaseInfoPage.msg8");
return message;
}
}
monitor.worked(1);
if (dbOp.checkDbExistOnServer()) {
message = Messages.getString("wizard.NewTermDbBaseInfoPage.msg9") + dbOp.getMetaData().getDatabaseName();
return message;
}
if (monitor.isCanceled()) {
throw new OperationCanceledException();
}
monitor.done();
return message;
}
public String canCreateDb(IProgressMonitor monitor) {
String message = null;
if (dbOp == null) {
message = Messages.getString("wizard.NewTermDbBaseInfoPage.msg1");
}
message = checkDb4Server(monitor);
if (message != null) {
final String _message = message;
Display.getDefault().asyncExec(new Runnable() {
public void run() {
setErrorMessage(_message);
}
});
} else {
pStore.setValue(TBPreferenceConstants.TB_RM_DBTYPE, dbModel.getDbType());
pStore.setValue(TBPreferenceConstants.TB_RM_INSTANCE, dbModel.getInstance());
pStore.setValue(TBPreferenceConstants.TB_RM_SERVER, dbModel.getHost());
pStore.setValue(TBPreferenceConstants.TB_RM_PORT, dbModel.getPort());
pStore.setValue(TBPreferenceConstants.TB_RM_USERNAME, dbModel.getUserName());
pStore.setValue(TBPreferenceConstants.TB_RM_PATH, dbModel.getItlDBLocation());
}
return message;
}
/**
* 创建数据库
* @return ;
*/
public String executeCreateDB(SystemDBOperator dbOp, IProgressMonitor monitor) {
if (monitor == null) {
monitor = new NullProgressMonitor();
}
monitor.beginTask("", 3);
monitor.setTaskName(Messages.getString("wizard.NewTermDbBaseInfoPage.task2"));
String message = null;
try {
if (Constants.FAILURE == dbOp.createDB()) {
message = Messages.getString("wizard.NewTermDbBaseInfoPage.msg8");
} else {
if (!dbOp.getDBConfig().getDefaultType().equals(Constants.DBTYPE_SQLITE)) {
dbOp.updataSysDb(Constants.DB_TYPE_TB); // 更新系统库
saveToServerConfigFile(dbOp); // 处理本地服务器列表
}
}
monitor.worked(3);
} catch (SQLException e) {
logger.error("", e);
e.printStackTrace();
message = Messages.getString("wizard.NewTermDbBaseInfoPage.msg10") + e.getMessage();
return message;
} finally {
if (message != null) {
final String _message = message;
Display.getDefault().asyncExec(new Runnable() {
public void run() {
setErrorMessage(_message);
}
});
}
monitor.done();
}
return message;
}
private void saveToServerConfigFile(SystemDBOperator dbOp) {
DatabaseConfiger cf = new DatabaseConfiger();
DatabaseModelBean bean = new DatabaseModelBean();
MetaData md = dbOp.getMetaData();
bean.metaDatatToBean(md);
String serverId = cf.isServerExist(bean, md); // 判断当前服务器是否已经存在
if (serverId == null || serverId.equals("")) { // 不存在
cf.addServerConfig(bean);
} else {
bean.setId(serverId);
cf.updateServerConfigById(serverId, bean);
}
}
public boolean canFlipToNextPage() {
return isPageComplete();
}
public IWizardPage getNextPage() {
WizardPage nextPage = (WizardPage) super.getNextPage();
IRunnableWithProgress runnable = new IRunnableWithProgress() {
public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
if (canCreateDb(monitor) != null) {
throw new InterruptedException();
}
}
};
try {
getContainer().run(true, true, runnable);
} catch (InvocationTargetException e) {
logger.error("", e);
e.printStackTrace();
return null;
} catch (InterruptedException e) {
e.printStackTrace();
return null;
}
nextPage.setErrorMessage(null);
return nextPage;
}
}
| 22,471 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
TermDbManagerImportWizardTbxPage.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/database/net.heartsome.cat.database.ui.tb/src/net/heartsome/cat/database/ui/tb/wizard/TermDbManagerImportWizardTbxPage.java | /**
* ImportWizardTbxPage.java
*
* Version information :
*
* Date:Oct 20, 2011
*
* Copyright notice :
* 本文件及其附带的相关文件包含机密信息,仅限瀚特盛科技有限公司指定的,与本项目有关的内部人员和客户联络人员查阅和使用。
* 如果您不是本保密声明中指定的收件者,请立即销毁本文件,禁止对本文件或根据本文件中的内容采取任何其他行动,
* 包括但不限于:泄露本文件中的信息、以任何方式制作本文件全部或部分内容之副本、将本文件或其相关副本提供给任何其他人。
*/
package net.heartsome.cat.database.ui.tb.wizard;
import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import net.heartsome.cat.common.bean.DatabaseModelBean;
import net.heartsome.cat.common.core.exception.ImportException;
import net.heartsome.cat.common.ui.HSDropDownButton;
import net.heartsome.cat.database.bean.TBPreferenceConstants;
import net.heartsome.cat.database.service.DatabaseService;
import net.heartsome.cat.database.ui.tb.Activator;
import net.heartsome.cat.database.ui.tb.Utils;
import net.heartsome.cat.database.ui.tb.dialog.TermDbManagerDialog;
import net.heartsome.cat.database.ui.tb.resource.Messages;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.window.Window;
import org.eclipse.jface.wizard.WizardPage;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
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.Display;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.swt.widgets.Text;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author Jason
* @version
* @since JDK1.6
*/
public class TermDbManagerImportWizardTbxPage extends WizardPage {
Logger logger = LoggerFactory.getLogger(TermDbManagerImportWizardTbxPage.class);
private Text tbxFileText;
private DatabaseModelBean dbModel;
private Text text;
/**
* Create the wizard.
*/
public TermDbManagerImportWizardTbxPage() {
super("wizardPage");
setTitle(Messages.getString("wizard.TermDbManagerImportWizardTbxPage.title"));
setDescription(Messages.getString("wizard.TermDbManagerImportWizardTbxPage.desc"));
setImageDescriptor(Activator.getImageDescriptor("images/dialog/import-tbx-logo.png"));
}
/**
* Create contents of the wizard.
* @param parent
*/
public void createControl(Composite parent) {
Composite container = new Composite(parent, SWT.NULL);
container.setLayout(new GridLayout(3, false));
Label lblTmx = new Label(container, SWT.NONE);
lblTmx.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
lblTmx.setText(Messages.getString("wizard.TermDbManagerImportWizardTbxPage.lblTmx"));
tbxFileText = new Text(container, SWT.BORDER | SWT.READ_ONLY);
tbxFileText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
tbxFileText.addModifyListener(new ModifyListener() {
public void modifyText(ModifyEvent e) {
validator();
}
});
Button tmxFileBorwserBtn = new Button(container, SWT.NONE);
tmxFileBorwserBtn.setText(Messages.getString("wizard.TermDbManagerImportWizardTbxPage.tmxFileBorwserBtn"));
tmxFileBorwserBtn.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
FileDialog dlg = new FileDialog(getShell());
String[] filterExt = { "*.tbx", "*.xlsx", "*.txt" };
dlg.setFilterExtensions(filterExt);
String path = dlg.open();
// String path = NativeDialogFactory.fileSelectionDialog(getShell(),
// Messages.getString("wizard.TermDbManagerImportWizardTbxPage.openFile"), SWT.OPEN);
if (path != null) {
tbxFileText.setText(path);
}
}
});
Label lblNewLabel = new Label(container, SWT.NONE);
lblNewLabel.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
lblNewLabel.setText(Messages.getString("wizard.TermDbManagerImportWizardTbxPage.lblNewLabel"));
text = new Text(container, SWT.BORDER | SWT.READ_ONLY);
text.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
text.addModifyListener(new ModifyListener() {
public void modifyText(ModifyEvent e) {
validator();
}
});
HSDropDownButton addBtn = new HSDropDownButton(container, SWT.NONE);
addBtn.setText(Messages.getString("wizard.TermDbManagerImportWizardTbxPage.button"));
Menu addMenu = addBtn.getMenu();
MenuItem item = new MenuItem(addMenu, SWT.PUSH);
item.setText(Messages.getString("tb.dialog.addTb.DropDownButton.AddFileTb"));
item.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
FileDialog fileDialg = new FileDialog(getShell());
fileDialg.setFilterExtensions(new String[] { "*.hstb", "*.*" });
String result = fileDialg.open();
if (result == null) {
return;
}
File f = new File(result);
if (!f.exists()) {
return;
}
Map<DatabaseModelBean, String> r = null;
try {
r = Utils.convertFile2TbModel(f, false);
} catch (Exception e1) {
MessageDialog.openError(getShell(), Messages.getString("tb.dialog.addFileTb.errorTitle"),
e1.getMessage());
}
if (r == null) {
return;
}
Iterator<DatabaseModelBean> it = r.keySet().iterator();
if (it.hasNext()) {
dbModel = it.next();
text.setText(f.getAbsolutePath());
}
}
});
MenuItem serverItem = new MenuItem(addMenu, SWT.PUSH);
serverItem.setText(Messages.getString("tb.dialog.addTb.DropDownButton.AddServerTb"));
serverItem.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
TermDbManagerDialog dialog = new TermDbManagerDialog(getShell());
dialog.setDialogUseFor(TermDbManagerDialog.TYPE_DBSELECTED);
if (dialog.open() == Window.OK) {
Iterator<DatabaseModelBean> it = dialog.getHasSelectedDatabase().keySet().iterator();
List<DatabaseModelBean> list = new ArrayList<DatabaseModelBean>();
while (it.hasNext()) {
list.add(it.next());
}
if (list.size() > 0) {
dbModel = list.get(0); // 只取第一个.
text.setText(dbModel.getDbName());
}
}
}
});
setControl(container);
}
public void executeImport(String tbxFile, IProgressMonitor monitor) throws InterruptedException {
if (monitor == null) {
monitor = new NullProgressMonitor();
}
monitor.beginTask("", 100);
monitor.setTaskName(Messages.getString("wizard.TermDbManagerImportWizardTbxPage.task1"));
int tbxResult = -10;
String message = "";
try {
tbxResult = DatabaseService.importTbxWithFile(tbxFile, monitor, dbModel.toDbMetaData(),
getTbxImportStrategy());
} catch (ImportException e) {
message = e.getMessage();
}
if (!message.equals("")) {
final String _message = message;
Display.getDefault().asyncExec(new Runnable() {
public void run() {
setErrorMessage(_message);
}
});
throw new InterruptedException();
}
StringBuffer resultMessage = new StringBuffer();
if (!resultMessage.toString().equals("")) {
final String _message = resultMessage.toString();
Display.getDefault().asyncExec(new Runnable() {
public void run() {
setErrorMessage(_message);
}
});
throw new InterruptedException();
}
if (tbxResult != DatabaseService.SUCCESS) {
if (tbxResult == DatabaseService.FAILURE_1) {
resultMessage.append(Messages.getString("wizard.TermDbManagerImportWizardTbxPage.msg1"));
} else if (tbxResult == DatabaseService.FAILURE_2) {
resultMessage.append(Messages.getString("wizard.TermDbManagerImportWizardTbxPage.msg2"));
} else if (tbxResult == DatabaseService.FAILURE_3) {
resultMessage.append(Messages.getString("wizard.TermDbManagerImportWizardTbxPage.msg3"));
} else if (tbxResult == DatabaseService.FAILURE_4) {
resultMessage.append(Messages.getString("wizard.TermDbManagerImportWizardTbxPage.msg4"));
} else if (tbxResult == DatabaseService.FAILURE) {
resultMessage.append(Messages.getString("wizard.TermDbManagerImportWizardTbxPage.msg5"));
} else if (tbxResult == DatabaseService.CANCEL) {
resultMessage.append(Messages.getString("wizard.TermDbManagerImportWizardTbxPage.msg6"));
}
if (!resultMessage.toString().equals("")) {
final String _message = resultMessage.toString();
Display.getDefault().asyncExec(new Runnable() {
public void run() {
setErrorMessage(_message);
}
});
}
throw new InterruptedException();
} else {
Display.getDefault().asyncExec(new Runnable() {
public void run() {
setErrorMessage(null);
setMessage(Messages.getString("wizard.TermDbManagerImportWizardTbxPage.msg7"));
}
});
}
monitor.done();
}
/**
* 输入验证器 ;
*/
private void validator() {
setErrorMessage(null);
setMessage(null);
String tmxFile = getTBXFile();
if (tmxFile == null) {
setErrorMessage(Messages.getString("wizard.TermDbManagerImportWizardTbxPage.msg8"));
setPageComplete(false);
} else {
setErrorMessage(null);
setPageComplete(true);
}
if (this.dbModel == null) {
setErrorMessage(Messages.getString("wizard.TermDbManagerImportWizardTbxPage.msg9"));
setPageComplete(false);
} else {
setErrorMessage(null);
setPageComplete(true);
}
}
/**
* 从首选项中读取导入策略
* @return ;
*/
public int getTbxImportStrategy() {
IPreferenceStore ps = Activator.getDefault().getPreferenceStore();
return ps.getInt(TBPreferenceConstants.TB_UPDATE);
}
public String getTBXFile() {
String file = tbxFileText.getText().trim();
if (file == null || file.length() == 0) {
return null;
}
return file;
}
}
| 10,293 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
TbxImportWizardTbxPage.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/database/net.heartsome.cat.database.ui.tb/src/net/heartsome/cat/database/ui/tb/wizard/TbxImportWizardTbxPage.java | /**
* ImportWizardTbxPage.java
*
* Version information :
*
* Date:Oct 20, 2011
*
* Copyright notice :
* 本文件及其附带的相关文件包含机密信息,仅限瀚特盛科技有限公司指定的,与本项目有关的内部人员和客户联络人员查阅和使用。
* 如果您不是本保密声明中指定的收件者,请立即销毁本文件,禁止对本文件或根据本文件中的内容采取任何其他行动,
* 包括但不限于:泄露本文件中的信息、以任何方式制作本文件全部或部分内容之副本、将本文件或其相关副本提供给任何其他人。
*/
package net.heartsome.cat.database.ui.tb.wizard;
import net.heartsome.cat.common.bean.DatabaseModelBean;
import net.heartsome.cat.common.core.exception.ImportException;
import net.heartsome.cat.database.bean.TBPreferenceConstants;
import net.heartsome.cat.database.service.DatabaseService;
import net.heartsome.cat.database.ui.tb.Activator;
import net.heartsome.cat.database.ui.tb.resource.Messages;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.wizard.WizardPage;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
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.Display;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author Jason
* @version
* @since JDK1.6
*/
public class TbxImportWizardTbxPage extends WizardPage {
Logger logger = LoggerFactory.getLogger(TbxImportWizardTbxPage.class);
private Text tbxFileText;
private DatabaseModelBean dbModel;
/**
* Create the wizard.
*/
public TbxImportWizardTbxPage(DatabaseModelBean dbModel) {
super("wizardPage");
setTitle(Messages.getString("wizard.TbxImportWizardTbxPage.title"));
setDescription(Messages.getString("wizard.TbxImportWizardTbxPage.desc"));
setImageDescriptor(Activator.getImageDescriptor("images/dialog/import-tbx-logo.png"));
this.dbModel = dbModel;
}
/**
* Create contents of the wizard.
* @param parent
*/
public void createControl(Composite parent) {
Composite container = new Composite(parent, SWT.NULL);
container.setLayout(new GridLayout(3, false));
Label lblTmx = new Label(container, SWT.NONE);
lblTmx.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
lblTmx.setText(Messages.getString("wizard.TbxImportWizardTbxPage.lblTmx"));
tbxFileText = new Text(container, SWT.BORDER | SWT.READ_ONLY);
tbxFileText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
tbxFileText.addModifyListener(new ModifyListener() {
public void modifyText(ModifyEvent e) {
String tmxFile = getTBXFile();
if (tmxFile == null) {
setErrorMessage(Messages.getString("wizard.TbxImportWizardTbxPage.msg1"));
setPageComplete(false);
} else {
setErrorMessage(null);
setPageComplete(true);
}
}
});
Button tmxFileBorwserBtn = new Button(container, SWT.NONE);
tmxFileBorwserBtn.setText(Messages.getString("wizard.TbxImportWizardTbxPage.tmxFileBorwserBtn"));
tmxFileBorwserBtn.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
FileDialog dlg = new FileDialog(getShell());
String[] filterExt = { "*.tbx", "*.xlsx", "*.txt" };
dlg.setFilterExtensions(filterExt);
String path = dlg.open();
if (path != null) {
tbxFileText.setText(path);
}
}
});
setControl(container);
}
public void executeImport(String tbxFile, IProgressMonitor monitor) throws InterruptedException {
if (monitor == null) {
monitor = new NullProgressMonitor();
}
monitor.beginTask("", 100);
monitor.setTaskName(Messages.getString("wizard.TbxImportWizardTbxPage.task1"));
int tbxResult = -10;
String message = "";
try {
tbxResult = DatabaseService.importTbxWithFile(tbxFile, monitor, dbModel.toDbMetaData(),
getTbxImportStrategy());
} catch (ImportException e) {
message = e.getMessage();
}
if (!message.equals("")) {
final String _message = message;
Display.getDefault().asyncExec(new Runnable() {
public void run() {
setErrorMessage(_message);
}
});
throw new InterruptedException();
}
StringBuffer resultMessage = new StringBuffer();
if (tbxResult != DatabaseService.SUCCESS) {
if (tbxResult == DatabaseService.FAILURE_1) {
resultMessage.append(Messages.getString("wizard.TbxImportWizardTbxPage.msg1"));
} else if (tbxResult == DatabaseService.FAILURE_2) {
resultMessage.append(Messages.getString("wizard.TbxImportWizardTbxPage.msg2"));
} else if (tbxResult == DatabaseService.FAILURE_3) {
resultMessage.append(Messages.getString("wizard.TbxImportWizardTbxPage.msg3"));
} else if (tbxResult == DatabaseService.FAILURE_4) {
resultMessage.append(Messages.getString("wizard.TbxImportWizardTbxPage.msg4"));
} else if (tbxResult == DatabaseService.FAILURE) {
resultMessage.append(Messages.getString("wizard.TbxImportWizardTbxPage.msg5"));
} else if (tbxResult == DatabaseService.CANCEL) {
resultMessage.append(Messages.getString("wizard.TbxImportWizardTbxPage.msg6"));
}
if (!resultMessage.toString().equals("")) {
final String _message = resultMessage.toString();
Display.getDefault().asyncExec(new Runnable() {
public void run() {
setErrorMessage(_message);
}
});
}
throw new InterruptedException();
}
monitor.done();
}
/**
* 从首选项中读取导入策略
* @return ;
*/
public int getTbxImportStrategy() {
IPreferenceStore ps = Activator.getDefault().getPreferenceStore();
return ps.getInt(TBPreferenceConstants.TB_UPDATE);
}
public String getTBXFile() {
String file = tbxFileText.getText().trim();
if (file == null || file.length() == 0) {
return null;
}
return file;
}
}
| 6,295 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
TermDbManagerImportWizard.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/database/net.heartsome.cat.database.ui.tb/src/net/heartsome/cat/database/ui/tb/wizard/TermDbManagerImportWizard.java | /**
* ImportWizard.java
*
* Version information :
*
* Date:Oct 20, 2011
*
* Copyright notice :
* 本文件及其附带的相关文件包含机密信息,仅限瀚特盛科技有限公司指定的,与本项目有关的内部人员和客户联络人员查阅和使用。
* 如果您不是本保密声明中指定的收件者,请立即销毁本文件,禁止对本文件或根据本文件中的内容采取任何其他行动,
* 包括但不限于:泄露本文件中的信息、以任何方式制作本文件全部或部分内容之副本、将本文件或其相关副本提供给任何其他人。
*/
package net.heartsome.cat.database.ui.tb.wizard;
import java.lang.reflect.InvocationTargetException;
import net.heartsome.cat.database.ui.tb.resource.Messages;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.wizard.Wizard;
/**
* @author Jason
* @version
* @since JDK1.6
*/
public class TermDbManagerImportWizard extends Wizard {
private TermDbManagerImportWizardTbxPage tbxPage;
public TermDbManagerImportWizard() {
setNeedsProgressMonitor(true);
}
@Override
public void addPages() {
setWindowTitle(Messages.getString("wizard.TermDbManagerImportWizard.title"));
tbxPage = new TermDbManagerImportWizardTbxPage();
addPage(tbxPage);
}
@Override
public boolean performFinish() {
final String tbxFile = tbxPage.getTBXFile();
if (tbxFile == null || tbxFile.equals("")) {
tbxPage.setErrorMessage(Messages.getString("wizard.TermDbManagerImportWizard.msg"));
return false;
}
tbxPage.setErrorMessage(null);
tbxPage.setMessage(null);
IRunnableWithProgress runnable = new IRunnableWithProgress() {
public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
tbxPage.executeImport(tbxFile, monitor);
}
};
try {
getContainer().run(true, true, runnable);
} catch (InvocationTargetException e) {
e.printStackTrace();
return false;
} catch (InterruptedException e) {
e.printStackTrace();
return false;
}
// tbxPage.setPageComplete(false);
return true;
}
}
| 2,171 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
TBDatabaseInitializer.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/database/net.heartsome.cat.database.ui.tb/src/net/heartsome/cat/database/ui/tb/preference/TBDatabaseInitializer.java | /**
* TBDatabaseInitializer.java
*
* Version information :
*
* Date:2012-5-2
*
* Copyright notice :
* 本文件及其附带的相关文件包含机密信息,仅限瀚特盛科技有限公司指定的,与本项目有关的内部人员和客户联络人员查阅和使用。
* 如果您不是本保密声明中指定的收件者,请立即销毁本文件,禁止对本文件或根据本文件中的内容采取任何其他行动,
* 包括但不限于:泄露本文件中的信息、以任何方式制作本文件全部或部分内容之副本、将本文件或其相关副本提供给任何其他人。
*/
package net.heartsome.cat.database.ui.tb.preference;
import net.heartsome.cat.database.bean.TBPreferenceConstants;
import net.heartsome.cat.database.ui.tb.Activator;
import org.eclipse.core.runtime.preferences.AbstractPreferenceInitializer;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.ui.PlatformUI;
/**
* @author jason
* @version
* @since JDK1.6
*/
public class TBDatabaseInitializer extends AbstractPreferenceInitializer {
/** (non-Javadoc)
* @see org.eclipse.core.runtime.preferences.AbstractPreferenceInitializer#initializeDefaultPreferences()
*/
@Override
public void initializeDefaultPreferences() {
// 设置术语库默认更新策略
IPreferenceStore store = Activator.getDefault().getPreferenceStore();
store.setDefault(TBPreferenceConstants.TB_UPDATE, TBPreferenceConstants.TB_REPEAT_OVERWRITE);
// 初始化新建向导记住信息
store.setDefault(TBPreferenceConstants.TB_RM_DBTYPE, "");
store.setDefault(TBPreferenceConstants.TB_RM_INSTANCE, "");
store.setDefault(TBPreferenceConstants.TB_RM_SERVER, "");
store.setDefault(TBPreferenceConstants.TB_RM_PORT, "");
store.setDefault(TBPreferenceConstants.TB_RM_PATH, "");
store.setDefault(TBPreferenceConstants.TB_RM_USERNAME, "");
store.setDefault(TBPreferenceConstants.TB_CASE_SENSITIVE, true);
PlatformUI.getPreferenceStore().setDefault(TBPreferenceConstants.TB_CASE_SENSITIVE,true);
}
}
| 2,058 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
TBDatabasePage.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/database/net.heartsome.cat.database.ui.tb/src/net/heartsome/cat/database/ui/tb/preference/TBDatabasePage.java | package net.heartsome.cat.database.ui.tb.preference;
import net.heartsome.cat.database.bean.TBPreferenceConstants;
import net.heartsome.cat.database.ui.tb.Activator;
import net.heartsome.cat.database.ui.tb.resource.Messages;
import net.heartsome.cat.common.ui.HsImageLabel;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.preference.PreferencePage;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Group;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPreferencePage;
import org.eclipse.ui.PlatformUI;
/**
* 首选项>术语库设置界面
* @author peason
* @version
* @since JDK1.6
*/
public class TBDatabasePage extends PreferencePage implements IWorkbenchPreferencePage {
public static final String ID = "net.heartsome.cat.database.ui.tb.preference.tbpage";
private IPreferenceStore preferenceStore;
/** 术语库更新设置 > 始终增加单选按钮 */
private Button btnAlwaysAdd;
/** 术语库更新设置 > 重复覆盖单选按钮 */
private Button btnRepeatOverwrite;
/** 术语库更新设置 > 重复合并单选按钮 */
private Button btnRepeatMerge;
/** 术语库更新设置 > 重复忽略单选按钮 */
private Button btnRepeatIgnore;
private Button btnCaseSensitive;
/**
* 构造函数
*/
public TBDatabasePage() {
setTitle(Messages.getString("preference.TBDatabasePage.title"));
setPreferenceStore(Activator.getDefault().getPreferenceStore());
preferenceStore = getPreferenceStore();
}
public void init(IWorkbench workbench) {
// TODO Auto-generated method stub
}
@Override
protected Control createContents(Composite parent) {
// TODO Auto-generated method stub
Composite tparent = new Composite(parent, SWT.NONE);
tparent.setLayout(new GridLayout());
tparent.setLayoutData(new GridData(GridData.FILL_BOTH));
// 添加术语匹配是否忽略大小写
{
Group commonGroup1 = new Group(tparent, SWT.NONE);
commonGroup1.setLayout(new GridLayout());
commonGroup1.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
commonGroup1.setText(Messages.getString("preference.TBDatabasePage.commontitle"));
HsImageLabel imageLbale1 = new HsImageLabel(Messages.getString("preference.TBDatabasePage.commonsearchterm"),
Activator.getImageDescriptor("images/preference/tb/tb_update_32.png"));
Composite comp1 = imageLbale1.createControl(commonGroup1);
btnCaseSensitive = new Button(comp1, SWT.CHECK);
btnCaseSensitive.setText(Messages.getString("preference.TBDatabasePage.commonCasesensitive"));
btnCaseSensitive.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
imageLbale1.computeSize();
}
Group commonGroup = new Group(tparent, SWT.NONE);
commonGroup.setLayout(new GridLayout());
commonGroup.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
commonGroup.setText(Messages.getString("preference.TBDatabasePage.commonGroup"));
HsImageLabel imageLbale = new HsImageLabel(Messages.getString("preference.TBDatabasePage.imageLbale"),
Activator.getImageDescriptor("images/preference/tb/tb_update_32.png"));
Composite comp = imageLbale.createControl(commonGroup);
btnAlwaysAdd = new Button(comp, SWT.RADIO);
btnAlwaysAdd.setText(Messages.getString("preference.TBDatabasePage.btnAlwaysAdd"));
btnAlwaysAdd.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
btnRepeatOverwrite = new Button(comp, SWT.RADIO);
btnRepeatOverwrite.setText(Messages.getString("preference.TBDatabasePage.btnRepeatOverwrite"));
btnRepeatOverwrite.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
btnRepeatMerge = new Button(comp, SWT.RADIO);
btnRepeatMerge.setText(Messages.getString("preference.TBDatabasePage.btnRepeatMerge"));
btnRepeatMerge.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
btnRepeatIgnore = new Button(comp, SWT.RADIO);
btnRepeatIgnore.setText(Messages.getString("preference.TBDatabasePage.btnRepeatIgnore"));
btnRepeatIgnore.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
parent.pack();
imageLbale.computeSize();
int intUpdateTB = preferenceStore.getInt(TBPreferenceConstants.TB_UPDATE);
setInitValues(intUpdateTB);
return parent;
}
@Override
public boolean performOk() {
if (btnAlwaysAdd.getSelection()) {
preferenceStore.setValue(TBPreferenceConstants.TB_UPDATE, TBPreferenceConstants.TB_ALWAYS_ADD);
} else if (btnRepeatOverwrite.getSelection()) {
preferenceStore.setValue(TBPreferenceConstants.TB_UPDATE, TBPreferenceConstants.TB_REPEAT_OVERWRITE);
} else if (btnRepeatMerge.getSelection()) {
preferenceStore.setValue(TBPreferenceConstants.TB_UPDATE, TBPreferenceConstants.TB_REPEAT_MERGE);
} else if (btnRepeatIgnore.getSelection()) {
preferenceStore.setValue(TBPreferenceConstants.TB_UPDATE, TBPreferenceConstants.TB_REPEAT_IGNORE);
}
// 设置是否忽略大小写
preferenceStore.setDefault(TBPreferenceConstants.TB_CASE_SENSITIVE, btnCaseSensitive.getSelection());
//
PlatformUI.getPreferenceStore().setDefault(TBPreferenceConstants.TB_CASE_SENSITIVE, btnCaseSensitive.getSelection());
return true;
}
@Override
protected void performDefaults() {
int intUpdateTB = preferenceStore.getDefaultInt(TBPreferenceConstants.TB_UPDATE);
setInitValues(intUpdateTB);
}
private void setInitValues(int intUpdateTB) {
if (intUpdateTB == TBPreferenceConstants.TB_ALWAYS_ADD) {
btnAlwaysAdd.setSelection(true);
btnRepeatOverwrite.setSelection(false);
btnRepeatMerge.setSelection(false);
btnRepeatIgnore.setSelection(false);
} else if (intUpdateTB == TBPreferenceConstants.TB_REPEAT_OVERWRITE) {
btnAlwaysAdd.setSelection(false);
btnRepeatOverwrite.setSelection(true);
btnRepeatMerge.setSelection(false);
btnRepeatIgnore.setSelection(false);
} else if (intUpdateTB == TBPreferenceConstants.TB_REPEAT_MERGE) {
btnAlwaysAdd.setSelection(false);
btnRepeatOverwrite.setSelection(false);
btnRepeatMerge.setSelection(true);
btnRepeatIgnore.setSelection(false);
} else if (intUpdateTB == TBPreferenceConstants.TB_REPEAT_IGNORE) {
btnAlwaysAdd.setSelection(false);
btnRepeatOverwrite.setSelection(false);
btnRepeatMerge.setSelection(false);
btnRepeatIgnore.setSelection(true);
}
// 设置是否忽略大小写
btnCaseSensitive.setSelection(preferenceStore.getDefaultBoolean(TBPreferenceConstants.TB_CASE_SENSITIVE));
}
}
| 6,589 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
TermDbManagerDialog.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/database/net.heartsome.cat.database.ui.tb/src/net/heartsome/cat/database/ui/tb/dialog/TermDbManagerDialog.java | /**
* DatabaseManagerDialog.java
*
* Version information :
*
* Date:Dec 1, 2011
*
* Copyright notice :
* 本文件及其附带的相关文件包含机密信息,仅限瀚特盛科技有限公司指定的,与本项目有关的内部人员和客户联络人员查阅和使用。
* 如果您不是本保密声明中指定的收件者,请立即销毁本文件,禁止对本文件或根据本文件中的内容采取任何其他行动,
* 包括但不限于:泄露本文件中的信息、以任何方式制作本文件全部或部分内容之副本、将本文件或其相关副本提供给任何其他人。
*/
package net.heartsome.cat.database.ui.tb.dialog;
import java.io.File;
import java.sql.SQLException;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import net.heartsome.cat.common.bean.DatabaseModelBean;
import net.heartsome.cat.common.bean.MetaData;
import net.heartsome.cat.common.util.CommonFunction;
import net.heartsome.cat.database.Constants;
import net.heartsome.cat.database.DBOperator;
import net.heartsome.cat.database.SystemDBOperator;
import net.heartsome.cat.database.service.DatabaseService;
import net.heartsome.cat.database.ui.bean.DatabaseManagerDbListBean;
import net.heartsome.cat.database.ui.core.DatabaseConfiger;
import net.heartsome.cat.database.ui.core.DbValidator;
import net.heartsome.cat.database.ui.tb.Activator;
import net.heartsome.cat.database.ui.tb.ImageConstants;
import net.heartsome.cat.database.ui.tb.resource.Messages;
import net.heartsome.cat.database.ui.tb.wizard.TbxImportWizard;
import net.heartsome.cat.database.ui.tb.wizard.TermDbManagerImportWizardDialog;
import org.eclipse.core.databinding.DataBindingContext;
import org.eclipse.core.databinding.beans.BeanProperties;
import org.eclipse.core.databinding.observable.list.WritableList;
import org.eclipse.core.databinding.observable.value.IObservableValue;
import org.eclipse.core.databinding.validation.ValidationStatus;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.databinding.swt.WidgetProperties;
import org.eclipse.jface.databinding.viewers.ViewerSupport;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.IInputValidator;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.dialogs.TrayDialog;
import org.eclipse.jface.layout.GridDataFactory;
import org.eclipse.jface.resource.JFaceResources;
import org.eclipse.jface.viewers.ArrayContentProvider;
import org.eclipse.jface.viewers.ColumnLabelProvider;
import org.eclipse.jface.viewers.DoubleClickEvent;
import org.eclipse.jface.viewers.IDoubleClickListener;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.TableViewerColumn;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.window.Window;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.BusyIndicator;
import org.eclipse.swt.custom.ScrolledComposite;
import org.eclipse.swt.events.DisposeEvent;
import org.eclipse.swt.events.DisposeListener;
import org.eclipse.swt.events.MenuDetectEvent;
import org.eclipse.swt.events.MenuDetectListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.ShellAdapter;
import org.eclipse.swt.events.ShellEvent;
import org.eclipse.swt.graphics.Cursor;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.DirectoryDialog;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.Sash;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.widgets.ToolBar;
import org.eclipse.swt.widgets.ToolItem;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.ui.PlatformUI;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author Jason
* @version
* @since JDK1.6
*/
public class TermDbManagerDialog extends TrayDialog {
// The last known tree width
private static int lastTreeWidth = 180;
private Point lastShellSize;
/** The tree viewer. */
private TreeViewer treeViewer;
private Text hostText;
private Text usernameText;
private Text passwordText;
private Text instanceText;
private Text portText;
private Button searchBtn;
private TableViewer dbTableViewer;
private static String currDbType;
private static String lastSelectedServerId;
/**
* 和界面相关的输入模型,与界面输入组件进行绑定.与会与选择具体的配置进行关联
*/
private DatabaseModelBean currServer;
private Map<String, List<DatabaseModelBean>> treeInputMap;
private DatabaseConfiger configer;
private Map<String, MetaData> dbMetaDataMap;
private Text locationText;
private Button borwserBtn;
private List<DatabaseManagerDbListBean> currServerdbList;
private WritableList currServerdbListInput;
private Image internalDbImg = Activator.getImageDescriptor(ImageConstants.INTERNALDB).createImage();
private Image mySqlImg = Activator.getImageDescriptor(ImageConstants.MYSQL).createImage();
private Image oracleImg = Activator.getImageDescriptor(ImageConstants.ORACLE).createImage();
private Image sqlServerImg = Activator.getImageDescriptor(ImageConstants.SQLSERVER).createImage();
private Image postgreImg = Activator.getImageDescriptor(ImageConstants.POSTGRESQL).createImage();
private Image ipImg = Activator.getImageDescriptor(ImageConstants.IP).createImage();
private Image sqliteImg = Activator.getImageDescriptor(ImageConstants.SQLITE).createImage();
/**
* tree pop menu
* @see #initTreePopMenu()
*/
private Menu treePopMenu;
private Logger logger = LoggerFactory.getLogger(TermDbManagerDialog.class);
private List<DatabaseModelBean> needUpdateToFile = new ArrayList<DatabaseModelBean>();
/**
* Create the dialog.
* @param parentShell
*/
public TermDbManagerDialog(Shell parentShell) {
super(parentShell);
this.currServer = new DatabaseModelBean();
this.currServerdbList = new ArrayList<DatabaseManagerDbListBean>();
this.configer = new DatabaseConfiger();
this.treeInputMap = configer.getAllServerConfig();
this.dbMetaDataMap = DatabaseService.getSystemSuportDbMetaData();
List<String> dbTypeList = DatabaseService.getSystemSuportDbType();
for (int i = 0; i < dbTypeList.size(); i++) {
String type = dbTypeList.get(i);
if (treeInputMap.containsKey(type)) {
continue;
} else {
treeInputMap.put(type, new ArrayList<DatabaseModelBean>());
}
}
treeInputMap.remove(Constants.DBTYPE_SQLITE);
setHelpAvailable(true);
}
@Override
protected void configureShell(Shell newShell) {
super.configureShell(newShell);
newShell.setText(Messages.getString("dialog.TermDbManagerDialog.title"));
newShell.addShellListener(new ShellAdapter() {
public void shellActivated(ShellEvent e) {
if (lastShellSize == null) {
lastShellSize = getShell().getSize();
}
}
});
}
@Override
protected boolean isResizable() {
return true;
}
@Override
protected Control createContents(final Composite parent) {
Control control = super.createContents(parent);
selectSaveItem();
return control;
}
/**
* 添加帮助按钮 robert 2012-09-06
*/
@Override
protected Control createHelpControl(Composite parent) {
// ROBERTHELP 术语库管理
String language = CommonFunction.getSystemLanguage();
final String helpUrl = MessageFormat.format(
"/net.heartsome.cat.ts.ui.help/html/{0}/ch06s04.html#tb-management", language);
Image helpImage = JFaceResources.getImage(DLG_IMG_HELP);
ToolBar toolBar = new ToolBar(parent, SWT.FLAT | SWT.NO_FOCUS);
((GridLayout) parent.getLayout()).numColumns++;
toolBar.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_CENTER));
final Cursor cursor = new Cursor(parent.getDisplay(), SWT.CURSOR_HAND);
toolBar.setCursor(cursor);
toolBar.addDisposeListener(new DisposeListener() {
public void widgetDisposed(DisposeEvent e) {
cursor.dispose();
}
});
ToolItem helpItem = new ToolItem(toolBar, SWT.NONE);
helpItem.setImage(helpImage);
helpItem.setToolTipText(JFaceResources.getString("helpToolTip")); //$NON-NLS-1$
helpItem.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
PlatformUI.getWorkbench().getHelpSystem().displayHelpResource(helpUrl);
}
});
return toolBar;
}
/**
* 选择当前选中的内容 ;
*/
private void selectSaveItem() {
if (getCurrDbType() != null) {
boolean expanded = getTreeViewer().getExpandedState(getCurrDbType());
if (!expanded) {
getTreeViewer().setExpandedState(getCurrDbType(), !expanded);
}
DatabaseModelBean lastSelectItem = findServerBean(getCurrDbType(), getLastSelectedServer());
if (lastSelectItem != null) {
getTreeViewer().setSelection(new StructuredSelection(lastSelectItem), true);
getTreeViewer().getControl().setFocus();
} else {
getTreeViewer().setSelection(new StructuredSelection(getCurrDbType()), true);
getTreeViewer().getControl().setFocus();
}
}
}
/**
* 查找上次的选中的项
* @param dbType
* 数据库类型
* @param id
* 服务器ID
* @return ;
*/
private DatabaseModelBean findServerBean(String dbType, String id) {
List<DatabaseModelBean> list = treeInputMap.get(dbType);
if (list == null) {
return null;
}
for (int i = 0; i < list.size(); i++) {
if (list.get(i).getId().equals(id)) {
return list.get(i);
}
}
return null;
}
/**
* Create contents of the dialog.
* @param parent
*/
@Override
protected Control createDialogArea(Composite parent) {
final Composite composite = (Composite) super.createDialogArea(parent);
GridLayout parentLayout = ((GridLayout) composite.getLayout());
parentLayout.numColumns = 4;
parentLayout.marginHeight = 0;
parentLayout.marginWidth = 0;
parentLayout.marginTop = 0;
parentLayout.verticalSpacing = 0;
parentLayout.horizontalSpacing = 0;
Control treeControl = createTreeAreaContents(composite);
createSash(composite, treeControl);
Label versep = new Label(composite, SWT.SEPARATOR | SWT.VERTICAL);
GridData verGd = new GridData(GridData.FILL_VERTICAL | GridData.GRAB_VERTICAL);
versep.setLayoutData(verGd);
versep.setLayoutData(new GridData(SWT.LEFT, SWT.FILL, false, true));
Composite pageAreaComposite = new Composite(composite, SWT.NONE);
pageAreaComposite.setLayoutData(new GridData(GridData.FILL_BOTH));
GridLayout layout = new GridLayout(1, true);
layout.marginHeight = 0;
layout.marginWidth = 0;
layout.verticalSpacing = 0;
pageAreaComposite.setLayout(layout);
// Build the Page container
Composite pageContainer = createPageContainer(pageAreaComposite);
GridData pageContainerData = new GridData(GridData.FILL_BOTH);
pageContainerData.horizontalIndent = IDialogConstants.HORIZONTAL_MARGIN;
pageContainer.setLayoutData(pageContainerData);
// Build the separator line
Label bottomSeparator = new Label(parent, SWT.HORIZONTAL | SWT.SEPARATOR);
bottomSeparator.setLayoutData(new GridData(GridData.FILL_HORIZONTAL | GridData.GRAB_HORIZONTAL));
return composite;
}
/**
* Create contents of the button bar.
* @param parent
*/
@Override
protected void createButtonsForButtonBar(Composite parent) {
if (dialogType == TYPE_DBMANAGE) {
createButton(parent, IDialogConstants.CANCEL_ID, IDialogConstants.CLOSE_LABEL, false);
} else {
super.createButtonsForButtonBar(parent);
}
getShell().setDefaultButton(searchBtn);
initDataBindings();
}
private int dialogType = 0; // default is DatabaseManager
public static final int TYPE_DBMANAGE = 0;
public static final int TYPE_DBSELECTED = 1;
/**
* 设置对话框的用处,决定了生成的按钮
* @param type
* ;
*/
public void setDialogUseFor(int type) {
this.dialogType = type;
}
public int getDialogUseFor() {
return this.dialogType;
}
/**
* 创建右侧页面内容
* @param parent
* 页面容器
* @return ;
*/
protected Composite createPageContainer(Composite parent) {
Composite outer = new Composite(parent, SWT.NONE);
GridData outerData = new GridData(GridData.FILL_BOTH | GridData.GRAB_HORIZONTAL | GridData.GRAB_VERTICAL);
outerData.horizontalIndent = IDialogConstants.HORIZONTAL_MARGIN;
outer.setLayout(new GridLayout());
outer.setLayoutData(outerData);
// Create an outer composite for spacing
ScrolledComposite scrolled = new ScrolledComposite(outer, SWT.V_SCROLL | SWT.H_SCROLL);
// always show the focus control
scrolled.setShowFocusedControl(true);
scrolled.setExpandHorizontal(true);
scrolled.setExpandVertical(true);
scrolled.setLayoutData(new GridData(GridData.FILL_BOTH | GridData.GRAB_HORIZONTAL | GridData.GRAB_VERTICAL));
GridLayout gld = new GridLayout(1, false);
gld.marginWidth = 0;
gld.marginHeight = 0;
scrolled.setLayout(gld);
Composite result = new Composite(scrolled, SWT.NONE);
GridData resultData = new GridData(GridData.FILL_BOTH | GridData.GRAB_HORIZONTAL | GridData.GRAB_VERTICAL);
result.setLayoutData(resultData);
GridLayout gl_result = new GridLayout(1, false);
gl_result.marginWidth = 0;
gl_result.marginHeight = 0;
result.setLayout(gl_result);
Group parameterGroup = new Group(result, SWT.NONE);
parameterGroup.setText(Messages.getString("dialog.TermDbManagerDialog.parameterGroup"));
GridLayout parameterLayout = new GridLayout(4, false);
parameterGroup.setLayout(parameterLayout);
GridData parameterGridData = new GridData(GridData.FILL_HORIZONTAL);
parameterGroup.setLayoutData(parameterGridData);
Label label = new Label(parameterGroup, SWT.RIGHT);
label.setText(Messages.getString("dialog.TermDbManagerDialog.lblHost"));
GridDataFactory.swtDefaults().align(SWT.RIGHT, SWT.CENTER).applyTo(label);
hostText = new Text(parameterGroup, SWT.BORDER);
hostText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
label = new Label(parameterGroup, SWT.RIGHT);
label.setText(Messages.getString("dialog.TermDbManagerDialog.lblPort"));
GridDataFactory.swtDefaults().align(SWT.RIGHT, SWT.CENTER).applyTo(label);
portText = new Text(parameterGroup, SWT.BORDER);
label = new Label(parameterGroup, SWT.RIGHT);
label.setText(Messages.getString("dialog.TermDbManagerDialog.lblInstance"));
GridDataFactory.swtDefaults().align(SWT.RIGHT, SWT.CENTER).applyTo(label);
instanceText = new Text(parameterGroup, SWT.BORDER);
instanceText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
new Label(parameterGroup, SWT.NONE);
new Label(parameterGroup, SWT.NONE);
label = new Label(parameterGroup, SWT.RIGHT);
label.setText(Messages.getString("dialog.TermDbManagerDialog.lblLocation"));
GridDataFactory.swtDefaults().align(SWT.RIGHT, SWT.CENTER).applyTo(label);
locationText = new Text(parameterGroup, SWT.BORDER);
locationText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
borwserBtn = new Button(parameterGroup, SWT.NONE);
borwserBtn.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, true, false, 2, 1));
borwserBtn.setText(Messages.getString("dialog.TermDbManagerDialog.borwserBtn"));
borwserBtn.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent event) {
DirectoryDialog dlg = new DirectoryDialog(getShell());
String path = dlg.open();
if (path != null) {
locationText.setText(path);
}
}
});
label = new Label(parameterGroup, SWT.RIGHT);
label.setText(Messages.getString("dialog.TermDbManagerDialog.lblUsername"));
GridDataFactory.swtDefaults().align(SWT.RIGHT, SWT.CENTER).applyTo(label);
usernameText = new Text(parameterGroup, SWT.BORDER);
usernameText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
label = new Label(parameterGroup, SWT.RIGHT);
label.setText(Messages.getString("dialog.TermDbManagerDialog.lblPwd"));
GridDataFactory.swtDefaults().align(SWT.RIGHT, SWT.CENTER).applyTo(label);
passwordText = new Text(parameterGroup, SWT.BORDER | SWT.PASSWORD);
passwordText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
Composite btnComposite = new Composite(parameterGroup, SWT.NONE);
btnComposite.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 4, 1));
GridLayout btnCompositeLayout = new GridLayout(1, false);
btnCompositeLayout.marginHeight = 0;
btnCompositeLayout.marginWidth = 0;
btnComposite.setLayout(btnCompositeLayout);
// remenmberBtn = new Button(btnComposite, SWT.CHECK|SWT.BORDER);
// remenmberBtn.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1));
// remenmberBtn.setText("将本次连接信息添加到数据库类型的快捷连接方式(&R)");
// remenmberBtn.setSelection(true);
searchBtn = new Button(btnComposite, SWT.NONE);
searchBtn.setText(Messages.getString("dialog.TermDbManagerDialog.searchBtn"));
searchBtn.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
BusyIndicator.showWhile(getShell().getDisplay(), new Runnable() {
public void run() {
// 输入合法性检查
IStatus status = validator();
if (status.getSeverity() != IStatus.OK) {
MessageDialog.openInformation(getShell(),
Messages.getString("dialog.TermDbManagerDialog.msgTitle"), status.getMessage());
return;
}
SystemDBOperator sysDbOp = getCurrSysDbOp();
if (sysDbOp == null) {
return;
}
// 连接检查
if (!sysDbOp.checkDbConnection()) {
MessageDialog.openInformation(getShell(),
Messages.getString("dialog.TermDbManagerDialog.msgTitle"),
Messages.getString("dialog.TermDbManagerDialog.msg1"));
return;
}
// if (remenmberBtn.getSelection() == true) {
// 当前数据库类型下的所有服务器
List<DatabaseModelBean> currDbTypeServers = treeInputMap.get(getCurrDbType());
if (currServer.getId().equals("")) {
addServerWithExistCheck(currServer, currDbTypeServers);
getTreeViewer().refresh();
selectSaveItem(); // 在树上选择当前操作的节点
}
// ISelection selection = getTreeViewer().getSelection();
// if (selection.isEmpty()) {
// return;
// }
// } else { // 不记住信息
executeSearch(sysDbOp);
// }
}
});
}
});
Group tableComposite = new Group(result, SWT.NONE);
tableComposite.setText(Messages.getString("dialog.TermDbManagerDialog.tableComposite"));
tableComposite.setLayout(new GridLayout(1, false));
tableComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));
dbTableViewer = new TableViewer(tableComposite, SWT.BORDER | SWT.FULL_SELECTION | SWT.SINGLE | SWT.H_SCROLL
| SWT.V_SCROLL);
Table table = dbTableViewer.getTable();
table.setLinesVisible(true);
table.setHeaderVisible(true);
GridData tableGd = new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1);
tableGd.heightHint = 180;
table.setLayoutData(tableGd);
createColumn(dbTableViewer);
if (getDialogUseFor() == TYPE_DBSELECTED) {
dbTableViewer.addDoubleClickListener(new IDoubleClickListener() {
public void doubleClick(DoubleClickEvent event) {
okPressed();
}
});
}
dbTableViewer.setContentProvider(new ArrayContentProvider());
currServerdbListInput = new WritableList(currServerdbList, DatabaseManagerDbListBean.class);
dbTableViewer.setInput(currServerdbListInput);
Composite composite = new Composite(tableComposite, SWT.NONE);
GridLayout gl_composite = new GridLayout(3, false);
gl_composite.marginHeight = 0;
gl_composite.marginWidth = 0;
composite.setLayout(gl_composite);
composite.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
Button btnc = new Button(composite, SWT.NONE);
btnc.setText(Messages.getString("dialog.TermDbManagerDialog.btnc"));
btnc.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
createNewDatabase();
}
});
Button btnd_1 = new Button(composite, SWT.NONE);
btnd_1.setText(Messages.getString("dialog.TermDbManagerDialog.btnd_1"));
btnd_1.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
BusyIndicator.showWhile(getShell().getDisplay(), new Runnable() {
public void run() {
ISelection selection = getDbTableViewer().getSelection();
if (selection.isEmpty()) {
return;
}
if (MessageDialog.openConfirm(getShell(),
Messages.getString("dialog.TermDbManagerDialog.msgTitle"),
Messages.getString("dialog.TermDbManagerDialog.msg2"))) {
IStructuredSelection structuredSelection = (IStructuredSelection) selection;
@SuppressWarnings("unchecked")
List<DatabaseManagerDbListBean> needDeletes = structuredSelection.toList();
SystemDBOperator dbop = getCurrSysDbOp();
for (int i = 0; i < needDeletes.size(); i++) {
try {
String dbName = needDeletes.get(i).getDbName();
dbop.dropDb(dbName);
dbop.removeSysDb(dbName);
} catch (Exception e1) {
logger.error(Messages.getString("dialog.TermDbManagerDialog.logger1"), e1);
MessageDialog.openError(getShell(),
Messages.getString("dialog.TermDbManagerDialog.msgTitle"),
Messages.getString("dialog.TermDbManagerDialog.msg3") + e1.getMessage());
break;
}
currServerdbListInput.remove(needDeletes.get(i));
}
}
}
});
}
});
Button importBtn = new Button(composite, SWT.NONE);
importBtn.setText(Messages.getString("dialog.TermDbManagerDialog.importBtn"));
importBtn.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
ISelection selection = getDbTableViewer().getSelection();
if (selection.isEmpty()) {
MessageDialog.openInformation(getShell(),
Messages.getString("dialog.TermDbManagerDialog.msgTitle"),
Messages.getString("dialog.TermDbManagerDialog.msg4"));
return;
}
IStructuredSelection stcSel = (IStructuredSelection) selection;
DatabaseManagerDbListBean dbBean = (DatabaseManagerDbListBean) stcSel.getFirstElement();
DatabaseModelBean dbModelBean = new DatabaseModelBean();
currServer.copyToOtherIntance(dbModelBean);
dbModelBean.setDbName(dbBean.getDbName());
TbxImportWizard wizard = new TbxImportWizard(dbModelBean);
TermDbManagerImportWizardDialog dlg = new TermDbManagerImportWizardDialog(getShell(), wizard);
if (dlg.open() == 0) {
executeSearch(getCurrSysDbOp()); // 重新加载内容
}
}
});
Point searchPoint = searchBtn.computeSize(SWT.DEFAULT, SWT.DEFAULT, true);
Point createPoint = btnc.computeSize(SWT.DEFAULT, SWT.DEFAULT, true);
Point remPoint = btnd_1.computeSize(SWT.DEFAULT, SWT.DEFAULT, true);
Point importPoint = importBtn.computeSize(SWT.DEFAULT, SWT.DEFAULT, true);
int width = Math.max(importPoint.x, Math.max(remPoint.x, Math.max(searchPoint.x, createPoint.x)));
GridData btnData = new GridData();
btnData.widthHint = width + 10;
btnc.setLayoutData(btnData);
btnd_1.setLayoutData(btnData);
importBtn.setLayoutData(btnData);
searchBtn.getLayoutData();
GridData searchData = new GridData(SWT.RIGHT, SWT.CENTER, true, true, 4, 1);
searchData.widthHint = width + 10;
searchBtn.setLayoutData(searchData);
scrolled.setContent(result);
scrolled.setMinSize(getShell().computeSize(SWT.DEFAULT, SWT.DEFAULT));
return result;
}
/**
* 创建左侧树
* @param parent
* the SWT parent for the tree area controls.
* @return the new <code>Control</code>.
*/
protected Control createTreeAreaContents(Composite parent) {
// Build the tree an put it into the composite.
treeViewer = createTreeViewer(parent);
treeViewer.setInput(treeInputMap);
updateTreeFont(JFaceResources.getDialogFont());
layoutTreeAreaControl(treeViewer.getControl());
initTreePopMenu();
return treeViewer.getControl();
}
/**
* 初始化树右键菜单 ;
*/
private void initTreePopMenu() {
MenuManager menuManager = new MenuManager("");
menuManager.add(new Action(Messages.getString("dialog.TermDbManagerDialog.deleteAction")) {
@Override
public void run() {
ISelection selection = getTreeViewer().getSelection();
if (selection.isEmpty()) {
return;
}
IStructuredSelection structuredSelection = (IStructuredSelection) selection;
Object obj = structuredSelection.getFirstElement();
if (obj instanceof DatabaseModelBean) {
List<DatabaseModelBean> currDbTypeServers = treeInputMap.get(currDbType);
configer.deleteServerById(((DatabaseModelBean) obj).getId());
int i = currDbTypeServers.indexOf(obj);
currDbTypeServers.remove(i);
getTreeViewer().refresh();
// selectSaveItem();
// setLastSelectedServer(null);
if (currDbTypeServers.size() != 0) {
if (i > currDbTypeServers.size() - 1) {
setLastSelectedServer(currDbTypeServers.get(i - 1).getId());
} else {
setLastSelectedServer(currDbTypeServers.get(i).getId());
}
initUI(false);
} else {
setLastSelectedServer(null);
initUI(true);
}
selectSaveItem();
}
}
});
Tree tree = treeViewer.getTree();
this.treePopMenu = menuManager.createContextMenu(tree);
}
/**
* @param control
* the <code>Control</code> to lay out.
*/
protected void layoutTreeAreaControl(Control control) {
GridData gd = new GridData(GridData.FILL_VERTICAL);
gd.widthHint = getLastRightWidth();
gd.verticalSpan = 1;
control.setLayoutData(gd);
}
/**
* Create a new <code>TreeViewer</code>.
* @param parent
* the parent <code>Composite</code>.
* @return the <code>TreeViewer</code>.
*/
protected TreeViewer createTreeViewer(Composite parent) {
final TreeViewer viewer = new TreeViewer(parent, SWT.NONE);
addListeners(viewer);
viewer.setLabelProvider(new TreeLableProvider());
viewer.setContentProvider(new TreeContentProvider());
return viewer;
}
/**
* Add Selection Listener to tree viewer
* @param viewer
* ;
*/
private void addListeners(final TreeViewer viewer) {
// 选择事件
viewer.addPostSelectionChangedListener(new ISelectionChangedListener() {
public void selectionChanged(SelectionChangedEvent event) {
ISelection selection = event.getSelection();
if (selection.isEmpty()) {
return;
}
IStructuredSelection structuredSelection = (IStructuredSelection) selection;
Object obj = structuredSelection.getFirstElement();
if (obj instanceof DatabaseModelBean) {
DatabaseModelBean bean = (DatabaseModelBean) obj;
setCurrDbType(bean.getDbType());
bean.copyToOtherIntance(currServer);
SystemDBOperator dbop = getCurrSysDbOp();
if (dbop != null) {
executeSearch(dbop);
}
initUI(false); // 当数据库类型发生改变时重新初始化界面
} else if (obj instanceof String) {
setCurrDbType((String) obj);
resetInputValue();
currServerdbListInput.clear();
initUI(true);
}
}
});
// 双击展开事件
((Tree) viewer.getControl()).addSelectionListener(new SelectionAdapter() {
public void widgetDefaultSelected(final SelectionEvent event) {
ISelection selection = viewer.getSelection();
if (selection.isEmpty()) {
return;
}
IStructuredSelection structuredSelection = (IStructuredSelection) selection;
Object obj = structuredSelection.getFirstElement();
if (obj instanceof String) {
String type = (String) obj;
boolean expanded = viewer.getExpandedState(type);
viewer.setExpandedState(type, !expanded);
}
}
});
// 右键菜单事件,判断何时出现右键菜单
viewer.getControl().addMenuDetectListener(new MenuDetectListener() {
public void menuDetected(MenuDetectEvent e) {
ISelection selection = viewer.getSelection();
if (selection.isEmpty()) {
return;
}
IStructuredSelection structuredSelection = (IStructuredSelection) selection;
Object obj = structuredSelection.getFirstElement();
Tree tree = treeViewer.getTree();
if (obj instanceof DatabaseModelBean) {
tree.setMenu(treePopMenu); // 将菜单挂到树上
} else {
tree.setMenu(null);
}
}
});
}
/**
* 获取当前服务器操作对象
* @return ;
*/
private SystemDBOperator getCurrSysDbOp() {
return DatabaseService.getSysDbOperateByMetaData(currServer.toDbMetaData());
}
/**
* Update the tree to use the specified <code>Font</code>.
* @param dialogFont
* the <code>Font</code> to use.
*/
protected void updateTreeFont(Font dialogFont) {
getTreeViewer().getControl().setFont(dialogFont);
}
/**
* @return the <code>TreeViewer</code> for this dialog.
*/
public TreeViewer getTreeViewer() {
return treeViewer;
}
/**
* @return The <code>TableViewer</code> for database list in dialog ;
*/
public TableViewer getDbTableViewer() {
return this.dbTableViewer;
}
/**
* @return the need update to file server configure
*/
public List<DatabaseModelBean> getNeedUpdateToFile() {
return this.needUpdateToFile;
}
/**
* Create the sash with right control on the right. Note that this method assumes GridData for the layout data of
* the rightControl.
* @param composite
* @param rightControl
* @return Sash
*/
protected Sash createSash(final Composite composite, final Control rightControl) {
final Sash sash = new Sash(composite, SWT.VERTICAL);
sash.setLayoutData(new GridData(GridData.FILL_VERTICAL));
sash.setBackground(composite.getDisplay().getSystemColor(SWT.COLOR_LIST_BACKGROUND));
// the following listener resizes the tree control based on sash deltas.
// If necessary, it will also grow/shrink the dialog.
sash.addListener(SWT.Selection, new Listener() {
/*
* (non-Javadoc)
*
* @see org.eclipse.swt.widgets.Listener#handleEvent(org.eclipse.swt. widgets.Event)
*/
public void handleEvent(Event event) {
if (event.detail == SWT.DRAG) {
return;
}
int shift = event.x - sash.getBounds().x;
GridData data = (GridData) rightControl.getLayoutData();
int newWidthHint = data.widthHint + shift;
if (newWidthHint < 20) {
return;
}
Point computedSize = getShell().computeSize(SWT.DEFAULT, SWT.DEFAULT);
Point currentSize = getShell().getSize();
// if the dialog wasn't of a custom size we know we can shrink
// it if necessary based on sash movement.
boolean customSize = !computedSize.equals(currentSize);
data.widthHint = newWidthHint;
setLastTreeWidth(newWidthHint);
composite.layout(true);
// recompute based on new widget size
computedSize = getShell().computeSize(SWT.DEFAULT, SWT.DEFAULT);
// if the dialog was of a custom size then increase it only if
// necessary.
if (customSize) {
computedSize.x = Math.max(computedSize.x, currentSize.x);
}
computedSize.y = Math.max(computedSize.y, currentSize.y);
if (computedSize.equals(currentSize)) {
return;
}
setShellSize(computedSize.x, computedSize.y);
lastShellSize = getShell().getSize();
}
});
return sash;
}
/**
* Get the last known right side width.
* @return the width.
*/
protected int getLastRightWidth() {
return lastTreeWidth;
}
/**
* Save the last known tree width.
* @param width
* the width.
*/
private void setLastTreeWidth(int width) {
lastTreeWidth = width;
}
/**
* Return the initial size of the dialog.
*/
@Override
protected Point getInitialSize() {
return getShell().computeSize(SWT.DEFAULT, SWT.DEFAULT);
}
/**
* Changes the shell size to the given size, ensuring that it is no larger than the display bounds.
* @param width
* the shell width
* @param height
* the shell height
*/
private void setShellSize(int width, int height) {
Rectangle preferred = getShell().getBounds();
preferred.width = width;
preferred.height = height;
getShell().setBounds(getConstrainedShellBounds(preferred));
}
/**
* The TreeViewer label provider
* @author Jason
* @version
* @since JDK1.6
*/
class TreeLableProvider extends LabelProvider {
/**
* @param element
* must be an instance of <code>IPreferenceNode</code>.
* @see org.eclipse.jface.viewers.ILabelProvider#getText(java.lang.Object)
*/
public String getText(Object element) {
if (element instanceof String) {
String dbType = (String) element;
if (dbType.equals(Constants.DBTYPE_MYSQL)) {
dbType = Constants.DBTYPE_MYSQL_FOR_UI;
} else if (dbType.equals(Constants.DBTYPE_MSSQL2005)) {
dbType = Constants.DBTYPE_MSSQL2005_FOR_UI;
} else if (dbType.equals(Constants.DBTYPE_SQLITE)) {
dbType = Messages.getString("dialog.db.recommend");
}
return dbType;
} else {
DatabaseModelBean bean = (DatabaseModelBean) element;
StringBuffer urlStr = new StringBuffer();
if (bean.getDbType().equals(Constants.DBTYPE_INTERNALDB)
|| bean.getDbType().equals(Constants.DBTYPE_SQLITE)) {
urlStr.append(bean.getItlDBLocation());
} else {
urlStr.append(bean.getHost());
urlStr.append(":");
urlStr.append(bean.getPort());
if (bean.getInstance() != null && !bean.getInstance().equals("")) {
urlStr.append("/");
urlStr.append(bean.getInstance());
}
}
return urlStr.toString();
}
}
/**
* @param element
* must be an instance of String or <code>DatabaseModelBean</code>.
* @see org.eclipse.jface.viewers.ILabelProvider#getImage(java.lang.Object)
*/
public Image getImage(Object element) {
if (element instanceof String) {
String dbtype = (String) element;
if (dbtype.equals(Constants.DBTYPE_INTERNALDB)) {
return internalDbImg;
} else if (dbtype.equals(Constants.DBTYPE_MYSQL)) {
return mySqlImg;
} else if (dbtype.equals(Constants.DBTYPE_MSSQL2005)) {
return sqlServerImg;
} else if (dbtype.equals(Constants.DBTYPE_POSTGRESQL)) {
return postgreImg;
} else if (dbtype.equals(Constants.DBTYPE_Oracle)) {
return oracleImg;
} else if (dbtype.equals(Constants.DBTYPE_SQLITE)) {
return sqliteImg;
} else {
return null;
}
} else if (element instanceof DatabaseModelBean) {
return ipImg;
} else {
return null;
}
}
}
/**
* The TreeViewer content provider
* @author Jason
* @version
* @since JDK1.6
*/
class TreeContentProvider implements ITreeContentProvider {
private Map<String, List<DatabaseModelBean>> map;
public void dispose() {
}
@SuppressWarnings("unchecked")
public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
this.map = (Map<String, List<DatabaseModelBean>>) newInput;
}
public Object[] getElements(Object inputElement) {
List<Object> t = new ArrayList<Object>(map.keySet());
int size = t.size();
Object[] temp = new Object[size];
if (t.contains(Constants.DBTYPE_INTERNALDB)) {
temp[size - 1] = Constants.DBTYPE_INTERNALDB;
}
if (t.contains(Constants.DBTYPE_MYSQL)) {
temp[size - 5] = Constants.DBTYPE_MYSQL;
}
if (t.contains(Constants.DBTYPE_MSSQL2005)) {
temp[size - 4] = Constants.DBTYPE_MSSQL2005;
}
if (t.contains(Constants.DBTYPE_POSTGRESQL)) {
temp[size - 2] = Constants.DBTYPE_POSTGRESQL;
}
if (t.contains(Constants.DBTYPE_Oracle)) {
temp[size - 3] = Constants.DBTYPE_Oracle;
}
if(t.contains(Constants.DBTYPE_SQLITE)){
temp[0] = Constants.DBTYPE_SQLITE;
}
return temp;
}
public Object[] getChildren(Object parentElement) {
if (parentElement instanceof String) {
String dbType = (String) parentElement;
List<DatabaseModelBean> servers = map.get(dbType);
Collections.sort(servers, new Comparator<DatabaseModelBean>() {
public int compare(DatabaseModelBean o1, DatabaseModelBean o2) {
return o1.getHost().compareTo(o2.getHost());
}
});
return servers.toArray();
}
return null;
}
public Object getParent(Object element) {
return null;
}
public boolean hasChildren(Object element) {
if (element instanceof String) {
if (map.get(element).size() != 0) {
return true;
}
}
return false;
}
}
/**
* 初始化数据绑定 将界面与<code>currServer</code>进行绑定
* @return ;
*/
protected void initDataBindings() {
DataBindingContext bindingContext = new DataBindingContext();
IObservableValue widgetValue = WidgetProperties.text(SWT.Modify).observe(instanceText);
final IObservableValue instanceModelValue = BeanProperties.value("instance").observe(currServer);
bindingContext.bindValue(widgetValue, instanceModelValue, null, null);
widgetValue = WidgetProperties.text(SWT.Modify).observe(hostText);
final IObservableValue hostModelValue = BeanProperties.value("host").observe(currServer);
bindingContext.bindValue(widgetValue, hostModelValue, null, null);
widgetValue = WidgetProperties.text(SWT.Modify).observe(portText);
final IObservableValue protModelValue = BeanProperties.value("port").observe(currServer);
bindingContext.bindValue(widgetValue, protModelValue, null, null);
widgetValue = WidgetProperties.text(SWT.Modify).observe(locationText);
final IObservableValue locationModelValue = BeanProperties.value("itlDBLocation").observe(currServer);
bindingContext.bindValue(widgetValue, locationModelValue, null, null);
widgetValue = WidgetProperties.text(SWT.Modify).observe(usernameText);
final IObservableValue usernameModelValue = BeanProperties.value("userName").observe(currServer);
bindingContext.bindValue(widgetValue, usernameModelValue, null, null);
widgetValue = WidgetProperties.text(SWT.Modify).observe(passwordText);
final IObservableValue passwordModelValue = BeanProperties.value("password").observe(currServer);
bindingContext.bindValue(widgetValue, passwordModelValue, null, null);
ViewerSupport.bind(dbTableViewer, currServerdbListInput,
BeanProperties.values(new String[] { "index", "dbName", "langs" }));
}
/**
* 创建Table列
* @param viewer
* ;
*/
private void createColumn(final TableViewer viewer) {
String[] clmnTitles = { Messages.getString("dialog.TermDbManagerDialog.clmnTitles1"),
Messages.getString("dialog.TermDbManagerDialog.clmnTitles2"),
Messages.getString("dialog.TermDbManagerDialog.clmnTitles3") };
int[] clmnBounds = { 50, 100, 100 };
TableViewerColumn col = createTableViewerColumn(viewer, clmnTitles[0], clmnBounds[0], 0);
col.setLabelProvider(new ColumnLabelProvider() {
public String getText(Object element) {
DatabaseManagerDbListBean bean = (DatabaseManagerDbListBean) element;
return bean.getIndex();
}
});
col = createTableViewerColumn(viewer, clmnTitles[1], clmnBounds[1], 1);
col.setLabelProvider(new ColumnLabelProvider() {
public String getText(Object element) {
DatabaseManagerDbListBean bean = (DatabaseManagerDbListBean) element;
return bean.getDbName();
}
});
col = createTableViewerColumn(viewer, clmnTitles[2], clmnBounds[2], 2);
col.setLabelProvider(new ColumnLabelProvider() {
public String getText(Object element) {
DatabaseManagerDbListBean bean = (DatabaseManagerDbListBean) element;
return bean.getLangs();
}
});
}
/**
* 设置TableViewer 列属性
* @param viewer
* @param title
* 列标题
* @param bound
* 列宽
* @param colNumber
* 列序号
* @return {@link TableViewerColumn};
*/
private TableViewerColumn createTableViewerColumn(TableViewer viewer, String title, int bound, final int colNumber) {
final TableViewerColumn viewerColumn = new TableViewerColumn(viewer, SWT.NONE | SWT.Resize);
final TableColumn column = viewerColumn.getColumn();
column.setText(title);
column.setWidth(bound);
column.setResizable(true);
column.setMoveable(true);
return viewerColumn;
}
/**
* 输入验证器 ;
*/
private IStatus validator() {
String instance = currServer.getInstance();
String host = currServer.getHost();
String port = currServer.getPort();
String location = currServer.getItlDBLocation();
String username = currServer.getUserName();
MetaData dbMetaData = dbMetaDataMap.get(currServer.getDbType());
if (dbMetaData.dataPathSupported()) {
File f = new File(location);
if (location == null || location.trim().length() == 0) {
if (dbMetaData.getDbType().equals(Constants.DBTYPE_INTERNALDB)) {
return ValidationStatus.error(Messages.getString("dialog.TermDbManagerDialog.msg5"));
} else if (dbMetaData.getDbType().equals(Constants.DBTYPE_SQLITE)) {
return ValidationStatus.error(Messages.getString("dialog.TermDbManagerDialog.msg11"));
}
} else if (!f.exists()) {
return ValidationStatus.error(Messages.getString("dialog.TermDbManagerDialog.msg12"));
}
}
if (dbMetaData.serverNameSupported()) {
if (host == null || host.trim().length() == 0) {
return ValidationStatus.error(Messages.getString("dialog.TermDbManagerDialog.msg6"));
}
}
if (dbMetaData.portSupported()) {
if (port == null || port.trim().length() == 0) {
return ValidationStatus.error(Messages.getString("dialog.TermDbManagerDialog.msg7"));
}
}
if (dbMetaData.userNameSupported()) {
if (username == null || username.trim().length() == 0) {
return ValidationStatus.error(Messages.getString("dialog.TermDbManagerDialog.msg8"));
}
}
if (dbMetaData.instanceSupported()) {
if (instance == null || instance.trim().length() == 0) {
return ValidationStatus.error(Messages.getString("dialog.TermDbManagerDialog.msg9"));
}
}
return ValidationStatus.ok();
}
/**
* 检查当前配置是否发生了改变
* @param list
* @param b
* @param metaData
* @return ;
*/
private DatabaseModelBean configIsChanged(List<DatabaseModelBean> list, DatabaseModelBean b, MetaData metaData) {
for (int i = 0; i < list.size(); i++) {
DatabaseModelBean a = list.get(i);
if (a.getId().equals(b.getId())) {
if (metaData.dataPathSupported()) {
if (!a.getItlDBLocation().equals(b.getItlDBLocation())) {
return a;
}
} else {
if (!a.getHost().equals(b.getHost()) || !a.getPort().equals(a.getPort())) {
return a;
}
if (metaData.instanceSupported()) {
if (!a.getInstance().equals(b.getInstance())) {
return a;
}
}
if (metaData.userNameSupported()) {
if (!a.getUserName().equals(b.getUserName()) || !a.getPassword().equals(b.getPassword())) {
return a;
}
}
}
return null;
}
}
return null;
}
/**
* 将当前操作的服务器配置信息添加到配置文件中<br>
* 在添加前,先判断该服务器是否已经存在,如果已经存在则更新
* @param currServer
* 需要处理的配置信息
* @param currDbTypeServers
* 当前数据库类型下的所有服务器,用于显示在界面上;
*/
private void addServerWithExistCheck(DatabaseModelBean currServer, List<DatabaseModelBean> currDbTypeServers) {
DatabaseModelBean bean = currServer.copyToOtherIntance(new DatabaseModelBean());
String existSerId = configer.isServerExist(bean, getCurrDbMetaData());
if (existSerId != null && !existSerId.equals("")) { // 当前服务器配置信息已经存在
if (!bean.getId().equals(existSerId)) {
configer.deleteServerById(bean.getId());
for (DatabaseModelBean temp : currDbTypeServers) {
if (temp.getId().equals(bean.getId())) {
currDbTypeServers.remove(temp);
break;
}
}
}
bean.setId(existSerId);
currServer.setId(existSerId);
updateServer(bean, currDbTypeServers);
return;
}
configer.addServerConfig(bean);
currDbTypeServers.add(bean);
setLastSelectedServer(bean.getId());
}
/**
* 更新当前操作的服务器配置信息到配置文件中
* @param currServer
* 需要处理的服务器配置信息
* @param currDbTypeServers
* 当前数据库类型下的所有服务器,用于显示在界面上;
*/
private void updateServer(DatabaseModelBean currServer, List<DatabaseModelBean> currDbTypeServers) {
MetaData metaDataWithCheck = dbMetaDataMap.get(currServer.getDbType());
DatabaseModelBean hasChanged = configIsChanged(currDbTypeServers, currServer, metaDataWithCheck);
if (hasChanged != null) {
currServer.copyToOtherIntance(hasChanged);
configer.updateServerConfigById(hasChanged.getId(), hasChanged);
}
setLastSelectedServer(currServer.getId());
}
/**
* 设置最后选中的服务器
* @param serverId
* ;
*/
private void setLastSelectedServer(String serverId) {
lastSelectedServerId = serverId;
}
/**
* 获最后选中的服务器
* @return ;
*/
private String getLastSelectedServer() {
return lastSelectedServerId;
}
/**
* 获取当前操作的数据库类型
* @return ;
*/
private String getCurrDbType() {
return currDbType;
}
/**
* 设置当前操作的数据库类型
* @param dbType
* 当前操作的数据库类型 ;
*/
private void setCurrDbType(String dbType) {
currDbType = dbType;
}
/**
* 获取当前数据库类型的元数据
* @return ;
*/
protected MetaData getCurrDbMetaData() {
return dbMetaDataMap.get(getCurrDbType());
}
/**
* 当选择数据库类型节点时,重置所有输入 ;
*/
private void resetInputValue() {
MetaData metaData = dbMetaDataMap.get(getCurrDbType());
currServer.setId("");
currServer.setDbType(metaData.getDbType());
currServer.setItlDBLocation("");
if (metaData.dataPathSupported()) {
currServer.setItlDBLocation(metaData.getDataPath());
}
currServer.setHost("");
if (metaData.serverNameSupported()) {
currServer.setHost(metaData.getServerName());
}
currServer.setInstance("");
if (metaData.instanceSupported()) {
currServer.setInstance(metaData.getInstance());
}
currServer.setPort("");
if (metaData.portSupported()) {
currServer.setPort(metaData.getPort());
}
currServer.setUserName("");
if (metaData.userNameSupported()) {
currServer.setUserName(metaData.getUserName());
}
currServer.setPassword("");
if (metaData.passwordSupported()) {
currServer.setPassword(metaData.getPassword());
}
}
/**
* 根据当前操作不同的数据库类型,初始化界面 ;
*/
private void initUI(boolean isAdd) {
MetaData curDbMetaData = dbMetaDataMap.get(getCurrDbType());
if (!isAdd) {
Control[] childrens = locationText.getParent().getChildren();
for (Control c : childrens) {
if (!(c instanceof Composite)) {
if (c instanceof Text || c instanceof Button) {
c.setEnabled(false);
}
} else {
Composite com = (Composite) c;
Control[] ch = com.getChildren();
for (Control chl : ch) {
if (c instanceof Text || c instanceof Button) {
chl.setEnabled(false);
}
}
}
}
} else {
if (curDbMetaData.dataPathSupported()) {
locationText.setEnabled(true);
borwserBtn.setEnabled(true);
} else {
locationText.setEnabled(false);
borwserBtn.setEnabled(false);
}
if (curDbMetaData.serverNameSupported()) {
hostText.setEnabled(true);
} else {
hostText.setEnabled(false);
}
if (curDbMetaData.instanceSupported()) {
instanceText.setEnabled(true);
} else {
instanceText.setEnabled(false);
}
if (curDbMetaData.portSupported()) {
portText.setEnabled(true);
} else {
portText.setEnabled(false);
}
if (curDbMetaData.userNameSupported()) {
usernameText.setEnabled(true);
} else {
usernameText.setEnabled(false);
}
if (curDbMetaData.passwordSupported()) {
passwordText.setEnabled(true);
} else {
passwordText.setEnabled(false);
}
}
}
private List<DatabaseManagerDbListBean> searchCurrServerDatabase(SystemDBOperator sysDbOp,
DatabaseModelBean currServer) {
List<DatabaseManagerDbListBean> temp = new ArrayList<DatabaseManagerDbListBean>();
// 检查是否创建了系统库
if (!sysDbOp.checkSysDb()) {
// MessageDialog.openInformation(getShell(), "提示信息",
// "当前服务器上没有创建任何库");
setLastSelectedServer(null);
return null;
}
// 检查是否创建了库
List<String> dbNames = sysDbOp.getSysDbNames(Constants.DB_TYPE_TB);
if (dbNames.size() == 0) {
// MessageDialog.openInformation(getShell(), "提示信息",
// "当前服务器上没有创建任何库");
setLastSelectedServer(null);
return null;
}
// 获取数据库相关资料,封装了库名称和语言
MetaData metaData = currServer.toDbMetaData();
DBOperator dbop = DatabaseService.getDBOperator(metaData);
for (int i = 0; i < dbNames.size(); i++) {
DatabaseManagerDbListBean bean = new DatabaseManagerDbListBean();
String dbName = dbNames.get(i);
bean.setIndex(i + 1 + "");
bean.setDbName(dbName);
metaData.setDatabaseName(dbName);
dbop.setMetaData(metaData);
String lang = "";
try {
dbop.start();
List<String> langs = dbop.getLanguages();
for (int j = 0; j < langs.size(); j++) {
lang += langs.get(j);
if (j != langs.size() - 1) {
lang += ", ";
}
}
} catch (Exception e1) {
logger.error("", e1);
continue;
} finally {
try {
if (dbop != null) {
dbop.end();
}
} catch (SQLException e) {
logger.error("", e);
}
}
if (lang.equals("")) {
bean.setLangs(Messages.getString("dialog.TermDbManagerDialog.msg10"));
} else {
bean.setLangs(lang);
}
temp.add(bean);
}
return temp;
}
/**
* 执行查询
* @param sysDbOp
* ;
*/
private void executeSearch(final SystemDBOperator sysDbOp) {
BusyIndicator.showWhile(getShell().getDisplay(), new Runnable() {
public void run() {
// 连接检查
if (!sysDbOp.checkDbConnection()) {
MessageDialog.openInformation(getShell(),
Messages.getString("dialog.TermDbManagerDialog.msgTitle"),
Messages.getString("dialog.TermDbManagerDialog.msg1"));
setLastSelectedServer(null);
return;
}
// 获取数据库信息,包括名称和语言
List<DatabaseManagerDbListBean> temp = searchCurrServerDatabase(sysDbOp, currServer);
currServerdbListInput.clear();
if (temp != null) {
currServerdbListInput.addAll(temp);
if (temp.size() > 0) {
getDbTableViewer().setSelection(new StructuredSelection(temp.get(0)));
}
setLastSelectedServer(currServer.getId());
}
}
});
}
/**
* 创建新库 ;
*/
private void createNewDatabase() {
// 数据库连接参数输入合法性检查
IStatus status = validator();
if (status.getSeverity() != IStatus.OK) {
MessageDialog.openInformation(getShell(), Messages.getString("dialog.TermDbManagerDialog.msgTitle"),
status.getMessage());
return;
}
SystemDBOperator sysDbOp = getCurrSysDbOp();
if (sysDbOp == null) {
return;
}
// 连接检查
if (!sysDbOp.checkDbConnection()) {
MessageDialog.openInformation(getShell(), Messages.getString("dialog.TermDbManagerDialog.msgTitle"),
Messages.getString("dialog.TermDbManagerDialog.msg1"));
return;
}
TermDbNameInputDialog inputDbNameialog = new TermDbNameInputDialog(getShell(),
Messages.getString("dialog.TermDbManagerDialog.inputDbNameialogTitle"),
Messages.getString("dialog.TermDbManagerDialog.inputDbNameialogMsg"), "", new IInputValidator() {
public String isValid(String newText) {
String vRs = DbValidator.valiateDbName(newText);
return vRs;
}
});
inputDbNameialog.setSystemDbOp(sysDbOp);
if (inputDbNameialog.open() == Window.OK) {
executeSearch(sysDbOp); // 刷新界面
}
}
/** key-数据库的数据库封装,value-库中的语言 */
private Map<DatabaseModelBean, String> hasSelected;
/**
* 当使用该对话框作为数据库选择时 ;
*/
private void executeSelectDatabase() {
ISelection selection = getDbTableViewer().getSelection();
if (selection.isEmpty()) {
return;
}
hasSelected = new HashMap<DatabaseModelBean, String>();
IStructuredSelection structuredSelection = (IStructuredSelection) selection;
Iterator<?> it = structuredSelection.iterator();
while (it.hasNext()) {
DatabaseManagerDbListBean dbBean = (DatabaseManagerDbListBean) it.next();
DatabaseModelBean dbModelBean = new DatabaseModelBean();
currServer.copyToOtherIntance(dbModelBean);
dbModelBean.setDbName(dbBean.getDbName());
// Fix Bug #3290 导出TMX/TBX--导出内容异常 去掉语言前后的空格
hasSelected.put(dbModelBean, dbBean.getLangs().replace(" ", ""));
}
}
protected void okPressed() {
if (getDialogUseFor() == TYPE_DBSELECTED) {
executeSelectDatabase();
}
super.okPressed();
}
@Override
public boolean close() {
if (internalDbImg != null && !internalDbImg.isDisposed()) {
internalDbImg.dispose();
}
if (mySqlImg != null && !mySqlImg.isDisposed()) {
mySqlImg.dispose();
}
if (oracleImg != null && !oracleImg.isDisposed()) {
oracleImg.dispose();
}
if (sqlServerImg != null && !sqlServerImg.isDisposed()) {
sqlServerImg.dispose();
}
if (postgreImg != null && !postgreImg.isDisposed()) {
postgreImg.dispose();
}
if (ipImg != null && !ipImg.isDisposed()) {
ipImg.dispose();
}
if (sqliteImg != null && !sqliteImg.isDisposed()) {
sqliteImg.dispose();
}
return super.close();
}
/**
* 获取当前选择的库
* @return ;
*/
public Map<DatabaseModelBean, String> getHasSelectedDatabase() {
if (hasSelected != null) {
return hasSelected;
} else {
return new HashMap<DatabaseModelBean, String>();
}
}
}
| 55,131 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
TBSearchCellRenderer.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/database/net.heartsome.cat.database.ui.tb/src/net/heartsome/cat/database/ui/tb/dialog/TBSearchCellRenderer.java | package net.heartsome.cat.database.ui.tb.dialog;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import net.heartsome.cat.common.util.TextUtil;
import net.heartsome.cat.ts.ui.grid.XGridCellRenderer;
import org.eclipse.nebula.widgets.grid.Grid;
import org.eclipse.nebula.widgets.grid.GridItem;
import org.eclipse.nebula.widgets.grid.IInternalWidget;
import org.eclipse.nebula.widgets.grid.internal.BranchRenderer;
import org.eclipse.nebula.widgets.grid.internal.CheckBoxRenderer;
import org.eclipse.nebula.widgets.grid.internal.ToggleRenderer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.DisposeEvent;
import org.eclipse.swt.events.DisposeListener;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.graphics.TextLayout;
import org.eclipse.swt.graphics.TextStyle;
/**
* 用于对单元格样式进行设置的类
* @author peason
* @version
* @since JDK1.6
*/
@SuppressWarnings({ "restriction" })
public class TBSearchCellRenderer extends XGridCellRenderer {
int leftMargin = 4;
int rightMargin = 4;
int topMargin = 0;
int bottomMargin = 0;
int textTopMargin = 1;
int textBottomMargin = 2;
private int insideMargin = 3;
int treeIndent = 20;
private ToggleRenderer toggleRenderer;
private BranchRenderer branchRenderer;
private CheckBoxRenderer checkRenderer;
private TextLayout textLayout;
/** 添加样式的文本 */
private String strText;
/** 设置样式时是否区分大小写 */
private boolean blnIsCaseSensitive;
/** 设置样式时是否使用正则表达式 */
private boolean blnIsApplyRegular;
private TextStyle style;
/** 要加样式的列 */
private int styleColumn = 1;
public String getStrText() {
return strText;
}
public void setStrText(String strText) {
this.strText = strText;
}
public boolean isBtnIsCaseSensitive() {
return blnIsCaseSensitive;
}
public void setBlnIsCaseSensitive(boolean blnIsCaseSensitive) {
this.blnIsCaseSensitive = blnIsCaseSensitive;
}
public int getStyleColumn() {
return styleColumn;
}
public void setStyleColumn(int styleColumn) {
this.styleColumn = styleColumn;
}
public boolean isBlnIsApplyRegular() {
return blnIsApplyRegular;
}
public void setBlnIsApplyRegular(boolean blnIsApplyRegular) {
this.blnIsApplyRegular = blnIsApplyRegular;
}
/**
* (non-Javadoc)
* @see org.eclipse.nebula.widgets.grid.IRenderer#paint(org.eclipse.swt.graphics.GC, java.lang.Object)
*/
public void paint(GC gc, Object value) {
GridItem item = (GridItem) value;
gc.setFont(item.getFont(getColumn()));
boolean drawAsSelected = isSelected();
boolean drawBackground = true;
if (isCellSelected()) {
drawAsSelected = true;// (!isCellFocus());
}
if (drawAsSelected) {
gc.setBackground(getDisplay().getSystemColor(SWT.COLOR_LIST_SELECTION));
gc.setForeground(getDisplay().getSystemColor(SWT.COLOR_LIST_SELECTION_TEXT));
} else {
if (item.getParent().isEnabled()) {
Color back = item.getBackground(getColumn());
if (back != null) {
gc.setBackground(back);
} else {
drawBackground = false;
}
} else {
gc.setBackground(getDisplay().getSystemColor(SWT.COLOR_WIDGET_BACKGROUND));
}
gc.setForeground(item.getForeground(getColumn()));
}
if (drawBackground)
gc.fillRectangle(getBounds().x, getBounds().y, getBounds().width, getBounds().height);
int x = leftMargin;
if (isTree()) {
boolean renderBranches = item.getParent().getTreeLinesVisible();
if (renderBranches) {
branchRenderer.setBranches(getBranches(item));
branchRenderer.setIndent(treeIndent);
branchRenderer.setBounds(getBounds().x + x, getBounds().y, getToggleIndent(item),
getBounds().height + 1); // Take into account border
}
x += getToggleIndent(item);
toggleRenderer.setExpanded(item.isExpanded());
toggleRenderer.setHover(getHoverDetail().equals("toggle"));
toggleRenderer.setLocation(getBounds().x + x, (getBounds().height - toggleRenderer.getBounds().height) / 2
+ getBounds().y);
if (item.hasChildren())
toggleRenderer.paint(gc, null);
if (renderBranches) {
branchRenderer.setToggleBounds(toggleRenderer.getBounds());
branchRenderer.paint(gc, null);
}
x += toggleRenderer.getBounds().width + insideMargin;
}
if (isCheck()) {
checkRenderer.setChecked(item.getChecked(getColumn()));
checkRenderer.setGrayed(item.getGrayed(getColumn()));
if (!item.getParent().isEnabled()) {
checkRenderer.setGrayed(true);
}
checkRenderer.setHover(getHoverDetail().equals("check"));
if (isCenteredCheckBoxOnly(item)) {
// Special logic if this column only has a checkbox and is centered
checkRenderer.setBounds(getBounds().x + ((getBounds().width - checkRenderer.getBounds().width) / 2),
(getBounds().height - checkRenderer.getBounds().height) / 2 + getBounds().y,
checkRenderer.getBounds().width, checkRenderer.getBounds().height);
} else {
checkRenderer.setBounds(getBounds().x + x, (getBounds().height - checkRenderer.getBounds().height) / 2
+ getBounds().y, checkRenderer.getBounds().width, checkRenderer.getBounds().height);
x += checkRenderer.getBounds().width + insideMargin;
}
checkRenderer.paint(gc, null);
}
Image image = item.getImage(getColumn());
if (image != null) {
int y = getBounds().y;
y += (getBounds().height - image.getBounds().height) / 2;
gc.drawImage(image, getBounds().x + x, y);
x += image.getBounds().width + insideMargin;
}
if (drawAsSelected) {
gc.setForeground(getDisplay().getSystemColor(SWT.COLOR_LIST_SELECTION_TEXT));
} else {
gc.setForeground(item.getForeground(getColumn()));
}
int width = getBounds().width - x - rightMargin;
int height = getBounds().height - bottomMargin;
int y = getBounds().y + textTopMargin + topMargin;
if (textLayout == null) {
textLayout = new TextLayout(gc.getDevice());
item.getParent().addDisposeListener(new DisposeListener() {
public void widgetDisposed(DisposeEvent e) {
textLayout.dispose();
}
});
}
textLayout.setOrientation(item.getParent().getOrientation());
textLayout.setFont(gc.getFont());
String itemText = item.getText(getColumn());
textLayout.setText(item.getText(getColumn()));
textLayout.setAlignment(getAlignment());
textLayout.setWidth(width < 1 ? 1 : width);
if (styleColumn != -1 && getColumn() == styleColumn) {
if (style == null) {
final Font font = new Font(gc.getDevice(), gc.getFont().getFontData()[0].getName(), gc.getFont()
.getFontData()[0].getHeight(), SWT.BOLD);
style = new TextStyle(font, null, null);
item.getParent().addDisposeListener(new DisposeListener() {
public void widgetDisposed(DisposeEvent e) {
font.dispose();
}
});
}
if (strText != null) {
if (blnIsApplyRegular) {
Pattern pattern = null;
if (blnIsCaseSensitive) {
pattern = Pattern.compile(strText);
} else {
pattern = Pattern.compile(strText, Pattern.CASE_INSENSITIVE);
}
Matcher matcher = pattern.matcher(itemText);
while (matcher.find()) {
textLayout.setStyle(style, matcher.start(), matcher.end() - 1);
}
} else {
int index;
if (blnIsCaseSensitive) {
index = itemText.indexOf(strText);
} else {
index = itemText.toUpperCase().indexOf(strText.toUpperCase());
}
if (index != -1) {
textLayout.setStyle(null, 0, itemText.length() -1);
for (int i = 1; i < strText.length(); i++) {
int j = TextUtil.indexOf(itemText, strText, i, blnIsCaseSensitive);
if (j != -1) {
textLayout.setStyle(style, j, j + strText.length() - 1);
} else {
break;
}
}
}
}
}
}
if (item.getParent().isAutoHeight()) {
int textHeight = topMargin + textTopMargin;
for (int cnt = 0; cnt < textLayout.getLineCount(); cnt++)
textHeight += textLayout.getLineBounds(cnt).height;
textHeight += textBottomMargin + bottomMargin;
Object obj = item.getData("itemHeight");
if(getColumn() != item.getParent().getColumnCount() - 1){
if(obj != null){
int heigth = (Integer) obj;
textHeight = Math.max(textHeight, heigth);
}
item.setData("itemHeight", textHeight);
} else {
int heigth = (Integer) obj;
textHeight = Math.max(textHeight, heigth);
if(textHeight != item.getHeight()){
item.setHeight(textHeight);
}
item.setData("itemHeight", null);
}
}
y += getVerticalAlignmentAdjustment(textLayout.getBounds().height, height);
textLayout.draw(gc, getBounds().x + x, y);
if (item.getParent().getLinesVisible()) {
if (isCellSelected()) {
gc.setForeground(getDisplay().getSystemColor(SWT.COLOR_WIDGET_DARK_SHADOW));
} else {
gc.setForeground(item.getParent().getLineColor());
}
gc.drawLine(getBounds().x, getBounds().y + getBounds().height, getBounds().x + getBounds().width - 1,
getBounds().y + getBounds().height);
gc.drawLine(getBounds().x + getBounds().width - 1, getBounds().y, getBounds().x + getBounds().width - 1,
getBounds().y + getBounds().height);
}
if (isCellFocus()) {
Rectangle focusRect = new Rectangle(getBounds().x, getBounds().y, getBounds().width - 1, getBounds().height);
gc.setForeground(getDisplay().getSystemColor(SWT.COLOR_LIST_FOREGROUND));
gc.drawRectangle(focusRect);
if (isFocus()) {
focusRect.x++;
focusRect.width -= 2;
focusRect.y++;
focusRect.height -= 2;
gc.drawRectangle(focusRect);
}
}
}
/**
* Calculates the sequence of branch lines which should be rendered for the provided item
* @param item
* @return an array of integers composed using the constants in {@link BranchRenderer}
*/
private int[] getBranches(GridItem item) {
int[] branches = new int[item.getLevel() + 1];
GridItem[] roots = item.getParent().getRootItems();
// Is this a node or a leaf?
if (item.getParentItem() == null) {
// Add descender if not last item
if (!item.isExpanded() && roots[roots.length - 1].equals(item)) {
if (item.hasChildren())
branches[item.getLevel()] = BranchRenderer.LAST_ROOT;
else
branches[item.getLevel()] = BranchRenderer.SMALL_L;
} else {
if (item.hasChildren())
branches[item.getLevel()] = BranchRenderer.ROOT;
else
branches[item.getLevel()] = BranchRenderer.SMALL_T;
}
} else if (item.hasChildren())
if (item.isExpanded())
branches[item.getLevel()] = BranchRenderer.NODE;
else
branches[item.getLevel()] = BranchRenderer.NONE;
else
branches[item.getLevel()] = BranchRenderer.LEAF;
// Branch for current item
GridItem parent = item.getParentItem();
if (parent == null)
return branches;
// Are there siblings below this item?
if (parent.indexOf(item) < parent.getItemCount() - 1)
branches[item.getLevel() - 1] = BranchRenderer.T;
// Is the next node a root?
else if (parent.getParentItem() == null && !parent.equals(roots[roots.length - 1]))
branches[item.getLevel() - 1] = BranchRenderer.T;
// This must be the last element at this level
else
branches[item.getLevel() - 1] = BranchRenderer.L;
Grid grid = item.getParent();
item = parent;
parent = item.getParentItem();
// Branches for parent items
while (item.getLevel() > 0) {
if (parent.indexOf(item) == parent.getItemCount() - 1) {
if (parent.getParentItem() == null && !grid.getRootItem(grid.getRootItemCount() - 1).equals(parent))
branches[item.getLevel() - 1] = BranchRenderer.I;
else
branches[item.getLevel() - 1] = BranchRenderer.NONE;
} else
branches[item.getLevel() - 1] = BranchRenderer.I;
item = parent;
parent = item.getParentItem();
}
// item should be null at this point
return branches;
}
/**
* {@inheritDoc}
*/
public Point computeSize(GC gc, int wHint, int hHint, Object value) {
GridItem item = (GridItem) value;
gc.setFont(item.getFont(getColumn()));
int x = 0;
x += leftMargin;
if (isTree()) {
x += getToggleIndent(item);
x += toggleRenderer.getBounds().width + insideMargin;
}
if (isCheck()) {
x += checkRenderer.getBounds().width + insideMargin;
}
int y = 0;
Image image = item.getImage(getColumn());
if (image != null) {
y = topMargin + image.getBounds().height + bottomMargin;
x += image.getBounds().width + insideMargin;
}
// MOPR-DND
// MOPR: replaced this code (to get correct preferred height for cells in word-wrap columns)
//
// x += gc.stringExtent(item.getText(column)).x + rightMargin;
//
// y = Math.max(y,topMargin + gc.getFontMetrics().getHeight() + bottomMargin);
//
// with this code:
int textHeight = 0;
if (!isWordWrap()) {
x += gc.textExtent(item.getText(getColumn())).x + rightMargin;
textHeight = topMargin + textTopMargin + gc.getFontMetrics().getHeight() + textBottomMargin + bottomMargin;
} else {
int plainTextWidth;
if (wHint == SWT.DEFAULT)
plainTextWidth = getBounds().width - x - rightMargin;
else
plainTextWidth = wHint - x - rightMargin;
TextLayout currTextLayout = new TextLayout(gc.getDevice());
currTextLayout.setFont(gc.getFont());
currTextLayout.setText(item.getText(getColumn()));
currTextLayout.setAlignment(getAlignment());
currTextLayout.setWidth(plainTextWidth < 1 ? 1 : plainTextWidth);
x += plainTextWidth + rightMargin;
textHeight += topMargin + textTopMargin;
for (int cnt = 0; cnt < currTextLayout.getLineCount(); cnt++)
textHeight += currTextLayout.getLineBounds(cnt).height;
textHeight += textBottomMargin + bottomMargin;
currTextLayout.dispose();
}
y = Math.max(y, textHeight);
return new Point(x, y);
}
/**
* {@inheritDoc}
*/
public boolean notify(int event, Point point, Object value) {
GridItem item = (GridItem) value;
if (isCheck()) {
if (event == IInternalWidget.MouseMove) {
if (overCheck(item, point)) {
setHoverDetail("check");
return true;
}
}
if (event == IInternalWidget.LeftMouseButtonDown) {
if (overCheck(item, point)) {
if (!item.getCheckable(getColumn())) {
return false;
}
item.setChecked(getColumn(), !item.getChecked(getColumn()));
item.getParent().redraw();
item.fireCheckEvent(getColumn());
return true;
}
}
}
if (isTree() && item.hasChildren()) {
if (event == IInternalWidget.MouseMove) {
if (overToggle(item, point)) {
setHoverDetail("toggle");
return true;
}
}
if (event == IInternalWidget.LeftMouseButtonDown) {
if (overToggle(item, point)) {
item.setExpanded(!item.isExpanded());
item.getParent().redraw();
if (item.isExpanded()) {
item.fireEvent(SWT.Expand);
} else {
item.fireEvent(SWT.Collapse);
}
return true;
}
}
}
return false;
}
private boolean overCheck(GridItem item, Point point) {
if (isCenteredCheckBoxOnly(item)) {
point = new Point(point.x, point.y);
point.x -= getBounds().x;
point.y -= getBounds().y;
Rectangle checkBounds = new Rectangle(0, 0, 0, 0);
checkBounds.x = (getBounds().width - checkRenderer.getBounds().width) / 2;
checkBounds.y = ((getBounds().height - checkRenderer.getBounds().height) / 2);
checkBounds.width = checkRenderer.getBounds().width;
checkBounds.height = checkRenderer.getBounds().height;
return checkBounds.contains(point);
} else {
point = new Point(point.x, point.y);
point.x -= getBounds().x;
point.y -= getBounds().y;
int x = leftMargin;
if (isTree()) {
x += getToggleIndent(item);
x += toggleRenderer.getSize().x + insideMargin;
}
if (point.x >= x && point.x < (x + checkRenderer.getSize().x)) {
int yStart = ((getBounds().height - checkRenderer.getBounds().height) / 2);
if (point.y >= yStart && point.y < yStart + checkRenderer.getSize().y) {
return true;
}
}
return false;
}
}
private int getToggleIndent(GridItem item) {
return item.getLevel() * treeIndent;
}
private boolean overToggle(GridItem item, Point point) {
point = new Point(point.x, point.y);
point.x -= getBounds().x - 1;
point.y -= getBounds().y - 1;
int x = leftMargin;
x += getToggleIndent(item);
if (point.x >= x && point.x < (x + toggleRenderer.getSize().x)) {
// return true;
int yStart = ((getBounds().height - toggleRenderer.getBounds().height) / 2);
if (point.y >= yStart && point.y < yStart + toggleRenderer.getSize().y) {
return true;
}
}
return false;
}
/**
* {@inheritDoc}
*/
public void setTree(boolean tree) {
super.setTree(tree);
if (tree) {
toggleRenderer = new ToggleRenderer();
toggleRenderer.setDisplay(getDisplay());
branchRenderer = new BranchRenderer();
branchRenderer.setDisplay(getDisplay());
}
}
/**
* {@inheritDoc}
*/
public void setCheck(boolean check) {
super.setCheck(check);
if (check) {
checkRenderer = new CheckBoxRenderer();
checkRenderer.setDisplay(getDisplay());
} else {
checkRenderer = null;
}
}
/**
* {@inheritDoc}
*/
public Rectangle getTextBounds(GridItem item, boolean preferred) {
int x = leftMargin;
if (isTree()) {
x += getToggleIndent(item);
x += toggleRenderer.getBounds().width + insideMargin;
}
if (isCheck()) {
x += checkRenderer.getBounds().width + insideMargin;
}
Image image = item.getImage(getColumn());
if (image != null) {
x += image.getBounds().width + insideMargin;
}
Rectangle bounds = new Rectangle(x, topMargin + textTopMargin, 0, 0);
GC gc = new GC(item.getParent());
gc.setFont(item.getFont(getColumn()));
Point size = gc.stringExtent(item.getText(getColumn()));
bounds.height = size.y;
if (preferred) {
bounds.width = size.x - 1;
} else {
bounds.width = getBounds().width - x - rightMargin;
}
gc.dispose();
return bounds;
}
private boolean isCenteredCheckBoxOnly(GridItem item) {
return !isTree() && item.getImage(getColumn()) == null && item.getText(getColumn()).equals("")
&& getAlignment() == SWT.CENTER;
}
}
| 18,284 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
ExportTbxDialog.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/database/net.heartsome.cat.database.ui.tb/src/net/heartsome/cat/database/ui/tb/dialog/ExportTbxDialog.java | /**
* ExportTbxDialog.java
*
* Version information :
*
* Date:Dec 7, 2011
*
* Copyright notice :
* 本文件及其附带的相关文件包含机密信息,仅限瀚特盛科技有限公司指定的,与本项目有关的内部人员和客户联络人员查阅和使用。
* 如果您不是本保密声明中指定的收件者,请立即销毁本文件,禁止对本文件或根据本文件中的内容采取任何其他行动,
* 包括但不限于:泄露本文件中的信息、以任何方式制作本文件全部或部分内容之副本、将本文件或其相关副本提供给任何其他人。
*/
package net.heartsome.cat.database.ui.tb.dialog;
import java.io.File;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import net.heartsome.cat.common.bean.DatabaseModelBean;
import net.heartsome.cat.common.locale.LocaleService;
import net.heartsome.cat.common.ui.HSDropDownButton;
import net.heartsome.cat.common.util.CommonFunction;
import net.heartsome.cat.database.bean.ExportDatabaseBean;
import net.heartsome.cat.database.bean.ExportFilterBean;
import net.heartsome.cat.database.service.DatabaseService;
import net.heartsome.cat.database.ui.core.ExportFilterStoreConfiger;
import net.heartsome.cat.database.ui.dialog.ExportFilterSettingDialog;
import net.heartsome.cat.database.ui.tb.Utils;
import net.heartsome.cat.database.ui.tb.resource.Messages;
import net.heartsome.cat.document.ExportAbstract;
import net.heartsome.cat.document.ExportTbxImpl;
import net.heartsome.cat.ts.util.ProgressIndicatorManager;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.IJobChangeEvent;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.core.runtime.jobs.JobChangeAdapter;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.dialogs.TrayDialog;
import org.eclipse.jface.resource.JFaceResources;
import org.eclipse.jface.viewers.ArrayContentProvider;
import org.eclipse.jface.viewers.ColumnLabelProvider;
import org.eclipse.jface.viewers.ComboViewer;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.viewers.ListViewer;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.TableViewerColumn;
import org.eclipse.jface.window.Window;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.DisposeEvent;
import org.eclipse.swt.events.DisposeListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Cursor;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.DirectoryDialog;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.widgets.ToolBar;
import org.eclipse.swt.widgets.ToolItem;
import org.eclipse.ui.PlatformUI;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* 从库中导出为TBX文件
* @author Jason
* @version
* @since JDK1.6
*/
public class ExportTbxDialog extends TrayDialog {
Logger logger = LoggerFactory.getLogger(ExportTbxDialog.class);
private TableViewer dbListViewer;
private ListViewer hasSelLangListViewer;
private ComboViewer srcLangcomboViewer;
private Button hasChangedCodingCbtn;
private ComboViewer encodingComboViewer;
private Button hasFilterChangedBtn;
private ComboViewer filterComboViewer;
private Button filterSettingBtn;
private Button filterDeleteBtn;
private Text tbxFileText;
private Button browserBtn;
private Button deleteDbBtn;
private List<ExportFilterBean> filterList; // 过滤规则
private List<ExportDatabaseBean> dbList;
private ExportDatabaseBean currentDatabase;
private String[] pageCodes;
private ExportFilterStoreConfiger filterStore;
/**
* Create the dialog.
* @param parentShell
*/
public ExportTbxDialog(Shell parentShell) {
super(parentShell);
this.dbList = new ArrayList<ExportDatabaseBean>();
this.pageCodes = LocaleService.getPageCodes();
this.filterStore = new ExportFilterStoreConfiger();
this.initFilterStore();
setHelpAvailable(true);
}
@Override
protected void configureShell(Shell newShell) {
super.configureShell(newShell);
newShell.setText(Messages.getString("dialog.ExportTbxDialog.title"));
}
/**
* 添加帮助按钮 robert 2012-09-06
*/
@Override
protected Control createHelpControl(Composite parent) {
// ROBERTHELP 导出 tbx
String language = CommonFunction.getSystemLanguage();
final String helpUrl = MessageFormat.format("/net.heartsome.cat.ts.ui.help/html/{0}/ch06s05.html#export-tbx",
language);
Image helpImage = JFaceResources.getImage(DLG_IMG_HELP);
ToolBar toolBar = new ToolBar(parent, SWT.FLAT | SWT.NO_FOCUS);
((GridLayout) parent.getLayout()).numColumns++;
toolBar.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_CENTER));
final Cursor cursor = new Cursor(parent.getDisplay(), SWT.CURSOR_HAND);
toolBar.setCursor(cursor);
toolBar.addDisposeListener(new DisposeListener() {
public void widgetDisposed(DisposeEvent e) {
cursor.dispose();
}
});
ToolItem helpItem = new ToolItem(toolBar, SWT.NONE);
helpItem.setImage(helpImage);
helpItem.setToolTipText(JFaceResources.getString("helpToolTip")); //$NON-NLS-1$
helpItem.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
PlatformUI.getWorkbench().getHelpSystem().displayHelpResource(helpUrl);
}
});
return toolBar;
}
/**
* Create contents of the dialog.
* @param parent
*/
@Override
protected Control createDialogArea(Composite parent) {
Composite container = (Composite) super.createDialogArea(parent);
container.setLayout(new GridLayout(1, false));
Group dbListGroup = new Group(container, SWT.NONE);
GridLayout glDbListGroup = new GridLayout(2, false);
glDbListGroup.horizontalSpacing = 0;
glDbListGroup.marginHeight = 0;
glDbListGroup.marginWidth = 0;
dbListGroup.setLayout(glDbListGroup);
dbListGroup.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
dbListGroup.setText(Messages.getString("dialog.ExportTbxDialog.dbListGroup"));
Composite leftComposite = new Composite(dbListGroup, SWT.NONE);
GridLayout glLeftComposite = new GridLayout(1, false);
glLeftComposite.verticalSpacing = 0;
glLeftComposite.marginHeight = 0;
leftComposite.setLayout(glLeftComposite);
leftComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false, 1, 1));
// 列表和语言设置
Composite dbListComposite = new Composite(leftComposite, SWT.NONE);
GridLayout glTopLeftComposite = new GridLayout(1, false);
glTopLeftComposite.marginHeight = 0;
glTopLeftComposite.marginWidth = 0;
dbListComposite.setLayout(glTopLeftComposite);
dbListComposite.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
dbListViewer = new TableViewer(dbListComposite, SWT.BORDER | SWT.FULL_SELECTION);
Table table = dbListViewer.getTable();
GridData gd_table = new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1);
gd_table.heightHint = 100;
table.setLayoutData(gd_table);
table.setHeaderVisible(true);
table.setLinesVisible(true);
dbListViewer.setContentProvider(new ArrayContentProvider());
dbListViewer.setInput(dbList);
createColumn(dbListViewer);
dbListViewer.addSelectionChangedListener(new ISelectionChangedListener() {
public void selectionChanged(SelectionChangedEvent event) {
IStructuredSelection selection = (IStructuredSelection) event.getSelection();
currentDatabase = (ExportDatabaseBean) selection.getFirstElement();
loadData();
}
});
Composite langSetComposite = new Composite(leftComposite, SWT.NONE);
GridLayout gl_langSetComposite = new GridLayout(2, false);
gl_langSetComposite.marginWidth = 0;
langSetComposite.setLayout(gl_langSetComposite);
langSetComposite.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1));
Label langSelLabel = new Label(langSetComposite, SWT.NONE);
langSelLabel.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
langSelLabel.setText(Messages.getString("dialog.ExportTbxDialog.langSelLabel"));
hasSelLangListViewer = new ListViewer(langSetComposite, SWT.BORDER | SWT.V_SCROLL | SWT.MULTI);
org.eclipse.swt.widgets.List list = hasSelLangListViewer.getList();
GridData glLangList = new GridData(SWT.FILL, SWT.FILL, true, false, 1, 1);
glLangList.heightHint = 76;
list.setLayoutData(glLangList);
hasSelLangListViewer.setContentProvider(new ArrayContentProvider());
hasSelLangListViewer.addSelectionChangedListener(new ISelectionChangedListener() {
@SuppressWarnings("unchecked")
public void selectionChanged(SelectionChangedEvent event) {
IStructuredSelection sel = (IStructuredSelection) event.getSelection();
if (sel.isEmpty()) {
return;
}
if (currentDatabase != null) {
currentDatabase.getHasSelectedLangs().clear();
currentDatabase.getHasSelectedLangs().addAll(sel.toList());
List<String> canSelSrcLangs = new ArrayList<String>();
canSelSrcLangs.addAll(sel.toList());
currentDatabase.setCanSelSrcLangs(canSelSrcLangs);
srcLangcomboViewer.setInput(canSelSrcLangs);
if (canSelSrcLangs.contains(currentDatabase.getSrcLang())) {
String srcLang = currentDatabase.getSrcLang();
if (srcLang != null && !srcLang.equals("")) {
for (int i = 0; i < canSelSrcLangs.size(); i++) {
if (canSelSrcLangs.get(i).equals(srcLang)) {
srcLangcomboViewer.getCombo().select(i);
break;
}
}
}
} else {
srcLangcomboViewer.getCombo().select(0);
}
}
}
});
Label srcLangSelLabel = new Label(langSetComposite, SWT.NONE);
srcLangSelLabel.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
srcLangSelLabel.setBounds(0, 0, 79, 19);
srcLangSelLabel.setText(Messages.getString("dialog.ExportTbxDialog.srcLangSelLabel"));
srcLangcomboViewer = new ComboViewer(langSetComposite, SWT.NONE | SWT.READ_ONLY);
Combo combo = srcLangcomboViewer.getCombo();
GridData gd_combo = new GridData(SWT.LEFT, SWT.CENTER, true, false, 1, 1);
gd_combo.widthHint = 197;
combo.setLayoutData(gd_combo);
srcLangcomboViewer.setContentProvider(new ArrayContentProvider());
srcLangcomboViewer.addSelectionChangedListener(new ISelectionChangedListener() {
public void selectionChanged(SelectionChangedEvent event) {
IStructuredSelection sel = (IStructuredSelection) event.getSelection();
if (sel.isEmpty()) {
return;
}
if (currentDatabase != null) {
currentDatabase.setSrcLang((String) sel.getFirstElement());
}
}
});
// 操作库列的按钮区域
Composite rightComposite = new Composite(dbListGroup, SWT.NONE);
GridLayout gl_rightComposite = new GridLayout(1, false);
gl_rightComposite.marginRight = 5;
gl_rightComposite.marginHeight = 0;
gl_rightComposite.marginWidth = 0;
rightComposite.setLayout(gl_rightComposite);
rightComposite.setLayoutData(new GridData(SWT.LEFT, SWT.TOP, false, false, 1, 1));
HSDropDownButton addBtn = new HSDropDownButton(rightComposite, SWT.NONE);
addBtn.setText(Messages.getString("dialog.ExportTbxDialog.AddDbBtn"));
Menu addMenu = addBtn.getMenu();
MenuItem item = new MenuItem(addMenu, SWT.PUSH);
item.setText(Messages.getString("tb.dialog.addTb.DropDownButton.AddFileTb"));
item.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
FileDialog fileDialg = new FileDialog(getShell());
fileDialg.setFilterExtensions(new String[] { "*.hstb", "*.*" });
String result = fileDialg.open();
if (result == null) {
return;
}
File f = new File(result);
if (!f.exists()) {
return;
}
Map<DatabaseModelBean, String> r = null;
try {
r = Utils.convertFile2TbModel(f, true);
} catch (Exception e1) {
MessageDialog.openError(getShell(), Messages.getString("tb.dialog.addFileTb.errorTitle"),
e1.getMessage());
}
if (r == null) {
return;
}
Iterator<DatabaseModelBean> it = r.keySet().iterator();
if (it.hasNext()) {
DatabaseModelBean selectedVal = it.next();
ExportDatabaseBean bean = new ExportDatabaseBean(selectedVal.toDbMetaData(), r.get(selectedVal));
if (!dbList.contains(bean)) { // 实现: 重写equals方法
dbList.add(bean);
bean.setIndex(dbList.size() + "");
}
dbListViewer.getTable().removeAll();
dbListViewer.setInput(dbList);
if (dbList.size() != 0) {
deleteDbBtn.setEnabled(true);
browserBtn.setEnabled(true);
selectCurrentDb(currentDatabase);
} else {
deleteDbBtn.setEnabled(false);
browserBtn.setEnabled(false);
}
}
}
});
MenuItem serverItem = new MenuItem(addMenu, SWT.PUSH);
serverItem.setText(Messages.getString("tb.dialog.addTb.DropDownButton.AddServerTb"));
serverItem.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
TermDbManagerDialog dialog = new TermDbManagerDialog(getShell());
dialog.setDialogUseFor(TermDbManagerDialog.TYPE_DBSELECTED);
if (dialog.open() == Window.OK) {
Map<DatabaseModelBean, String> selDb = dialog.getHasSelectedDatabase();
Iterator<Entry<DatabaseModelBean, String>> entryIt = selDb.entrySet().iterator();
while (entryIt.hasNext()) {
Entry<DatabaseModelBean, String> entry = entryIt.next();
ExportDatabaseBean bean = new ExportDatabaseBean(entry.getKey().toDbMetaData(), entry
.getValue());
if (!dbList.contains(bean)) { // 实现: 重写equals方法
dbList.add(bean);
bean.setIndex(dbList.size() + "");
}
}
dbListViewer.getTable().removeAll();
dbListViewer.setInput(dbList);
}
if (dbList.size() != 0) {
deleteDbBtn.setEnabled(true);
browserBtn.setEnabled(true);
selectCurrentDb(currentDatabase);
} else {
deleteDbBtn.setEnabled(false);
browserBtn.setEnabled(false);
}
}
});
deleteDbBtn = new Button(rightComposite, SWT.NONE);
deleteDbBtn.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1));
deleteDbBtn.setBounds(0, 0, 104, 31);
deleteDbBtn.setText(Messages.getString("dialog.ExportTbxDialog.deleteDbBtn"));
deleteDbBtn.setEnabled(false);
deleteDbBtn.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
IStructuredSelection sel = (IStructuredSelection) dbListViewer.getSelection();
if (sel.isEmpty()) {
MessageDialog.openInformation(getShell(), Messages.getString("dialog.ExportTbxDialog.msgTitle"),
Messages.getString("dialog.ExportTbxDialog.msg1"));
return;
}
dbList.removeAll(sel.toList());
dbListViewer.remove(sel.toArray());
if (dbList.size() != 0) {
deleteDbBtn.setEnabled(true);
browserBtn.setEnabled(true);
selectCurrentDb(currentDatabase);
} else {
currentDatabase = null;
deleteDbBtn.setEnabled(false);
browserBtn.setEnabled(false);
}
}
});
Composite tbxTemplateComp = new Composite(container, SWT.NONE);
GridLayout glTbxTemplateComp = new GridLayout(1, false);
glTbxTemplateComp.marginWidth = 0;
glTbxTemplateComp.marginHeight = 0;
tbxTemplateComp.setLayout(glTbxTemplateComp);
Composite encodingComposite = new Composite(container, SWT.NONE);
GridLayout glEncodingComposite = new GridLayout(2, false);
glEncodingComposite.marginWidth = 0;
glEncodingComposite.marginHeight = 0;
encodingComposite.setLayout(glEncodingComposite);
encodingComposite.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
hasChangedCodingCbtn = new Button(encodingComposite, SWT.CHECK);
hasChangedCodingCbtn.setText(Messages.getString("dialog.ExportTbxDialog.hasChangedCodingCbtn"));
hasChangedCodingCbtn.setSelection(false);
hasChangedCodingCbtn.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
encodingComboViewer.getCombo().setEnabled(hasChangedCodingCbtn.getSelection());
}
});
encodingComboViewer = new ComboViewer(encodingComposite, SWT.NONE | SWT.READ_ONLY);
Combo encodingCombo = encodingComboViewer.getCombo();
GridData gdEncodingCombo = new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1);
gdEncodingCombo.widthHint = 279;
encodingCombo.setLayoutData(gdEncodingCombo);
encodingCombo.setEnabled(hasChangedCodingCbtn.getSelection());
encodingComboViewer.setContentProvider(new ArrayContentProvider());
encodingComboViewer.setInput(pageCodes);
Composite filterComposite = new Composite(container, SWT.NONE);
filterComposite.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1));
GridLayout glFilterComposite = new GridLayout(4, false);
glFilterComposite.marginWidth = 0;
glFilterComposite.marginHeight = 0;
filterComposite.setLayout(glFilterComposite);
hasFilterChangedBtn = new Button(filterComposite, SWT.CHECK);
hasFilterChangedBtn.setText(Messages.getString("dialog.ExportTbxDialog.button"));
hasFilterChangedBtn.setSelection(false);
hasFilterChangedBtn.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
filterComboViewer.getCombo().setEnabled(hasFilterChangedBtn.getSelection());
filterSettingBtn.setEnabled(hasFilterChangedBtn.getSelection());
filterDeleteBtn.setEnabled(hasFilterChangedBtn.getSelection());
}
});
filterComboViewer = new ComboViewer(filterComposite, SWT.NONE);
Combo filterCombo = filterComboViewer.getCombo();
filterCombo.setEnabled(false);
filterCombo.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
filterComboViewer.setContentProvider(new ArrayContentProvider());
filterComboViewer.setLabelProvider(new FilterLabelProvider());
filterComboViewer.setInput(filterList);
filterCombo.select(0); // 有一个空的过滤器
filterSettingBtn = new Button(filterComposite, SWT.NONE);
filterSettingBtn.setText(Messages.getString("dialog.ExportTbxDialog.filterSettingBtn"));
filterSettingBtn.setEnabled(false);
filterSettingBtn.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
IStructuredSelection sel = (IStructuredSelection) filterComboViewer.getSelection();
ExportFilterBean bean = (ExportFilterBean) sel.getFirstElement();
if (bean.equals(filterList.get(0))) { // 0位置的始终存在 Empty
// 新建
filterSetting(null);
} else {
// 编辑
filterSetting(bean);
}
}
});
filterDeleteBtn = new Button(filterComposite, SWT.NONE);
filterDeleteBtn.setText(Messages.getString("dialog.ExportTbxDialog.filterDeleteBtn"));
filterDeleteBtn.setEnabled(false);
filterDeleteBtn.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
IStructuredSelection sel = (IStructuredSelection) filterComboViewer.getSelection();
ExportFilterBean bean = (ExportFilterBean) sel.getFirstElement();
if (bean.equals(filterList.get(0))) { // 总是存在一个空的filter,显示为"无"
return;
}
if (MessageDialog.openConfirm(getShell(), Messages.getString("dialog.ExportTbxDialog.msgTitle"),
Messages.getString("dialog.ExportTbxDialog.msg2"))) {
filterStore.deleteFilterRuleByName(bean.getFilterName(), "TBX");
int i = filterList.indexOf(bean);
filterList.remove(i);
filterComboViewer.setInput(filterList);
filterComboViewer.getCombo().select(0);
}
}
});
Composite tbxFileSetComposite = new Composite(container, SWT.NONE);
GridLayout glTbxFileSetComposite = new GridLayout(3, false);
glTbxFileSetComposite.marginWidth = 0;
glTbxFileSetComposite.marginHeight = 0;
tbxFileSetComposite.setLayout(glTbxFileSetComposite);
tbxFileSetComposite.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
Label tbxFileLabel = new Label(tbxFileSetComposite, SWT.NONE);
tbxFileLabel.setText(Messages.getString("dialog.ExportTbxDialog.tbxFileLabel"));
tbxFileText = new Text(tbxFileSetComposite, SWT.BORDER);
tbxFileText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
tbxFileText.setEnabled(false);
browserBtn = new Button(tbxFileSetComposite, SWT.NONE);
browserBtn.setText(Messages.getString("dialog.ExportTbxDialog.browserBtn"));
browserBtn.setEnabled(false);
browserBtn.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
if (dbList.size() > 1) {
DirectoryDialog dlg = new DirectoryDialog(getParentShell());
String filePath = dlg.open();
if (filePath != null) {
tbxFileText.setText(filePath);
}
} else {
FileDialog dlg = new FileDialog(getShell(), SWT.SAVE);
String[] filterExt = { "*.tbx" };
dlg.setFilterExtensions(filterExt);
String filePath = dlg.open();
if (filePath != null) {
tbxFileText.setText(filePath);
}
}
}
});
return container;
}
/**
* 选择当前选中的数据库 ;
*/
private void selectCurrentDb(ExportDatabaseBean bean) {
if (bean != null) {
dbListViewer.setSelection(new StructuredSelection(bean));
} else {
if (dbList.size() != 0) {
dbListViewer.setSelection(new StructuredSelection(dbList.get(0)));
}
}
dbListViewer.getTable().setFocus();
}
private void filterSetting(ExportFilterBean filter) {
ExportFilterSettingDialog filterDlg = new ExportFilterSettingDialog(getShell(), "TBX");
filterDlg.setFilterStore(filterStore); // 两个对话框共用一个store
if (filter != null) { // 编辑当前过滤条件
filterDlg.setCurrentFilter(filter);
if (filterDlg.open() == Window.OK) {
int i = filterList.indexOf(filter);
filterList.remove(i);
filterList.add(i, filterDlg.getSettingResult());
filterComboViewer.setInput(filterList);
filterComboViewer.getCombo().select(i);
}
} else {
if (filterDlg.open() == Window.OK) {
filterList.add(1, filterDlg.getSettingResult());
filterComboViewer.setInput(filterList);
filterComboViewer.getCombo().select(1);
}
}
}
/**
* 初始化过滤器列表 ;
*/
private void initFilterStore() {
this.filterList = filterStore.getFilterRule("TBX");
ExportFilterBean empty = new ExportFilterBean();
empty.setFilterName(Messages.getString("dialog.ExportTbxDialog.empty"));
filterList.add(0, empty);
}
/**
* 加载语言数据 ;
*/
private void loadData() {
if (currentDatabase == null) { // 清理数据
hasSelLangListViewer.getList().removeAll();
srcLangcomboViewer.getCombo().removeAll();
encodingComboViewer.getCombo().setText("");
return;
}
// 加载所有语言
hasSelLangListViewer.setInput(currentDatabase.getExistLangs().split(","));
hasSelLangListViewer.setSelection(new StructuredSelection(currentDatabase.getHasSelectedLangs()));
// 加载源语言;
srcLangcomboViewer.setInput(currentDatabase.getCanSelSrcLangs());
srcLangcomboViewer.setSelection(new StructuredSelection(currentDatabase.getCanSelSrcLangs().get(0)));
// 加载编码列表,默认为UTF-8
encodingComboViewer.setSelection(new StructuredSelection("UTF-8"));
}
/**
* Create contents of the button bar.
* @param parent
*/
@Override
protected void createButtonsForButtonBar(Composite parent) {
createButton(parent, IDialogConstants.OK_ID, Messages.getString("dialog.ExportTbxDialog.ok"), true);
createButton(parent, IDialogConstants.CANCEL_ID, Messages.getString("dialog.ExportTbxDialog.cancel"), false);
}
/**
* 创建Table列
* @param viewer
* ;
*/
private void createColumn(final TableViewer viewer) {
String[] clmnTitles = { Messages.getString("dialog.ExportTbxDialog.clmnTitles1"),
Messages.getString("dialog.ExportTbxDialog.clmnTitles2"),
Messages.getString("dialog.ExportTbxDialog.clmnTitles3"),
Messages.getString("dialog.ExportTbxDialog.clmnTitles4") };
int[] clmnBounds = { 50, 80, 100, 100 };
TableViewerColumn col = createTableViewerColumn(viewer, clmnTitles[0], clmnBounds[0], 0);
col.setLabelProvider(new ColumnLabelProvider() {
public String getText(Object element) {
ExportDatabaseBean bean = (ExportDatabaseBean) element;
return bean.getIndex();
}
});
col = createTableViewerColumn(viewer, clmnTitles[1], clmnBounds[1], 1);
col.setLabelProvider(new ColumnLabelProvider() {
public String getText(Object element) {
ExportDatabaseBean bean = (ExportDatabaseBean) element;
return bean.getDbBean().getDbType();
}
});
col = createTableViewerColumn(viewer, clmnTitles[2], clmnBounds[2], 2);
col.setLabelProvider(new ColumnLabelProvider() {
public String getText(Object element) {
ExportDatabaseBean bean = (ExportDatabaseBean) element;
return bean.getDbBean().getDatabaseName();
}
});
col = createTableViewerColumn(viewer, clmnTitles[3], clmnBounds[3], 3);
col.setLabelProvider(new ColumnLabelProvider() {
public String getText(Object element) {
ExportDatabaseBean bean = (ExportDatabaseBean) element;
return bean.getExistLangs();
}
});
}
/**
* 设置TableViewer 列属性
* @param viewer
* @param title
* 列标题
* @param bound
* 列宽
* @param colNumber
* 列序号
* @return {@link TableViewerColumn};
*/
private TableViewerColumn createTableViewerColumn(TableViewer viewer, String title, int bound, final int colNumber) {
final TableViewerColumn viewerColumn = new TableViewerColumn(viewer, SWT.NONE | SWT.Resize);
final TableColumn column = viewerColumn.getColumn();
column.setText(title);
column.setWidth(bound);
column.setResizable(true);
column.setMoveable(true);
return viewerColumn;
}
/**
* Return the initial size of the dialog.
*/
@Override
protected Point getInitialSize() {
return new Point(584, 559);
}
private final class FilterLabelProvider extends LabelProvider {
@Override
public Image getImage(Object element) {
return null;
}
@Override
public String getText(Object element) {
if (element instanceof ExportFilterBean) {
return ((ExportFilterBean) element).getFilterName();
}
return null;
}
}
@Override
protected void okPressed() {
String encoding = "UTF-8";
if (hasChangedCodingCbtn.getSelection()) {
encoding = this.encodingComboViewer.getCombo().getText();
}
String exportPath = this.tbxFileText.getText();
ExportFilterBean filterBean = null;
if (hasFilterChangedBtn.getSelection()) {
IStructuredSelection sel = (IStructuredSelection) filterComboViewer.getSelection();
filterBean = (ExportFilterBean) sel.getFirstElement();
if (filterBean.equals(filterList.get(0))) {
filterBean = null;
}
}
if (this.dbList.size() == 0) {
MessageDialog.openInformation(getShell(), Messages.getString("dialog.ExportTbxDialog.msgTitle"),
Messages.getString("dialog.ExportTbxDialog.msg3"));
return;
}
for (Iterator<ExportDatabaseBean> iterator = dbList.iterator(); iterator.hasNext();) {
ExportDatabaseBean dbBean = iterator.next();
if (dbBean.getHasSelectedLangs().size() < 2) {
String dbType = dbBean.getDbBean().getDbType();
String name = dbBean.getDbBean().getDatabaseName();
MessageDialog.openInformation(getShell(), Messages.getString("dialog.ExportTbxDialog.msgTitle"),
MessageFormat.format(Messages.getString("dialog.ExportTbxDialog.msg4"), dbType, name));
return;
}
}
if (exportPath == null || exportPath.equals("")) {
MessageDialog.openInformation(getShell(), Messages.getString("dialog.ExportTbxDialog.msgTitle"),
Messages.getString("dialog.ExportTbxDialog.msg5"));
return;
}
if (this.dbList.size() > 1) {
File f = new File(exportPath);
if (!f.isDirectory()) {
MessageDialog.openInformation(getShell(), Messages.getString("dialog.ExportTbxDialog.msgTitle"),
Messages.getString("dialog.ExportTbxDialog.msg7"));
return;
}
}
if (this.dbList.size() == 1) {
File f = new File(exportPath);
if (f.isDirectory()) {
MessageDialog.openInformation(getShell(), Messages.getString("dialog.ExportTbxDialog.msgTitle"),
Messages.getString("dialog.ExportTbxDialog.msg8"));
return;
}
}
if (this.dbList.size() == 1) {
dbList.get(0).setExportFilePath(exportPath);
File file = new File(exportPath);
if (file.exists()) {
if (!MessageDialog.openConfirm(getShell(), Messages.getString("dialog.ExportTbxDialog.msgTitle"),
MessageFormat.format(Messages.getString("dialog.ExportTbxDialog.msg6"), exportPath))) {
return;
}
}
} else {
for (Iterator<ExportDatabaseBean> iterator = dbList.iterator(); iterator.hasNext();) {
ExportDatabaseBean db = iterator.next();
String databaseName = db.getDbBean().getDatabaseName();
String path = exportPath + System.getProperty("file.separator") + databaseName
+ db.getDbBean().getDbType() + ".tbx";
File file = new File(path);
if (file.exists()) {
if (!MessageDialog.openConfirm(getShell(), Messages.getString("dialog.ExportTbxDialog.msgTitle"),
MessageFormat.format(Messages.getString("dialog.ExportTbxDialog.msg6"), path))) {
return;
}
}
db.setExportFilePath(path);
}
}
final ExportAbstract exportor = new ExportTbxImpl(this.dbList, filterBean, encoding);
Job job = new Job(Messages.getString("dialog.ExportTbxDialog.job")) {
@Override
protected IStatus run(IProgressMonitor monitor) {
final String result = DatabaseService.executeExport(exportor, monitor);
Display.getDefault().syncExec(new Runnable() {
public void run() {
MessageDialog.openInformation(getShell(),
Messages.getString("dialog.ExportTbxDialog.msgTitle"), result);
}
});
return Status.OK_STATUS;
}
};
// 当程序退出时,检测当前 job 是否正常关闭
CommonFunction.jobCantCancelTip(job);
job.addJobChangeListener(new JobChangeAdapter() {
@Override
public void running(IJobChangeEvent event) {
ProgressIndicatorManager.displayProgressIndicator();
super.running(event);
}
@Override
public void done(IJobChangeEvent event) {
ProgressIndicatorManager.hideProgressIndicator();
super.done(event);
}
});
job.setUser(true);
job.schedule();
super.okPressed();
}
}
| 31,369 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
TermBaseSearchDialog.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/database/net.heartsome.cat.database.ui.tb/src/net/heartsome/cat/database/ui/tb/dialog/TermBaseSearchDialog.java | package net.heartsome.cat.database.ui.tb.dialog;
import java.sql.SQLException;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.IdentityHashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import net.heartsome.cat.common.bean.DatabaseModelBean;
import net.heartsome.cat.common.bean.MetaData;
import net.heartsome.cat.common.core.Constant;
import net.heartsome.cat.common.util.CommonFunction;
import net.heartsome.cat.database.DBOperator;
import net.heartsome.cat.database.service.DatabaseService;
import net.heartsome.cat.database.ui.tb.Activator;
import net.heartsome.cat.database.ui.tb.resource.Messages;
import net.heartsome.cat.ts.core.bean.TransUnitBean;
import net.heartsome.cat.ts.core.file.ProjectConfiger;
import net.heartsome.cat.ts.core.file.ProjectConfigerFactory;
import net.heartsome.cat.ts.ui.editors.IXliffEditor;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.resources.IProject;
import org.eclipse.jface.dialogs.IDialogSettings;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.dialogs.TrayDialog;
import org.eclipse.jface.layout.GridDataFactory;
import org.eclipse.jface.layout.GridLayoutFactory;
import org.eclipse.jface.resource.JFaceResources;
import org.eclipse.nebula.widgets.grid.Grid;
import org.eclipse.nebula.widgets.grid.GridColumn;
import org.eclipse.nebula.widgets.grid.GridItem;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.DisposeEvent;
import org.eclipse.swt.events.DisposeListener;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.KeyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.graphics.Cursor;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Spinner;
import org.eclipse.swt.widgets.ToolBar;
import org.eclipse.swt.widgets.ToolItem;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.PlatformUI;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* 搜索术语对话框
* @author peason
* @version
* @since JDK1.6
*/
public class TermBaseSearchDialog extends TrayDialog {
private static final Logger LOGGER = LoggerFactory.getLogger(TermBaseSearchDialog.class.getName());
/** 当前项目术语库中的语言集合 */
private ArrayList<String> lstLangs = new ArrayList<String>();
/** 当前项目的记忆库集合 */
private List<DatabaseModelBean> lstDatabase = new ArrayList<DatabaseModelBean>();
/** 当前文件的源语言 */
private String strSrcLang;
/** 当前文件的目标语言 */
private String strTgtLang;
/** 要搜索的文本 */
private String strSearchText;
/** 搜索下拉框 */
private Combo cmbSearch;
/** 搜索按钮 */
private Button btnSearch;
/** 是否区分大小写复选框 */
private Button btnIsCaseSensitive;
/** 是否应用正则表达式复选框 */
private Button btnApplyRegularExpression;
/** 是否忽略标记复选框 */
private Button btnIsIgnoreMark;
/** 术语相似度设置按钮 */
private Spinner spiMatchQuality;
/** 术语库下拉框 */
private Combo cmbDatabase;
private Grid grid;
/** 选择语言按钮 */
private Button btnSelectLang;
/** 选择语言菜单 */
private Menu menu;
private GridColumn columnSrcLang;
private TBSearchCellRenderer srcCellRenderer = new TBSearchCellRenderer();
// private ToolBar selLangBar;
private final int HISTORY_SIZE = 5;
private List<String> lstSearchHistory;
// private IPreferenceStore preferenceStore;
/**
* 构造方法
* @param parentShell
* @param project
* 当前项目
* @param strSrcLang
* 当前文件的源语言
* @param strTgtLang
* 当前文件的目标语言
* @param strSearchText
* 搜索文本
*/
public TermBaseSearchDialog(Shell parentShell, IProject project, String strSrcLang, String strTgtLang,
String strSearchText) {
super(parentShell);
this.strSrcLang = strSrcLang;
this.strTgtLang = strTgtLang;
this.strSearchText = strSearchText;
// this.preferenceStore=Activator.getDefault().getPreferenceStore();
ProjectConfiger projectConfig = ProjectConfigerFactory.getProjectConfiger(project);
lstDatabase = projectConfig.getTermBaseDbs(false);
setHelpAvailable(true);
setBlockOnOpen(false);
lstSearchHistory = new ArrayList<String>(HISTORY_SIZE - 1);
}
@Override
protected void configureShell(Shell newShell) {
super.configureShell(newShell);
newShell.setText(Messages.getString("dialog.TermBaseSearchDialog.title"));
}
/**
* 添加帮助按钮 robert 2012-09-06
*/
@Override
protected Control createHelpControl(Composite parent) {
// ROBERTHELP 搜索术语
String language = CommonFunction.getSystemLanguage();
final String helpUrl = MessageFormat.format(
"/net.heartsome.cat.ts.ui.help/html/{0}/ch05s04.html#search-terminology", language);
Image helpImage = JFaceResources.getImage(DLG_IMG_HELP);
ToolBar toolBar = new ToolBar(parent, SWT.FLAT | SWT.NO_FOCUS);
((GridLayout) parent.getLayout()).numColumns++;
toolBar.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_CENTER));
final Cursor cursor = new Cursor(parent.getDisplay(), SWT.CURSOR_HAND);
toolBar.setCursor(cursor);
toolBar.addDisposeListener(new DisposeListener() {
public void widgetDisposed(DisposeEvent e) {
cursor.dispose();
}
});
ToolItem helpItem = new ToolItem(toolBar, SWT.NONE);
helpItem.setImage(helpImage);
helpItem.setToolTipText(JFaceResources.getString("helpToolTip")); //$NON-NLS-1$
helpItem.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
PlatformUI.getWorkbench().getHelpSystem().displayHelpResource(helpUrl);
}
});
return toolBar;
}
@Override
protected Control createDialogArea(Composite parent) {
Composite tparent = (Composite) super.createDialogArea(parent);
tparent.setLayout(new GridLayout());
GridData parentData = new GridData(GridData.FILL_BOTH);
parentData.heightHint = 600;
parentData.widthHint = 775;
tparent.setLayoutData(parentData);
Group groupSearch = new Group(tparent, SWT.None);
groupSearch.setText(Messages.getString("dialog.TermBaseSearchDialog.groupSearch"));
GridLayoutFactory.swtDefaults().margins(5, 5).numColumns(3).equalWidth(false).applyTo(groupSearch);
GridDataFactory.fillDefaults().grab(true, false).applyTo(groupSearch);
Label lblSearch = new Label(groupSearch, SWT.NONE);
lblSearch.setText(Messages.getString("dialog.TermBaseSearchDialog.lblSearch"));
GridDataFactory.fillDefaults().align(SWT.RIGHT, SWT.CENTER).applyTo(lblSearch);
cmbSearch = new Combo(groupSearch, SWT.DROP_DOWN | SWT.BORDER);
cmbSearch.setText(strSearchText == null ? "" : strSearchText);
GridData txtData = new GridData();
// 解决在 Windows 下文本框高度太小的问题
// txtData.heightHint = 20;
txtData.widthHint = 590;
cmbSearch.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
btnSearch = new Button(groupSearch, SWT.PUSH);
btnSearch.setText(Messages.getString("dialog.TermBaseSearchDialog.btnSearch"));
new Label(groupSearch, SWT.NONE);
Composite compCondition = new Composite(groupSearch, SWT.NONE);
GridLayoutFactory.fillDefaults().spacing(8, 0).numColumns(4).equalWidth(false).applyTo(compCondition);
GridDataFactory.fillDefaults().span(2, 1).grab(true, false).applyTo(compCondition);
btnIsCaseSensitive = new Button(compCondition, SWT.CHECK);
btnIsCaseSensitive.setText(Messages.getString("dialog.TermBaseSearchDialog.btnIsCaseSensitive"));
GridDataFactory.swtDefaults().applyTo(btnIsCaseSensitive);
btnIsIgnoreMark = new Button(compCondition, SWT.CHECK);
btnIsIgnoreMark.setText(Messages.getString("dialog.TermBaseSearchDialog.btnIsIgnoreMark"));
btnIsIgnoreMark.setSelection(true);
GridDataFactory.swtDefaults().applyTo(btnIsIgnoreMark);
btnApplyRegularExpression = new Button(compCondition, SWT.CHECK);
btnApplyRegularExpression.setText(Messages.getString("dialog.TermBaseSearchDialog.btnApplyRegularExpression"));
GridDataFactory.swtDefaults().applyTo(btnApplyRegularExpression);
Composite compMatchQuality = new Composite(compCondition, SWT.NONE);
GridLayoutFactory.fillDefaults().extendedMargins(0, 0, 0, 0).margins(0, 0).spacing(0, 0).numColumns(3)
.equalWidth(false).applyTo(compMatchQuality);
GridDataFactory.fillDefaults().align(SWT.LEFT, SWT.CENTER).grab(true, false).applyTo(compMatchQuality);
new Label(compMatchQuality, SWT.NONE).setText(Messages.getString("dialog.TermBaseSearchDialog.lblQuality"));
spiMatchQuality = new Spinner(compMatchQuality, SWT.BORDER);
spiMatchQuality.setMaximum(100);
spiMatchQuality.setMinimum(30);
spiMatchQuality.setIncrement(5);
spiMatchQuality.setSelection(100);
GridData spinnaData = new GridData();
spinnaData.widthHint = 23;
spiMatchQuality.setLayoutData(spinnaData);
new Label(compMatchQuality, SWT.NONE).setText("%");
Label lblTB = new Label(groupSearch, SWT.NONE);
lblTB.setText(Messages.getString("dialog.TermBaseSearchDialog.lblTB"));
GridDataFactory.fillDefaults().align(SWT.RIGHT, SWT.CENTER).applyTo(lblTB);
Composite cmpTB = new Composite(groupSearch, SWT.NONE);
GridLayoutFactory.fillDefaults().spacing(8, 0).numColumns(2).equalWidth(false).applyTo(cmpTB);
GridDataFactory.fillDefaults().span(2, 1).grab(true, false).applyTo(cmpTB);
cmbDatabase = new Combo(cmpTB, SWT.READ_ONLY);
GridDataFactory.swtDefaults().hint(120, SWT.DEFAULT).applyTo(cmbDatabase);
initDatabaseCombo();
btnSelectLang = new Button(cmpTB, SWT.RIGHT);
// GridData data = new GridData();
// data.widthHint = 150;
// data.heightHint = 27;
// btnSelectLang.setLayoutData(data);
// btnSelectLang.setImage(Activator.getImageDescriptor(ImageConstants.CONCORDANCE_SELECT_LANG).createImage());
// btnSelectLang.addPaintListener(new PaintListener() {
// public void paintControl(PaintEvent e) {
// e.gc.drawText(Messages.getString("dialog.TermBaseSearchDialog.btnSelectLang"), 5, 5,
// SWT.DRAW_TRANSPARENT);
// }
// });
btnSelectLang.setText(Messages.getString("dialog.TermBaseSearchDialog.btnSelectLang"));
initLanguageMenu();
Group groupTable = new Group(tparent, SWT.NONE);
GridLayoutFactory.swtDefaults().margins(10, 10).applyTo(groupTable);
groupTable.setLayoutData(new GridData(GridData.FILL_BOTH));
// GridDataFactory.fillDefaults().hint(700, 440).applyTo(groupTable);
groupTable.setText(Messages.getString("dialog.TermBaseSearchDialog.groupTable"));
grid = new Grid(groupTable, SWT.V_SCROLL | SWT.H_SCROLL | SWT.BORDER | SWT.FULL_SELECTION);
grid.setHeaderVisible(true);
grid.setLinesVisible(true);
grid.setLayoutData(new GridData(GridData.FILL_BOTH));
grid.setAutoHeight(true);
grid.setRowsResizeable(true);
grid.setWordWrapHeader(true);
if (strSrcLang != null) {
columnSrcLang = new GridColumn(grid, SWT.NONE);
srcCellRenderer.setVerticalAlignment(SWT.CENTER);
srcCellRenderer.setStyleColumn(0);
columnSrcLang.setCellRenderer(srcCellRenderer);
columnSrcLang.setText(strSrcLang);
columnSrcLang.setWidth(365);
columnSrcLang.setWordWrap(true);
}
if (strTgtLang != null) {
GridColumn columnTgtLang = new GridColumn(grid, SWT.NONE);
TBSearchCellRenderer cellRenderer = new TBSearchCellRenderer();
cellRenderer.setVerticalAlignment(SWT.CENTER);
columnTgtLang.setCellRenderer(cellRenderer);
columnTgtLang.setText(strTgtLang);
columnTgtLang.setWidth(365);
columnTgtLang.setWordWrap(true);
}
for (String strLang : lstLangs) {
final GridColumn column = new GridColumn(grid, SWT.NONE);
TBSearchCellRenderer cellRenderer = new TBSearchCellRenderer();
cellRenderer.setVerticalAlignment(SWT.CENTER);
column.setCellRenderer(cellRenderer);
column.setText(strLang);
column.setWidth(0);
column.setWordWrap(true);
}
readDialogSettings();
setEnabled();
updateCombo(cmbSearch, lstSearchHistory);
if (!strSearchText.equals("")) {
cmbSearch.setText(strSearchText);
} else if (lstSearchHistory != null && lstSearchHistory.size() > 0) {
cmbSearch.setText(lstSearchHistory.get(0));
}
cmbSearch.setSelection(new Point(0, cmbSearch.getText().length()));
initListener();
return parent;
}
/**
* 初始化术语库下拉框 ;
*/
private void initDatabaseCombo() {
List<String> lstItem = new ArrayList<String>();
lstItem.add(Messages.getString("dialog.TermDbManagerDialog.lstItem"));
// int index = 0;
for (int i = 0; i < lstDatabase.size(); i++) {
DatabaseModelBean model = lstDatabase.get(i);
// if (model.isDefault()) {
// index = i;
// }
lstItem.add(model.getDbName());
}
cmbDatabase.setItems((String[]) lstItem.toArray(new String[lstItem.size()]));
cmbDatabase.select(0);
}
/**
* 初始化语言菜单 ;
*/
private void initLanguageMenu() {
Set<String> set = new HashSet<String>();
for (DatabaseModelBean model : lstDatabase) {
MetaData metaData = model.toDbMetaData();
DBOperator dbop = DatabaseService.getDBOperator(metaData);
if(null == dbop){
continue;
}
try {
dbop.start();
set.addAll(dbop.getLanguages());
} catch (SQLException e) {
LOGGER.error(Messages.getString("dialog.TermBaseSearchDialog.logger1"), e);
} catch (ClassNotFoundException e) {
LOGGER.error(Messages.getString("dialog.TermBaseSearchDialog.logger1"), e);
} finally {
try {
if (dbop != null) {
dbop.end();
}
} catch (SQLException e) {
LOGGER.error("", e);
}
}
}
set.remove(strSrcLang);
set.remove(strTgtLang);
lstLangs = new ArrayList<String>(set);
Collections.sort(lstLangs);
// cmbLang.setItems((String[]) langs.toArray(new String[langs.size()]));
menu = new Menu(getShell(), SWT.POP_UP);
// if (strSrcLang != null) {
// MenuItem itemSrc = new MenuItem(menu, SWT.CHECK);
// itemSrc.setText(strSrcLang);
// itemSrc.setSelection(true);
// itemSrc.setEnabled(false);
// }
if (strTgtLang != null) {
MenuItem itemTgt = new MenuItem(menu, SWT.CHECK);
itemTgt.setText(strTgtLang);
itemTgt.setSelection(true);
itemTgt.setEnabled(false);
}
for (final String lang : lstLangs) {
final MenuItem itemLang = new MenuItem(menu, SWT.CHECK);
itemLang.setText(lang);
itemLang.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event event) {
ArrayList<GridColumn> lstShowColumn = new ArrayList<GridColumn>();
// 每增加一列,除标记列外的其他列的和加100,然后平均分配给各个语言列,删除一列则做相反的操作
if (itemLang.getSelection()) {
int totalWidth = 0;
boolean blnIsResetWidth = false;
for (int index = 0; index < grid.getColumnCount(); index++) {
GridColumn column = grid.getColumn(index);
if (column.getText().equals(lang) && column.getWidth() == 0) {
lstShowColumn.add(column);
blnIsResetWidth = true;
} else if (column.getWidth() > 0) {
totalWidth += column.getWidth();
lstShowColumn.add(column);
}
}
if (blnIsResetWidth) {
int width = (totalWidth + 100) / lstShowColumn.size();
for (GridColumn column : lstShowColumn) {
column.setWidth(width);
}
}
// if (grid.getItemCount() > 0) {
// search();
// }
} else {
GridColumn deleteColumn = null;
for (int index = 0; index < grid.getColumnCount(); index++) {
GridColumn column = grid.getColumn(index);
if (column.getWidth() > 0) {
lstShowColumn.add(column);
}
if (column.getText().equals(lang)) {
deleteColumn = column;
// 将删除列中的数据清空,以保证行高正常调整
for (GridItem item : grid.getItems()) {
item.setText(index, "");
}
}
}
int width = (deleteColumn.getWidth() * lstShowColumn.size() - 100) / (lstShowColumn.size() - 1);
deleteColumn.setWidth(0);
lstShowColumn.remove(deleteColumn);
for (GridColumn column : lstShowColumn) {
column.setWidth(width);
}
// search();
}
}
});
}
}
/**
* 初始化各控件的监听 ;
*/
private void initListener() {
// 当点击添加/删除语言按钮时,菜单要显示在按钮下方
btnSelectLang.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event event) {
Rectangle rect = btnSelectLang.getBounds();
// Point pt = selLangBar.toDisplay(new Point(event.x + rect.width, event.y + rect.height));
// menu.setOrientation(SWT.RIGHT_TO_LEFT);
Point pt = btnSelectLang.toDisplay(new Point(event.x, event.y + rect.height));
menu.setLocation(pt.x, pt.y);
menu.setVisible(true);
}
});
btnApplyRegularExpression.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent e) {
setEnabled();
}
public void widgetDefaultSelected(SelectionEvent e) {
}
});
btnSearch.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent e) {
search();
}
public void widgetDefaultSelected(SelectionEvent e) {
}
});
cmbSearch.addKeyListener(new KeyListener() {
public void keyPressed(KeyEvent e) {
if (e.character == SWT.CR) {
search();
}
}
public void keyReleased(KeyEvent e) {
}
});
/**
* 添加双击插入术语到编辑区
*/
grid.addListener(SWT.MouseDoubleClick, new Listener() {
public void handleEvent(Event event) {
// TODO Auto-generated method stub
InsertGridTgtToEditor();
}
});
}
private void InsertGridTgtToEditor() {
GridItem[] selection = grid.getSelection();
if (null == selection || selection.length == 0) {
return;
}
IXliffEditor tempEditor = null;
IEditorPart activeEditor = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage()
.getActiveEditor();
if (activeEditor instanceof IXliffEditor) {
IXliffEditor editor = (IXliffEditor) activeEditor;
tempEditor = editor;
}
if (tempEditor == null) {
return;
}
int[] selectedRows = tempEditor.getSelectedRows();
if (null == selectedRows || selectedRows.length == 0) {
return;
}
int rowIndex = selectedRows[0];
if (tempEditor == null || rowIndex < 0) {
return;
}
TransUnitBean transUnit = tempEditor.getRowTransUnitBean(rowIndex);
Hashtable<String, String> tuProp = transUnit.getTuProps();
if (tuProp != null) {
String translate = tuProp.get("translate");
if (translate != null && translate.equalsIgnoreCase("no")) {
MessageDialog.openInformation(tempEditor.getSite().getShell(),
Messages.getString("view.TerminologyViewPart.msgTitle"),
Messages.getString("view.TerminologyViewPart.msg1"));
return;
}
}
String tarTerm = selection[0].getText(1);
if (null == tarTerm || tarTerm.isEmpty()) {
return;
}
try {
tempEditor.insertCell(rowIndex, tempEditor.getTgtColumnIndex(), tarTerm);
// tempEditor.setFocus(); // 焦点给回编辑器
} catch (ExecutionException e) {
if (Constant.RUNNING_MODE == Constant.MODE_DEBUG) {
e.printStackTrace();
}
MessageDialog.openInformation(tempEditor.getSite().getShell(),
Messages.getString("view.TerminologyViewPart.msgTitle"),
Messages.getString("view.TerminologyViewPart.msg2") + e.getMessage());
}
}
/**
* 搜索术语库 ;
*/
@SuppressWarnings("unchecked")
public void search() {
updateHistory(cmbSearch, lstSearchHistory);
String searchText = cmbSearch.getText();
searchText = cleanString(searchText);
if (searchText == null || searchText.trim().equals("")) {
MessageDialog.openInformation(getShell(), Messages.getString("dialog.TermBaseSearchDialog.msgTitle"),
Messages.getString("dialog.TermBaseSearchDialog.msg1"));
return;
}
if (lstDatabase.size() == 0) {
MessageDialog.openInformation(getShell(), Messages.getString("dialog.TermBaseSearchDialog.msgTitle"),
Messages.getString("dialog.TermBaseSearchDialog.msg2"));
return;
}
ArrayList<String> lstSelLangs = new ArrayList<String>();
lstSelLangs.add(strSrcLang);
for (MenuItem item : menu.getItems()) {
if (item.getSelection()) {
lstSelLangs.add(item.getText());
}
}
LinkedHashMap<MetaData, HashMap<String, IdentityHashMap<String, String>>> mapResult = new LinkedHashMap<MetaData, HashMap<String, IdentityHashMap<String, String>>>();
ArrayList<DatabaseModelBean> lstDB = new ArrayList<DatabaseModelBean>();
if (cmbDatabase.getSelectionIndex() == 0) {
lstDB.addAll(lstDatabase);
} else {
DatabaseModelBean model = lstDatabase.get(cmbDatabase.getSelectionIndex() - 1);
lstDB.add(model);
}
for (DatabaseModelBean model : lstDB) {
MetaData metaData = model.toDbMetaData();
DBOperator dbop = DatabaseService.getDBOperator(metaData);
try {
dbop.start();
HashMap<String, IdentityHashMap<String, String>> mapTermBase = dbop.getTermBaseResult(searchText,
!(btnIsCaseSensitive.getSelection()), btnApplyRegularExpression.getSelection(),
btnIsIgnoreMark.getSelection(), strSrcLang, lstSelLangs, spiMatchQuality.getSelection());
if (mapTermBase != null && mapTermBase.size() > 0) {
mapResult.put(metaData, mapTermBase);
}
} catch (SQLException e1) {
LOGGER.error(Messages.getString("dialog.TermBaseSearchDialog.logger2"), e1);
} catch (ClassNotFoundException e1) {
LOGGER.error(Messages.getString("dialog.TermBaseSearchDialog.logger3"), e1);
} finally {
try {
if (dbop != null) {
dbop.end();
}
} catch (SQLException e) {
LOGGER.error("", e);
}
}
}
Rectangle rect = grid.getBounds();
grid.removeAll();
grid.pack();
grid.setHeaderVisible(true);
grid.setBounds(rect);
if (mapResult.size() == 0) {
MessageDialog.openInformation(getShell(), Messages.getString("dialog.TermBaseSearchDialog.msgTitle"),
Messages.getString("dialog.TermBaseSearchDialog.msg3"));
return;
}
srcCellRenderer.setStrText(searchText);
srcCellRenderer.setBlnIsCaseSensitive(btnIsCaseSensitive.getSelection());
srcCellRenderer.setBlnIsApplyRegular(btnApplyRegularExpression.getSelection());
if (mapResult.size() > 0) {
if (btnApplyRegularExpression.getSelection()) {
Iterator<Entry<MetaData, HashMap<String, IdentityHashMap<String, String>>>> iterator = mapResult
.entrySet().iterator();
while (iterator.hasNext()) {
Entry<MetaData, HashMap<String, IdentityHashMap<String, String>>> entry = iterator.next();
MetaData metaData1 = entry.getKey();
HashMap<String, IdentityHashMap<String, String>> map = entry.getValue();
Iterator<Entry<String, IdentityHashMap<String, String>>> it = map.entrySet().iterator();
while (it.hasNext()) {
Entry<String, IdentityHashMap<String, String>> e = it.next();
createGridItem(metaData1, e.getValue());
}
}
} else {
LinkedHashMap<String, Object[]> map = sortMap(mapResult);
Iterator<Entry<String, Object[]>> it = map.entrySet().iterator();
while (it.hasNext()) {
Entry<String, Object[]> entry = it.next();
Object[] arrObj = entry.getValue();
createGridItem((MetaData) arrObj[0], (IdentityHashMap<String, String>) arrObj[1]);
}
}
}
}
/**
* 向表格中添加记录
* @param metaData
* @param map
* ;
*/
private void createGridItem(MetaData metaData, IdentityHashMap<String, String> map) {
// Bug #2232
List<HashMap<String, String>> lstMap = new ArrayList<HashMap<String, String>>();
Iterator<Entry<String, String>> it = map.entrySet().iterator();
String srcText = null;
while (it.hasNext()) {
Entry<String, String> e = (Entry<String, String>) it.next();
String key = e.getKey();
if (key.equalsIgnoreCase(strSrcLang)) {
srcText = resetCleanString(e.getValue());
continue;
}
boolean isContain = false;
for (HashMap<String, String> hashMap : lstMap) {
if (!hashMap.containsKey(key)) {
hashMap.put(key, e.getValue());
isContain = true;
}
}
if (!isContain) {
HashMap<String, String> hashMap = new HashMap<String, String>();
hashMap.put(key, e.getValue());
lstMap.add(hashMap);
}
}
for (HashMap<String, String> hashMap : lstMap) {
GridItem item = new GridItem(grid, SWT.NONE);
hashMap.put("dbName", metaData.getDatabaseName());
hashMap.put("dbType", metaData.getDbType());
hashMap.put("severName", metaData.getServerName());
int arrIndex = 0;
if (strSrcLang != null) {
item.setText(arrIndex++, srcText);
}
if (strTgtLang != null) {
String tgtText = hashMap.get(strTgtLang) == null ? "" : hashMap.get(strTgtLang);
tgtText = resetCleanString(tgtText);
item.setText(arrIndex++, tgtText);
}
item.setData(hashMap);
item.setData("metaData", metaData);
for (int i = 0; i < lstLangs.size(); i++) {
item.setText((arrIndex + i), hashMap.get(lstLangs.get(i)) == null ? "" : hashMap.get(lstLangs.get(i)));
}
}
}
/**
* 对搜索结果按相似度进行排序
* @param mapItem
* @return ;
*/
private LinkedHashMap<String, Object[]> sortMap(
LinkedHashMap<MetaData, HashMap<String, IdentityHashMap<String, String>>> mapItem) {
Iterator<Entry<MetaData, HashMap<String, IdentityHashMap<String, String>>>> it = mapItem.entrySet().iterator();
LinkedHashMap<String, Object[]> mapData = new LinkedHashMap<String, Object[]>();
while (it.hasNext()) {
Entry<MetaData, HashMap<String, IdentityHashMap<String, String>>> entry = it.next();
MetaData metaData = entry.getKey();
HashMap<String, IdentityHashMap<String, String>> mapTerm = entry.getValue();
Iterator<Entry<String, IdentityHashMap<String, String>>> iterator = mapTerm.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, IdentityHashMap<String, String>> e = (Map.Entry<String, IdentityHashMap<String, String>>) iterator
.next();
String strGroupIdString = e.getKey();
IdentityHashMap<String, String> map = e.getValue();
String key = metaData.getDatabaseName() + "_" + metaData.getServerName() + "_" + strGroupIdString;
Object[] arrObj = new Object[] { metaData, map };
mapData.put(key, arrObj);
}
}
ArrayList<Entry<String, Object[]>> entryList = new ArrayList<Entry<String, Object[]>>(mapData.entrySet());
Collections.sort(entryList, new Comparator<Map.Entry<String, Object[]>>() {
@SuppressWarnings("unchecked")
public int compare(Map.Entry<String, Object[]> arg0, Map.Entry<String, Object[]> arg1) {
IdentityHashMap<String, String> map0 = (IdentityHashMap<String, String>) arg0.getValue()[1];
IdentityHashMap<String, String> map1 = (IdentityHashMap<String, String>) arg1.getValue()[1];
String strSimilarity0 = map0.get("similarity");
String strSimilarity1 = map1.get("similarity");
if (strSimilarity0 == null || strSimilarity1 == null) {
if (strSimilarity0 != null) {
return -1;
} else if (strSimilarity1 != null) {
return 1;
} else {
return 0;
}
} else {
int intData0 = Integer.parseInt(strSimilarity0);
int intData1 = Integer.parseInt(strSimilarity1);
if (intData0 > intData1) {
return -1;
} else if (intData0 < intData1) {
return 1;
} else {
return 0;
}
}
}
});
mapData.clear();
for (Entry<String, Object[]> entry : entryList) {
String key = entry.getKey();
Object[] obj = entry.getValue();
mapData.put(key, obj);
}
return mapData;
}
protected void createButtonsForButtonBar(Composite parent) {
getShell().setDefaultButton(btnSearch);
Composite content = parent.getParent();
// parent.dispose();
content.layout();
}
private static String cleanString(String string) {
string = string.replaceAll("&", "&");
string = string.replaceAll("<", "<");
string = string.replaceAll(">", ">");
// string = string.replaceAll("\"", """);
return string;
}
private static String resetCleanString(String string) {
string = string.replaceAll("<", "<");
string = string.replaceAll(">", ">");
// string = string.replaceAll(""", "\"");
string = string.replaceAll("&", "&");
return string;
}
private IDialogSettings getDialogSettings() {
IDialogSettings settings = Activator.getDefault().getDialogSettings();
IDialogSettings fDialogSettings = settings.getSection(getClass().getName());
if (fDialogSettings == null)
fDialogSettings = settings.addNewSection(getClass().getName());
return fDialogSettings;
}
private void setEnabled() {
if (btnApplyRegularExpression.getSelection()) {
spiMatchQuality.setEnabled(false);
} else {
spiMatchQuality.setEnabled(true);
}
}
private void readDialogSettings() {
IDialogSettings ids = getDialogSettings();
btnIsCaseSensitive.setSelection(ids
.getBoolean("net.heartsome.cat.database.ui.tb.dialog.TermBaseSearchDialog.caseSensitive"));
// btnIsCaseSensitive.setSelection(preferenceStore.getBoolean(TBPreferenceConstants.TB_CASE_SENSITIVE));
btnIsIgnoreMark.setSelection(!ids
.getBoolean("net.heartsome.cat.database.ui.tb.dialog.TermBaseSearchDialog.ignoreMark"));
btnApplyRegularExpression.setSelection(ids
.getBoolean("net.heartsome.cat.database.ui.tb.dialog.TermBaseSearchDialog.regEx"));
try {
spiMatchQuality.setSelection(ids
.getInt("net.heartsome.cat.database.ui.tb.dialog.TermBaseSearchDialog.matchQuality"));
} catch (NumberFormatException e) {
spiMatchQuality.setSelection(100);
}
String[] arrSearchHistory = ids
.getArray("net.heartsome.cat.database.ui.tb.dialog.TermBaseSearchDialog.searchHistory");
if (arrSearchHistory != null) {
lstSearchHistory.clear();
for (int i = 0; i < arrSearchHistory.length; i++) {
lstSearchHistory.add(arrSearchHistory[i]);
}
}
String selTM = ids.get("net.heartsome.cat.database.ui.tb.dialog.TermBaseSearchDialog.selTM");
int selIndex = 0;
if (selTM != null) {
for (int i = 0; i < cmbDatabase.getItemCount(); i++) {
if (selTM.equals(cmbDatabase.getItem(i))) {
selIndex = i;
break;
}
}
}
cmbDatabase.select(selIndex);
String[] arrTarget = ids.getArray("net.heartsome.cat.database.ui.tb.dialog.TermBaseSearchDialog.selTgt");
List<String> lstSelItem = new ArrayList<String>();
if (arrTarget != null) {
for (int i = 0; i < menu.getItemCount(); i++) {
MenuItem item = menu.getItem(i);
for (String target : arrTarget) {
if (item.getText().equals(target)) {
item.setSelection(true);
break;
}
}
if (item.getSelection()) {
lstSelItem.add(item.getText());
}
}
}
// 重设表格列宽
int totalWidth = 0;
List<GridColumn> lstShowColumn = new ArrayList<GridColumn>();
for (int index = 0; index < grid.getColumnCount(); index++) {
GridColumn column = grid.getColumn(index);
if (column.getWidth() > 0) {
totalWidth += column.getWidth();
}
if (column.getWidth() > 0 || lstSelItem.indexOf(column.getText()) >= 0) {
lstShowColumn.add(column);
}
}
int width = (totalWidth + 100) / lstShowColumn.size();
for (GridColumn column : lstShowColumn) {
column.setWidth(width);
}
}
@Override
public boolean close() {
writeDialogSettings();
return super.close();
}
private void writeDialogSettings() {
IDialogSettings ids = getDialogSettings();
ids.put("net.heartsome.cat.database.ui.tb.dialog.TermBaseSearchDialog.caseSensitive",
btnIsCaseSensitive.getSelection());
// preferenceStore.setDefault(TBPreferenceConstants.TB_CASE_SENSITIVE,btnIsCaseSensitive.getSelection());
ids.put("net.heartsome.cat.database.ui.tb.dialog.TermBaseSearchDialog.ignoreMark",
!btnIsIgnoreMark.getSelection());
ids.put("net.heartsome.cat.database.ui.tb.dialog.TermBaseSearchDialog.regEx",
btnApplyRegularExpression.getSelection());
ids.put("net.heartsome.cat.database.ui.tb.dialog.TermBaseSearchDialog.matchQuality",
spiMatchQuality.getSelection());
if (okToUse(cmbSearch)) {
String searchString = cmbSearch.getText();
if (searchString.length() > 0) {
lstSearchHistory.add(0, searchString);
}
writeHistory(lstSearchHistory, ids,
"net.heartsome.cat.database.ui.tb.dialog.TermBaseSearchDialog.searchHistory");
}
ids.put("net.heartsome.cat.database.ui.tb.dialog.TermBaseSearchDialog.selTM", cmbDatabase.getText());
List<String> lstTgt = new ArrayList<String>();
for (MenuItem item : menu.getItems()) {
if (item.getSelection()) {
lstTgt.add(item.getText());
}
}
String[] arrTgt = new String[lstTgt.size()];
lstTgt.toArray(arrTgt);
ids.put("net.heartsome.cat.database.ui.tb.dialog.TermBaseSearchDialog.selTgt", arrTgt);
}
/**
* Returns <code>true</code> if control can be used.
* @param control
* the control to be checked
* @return <code>true</code> if control can be used
*/
private boolean okToUse(Control control) {
return control != null && !control.isDisposed();
}
/**
* Writes the given history into the given dialog store.
* @param history
* the history
* @param settings
* the dialog settings
* @param sectionName
* the section name
* @since 3.2
*/
private void writeHistory(List<String> history, IDialogSettings settings, String sectionName) {
int itemCount = history.size();
Set<String> distinctItems = new HashSet<String>(itemCount);
for (int i = 0; i < itemCount; i++) {
String item = (String) history.get(i);
if (distinctItems.contains(item)) {
history.remove(i--);
itemCount--;
} else {
distinctItems.add(item);
}
}
while (history.size() > 8) {
history.remove(8);
}
String[] names = new String[history.size()];
history.toArray(names);
settings.put(sectionName, names);
}
/**
* Updates the combo with the history.
* @param combo
* to be updated
* @param history
* to be put into the combo
*/
private void updateHistory(Combo combo, List<String> history) {
String findString = combo.getText();
int index = history.indexOf(findString);
if (index != 0) {
if (index != -1) {
history.remove(index);
}
history.add(0, findString);
Point selection = combo.getSelection();
updateCombo(combo, history);
combo.setText(findString);
combo.setSelection(selection);
}
}
/**
* Updates the given combo with the given content.
* @param combo
* combo to be updated
* @param content
* to be put into the combo
*/
private void updateCombo(Combo combo, List<String> content) {
combo.removeAll();
for (int i = 0; i < content.size(); i++) {
combo.add(content.get(i));
}
}
}
| 35,564 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
TermDbNameInputDialog.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/database/net.heartsome.cat.database.ui.tb/src/net/heartsome/cat/database/ui/tb/dialog/TermDbNameInputDialog.java | /**
* DatabaseNameInputDialog.java
*
* Version information :
*
* Date:Dec 7, 2011
*
* Copyright notice :
* 本文件及其附带的相关文件包含机密信息,仅限瀚特盛科技有限公司指定的,与本项目有关的内部人员和客户联络人员查阅和使用。
* 如果您不是本保密声明中指定的收件者,请立即销毁本文件,禁止对本文件或根据本文件中的内容采取任何其他行动,
* 包括但不限于:泄露本文件中的信息、以任何方式制作本文件全部或部分内容之副本、将本文件或其相关副本提供给任何其他人。
*/
package net.heartsome.cat.database.ui.tb.dialog;
import net.heartsome.cat.database.Constants;
import net.heartsome.cat.database.SystemDBOperator;
import net.heartsome.cat.database.ui.tb.resource.Messages;
import org.eclipse.jface.dialogs.IInputValidator;
import org.eclipse.jface.dialogs.InputDialog;
import org.eclipse.swt.custom.BusyIndicator;
import org.eclipse.swt.widgets.Shell;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* 用于创建数据库时,输入数据库名称
* @author Jason
* @version
* @since JDK1.6
*/
public class TermDbNameInputDialog extends InputDialog {
private Logger logger = LoggerFactory.getLogger(TermDbNameInputDialog.class);
private SystemDBOperator dbop;
public TermDbNameInputDialog(Shell parentShell, String dialogTitle, String dialogMessage, String initialValue,
IInputValidator validator) {
super(parentShell, dialogTitle, dialogMessage, initialValue, validator);
}
public SystemDBOperator getSystemDbOp() {
return this.dbop;
}
public void setSystemDbOp(SystemDBOperator dbop) {
this.dbop = dbop;
}
@Override
protected void okPressed() {
SystemDBOperator dbop = getSystemDbOp();
createNewDatabase(dbop, super.getValue());
if(getReturnCode() == 2){
super.okPressed();
}
}
private void createNewDatabase(final SystemDBOperator sysDbOp, final String dbName) {
BusyIndicator.showWhile(getShell().getDisplay(), new Runnable() {
public void run() {
// 检查是否创建了系统库,没创建则创建
if (!sysDbOp.checkSysDb()) {
try {
sysDbOp.createSysDb();
} catch (Exception e) {
logger.error(Messages.getString("dialog.TermDbNameInputDialog.logger1"), e);
setReturnCode(1);
setErrorMessage(Messages.getString("dialog.TermDbNameInputDialog.msg1"));
return;
}
}
sysDbOp.getMetaData().setDatabaseName(dbName);
if (sysDbOp.checkDbExistOnServer()) {
setReturnCode(1);
setErrorMessage(Messages.getString("dialog.TermDbNameInputDialog.msg2"));
return;
}
try {
if (Constants.FAILURE == sysDbOp.createDB()) {
setReturnCode(1);
logger.error(Messages.getString("dialog.TermDbNameInputDialog.logger2"));
setErrorMessage(Messages.getString("dialog.TermDbNameInputDialog.msg1"));
return;
}
sysDbOp.updataSysDb(Constants.DB_TYPE_TB);
setReturnCode(2);
} catch (Exception e) {
setReturnCode(1);
logger.error(Messages.getString("dialog.TermDbNameInputDialog.logger2"), e);
setErrorMessage(Messages.getString("dialog.TermDbNameInputDialog.msg1"));
return;
}
}
});
}
}
| 3,259 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
TermBaseSearchHandler.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/database/net.heartsome.cat.database.ui.tb/src/net/heartsome/cat/database/ui/tb/handler/TermBaseSearchHandler.java | package net.heartsome.cat.database.ui.tb.handler;
import java.util.List;
import net.heartsome.cat.common.bean.DatabaseModelBean;
import net.heartsome.cat.common.locale.Language;
import net.heartsome.cat.common.locale.LocaleService;
import net.heartsome.cat.database.ui.tb.dialog.TermBaseSearchDialog;
import net.heartsome.cat.database.ui.tb.resource.Messages;
import net.heartsome.cat.ts.core.file.ProjectConfiger;
import net.heartsome.cat.ts.core.file.ProjectConfigerFactory;
import net.heartsome.cat.ts.ui.editors.IXliffEditor;
import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.resources.IProject;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.SWT;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.handlers.HandlerUtil;
import org.eclipse.ui.part.FileEditorInput;
/**
* 搜索术语库的 Handler
* @author peason
* @version
* @since JDK1.6
*/
public class TermBaseSearchHandler extends AbstractHandler {
public Object execute(ExecutionEvent event) throws ExecutionException {
if (!isEnabled()) {
return null;
}
IEditorPart editor = HandlerUtil.getActiveEditor(event);
if (editor instanceof IXliffEditor) {
IXliffEditor xliffEditor = (IXliffEditor) editor;
IProject project = ((FileEditorInput) editor.getEditorInput()).getFile().getProject();
ProjectConfiger projectConfig = ProjectConfigerFactory.getProjectConfiger(project);
List<DatabaseModelBean> lstDatabase = projectConfig.getTermBaseDbs(false);
if (lstDatabase == null || lstDatabase.size() == 0) {
MessageDialog.openInformation(HandlerUtil.getActiveShell(event),
Messages.getString("handler.TermBaseSearchHandler.msgTitle"),
Messages.getString("handler.TermBaseSearchHandler.msg"));
return null;
}
String selectText = xliffEditor.getSelectPureText();
if ((selectText == null || selectText.equals("")) && xliffEditor.getSelectedRowIds().size() == 1) {
selectText = xliffEditor.getXLFHandler().getSrcPureText(xliffEditor.getSelectedRowIds().get(0));
selectText = resetCeanString(selectText);
}
String srcLang = xliffEditor.getSrcColumnName();
String tgtLang = xliffEditor.getTgtColumnName();
TermBaseSearchDialog dialog = new TermBaseSearchDialog(editor.getSite().getShell(), project,
srcLang, tgtLang, selectText.trim());
Language srcLangL = LocaleService.getLanguageConfiger().getLanguageByCode(srcLang);
Language tgtLangL = LocaleService.getLanguageConfiger().getLanguageByCode(tgtLang);
dialog.open();
if (srcLangL.isBidi() || tgtLangL.isBidi()) {
dialog.getShell().setOrientation(SWT.RIGHT_TO_LEFT);
}
if (selectText != null && !selectText.trim().equals("")) {
dialog.search();
}
}
return null;
}
public static String resetCeanString(String string) {
string = string.replaceAll("<", "<" );
string = string.replaceAll(">", ">");
// string = string.replaceAll(""", "\"");
string = string.replaceAll("&", "&");
return string;
}
}
| 3,108 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
TermDbManageHandler.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/database/net.heartsome.cat.database.ui.tb/src/net/heartsome/cat/database/ui/tb/handler/TermDbManageHandler.java | /**
* TermDbManageHandler.java
*
* Version information :
*
* Date:2012-5-3
*
* Copyright notice :
* 本文件及其附带的相关文件包含机密信息,仅限瀚特盛科技有限公司指定的,与本项目有关的内部人员和客户联络人员查阅和使用。
* 如果您不是本保密声明中指定的收件者,请立即销毁本文件,禁止对本文件或根据本文件中的内容采取任何其他行动,
* 包括但不限于:泄露本文件中的信息、以任何方式制作本文件全部或部分内容之副本、将本文件或其相关副本提供给任何其他人。
*/
package net.heartsome.cat.database.ui.tb.handler;
import net.heartsome.cat.database.ui.tb.dialog.TermDbManagerDialog;
import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.handlers.HandlerUtil;
/**
* @author jason
* @version
* @since JDK1.6
*/
public class TermDbManageHandler extends AbstractHandler {
public Object execute(ExecutionEvent event) throws ExecutionException {
IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindow(event);
TermDbManagerDialog dialog = new TermDbManagerDialog(window.getShell());
dialog.setDialogUseFor(TermDbManagerDialog.TYPE_DBMANAGE);
dialog.open();
return null;
}
}
| 1,421 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
NewTBHandler.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/database/net.heartsome.cat.database.ui.tb/src/net/heartsome/cat/database/ui/tb/handler/NewTBHandler.java | package net.heartsome.cat.database.ui.tb.handler;
import net.heartsome.cat.database.ui.tb.wizard.NewTermDbWizard;
import net.heartsome.cat.database.ui.tb.wizard.TermDbManagerImportWizardDialog;
import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.handlers.HandlerUtil;
/**
* 新建术语库的 Handler
* @author peason
* @version
* @since JDK1.6
*/
public class NewTBHandler extends AbstractHandler {
public Object execute(ExecutionEvent event) throws ExecutionException {
IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindow(event);
NewTermDbWizard wizard = new NewTermDbWizard();
TermDbManagerImportWizardDialog dialog = new TermDbManagerImportWizardDialog(window.getShell(), wizard);
dialog.open();
return null;
}
}
| 916 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
ExportTbxHandler.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/database/net.heartsome.cat.database.ui.tb/src/net/heartsome/cat/database/ui/tb/handler/ExportTbxHandler.java | /**
* ExportTbxHandler.java
*
* Version information :
*
* Date:2012-5-3
*
* Copyright notice :
* 本文件及其附带的相关文件包含机密信息,仅限瀚特盛科技有限公司指定的,与本项目有关的内部人员和客户联络人员查阅和使用。
* 如果您不是本保密声明中指定的收件者,请立即销毁本文件,禁止对本文件或根据本文件中的内容采取任何其他行动,
* 包括但不限于:泄露本文件中的信息、以任何方式制作本文件全部或部分内容之副本、将本文件或其相关副本提供给任何其他人。
*/
package net.heartsome.cat.database.ui.tb.handler;
import net.heartsome.cat.database.ui.tb.dialog.ExportTbxDialog;
import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.ui.handlers.HandlerUtil;
/**
* @author jason
* @version
* @since JDK1.6
*/
public class ExportTbxHandler extends AbstractHandler {
/** (non-Javadoc)
* @see org.eclipse.core.commands.IHandler#execute(org.eclipse.core.commands.ExecutionEvent)
*/
public Object execute(ExecutionEvent event) throws ExecutionException {
ExportTbxDialog dialog = new ExportTbxDialog(HandlerUtil.getActiveShell(event));
dialog.open();
return null;
}
}
| 1,361 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
ImportTbxHandler.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/database/net.heartsome.cat.database.ui.tb/src/net/heartsome/cat/database/ui/tb/handler/ImportTbxHandler.java | /**
* ImportTbxHandler.java
*
* Version information :
*
* Date:Dec 7, 2011
*
* Copyright notice :
* 本文件及其附带的相关文件包含机密信息,仅限瀚特盛科技有限公司指定的,与本项目有关的内部人员和客户联络人员查阅和使用。
* 如果您不是本保密声明中指定的收件者,请立即销毁本文件,禁止对本文件或根据本文件中的内容采取任何其他行动,
* 包括但不限于:泄露本文件中的信息、以任何方式制作本文件全部或部分内容之副本、将本文件或其相关副本提供给任何其他人。
*/
package net.heartsome.cat.database.ui.tb.handler;
import java.text.MessageFormat;
import net.heartsome.cat.common.util.CommonFunction;
import net.heartsome.cat.database.ui.tb.wizard.TermDbManagerImportWizard;
import net.heartsome.cat.database.ui.tb.wizard.TermDbManagerImportWizardDialog;
import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.jface.resource.JFaceResources;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.DisposeEvent;
import org.eclipse.swt.events.DisposeListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Cursor;
import org.eclipse.swt.graphics.Image;
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.ToolBar;
import org.eclipse.swt.widgets.ToolItem;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.handlers.HandlerUtil;
/**
* @author Jason
* @version
* @since JDK1.6
*/
public class ImportTbxHandler extends AbstractHandler {
/**
* (non-Javadoc)
*
* @see org.eclipse.core.commands.IHandler#execute(org.eclipse.core.commands.ExecutionEvent)
*/
public Object execute(ExecutionEvent event) throws ExecutionException {
IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindow(event);
TermDbManagerImportWizard wizard = new TermDbManagerImportWizard();
TermDbManagerImportWizardDialog dlg = new TermDbManagerImportWizardDialog(window.getShell(), wizard) {
// robert help 2012-09-06
@Override
protected Control createHelpControl(Composite parent) {
// ROBERTHELP 导入TBX
String language = CommonFunction.getSystemLanguage();
final String helpUrl = MessageFormat.format(
"/net.heartsome.cat.ts.ui.help/html/{0}/ch05s03.html#create-tb-wizard-import-tbx", language);
Image helpImage = JFaceResources.getImage(DLG_IMG_HELP);
ToolBar toolBar = new ToolBar(parent, SWT.FLAT | SWT.NO_FOCUS);
((GridLayout) parent.getLayout()).numColumns++;
toolBar.setLayoutData(new GridData(
GridData.HORIZONTAL_ALIGN_CENTER));
final Cursor cursor = new Cursor(parent.getDisplay(),
SWT.CURSOR_HAND);
toolBar.setCursor(cursor);
toolBar.addDisposeListener(new DisposeListener() {
public void widgetDisposed(DisposeEvent e) {
cursor.dispose();
}
});
ToolItem helpItem = new ToolItem(toolBar, SWT.NONE);
helpItem.setImage(helpImage);
helpItem.setToolTipText(JFaceResources.getString("helpToolTip")); //$NON-NLS-1$
helpItem.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
PlatformUI.getWorkbench().getHelpSystem().displayHelpResource(helpUrl);
}
});
return toolBar;
}
};
dlg.setHelpAvailable(true);
dlg.open();
return null;
}
}
| 3,669 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
ProjectSettingTBPage.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/database/net.heartsome.cat.database.ui.tb/src/net/heartsome/cat/database/ui/tb/projectsetting/ProjectSettingTBPage.java | /**
* ProjectConfigTBPage.java
*
* Version information :
*
* Date:Nov 29, 2011
*
* Copyright notice :
* 本文件及其附带的相关文件包含机密信息,仅限瀚特盛科技有限公司指定的,与本项目有关的内部人员和客户联络人员查阅和使用。
* 如果您不是本保密声明中指定的收件者,请立即销毁本文件,禁止对本文件或根据本文件中的内容采取任何其他行动,
* 包括但不限于:泄露本文件中的信息、以任何方式制作本文件全部或部分内容之副本、将本文件或其相关副本提供给任何其他人。
*/
package net.heartsome.cat.database.ui.tb.projectsetting;
import java.io.File;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import net.heartsome.cat.common.bean.DatabaseModelBean;
import net.heartsome.cat.common.bean.ProjectInfoBean;
import net.heartsome.cat.common.locale.Language;
import net.heartsome.cat.common.resources.ResourceUtils;
import net.heartsome.cat.common.ui.HSDropDownButton;
import net.heartsome.cat.database.Constants;
import net.heartsome.cat.database.DBOperator;
import net.heartsome.cat.database.service.DatabaseService;
import net.heartsome.cat.database.ui.tb.Activator;
import net.heartsome.cat.database.ui.tb.ImageConstants;
import net.heartsome.cat.database.ui.tb.Utils;
import net.heartsome.cat.database.ui.tb.dialog.TermDbManagerDialog;
import net.heartsome.cat.database.ui.tb.resource.Messages;
import net.heartsome.cat.database.ui.tb.wizard.NewTermDbWizard;
import net.heartsome.cat.database.ui.tb.wizard.TbxImportWizard;
import net.heartsome.cat.database.ui.tb.wizard.TermDbManagerImportWizardDialog;
import net.heartsome.cat.ts.ui.extensionpoint.AbstractProjectSettingPage;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.ArrayContentProvider;
import org.eclipse.jface.viewers.CellEditor;
import org.eclipse.jface.viewers.CheckboxCellEditor;
import org.eclipse.jface.viewers.ColumnLabelProvider;
import org.eclipse.jface.viewers.EditingSupport;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.TableViewerColumn;
import org.eclipse.jface.window.Window;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.ui.IWorkbench;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ProjectSettingTBPage extends AbstractProjectSettingPage {
private static final Logger LOGGER = LoggerFactory.getLogger(ProjectSettingTBPage.class);
private TableViewer tableViewer;
private List<DatabaseModelBean> curDbList;
private Image checkedImage = Activator.getImageDescriptor(ImageConstants.CHECKED).createImage();
private Image uncheckedImage = Activator.getImageDescriptor(ImageConstants.UNCHECKED).createImage();
/**
* Create the preference page.
* @param cfgBean
*/
public ProjectSettingTBPage() {
super("TB");
setTitle(Messages.getString("projectsetting.ProjectSettingTBPage.title"));
noDefaultAndApplyButton();
}
@Override
public void setProjectInfoBean(ProjectInfoBean projInfoBean) {
super.projectInfoBean = projInfoBean;
this.curDbList = projInfoBean.getTbDb();
for (DatabaseModelBean bean : this.curDbList) {
checkDbHashMatch(bean);
}
}
/**
* Create contents of the preference page.
* @param parent
*/
@Override
public Control createContents(Composite parent) {
Composite container = new Composite(parent, SWT.NULL);
container.setLayout(new GridLayout(1, false));
tableViewer = new TableViewer(container, SWT.BORDER | SWT.FULL_SELECTION | SWT.SINGLE);
Table table = tableViewer.getTable();
table.setLinesVisible(true);
table.setHeaderVisible(true);
table.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));
tableViewer.setContentProvider(new ArrayContentProvider());
createColumn(tableViewer);
tableViewer.setInput(curDbList);
tableViewer.addSelectionChangedListener(new ISelectionChangedListener() {
public void selectionChanged(SelectionChangedEvent event) {
IStructuredSelection selection = (IStructuredSelection) tableViewer.getSelection();
DatabaseModelBean dbModel = (DatabaseModelBean) selection.getFirstElement();
if(null == dbModel){
return;
}
if (Constants.DBTYPE_SQLITE.equals(dbModel.getDbType())) {
String path = dbModel.getItlDBLocation() + File.separator + dbModel.getDbName();
File file = new File(path);
if (!file.exists()) {
setMessage(Messages.getString("projectsetting.ProjectSettingTBPage.FileNotFoundMsg"));
return;
}else{
setMessage(Messages.getString("projectsetting.ProjectSettingTBPage.title"));
}
}
if (dbModel != null && !dbModel.isHasMatch()) {
setMessage(Messages.getString("projectsetting.ProjectSettingTBPage.msg1"));
}
}
});
Composite composite = new Composite(container, SWT.NONE);
composite.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
composite.setLayout(new GridLayout(5, false));
new Label(composite, SWT.NONE);
HSDropDownButton addBtn = new HSDropDownButton(composite, SWT.NONE);
addBtn.setText(Messages.getString("projectsetting.ProjectSettingTBPage.addBtn"));
Menu addMenu = addBtn.getMenu();
MenuItem item = new MenuItem(addMenu, SWT.PUSH);
item.setText(Messages.getString("tb.dialog.addTb.DropDownButton.AddFileTb"));
item.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
FileDialog fileDialg = new FileDialog(getShell());
fileDialg.setFilterExtensions(new String[] { "*.hstb", "*.*" });
String result = fileDialg.open();
if (result == null) {
return;
}
File f = new File(result);
if (!f.exists()) {
return;
}
Map<DatabaseModelBean, String> r = null;
try {
r = Utils.convertFile2TbModel(f, false);
} catch (Exception e1) {
MessageDialog.openError(getShell(), Messages.getString("tb.dialog.addFileTb.errorTitle"),
e1.getMessage());
}
if (r == null) {
return;
}
Iterator<DatabaseModelBean> it = r.keySet().iterator();
if (it.hasNext()) {
DatabaseModelBean selectedVal = it.next();
List<DatabaseModelBean> dbList = new ArrayList<DatabaseModelBean>();
dbList.add(selectedVal);
addToCurrDbList(dbList);
}
}
});
MenuItem serverItem = new MenuItem(addMenu, SWT.PUSH);
serverItem.setText(Messages.getString("tb.dialog.addTb.DropDownButton.AddServerTb"));
serverItem.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
TermDbManagerDialog dialog = new TermDbManagerDialog(getShell());
dialog.setDialogUseFor(TermDbManagerDialog.TYPE_DBSELECTED);
if (dialog.open() == Window.OK) {
Iterator<DatabaseModelBean> it = dialog.getHasSelectedDatabase().keySet().iterator();
List<DatabaseModelBean> dbList = new ArrayList<DatabaseModelBean>();
while (it.hasNext()) {
dbList.add(it.next());
}
addToCurrDbList(dbList);
}
}
});
Button createBtn = new Button(composite, SWT.NONE);
createBtn.setText(Messages.getString("projectsetting.ProjectSettingTBPage.createBtn"));
createBtn.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
NewTermDbWizard wizard = new NewTermDbWizard();
TermDbManagerImportWizardDialog dlg = new TermDbManagerImportWizardDialog(getShell(), wizard);
if (dlg.open() == 0) {
DatabaseModelBean dbModel = wizard.getCreateDb();
List<DatabaseModelBean> dbList = new ArrayList<DatabaseModelBean>();
dbList.add(dbModel);
addToCurrDbList(dbList);
}
}
});
Button removeBtn = new Button(composite, SWT.NONE);
removeBtn.setText(Messages.getString("projectsetting.ProjectSettingTBPage.removeBtn"));
removeBtn.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
removeForCurrDbList((IStructuredSelection) tableViewer.getSelection());
}
});
Button importTmxBtn = new Button(composite, SWT.NONE);
importTmxBtn.setText(Messages.getString("projectsetting.ProjectSettingTBPage.importTmxBtn"));
importTmxBtn.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
IStructuredSelection selection = (IStructuredSelection) tableViewer.getSelection();
Iterator<?> it = selection.iterator();
if (it.hasNext()) {
DatabaseModelBean dbModel = (DatabaseModelBean) it.next();
TbxImportWizard wizard = new TbxImportWizard(dbModel);
TermDbManagerImportWizardDialog dlg = new TermDbManagerImportWizardDialog(getShell(), wizard);
if (dlg.open() == 0) {
checkDbHashMatch(dbModel);
tableViewer.refresh();
}
// 刷新项目
ResourceUtils.refreshCurentSelectProject();
} else {
MessageDialog.openInformation(getShell(),
Messages.getString("projectsetting.ProjectSettingTBPage.msgTitle"),
Messages.getString("projectsetting.ProjectSettingTBPage.msg2"));
}
}
});
addBtn.setFocus();
Point addPoint = addBtn.computeSize(SWT.DEFAULT, SWT.DEFAULT, true);
Point createPoint = createBtn.computeSize(SWT.DEFAULT, SWT.DEFAULT, true);
Point remPoint = removeBtn.computeSize(SWT.DEFAULT, SWT.DEFAULT, true);
Point importPoint = importTmxBtn.computeSize(SWT.DEFAULT, SWT.DEFAULT, true);
int width = Math.max(importPoint.x, Math.max(remPoint.x, Math.max(addPoint.x, createPoint.x)));
GridData btnData = new GridData();
btnData.widthHint = width + 10;
addBtn.setLayoutData(btnData);
createBtn.setLayoutData(btnData);
removeBtn.setLayoutData(btnData);
importTmxBtn.setLayoutData(btnData);
return container;
}
/**
* 从当前列表中删除选中的库
* @param selection
* ;
*/
private void removeForCurrDbList(IStructuredSelection selection) {
curDbList.removeAll(selection.toList());
this.tableViewer.remove(selection.toArray());
}
/**
* 将选中的内容添加到列表中
* @param selection
* ;
*/
private void addToCurrDbList(List<DatabaseModelBean> hasSelection) {
StringBuffer dbNames = new StringBuffer();
for (int i = 0; i < hasSelection.size(); i++) {
DatabaseModelBean dbModel = hasSelection.get(i);
checkDbHashMatch(dbModel);
if (!checkDbIsExist(curDbList, dbModel)) {
if (curDbList.size() == 0) { // 第一个添加的库为默认库
dbModel.setDefault(true);
}
curDbList.add(dbModel);
this.tableViewer.add(dbModel);
} else {
dbNames.append(dbModel.getDbName());
dbNames.append("\n");
}
}
if (dbNames.length() != 0) {
MessageDialog.openInformation(getShell(),
Messages.getString("projectsetting.ProjectSettingTBPage.msgTitle"),
Messages.getString("projectsetting.ProjectSettingTBPage.msg3") + dbNames.toString());
}
}
/**
* 检查当前库是否已经存在
* @param b
* @return ;
*/
public boolean checkDbIsExist(List<DatabaseModelBean> curDbList, DatabaseModelBean b) {
for (int i = 0; i < curDbList.size(); i++) {
DatabaseModelBean a = curDbList.get(i);
String dbname = a.getDbName();
String host = a.getHost();
String port = a.getPort();
String instance = a.getInstance();
if (b.getDbName().equals(dbname) && b.getHost().equals(host) && b.getPort().equals(port)
&& b.getInstance().equals(instance)) {
return true;
}
}
return false;
}
/**
* 需要调用Database模块 检查当前项目在库中是否有语言对的匹配
* @param dbModel
* 数据库信息;
*/
public void checkDbHashMatch(DatabaseModelBean dbModel) {
Language srcLang = super.projectInfoBean.getSourceLang();
DBOperator dbOp = DatabaseService.getDBOperator(dbModel.toDbMetaData());
try {
if (dbOp != null) {
dbOp.start();
dbModel.setHasMatch(dbOp.checkHasMatchs(srcLang.getCode(), "B"));
}
} catch (Exception e) {
LOGGER.error("", e);
e.printStackTrace();
dbModel.setHasMatch(false);
} finally {
if (dbOp != null) {
try {
if (dbOp != null) {
dbOp.end();
}
} catch (SQLException e) {
LOGGER.error("", e);
}
}
}
}
/**
* 创建Table列
* @param viewer
* ;
*/
private void createColumn(final TableViewer viewer) {
String[] clmnTitles = { Messages.getString("projectsetting.ProjectSettingTBPage.clmnTitles1"),
Messages.getString("projectsetting.ProjectSettingTBPage.clmnTitles2"),
Messages.getString("projectsetting.ProjectSettingTBPage.clmnTitles3"),
Messages.getString("projectsetting.ProjectSettingTBPage.clmnTitles4"),
Messages.getString("projectsetting.ProjectSettingTBPage.clmnTitles5") };
int[] clmnBounds = { 100, 100, 200, 90, 70 };
TableViewerColumn col = createTableViewerColumn(viewer, clmnTitles[0], clmnBounds[0], 0);
col.setLabelProvider(new ColumnLabelProvider() {
public String getText(Object element) {
DatabaseModelBean dbModel = (DatabaseModelBean) element;
return dbModel.getDbName();
}
});
col = createTableViewerColumn(viewer, clmnTitles[1], clmnBounds[1], 1);
col.setLabelProvider(new ColumnLabelProvider() {
public String getText(Object element) {
DatabaseModelBean dbModel = (DatabaseModelBean) element;
String dbType = dbModel.getDbType();
if (dbType.equals(Constants.DBTYPE_MYSQL)) {
dbType = Constants.DBTYPE_MYSQL_FOR_UI;
} else if (dbType.equals(Constants.DBTYPE_MSSQL2005)) {
dbType = Constants.DBTYPE_MSSQL2005_FOR_UI;
} else if (dbType.equals(Constants.DBTYPE_SQLITE)) {
dbType = Messages.getString("tb.dbtype.sqlite");
}
return dbType;
}
});
col = createTableViewerColumn(viewer, clmnTitles[2], clmnBounds[2], 2);
col.setLabelProvider(new ColumnLabelProvider() {
public String getText(Object element) {
DatabaseModelBean dbModel = (DatabaseModelBean) element;
if (dbModel.getDbType().equals("Internal DB") || dbModel.getDbType().equals("SQLite")) {
return dbModel.getItlDBLocation();
}
return dbModel.getHost();
}
});
col = createTableViewerColumn(viewer, clmnTitles[3], clmnBounds[3], 3);
col.setLabelProvider(new ColumnLabelProvider() {
public String getText(Object element) {
DatabaseModelBean dbModel = (DatabaseModelBean) element;
if (dbModel.isHasMatch()) {
return Messages.getString("projectsetting.ProjectSettingTBPage.yes");
} else {
return Messages.getString("projectsetting.ProjectSettingTBPage.no");
}
}
});
col = createTableViewerColumn(viewer, clmnTitles[4], clmnBounds[4], 4);
col.setLabelProvider(new ColumnLabelProvider() {
public Image getImage(Object element) {
DatabaseModelBean dbModel = (DatabaseModelBean) element;
if (dbModel.isDefault()) {
return checkedImage;
} else {
return uncheckedImage;
}
}
public String getText(Object element) {
return null;
}
});
col.setEditingSupport(new ReadableEditingSupport(viewer));
}
/**
* 设置TableViewer 列属性
* @param viewer
* @param title
* 列标题
* @param bound
* 列宽
* @param colNumber
* 列序号
* @return {@link TableViewerColumn};
*/
private TableViewerColumn createTableViewerColumn(TableViewer viewer, String title, int bound, final int colNumber) {
final TableViewerColumn viewerColumn = new TableViewerColumn(viewer, SWT.NONE | SWT.Resize);
final TableColumn column = viewerColumn.getColumn();
column.setText(title);
column.setWidth(bound);
column.setResizable(true);
column.setMoveable(true);
return viewerColumn;
}
/**
* Cell Editing Support for readable
* @author Jason
* @version
* @since JDK1.6
*/
protected class ReadableEditingSupport extends EditingSupport {
private final TableViewer viewer;
public ReadableEditingSupport(TableViewer viewer) {
super(viewer);
this.viewer = viewer;
}
@Override
protected CellEditor getCellEditor(Object element) {
return new CheckboxCellEditor(null, SWT.CHECK);
}
@Override
protected boolean canEdit(Object element) {
return true;
}
@Override
protected Object getValue(Object element) {
DatabaseModelBean dbModel = (DatabaseModelBean) element;
return dbModel.isDefault();
}
@Override
protected void setValue(Object element, Object value) {
// 实现单选
List<?> dbList = (List<?>) viewer.getInput();
for (int i = 0; i < dbList.size(); i++) {
((DatabaseModelBean) dbList.get(i)).setDefault(false);
}
// 实现单选
// 执行修改
DatabaseModelBean dbModel = (DatabaseModelBean) element;
dbModel.setDefault((Boolean) value);
// 刷新
viewer.refresh();
}
}
/**
* Initialize the preference page.
*/
public void init(IWorkbench workbench) {
// Initialize the preference page
}
@Override
public void dispose() {
if (checkedImage != null && !checkedImage.isDisposed()) {
checkedImage.dispose();
}
if (uncheckedImage != null && !uncheckedImage.isDisposed()) {
uncheckedImage.dispose();
}
super.dispose();
}
}
| 17,906 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
NewProjectTbPage.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/database/net.heartsome.cat.database.ui.tb/src/net/heartsome/cat/database/ui/tb/newproject/NewProjectTbPage.java | package net.heartsome.cat.database.ui.tb.newproject;
import java.io.File;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import net.heartsome.cat.common.bean.DatabaseModelBean;
import net.heartsome.cat.common.ui.HSDropDownButton;
import net.heartsome.cat.database.Constants;
import net.heartsome.cat.database.DBOperator;
import net.heartsome.cat.database.service.DatabaseService;
import net.heartsome.cat.database.ui.tb.Activator;
import net.heartsome.cat.database.ui.tb.ImageConstants;
import net.heartsome.cat.database.ui.tb.Utils;
import net.heartsome.cat.database.ui.tb.dialog.TermDbManagerDialog;
import net.heartsome.cat.database.ui.tb.resource.Messages;
import net.heartsome.cat.database.ui.tb.wizard.NewTermDbWizard;
import net.heartsome.cat.database.ui.tb.wizard.TbxImportWizard;
import net.heartsome.cat.database.ui.tb.wizard.TermDbManagerImportWizardDialog;
import net.heartsome.cat.ts.ui.extensionpoint.AbstractNewProjectWizardPage;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.ArrayContentProvider;
import org.eclipse.jface.viewers.CellEditor;
import org.eclipse.jface.viewers.CheckboxCellEditor;
import org.eclipse.jface.viewers.ColumnLabelProvider;
import org.eclipse.jface.viewers.EditingSupport;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.TableViewerColumn;
import org.eclipse.jface.window.Window;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Image;
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.Event;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class NewProjectTbPage extends AbstractNewProjectWizardPage {
private static final Logger LOGGER = LoggerFactory.getLogger(NewProjectTbPage.class);
private TableViewer tableViewer;
private List<Object> curDbList;
private Image checkedImage = Activator.getImageDescriptor(ImageConstants.CHECKED).createImage();
private Image uncheckedImage = Activator.getImageDescriptor(ImageConstants.UNCHECKED).createImage();
/**
* Create the wizard.
*/
public NewProjectTbPage() {
super("wizardPage", "TB");
setTitle(Messages.getString("newproject.NewProjectTbPage.title"));
setDescription(Messages.getString("newproject.NewProjectTbPage.desc"));
curDbList = new ArrayList<Object>();
}
/**
* Create contents of the wizard.
* @param parent
*/
public void createControl(Composite parent) {
Composite container = new Composite(parent, SWT.NULL);
container.setLayout(new GridLayout(1, false));
tableViewer = new TableViewer(container, SWT.BORDER | SWT.FULL_SELECTION | SWT.SINGLE);
Table table = tableViewer.getTable();
table.setLinesVisible(true);
table.setHeaderVisible(true);
table.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));
tableViewer.setContentProvider(new ArrayContentProvider());
createColumn(tableViewer);
tableViewer.setInput(curDbList);
tableViewer.addSelectionChangedListener(new ISelectionChangedListener() {
public void selectionChanged(SelectionChangedEvent event) {
IStructuredSelection selection = (IStructuredSelection) tableViewer.getSelection();
DatabaseModelBean dbModel = (DatabaseModelBean) selection.getFirstElement();
if (dbModel != null && !dbModel.isHasMatch()) {
setMessage(Messages.getString("newproject.NewProjectTbPage.msg1"));
} else {
setMessage(null);
}
}
});
Composite composite = new Composite(container, SWT.NONE);
composite.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
composite.setLayout(new GridLayout(5, false));
new Label(composite, SWT.NONE);
HSDropDownButton addBtn = new HSDropDownButton(composite, SWT.NONE);
addBtn.setText(Messages.getString("newproject.NewProjectTbPage.addBtn"));
Menu addMenu = addBtn.getMenu();
MenuItem item = new MenuItem(addMenu, SWT.PUSH);
item.setText(Messages.getString("tb.dialog.addTb.DropDownButton.AddFileTb"));
item.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
FileDialog fileDialg = new FileDialog(getShell());
fileDialg.setFilterExtensions(new String[] { "*.hstb", "*.*" });
String result = fileDialg.open();
if (result == null) {
return;
}
File f = new File(result);
if (!f.exists()) {
return;
}
Map<DatabaseModelBean, String> r = null;
try {
r = Utils.convertFile2TbModel(f, false);
} catch (Exception e1) {
MessageDialog.openError(getShell(), Messages.getString("tb.dialog.addFileTb.errorTitle"),
e1.getMessage());
}
if (r == null) {
return;
}
Iterator<DatabaseModelBean> it = r.keySet().iterator();
if (it.hasNext()) {
DatabaseModelBean selectedVal = it.next();
List<DatabaseModelBean> dbList = new ArrayList<DatabaseModelBean>();
dbList.add(selectedVal);
addToCurrDbList(dbList);
}
}
});
MenuItem serverItem = new MenuItem(addMenu, SWT.PUSH);
serverItem.setText(Messages.getString("tb.dialog.addTb.DropDownButton.AddServerTb"));
serverItem.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
TermDbManagerDialog dialog = new TermDbManagerDialog(getShell());
dialog.setDialogUseFor(TermDbManagerDialog.TYPE_DBSELECTED);
if (dialog.open() == Window.OK) {
Iterator<DatabaseModelBean> it = dialog.getHasSelectedDatabase().keySet().iterator();
List<DatabaseModelBean> dbList = new ArrayList<DatabaseModelBean>();
while (it.hasNext()) {
dbList.add(it.next());
}
addToCurrDbList(dbList);
}
}
});
Button createBtn = new Button(composite, SWT.NONE);
createBtn.setText(Messages.getString("newproject.NewProjectTbPage.createBtn"));
createBtn.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
NewTermDbWizard wizard = new NewTermDbWizard();
TermDbManagerImportWizardDialog dlg = new TermDbManagerImportWizardDialog(getShell(), wizard);
if (dlg.open() == 0) {
DatabaseModelBean dbModel = wizard.getCreateDb();
List<DatabaseModelBean> dbList = new ArrayList<DatabaseModelBean>(1);
dbList.add(dbModel);
addToCurrDbList(dbList);
}
}
});
Button removeBtn = new Button(composite, SWT.NONE);
removeBtn.setText(Messages.getString("newproject.NewProjectTbPage.removeBtn"));
removeBtn.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
removeForCurrDbList((IStructuredSelection) tableViewer.getSelection());
}
});
Button importTmxBtn = new Button(composite, SWT.NONE);
importTmxBtn.setText(Messages.getString("newproject.NewProjectTbPage.importTmxBtn"));
importTmxBtn.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
IStructuredSelection selection = (IStructuredSelection) tableViewer.getSelection();
Iterator<?> it = selection.iterator();
if (it.hasNext()) {
DatabaseModelBean dbModel = (DatabaseModelBean) it.next();
TbxImportWizard wizard = new TbxImportWizard(dbModel);
TermDbManagerImportWizardDialog dlg = new TermDbManagerImportWizardDialog(getShell(), wizard);
if (dlg.open() == 0) {
checkDbHashMatch(dbModel);
tableViewer.refresh();
}
} else {
MessageDialog.openInformation(getShell(),
Messages.getString("newproject.NewProjectTbPage.msgTitle"),
Messages.getString("newproject.NewProjectTbPage.msg3"));
}
}
});
addBtn.setFocus();
setControl(container);
}
private void addToCurrDbList(List<DatabaseModelBean> hasSelection) {
StringBuffer dbNames = new StringBuffer();
for (int i = 0; i < hasSelection.size(); i++) {
DatabaseModelBean dbModel = hasSelection.get(i);
checkDbHashMatch(dbModel);
if (!checkDbIsExist(curDbList, dbModel)) { // 判断当前是否已经存在了
if (curDbList.size() == 0) { // 第一个添加的库为默认库
dbModel.setDefault(true);
}
curDbList.add(dbModel);
this.tableViewer.refresh();
} else {
dbNames.append(dbModel.getDbName());
dbNames.append("\n");
}
}
if (dbNames.length() != 0) {
MessageDialog.openInformation(getShell(), Messages.getString("newproject.NewProjectTbPage.msgTitle"),
Messages.getString("newproject.NewProjectTbPage.msg2") + dbNames.toString());
}
}
/**
* 检查当前库是否已经存在
* @param b
* @return ;
*/
private boolean checkDbIsExist(List<Object> curDbList, DatabaseModelBean b) {
for (int i = 0; i < curDbList.size(); i++) {
DatabaseModelBean a = (DatabaseModelBean) curDbList.get(i);
String dbname = a.getDbName();
String host = a.getHost();
String port = a.getPort();
String instance = a.getInstance();
String localPath = a.getItlDBLocation();
if (b.getDbName().equals(dbname) && b.getHost().equals(host) && b.getItlDBLocation().equals(localPath)
&& b.getPort().equals(port) && b.getInstance().equals(instance)) {
return true;
}
}
return false;
}
private void removeForCurrDbList(IStructuredSelection selection) {
curDbList.removeAll(selection.toList());
this.tableViewer.remove(selection.toArray());
}
/**
* 针对添加,创建,删除,导入TMX的事件响应
* @see org.eclipse.swt.widgets.Listener#handleEvent(org.eclipse.swt.widgets.Event)
*/
public void handleEvent(Event event) {
}
/**
* 创建Table列
* @param viewer
* ;
*/
private void createColumn(final TableViewer viewer) {
String[] clmnTitles = { Messages.getString("newproject.NewProjectTbPage.clmnTitles1"),
Messages.getString("newproject.NewProjectTbPage.clmnTitles2"),
Messages.getString("newproject.NewProjectTbPage.clmnTitles3"),
Messages.getString("newproject.NewProjectTbPage.clmnTitles4"),
Messages.getString("newproject.NewProjectTbPage.clmnTitles5") };
int[] clmnBounds = { 100, 100, 200, 90, 70 };
TableViewerColumn col = createTableViewerColumn(viewer, clmnTitles[0], clmnBounds[0], 0);
col.setLabelProvider(new ColumnLabelProvider() {
public String getText(Object element) {
DatabaseModelBean dbModel = (DatabaseModelBean) element;
return dbModel.getDbName();
}
});
col = createTableViewerColumn(viewer, clmnTitles[1], clmnBounds[1], 1);
col.setLabelProvider(new ColumnLabelProvider() {
public String getText(Object element) {
DatabaseModelBean dbModel = (DatabaseModelBean) element;
if (dbModel.getDbType().equals(Constants.DBTYPE_SQLITE)) {
return Messages.getString("tb.dbtype.sqlite");
}
return dbModel.getDbType();
}
});
col = createTableViewerColumn(viewer, clmnTitles[2], clmnBounds[2], 2);
col.setLabelProvider(new ColumnLabelProvider() {
public String getText(Object element) {
DatabaseModelBean dbModel = (DatabaseModelBean) element;
if (dbModel.getDbType().equals(Constants.DBTYPE_INTERNALDB)
|| dbModel.getDbType().equals(Constants.DBTYPE_SQLITE)) {
return dbModel.getItlDBLocation();
}
return dbModel.getHost();
}
});
col = createTableViewerColumn(viewer, clmnTitles[3], clmnBounds[3], 3);
col.setLabelProvider(new ColumnLabelProvider() {
public String getText(Object element) {
DatabaseModelBean dbModel = (DatabaseModelBean) element;
if (dbModel.isHasMatch()) {
return Messages.getString("newproject.NewProjectTbPage.yes");
} else {
return Messages.getString("newproject.NewProjectTbPage.no");
}
}
});
col = createTableViewerColumn(viewer, clmnTitles[4], clmnBounds[4], 4);
col.setLabelProvider(new ColumnLabelProvider() {
public Image getImage(Object element) {
DatabaseModelBean dbModel = (DatabaseModelBean) element;
if (dbModel.isDefault()) {
return checkedImage;
} else {
return uncheckedImage;
}
}
public String getText(Object element) {
return null;
}
});
col.setEditingSupport(new ReadableEditingSupport(viewer));
}
/**
* 设置TableViewer 列属性
* @param viewer
* @param title
* 列标题
* @param bound
* 列宽
* @param colNumber
* 列序号
* @return {@link TableViewerColumn};
*/
private TableViewerColumn createTableViewerColumn(TableViewer viewer, String title, int bound, final int colNumber) {
final TableViewerColumn viewerColumn = new TableViewerColumn(viewer, SWT.NONE | SWT.Resize);
final TableColumn column = viewerColumn.getColumn();
column.setText(title);
column.setWidth(bound);
column.setResizable(true);
column.setMoveable(true);
return viewerColumn;
}
/**
* Cell Editing Support for readable
* @author Jason
* @version
* @since JDK1.6
*/
protected class ReadableEditingSupport extends EditingSupport {
private final TableViewer viewer;
public ReadableEditingSupport(TableViewer viewer) {
super(viewer);
this.viewer = viewer;
}
@Override
protected CellEditor getCellEditor(Object element) {
return new CheckboxCellEditor(null, SWT.CHECK);
}
@Override
protected boolean canEdit(Object element) {
return true;
}
@Override
protected Object getValue(Object element) {
DatabaseModelBean dbModel = (DatabaseModelBean) element;
return dbModel.isDefault();
}
@Override
protected void setValue(Object element, Object value) {
// 实现单选
List<?> dbList = (List<?>) viewer.getInput();
for (int i = 0; i < dbList.size(); i++) {
((DatabaseModelBean) dbList.get(i)).setDefault(false);
}
// 实现单选
// 执行修改
DatabaseModelBean dbModel = (DatabaseModelBean) element;
dbModel.setDefault((Boolean) value);
// 刷新
viewer.refresh();
}
}
/**
* 需要调用Database模块 检查当前项目在库中是否有语言对的匹配
* @param dbModel
* 数据库信息;
*/
private void checkDbHashMatch(DatabaseModelBean dbModel, String type) {
DBOperator dbOp = DatabaseService.getDBOperator(dbModel.toDbMetaData());
try {
dbOp.start();
dbModel.setHasMatch(dbOp.checkHasMatchs(super.projSourceLang.getCode(), type));
} catch (Exception e) {
LOGGER.error("", e);
e.printStackTrace();
dbModel.setHasMatch(false);
} finally {
try {
if (dbOp != null) {
dbOp.end();
}
} catch (SQLException e) {
LOGGER.error("", e);
}
}
}
/**
* 需要调用Database模块 检查当前项目在库中是否有语言对的匹配
* @param dbModel
* 数据库信息;
*/
private void checkDbHashMatch(DatabaseModelBean dbModel) {
checkDbHashMatch(dbModel, "B");
}
@Override
public List<DatabaseModelBean> getSelectedDatabase() {
List<DatabaseModelBean> tbDbList = new ArrayList<DatabaseModelBean>();
for (int i = 0; i < curDbList.size(); i++) {
tbDbList.add((DatabaseModelBean) curDbList.get(i));
}
return tbDbList;
}
@Override
public void dispose() {
if (checkedImage != null && !checkedImage.isDisposed()) {
checkedImage.dispose();
}
if (uncheckedImage != null && !uncheckedImage.isDisposed()) {
uncheckedImage.dispose();
}
super.dispose();
}
}
| 15,786 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
Messages.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/database/net.heartsome.cat.database.ui.tb/src/net/heartsome/cat/database/ui/tb/resource/Messages.java | package net.heartsome.cat.database.ui.tb.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.database.ui.tb.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;
}
}
}
| 566 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
Activator.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/database/net.heartsome.cat.database.hsql/src/net/heartsome/cat/database/hsql/Activator.java | package net.heartsome.cat.database.hsql;
import net.heartsome.cat.database.DBServiceProvider;
import org.eclipse.core.runtime.Plugin;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceRegistration;
/**
* The activator class controls the plug-in life cycle
*/
public class Activator extends Plugin {
// The plug-in ID
public static final String PLUGIN_ID = "net.heartsome.cat.database.hsql";
// The shared instance
private static Activator plugin;
// The hsql service registration
private ServiceRegistration<DBServiceProvider> hsqlServiceRegistration;
/**
* 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;
DbServiceProviderImpl service = new DbServiceProviderImpl();
hsqlServiceRegistration = context.registerService(DBServiceProvider.class, service, null);
}
/*
* (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);
hsqlServiceRegistration.unregister();
}
/**
* Returns the shared instance
*
* @return the shared instance
*/
public static Activator getDefault() {
return plugin;
}
}
| 1,427 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
TMDatabaseImpl.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/database/net.heartsome.cat.database.hsql/src/net/heartsome/cat/database/hsql/TMDatabaseImpl.java | package net.heartsome.cat.database.hsql;
import java.net.URL;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
import net.heartsome.cat.common.util.TextUtil;
import net.heartsome.cat.database.Constants;
import net.heartsome.cat.database.DBConfig;
import net.heartsome.cat.database.DBOperator;
import net.heartsome.cat.database.Utils;
import org.eclipse.core.runtime.Platform;
import org.osgi.framework.Bundle;
/**
* @author terry
* @version
* @since JDK1.6
*/
public class TMDatabaseImpl extends DBOperator {
/**
* 构造函数
*/
public TMDatabaseImpl() {
Bundle buddle = Platform.getBundle(Activator.PLUGIN_ID);
URL fileUrl = buddle.getEntry(Constants.DBCONFIG_PATH);
dbConfig = new DBConfig(fileUrl);
}
@Override
public void start() throws SQLException, ClassNotFoundException {
String driver = dbConfig.getDriver();
Class.forName(driver);
String url = Utils.replaceParams(dbConfig.getDbURL(), metaData);
Properties prop = Utils.replaceParams(dbConfig.getConfigProperty(), metaData);
prop.setProperty("ifexists", "true");
conn = DriverManager.getConnection(url, prop);
// conn.setAutoCommit(false);
}
// @Override
// public void end() throws SQLException {
// if (conn != null && !conn.isClosed()) {
// Statement statement = null;
// try {
// statement = conn.createStatement();
// statement.executeUpdate("SHUTDOWN;");
// } catch (SQLNonTransientConnectionException e) {
// e.printStackTrace();
// super.end();
// }catch (SQLException ex) {
// LOGGER.error("", ex);
// } finally {
// if (statement != null) {
// statement.close();
// }
// }
// }
// super.end();
// }
/**
* (non-Javadoc)
* @see net.heartsome.cat.database.DBOperator#replaceTMOrTBConditionSql(java.lang.String, java.lang.String, boolean,
* boolean, boolean, java.lang.String, java.lang.String[])
*/
public String replaceTMOrTBConditionSql(String sql, String strSearch, boolean isCaseSensitive,
boolean isApplyRegular, boolean isIgnoreMark, String srcLang, String[] arrFilter) {
strSearch = strSearch == null ? "" : strSearch;
StringBuffer strCondition = new StringBuffer();
if (srcLang != null) {
strCondition.append(" AND LANG='" + srcLang + "'");
} else {
return null;
}
if (isApplyRegular) {
strCondition.append(" AND REGEXP_SUBSTRING(" + (isIgnoreMark ? "A.PURE" : "A.CONTENT") + ", '"
+ (isCaseSensitive ? "" : "(?i)") + TextUtil.replaceRegextSqlWithHSQL(strSearch) + "')!=''");
} else if (isCaseSensitive) {
strCondition.append(" AND " + (isIgnoreMark ? "A.PURE" : "A.CONTENT") + " LIKE '%"
+ TextUtil.cleanStringByLikeWithHSQL(strSearch) + "%' ESCAPE '\\\\'");
} else {
strCondition.append(" AND upper(" + (isIgnoreMark ? "A.PURE" : "A.CONTENT") + ") LIKE '%"
+ TextUtil.cleanStringByLikeWithHSQL(strSearch).toUpperCase() + "%' ESCAPE '\\\\'");
}
if (arrFilter != null) {
StringBuffer strFilter = new StringBuffer(arrFilter[1] + " '%"
+ TextUtil.cleanStringByLikeWithHSQL(arrFilter[2]).toUpperCase() + "%' ESCAPE '\\\\'");
// 过滤条件要加在源语言中
if (arrFilter[0].equalsIgnoreCase(srcLang)) {
sql = Utils.replaceString(sql, "__TABLE_TEXTDATA__", "");
strFilter.insert(0, " AND upper(A.PURE) ");
strCondition.append(strFilter.toString());
} else {
sql = Utils.replaceString(sql, "__TABLE_TEXTDATA__", " ,TEXTDATA B ");
strCondition.append(" AND A.GROUPID=B.GROUPID AND B.TYPE='M' AND B.LANG='" + arrFilter[0] + "'");
strFilter.insert(0, " AND upper(B.PURE) ");
strCondition.append(strFilter.toString());
}
} else {
sql = Utils.replaceString(sql, "__TABLE_TEXTDATA__", "");
}
sql = Utils.replaceString(sql, "__CONDITION__", strCondition.toString());
return sql;
}
}
| 3,804 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
MetaDataImpl.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/database/net.heartsome.cat.database.hsql/src/net/heartsome/cat/database/hsql/MetaDataImpl.java | package net.heartsome.cat.database.hsql;
import net.heartsome.cat.common.bean.MetaData;
public class MetaDataImpl extends MetaData{
@Override
public boolean instanceSupported() {
return false;
}
@Override
public boolean passwordSupported() {
return false;
}
@Override
public boolean portSupported() {
return false;
}
@Override
public boolean serverNameSupported() {
return false;
}
@Override
public boolean userNameSupported() {
return false;
}
}
| 485 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
OperateSystemDBImpl.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/database/net.heartsome.cat.database.hsql/src/net/heartsome/cat/database/hsql/OperateSystemDBImpl.java | package net.heartsome.cat.database.hsql;
import java.io.File;
import java.net.URL;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import net.heartsome.cat.common.bean.MetaData;
import net.heartsome.cat.database.Constants;
import net.heartsome.cat.database.DBConfig;
import net.heartsome.cat.database.SystemDBOperator;
import net.heartsome.cat.database.Utils;
import net.heartsome.cat.database.hsql.resource.Messages;
import org.eclipse.core.runtime.Platform;
import org.osgi.framework.Bundle;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class OperateSystemDBImpl extends SystemDBOperator {
private Logger logger = LoggerFactory.getLogger(OperateSystemDBImpl.class);
public OperateSystemDBImpl() {
metaData = new MetaDataImpl();
Bundle buddle = Platform.getBundle(Activator.PLUGIN_ID);
URL fileUrl = buddle.getEntry(Constants.DBCONFIG_PATH);
dbConfig = new DBConfig(fileUrl);
metaData.setDbType(dbConfig.getDefaultType());
}
@Override
public int createDB() throws SQLException {
List<String> createTables = dbConfig.getCreateTables();
createTables.addAll(dbConfig.getCreateIndexs());
return createDB(createTables, metaData);
}
/**
* 创建数据表
* @param createTables
* @param metaData
* @return
* @throws SQLException
* ;
*/
private int createDB(List<String> createTables, MetaData metaData) throws SQLException {
Connection conn = null;
Statement stmt = null;
String driver = dbConfig.getDriver();
String url = Utils.replaceParams(dbConfig.getDbURL(), metaData);
Properties prop = Utils.replaceParams(dbConfig.getConfigProperty(), metaData);
try {
conn = getConnection(driver, url, prop);
conn.setAutoCommit(false);
stmt = conn.createStatement();
if (createTables != null) {
for (String i : createTables) {
String step = Utils.replaceParams(i, metaData);
stmt.execute(step);
}
}
conn.commit();
} catch (ClassNotFoundException e) {
logger.error("", e);
e.printStackTrace();
return Constants.FAILURE;
} catch (SQLException e) {
logger.error("", e);
e.printStackTrace();
try {
if (conn != null && !conn.isClosed()) {
conn.rollback();
}
} catch (SQLException e1) {
throw e1;
}
} finally {
try {
stmt.executeUpdate("SHUTDOWN;");
} catch (SQLException e) {
logger.error("", e);
}
freeConnection(stmt, conn);
}
return Constants.SUCCESS;
}
@Override
public void removeSysDb(String dbName) throws SQLException {
Connection conn = null;
PreparedStatement pstmt = null;
String driver = dbConfig.getDriver();
metaData.setDatabaseName(Constants.HSSYSDB);
String url = Utils.replaceParams(dbConfig.getDbURL(), metaData);
Properties prop = Utils.replaceParams(dbConfig.getConfigProperty(), metaData);
// 删除系统表中的数据
prop = Utils.replaceParams(dbConfig.getConfigProperty(), metaData);
try {
conn = getConnection(driver, url, prop);
String removeDb = dbConfig.getRemoveSysDb();
pstmt = conn.prepareStatement(removeDb);
pstmt.setString(1, dbName);
pstmt.execute();
} catch (ClassNotFoundException e) {
logger.warn("", e);
} finally {
Statement _stmt = null;
try {
_stmt = conn.createStatement();
_stmt.executeUpdate("SHUTDOWN;");
} catch (SQLException e) {
logger.error("", e);
} finally{
if(_stmt != null){
_stmt.close();
}
}
freeConnection(pstmt, conn);
}
}
/**
* 插入系统库
* @param dbName
* 数据库名称
* @param quality
* 是否优化
*/
public void addSysDb(String dbName, String quality, int type) {
MetaData data = null;
try {
data = (MetaData) metaData.clone();
data.setDatabaseName(Constants.HSSYSDB);
} catch (CloneNotSupportedException e) {
logger.warn("", e);
return;
}
String driver = dbConfig.getDriver();
String url = Utils.replaceParams(dbConfig.getDbURL(), data);
Properties prop = Utils.replaceParams(dbConfig.getConfigProperty(), data);
Connection conn = null;
PreparedStatement stmt = null;
try {
conn = getConnection(driver, url, prop);
String insertDb = Utils.replaceParams(dbConfig.getInsertSysDb(), data);
stmt = conn.prepareStatement(insertDb);
stmt.setString(1, dbName);
stmt.setString(2, quality);
stmt.setInt(3, type);
stmt.execute();
} catch (ClassNotFoundException e) {
logger.warn("", e);
} catch (SQLException e) {
logger.warn("", e);
} finally {
Statement _stmt = null;
try {
_stmt = conn.createStatement();
_stmt.executeUpdate("SHUTDOWN;");
} catch (SQLException e) {
logger.error("", e);
} finally{
if(_stmt != null){
try {
_stmt.close();
} catch (SQLException e) {
logger.error("",e);
}
}
}
freeConnection(stmt, conn);
}
}
/**
* 创建系统库
* @return
* @throws SQLException
*/
public int createSysDb() throws SQLException {
MetaData data = null;
try {
data = (MetaData) metaData.clone();
data.setDatabaseName(Constants.HSSYSDB);
} catch (CloneNotSupportedException e) {
logger.warn("", e);
return Constants.FAILURE;
}
List<String> createTables = dbConfig.getCreateSysTables();
return createDB(createTables, data);
}
@Override
public boolean checkSysDb() {
MetaData data = null;
try {
data = (MetaData) metaData.clone();
data.setDatabaseName(Constants.HSSYSDB);
} catch (CloneNotSupportedException e) {
logger.warn("", e);
return false;
}
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
String driver = dbConfig.getDriver();
String url = Utils.replaceParams(dbConfig.getDbURL(), data);
Properties prop = Utils.replaceParams(dbConfig.getConfigProperty(), data);
try {
conn = getConnection(driver, url, prop);
stmt = conn.createStatement();
rs = stmt.executeQuery("SELECT DBNAME, QUALITY, USERS FROM HSCATSYSDB");
} catch (ClassNotFoundException e) {
logger.warn(Messages.getString("hsql.OperateSystemDBImpl.logger1"), e);
return false;
} catch (SQLException e) {
// 系统表不存在则创建系统表
List<String> createTables = dbConfig.getCreateSysTables();
try {
createDB(createTables, data);
return true;
} catch (SQLException e1) {
logger.error(Messages.getString("hsql.OperateSystemDBImpl.logger2"), e);
return false;
}
} finally {
try {
if(stmt != null){
stmt.executeUpdate("SHUTDOWN;");
}
} catch (SQLException e) {
// logger.error("", e);
}
if(rs != null){
try {
rs.close();
} catch (SQLException e) {
logger.error("",e);
}
}
freeConnection(stmt, conn);
}
return true;
}
@Override
public List<String> getSysDbNames(int type) {
MetaData data = null;
try {
data = (MetaData) metaData.clone();
data.setDatabaseName(Constants.HSSYSDB);
} catch (CloneNotSupportedException e) {
logger.warn("", e);
return null;
}
String driver = dbConfig.getDriver();
String url = Utils.replaceParams(dbConfig.getDbURL(), data);
Properties prop = Utils.replaceParams(dbConfig.getConfigProperty(), data);
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
List<String> result = new ArrayList<String>();
try {
conn = getConnection(driver, url, prop);
String sql = dbConfig.getSysDbList();
stmt = conn.prepareStatement(sql);
stmt.setInt(1, type);
rs = stmt.executeQuery();
while (rs.next()) {
result.add(rs.getString("DBNAME"));
}
} catch (ClassNotFoundException e) {
logger.warn("", e);
} catch (SQLException e) {
logger.warn("", e);
} finally {
Statement _stmt = null;
try {
_stmt = conn.createStatement();
_stmt.executeUpdate("SHUTDOWN;");
} catch (SQLException e) {
logger.error("", e);
} finally{
if(stmt != null){
try {
_stmt.close();
} catch (SQLException e) {
logger.warn("", e);
}
}
}
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
logger.warn("", e);
}
}
freeConnection(stmt, conn);
}
return result;
}
@Override
public boolean checkDbConnection() {
return true;
}
/**
* (non-Javadoc)
* @see net.heartsome.cat.database.SystemDBOperator#checkDbExistOnServer()
*/
@Override
public boolean checkDbExistOnServer() {
Connection conn = null;
MetaData data = null;
try {
data = (MetaData) metaData.clone();
} catch (CloneNotSupportedException e) {
logger.warn("", e);
return false;
}
try {
String url = Utils.replaceParams(dbConfig.getDbURL(), data);
String driver = dbConfig.getDriver();
Properties prop = Utils.replaceParams(dbConfig.getConfigProperty(), data);
prop.setProperty("ifexists", "true");
conn = getConnection(driver, url, prop);
} catch (ClassNotFoundException e) {
logger.error(Messages.getString("hsql.OperateSystemDBImpl.logger3"), e);
return false;
} catch (SQLException e) {
//logger.error("", e);
// Just check ,so don't need record the exception
return false;
} finally {
if (conn != null) {
try {
Statement stmt = conn.createStatement();
stmt.executeUpdate("SHUTDOWN;");
freeConnection(stmt, conn);
} catch (SQLException e) {
logger.error("", e);
}
}
}
return true;
}
@Override
public void dropDb(String dbName) throws SQLException {
Connection conn = null;
Statement stmt = null;
String driver = dbConfig.getDriver();
metaData.setDatabaseName(dbName);
String url = Utils.replaceParams(dbConfig.getDbURL(), metaData);
Properties prop = Utils.replaceParams(dbConfig.getConfigProperty(), metaData);
try {
conn = getConnection(driver, url, prop);
conn.setAutoCommit(false);
stmt = conn.createStatement();
String path = metaData.getDataPath();
stmt.executeUpdate("SHUTDOWN;");
stmt.close();
conn.close();
File f = new File(path + "/" + dbName + ".script");
if (f.exists()) {
f.delete();
}
f = new File(path + "/" + dbName + ".properties");
if (f.exists()) {
f.delete();
}
f = new File(path + "/" + dbName + ".data");
if (f.exists()) {
f.delete();
}
f = new File(path + "/" + dbName + ".backup");
if (f.exists()) {
f.delete();
}
f = new File(path + "/" + dbName + ".log");
if (f.exists()) {
f.delete();
}
f = new File(path + "/" + dbName + ".lck");
if (f.exists()) {
f.delete();
}
f = new File(path + "/" + dbName + ".tmp");
if (f.exists()) {
f.delete();
}
f = null;
} catch (ClassNotFoundException e) {
logger.warn("", e);
}
}
@Override
protected Connection getConnection(String driver, String url, Properties prop) throws ClassNotFoundException,
SQLException {
Class.forName(driver);
return DriverManager.getConnection(url, prop);
}
}
| 11,052 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
DbServiceProviderImpl.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/database/net.heartsome.cat.database.hsql/src/net/heartsome/cat/database/hsql/DbServiceProviderImpl.java | package net.heartsome.cat.database.hsql;
import net.heartsome.cat.database.DBServiceProvider;
import net.heartsome.cat.database.SystemDBOperator;
import net.heartsome.cat.database.DBOperator;
public class DbServiceProviderImpl implements DBServiceProvider{
public SystemDBOperator getOperateDBInstance() {
return new OperateSystemDBImpl();
}
public DBOperator getTmDatabaseInstance() {
return new TMDatabaseImpl();
}
}
| 432 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
Messages.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/database/net.heartsome.cat.database.hsql/src/net/heartsome/cat/database/hsql/resource/Messages.java | package net.heartsome.cat.database.hsql.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.database.hsql.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 + '!';
}
}
}
| 907 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
Activator.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/database/net.heartsome.cat.database.postgreSQL/src/net/heartsome/cat/database/postgresql/Activator.java | package net.heartsome.cat.database.postgresql;
import net.heartsome.cat.database.DBServiceProvider;
import org.eclipse.core.runtime.Plugin;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceRegistration;
/**
* The activator class controls the plug-in life cycle
*/
public class Activator extends Plugin {
// The plug-in ID
public static final String PLUGIN_ID = "net.heartsome.cat.database.postgreSQL";
// The shared instance
private static Activator plugin;
// The postgresql service registration
private ServiceRegistration<DBServiceProvider> postgresqlServiceRegistration;
/**
* 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;
DbServiceProviderImpl service = new DbServiceProviderImpl();
postgresqlServiceRegistration = context.registerService(DBServiceProvider.class, service, null);
}
/*
* (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);
postgresqlServiceRegistration.unregister();
}
/**
* Returns the shared instance
*
* @return the shared instance
*/
public static Activator getDefault() {
return plugin;
}
}
| 1,463 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
TMDatabaseImpl.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/database/net.heartsome.cat.database.postgreSQL/src/net/heartsome/cat/database/postgresql/TMDatabaseImpl.java | package net.heartsome.cat.database.postgresql;
import java.net.URL;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
import net.heartsome.cat.common.util.TextUtil;
import net.heartsome.cat.database.Constants;
import net.heartsome.cat.database.DBConfig;
import net.heartsome.cat.database.DBOperator;
import net.heartsome.cat.database.Utils;
import org.eclipse.core.runtime.Platform;
import org.osgi.framework.Bundle;
/**
* @author terry
* @version
* @since JDK1.6
*/
public class TMDatabaseImpl extends DBOperator {
public void start() throws SQLException, ClassNotFoundException {
String driver = dbConfig.getDriver();
Class.forName(driver);
String url = Utils.replaceParams(dbConfig.getDbURL(), metaData);
Properties prop = Utils.replaceParams(dbConfig.getConfigProperty(), metaData);
conn = DriverManager.getConnection(url, prop);
// 在 PostgreSQL 中如果使用事务,那么在事务中创建表格会抛出异常。
conn.setAutoCommit(false);
}
/**
* 构造函数
*/
public TMDatabaseImpl() {
Bundle buddle = Platform.getBundle(Activator.PLUGIN_ID);
URL fileUrl = buddle.getEntry(Constants.DBCONFIG_PATH);
dbConfig = new DBConfig(fileUrl);
}
/**
* (non-Javadoc)
* @see net.heartsome.cat.database.DBOperator#replaceTMOrTBConditionSql(java.lang.String, java.lang.String, boolean,
* boolean, boolean, java.lang.String, java.lang.String[])
*/
public String replaceTMOrTBConditionSql(String sql, String strSearch, boolean isCaseSensitive,
boolean isApplyRegular, boolean isIgnoreMark, String srcLang, String[] arrFilter) {
strSearch = strSearch == null ? "" : strSearch;
StringBuffer strCondition = new StringBuffer();
if (srcLang != null) {
strCondition.append(" AND A.LANG='" + srcLang + "'");
} else {
return null;
}
if (isApplyRegular) {
// ~ 匹配正则表达式,大小写相关。例: 'thomas' ~ '.*thomas.*'
// ~* 匹配正则表达式,大小写无关。例: 'thomas' ~* '.*Thomas.*'
// !~ 不匹配正则表达式,大小写相关。例: 'thomas' !~ '.*Thomas.*'
// !~* 不匹配正则表达式,大小写无关。例: 'thomas' !~* '.*vadim.*'
strCondition.append(" AND " + (isIgnoreMark ? "A.PURE" : "A.CONTENT") + " "
+ (isCaseSensitive ? "~" : "~*") + " '" + TextUtil.replaceRegextSqlWithMOP(strSearch) + "'");
} else if (isCaseSensitive) {
// postgreSql 中区分大小写用 LIKE,不区分用 ILIKE
strCondition.append(" AND " + (isIgnoreMark ? "A.PURE" : "A.CONTENT") + " LIKE '%"
+ TextUtil.cleanStringByLikeWithPostgreSql(strSearch) + "%' ESCAPE '\\\\'");
} else {
strCondition.append(" AND " + (isIgnoreMark ? "A.PURE" : "A.CONTENT") + " ILIKE '%"
+ TextUtil.cleanStringByLikeWithPostgreSql(strSearch) + "%' ESCAPE '\\\\'");
}
if (arrFilter != null) {
StringBuffer strFilter = new StringBuffer(arrFilter[1].replaceAll("LIKE", "ILIKE").replaceAll("like",
"ILIKE")
+ " '%" + TextUtil.cleanStringByLikeWithPostgreSql(arrFilter[2]) + "%' ESCAPE '\\\\'");
// 过滤条件要加在源语言中
if (arrFilter[0].equalsIgnoreCase(srcLang)) {
sql = Utils.replaceString(sql, "__TABLE_TEXTDATA__", "");
strFilter.insert(0, " AND A.PURE ");
strCondition.append(strFilter.toString());
} else {
sql = Utils.replaceString(sql, "__TABLE_TEXTDATA__", " ,TEXTDATA B ");
strCondition.append(" AND A.GROUPID=B.GROUPID AND B.TYPE='M' AND B.LANG='" + arrFilter[0] + "'");
strFilter.insert(0, " AND B.PURE ");
strCondition.append(strFilter.toString());
}
} else {
sql = Utils.replaceString(sql, "__TABLE_TEXTDATA__", "");
}
sql = Utils.replaceString(sql, "__CONDITION__", strCondition.toString());
return sql;
}
}
| 3,749 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
MetaDataImpl.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/database/net.heartsome.cat.database.postgreSQL/src/net/heartsome/cat/database/postgresql/MetaDataImpl.java | package net.heartsome.cat.database.postgresql;
import net.heartsome.cat.common.bean.MetaData;
public class MetaDataImpl extends MetaData{
@Override
public boolean dataPathSupported() {
return false;
}
@Override
public boolean instanceSupported() {
return false;
}
/**
* PostgreSQL数据库名称,只支持小写
* (non-Javadoc)
* @see net.heartsome.cat.common.bean.MetaData#setDatabaseName(java.lang.String)
*/
@Override
public void setDatabaseName(String databaseName) {
this.databaseName = databaseName.toLowerCase();
}
}
| 554 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
OperateDBImpl.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/database/net.heartsome.cat.database.postgreSQL/src/net/heartsome/cat/database/postgresql/OperateDBImpl.java | package net.heartsome.cat.database.postgresql;
import java.net.URL;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;
import java.util.Properties;
import net.heartsome.cat.common.bean.MetaData;
import net.heartsome.cat.database.Constants;
import net.heartsome.cat.database.DBConfig;
import net.heartsome.cat.database.SystemDBOperator;
import net.heartsome.cat.database.Utils;
import net.heartsome.cat.database.postgresql.resource.Messages;
import org.eclipse.core.runtime.Platform;
import org.osgi.framework.Bundle;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class OperateDBImpl extends SystemDBOperator {
private Logger logger = LoggerFactory.getLogger(this.getClass());
public OperateDBImpl() {
metaData = new MetaDataImpl();
Bundle buddle = Platform.getBundle(Activator.PLUGIN_ID);
URL fileUrl = buddle.getEntry(Constants.DBCONFIG_PATH);
dbConfig = new DBConfig(fileUrl);
metaData.setServerName(dbConfig.getDefaultServer());
metaData.setPort(dbConfig.getDefaultPort());
metaData.setDbType(dbConfig.getDefaultType());
}
@Override
public boolean checkDbConnection() {
Connection conn = null;
Statement stmt = null;
String driver = dbConfig.getDriver();
String url = Utils.replaceParams(dbConfig.getDbURL(), metaData);
Properties prop = Utils.replaceParams(dbConfig.getConfigProperty(), metaData);
// 创建数据库
try {
conn = getConnection(driver, url.substring(0, url.lastIndexOf("/")) + "/template1", prop); //$NON-NLS-1$
} catch (ClassNotFoundException e) {
logger.error(Messages.getString("postgresql.OperateDBImpl.logger1"), e);
return false;
} catch (SQLException e) {
logger.error(Messages.getString("postgresql.OperateDBImpl.logger2"), e);
return false;
} finally {
freeConnection(stmt, conn);
}
return true;
}
@Override
protected int createDB(String createDb, List<String> createTables, MetaData metaData) throws SQLException {
Connection conn = null;
Statement stmt = null;
String driver = dbConfig.getDriver();
String url = Utils.replaceParams(dbConfig.getDbURL(), metaData);
Properties prop = Utils.replaceParams(dbConfig.getConfigProperty(), metaData);
// 创建数据库
try {
conn = getConnection(driver, url.substring(0, url.lastIndexOf("/")) + "/template1", prop); //$NON-NLS-1$
stmt = conn.createStatement();
stmt.execute(createDb);
} catch (ClassNotFoundException e) {
logger.error(Messages.getString("postgresql.OperateDBImpl.logger1"), e);
return Constants.FAILURE;
} finally {
freeConnection(stmt, conn);
}
// 创建数据库表格
try {
conn = getConnection(driver, url, prop);
conn.setAutoCommit(false);
stmt = conn.createStatement();
if (createTables != null) {
for (String i : createTables) {
String step = Utils.replaceParams(i, metaData);
stmt.execute(step);
}
}
conn.commit();
} catch (SQLException e) {
try {
if (conn != null && !conn.isClosed()) {
conn.rollback();
}
} catch (SQLException e1) {
logger.warn("", e1);
}
logger.warn("", e);
return Constants.FAILURE;
} catch (ClassNotFoundException e) {
try {
if (conn != null && !conn.isClosed()) {
conn.rollback();
}
} catch (SQLException e1) {
logger.warn("", e1);
}
logger.warn("", e);
return Constants.FAILURE;
} finally {
freeConnection(stmt, conn);
}
return Constants.SUCCESS;
}
@Override
public void dropDb(String dbName) throws SQLException {
Connection conn = null;
Statement stmt = null;
String driver = dbConfig.getDriver();
metaData.setDatabaseName(dbName);
String url = Utils.replaceParams(dbConfig.getDbURL(), metaData);
Properties prop = Utils.replaceParams(dbConfig.getConfigProperty(), metaData);
// 删除数据库
try {
conn = getConnection(driver, url.substring(0, url.lastIndexOf("/")) + "/template1", prop); //$NON-NLS-1$
stmt = conn.createStatement();
String dropDb = Utils.replaceParams(dbConfig.getDropDb(), metaData);
stmt.execute(dropDb);
} catch (ClassNotFoundException e) {
logger.warn("", e);
} finally {
freeConnection(stmt, conn);
}
}
@Override
protected Connection getConnection(String driver, String url, Properties prop) throws ClassNotFoundException,
SQLException {
Class.forName(driver);
return DriverManager.getConnection(url, prop);
}
}
| 4,461 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
DbServiceProviderImpl.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/database/net.heartsome.cat.database.postgreSQL/src/net/heartsome/cat/database/postgresql/DbServiceProviderImpl.java | package net.heartsome.cat.database.postgresql;
import net.heartsome.cat.database.DBServiceProvider;
import net.heartsome.cat.database.SystemDBOperator;
import net.heartsome.cat.database.DBOperator;
public class DbServiceProviderImpl implements DBServiceProvider{
public SystemDBOperator getOperateDBInstance() {
return new OperateDBImpl();
}
public DBOperator getTmDatabaseInstance() {
return new TMDatabaseImpl();
}
}
| 432 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
Messages.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/database/net.heartsome.cat.database.postgreSQL/src/net/heartsome/cat/database/postgresql/resource/Messages.java | package net.heartsome.cat.database.postgresql.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.database.postgresql.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 + '!';
}
}
}
| 919 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
ImportTbx.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/database/net.heartsome.cat.database/src/net/heartsome/cat/document/ImportTbx.java | /**
* ImportTbx.java
*
* Version information :
*
* Date:Nov 18, 2011
*
* Copyright notice :
* 本文件及其附带的相关文件包含机密信息,仅限瀚特盛科技有限公司指定的,与本项目有关的内部人员和客户联络人员查阅和使用。
* 如果您不是本保密声明中指定的收件者,请立即销毁本文件,禁止对本文件或根据本文件中的内容采取任何其他行动,
* 包括但不限于:泄露本文件中的信息、以任何方式制作本文件全部或部分内容之副本、将本文件或其相关副本提供给任何其他人。
*/
package net.heartsome.cat.document;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import net.heartsome.cat.common.locale.LocaleService;
import net.heartsome.cat.database.Constants;
import net.heartsome.cat.database.DBOperator;
import net.heartsome.cat.database.Utils;
import net.heartsome.cat.database.resource.Messages;
import net.heartsome.xml.vtdimpl.VTDUtils;
import org.eclipse.core.runtime.OperationCanceledException;
import com.ximpleware.AutoPilot;
import com.ximpleware.EOFException;
import com.ximpleware.EncodingException;
import com.ximpleware.EntityException;
import com.ximpleware.ModifyException;
import com.ximpleware.NavException;
import com.ximpleware.ParseException;
import com.ximpleware.TranscodeException;
import com.ximpleware.VTDGen;
import com.ximpleware.XMLModifier;
import com.ximpleware.XPathEvalException;
import com.ximpleware.XPathParseException;
/**
* @author Jason
* @version
* @since JDK1.6
*/
public class ImportTbx extends ImportAbstract {
public ImportTbx(DBOperator tmDatabase, int importMode) {
this.fileType = Constants.TBX;
this.dbOperator = tmDatabase;
this.importStrategy = importMode;
}
/**
* (non-Javadoc)
* @throws ParseException
* @throws EntityException
* @throws EOFException
* @throws EncodingException
* @throws IOException
* @throws ModifyException
* @throws TranscodeException
* @see net.heartsome.cat.document.ImportAbstract#executeImport(java.lang.String)
*/
@Override
protected void executeImport(String srcLang) throws SQLException, NavException, XPathParseException,
XPathEvalException, EncodingException, EOFException, EntityException, ParseException, TranscodeException,
ModifyException, IOException {
srcLang = Utils.convertLangCode(srcLang);
if (monitor != null) {
int task = vu.getChildElementsCount("/martif/text/body") + vu.getChildElementsCount("/martif/text/back")
+ 10;
monitor.beginTask(Messages.getString("document.ImportTbx.task1"), task);
}
int headerPkId = 0;
String sourceLang = null;
AutoPilot ap = new AutoPilot(vu.getVTDNav());
ap.selectXPath("/martif");
Map<String, String> martifAttr = new HashMap<String, String>();
if (ap.evalXPath() != -1) {
martifAttr = vu.getCurrentElementAttributs();
sourceLang = martifAttr.get("xml:lang");
if (sourceLang == null) {
sourceLang = martifAttr.get("lang");
}
}
if (sourceLang == null || sourceLang.equals("")) {
sourceLang = srcLang;
} else {
sourceLang = Utils.convertLangCode(sourceLang);
}
if (sourceLang == null || sourceLang.equals("*all*") || sourceLang.equals("")) {
if (LocaleService.getLanguage(sourceLang).equals("")) {
throw new NavException(Messages.getString("document.ImportTbx.msg1"));
}
}
if (monitor != null) {
monitor.worked(5);
}
// 导入Header
ap.selectXPath("/martif/martifHeader");
if (ap.evalXPath() != -1) {
String hContent = vu.getElementFragment();
if (hContent != null) {
headerPkId = dbOperator.insertBMartifHeader(hContent, getElementAttribute("id"));
}
}
// TOTO 保存martifAttr到BATTRIBUTE表
dbOperator.insertBAttribute(martifAttr, "martif", headerPkId);
ap.selectXPath("/martif/text");
if (ap.evalXPath() != -1) {
Map<String, String> textAttr = vu.getCurrentElementAttributs();
dbOperator.insertBAttribute(textAttr, "text", headerPkId);
}
ap.selectXPath("/martif/body");
if (ap.evalXPath() != -1) {
Map<String, String> bodyAttr = vu.getCurrentElementAttributs();
dbOperator.insertBAttribute(bodyAttr, "body", headerPkId);
}
if (monitor != null) {
monitor.worked(5);
}
this.saveTermEntry(sourceLang, headerPkId);
ap.selectXPath("/martif/text/back");
if (ap.evalXPath() != -1) {
Map<String, String> backAttr = vu.getCurrentElementAttributs();
// TODO 保存back节点的属性
dbOperator.insertBAttribute(backAttr, "back", headerPkId);
ap.selectXPath("./refObjectList");
while (ap.evalXPath() != -1) {
String roblId = getElementAttribute("id");
String roblContent = vu.getElementFragment();
// 保存refObjectList内容
dbOperator.insertBRefobjectlist(roblContent, roblId, headerPkId);
if (monitor != null) {
monitor.worked(1);
}
}
}
if (monitor != null) {
monitor.done();
}
}
/**
* 始终增加策略
* @param headerId
* @throws XPathParseException
* @throws XPathEvalException
* @throws NavException
* @throws SQLException
* ;
*/
private void saveTermEntryWithAdd(int headerId, AutoPilot langSetAp, AutoPilot termAp) throws XPathParseException,
XPathEvalException, NavException, SQLException {
int termEntryPkId = dbOperator.insertBTermentry(vu.getElementFragment(), getElementAttribute("id"), headerId); // 将TermEntry整个节点写入库中
vu.getVTDNav().push();
while (langSetAp.evalXPath() != -1) {
String lang = getLang(); // 获取 LangSet节点下的语言
String pureText = "";
String fullText = "";
// 取LangSet节点下的Term节点内容
vu.getVTDNav().push();
while (termAp.evalXPath() != -1) {
pureText = DocUtils.getTmxTbxPureText(vu);
fullText = vu.getElementContent();
// TODO 将langSet节点中的term节点内容写入Textdata表中
String hash = null; // 当pureText为空字符串时,HASH字段留空
if (pureText != null) {
hash = "" + pureText.hashCode();
}
dbOperator.insertTextData("B", termEntryPkId, hash, pureText, fullText, lang, null, null);
}
termAp.resetXPath();
vu.getVTDNav().pop();
}
langSetAp.resetXPath();
vu.getVTDNav().pop();
AutoPilot noteAp = new AutoPilot(vu.getVTDNav());
noteAp.selectXPath("./note");
vu.getVTDNav().push();
while (noteAp.evalXPath() != -1) {
String content = vu.getElementContent();
String id = vu.getCurrentElementAttribut("id", "");
if (id.equals("") || content == null || content.equals("")) {
continue;
}
dbOperator.insertBNode(termEntryPkId, "termEntry", "E", "note", id, content);
}
vu.getVTDNav().pop();
}
/**
* 覆盖或者忽略
* @param headerId
* ;
* @throws SQLException
* @throws NavException
* @throws XPathEvalException
* @throws XPathParseException
* @throws ParseException
* @throws EntityException
* @throws EOFException
* @throws EncodingException
* @throws IOException
* @throws ModifyException
* @throws TranscodeException
*/
private void saveTermEntry(String srcLang, int headerId) throws XPathParseException, XPathEvalException,
NavException, SQLException, EncodingException, EOFException, EntityException, ParseException,
TranscodeException, ModifyException, IOException {
AutoPilot ap = new AutoPilot(vu.getVTDNav());
ap.selectXPath("/martif/text/body/termEntry"); // term entry
AutoPilot _ap = new AutoPilot(vu.getVTDNav());
_ap.declareXPathNameSpace("xml", VTDUtils.XML_NAMESPACE_URL);
_ap.selectXPath("./langSet[@xml:lang='" + srcLang + "']/tig/term|./ntig/termGrp/term"); // langSet == sourceLang
AutoPilot langSetAp = new AutoPilot(vu.getVTDNav());
langSetAp.selectXPath("./langSet");
AutoPilot termAp = new AutoPilot(vu.getVTDNav());
termAp.selectXPath("./tig/term|./ntig/termGrp/term"); // Term
List<String> textDataIds = new ArrayList<String>();
while (ap.evalXPath() != -1) { // 循环termEntry节点
if (monitor != null && monitor.isCanceled()) {
throw new OperationCanceledException();
}
if (importStrategy == Constants.IMPORT_MODEL_ALWAYSADD) { // 始终增加模式
saveTermEntryWithAdd(headerId, langSetAp, termAp);
if (monitor != null) {
monitor.worked(1);
}
continue;
}
// 判断该TermEntry节点是否重复
vu.getVTDNav().push();
while (_ap.evalXPath() != -1) {
String pureText = DocUtils.getTmxTbxPureText(vu);
pureText = pureText.trim();
textDataIds = dbOperator.getTextDataId(pureText.hashCode(), Utils.convertLangCode(srcLang), "B");
if (textDataIds.size() > 0) { // 当前TermEntry重复
break;
}
}
_ap.resetXPath();
vu.getVTDNav().pop();
// System.out.println(textDataIds);
if (textDataIds.size() == 0) { // 在库中没有重复的TermEntry
saveTermEntryWithAdd(headerId, langSetAp, termAp);
} else {
if (importStrategy == Constants.IMPORT_MODEL_IGNORE) { // 忽略当前TermEntry
if (monitor != null) {
monitor.worked(1);
}
continue;
} else { // 合并
List<String> termEntryPks = new ArrayList<String>();
termEntryPks = dbOperator.getTextDataGroupIdByTextId(textDataIds); // 获取源文相同的TermEntry Pk
// System.out.println(termEntryPks);
List<Map<String, String>> dbTermEntrys = dbOperator.getBTermEntryByPk(termEntryPks); // 获取TermEntry的内容
if (dbTermEntrys.size() == 1) { // 在库中只有一个TermEntry和当前TermEntry重复
if (importStrategy == Constants.IMPORT_MODEL_MERGE) {
saveTermEntryWithMerge(dbTermEntrys.get(0), langSetAp, termAp);
} else if (importStrategy == Constants.IMPORT_MODEL_OVERWRITE) {
saveTermEntryWithOverwrite(dbTermEntrys.get(0), langSetAp, termAp);
}
} else {
boolean updateflag = false;// 标记是否已经执行过更新
for (int i = 0; i < dbTermEntrys.size(); i++) {
Map<String, String> dbTermEntry = dbTermEntrys.get(i);
if (dbTermEntry.get("CID").equals(getElementAttribute("id"))) {
updateflag = true;
if (importStrategy == Constants.IMPORT_MODEL_MERGE) {
saveTermEntryWithMerge(dbTermEntry, langSetAp, termAp);
} else if (importStrategy == Constants.IMPORT_MODEL_OVERWRITE) {
saveTermEntryWithOverwrite(dbTermEntry, langSetAp, termAp);
}
}
}
if (!updateflag) { // 没有执行更新,即没有在库中找到和当前TermEntry ID一样的
saveTermEntryWithAdd(headerId, langSetAp, termAp);
}
}
}
}
if (monitor != null) {
monitor.worked(1);
}
}
}
private void saveTermEntryWithMerge(Map<String, String> dbTermEntry, AutoPilot langSetAp, AutoPilot termAp)
throws XPathParseException, XPathEvalException, NavException, SQLException, EncodingException,
EOFException, EntityException, ParseException, TranscodeException, ModifyException, IOException {
String content = dbTermEntry.get("CONTENT");
String termEntryPk = dbTermEntry.get("BTEPKID");
boolean changFlag = false; // content修改标记
VTDGen vg = new VTDGen();
VTDUtils vtdUtiles = new VTDUtils();
vg.setDoc(content.getBytes());
vg.parse(true);
vtdUtiles.bind(vg.getNav());
AutoPilot _ap = new AutoPilot(vtdUtiles.getVTDNav());
if (!content.equals(vu.getElementFragment())) {
vu.getVTDNav().push();
while (langSetAp.evalXPath() != -1) {
String curlang = getElementAttribute("xml:lang");
String tigValue = vu.getChildContent("tig");
String ntigValue = vu.getChildContent("ntig");
vtdUtiles.getVTDNav().push();
_ap.selectXPath("/termEntry/langSet[@xml:lang='" + curlang + "']");
if (_ap.evalXPath() != -1) { // 当语言的langSet在库中是否存在
vu.getVTDNav().push();
while (termAp.evalXPath() != -1) {
String fullText = vu.getElementContent();
String pureText = DocUtils.getTmxTbxPureText(vu);
vtdUtiles.getVTDNav().push();
_ap.selectXPath("./tig[term='" + fullText + "']|./ntig/termGrp[term='" + fullText + "']");
if (_ap.evalXPath() == -1) {
XMLModifier xm = null;
if (tigValue != null) {
xm = vtdUtiles.insert("/termEntry/langSet[@xml:lang='" + curlang + "']/tig", "<tig>"
+ tigValue + "</tig>");
} else if (ntigValue != null) {
xm = vtdUtiles.insert("/termEntry/langSet[@xml:lang='" + curlang + "']/tig", "<ntig>"
+ ntigValue + "</ntig>");
}
vtdUtiles.bind(xm.outputAndReparse());
String hash = null; // 当pureText为空字符串时,HASH字段留空
if (pureText != null) {
hash = "" + pureText.hashCode();
}
dbOperator.insertTextData("B", Integer.parseInt(termEntryPk), hash, pureText, fullText,
Utils.convertLangCode(curlang), null, null);
changFlag = true;
}
_ap.resetXPath();
vtdUtiles.getVTDNav().pop();
}
termAp.resetXPath();
vu.getVTDNav().pop();//
} else {
// 库中不存在该种语言的langSet,则新增
XMLModifier xm = vtdUtiles.insert("/termEntry/langSet", vu.getElementFragment());
vtdUtiles.bind(xm.outputAndReparse());
changFlag = true;
vu.getVTDNav().push();
if (termAp.evalXPath() != -1) {
String fullText = vu.getElementContent();
String pureText = DocUtils.getTmxTbxPureText(vu);
String hash = null; // 当pureText为空字符串时,HASH字段留空
if (pureText != null) {
hash = "" + pureText.hashCode();
}
dbOperator.insertTextData("B", Integer.parseInt(termEntryPk), hash, pureText, fullText,
Utils.convertLangCode(curlang), null, null);
}
termAp.resetXPath();
vu.getVTDNav().pop();
}
vtdUtiles.getVTDNav().pop();
}
langSetAp.resetXPath();
vu.getVTDNav().pop();
// 处理note
List<String> existDbNoteId = new ArrayList<String>();
List<String> existDbNotePk = new ArrayList<String>();
List<String> noteIdRm = new ArrayList<String>(); // 用于记录已经处理的noteId,过滤掉文件重复的内容
StringBuffer noteContentBf = new StringBuffer();
AutoPilot noteAp = new AutoPilot(vu.getVTDNav());
vu.getVTDNav().push();
noteAp.selectXPath("./note");
while (noteAp.evalXPath() != -1) {
String noteId = vu.getCurrentElementAttribut("id", "");
String noteContent = vu.getElementContent();
if (noteId.equals("") || noteContent == null || noteContent.equals("")) {
continue;
}
String[] ids = noteId.split(",");
if (ids.length != 2) {
continue;
}
String reNoteId = ids[1] + "," + ids[0];
if (noteIdRm.contains(noteId) || noteIdRm.contains(reNoteId)) {
continue; // 重复不重复写入
}
noteIdRm.add(noteId); // 记录已经处理的note
AutoPilot dbNoteAp = new AutoPilot(vtdUtiles.getVTDNav());
dbNoteAp.selectXPath("/termEntry/note[@id='" + noteId + "' or @id='" + reNoteId + "']");
while (dbNoteAp.evalXPath() != -1) {
String dbNoteId = vtdUtiles.getCurrentElementAttribut("id", "");
if (!existDbNoteId.contains(dbNoteId)) {
existDbNoteId.add(dbNoteId);
}
List<Map<String, String>> result = dbOperator.getBNodeByParent(termEntryPk, "termEntry", "E",
"note", dbNoteId);
for (Map<String, String> map : result) {
existDbNotePk.add(map.get("NPKID"));
}
}
dbOperator.insertBNode(Integer.parseInt(termEntryPk), "termEntry", "E", "note", noteId, noteContent);
noteContentBf.append(vu.getElementFragment());
}
vu.getVTDNav().pop();
if (existDbNotePk.size() > 0) {
dbOperator.deleteBNode(existDbNotePk);
}
StringBuffer xpathWhere = new StringBuffer();
for (String dbNodeId : existDbNoteId) {
xpathWhere.append("@id='" + dbNodeId + "' or ");
}
if (xpathWhere.length() > 0) {
String xpath = xpathWhere.substring(0, xpathWhere.lastIndexOf("or"));
XMLModifier xm = vtdUtiles.delete("/termEntry/note[" + xpath + "]", VTDUtils.PILOT_TO_END); // 清除文件中的note
vtdUtiles.bind(xm.outputAndReparse());
changFlag = true;
}
if (noteContentBf.length() != 0) {
XMLModifier xm = vtdUtiles.insert("/termEntry/text()", noteContentBf.toString());
vtdUtiles.bind(xm.outputAndReparse());
changFlag = true;
}
if (changFlag) {
dbOperator.updateTermEntry(vtdUtiles.getElementFragment(), termEntryPk);
}
}
}
private void saveTermEntryWithOverwrite(Map<String, String> dbTermEntry, AutoPilot langSetAp, AutoPilot termAp)
throws XPathParseException, XPathEvalException, NavException, SQLException, EncodingException,
EOFException, EntityException, ParseException, TranscodeException, ModifyException, IOException {
VTDGen vg = new VTDGen();
VTDUtils vtdUtiles = new VTDUtils();
String content = dbTermEntry.get("CONTENT");
String termEntryPk = dbTermEntry.get("BTEPKID");
if (!content.equals(vu.getElementFragment())) {
String prelang = "";
vu.getVTDNav().push();
while (langSetAp.evalXPath() != -1) {
String curlang = getElementAttribute("xml:lang");
String langSetValue = vu.getElementFragment();
vg.setDoc(content.getBytes());
vg.parse(true);
vtdUtiles.bind(vg.getNav());
if (!prelang.endsWith(curlang)) {
prelang = curlang;
dbOperator.deleteTerm(termEntryPk, curlang);
AutoPilot ap = new AutoPilot(vtdUtiles.getVTDNav());
ap.declareXPathNameSpace("xml", vtdUtiles.XML_NAMESPACE_URL);
XMLModifier xm = new XMLModifier(vtdUtiles.getVTDNav());
vtdUtiles.delete(ap, xm, "/termEntry/langSet[@xml:lang='" + curlang + "']");
vtdUtiles.bind(xm.outputAndReparse());
}
XMLModifier xm = vtdUtiles.insert("/termEntry/langSet", langSetValue);
vtdUtiles.bind(xm.outputAndReparse());
vu.getVTDNav().push();
while (termAp.evalXPath() != -1) {
String pureText = DocUtils.getTmxTbxPureText(vu);
String fullText = vu.getElementContent();
String hash = null; // 当pureText为空字符串时,HASH字段留空
if (pureText != null) {
hash = "" + pureText.hashCode();
}
dbOperator.insertTextData("B", Integer.parseInt(termEntryPk), hash, pureText, fullText,
Utils.convertLangCode(curlang), null, null);
}
termAp.resetXPath();
vu.getVTDNav().pop();
}
langSetAp.resetXPath();
vu.getVTDNav().pop();
// 处理note
List<String> existDbNoteId = new ArrayList<String>();
List<String> existDbNotePk = new ArrayList<String>();
List<String> noteIdRm = new ArrayList<String>(); // 用于记录已经处理的noteId,过滤掉文件重复的内容
StringBuffer noteContentBf = new StringBuffer();
AutoPilot noteAp = new AutoPilot(vu.getVTDNav());
vu.getVTDNav().push();
noteAp.selectXPath("./note");
while (noteAp.evalXPath() != -1) {
String noteId = vu.getCurrentElementAttribut("id", "");
String noteContent = vu.getElementContent();
if (noteId.equals("") || noteContent == null || noteContent.equals("")) {
continue;
}
String[] ids = noteId.split(",");
if (ids.length != 2) {
continue;
}
String reNoteId = ids[1] + "," + ids[0];
if (noteIdRm.contains(noteId) || noteIdRm.contains(reNoteId)) {
continue; // 重复不重复写入
}
noteIdRm.add(noteId); // 记录已经处理的note
AutoPilot dbNoteAp = new AutoPilot(vtdUtiles.getVTDNav());
dbNoteAp.selectXPath("/termEntry/note[@id='" + noteId + "' or @id='" + reNoteId + "']");
while (dbNoteAp.evalXPath() != -1) {
String dbNoteId = vtdUtiles.getCurrentElementAttribut("id", "");
if (!existDbNoteId.contains(dbNoteId)) {
existDbNoteId.add(dbNoteId);
}
List<Map<String, String>> result = dbOperator.getBNodeByParent(termEntryPk, "termEntry", "E",
"note", dbNoteId);
for (Map<String, String> map : result) {
existDbNotePk.add(map.get("NPKID"));
}
}
dbOperator.insertBNode(Integer.parseInt(termEntryPk), "termEntry", "E", "note", noteId, noteContent);
noteContentBf.append(vu.getElementFragment());
}
if (existDbNotePk.size() > 0) {
dbOperator.deleteBNode(existDbNotePk);
}
StringBuffer xpathWhere = new StringBuffer();
for (String dbNodeId : existDbNoteId) {
xpathWhere.append("@id='" + dbNodeId + "' or ");
}
if (xpathWhere.length() > 0) {
String xpath = xpathWhere.substring(0, xpathWhere.lastIndexOf("or"));
XMLModifier xm = vtdUtiles.delete("/termEntry/note[" + xpath + "]", VTDUtils.PILOT_TO_END); // 清除文件中的note
vtdUtiles.bind(xm.outputAndReparse());
}
if (noteContentBf.length() != 0) {
XMLModifier xm = vtdUtiles.insert("/termEntry/text()", noteContentBf.toString());
vtdUtiles.bind(xm.outputAndReparse());
}
content = vtdUtiles.getElementFragment();
dbOperator.updateTermEntry(content, termEntryPk);
vu.getVTDNav().pop();
}
}
/**
* 获取当前节点属性的值
* @param attrName
* 属性名称
* @return
* @throws XPathParseException
* @throws XPathEvalException
* @throws NavException
* ;
*/
private String getElementAttribute(String attrName) throws XPathParseException, XPathEvalException, NavException {
Map<String, String> attr = vu.getCurrentElementAttributs();
if (attr != null) {
String attrValue = attr.get(attrName);
return attr.get(attrName) == null ? "" : attrValue;
}
return "";
}
}
| 21,472 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
ExportTbxImpl.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/database/net.heartsome.cat.database/src/net/heartsome/cat/document/ExportTbxImpl.java | /**
* ExportTbxImpl.java
*
* Version information :
*
* Date:Feb 24, 2012
*
* Copyright notice :
* 本文件及其附带的相关文件包含机密信息,仅限瀚特盛科技有限公司指定的,与本项目有关的内部人员和客户联络人员查阅和使用。
* 如果您不是本保密声明中指定的收件者,请立即销毁本文件,禁止对本文件或根据本文件中的内容采取任何其他行动,
* 包括但不限于:泄露本文件中的信息、以任何方式制作本文件全部或部分内容之副本、将本文件或其相关副本提供给任何其他人。
*/
package net.heartsome.cat.document;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.sql.SQLException;
import java.util.Iterator;
import java.util.List;
import net.heartsome.cat.database.DBOperator;
import net.heartsome.cat.database.bean.ExportDatabaseBean;
import net.heartsome.cat.database.bean.ExportFilterBean;
import net.heartsome.cat.database.bean.ExportFilterComponentBean;
import net.heartsome.cat.database.resource.Messages;
import net.heartsome.cat.database.service.DatabaseService;
import net.heartsome.xml.vtdimpl.VTDUtils;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.SubProgressMonitor;
import com.ximpleware.AutoPilot;
import com.ximpleware.ModifyException;
import com.ximpleware.NavException;
import com.ximpleware.TranscodeException;
import com.ximpleware.VTDGen;
import com.ximpleware.XMLModifier;
/**
* @author Jason
* @version
* @since JDK1.6
*/
public class ExportTbxImpl extends ExportAbstract {
private FileOutputStream output;
public ExportTbxImpl(List<ExportDatabaseBean> dbList, ExportFilterBean filterBean, String encoding) {
super(dbList, filterBean, encoding);
}
/**
* (non-Javadoc)
* @see net.heartsome.cat.document.ExportAbstract#executeExport(org.eclipse.core.runtime.IProgressMonitor)
*/
@Override
public String executeExport(IProgressMonitor monitor) {
if (monitor == null) {
monitor = new NullProgressMonitor();
}
String whereResult = "";
if (this.filterBean != null) {
StringBuffer whereBf = new StringBuffer();
String connector = this.filterBean.getFilterConnector();
List<ExportFilterComponentBean> filterOptions = this.filterBean.getFilterOption();
whereBf.append(" AND ");
for (Iterator<ExportFilterComponentBean> iterator = filterOptions.iterator(); iterator.hasNext();) {
ExportFilterComponentBean filterBean = iterator.next();
whereBf.append("PURE ");
whereBf.append("LIKE ");
whereBf.append("'%" + filterBean.getFilterVlaue() + "%' ");
whereBf.append(connector + " ");
}
whereResult = whereBf.toString();
whereResult = whereResult.substring(0, whereResult.lastIndexOf(connector));
}
monitor.beginTask("", dbList.size());
for (Iterator<ExportDatabaseBean> iterator = dbList.iterator(); iterator.hasNext();) {
ExportDatabaseBean db = iterator.next();
String srcLang = db.getSrcLang();
List<String> needLang = db.getHasSelectedLangs();
DBOperator dbOp = DatabaseService.getDBOperator(db.getDbBean());
try {
dbOp.start();
output = new FileOutputStream(db.getExportFilePath());
writeHeader(srcLang);
writeString("<text>\n<body>\n");
List<Integer> tPkId = dbOp.getAfterFilterTermEntryPK(whereResult, needLang);
// Fix Bug #2361 TBX文件导出问题--语言不能正确过滤导出 by Jason
tPkId = dbOp.validateTermEntryPk(tPkId, needLang, srcLang);
IProgressMonitor subMonitor = new SubProgressMonitor(monitor, 1);
subMonitor.beginTask(Messages.getString("document.ExportTbxImpl.task1") + db.getDbBean().getDatabaseName(), tPkId.size());
subMonitor.setTaskName(Messages.getString("document.ExportTbxImpl.task1") + db.getDbBean().getDatabaseName());
for (int i = 0; i < tPkId.size(); i++) {
// long l = System.currentTimeMillis();
if (monitor.isCanceled()) {
clearResource();
return USER_CANCEL;
}
int termEntryPK = tPkId.get(i);
String termEntry = dbOp.retrieveTermEntry(termEntryPK);
if (termEntry != null && !termEntry.equals("")) {
writeString(termEntry);
}
subMonitor.worked(1);
}
writeString("</body>\n</text>\n</martif>\n");
} catch (SQLException e) {
logger.error(DBOP_ERROR, e);
e.printStackTrace();
clearResource();
return DBOP_ERROR + db.getDbBean().getDbType() + " " + db.getDbBean().getDatabaseName();
} catch (ClassNotFoundException e) {
logger.error(JDBC_ERROR, e);
e.printStackTrace();
clearResource();
return JDBC_ERROR + db.getDbBean().getDbType();
} catch (IOException e) {
logger.error(FILE_ERROR, e);
e.printStackTrace();
clearResource();
return FILE_ERROR + db.getDbBean().getDbType() + " " + db.getDbBean().getDatabaseName();
} finally {
try {
output.close();
if (dbOp != null) {
dbOp.end();
}
} catch (SQLException e) {
logger.error(RELEASE_DB_ERROR, e);
} catch (IOException e) {
logger.error(RELEASE_FILE_ERROR, e);
}
}
filterLangSet(db.getExportFilePath(),srcLang, needLang);
}
monitor.done();
return SUCCESS;
}
/**
* 过滤从库中导出的langSet节点<br>
* 在库中TremEntry是以整个节点进行存储的,因此,在导出后也是整个节点导出,所以会将无关的语言也导出来。<br>
* 在导出后,生成的TBX文件中进语言进行过滤
* @param filePath
* 导出后生成的TBX文件路径
* @param srcLang
* 源语言
* @param needLang
* 当前需要导出的语言;
*/
private void filterLangSet(String filePath, String srcLang, List<String> needLang) {
try {
VTDGen vg = new VTDGen();
if (vg.parseFile(filePath, true)) {
VTDUtils vu = new VTDUtils(vg.getNav());
StringBuffer xpath = new StringBuffer("/martif/text/body/termEntry/langSet[");
String noteXpathtemp = "starts-with(@id,'__LANG__,') or ends-with(@id,',__LANG__')";
StringBuffer noteTgtXpath = new StringBuffer();
for (String lang : needLang) {
xpath.append("not(@xml:lang='" + lang + "') and ");
if(!lang.equals(srcLang)){
noteTgtXpath.append(noteXpathtemp.replace("__LANG__", lang)).append(" or ");
}
}
String tgtLangXpath = noteTgtXpath.substring(0, noteTgtXpath.lastIndexOf("or"));
StringBuffer noteXpath = new StringBuffer();
noteXpath.append("/martif/text/body/termEntry/note[");
noteXpath.append("not(");
noteXpath.append("(").append(noteXpathtemp.replace("__LANG__", srcLang)).append(")");
noteXpath.append(" and ");
noteXpath.append("(").append(tgtLangXpath).append(")");
noteXpath.append(")");
noteXpath.append("]");
String xpathStr = xpath.substring(0, xpath.lastIndexOf("and")) + "]";
XMLModifier xm = new XMLModifier(vu.getVTDNav());
AutoPilot ap = new AutoPilot(vu.getVTDNav());
ap.declareXPathNameSpace("xml", VTDUtils.XML_NAMESPACE_URL);
xm = vu.delete(ap, xm, xpathStr, VTDUtils.PILOT_TO_END);
xm = vu.delete(ap, xm, noteXpath.toString(), VTDUtils.PILOT_TO_END);
FileOutputStream fos = new FileOutputStream(filePath);
BufferedOutputStream bos = new BufferedOutputStream(fos);
xm.output(bos); // 写入文件
bos.close();
fos.close();
}
} catch (NavException e) {
logger.error("", e);
e.printStackTrace();
} catch (ModifyException e) {
logger.error("", e);
e.printStackTrace();
} catch (FileNotFoundException e) {
logger.error("", e);
e.printStackTrace();
} catch (TranscodeException e) {
logger.error("", e);
e.printStackTrace();
} catch (IOException e) {
logger.error("", e);
e.printStackTrace();
}
}
/**
* 将内容写入文件
* @param string
* @throws UnsupportedEncodingException
* @throws IOException
* ;
*/
private void writeString(String string) throws UnsupportedEncodingException, IOException {
output.write(string.getBytes(this.encoding));
}
/**
* 输出Header内容
* @param srcLang
* @throws IOException
* ;
*/
private void writeHeader(String srcLang) throws IOException {
writeString("<?xml version=\"1.0\" encoding=\"" + this.encoding + "\"?>\n");
writeString("<martif type=\"TBX\" xml:lang=\"" + srcLang + "\">\n");
writeString("<martifHeader>\n");
writeString("<fileDesc>Generated by Heartsome Translation Studio TBX Exporter</fileDesc>\n");
writeString("<encodingDesc><p type=\"DCSName\">tbxdefault.xcs</p></encodingDesc>\n");
writeString("</martifHeader>\n");
}
/**
* 清除所有已经生成的文件 ;
*/
private void clearResource() {
for (Iterator<ExportDatabaseBean> tempIt = dbList.iterator(); tempIt.hasNext();) {
ExportDatabaseBean tempDb = tempIt.next();
String path = tempDb.getExportFilePath();
File file = new File(path);
if (file.exists()) {
file.delete();
}
}
}
}
| 9,160 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
ImportTmx.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/database/net.heartsome.cat.database/src/net/heartsome/cat/document/ImportTmx.java | /**
* ImportTmxTemp.java
*
* Version information :
*
* Date:2013-1-28
*
* Copyright notice :
* 本文件及其附带的相关文件包含机密信息,仅限瀚特盛科技有限公司指定的,与本项目有关的内部人员和客户联络人员查阅和使用。
* 如果您不是本保密声明中指定的收件者,请立即销毁本文件,禁止对本文件或根据本文件中的内容采取任何其他行动,
* 包括但不限于:泄露本文件中的信息、以任何方式制作本文件全部或部分内容之副本、将本文件或其相关副本提供给任何其他人。
*/
package net.heartsome.cat.document;
import java.io.File;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import net.heartsome.cat.common.bean.TmxContexts;
import net.heartsome.cat.common.bean.TmxNote;
import net.heartsome.cat.common.bean.TmxProp;
import net.heartsome.cat.common.bean.TmxSegement;
import net.heartsome.cat.common.bean.TmxTU;
import net.heartsome.cat.common.core.exception.ImportException;
import net.heartsome.cat.database.Constants;
import net.heartsome.cat.database.DBOperator;
import net.heartsome.cat.database.Utils;
import net.heartsome.cat.database.resource.Messages;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author Jason
* @version
* @since JDK1.6
*/
public class ImportTmx {
public static final Logger logger = LoggerFactory.getLogger(ImportTmx.class);
/** 导入策略 */
private int importStrategy;
private DBOperator db;
private TmxReader reader;
private List<TmxTU> tmxTuCache;
private final int cacheSize = 200;
private IProgressMonitor monitor;
public ImportTmx(DBOperator db, int importStrategy, IProgressMonitor monitor) {
if (monitor == null) {
this.monitor = new NullProgressMonitor();
} else {
this.monitor = monitor;
}
this.db = db;
this.importStrategy = importStrategy;
tmxTuCache = new ArrayList<TmxTU>(cacheSize);
}
public void importTmxContent(String content) throws ImportException {
try {
reader = new TmxReader(content);
String srcLang = reader.getTmxHeader().getSrclang();
if (srcLang == null || srcLang.equals("*all*") || srcLang.equals("")) {
// 从TMX中读取不到源语言,此时只能执行增加
importStrategy = Constants.IMPORT_MODEL_ALWAYSADD;
}
} catch (TmxReadException e) {
throw new ImportException(e.getMessage());
}
doImport();
}
public void importTmxFile(File tmxFile) throws ImportException {
try {
reader = new TmxReader(tmxFile);
reader.tryToClearTags(true);
String srcLang = reader.getTmxHeader().getSrclang();
if (srcLang == null || srcLang.equals("*all*") || srcLang.equals("")) {
// 从TMX中读取不到源语言,此时只能执行增加
importStrategy = Constants.IMPORT_MODEL_ALWAYSADD;
}
} catch (TmxReadException e) {
throw new ImportException(e.getMessage());
}
doImport();
}
private void doImport() throws ImportException {
int totalTu = reader.getTotalTu();
if (totalTu == 0) {
throw new ImportException(Messages.getString("document.TmxReader.readTuMsg"));
}
String monitorMsg = Messages.getString("document.ImportTmx.task1");
monitor.beginTask(monitorMsg, totalTu * 2);
TmxReaderEvent event = null;
while ((event = reader.read()) != null) {
if (event.getState() == TmxReaderEvent.END_FILE) {
// end file
break;
} else if (event.getState() == TmxReaderEvent.ERROR_TU) {
// error TU
continue;
} else if (event.getState() == TmxReaderEvent.READ_EXCEPTION) {
// read TU throw a exception
continue;
} else if (event.getState() == TmxReaderEvent.NORMAL_READ) {
if (monitor != null && monitor.isCanceled()) {
monitor.setTaskName(Messages.getString("document.ImportTmx.msg1"));
throw new ImportException(Messages.getString("document.ImportTmx.canceledImport"));
}
// normal TU returned
if (cacheSize == tmxTuCache.size()) {
try {
flush();
} catch (SQLException e) {
throw new ImportException(Messages.getString("document.ImportTmx.dbOpError") + e.getMessage());
}
}
tmxTuCache.add(event.getTu());
monitor.worked(1);
if (monitor != null && monitor.isCanceled()) {
monitor.setTaskName(Messages.getString("document.ImportTmx.msg1"));
throw new ImportException(Messages.getString("document.ImportTmx.canceledImport"));
}
}
}
if (monitor != null && monitor.isCanceled()) {
monitor.setTaskName(Messages.getString("document.ImportTmx.msg1"));
throw new ImportException(Messages.getString("document.ImportTmx.canceledImport"));
}
try {
flush();
} catch (SQLException e) {
throw new ImportException(Messages.getString("document.ImportTmx.dbOpError") + e.getMessage());
}
monitor.done();
}
private void flush() throws SQLException {
if (importStrategy == Constants.IMPORT_MODEL_ALWAYSADD) { // 始终增加
// transaction control
// long l = System.currentTimeMillis();
db.beginTransaction();
try {
for (TmxTU tu : tmxTuCache) {
addTu(tu);
monitor.worked(1);
if (monitor != null && monitor.isCanceled()) {
break;
}
}
} catch (SQLException e) {
db.rollBack();
throw e;
}
db.commit();
tmxTuCache.clear();
// System.out.println((System.currentTimeMillis() - l));
} else if (importStrategy == Constants.IMPORT_MODEL_OVERWRITE) {
Map<TmxTU, List<TmxTU>> duplicateTuCache = new HashMap<TmxTU, List<TmxTU>>();
// Map<TmxTU, List<TmxSegement>> duplicateTuvPkCache = new HashMap<TmxTU, List<TmxSegement>>();
// long l2 = System.currentTimeMillis();
List<TmxTU> filterSrcSameTu = filterSrcSameTu(tmxTuCache,Constants.IMPORT_MODEL_OVERWRITE);
for (TmxTU tu : filterSrcSameTu) {
if (monitor != null && monitor.isCanceled()) {
return;
}
// long l1 = System.currentTimeMillis();
List<TmxTU> dbTus = checkDuplicate(tu);
if (dbTus == null) { // error TU
continue;
}
// cached the DB exist TU
duplicateTuCache.put(tu, dbTus);
if (dbTus.size() != 0) {
// long l = System.currentTimeMillis();
for (TmxTU dbTu : dbTus) {
List<TmxSegement> tuvs = tu.getSegments();
List<TmxSegement> dbTuvs = new ArrayList<TmxSegement>();
for (TmxSegement tuv : tuvs) {
dbTuvs.addAll(db.getTextDataIdByGroupIdLang(dbTu.getTmId(), "M", tuv.getLangCode()));
}
dbTu.setSegments(dbTuvs);
List<TmxProp> dbProps = db.getTuMprops(dbTu.getTmId(), "TU");
dbTu.setProps(dbProps);
List<TmxNote> dbNotes = db.getTuMNote(dbTu.getTmId(), "TU");
dbTu.setNotes(dbNotes);
// duplicateTuvPkCache.put(dbTu, dbTuvs);
}
// System.out.println("getTextDataidByGroup:"+ (System.currentTimeMillis() - l));
}
// System.out.println("tu check with db:"+ (System.currentTimeMillis() - l1));
}
// System.out.println("200 tu check with db:"+ (System.currentTimeMillis() - l2));
tmxTuCache.clear();
filterSrcSameTu.clear();
// Transaction control
db.beginTransaction();
try {
Iterator<TmxTU> tuIt = duplicateTuCache.keySet().iterator();
while (tuIt.hasNext()) {
if (monitor != null && monitor.isCanceled()) {
break;
}
TmxTU tu = tuIt.next();
List<TmxTU> dbTus = duplicateTuCache.get(tu);
if (dbTus.size() == 0) {
addTu(tu);
} else {
for (TmxTU dbTu : dbTus) {
String changeDate = tu.getChangeDate() == null ? "" : tu.getChangeDate();
String changeId = tu.getChangeUser() == null ? "" : tu.getChangeUser();
String dbChangeDate = dbTu.getChangeDate() == null ? "" : dbTu.getChangeDate();
String dbChangeId = dbTu.getChangeUser() == null ? "" : dbTu.getChangeUser();
// Update TU Attribute (XmlElement Attribute)
if (!changeDate.equals(dbChangeDate) || !changeId.equals(dbChangeId)) {
db.updateTuChangeInfo(dbTu.getTmId(), tu.getTuId(), changeId, changeDate);
}
// Update Prop
List<TmxProp> props = tu.getProps();
List<TmxProp> dbProps = dbTu.getProps();
if (dbProps.size() == 0 && props != null) {
for (TmxProp _prop : props) {
db.insertTMXProp(dbTu.getTmId(), "TU", _prop.getName(), null, null,
_prop.getValue());
}
} else if (props != null) {
for (TmxProp prop : props) {
boolean exist = false;
for (TmxProp dbProp : dbProps) {
if (prop.equals(dbProp)) {
exist = true;
break;
}
}
if (!exist) {
db.deleteMprop("TU", dbTu.getTmId() + "");
for (TmxProp _prop : props) {
db.insertTMXProp(dbTu.getTmId(), "TU", _prop.getName(), null, null,
_prop.getValue());
}
break;
}
}
}
// Update Note
List<TmxNote> notes = tu.getNotes();
List<TmxNote> dbNotes = dbTu.getNotes();
if (dbNotes.size() == 0 && notes != null) {
for (TmxNote note : notes) {
db.insertTMXNote(dbTu.getTmId(), "TU", note.getContent(), null, null, null, null,
note.getEncoding(), note.getXmlLang());
}
} else if (notes != null) {
for (TmxNote note : notes) {
boolean exist = false;
for (TmxNote dbNote : dbNotes) {
if (note.equals(dbNote)) {
exist = true;
break;
}
}
if (!exist) {
db.deleteMNote("TU", dbTu.getTmId() + "");
for (TmxNote _note : notes) {
db.insertTMXNote(dbTu.getTmId(), "TU", _note.getContent(), null, null,
null, null, _note.getEncoding(), _note.getXmlLang());
}
break;
}
}
}
// Update TUVS except source TUV
List<TmxSegement> tuvs = tu.getSegments();
if (tuvs != null) {
for (TmxSegement tuv : tuvs) {
List<TmxSegement> dbTuvs = dbTu.getSegments();
String lang = tuv.getLangCode();
String content = tuv.getFullText();
if (content == null) {
continue;
}
if (dbTuvs.size() != 0) {
boolean flg = false;
boolean isDuplicate = false;
for (TmxSegement dbTuv : dbTuvs) {
if (dbTuv.getLangCode().equalsIgnoreCase(lang)) {
String dbContent = dbTuv.getFullText();
if (!dbContent.equals(content)) {
db.deleteAllTuvRelations(
Arrays.asList(new Integer[] { dbTuv.getDbPk() }), lang);
flg = true;
}
isDuplicate = true;
}
}
if (flg == true || !isDuplicate) {
addTuv(dbTu.getTmId(), tuv, null, null);
}
} else {
addTuv(dbTu.getTmId(), tuv, null, null);
}
}
}
// Update context
TmxContexts dbContexts = dbTu.getContexts();
if (tu.getContexts() != null) {
String preContext = tu.getContexts().getPreContext();
String nextContext = tu.getContexts().getNextContext();
if (dbContexts == null) {
db.updateTuvContext(dbTu.getTmId(), tu.getSource().getLangCode(), preContext,
nextContext);
} else {
String dbPreContext = dbContexts.getPreContext();
String dbNextContext = dbContexts.getNextContext();
if (!dbPreContext.equals(preContext) || !dbNextContext.equals(nextContext)) {
db.updateTuvContext(dbTu.getTmId(), tu.getSource().getLangCode(), preContext,
nextContext);
}
}
}
}
}
monitor.worked(1);
}
} catch (SQLException e) {
db.rollBack();
throw e;
}
db.commit();
duplicateTuCache.clear();
} else if (importStrategy == Constants.IMPORT_MODEL_IGNORE) {
List<TmxTU> needAddTus = new ArrayList<TmxTU>();
List<TmxTU> filterSrcSameTu = filterSrcSameTu(tmxTuCache, Constants.IMPORT_MODEL_IGNORE);
for (TmxTU tu : filterSrcSameTu) {
if (monitor != null && monitor.isCanceled()) {
return;
}
List<TmxTU> dbTus = checkDuplicate(tu);
if (dbTus == null) { // error TU
continue;
}
// cached the DB exist TU
if (dbTus.size() == 0) {
needAddTus.add(tu);
}
}
tmxTuCache.clear();
filterSrcSameTu.clear();
// Transaction control
db.beginTransaction();
try {
for (TmxTU tu : needAddTus) {
if (monitor != null && monitor.isCanceled()) {
break;
}
addTu(tu);
monitor.worked(1);
}
} catch (SQLException e) {
db.rollBack();
throw e;
}
db.commit();
needAddTus.clear();
}
}
private List<TmxTU> checkDuplicate(TmxTU tu) throws SQLException {
TmxSegement srcTuv = tu.getSource();
List<TmxSegement> tuvs = tu.getSegments();
if (srcTuv == null || tuvs == null || tu.getSegments().size() == 0) {
return null;
}
String pureText = srcTuv.getPureText();
if (pureText == null) {
return null;
}
int hash = pureText.hashCode();
String tuId = tu.getTuId();
if (tuId == null || tuId.equals("")) {
tuId = generateTuId();
tu.setTuId(tuId);
}
// long l = System.currentTimeMillis();
List<TmxTU> dbTus = db.getTUInfoByTuvInfo(hash, Utils.convertLangCode(srcTuv.getLangCode()), tuId);
// System.out.println("checkDuplicate tu: "+ (System.currentTimeMillis() - l));
return dbTus;
}
private boolean addTu(TmxTU tu) throws SQLException {
TmxSegement srcTuv = tu.getSource();
List<TmxSegement> tuvs = tu.getSegments();
if ((srcTuv == null && tuvs == null) || (srcTuv == null && tuvs.size() < 2)) {
// check TU
return false;
}
String tuId = tu.getTuId();
if (tuId == null || tuId.equals("")) {
tuId = generateTuId();
}
int tuPk = db.insertTU(0, tuId, tu.getCreationUser(), tu.getCreationDate(), tu.getChangeUser(),
tu.getChangeDate(), tu.getCreationTool(), tu.getCreationToolVersion(), null, null, null);
List<TmxNote> notes = tu.getNotes();
if (notes != null && notes.size() != 0) {
for (TmxNote note : notes) {
db.insertTMXNote(tuPk, "TU", note.getContent(), null, null, null, null, note.getEncoding(),
note.getXmlLang());
}
}
List<TmxProp> props = tu.getProps();
if (props != null && props.size() != 0) {
for (TmxProp prop : props) {
db.insertTMXProp(tuPk, "TU", prop.getName(), null, null, prop.getValue());
}
}
String preContext = null;
String nextContext = null;
if (tu.getContexts() != null) {
preContext = tu.getContexts().getPreContext();
nextContext = tu.getContexts().getNextContext();
}
if (srcTuv != null) {
addTuv(tuPk, srcTuv, preContext, nextContext);
preContext = null;
nextContext = null;
}
if (tuvs != null) {
for (TmxSegement tuv : tuvs) {
addTuv(tuPk, tuv, preContext, nextContext);
}
}
return true;
}
private void addTuv(int tuPk, TmxSegement tuv, String preContext, String nextContext) throws SQLException {
String pureText = tuv.getPureText();
String hash = pureText == null ? null : pureText.hashCode() + "";
try {
db.insertTextData("M", tuPk, hash, pureText, tuv.getFullText(), Utils.convertLangCode(tuv.getLangCode()),
preContext == null ? "" : preContext, nextContext == null ? "" : nextContext);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 按“时间戳与随机五位数”规则生成TUID
* @return ;
*/
private String generateTuId() {
return System.currentTimeMillis() + Utils.validateCode(5);
}
/**
* @param cache
* @param importStrategy
* @return ;
*/
private List<TmxTU> filterSrcSameTu(List<TmxTU> cache, int importStrategy) {
if (null == cache || cache.isEmpty()) {
return cache;
}
Map<String, List<TmxTU>> map = new HashMap<String, List<TmxTU>>();
String srcText = "";
for (TmxTU tu : cache) {
srcText = tu.getSource().getPureText();
if (map.get(srcText) != null) {
map.get(srcText).add(tu);
} else {
List<TmxTU> temp = new ArrayList<TmxTU>();
map.put(srcText, temp);
temp.add(tu);
}
}
List<TmxTU> rs = new ArrayList<TmxTU>();
Iterator<List<TmxTU>> iterator = map.values().iterator();
while (iterator.hasNext()) {
List<TmxTU> next = iterator.next();
if(importStrategy == Constants.IMPORT_MODEL_IGNORE){
rs.add(next.get(0));
}else{
rs.add(next.get(next.size()-1));
}
}
return rs;
}
}
| 16,586 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
TmxFilterInterface.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/database/net.heartsome.cat.database/src/net/heartsome/cat/document/TmxFilterInterface.java | /**
* TmxFilter.java
*
* Version information :
*
* Date:2013-5-17
*
* Copyright notice :
* 本文件及其附带的相关文件包含机密信息,仅限瀚特盛科技有限公司指定的,与本项目有关的内部人员和客户联络人员查阅和使用。
* 如果您不是本保密声明中指定的收件者,请立即销毁本文件,禁止对本文件或根据本文件中的内容采取任何其他行动,
* 包括但不限于:泄露本文件中的信息、以任何方式制作本文件全部或部分内容之副本、将本文件或其相关副本提供给任何其他人。
*/
package net.heartsome.cat.document;
/**
* @author Administrator
* @version
* @since JDK1.6
*/
public interface TmxFilterInterface {
public String SDL_2007_FOR_WIN = "TRADOS Translator's Workbench for Windows";
public String SDL_2007_VERSION = "Edition 8 Build 863";
public String clearString(String content);
}
| 965 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
ExportTmxImpl.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/database/net.heartsome.cat.database/src/net/heartsome/cat/document/ExportTmxImpl.java | /**
* ExportTmxImpl.java
*
* Version information :
*
* Date:Feb 20, 2012
*
* Copyright notice :
* 本文件及其附带的相关文件包含机密信息,仅限瀚特盛科技有限公司指定的,与本项目有关的内部人员和客户联络人员查阅和使用。
* 如果您不是本保密声明中指定的收件者,请立即销毁本文件,禁止对本文件或根据本文件中的内容采取任何其他行动,
* 包括但不限于:泄露本文件中的信息、以任何方式制作本文件全部或部分内容之副本、将本文件或其相关副本提供给任何其他人。
*/
package net.heartsome.cat.document;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.sql.SQLException;
import java.util.Calendar;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import net.heartsome.cat.database.DBOperator;
import net.heartsome.cat.database.bean.ExportDatabaseBean;
import net.heartsome.cat.database.bean.ExportFilterBean;
import net.heartsome.cat.database.resource.Messages;
import net.heartsome.cat.database.service.DatabaseService;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.SubProgressMonitor;
/**
* @author Jason
* @version
* @since JDK1.6
*/
public class ExportTmxImpl extends ExportAbstract {
private boolean isToplevelTmx; // 一级TMX
private boolean isTagLevelTmx; // 带标记的TMX
private FileOutputStream output;
/**
* 构造函数
* @param dbList
* 数据库列表 {@link ExportDatabaseBean}
* @param filterBean
* 过滤条件 {@link ExportFilterBean}
* @param encoding
* 编辑规则
* @param exportPath
* 导出的文件路径,一个库的情况下为文件,多个库的情况下为文件夹
* @param isToplevelTmx
* 是否为一级TMX
* @param isTagLevelTmx
* 是否是带标记的TMX
*/
public ExportTmxImpl(List<ExportDatabaseBean> dbList, ExportFilterBean filterBean, String encoding,
boolean isToplevelTmx, boolean isTagLevelTmx) {
super(dbList, filterBean, encoding);
this.isToplevelTmx = isToplevelTmx;
this.isTagLevelTmx = isTagLevelTmx;
}
/**
* (non-Javadoc)
* @see net.heartsome.cat.document.ExportAbstract#executeExport()
*/
@Override
public String executeExport(IProgressMonitor monitor) {
String mTuFilter = "";
String textDataFilter = "";
String mNoteFilter = "";
if (monitor == null) {
monitor = new NullProgressMonitor();
}
monitor.beginTask("", dbList.size());
for (Iterator<ExportDatabaseBean> iterator = dbList.iterator(); iterator.hasNext();) {
ExportDatabaseBean db = iterator.next();
String srcLang = db.getSrcLang();
DBOperator dbOp = DatabaseService.getDBOperator(db.getDbBean());
// 过滤条件
if (this.filterBean != null) {
mTuFilter = dbOp.generationExportTMXFilter("MTU", this.filterBean);
textDataFilter = dbOp.generationExportTMXFilter("TEXTDATA", this.filterBean);
mNoteFilter = dbOp.generationExportTMXFilter("MNOTE", this.filterBean);
}
try {
dbOp.start();
output = new FileOutputStream(db.getExportFilePath());
if (encoding.equalsIgnoreCase("UTF-16LE")) {
output.write(0xFF);
output.write(0xFE);
} else if (encoding.equalsIgnoreCase("UTF-16BE")) {
output.write(0xFE);
output.write(0xFF);
}
List<Integer> filterTu = dbOp.getAfterFilterTuPk(mTuFilter, mNoteFilter, textDataFilter);
writeHeader(srcLang);
writeString("<body>\n");
IProgressMonitor subMonitor = new SubProgressMonitor(monitor, 1);
subMonitor.beginTask(Messages.getString("document.ExportTmxImpl.task1")
+ db.getDbBean().getDatabaseName(), filterTu.size());
subMonitor.setTaskName(Messages.getString("document.ExportTmxImpl.task1")
+ db.getDbBean().getDatabaseName());
for (int i = 0; i < filterTu.size(); i++) {
// long l = System.currentTimeMillis();
if (monitor.isCanceled()) {
clearResource();
break;
}
int tuPk = filterTu.get(i);
String tuNodeContent = dbOp
.retrieveTu(tuPk, db.getHasSelectedLangs(), isToplevelTmx, isTagLevelTmx);
if (tuNodeContent != null && !tuNodeContent.equals("")) {
writeString(tuNodeContent);
}
subMonitor.worked(1);
}
writeString("</body>\n"); //$NON-NLS-1$
writeString("</tmx>\n"); //$NON-NLS-1$
subMonitor.done();
} catch (SQLException e) {
logger.error(DBOP_ERROR, e);
e.printStackTrace();
clearResource();
return DBOP_ERROR + db.getDbBean().getDbType() + " " + db.getDbBean().getDatabaseName();
} catch (ClassNotFoundException e) {
logger.error(JDBC_ERROR, e);
e.printStackTrace();
clearResource();
return JDBC_ERROR + db.getDbBean().getDbType();
} catch (IOException e) {
logger.error(FILE_ERROR, e);
e.printStackTrace();
clearResource();
return FILE_ERROR + db.getDbBean().getDbType() + " " + db.getDbBean().getDatabaseName();
} finally {
try {
output.close();
if (dbOp != null) {
dbOp.end();
}
} catch (SQLException e) {
logger.error(RELEASE_DB_ERROR, e);
} catch (IOException e) {
logger.error(RELEASE_FILE_ERROR, e);
}
}
}
if (monitor.isCanceled()) {
return USER_CANCEL;
}
monitor.done();
return SUCCESS;
}
/**
* 清除所有已经生成的文件 ;
*/
private void clearResource() {
for (Iterator<ExportDatabaseBean> tempIt = dbList.iterator(); tempIt.hasNext();) {
ExportDatabaseBean tempDb = tempIt.next();
String path = tempDb.getExportFilePath();
File file = new File(path);
if (file.exists()) {
file.delete();
}
}
}
/**
* 输出Header内容
* @param srcLang
* @throws IOException
* ;
*/
private void writeHeader(String srcLang) throws IOException {
writeString("<?xml version=\"1.0\" encoding=\"" + this.encoding + "\"?>\n");
writeString("<!DOCTYPE tmx PUBLIC \"-//LISA OSCAR:1998//DTD for Translation Memory eXchange//EN\" \"tmx14.dtd\" >\n");
writeString("<tmx version=\"1.4\">\n");
writeString("<header \n" + " creationtool=\"Heartsome TM Server\" \n"
+ " creationtoolversion=\"2.0-1\" \n" + " srclang=\"" + srcLang + "\" \n"
+ " adminlang=\"en\" \n" + " datatype=\"xml\" \n" + " o-tmf=\"unknown\" \n"
+ " segtype=\"block\" \n" + " creationdate=\"" + creationDate() + "\"\n>\n" + "</header>\n");
}
/**
* 将内容写入文件
* @param string
* @throws UnsupportedEncodingException
* @throws IOException
* ;
*/
private void writeString(String string) throws UnsupportedEncodingException, IOException {
output.write(string.getBytes(this.encoding));
}
/**
* 获取创建时间
* @return ;
*/
public String creationDate() {
Calendar calendar = Calendar.getInstance(Locale.US);
String sec = (calendar.get(Calendar.SECOND) < 10 ? "0" : "") //$NON-NLS-1$ //$NON-NLS-2$
+ calendar.get(Calendar.SECOND);
String min = (calendar.get(Calendar.MINUTE) < 10 ? "0" : "") //$NON-NLS-1$ //$NON-NLS-2$
+ calendar.get(Calendar.MINUTE);
String hour = (calendar.get(Calendar.HOUR_OF_DAY) < 10 ? "0" : "") //$NON-NLS-1$ //$NON-NLS-2$
+ calendar.get(Calendar.HOUR_OF_DAY);
String mday = (calendar.get(Calendar.DATE) < 10 ? "0" : "") //$NON-NLS-1$ //$NON-NLS-2$
+ calendar.get(Calendar.DATE);
String mon = (calendar.get(Calendar.MONTH) < 9 ? "0" : "") //$NON-NLS-1$ //$NON-NLS-2$
+ (calendar.get(Calendar.MONTH) + 1);
String longyear = "" + calendar.get(Calendar.YEAR); //$NON-NLS-1$
String date = longyear + mon + mday + "T" + hour + min + sec + "Z"; //$NON-NLS-1$ //$NON-NLS-2$
return date;
}
}
| 7,853 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
DocUtils.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/database/net.heartsome.cat.database/src/net/heartsome/cat/document/DocUtils.java | package net.heartsome.cat.document;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import net.heartsome.cat.database.resource.Messages;
import net.heartsome.xml.vtdimpl.VTDUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.ximpleware.AutoPilot;
import com.ximpleware.EOFException;
import com.ximpleware.EncodingException;
import com.ximpleware.EntityException;
import com.ximpleware.NavException;
import com.ximpleware.ParseException;
import com.ximpleware.VTDGen;
import com.ximpleware.VTDNav;
import com.ximpleware.XPathEvalException;
import com.ximpleware.XPathParseException;
/**
* 文档工具类
* @author terry
* @version
* @since JDK1.6
*/
public class DocUtils {
private static final Logger LOGGER = LoggerFactory.getLogger(DocUtils.class);
/**
* 构造函数
*/
protected DocUtils() {
throw new UnsupportedOperationException();
}
/**
* 判断是否是正确的 TBX 文件
* @param fileName
* TBX 文件的全路径
* @return 反回null,验证失败
* @throws ParseException
* @throws EntityException
* @throws EOFException
* @throws EncodingException
* @throws FileNotFoundException
*/
public static VTDUtils isTBX(String fileName) throws EncodingException, ParseException, FileNotFoundException {
VTDGen vg = new VTDGen();
FileInputStream fis = null;
File f = null;
try {
f = new File(fileName);
fis = new FileInputStream(f);
byte[] b = new byte[(int) f.length()];
int offset = 0;
int numRead = 0;
int numOfBytes = 1048576;// I choose this value randomally,
// any other (not too big) value also can be here.
if (b.length - offset < numOfBytes) {
numOfBytes = b.length - offset;
}
while (offset < b.length && (numRead = fis.read(b, offset, numOfBytes)) >= 0) {
offset += numRead;
if (b.length - offset < numOfBytes) {
numOfBytes = b.length - offset;
}
}
vg.setDoc(b);
vg.parse(true);
} catch (IOException e) {
LOGGER.error(Messages.getString("document.DocUtils.logger1"), e);
} finally {
if (fis != null) {
try {
fis.close();
} catch (Exception e) {
}
}
}
VTDNav vn = vg.getNav();
AutoPilot ap = new AutoPilot(vn);
String rootPath = "/martif";
VTDUtils vtdUtils = new VTDUtils();
try {
vtdUtils.bind(vn);
ap.selectXPath(rootPath);
if (ap.evalXPath() == -1) {
// Map<String, String> map = vtdUtils.getCurrentElementAttributs();
// if (!"TBX".equalsIgnoreCase(map.get("type"))) {
// return null;
// }
// } else {
return null;
}
} catch (NavException e) {
LOGGER.error(Messages.getString("document.DocUtils.logger2"), e);
return null;
} catch (XPathEvalException e) {
LOGGER.error(Messages.getString("document.DocUtils.logger2"), e);
return null;
} catch (XPathParseException e) {
LOGGER.error(Messages.getString("document.DocUtils.logger2"), e);
return null;
} finally {
vg.clear();
}
return vtdUtils;
}
/**
* 判断是否是正确的 TMX 文件
* @param fileName
* @return ;
* @throws FileNotFoundException
* @throws ParseException
* @throws EntityException
* @throws EOFException
* @throws EncodingException
*/
public static VTDUtils isTMX(String fileName) throws FileNotFoundException, EncodingException, ParseException {
VTDGen vg = new VTDGen();
FileInputStream fis = null;
File f = null;
try {
f = new File(fileName);
fis = new FileInputStream(f);
byte[] b = new byte[(int) f.length()];
int offset = 0;
int numRead = 0;
int numOfBytes = 1048576;// I choose this value randomally,
// any other (not too big) value also can be here.
if (b.length - offset < numOfBytes) {
numOfBytes = b.length - offset;
}
while (offset < b.length && (numRead = fis.read(b, offset, numOfBytes)) >= 0) {
offset += numRead;
if (b.length - offset < numOfBytes) {
numOfBytes = b.length - offset;
}
}
vg.setDoc(b);
vg.parse(true);
} catch (IOException e) {
LOGGER.error(Messages.getString("document.DocUtils.logger1"), e);
} finally {
if (fis != null) {
try {
fis.close();
} catch (Exception e) {
}
}
}
VTDNav vn = vg.getNav();
AutoPilot ap = new AutoPilot(vn);
String rootPath = "/tmx";
VTDUtils vu = new VTDUtils();
try {
vu.bind(vn);
ap.selectXPath(rootPath);
if (ap.evalXPath() == -1) {
return null;
}
} catch (NavException e) {
LOGGER.error(Messages.getString("document.DocUtils.logger2"), e);
return null;
} catch (XPathEvalException e) {
LOGGER.error(Messages.getString("document.DocUtils.logger2"), e);
return null;
} catch (XPathParseException e) {
LOGGER.error(Messages.getString("document.DocUtils.logger2"), e);
return null;
} finally {
vg.clear();
}
return vu;
}
/**
* 取得在 TMX 规范中,哪些属性是日期类型的
* @return ;
*/
public static List<String> getTMDateProp() {
List<String> result = new ArrayList<String>();
result.add("lastusagedate");
result.add("creationdate");
result.add("changedate");
return result;
}
public static String getTmxTbxPureText(VTDUtils vu) throws NavException, XPathParseException, XPathEvalException {
StringBuilder sb = new StringBuilder();
VTDNav vn = vu.getVTDNav();
try {
vn.push();
sb.append(vu.getElementContent());
AutoPilot ap = new AutoPilot(vn);
// 有子节点,即有内部标记
if (vu.getChildElementsCount() < 1) {
return sb.toString();
}
ap.resetXPath();
ap.selectXPath("./*");
while (ap.evalXPath() != -1) {
String childNodeName = vu.getCurrentElementName();
if ("g".equals(childNodeName) || "sub".equals(childNodeName) || "hi".equals(childNodeName)
|| "mrk".equals(childNodeName) || "foreign".equals(childNodeName)) {
if (vu.getChildElementsCount() < 1) {
String childFrag = vu.getElementFragment();
String childContent = vu.getElementContent();
childContent = childContent == null ? "" : childContent;
int start = sb.indexOf(childFrag);
sb.replace(start, start + childFrag.length(), childContent);
} else {
String childFrag = vu.getElementFragment();
String childContent = getTmxTbxPureText(vu);
childContent = childContent == null ? "" : childContent;
int start = sb.indexOf(childFrag);
sb.replace(start, start + childFrag.length(), childContent);
}
} else {
// ph节点的值为code data或者一个sub节点,因此,要考虑到sub节点的情况
if (vu.getChildElementsCount() < 1) {
String childFrag = vu.getElementFragment();
int start = sb.indexOf(childFrag);
sb.replace(start, start + childFrag.length(), "");
} else {
String childFrag = vu.getElementFragment();
String childContent = "";
AutoPilot _ap = new AutoPilot(vn);
_ap.selectXPath("./*");
while (_ap.evalXPath() != -1) {
if (vu.getChildElementsCount() <= 0) {
childContent += vu.getElementContent();
} else {
childContent += getTmxTbxPureText(vu);
}
}
childContent = childContent == null ? "" : childContent;
int start = sb.indexOf(childFrag);
sb.replace(start, start + childFrag.length(), childContent);
}
}
}
} finally {
vn.pop();
}
return sb.toString();
}
}
| 7,469 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
ImportAbstract.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/database/net.heartsome.cat.database/src/net/heartsome/cat/document/ImportAbstract.java | /**
* AbstractImport.java
*
* Version information :
*
* Date:Nov 7, 2011
*
* Copyright notice :
* 本文件及其附带的相关文件包含机密信息,仅限瀚特盛科技有限公司指定的,与本项目有关的内部人员和客户联络人员查阅和使用。
* 如果您不是本保密声明中指定的收件者,请立即销毁本文件,禁止对本文件或根据本文件中的内容采取任何其他行动,
* 包括但不限于:泄露本文件中的信息、以任何方式制作本文件全部或部分内容之副本、将本文件或其相关副本提供给任何其他人。
*/
package net.heartsome.cat.document;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.SQLException;
import net.heartsome.cat.common.core.exception.ImportException;
import net.heartsome.cat.database.Constants;
import net.heartsome.cat.database.DBOperator;
import net.heartsome.cat.database.Utils;
import net.heartsome.cat.database.resource.Messages;
import net.heartsome.xml.vtdimpl.VTDUtils;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.OperationCanceledException;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.widgets.Display;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.ximpleware.AutoPilot;
import com.ximpleware.EOFException;
import com.ximpleware.EncodingException;
import com.ximpleware.EntityException;
import com.ximpleware.ModifyException;
import com.ximpleware.NavException;
import com.ximpleware.ParseException;
import com.ximpleware.TranscodeException;
import com.ximpleware.VTDException;
import com.ximpleware.VTDGen;
import com.ximpleware.XPathEvalException;
import com.ximpleware.XPathParseException;
/**
* 此类及其实现类仅限于 TBX,原来的 TMX 导入已经完全独立出去。和这个不在有任何关系。
* @author Jason
* @version
* @since JDK1.6
*/
public abstract class ImportAbstract {
/** XML解析封装 */
protected VTDUtils vu;
/** 文件类型 */
protected String fileType;
/** 导入策略 */
protected int importStrategy;
/** 数据库操作对象 */
protected DBOperator dbOperator;
private Logger logger = LoggerFactory.getLogger(this.getClass());
protected IProgressMonitor monitor;
/***
* 将已解析XML文件导入到库中
* @param srcLang
* TMX源语言
* @param vtdUtils
* 封装的VTD解析工具
* @throws SQLException
* @throws NavException
* @throws XPathParseException
* @throws XPathEvalException
* ;
* @throws ParseException
* @throws EntityException
* @throws EOFException
* @throws EncodingException
* @throws IOException
* @throws ModifyException
* @throws TranscodeException
*/
protected abstract void executeImport(String srcLang) throws SQLException, NavException, XPathParseException,
XPathEvalException, EncodingException, EOFException, EntityException, ParseException, TranscodeException,
ModifyException, IOException, ImportException;
/**
* 将TMX文件导入数据库中,在执行导入前对文件处理以及对需要使用的资源进行初始化
* @param fileName
* TMX文件路径
* @param monitor
* 进度条
* @return ;
* @throws ImportException
*/
public int doImport(String fileName, IProgressMonitor monitor) throws ImportException {
this.monitor = monitor;
// 文件检查
String message = "";
try {
if (Constants.TBX.equals(fileType)) {
if ((vu = DocUtils.isTBX(fileName)) == null) {
return FAILURE_1;
}
} else {
if ((vu = DocUtils.isTMX(fileName)) == null) {
return FAILURE_1;
}
// 解析 header 接点
AutoPilot ap = new AutoPilot(vu.getVTDNav());
try {
ap.selectXPath("/tmx/header");
if (ap.evalXPath() != -1) {
int id = vu.getVTDNav().getAttrVal("srclang");
if (id != -1 && "*all*".equalsIgnoreCase(vu.getVTDNav().toString(id).trim())) {
final boolean[] flag = new boolean[1];
Display.getDefault().syncExec(new Runnable() {
public void run() {
flag[0] = MessageDialog.openConfirm(Display.getDefault().getActiveShell(),
Messages.getString("document.ImportTmx.title"),
Messages.getString("document.ImportTmx.msg2"));
}
});
if (!flag[0]) {
return CANCEL;
}
}
}
} catch (VTDException e) {
logger.error("", e);
}
}
} catch (EncodingException e) {
logger.error(Messages.getString("document.ImportAbstract.logger1"), e);
message = Messages.getString("document.ImportAbstract.msg1");
throw new ImportException(message + e.getMessage());
} catch (FileNotFoundException e) {
logger.error(Messages.getString("document.ImportAbstract.logger2"), e);
message = Messages.getString("document.ImportAbstract.msg2");
throw new ImportException(message + e.getMessage());
} catch (ParseException e) {
logger.error(Messages.getString("document.ImportAbstract.logger3"), e);
String errMsg = e.getMessage();
if (errMsg.indexOf("invalid encoding") != -1) {
// 编码异常
message = Messages.getString("document.ImportAbstract.msg1");
} else {
message = Messages.getString("document.ImportAbstract.tbx.msg1");
}
throw new ImportException(message + e.getMessage());
}
try {
dbOperator.beginTransaction();
executeImport(null); // 执行导入
dbOperator.commit();
} catch (VTDException e) {
logger.error("", e);
try {
dbOperator.rollBack();
} catch (SQLException e1) {
logger.error("", e);
}
throw new ImportException(Messages.getString("document.ImportAbstract.tbx.msg1") + e.getMessage());
} catch (SQLException e) {
logger.error("", e);
try {
dbOperator.rollBack();
} catch (SQLException e1) {
logger.error("", e1);
}
throw new ImportException(Messages.getString("document.ImportAbstract.tbx.importDbError") + e.getMessage());
} catch (OperationCanceledException e) {
logger.error("", e);
try {
dbOperator.rollBack();
} catch (SQLException e1) {
logger.error("", e1);
return CANCEL;
}
return CANCEL;
} catch (Exception e) {
logger.error("", e);
try {
dbOperator.rollBack();
} catch (SQLException e1) {
logger.error("", e1);
}
throw new ImportException(Messages.getString("document.ImportAbstract.tbx.importDbError") + e.getMessage());
}
return SUCCESS;
}
/**
* 导入文件内容
* @param fileContent
* @param srcLang
* @param monitor
* @return ;
* @throws ImportException
*/
public int doImport(String fileContent, String srcLang, IProgressMonitor monitor) throws ImportException {
if (monitor == null) {
this.monitor = new NullProgressMonitor();
} else {
this.monitor = monitor;
}
// 解析文件
String message = "";
VTDGen vg = new VTDGen();
vg.setDoc(fileContent.getBytes());
try {
vg.parse(true);
} catch (EncodingException e) {
logger.error(Messages.getString("document.ImportAbstract.logger1"), e);
message = Messages.getString("document.ImportAbstract.msg1");
throw new ImportException(message + e.getMessage());
} catch (EOFException e) {
logger.error("", e);
message = Messages.getString("document.ImportAbstract.tbx.msg1");
throw new ImportException(message + e.getMessage());
} catch (EntityException e) {
logger.error("", e);
message = Messages.getString("document.ImportAbstract.tbx.msg1");
throw new ImportException(message + e.getMessage());
} catch (ParseException e) {
logger.error(Messages.getString("document.ImportAbstract.logger3"), e);
String errMsg = e.getMessage();
if (errMsg.indexOf("invalid encoding") != -1) {
// 编码异常
message = Messages.getString("document.ImportAbstract.msg1");
} else {
message = Messages.getString("document.ImportAbstract.tbx.msg1");
}
throw new ImportException(message + e.getMessage());
}
try {
vu = new VTDUtils(vg.getNav()); // 构建VTD解析工具
dbOperator.beginTransaction();
executeImport(srcLang); // 执行导入
dbOperator.commit();
} catch (VTDException e) {
logger.error("", e);
try {
dbOperator.rollBack();
} catch (SQLException e1) {
logger.error("", e);
}
return FAILURE_4;
} catch (SQLException e) {
logger.error("", e);
try {
dbOperator.rollBack();
} catch (SQLException e1) {
logger.error("", e1);
}
throw new ImportException(Messages.getString("document.ImportAbstract.tbx.importDbError") + e.getMessage());
} catch (OperationCanceledException e) {
logger.error("", e);
try {
dbOperator.rollBack();
} catch (SQLException e1) {
logger.error("", e1);
return CANCEL;
}
} catch (Exception e) {
logger.error("", e);
try {
dbOperator.rollBack();
} catch (SQLException e1) {
logger.error("", e1);
}
throw new ImportException(Messages.getString("document.ImportAbstract.tbx.importDbError") + e.getMessage());
}
return SUCCESS;
}
/**
* 取得语言代码
* @return
* @throws XPathParseException
* @throws XPathEvalException
* @throws NavException
*/
protected String getLang() throws XPathParseException, XPathEvalException, NavException {
String lang = vu.getCurrentElementAttributs().get("xml:lang");
if (lang == null) {
lang = vu.getCurrentElementAttributs().get("lang");
}
return Utils.convertLangCode(lang);
}
/** 成功标志 */
public static final int SUCCESS = 1;
/** 失败标志 */
public static final int FAILURE = 0;
/** 不是正确的 TMX 或 TBX 文件 */
public static final int FAILURE_1 = -1;
/** 解析文件失败 */
public static final int FAILURE_2 = -2;
/** 数据库异常 */
public static final int FAILURE_3 = -3;
/** XPath 错误 */
public static final int FAILURE_4 = -4;
/** 取消标志 */
public static final int CANCEL = 2;
}
| 9,999 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
TmxFilterSDL2007Impl.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/database/net.heartsome.cat.database/src/net/heartsome/cat/document/TmxFilterSDL2007Impl.java | /**
* TmxFilterSDL2007Impl.java
*
* Version information :
*
* Date:2013-5-17
*
* Copyright notice :
* 本文件及其附带的相关文件包含机密信息,仅限瀚特盛科技有限公司指定的,与本项目有关的内部人员和客户联络人员查阅和使用。
* 如果您不是本保密声明中指定的收件者,请立即销毁本文件,禁止对本文件或根据本文件中的内容采取任何其他行动,
* 包括但不限于:泄露本文件中的信息、以任何方式制作本文件全部或部分内容之副本、将本文件或其相关副本提供给任何其他人。
*/
package net.heartsome.cat.document;
/**
* @author Administrator
* @version
* @since JDK1.6
*/
public class TmxFilterSDL2007Impl implements TmxFilterInterface{
public String clearString(String content) {
String result = content.replaceAll("<ut>[\\s\\S]*?</ut>", "").replaceAll("<cf[\\s\\S]*?>", "").replaceAll("</cf>", "");
return result.trim();
}
}
| 1,030 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
TmxReader.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/database/net.heartsome.cat.database/src/net/heartsome/cat/document/TmxReader.java | /**
* TmxFileReader.java
*
* Version information :
*
* Date:2013-1-25
*
* Copyright notice :
* 本文件及其附带的相关文件包含机密信息,仅限瀚特盛科技有限公司指定的,与本项目有关的内部人员和客户联络人员查阅和使用。
* 如果您不是本保密声明中指定的收件者,请立即销毁本文件,禁止对本文件或根据本文件中的内容采取任何其他行动,
* 包括但不限于:泄露本文件中的信息、以任何方式制作本文件全部或部分内容之副本、将本文件或其相关副本提供给任何其他人。
*/
package net.heartsome.cat.document;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import net.heartsome.cat.common.bean.TmxContexts;
import net.heartsome.cat.common.bean.TmxHeader;
import net.heartsome.cat.common.bean.TmxNote;
import net.heartsome.cat.common.bean.TmxProp;
import net.heartsome.cat.common.bean.TmxSegement;
import net.heartsome.cat.common.bean.TmxTU;
import net.heartsome.cat.common.util.FileEncodingDetector;
import net.heartsome.cat.database.Utils;
import net.heartsome.cat.database.resource.Messages;
import net.heartsome.xml.vtdimpl.VTDLoader;
import net.heartsome.xml.vtdimpl.VTDUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.ximpleware.AutoPilot;
import com.ximpleware.EncodingException;
import com.ximpleware.NavException;
import com.ximpleware.ParseException;
import com.ximpleware.VTDException;
import com.ximpleware.VTDGen;
import com.ximpleware.VTDNav;
import com.ximpleware.XPathEvalException;
import com.ximpleware.XPathParseException;
/**
* @author Jason
* @version
* @since JDK1.6
*/
public class TmxReader {
private final Logger logger = LoggerFactory.getLogger(TmxReader.class);
private TmxHeader header;
private int totalTu;
/** XML解析封装 */
private VTDUtils vu;
private AutoPilot tuAp;
private TmxFilterInterface tmxFilter = null;
public TmxReader(File file) throws TmxReadException {
// 解析文件
VTDGen vg = null;
try {
vg = VTDLoader.loadVTDGen(file, FileEncodingDetector.detectFileEncoding(file));
} catch (IOException e) {
logger.error(Messages.getString("document.DocUtils.logger1"), e);
throw new TmxReadException(Messages.getString("document.TmxReader.parseTmxFileError"));
} catch (EncodingException e) {
logger.error(Messages.getString("document.ImportAbstract.logger1"), e);
String message = Messages.getString("document.ImportAbstract.msg1");
throw new TmxReadException(message + e.getMessage());
} catch (ParseException e) {
logger.error(Messages.getString("document.ImportAbstract.logger3"), e);
String errMsg = e.getMessage();
String message;
if (errMsg.indexOf("invalid encoding") != -1) { // 编码异常
message = Messages.getString("document.ImportAbstract.msg1");
} else {
message = Messages.getString("document.ImportAbstract.msg3");
}
throw new TmxReadException(message + e.getMessage());
}
if (vg == null) {
throw new TmxReadException(Messages.getString("document.TmxReader.parseTmxFileError"));
}
// 验证TMX ,解析Header XMLElement,将节点导航到Body XMLElement
header = new TmxHeader();
validateTmxAndParseHeader(vg);
tuAp = new AutoPilot(vu.getVTDNav());
try {
tuAp.selectXPath("./tu");
} catch (XPathParseException e) {
throw new TmxReadException(Messages.getString("document.TmxReader.parseTmxFileError"));
}
}
public TmxReader(String tmxContent) throws TmxReadException {
// 解析文件
VTDGen vg = new VTDGen();
vg.setDoc(tmxContent.getBytes());
String message = "";
try {
vg.parse(true);
} catch (EncodingException e) {
logger.error(Messages.getString("document.ImportAbstract.logger1"), e);
message = Messages.getString("document.ImportAbstract.msg1");
throw new TmxReadException(message + e.getMessage());
} catch (ParseException e) {
logger.error(Messages.getString("document.ImportAbstract.logger3"), e);
String errMsg = e.getMessage();
if (errMsg.indexOf("invalid encoding") != -1) { // 编码异常
message = Messages.getString("document.ImportAbstract.msg1");
} else {
message = Messages.getString("document.ImportAbstract.msg3");
}
throw new TmxReadException(message + e.getMessage());
}
header = new TmxHeader();
validateTmxAndParseHeader(vg);
tuAp = new AutoPilot(vu.getVTDNav());
try {
tuAp.selectXPath("./tu");
} catch (XPathParseException e) {
throw new TmxReadException(Messages.getString("document.TmxReader.parseTmxFileError"));
}
}
public TmxReaderEvent read() {
TmxTU tu = null;
try {
if (tuAp.evalXPath() != -1) {
tu = new TmxTU();
readTuElementAttribute(tu);
readTuNoteElement(tu);
readTuPropElement(tu);
readTuTuvElement(tu);
} else {
return new TmxReaderEvent(null, TmxReaderEvent.END_FILE);
}
} catch (VTDException e) {
return new TmxReaderEvent(null, TmxReaderEvent.READ_EXCEPTION);
}
return new TmxReaderEvent(tu, TmxReaderEvent.NORMAL_READ);
}
private void readTuTuvElement(TmxTU tu) throws VTDException {
VTDNav vn = vu.getVTDNav();
vn.push();
AutoPilot ap = new AutoPilot(vn);
ap.selectXPath("./tuv");
// TUV 节点下的Note,Prop节点暂时不处理,所以此处暂时不解析
while (ap.evalXPath() != -1) {
int inx = vn.getAttrVal("xml:lang");
inx = inx == -1 ? vn.getAttrVal("lang") : inx;
String lang = inx != -1 ? vn.toString(inx) : null;
if (lang == null) {
continue;
}
vn.push();
if (vu.pilot("./seg") != -1) {
String fullText = vu.getElementContent().trim();
String pureText = DocUtils.getTmxTbxPureText(vu).trim();
if (fullText == null || pureText == null || fullText.equals("") || pureText.equals("")) {
// fix Bug #2928 by Jason SQLite--导入TMX异常, 导入程序正常退出,但是未完全导入所有内容,此处在continue时应该先调用vn.pop()
vn.pop();
continue;
}
TmxSegement segment = new TmxSegement();
segment.setLangCode(Utils.convertLangCode(lang));
// fix Bug #3406 by yule --xliff中的标记可能与TMX标记不兼容。
if (tmxFilter == null)
// segment.setFullText(InnerTagClearUtil.clearXliffTag4Tmx(fullText));
segment.setFullText(fullText); // 不在导入时清理
else {
String text = tmxFilter.clearString(fullText);
// text = InnerTagClearUtil.clearXliffTag4Tmx(text);// 不在导入时清理
segment.setFullText(text);
}
segment.setPureText(pureText);
if (lang.equalsIgnoreCase(header.getSrclang())) {
tu.setSource(segment);
} else {
tu.appendSegement(segment);
}
}
vn.pop();
}
vn.pop();
}
private void readTuPropElement(TmxTU tu) throws VTDException {
VTDNav vn = vu.getVTDNav();
vn.push();
AutoPilot ap = new AutoPilot(vn);
ap.selectXPath("./prop");
while (ap.evalXPath() != -1) {
String content = vu.getElementContent();
if (content == null) {
continue;
}
int inx = vn.getAttrVal("type");
String typeValue = inx != -1 ? vn.toString(inx) : null;
if (typeValue == null) {
continue;
}
if (typeValue.equals(TmxContexts.PRE_CONTEXT_NAME)) {
tu.appendContext(TmxContexts.PRE_CONTEXT_NAME, content.trim());
} else if (typeValue.equals(TmxContexts.NEXT_CONTEXT_NAME)) {
tu.appendContext(TmxContexts.NEXT_CONTEXT_NAME, content.trim());
} else if (typeValue.equals("x-Context")) {
// Trados TMX file
String[] contexts = content.split(",");
if (contexts.length == 2) {
tu.appendContext(TmxContexts.PRE_CONTEXT_NAME, contexts[0].trim());
tu.appendContext(TmxContexts.NEXT_CONTEXT_NAME, contexts[1].trim());
}
} else {
TmxProp p = new TmxProp(typeValue, content);
tu.appendProp(p);
}
}
vn.pop();
}
private void readTuNoteElement(TmxTU tu) throws VTDException {
VTDNav vn = vu.getVTDNav();
vn.push();
AutoPilot ap = new AutoPilot(vn);
ap.selectXPath("./note");
while (ap.evalXPath() != -1) {
String fragment = vu.getElementFragment();
TmxNote note = new TmxNote();
note.setContent(fragment);
int inx = vn.getAttrVal("xml:lang");
String value = inx != -1 ? vn.toString(inx) : null;
if (value != null) {
note.setXmlLang(value);
}
inx = vn.getAttrVal("o-encoding");
value = inx != -1 ? vn.toString(inx) : null;
if (value != null) {
note.setXmlLang(value);
}
tu.appendNote(note);
}
vn.pop();
}
private void readTuElementAttribute(TmxTU tu) throws VTDException {
VTDNav vn = vu.getVTDNav();
vn.push();
AutoPilot apAttributes = new AutoPilot(vu.getVTDNav());
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) : "";
// tuid, o-encoding, datatype, usagecount, lastusagedate, creationtool, creationtoolversion, creationdate,
// creationid, changedate, segtype, changeid, o-tmf, srclang.
if (name.equals("tuid")) {
tu.setTuId(value);
} else if (name.equals("creationtool")) {
tu.setCreationTool(value);
} else if (name.equals("creationtoolversion")) {
tu.setCreationToolVersion(value);
} else if (name.equals("creationdate")) {
tu.setCreationDate(value);
} else if (name.equals("creationid")) {
tu.setCreationUser(value);
} else if (name.equals("changedate")) {
tu.setChangeDate(value);
} else if (name.equals("changeid")) {
tu.setChangeUser(value);
} else {
tu.appendAttribute(name, value);
}
}
vn.pop();
}
/**
* Validate TMX Format,and pilot to Body XMLElement
* @param vg
* @throws TmxReadException
* ;
*/
private void validateTmxAndParseHeader(VTDGen vg) throws TmxReadException {
VTDNav vn = vg.getNav();
AutoPilot ap = new AutoPilot(vn);
String rootPath = "/tmx";
vu = new VTDUtils();
try {
vu.bind(vn);
ap.selectXPath(rootPath);
if (ap.evalXPath() == -1) {
throw new TmxReadException(Messages.getString("document.TmxReader.validateTmxFileError"));
}
ap.resetXPath();
ap.selectXPath("/tmx/header");
if (ap.evalXPath() == -1) {
throw new TmxReadException(Messages.getString("document.TmxReader.validateTmxFileError"));
}
int id = vu.getVTDNav().getAttrVal("srclang");
if (id == -1) {
throw new TmxReadException(Messages.getString("document.TmxReader.validateTmxFileError"));
}
header.setSrclang(vu.getVTDNav().toString(id).trim());
if (vu.pilot("/tmx/body") == -1) {
throw new TmxReadException(Messages.getString("document.TmxReader.validateTmxFileError"));
}
// compute total tu number
this.totalTu = vu.getChildElementsCount();
} catch (VTDException e) {
logger.error("", e);
throw new TmxReadException(Messages.getString("document.TmxReader.parseTmxFileError") + e.getMessage());
} finally {
vg.clear();
}
}
/**
* Parse file with VTD-XML
* @param file
* @return
* @throws TmxReadException
* All Exception come from VTDExcetpion;
*/
private VTDGen paseFile(File file) throws TmxReadException {
String encoding = FileEncodingDetector.detectFileEncoding(file);
VTDGen vg = new VTDGen();
FileInputStream fis = null;
String message = "";
try {
fis = new FileInputStream(file);
byte[] bArr = new byte[(int) file.length()];
int offset = 0;
int numRead = 0;
int numOfBytes = 1048576;// I choose this value randomally,
// any other (not too big) value also can be here.
if (bArr.length - offset < numOfBytes) {
numOfBytes = bArr.length - offset;
}
while (offset < bArr.length && (numRead = fis.read(bArr, offset, numOfBytes)) >= 0) {
offset += numRead;
if (bArr.length - offset < numOfBytes) {
numOfBytes = bArr.length - offset;
}
}
// clean invalid XML character
if (!(encoding.equalsIgnoreCase("UTF-16LE") || encoding.equalsIgnoreCase("UTF-16BE"))) {
byte[] _bArr = new byte[bArr.length];
int _bArrIndx = 0;
int type = 0;
for (int i = 0; i < bArr.length; i++) {
byte b = bArr[i];
if ((b >= type && b <= 8) || b == 11 || b == 12 || (b >= 14 && b <= 31)) {
continue;
} else if (b == 38 && i + 1 < bArr.length && bArr[i + 1] == 35 && i + 2 < bArr.length) {// &#
List<Byte> entis = new ArrayList<Byte>();
entis.add((byte) 38);
entis.add((byte) 35);
int j = i + 2;
if (bArr[j] == 120) {// x
entis.add((byte) 120);
while (true) {
j++;
if (j >= bArr.length) {
entis.clear();
b = bArr[i];
break;
}
b = bArr[j];
if ((b >= 48 && b <= 57) || (b >= 97 && b <= 102) || (b >= 65 && b <= 70)) {
entis.add(b);
} else if (b == 59) {
entis.add(b);
i = j;
break;
} else if (j - i > 10) {
entis.clear();
b = bArr[i];
break;
} else {
entis.clear();
b = bArr[i];
break;
}
}
} else {
while (true) {
b = bArr[j];
if ((b >= 48 && b <= 57)) {
entis.add(b);
} else if (b == 59) {
entis.add(b);
i = j;
break;
} else if (j - i > 10) {
entis.clear();
b = bArr[i];
break;
} else {
entis.clear();
b = bArr[i];
break;
}
j++;
if (j >= bArr.length) {
entis.clear();
b = bArr[i];
break;
}
}
}
if (!entis.isEmpty()) {
byte[] t = new byte[entis.size()];
for (int ti = 0; ti < entis.size(); ti++) {
t[ti] = entis.get(ti);
}
String s = new String(t);
if (s.matches("((&#[x]?)(([0]?([0-8]|[BbCcEe]))|(1[0-9])|(1[a-fA-F]));)")) {
continue;
}
}
}
_bArr[_bArrIndx++] = b;
}
bArr = null;
bArr = Arrays.copyOf(_bArr, _bArrIndx);
}
// use vtd parse
vg.setDoc(bArr);
vg.parse(true);
} catch (IOException e) {
logger.error(Messages.getString("document.DocUtils.logger1"), e);
throw new TmxReadException(Messages.getString("document.TmxReader.parseTmxFileError"));
} catch (EncodingException e) {
logger.error(Messages.getString("document.ImportAbstract.logger1"), e);
message = Messages.getString("document.ImportAbstract.msg1");
throw new TmxReadException(message + e.getMessage());
} catch (ParseException e) {
logger.error(Messages.getString("document.ImportAbstract.logger3"), e);
String errMsg = e.getMessage();
if (errMsg.indexOf("invalid encoding") != -1) { // 编码异常
message = Messages.getString("document.ImportAbstract.msg1");
} else {
message = Messages.getString("document.ImportAbstract.msg3");
}
throw new TmxReadException(message + e.getMessage());
} finally {
if (fis != null) {
try {
fis.close();
} catch (Exception e) {
}
}
}
return vg;
}
public TmxHeader getTmxHeader() {
return header;
}
public int getTotalTu() {
return totalTu;
}
/**
* 此方法用于清除导入TMX时清除第三方标记,如 sdl 2007 中的 ut 标签,清除标记请在以下方法中加入
* @param isClear
* ;
*/
public void tryToClearTags(boolean isClear) {
if (isClear) {
if (header == null || vu == null || tuAp == null) {
return;
}
try {
String creationtool = vu.getElementAttribute("/tmx/header", "creationtool");
String creationtoolversion = vu.getElementAttribute("/tmx/header", "creationtoolversion");
if (creationtool == null || creationtoolversion == null) {
return;
}
if (creationtool.equals(TmxFilterInterface.SDL_2007_FOR_WIN)) {
tmxFilter = new TmxFilterSDL2007Impl();
}
} catch (XPathParseException e) {
e.printStackTrace();
} catch (XPathEvalException e) {
e.printStackTrace();
} catch (NavException e) {
e.printStackTrace();
}
}
}
/**
* 获取 tmxfile 中的所有语言
* @return
*/
public List<String> getLangs() {
VTDNav vn = vu.getVTDNav();
vn.push();
List<String> langs = new LinkedList<String>();
langs.add(header.getSrclang());
AutoPilot ap = new AutoPilot(vn);
try {
ap.selectXPath("/tmx/body/tu/tuv");
String lang;
int index = -1;
while (ap.evalXPath() != -1) {
index = vn.getAttrVal("xml:lang");
if (index == -1)
continue;
lang = vn.toRawString(index);
if (!langs.contains(lang)) {
langs.add(lang);
}
}
} catch (Exception e) {
e.printStackTrace();
}
vn.pop();
return langs;
}
}
| 16,765 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
TmxReaderEvent.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/database/net.heartsome.cat.database/src/net/heartsome/cat/document/TmxReaderEvent.java | /**
* TmxReaderEvent.java
*
* Version information :
*
* Date:2013-1-29
*
* Copyright notice :
* 本文件及其附带的相关文件包含机密信息,仅限瀚特盛科技有限公司指定的,与本项目有关的内部人员和客户联络人员查阅和使用。
* 如果您不是本保密声明中指定的收件者,请立即销毁本文件,禁止对本文件或根据本文件中的内容采取任何其他行动,
* 包括但不限于:泄露本文件中的信息、以任何方式制作本文件全部或部分内容之副本、将本文件或其相关副本提供给任何其他人。
*/
package net.heartsome.cat.document;
import net.heartsome.cat.common.bean.TmxTU;
/**
* @author Jason
* @version
* @since JDK1.6
*/
public class TmxReaderEvent {
public static final int NORMAL_READ = -1;
public static final int END_FILE = 0;
public static final int ERROR_TU = 1;
public static final int READ_EXCEPTION = 2;
private TmxTU tu;
private int state;
public TmxReaderEvent(TmxTU tu) {
this.tu = tu;
}
public TmxReaderEvent(TmxTU tu, int state) {
this(tu);
this.state = state;
}
/** @return the tu */
public TmxTU getTu() {
return tu;
}
/**
* @param tu
* the tu to set
*/
public void setTu(TmxTU tu) {
this.tu = tu;
}
/** @return the readState */
public int getState() {
return state;
}
/**
* @param readState
* the readState to set
*/
public void setState(int state) {
this.state = state;
}
}
| 1,505 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
TmxReadException.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/database/net.heartsome.cat.database/src/net/heartsome/cat/document/TmxReadException.java | /**
* TmxReadException.java
*
* Version information :
*
* Date:2013-1-25
*
* Copyright notice :
* 本文件及其附带的相关文件包含机密信息,仅限瀚特盛科技有限公司指定的,与本项目有关的内部人员和客户联络人员查阅和使用。
* 如果您不是本保密声明中指定的收件者,请立即销毁本文件,禁止对本文件或根据本文件中的内容采取任何其他行动,
* 包括但不限于:泄露本文件中的信息、以任何方式制作本文件全部或部分内容之副本、将本文件或其相关副本提供给任何其他人。
*/
package net.heartsome.cat.document;
/**
* @author Jason
* @version
* @since JDK1.6
*/
public class TmxReadException extends Exception {
/** serialVersionUID. */
private static final long serialVersionUID = 1L;
private int exceptionCode;
public TmxReadException() {
super();
}
public TmxReadException(String message) {
super(message);
this.exceptionCode = -1;
}
public TmxReadException(String message, int exceptionCode) {
this(message);
this.exceptionCode = exceptionCode;
}
public TmxReadException(String message, Throwable cause) {
super(message, cause);
exceptionCode = -1;
}
public TmxReadException(String message, Throwable cause, int exceptionCode) {
this(message, cause);
this.exceptionCode = exceptionCode;
}
public int getExcetpitonCode(){
return exceptionCode;
}
}
| 1,449 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
ExportAbstract.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/database/net.heartsome.cat.database/src/net/heartsome/cat/document/ExportAbstract.java | /**
* ExportAbstract.java
*
* Version information :
*
* Date:Feb 20, 2012
*
* Copyright notice :
* 本文件及其附带的相关文件包含机密信息,仅限瀚特盛科技有限公司指定的,与本项目有关的内部人员和客户联络人员查阅和使用。
* 如果您不是本保密声明中指定的收件者,请立即销毁本文件,禁止对本文件或根据本文件中的内容采取任何其他行动,
* 包括但不限于:泄露本文件中的信息、以任何方式制作本文件全部或部分内容之副本、将本文件或其相关副本提供给任何其他人。
*/
package net.heartsome.cat.document;
import java.util.List;
import net.heartsome.cat.database.bean.ExportDatabaseBean;
import net.heartsome.cat.database.bean.ExportFilterBean;
import net.heartsome.cat.database.resource.Messages;
import org.eclipse.core.runtime.IProgressMonitor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* 导出时基本参数
* @author Jason
* @version
* @since JDK1.6
*/
public abstract class ExportAbstract {
public final static Logger logger = LoggerFactory.getLogger(ExportTmxImpl.class);
protected List<ExportDatabaseBean> dbList; // 需要导出的数据库
protected ExportFilterBean filterBean; // 过滤规则
protected String encoding; // 编码格式 默认值为UTF-8
public ExportAbstract(List<ExportDatabaseBean> dbList, ExportFilterBean filterBean, String encoding) {
this.dbList = dbList;
this.filterBean = filterBean;
this.encoding = encoding;
}
/**
* 执行导出
* @param monitor
* @return 返回结果信息;
*/
public abstract String executeExport(IProgressMonitor monitor);
protected String USER_CANCEL = Messages.getString("document.ExportAbstract.msg1");
protected String DBOP_ERROR = Messages.getString("document.ExportAbstract.msg2");
protected String JDBC_ERROR = Messages.getString("document.ExportAbstract.msg3");
protected String FILE_ERROR = Messages.getString("document.ExportAbstract.msg4");
protected String SUCCESS = Messages.getString("document.ExportAbstract.msg5");
protected String RELEASE_DB_ERROR = Messages.getString("document.ExportAbstract.msg6");
protected String RELEASE_FILE_ERROR = Messages.getString("document.ExportAbstract.msg7");
}
| 2,291 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
XCSUtility.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/database/net.heartsome.cat.database/src/net/heartsome/cat/document/XCSUtility.java | package net.heartsome.cat.document;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class XCSUtility {
private static Logger logger = LoggerFactory.getLogger(XCSUtility.class);
private Element root;
public XCSUtility(File file){
SAXReader reader = new SAXReader();
try {
Document doc = reader.read(file);
root = doc.getRootElement();
} catch (DocumentException e) {
logger.warn("", e);
}
}
/**
* 返回 picklist 中提供的选择类型
* @param node 节点的名称 对应 XCS 中 levels 节点的内容
* @param propName 属性的名称 对应 XCS 中 datCatSet 下所有元素的名称
* @param typeName 属性的类型 对应 XCS 中 name 属性的值
* @return 返回供选择的类型,如果是文本内容,则返回空的 List,如果不支持则返回 null;
*/
public List<String> pickList(String node, String propName, String typeName){
if(root == null){
return null;
}
Element element = getElement(node, propName, typeName);
if(element == null){
return null;
}
List<String> result = new ArrayList<String>();
Element constants = element.element("contents");
if(constants == null){
return null;
}
String dataType = constants.attributeValue("datatype");
if("picklist".equals(dataType)){
String text = constants.getText();
if(null == text || "".equals(text.trim())){
return null;
}
else{
String[] textArray = text.split(" ");
for(String i : textArray){
result.add(i.trim());
}
return result;
}
}
else{
return result;
}
}
private Element getElement(String node, String propName, String typeName){
Element datCatSetElement = root.element("datCatSet");
if(datCatSetElement == null){
return null;
}
@SuppressWarnings("unchecked")
List<Element> elements = datCatSetElement.elements();
List<Element> propElements = new ArrayList<Element>();
for(Element i : elements){
String name = i.getName();
if((propName + "Spec").equals(name)){
propElements.add(i);
}
}
if(propElements.size() == 0){
return null;
}
for(Element i : propElements){
if(typeName.equals(i.attributeValue("name"))){
Element levels = i.element("levels");
if(levels == null){
return i;
}
else{
String levelsStr = levels.getText().trim();
String[] levelsArray = levelsStr.split(" ");
for(String level : levelsArray){
if(node.equals(level.trim())){
return i;
}
}
}
}
}
return null;
}
}
| 2,703 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
IRowHandler.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/database/net.heartsome.cat.database/src/net/heartsome/cat/document/xlsx/IRowHandler.java | /**
* RowHandler.java
*
* Version information :
*
* Date:2013-12-16
*
* Copyright notice :
* 本文件及其附带的相关文件包含机密信息,仅限瀚特盛科技有限公司指定的,与本项目有关的内部人员和客户联络人员查阅和使用。
* 如果您不是本保密声明中指定的收件者,请立即销毁本文件,禁止对本文件或根据本文件中的内容采取任何其他行动,
* 包括但不限于:泄露本文件中的信息、以任何方式制作本文件全部或部分内容之副本、将本文件或其相关副本提供给任何其他人。
*/
package net.heartsome.cat.document.xlsx;
import java.util.List;
import org.xml.sax.SAXException;
/**
* @author Jason
* @version
* @since JDK1.6
*/
public interface IRowHandler {
void handleRows(List<Row> rows) throws SAXException;
}
| 890 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
Row.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/database/net.heartsome.cat.database/src/net/heartsome/cat/document/xlsx/Row.java | /**
* Row.java
*
* Version information :
*
* Date:2013-7-17
*
* Copyright notice :
* 本文件及其附带的相关文件包含机密信息,仅限瀚特盛科技有限公司指定的,与本项目有关的内部人员和客户联络人员查阅和使用。
* 如果您不是本保密声明中指定的收件者,请立即销毁本文件,禁止对本文件或根据本文件中的内容采取任何其他行动,
* 包括但不限于:泄露本文件中的信息、以任何方式制作本文件全部或部分内容之副本、将本文件或其相关副本提供给任何其他人。
*/
package net.heartsome.cat.document.xlsx;
import java.util.ArrayList;
import java.util.List;
/**
* @author yule
* @version
* @since JDK1.6
*/
public class Row {
/**
* 行号,从1开始
*/
private int rowNumber;
/**
* 每一行的表格
*/
private List<Cell> cells;
/**
* 行号,从1开始
* @return the rowNumber
*/
public int getRowNumber() {
return rowNumber;
}
/**
* @param rowNumber
* the rowNumber to set
*/
public void setRowNumber(int rowNumber) {
this.rowNumber = rowNumber;
}
/**
* 每一行的表格
* @return the cells
*/
public List<Cell> getCells() {
return cells;
}
/**
* @param cells
* the cells to set
*/
public void setCells(List<Cell> cells) {
this.cells = cells;
}
public void addCell(Cell e) {
if (this.cells == null) {
this.cells = new ArrayList<Cell>();
}
this.cells.add(e);
}
}
| 1,584 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
Cell.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/database/net.heartsome.cat.database/src/net/heartsome/cat/document/xlsx/Cell.java | /**
* Cell.java
*
* Version information :
*
* Date:2013-7-17
*
* Copyright notice :
* 本文件及其附带的相关文件包含机密信息,仅限瀚特盛科技有限公司指定的,与本项目有关的内部人员和客户联络人员查阅和使用。
* 如果您不是本保密声明中指定的收件者,请立即销毁本文件,禁止对本文件或根据本文件中的内容采取任何其他行动,
* 包括但不限于:泄露本文件中的信息、以任何方式制作本文件全部或部分内容之副本、将本文件或其相关副本提供给任何其他人。
*/
package net.heartsome.cat.document.xlsx;
/**
* @author yule
* @version
* @since JDK1.6
*/
public class Cell {
/** 单元格的序号.从A,B...X,Y,Z,AA,AB,AC....AX,AY,AZ,BA...开始 */
private String cellNumber;
/** 单元格中的内容 */
private String cellConentent;
/**
* 单元格的序号.从A,B...X,Y,Z,AA,AB,AC....AX,AY,AZ,BA...开始
* @return the cellNumber
*/
public String getCellNumber() {
return cellNumber;
}
/**
* @param cellNumber
* the cellNumber to set
*/
public void setCellNumber(String cellNumber) {
this.cellNumber = cellNumber;
}
/** @return the cellConentent */
public String getCellConentent() {
return cellConentent;
}
/**
* @param cellConentent
* the cellConentent to set
*/
public void setCellConentent(String cellConentent) {
this.cellConentent = cellConentent;
}
}
| 1,539 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
XlsxRowReader.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/database/net.heartsome.cat.database/src/net/heartsome/cat/document/xlsx/XlsxRowReader.java | /**
* XlsxReader.java
*
* Version information :
*
* Date:2013-12-16
*
* Copyright notice :
* 本文件及其附带的相关文件包含机密信息,仅限瀚特盛科技有限公司指定的,与本项目有关的内部人员和客户联络人员查阅和使用。
* 如果您不是本保密声明中指定的收件者,请立即销毁本文件,禁止对本文件或根据本文件中的内容采取任何其他行动,
* 包括但不限于:泄露本文件中的信息、以任何方式制作本文件全部或部分内容之副本、将本文件或其相关副本提供给任何其他人。
*/
package net.heartsome.cat.document.xlsx;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.apache.poi.openxml4j.exceptions.OpenXML4JException;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.openxml4j.opc.PackageAccess;
import org.apache.poi.xssf.eventusermodel.ReadOnlySharedStringsTable;
import org.apache.poi.xssf.eventusermodel.XSSFReader;
import org.apache.poi.xssf.usermodel.XSSFRichTextString;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.OperationCanceledException;
import org.eclipse.core.runtime.SubProgressMonitor;
import org.xml.sax.Attributes;
import org.xml.sax.ContentHandler;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
/**
* @author Jason
* @version 1.0
* @since JDK1.6
*/
public class XlsxRowReader {
private String xlsxFile;
private int cacheSize;
private List<Row> rowCache;
private IRowHandler rowsHandler;
/**
* 构造器
* @param xlsxFile
* 文件路径
* @param cacheSize
* 一次缓存的行数据
* @param handler
* 缓存满后,对缓存中的数据进行处理
*/
public XlsxRowReader(String xlsxFile, int cacheSize, IRowHandler handler) {
rowCache = new ArrayList<Row>();
this.xlsxFile = xlsxFile;
this.cacheSize = cacheSize;
this.rowsHandler = handler;
}
public void readRows(IProgressMonitor monitor) throws ParserConfigurationException, SAXException, IOException, OpenXML4JException {
monitor.beginTask("", 10);
monitor.worked(1);
OPCPackage p = OPCPackage.open(xlsxFile, PackageAccess.READ);
ReadOnlySharedStringsTable shareString = new ReadOnlySharedStringsTable(p);
XSSFReader xssfReader = new XSSFReader(p);
XSSFReader.SheetIterator iter = (XSSFReader.SheetIterator) xssfReader.getSheetsData();
try {
while (iter.hasNext()) {
InputStream stream = iter.next();
readCells(stream, shareString, new SubProgressMonitor(monitor, 9));
stream.close();
// 目前只处理第一个sheet
break;
}
} finally {
p.close();
monitor.done();
}
}
private void readCells(InputStream sheetInputStream, ReadOnlySharedStringsTable sharedStringsTable, IProgressMonitor monitor)
throws ParserConfigurationException, SAXException, IOException {
InputSource sheetSource = new InputSource(sheetInputStream);
SAXParserFactory saxFactory = SAXParserFactory.newInstance();
SAXParser saxParser = saxFactory.newSAXParser();
XMLReader sheetParser = saxParser.getXMLReader();
ContentHandler handler = new XSSFHander(sharedStringsTable, monitor);
sheetParser.setContentHandler(handler);
sheetParser.parse(sheetSource);
rowsHandler.handleRows(rowCache);
rowCache.clear();
}
class XSSFHander extends DefaultHandler {
private final Pattern NUMBER = Pattern.compile("[0-9]");
private String lastElementName;
private boolean isSheredString;
private StringBuilder lastCellContent = new StringBuilder();
private ReadOnlySharedStringsTable sharedStringsTable;
private Row cRow;
private Cell cCell;
private IProgressMonitor monitor;
public XSSFHander(ReadOnlySharedStringsTable sharedStringsTable, IProgressMonitor monitor) {
this.sharedStringsTable = sharedStringsTable;
this.monitor = monitor;
}
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
lastElementName = qName;
if("dimension".equals(qName)){
String v = attributes.getValue("ref");
String[] vs = v.split(":");
if(vs.length == 2){
String trs = vs[1].replaceAll("[a-zA-Z]", "");
try{
int tr = Integer.parseInt(trs);
monitor.beginTask("", tr);
}catch (NumberFormatException e) {
int m = (int) (new File(xlsxFile).length() / (1024 * 1024));
if (m == 0) {
m = 1;
}
m = m * 4;
monitor.beginTask("", m);
}
}
}
// 开始读取一行数据
if ("row".equals(qName)) {
String currRow = attributes.getValue("r");
cRow = new Row();
cRow.setRowNumber(Integer.parseInt(currRow));
}
if ("c".equals(qName)) {
String value = attributes.getValue("t");
if ("inlineStr".equals(value)) {
isSheredString = false;
} else {
isSheredString = true;
}
cCell = new Cell();
cCell.setCellNumber(getCellPosition(attributes.getValue("r")));
cRow.addCell(cCell);
}
}
/**
* (non-Javadoc)
* @see org.xml.sax.helpers.DefaultHandler#endElement(java.lang.String, java.lang.String, java.lang.String)
*/
@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
// 处理excel的行
if ("row".equals(qName)) {
if (cacheSize > rowCache.size() && cRow.getCells() != null) {
rowCache.add(cRow);
} else {
rowsHandler.handleRows(rowCache);
rowCache.clear();
}
lastElementName = null;
if (monitor.isCanceled()) {
throw new OperationCanceledException();
}
monitor.worked(1);
} else if ("t".equals(qName) && !isSheredString) {
cCell.setCellConentent(lastCellContent.toString().trim());
lastCellContent.delete(0, lastCellContent.length());
} else if ("v".equals(qName)) {
int idx = -1;
try {
idx = Integer.parseInt(lastCellContent.toString().trim());
XSSFRichTextString rtss = new XSSFRichTextString(sharedStringsTable.getEntryAt(idx));
cCell.setCellConentent(rtss.toString());
lastCellContent.delete(0, lastCellContent.length());
} catch (NumberFormatException e) {
}
}
}
/**
* (non-Javadoc)
* @see org.xml.sax.helpers.DefaultHandler#characters(char[], int, int)
*/
@Override
public void characters(char[] ch, int start, int length) throws SAXException {
if ("v".equals(lastElementName) || ("t".equals(lastElementName) && !isSheredString)) {
lastCellContent.append(ch, start, length);
}
}
private String getCellPosition(String cellNumber) {
return NUMBER.matcher(cellNumber).replaceAll("");
}
}
}
| 7,164 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
ConverterFactory.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/database/net.heartsome.cat.database/src/net/heartsome/cat/document/converter/ConverterFactory.java | /**
* ConverterFactory.java
*
* Version information :
*
* Date:2013/5/17
*
* Copyright notice :
* 本文件及其附带的相关文件包含机密信息,仅限瀚特盛科技有限公司指定的,与本项目有关的内部人员和客户联络人员查阅和使用。
* 如果您不是本保密声明中指定的收件者,请立即销毁本文件,禁止对本文件或根据本文件中的内容采取任何其他行动,
* 包括但不限于:泄露本文件中的信息、以任何方式制作本文件全部或部分内容之副本、将本文件或其相关副本提供给任何其他人。
*/
package net.heartsome.cat.document.converter;
import java.util.Locale;
import net.heartsome.cat.tmx.converter.AbstractFile2Tmx;
import net.heartsome.cat.tmx.converter.AbstractTmx2File;
import net.heartsome.cat.tmx.converter.txt.Tmx2Txt;
import net.heartsome.cat.tmx.converter.txt.Txt2Tmx;
import net.heartsome.cat.tmx.converter.xlsx.Tmx2xlsx;
import net.heartsome.cat.tmx.converter.xlsx.Xlsx2Tmx;
public final class ConverterFactory {
public final static int FILE_TYPE_DOCX = 1;
public final static int FILE_TYPE_CSV = 2;
public final static int FILE_TYPE_XLSX = 3;
public final static int FILE_TYPE_TXT = 4;
public final static int FILE_TYPE_TBX = 5;
public final static int FILE_TYPE_HSTM = 6;
/**
* Tmx转换成其他文件
* @param fileType
* @return ;
*/
public static AbstractTmx2File getTmx2FileConverter(int fileType) {
switch (fileType) {
case FILE_TYPE_XLSX:
return new Tmx2xlsx();
case FILE_TYPE_TXT:
return new Tmx2Txt();
default:
return null;
}
}
/**
* 其他文件转化成Tmx
* @param sourceFile
* @return ;
*/
public static AbstractFile2Tmx getFile2TmxConverter(String sourceFile) {
return getFile2TmxConverter(getFileType(sourceFile));
}
/**
* 其他文件转化成Tmx
* @param sourceFile
* @return ;
*/
public static AbstractFile2Tmx getFile2TmxConverter(int fileType) {
switch (fileType) {
case FILE_TYPE_XLSX:
return new Xlsx2Tmx();
case FILE_TYPE_TXT:
return new Txt2Tmx();
default:
return null;
}
}
/**
* 文件名转换成文件类型
* @param sourceFile
* @return ;
*/
public static int getFileType(String sourceFile) {
if (null == sourceFile || sourceFile.trim().isEmpty()) {
return -1;
}
String tempName = sourceFile.toLowerCase(Locale.ENGLISH);
if (tempName.endsWith(".docx")) {
return FILE_TYPE_DOCX;
} else if (tempName.endsWith(".csv")) {
return FILE_TYPE_CSV;
} else if (tempName.endsWith(".xlsx")) {
return FILE_TYPE_XLSX;
} else if (tempName.endsWith(".txt")) {
return FILE_TYPE_TXT;
} else if (tempName.endsWith(".tbx")) {
return FILE_TYPE_TBX;
} else if (tempName.endsWith(".hstm")) {
return FILE_TYPE_HSTM;
} else {
return -1;
}
}
public static AbstractConverter getFile2TbxConverter(String sourceFile) {
int fileType = getFileType(sourceFile);
if (fileType == -1) {
return null;
}
switch (fileType) {
case FILE_TYPE_XLSX:
return new Xlsx2TbxConverter(sourceFile);
case FILE_TYPE_TXT:
return new Txt2TbxConverter(sourceFile);
default:
return null;
}
}
}
| 3,326 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
Txt2TbxConverter.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/database/net.heartsome.cat.database/src/net/heartsome/cat/document/converter/Txt2TbxConverter.java | /**
* Txt2TbxConverter.java
*
* Version information :
*
* Date:2013-12-18
*
* Copyright notice :
* 本文件及其附带的相关文件包含机密信息,仅限瀚特盛科技有限公司指定的,与本项目有关的内部人员和客户联络人员查阅和使用。
* 如果您不是本保密声明中指定的收件者,请立即销毁本文件,禁止对本文件或根据本文件中的内容采取任何其他行动,
* 包括但不限于:泄露本文件中的信息、以任何方式制作本文件全部或部分内容之副本、将本文件或其相关副本提供给任何其他人。
*/
package net.heartsome.cat.document.converter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import net.heartsome.cat.common.locale.Language;
import net.heartsome.cat.common.locale.LocaleService;
import net.heartsome.cat.common.util.FileEncodingDetector;
import net.heartsome.cat.database.resource.Messages;
import net.heartsome.cat.document.txt.TxtRowReader;
import net.heartsome.cat.tmx.converter.LanguageUtils;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.OperationCanceledException;
import org.eclipse.core.runtime.SubProgressMonitor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author Jason
* @version
* @since JDK1.6
*/
public class Txt2TbxConverter extends AbstractConverter {
public Logger LOGGER = LoggerFactory.getLogger(Txt2TbxConverter.class);
private String txtFile;
private FileOutputStream out;
private String[] header = null;
public Txt2TbxConverter(String txtFile) {
this.txtFile = txtFile;
}
/**
* (non-Javadoc)
* @see net.heartsome.cat.document.converter.AbstractConverter#doConvert(java.lang.String,
* org.eclipse.core.runtime.IProgressMonitor)
*/
@Override
public void doConvert(String targetFile, IProgressMonitor monitor) throws Exception {
try {
monitor.beginTask("", 10);
monitor.worked(2);
out = new FileOutputStream(new File(targetFile));
File f = new File(txtFile);
String encoding = FileEncodingDetector.detectFileEncoding(f);
TxtRowReader reader = new TxtRowReader(f, encoding);
int rowsNum = reader.getLineNumber();
if (rowsNum < 2) {
throw new Exception(Messages.getString("converter.common.vaild.langcode.error"));
}
List<String[]> h = reader.read(1); // read header
if (h == null || h.size() == 0) {
throw new Exception(Messages.getString("converter.common.vaild.langcode.error"));
}
String[] hv = h.get(0);
if (hv == null || hv.length < 2) {
throw new Exception(Messages.getString("converter.common.vaild.langcode.error"));
}
Map<String, Language> defaultLanguage = LocaleService.getDefaultLanguage();
List<String> _temp = new ArrayList<String>();
for (String s : hv) {
s = LanguageUtils.convertLangCode(s);
if (_temp.contains(s)) {
throw new Exception(Messages.getString("converter.common.vaild.duplicatelangcode.error"));
}
if (defaultLanguage.get(s) == null) {
throw new Exception(Messages.getString("converter.common.vaild.langcode.error"));
}
_temp.add(s);
}
if (_temp.size() < 2) {
throw new Exception(Messages.getString("converter.common.vaild.langcode.error"));
}
header = _temp.toArray(new String[] {});
// generate header
String s = generateTbxHeader(header[0]);
writeString(s);
// generate body
int readSize = 10;
List<String[]> rs = null;
if(monitor.isCanceled()){
throw new OperationCanceledException();
}
SubProgressMonitor subMonitor = new SubProgressMonitor(monitor, 8);
subMonitor.beginTask("", rowsNum / readSize == 0 ? 1 : rowsNum / readSize);
while ((rs = reader.read(readSize)) != null) {
for (String[] r : rs) {
if (r == null || r.length < 2) {
continue;
}
int loopSize = r.length < header.length ? r.length : header.length;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < loopSize; i++) {
String value = r[i];
String lang = header[i];
sb.append("<langSet id=\"_" + (System.currentTimeMillis() + 1) + "\" xml:lang=\"" + lang
+ "\">\n");
sb.append("<tig>\n");
sb.append("<term>" + value + "</term>\n");
sb.append("</tig>\n");
sb.append("</langSet>\n");
}
if (sb.length() != 0) {
writeString("<termEntry id=\"_" + System.currentTimeMillis() + "\">\n");
writeString(sb.toString());
writeString("</termEntry>\n");
}
subMonitor.worked(1);
}
if(subMonitor.isCanceled()){
throw new OperationCanceledException();
}
}
// generate end
s = generateTbxEnd();
if (s != null && s.length() != 0) {
writeString(s);
}
subMonitor.done();
} finally {
out.close();
monitor.done();
}
}
private void writeString(String s) throws IOException {
if (s != null && s.length() != 0) {
out.write(s.getBytes("UTF-8"));
}
}
}
| 5,174 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
AbstractConverter.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/database/net.heartsome.cat.database/src/net/heartsome/cat/document/converter/AbstractConverter.java | /**
* AbstractCovnerter.java
*
* Version information :
*
* Date:2013-12-17
*
* Copyright notice :
* 本文件及其附带的相关文件包含机密信息,仅限瀚特盛科技有限公司指定的,与本项目有关的内部人员和客户联络人员查阅和使用。
* 如果您不是本保密声明中指定的收件者,请立即销毁本文件,禁止对本文件或根据本文件中的内容采取任何其他行动,
* 包括但不限于:泄露本文件中的信息、以任何方式制作本文件全部或部分内容之副本、将本文件或其相关副本提供给任何其他人。
*/
package net.heartsome.cat.document.converter;
import org.eclipse.core.runtime.IProgressMonitor;
/**
* @author Jason
* @version
* @since JDK1.6
*/
public abstract class AbstractConverter {
public abstract void doConvert(String targetFile, IProgressMonitor monitor) throws Exception;
protected String generateTbxHeader(String srcLang) {
StringBuilder sb = new StringBuilder();
sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
sb.append("<martif type=\"TBX\" xml:lang=\"" + srcLang + "\">\n");
sb.append("<martifHeader>\n");
sb.append("<fileDesc>Generated by Heartsome TBX Exporter</fileDesc>\n");
sb.append("<encodingDesc>\n");
sb.append("<p type=\"DCSName\">tbxdefault.xcs</p>\n");
sb.append("</encodingDesc>\n");
sb.append("</martifHeader>\n");
sb.append("<text>\n");
sb.append("<body>\n");
return sb.toString();
}
protected String generateTbxEnd() {
StringBuilder sb = new StringBuilder();
sb.append("</body>\n");
sb.append("</text>\n");
sb.append("</martif>\n");
return sb.toString();
}
}
| 1,721 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
Xlsx2TbxConverter.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/database/net.heartsome.cat.database/src/net/heartsome/cat/document/converter/Xlsx2TbxConverter.java | /**
* Xlsx2Tbx.java
*
* Version information :
*
* Date:2013-12-17
*
* Copyright notice :
* 本文件及其附带的相关文件包含机密信息,仅限瀚特盛科技有限公司指定的,与本项目有关的内部人员和客户联络人员查阅和使用。
* 如果您不是本保密声明中指定的收件者,请立即销毁本文件,禁止对本文件或根据本文件中的内容采取任何其他行动,
* 包括但不限于:泄露本文件中的信息、以任何方式制作本文件全部或部分内容之副本、将本文件或其相关副本提供给任何其他人。
*/
package net.heartsome.cat.document.converter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.xml.parsers.ParserConfigurationException;
import net.heartsome.cat.common.locale.Language;
import net.heartsome.cat.common.locale.LocaleService;
import net.heartsome.cat.database.resource.Messages;
import net.heartsome.cat.document.xlsx.Cell;
import net.heartsome.cat.document.xlsx.IRowHandler;
import net.heartsome.cat.document.xlsx.Row;
import net.heartsome.cat.document.xlsx.XlsxRowReader;
import net.heartsome.cat.tmx.converter.LanguageUtils;
import org.apache.poi.openxml4j.exceptions.OpenXML4JException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xml.sax.SAXException;
/**
* @author Jason
* @version
* @since JDK1.6
*/
public class Xlsx2TbxConverter extends AbstractConverter {
public Logger LOGGER = LoggerFactory.getLogger(Xlsx2TbxConverter.class);
private String xlsxFile;
private FileOutputStream out;
public Xlsx2TbxConverter(String xlsxFile) {
this.xlsxFile = xlsxFile;
}
@Override
public void doConvert(String targetFile, IProgressMonitor monitor) throws Exception {
try {
out = new FileOutputStream(new File(targetFile));
XlsxRowReader reader = new XlsxRowReader(this.xlsxFile, 20, handler);
try {
reader.readRows(monitor);
} catch (ParserConfigurationException e) {
LOGGER.error("", e);
throw new Exception(Messages.getString("converter.xlsx2tmx.parseExcle.error"));
} catch (SAXException e) {
LOGGER.error("", e);
if ("LANG-CODE-ERORR".equals(e.getMessage())) {
throw new Exception(Messages.getString("converter.common.vaild.langcode.error"));
} else if ("DIFF--SRC-LANG-CODE".equals(e.getMessage())) {
throw new Exception(Messages.getString("converter.common.appendtmx.diffsrcLang.error"));
} else if ("EMPTY-LANG-CODE".equals(e.getMessage())) {
throw new Exception(Messages.getString("converter.common.vaild.langcode.error"));
} else if ("DUPLICATE-LANG-CODE-ERORR".equals(e.getMessage())) {
throw new Exception(Messages.getString("converter.common.vaild.duplicatelangcode.error"));
}
} catch (IOException e) {
LOGGER.error("", e);
throw new Exception(Messages.getString("converter.xlsx2tmx.parseExcle.error"));
} catch (OpenXML4JException e) {
LOGGER.error("", e);
throw new Exception(Messages.getString("converter.xlsx2tmx.parseExcle.error"));
}
String s = generateTbxEnd();
if(s != null && s.length() != 0){
writeString(s);
}
} catch (FileNotFoundException e) {
LOGGER.error("", e);
} finally {
if (out != null) {
try {
out.close();
} catch (IOException e) {
}
}
}
}
private void writeString(String string) {
try {
out.write(string.getBytes("utf-8"));
} catch (UnsupportedEncodingException e) {
LOGGER.error("", e);
} catch (IOException e) {
LOGGER.error("", e);
}
}
private IRowHandler handler = new IRowHandler() {
private boolean flg = true;
/** key-value 列号-表头值 */
private Map<String, String> headerMap = new HashMap<String, String>();
public void handleRows(List<Row> rows) throws SAXException {
if (rows == null || rows.size() == 0) {
return;
}
if (flg) {
Row headerR = rows.remove(0);
if (!processHeader(headerR)) {
throw new SAXException("LANG-CODE-ERORR");
}
if (!validateHeader()) {
throw new SAXException("LANG-CODE-ERORR");
}
if (!validateDuplicateHeader()) {
throw new SAXException("DUPLICATE-LANG-CODE-ERORR");
}
flg = false;
String s = generateTbxHeader(headerR.getCells().get(0).getCellConentent());
if(s != null && s.length() != 0){
writeString(s);
}
}
for (Row r : rows) {
List<Cell> cells = r.getCells();
if (cells.size() < 2) {
continue;
}
StringBuilder sb = new StringBuilder();
for (Cell c : cells) {
String lang = headerMap.get(c.getCellNumber());
if (lang == null || lang.length() == 0) {
continue;
}
sb.append("<langSet id=\"_" + (System.currentTimeMillis() + 1) + "\" xml:lang=\"" + lang + "\">\n");
sb.append("<tig>\n");
sb.append("<term>" + c.getCellConentent().trim() + "</term>\n");
sb.append("</tig>\n");
sb.append("</langSet>\n");
}
if (sb.length() != 0) {
writeString("<termEntry id=\"_" + System.currentTimeMillis() + "\">\n");
writeString(sb.toString());
writeString("</termEntry>\n");
}
}
}
/**
* 解析第一行数据
* @param headerR
* @return ;
*/
private boolean processHeader(Row headerR) {
String lang = null;
if (null == headerR || headerR.getCells() == null) {
return false;
}
for (Cell cell : headerR.getCells()) {
lang = cell.getCellConentent();
String cellPostion = cell.getCellNumber();
lang = LanguageUtils.convertLangCode(lang);
if (null != lang) {
headerMap.put(cellPostion, lang);
}
}
if (headerMap.size() < 2) {
return false;
}
return true;
}
/**
* 验证第一行的数据是否符合要求
* @return ;
*/
private boolean validateHeader() {
if (headerMap == null || headerMap.size() == 0) {
return false;
}
Map<String, Language> defaultLanguage = LocaleService.getDefaultLanguage();
Collection<String> values = headerMap.values();
for (String value : values) {
if (defaultLanguage.get(value) == null) {
return false;
}
}
return true;
}
/**
* 验证第一行的数据是否重复
* @return ;
*/
private boolean validateDuplicateHeader() {
if (headerMap == null || headerMap.size() == 0) {
return false;
}
Collection<String> values = headerMap.values();
Set<String> temp = new HashSet<String>();
for (String value : values) {
temp.add(value);
}
if (values.size() != temp.size()) {
return false;
}
return true;
}
};
}
| 7,056 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
TxtRowReader.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/database/net.heartsome.cat.database/src/net/heartsome/cat/document/txt/TxtRowReader.java | /**
* TxtRowReader.java
*
* Version information :
*
* Date:2013-12-18
*
* Copyright notice :
* 本文件及其附带的相关文件包含机密信息,仅限瀚特盛科技有限公司指定的,与本项目有关的内部人员和客户联络人员查阅和使用。
* 如果您不是本保密声明中指定的收件者,请立即销毁本文件,禁止对本文件或根据本文件中的内容采取任何其他行动,
* 包括但不限于:泄露本文件中的信息、以任何方式制作本文件全部或部分内容之副本、将本文件或其相关副本提供给任何其他人。
*/
package net.heartsome.cat.document.txt;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* This instance must call close method
* @author Jason
* @version
* @since JDK1.6
*/
public class TxtRowReader {
private Logger LOGGER = LoggerFactory.getLogger(TxtRowReader.class);
private BufferedReader reader;
private String encoding;
private File txtFile;
private int lineNumber;
/**
* This instance must call close method
* @param txtFile
* @param fileEncoding
* @throws FileNotFoundException
* @throws IOException
*/
public TxtRowReader(File txtFile, String fileEncoding) throws FileNotFoundException, IOException {
if (txtFile == null || !txtFile.exists()) {
throw new FileNotFoundException();
}
this.encoding = fileEncoding;
this.txtFile = txtFile;
lineNumber = computeLineNumber();
reader = new BufferedReader(new InputStreamReader(new FileInputStream(txtFile), encoding));
}
public List<String[]> read(int size) throws IOException {
if (size < 1) {
return null;
}
List<String[]> result = new ArrayList<String[]>();
for (int i = 0; i < size; i++) {
String line = reader.readLine();
if (line == null) {
break;
}
String[] r = line.split("\\t");
result.add(r);
}
if (result.size() == 0) {
return null;
}
return result;
}
public void close() {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
LOGGER.error("", e);
}
}
}
public int getLineNumber() {
return lineNumber;
}
private int computeLineNumber() throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(txtFile), encoding));
int ch = -1;
int count = 0;
boolean isline = false;
try {
while ((ch = reader.read()) != -1) {
if (ch == '\r' || ch == '\n') {
if (!isline) {
isline = true;
count++;
}
} else {
isline = false;
}
}
} catch (IOException e1) {
e1.printStackTrace();
} finally {
try {
reader.close();
} catch (IOException e) {
LOGGER.error("", e);
}
}
return count;
}
}
| 3,080 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |