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 |
---|---|---|---|---|---|---|---|---|---|---|---|
TmxSegement.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/base_commons/net.heartsome.cat.common.core/src/net/heartsome/cat/common/bean/TmxSegement.java | package net.heartsome.cat.common.bean;
/**
* TUV
* @author jason
* @version
* @since JDK1.6
*/
public class TmxSegement {
private int dbPk;
private String pureText;
private String fullText;
private String langCode;
public TmxSegement() {
};
public TmxSegement(String pureText, String fullText, String langCode) {
this.pureText = pureText;
this.fullText = fullText;
this.langCode = langCode;
}
/**
* Set the value of pureText
* @param newVar
* the new value of pureText
*/
public void setPureText(String newVar) {
pureText = newVar;
}
/**
* Get the value of pureText
* @return the value of pureText
*/
public String getPureText() {
return pureText;
}
/**
* Set the value of fullText
* @param newVar
* the new value of fullText
*/
public void setFullText(String newVar) {
fullText = newVar;
}
/**
* Get the value of fullText
* @return the value of fullText
*/
public String getFullText() {
return fullText;
}
/**
* Set the value of langCode
* @param newVar
* the new value of langCode
*/
public void setLangCode(String newVar) {
langCode = newVar;
}
/**
* Get the value of langCode
* @return the value of langCode
*/
public String getLangCode() {
return langCode;
}
/** @return the dbPk */
public int getDbPk() {
return dbPk;
}
/**
* @param dbPk
* the dbPk to set
*/
public void setDbPk(int dbPk) {
this.dbPk = dbPk;
}
}
| 1,483 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
TranslationUnitAnalysisResult.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/base_commons/net.heartsome.cat.common.core/src/net/heartsome/cat/common/bean/TranslationUnitAnalysisResult.java | /**
* TranslationUnitAnalysResult.java
*
* Version information :
*
* Date:2012-12-4
*
* Copyright notice :
* 本文件及其附带的相关文件包含机密信息,仅限瀚特盛科技有限公司指定的,与本项目有关的内部人员和客户联络人员查阅和使用。
* 如果您不是本保密声明中指定的收件者,请立即销毁本文件,禁止对本文件或根据本文件中的内容采取任何其他行动,
* 包括但不限于:泄露本文件中的信息、以任何方式制作本文件全部或部分内容之副本、将本文件或其相关副本提供给任何其他人。
*/
package net.heartsome.cat.common.bean;
/**
* Translation Unit Translation memory analys result
* @author jason
* @version
* @since JDK1.6
*/
public class TranslationUnitAnalysisResult {
private int similarity;
private String dbName;
public TranslationUnitAnalysisResult() {
this(0, null);
}
public TranslationUnitAnalysisResult(int similarity){
this(similarity, null);
}
public TranslationUnitAnalysisResult(int similarity, String dbName) {
this.similarity = similarity;
this.dbName = dbName;
}
/** @return the similarity */
public int getSimilarity() {
return similarity;
}
/**
* @param similarity
* the similarity to set
*/
public void setSimilarity(int similarity) {
this.similarity = similarity;
}
/** @return the dbName */
public String getDbName() {
return dbName;
}
/**
* @param dbName
* the dbName to set
*/
public void setDbName(String dbName) {
this.dbName = dbName;
}
}
| 1,599 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
MetaData.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/base_commons/net.heartsome.cat.common.core/src/net/heartsome/cat/common/bean/MetaData.java | package net.heartsome.cat.common.bean;
/**
* 存放数据库配置的元数据
* @author terry
* @version
* @since JDK1.6
*/
public class MetaData implements Cloneable {
/** 数据库类型 */
protected String dbType;
/** 数据库名称 */
protected String databaseName = "";
/** 数据库实例(Oracle) */
protected String instance = "";
/** 服务器名 */
protected String serverName = "";
/** 端口号 */
protected String port = "";
/** 用户名 */
protected String userName = "";
/** 密码 */
protected String password = "";
/** 优化策略 */
protected String optimize = "speed";
/** 数据存放路径(internalDB) */
protected String dataPath = "";
/** 是否是术语库 */
protected boolean isTB = true;
/** 是否是记忆库 */
protected boolean isTM = true;
/**
* 获取数据库名称
* @return ;
*/
public String getDatabaseName() {
return databaseName;
}
/**
* 设置数据库名称
* @param databaseName ;
*/
public void setDatabaseName(String databaseName) {
this.databaseName = databaseName;
}
/**
* 是否支持数据库名称
* @return ;
*/
public boolean databaseNameSupported() {
return true;
}
/**
* 取得数据库实例名称
* @return ;
*/
public String getInstance() {
return instance;
}
/**
* 设置数据库实例名称
* @param instance ;
*/
public void setInstance(String instance) {
this.instance = instance;
}
/**
* 是否支持使用数据库实例名称
* @return ;
*/
public boolean instanceSupported() {
return true;
}
/**
* 取得服务器名称
* @return ;
*/
public String getServerName() {
return serverName;
}
/**
* 设置服务器名称
* @param serverName ;
*/
public void setServerName(String serverName) {
this.serverName = serverName;
}
/**
* 是否支持使用服务器名称
* @return ;
*/
public boolean serverNameSupported() {
return true;
}
/**
* 取得端口号
* @return ;
*/
public String getPort() {
return port;
}
/**
* 设置端口号
* @param port ;
*/
public void setPort(String port) {
this.port = port;
}
/**
* 是否支持使用端口号
* @return ;
*/
public boolean portSupported() {
return true;
}
/**
* 取得用户名
* @return ;
*/
public String getUserName() {
return userName;
}
/**
* 设置用户名
* @param userName ;
*/
public void setUserName(String userName) {
this.userName = userName;
}
/**
* 是否支持使用用户名
* @return ;
*/
public boolean userNameSupported() {
return true;
}
/**
* 取得密码
* @return ;
*/
public String getPassword() {
return password;
}
/**
* 设置密码
* @param password ;
*/
public void setPassword(String password) {
this.password = password;
}
/**
* 是否支持使用密码
* @return ;
*/
public boolean passwordSupported() {
return true;
}
/**
* 取得优化策略
* @return ;
*/
public String getOptimize() {
return optimize;
}
/* *//**
* 设置优化策略
* @param optimize ;
*//*
public void setOptimize(String optimize) {
this.optimize = optimize;
}*/
/**
* 取得数据库文件路径
* @return ;
*/
public String getDataPath() {
return dataPath;
}
/**
* 设置数据库文件路径
* @param dataPath ;
*/
public void setDataPath(String dataPath) {
this.dataPath = dataPath;
}
/**
* 是否支持使用数据库文件路径
* @return ;
*/
public boolean dataPathSupported() {
return true;
}
/**
* 取得数据库类型
* @return ;
*/
public String getDbType() {
return dbType;
}
/**
* 设置数据库类型
* @param dbType ;
*/
public void setDbType(String dbType) {
this.dbType = dbType;
}
/**
* 取得是否是术语库
* @return ;
*/
public boolean isTB() {
return isTB;
}
/**
* 设置是否是术语库
* @param isTB ;
*/
public void setTB(boolean isTB) {
this.isTB = isTB;
}
/**
* 取得是否是记忆库
* @return ;
*/
public boolean isTM() {
return isTM;
}
/**
* 设置是否是记忆库
* @param isTM ;
*/
public void setTM(boolean isTM) {
this.isTM = isTM;
}
@Override
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
| 4,309 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
TmxProp.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/base_commons/net.heartsome.cat.common.core/src/net/heartsome/cat/common/bean/TmxProp.java | package net.heartsome.cat.common.bean;
/**
* prop
* @author jason
* @version
* @since JDK1.6
*/
public class TmxProp {
/** The prop node type name */
private String name;
/** the prop node content */
private String value;
public TmxProp() {
}
public TmxProp(String name, String value) {
name = name == null ? "" : name;
value = value == null ? "" : value;
this.name = name;
this.value = value;
}
/**
* Both name and value equals then return true, otherwise return false;
*/
@Override
public boolean equals(Object obj) {
if (obj instanceof TmxProp) {
TmxProp _obj = (TmxProp) obj;
if (_obj.name.equals(this.name) && _obj.value.equals(this.value)) {
return true;
}
}
return false;
}
/**
* Set the value of name
* @param newVar
* the new value of name
*/
public void setName(String newVar) {
name = newVar;
}
/**
* Get the value of name
* @return the value of name
*/
public String getName() {
return name;
}
/**
* Set the value of value
* @param newVar
* the new value of value
*/
public void setValue(String newVar) {
value = newVar;
}
/**
* Get the value of value
* @return the value of value
*/
public String getValue() {
return value;
}
}
| 1,273 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
FuzzySearchResult.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/base_commons/net.heartsome.cat.common.core/src/net/heartsome/cat/common/bean/FuzzySearchResult.java | package net.heartsome.cat.common.bean;
/**
* @author jason
* @version
* @since JDK1.6
*/
public class FuzzySearchResult {
private TmxTU tu;
private String dbName;
private int similarity;
private Object dbOp;
public FuzzySearchResult(TmxTU tu) {
this.tu = tu;
}
public void setDbOp(Object dbOp){
this.dbOp = dbOp;
}
public Object getDbOp(){
return this.dbOp;
}
/**
* Set the value of tu
* @param newVar
* the new value of tu
*/
public void setTu(TmxTU newVar) {
tu = newVar;
}
/**
* Get the value of tu
* @return the value of tu
*/
public TmxTU getTu() {
return tu;
}
/**
* Set the value of dbName
* @param newVar
* the new value of dbName
*/
public void setDbName(String newVar) {
dbName = newVar;
}
/**
* Get the value of dbName
* @return the value of dbName
*/
public String getDbName() {
return dbName;
}
/**
* Set the value of similarity
* @param newVar
* the new value of similarity
*/
public void setSimilarity(int newVar) {
similarity = newVar;
}
/**
* Get the value of similarity
* @return the value of similarity
*/
public int getSimilarity() {
return similarity;
}
}
| 1,219 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
TmxContexts.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/base_commons/net.heartsome.cat.common.core/src/net/heartsome/cat/common/bean/TmxContexts.java | /**
* TmxContexts.java
*
* Version information :
*
* Date:2013-1-28
*
* Copyright notice :
* 本文件及其附带的相关文件包含机密信息,仅限瀚特盛科技有限公司指定的,与本项目有关的内部人员和客户联络人员查阅和使用。
* 如果您不是本保密声明中指定的收件者,请立即销毁本文件,禁止对本文件或根据本文件中的内容采取任何其他行动,
* 包括但不限于:泄露本文件中的信息、以任何方式制作本文件全部或部分内容之副本、将本文件或其相关副本提供给任何其他人。
*/
package net.heartsome.cat.common.bean;
/**
* @author Jason
* @version
* @since JDK1.6
*/
public class TmxContexts {
/** context Prop XmlElement type attribute value in R8 */
public static final String PRE_CONTEXT_NAME = "x-preContext";
/** context Prop XmlElement type attribute value in R8 */
public static final String NEXT_CONTEXT_NAME = "x-nextContext";
private String[] preContext;
private String[] nextContext;
public TmxContexts() {
preContext = new String[2];
nextContext = new String[2];
}
public void appendPreContext(String val) {
if (val == null || val.length() == 0) {
return;
}
if (preContext[0] != null && preContext[1] != null) {
String s1 = preContext[0];
preContext[0] = val;
preContext[1] = s1;
} else if (preContext[1] == null) {
preContext[1] = val;
} else if (preContext[0] == null) {
preContext[0] = val;
}
}
public void appendNextContext(String val) {
if (val == null || val.length() == 0) {
return;
}
if (nextContext[0] != null && nextContext[1] != null) {
String s1 = nextContext[0];
nextContext[0] = val;
nextContext[1] = s1;
} else if (nextContext[1] == null) {
nextContext[1] = val;
} else if (nextContext[0] == null) {
nextContext[0] = val;
}
}
/** @return the nextContext */
public String getNextContext() {
StringBuffer bf = new StringBuffer();
for (String s : nextContext) {
if (s != null && s.length() != 0) {
bf.append("," + s);
}
}
if (bf.length() != 0) {
return bf.substring(1);
}
return "";
}
/** @return the preContext */
public String getPreContext() {
StringBuffer bf = new StringBuffer();
for (String s : preContext) {
if (s != null && s.length() != 0) {
bf.append("," + s);
}
}
if (bf.length() != 0) {
return bf.substring(1);
}
return "";
}
}
| 2,447 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
ProjectInfoBean.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/base_commons/net.heartsome.cat.common.core/src/net/heartsome/cat/common/bean/ProjectInfoBean.java | /**
* ProjectConfigBean.java
*
* Version information :
*
* Date:Nov 25, 2011
*
* Copyright notice :
* 本文件及其附带的相关文件包含机密信息,仅限瀚特盛科技有限公司指定的,与本项目有关的内部人员和客户联络人员查阅和使用。
* 如果您不是本保密声明中指定的收件者,请立即销毁本文件,禁止对本文件或根据本文件中的内容采取任何其他行动,
* 包括但不限于:泄露本文件中的信息、以任何方式制作本文件全部或部分内容之副本、将本文件或其相关副本提供给任何其他人。
*/
package net.heartsome.cat.common.bean;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import net.heartsome.cat.common.locale.Language;
/**
* @author Jason
* @version
* @since JDK1.6
*/
public class ProjectInfoBean implements PropertyChangeListener {
private String projectName;
private LinkedHashMap<String, String> mapField;
private LinkedHashMap<String, Object[]> mapAttr;
private Language sourceLang;
private List<Language> targetLang;
private List<DatabaseModelBean> tmDb;
private List<DatabaseModelBean> tbDb;
private PropertyChangeSupport propertyChangeSupport = new PropertyChangeSupport(this);
public ProjectInfoBean() {
this.mapField = new LinkedHashMap<String, String>();
this.mapAttr = new LinkedHashMap<String, Object[]>();
this.targetLang = new ArrayList<Language>();
this.tmDb = new ArrayList<DatabaseModelBean>();
this.tbDb = new ArrayList<DatabaseModelBean>();
}
/** @return the projectName */
public String getProjectName() {
return projectName;
}
/**
* @param projectName
* the projectName to set
*/
public void setProjectName(String projectName) {
propertyChangeSupport.firePropertyChange("projectName", this.projectName, this.projectName = projectName);
}
public LinkedHashMap<String, String> getMapField() {
return mapField;
}
public void setMapField(LinkedHashMap<String, String> mapField) {
this.mapField = mapField;
// propertyChangeSupport.firePropertyChange("mapField", this.mapField, this.mapField = mapField);
}
public LinkedHashMap<String, Object[]> getMapAttr() {
return mapAttr;
}
public void setMapAttr(LinkedHashMap<String, Object[]> mapAttr) {
this.mapAttr = mapAttr;
// propertyChangeSupport.firePropertyChange("mapAttr", this.mapAttr, this.mapAttr = mapAttr);
}
/** @return the sourceLang */
public Language getSourceLang() {
return sourceLang;
}
/**
* @param sourceLang
* the sourceLang to set
*/
public void setSourceLang(Language sourceLang) {
propertyChangeSupport.firePropertyChange("sourceLang", this.sourceLang, this.sourceLang = sourceLang);
}
/** @return 返回目标语言集 */
public List<Language> getTargetLang() {
return targetLang;
}
/**
* @param targetLang
* the targetLang to set
*/
public void setTargetLang(List<Language> targetLang) {
propertyChangeSupport.firePropertyChange("sourceLang", this.sourceLang, this.targetLang = targetLang);
}
/** @return the tmDb */
public List<DatabaseModelBean> getTmDb() {
return tmDb;
}
/**
* @param tmDb
* the tmDb to set
*/
public void setTmDb(List<DatabaseModelBean> tmDb) {
this.tmDb = tmDb;
}
/** @return the tbDb */
public List<DatabaseModelBean> getTbDb() {
return tbDb;
}
/**
* @param tbDb
* the tbDb to set
*/
public void setTbDb(List<DatabaseModelBean> tbDb) {
this.tbDb = tbDb;
}
public void propertyChange(PropertyChangeEvent arg0) {
}
/**
* 添加数据Banding监听
* @param propertyName
* @param listener
*/
public void addPropertyChangeListener(String propertyName, PropertyChangeListener listener) {
propertyChangeSupport.addPropertyChangeListener(propertyName, listener);
}
/**
* 注销数据Banding监听
* @param listener
*/
public void removePropertyChangeListener(PropertyChangeListener listener) {
propertyChangeSupport.removePropertyChangeListener(listener);
}
}
| 4,192 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
TmxNote.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/base_commons/net.heartsome.cat.common.core/src/net/heartsome/cat/common/bean/TmxNote.java | /**
* TmxNote.java
*
* Version information :
*
* Date:2013-1-25
*
* Copyright notice :
* 本文件及其附带的相关文件包含机密信息,仅限瀚特盛科技有限公司指定的,与本项目有关的内部人员和客户联络人员查阅和使用。
* 如果您不是本保密声明中指定的收件者,请立即销毁本文件,禁止对本文件或根据本文件中的内容采取任何其他行动,
* 包括但不限于:泄露本文件中的信息、以任何方式制作本文件全部或部分内容之副本、将本文件或其相关副本提供给任何其他人。
*/
package net.heartsome.cat.common.bean;
/**
* The TMX note node
* @author Jason
* @version
* @since JDK1.6
*/
public class TmxNote {
private String xmlLang;
private String encoding;
private String content;
public TmxNote() {
}
/**
* @param xmlLang
* Attribute
* @param encoding
* Attribute
* @param content
* The content of note Node
*/
public TmxNote(String xmlLang, String encoding, String content) {
this.xmlLang = xmlLang;
this.encoding = encoding;
this.content = content;
}
@Override
public boolean equals(Object obj) {
if(obj instanceof TmxNote){
TmxNote _obj = (TmxNote) obj;
if(_obj.content.equals(this.content)){
return true;
}
}
return false;
}
/** @return the xmlLang */
public String getXmlLang() {
return xmlLang;
}
/**
* @param xmlLang
* the xmlLang to set
*/
public void setXmlLang(String xmlLang) {
this.xmlLang = xmlLang;
}
/** @return the encoding */
public String getEncoding() {
return encoding;
}
/**
* @param encoding
* the encoding to set
*/
public void setEncoding(String encoding) {
this.encoding = encoding;
}
/** @return the content */
public String getContent() {
return content;
}
/**
* @param content
* the content to set
*/
public void setContent(String content) {
this.content = content;
}
}
| 2,016 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
TmxTU.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/base_commons/net.heartsome.cat.common.core/src/net/heartsome/cat/common/bean/TmxTU.java | package net.heartsome.cat.common.bean;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* TM DB Translation memory encapsulation
* @author jason
* @version
* @since JDK1.6
*/
public class TmxTU {
/** MTU PK */
private int tmId;
private String tuId;
/*** TU属性值 */
private List<TmxProp> props;
private List<TmxNote> notes;
private String creationUser;
private String creationDate;
private String changeDate;
private String changeUser;
private String creationTool;
private String creationToolVersion;
/** TU XMLElement Attributes */
private Map<String, String> attributes;
private TmxSegement source;
private TmxSegement target;
private List<TmxSegement> segments;
private TmxContexts contexts;
public TmxTU() {
}
public TmxTU(TmxSegement source, TmxSegement target) {
this.source = source;
this.target = target;
}
public TmxTU(String creationUser, String creationDate, String changeDate, String changeUser, TmxSegement source,
TmxSegement target) {
this.creationUser = creationUser;
this.creationDate = creationDate;
this.changeUser = changeUser;
this.changeDate = changeDate;
this.source = source;
this.target = target;
}
/**
* Set the value of tmId MTU PK
* @param newVar
* the new value of tmId
*/
public void setTmId(int newVar) {
tmId = newVar;
}
/**
* Get the value of tmId MTU PK
* @return the value of tmId
*/
public int getTmId() {
return tmId;
}
/**
* Set the value of attributeValues TU属性值(prop node)
* @param newVar
* the new value of attributeValues
*/
public void setProps(List<TmxProp> newVar) {
props = newVar;
}
/**
* check whether contain the Obj
* @param obj
* @return ;
*/
public boolean isContainsProp(TmxProp obj) {
if (props == null || props.size() == 0) {
return false;
}
if (props.contains(obj)) {
return true;
}
return false;
}
/**
* Append a new Prop node
* @param newProp
* ;
*/
public void appendProp(TmxProp newProp) {
if (props == null) {
props = new ArrayList<TmxProp>();
}
if (!props.contains(newProp)) {
props.add(newProp);
}
}
/**
* Get the value of attributeValues TU属性值
* @return the value of attributeValues
*/
public List<TmxProp> getProps() {
return props;
}
/**
* Get the prop by prop node attribute value
* @param type
* Node Attribute value
* @return did not find return null;
*/
public TmxProp getPropByType(String type) {
if (props == null || props.size() == 0) {
return null;
}
for (TmxProp prop : props) {
if (prop.getName().equals(type)) {
return prop;
}
}
return null;
}
/** @return the notes */
public List<TmxNote> getNotes() {
return notes;
}
/**
* Append a new Note node
* @param note
* ;
*/
public void appendNote(TmxNote note) {
if (notes == null) {
notes = new ArrayList<TmxNote>();
}
if (!notes.contains(note)) {
notes.add(note);
}
}
/**
* @param notes
* the notes to set
*/
public void setNotes(List<TmxNote> notes) {
this.notes = notes;
}
/**
* Set the value of creationUser
* @param newVar
* the new value of creationUser
*/
public void setCreationUser(String newVar) {
creationUser = newVar;
}
/**
* Get the value of creationUser
* @return the value of creationUser
*/
public String getCreationUser() {
return creationUser;
}
/**
* Set the value of creationDate
* @param newVar
* the new value of creationDate
*/
public void setCreationDate(String newVar) {
creationDate = newVar;
}
/**
* Get the value of creationDate
* @return the value of creationDate
*/
public String getCreationDate() {
return creationDate;
}
/**
* Set the value of changeDate
* @param newVar
* the new value of changeDate
*/
public void setChangeDate(String newVar) {
changeDate = newVar;
}
/**
* Get the value of changeDate
* @return the value of changeDate
*/
public String getChangeDate() {
return changeDate;
}
/**
* Set the value of changeUser
* @param newVar
* the new value of changeUser
*/
public void setChangeUser(String newVar) {
changeUser = newVar;
}
/**
* Get the value of changeUser
* @return the value of changeUser
*/
public String getChangeUser() {
return changeUser;
}
/**
* Set the value of source
* @param newVar
* the new value of source
*/
public void setSource(TmxSegement newVar) {
source = newVar;
}
/**
* Get the value of source
* @return the value of source
*/
public TmxSegement getSource() {
return source;
}
/**
* Set the value of target
* @param newVar
* the new value of target
*/
public void setTarget(TmxSegement newVar) {
target = newVar;
}
/**
* Get the value of target
* @return the value of target
*/
public TmxSegement getTarget() {
return target;
}
public List<TmxSegement> getSegments() {
return segments;
}
public void setSegments(List<TmxSegement> segments) {
this.segments = segments;
}
public void appendSegement(TmxSegement segment) {
if (segments == null) {
segments = new ArrayList<TmxSegement>();
}
segments.add(segment);
}
/** @return the tuId */
public String getTuId() {
return tuId;
}
/**
* @param tuId
* the tuId to set
*/
public void setTuId(String tuId) {
this.tuId = tuId;
}
/** @return the createtionTool */
public String getCreationTool() {
return creationTool;
}
/**
* @param createtionTool
* the createtionTool to set
*/
public void setCreationTool(String createtionTool) {
this.creationTool = createtionTool;
}
/** @return the creationToolVersion */
public String getCreationToolVersion() {
return creationToolVersion;
}
/**
* @param creationToolVersion
* the creationToolVersion to set
*/
public void setCreationToolVersion(String creationToolVersion) {
this.creationToolVersion = creationToolVersion;
}
/** @return the attributes */
public Map<String, String> getAttributes() {
return attributes;
}
/**
* @param attributes
* the attributes to set
*/
public void setAttributes(Map<String, String> attributes) {
this.attributes = attributes;
}
public void appendAttribute(String name, String value) {
if (this.attributes == null) {
attributes = new HashMap<String, String>();
}
attributes.put(name, value);
}
/** @return the contexts */
public TmxContexts getContexts() {
return contexts;
}
/**
* @param contexts
* the contexts to set
*/
public void setContexts(TmxContexts contexts) {
this.contexts = contexts;
}
/**
* @param contextName
* @see {@link TmxContexts#PRE_CONTEXT_NAME} {@link TmxContexts#NEXT_CONTEXT_NAME}
* @param contextVal
* ;
*/
public void appendContext(String contextName, String contextVal) {
if (contextVal == null || contextVal.length() == 0) {
return;
}
if (this.contexts == null) {
contexts = new TmxContexts();
}
if (contextName.equals(TmxContexts.PRE_CONTEXT_NAME)) {
contexts.appendPreContext(contextVal);
} else if (contextName.equals(TmxContexts.NEXT_CONTEXT_NAME)) {
contexts.appendNextContext(contextVal);
}
}
}
| 7,386 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
ColorConfigBean.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/base_commons/net.heartsome.cat.common.core/src/net/heartsome/cat/common/bean/ColorConfigBean.java | /**
* ViewerColorBean.java
*
* Version information :
*
* Date:2012-5-2
*
* Copyright notice :
* 本文件及其附带的相关文件包含机密信息,仅限瀚特盛科技有限公司指定的,与本项目有关的内部人员和客户联络人员查阅和使用。
* 如果您不是本保密声明中指定的收件者,请立即销毁本文件,禁止对本文件或根据本文件中的内容采取任何其他行动,
* 包括但不限于:泄露本文件中的信息、以任何方式制作本文件全部或部分内容之副本、将本文件或其相关副本提供给任何其他人。
*/
package net.heartsome.cat.common.bean;
import org.eclipse.swt.graphics.Color;
/**
* 视图中的相关颜色封装
* @author jason
* @version
* @since JDK1.6
*/
public class ColorConfigBean {
private Color ptColor;
private Color qtColor;
private Color mtColor;
private Color tm101Color;
private Color tm100Color;
private Color tm90Color;
private Color tm80Color;
private Color tm70Color;
private Color tm0Color;
private Color highlightedTermColor;
// 源文不同前景色
private Color srcDiffFgColor;
// 源文不同背景色
private Color srcDiffBgColor;
// 标记前景色
private Color tagFgColor;
// 标记背景色
private Color tagBgColor;
/** 错误标记色 */
private Color wrongTagColor;
/** 错误单词的颜色 */
private Color errorWordColor;
private static ColorConfigBean instance;
public static ColorConfigBean getInstance() {
if (instance == null) {
instance = new ColorConfigBean();
}
return instance;
}
private ColorConfigBean() {
}
public void release() {
if (ptColor != null && !ptColor.isDisposed()) {
ptColor.dispose();
}
if (mtColor != null && !mtColor.isDisposed()) {
mtColor.dispose();
}
if (qtColor != null && !qtColor.isDisposed()) {
qtColor.dispose();
}
if (tm101Color != null && !tm101Color.isDisposed()) {
tm101Color.dispose();
}
if (tm100Color != null && !tm100Color.isDisposed()) {
tm100Color.dispose();
}
if (tm90Color != null && !tm90Color.isDisposed()) {
tm90Color.dispose();
}
if (tm80Color != null && !tm80Color.isDisposed()) {
tm80Color.dispose();
}
if (tm70Color != null && !tm70Color.isDisposed()) {
tm70Color.dispose();
}
if (tm0Color != null && !tm0Color.isDisposed()) {
tm0Color.dispose();
}
if (srcDiffFgColor != null && !srcDiffFgColor.isDisposed()) {
srcDiffFgColor.dispose();
}
if (srcDiffBgColor != null && !srcDiffBgColor.isDisposed()) {
srcDiffBgColor.dispose();
}
if (tagFgColor != null && !tagFgColor.isDisposed()) {
tagFgColor.dispose();
}
if (tagBgColor != null && !tagBgColor.isDisposed()) {
tagBgColor.dispose();
}
if (wrongTagColor != null && !wrongTagColor.isDisposed()) {
wrongTagColor.dispose();
}
}
/** @return the ptColor */
public Color getPtColor() {
return ptColor;
}
/** @return the qtColor */
public Color getQtColor() {
return qtColor;
}
/** @return the mtColor */
public Color getMtColor() {
return mtColor;
}
/** @return the tm101Color */
public Color getTm101Color() {
return tm101Color;
}
/** @return the tm100Color */
public Color getTm100Color() {
return tm100Color;
}
/** @return the tm90Color */
public Color getTm90Color() {
return tm90Color;
}
/** @return the tm80Color */
public Color getTm80Color() {
return tm80Color;
}
/** @return the tm70Color */
public Color getTm70Color() {
return tm70Color;
}
/** @return the rm0Color */
public Color getTm0Color() {
return tm0Color;
}
/** @return the srcDiffFgColor */
public Color getSrcDiffFgColor() {
return srcDiffFgColor;
}
/** @return the srcDiffBgColor */
public Color getSrcDiffBgColor() {
return srcDiffBgColor;
}
/** @return the tagFgColor */
public Color getTagFgColor() {
return tagFgColor;
}
/** @return the tagBgColor */
public Color getTagBgColor() {
return tagBgColor;
}
/** @return the wrongTagColor */
public Color getWrongTagColor() {
return wrongTagColor;
}
/** @return the highlightedTermColor */
public Color getHighlightedTermColor() {
return highlightedTermColor;
}
public Color getErrorWordColor() {
return errorWordColor;
}
/**
* @param ptColor
* the ptColor to set
*/
public void setPtColor(Color ptColor) {
this.ptColor = ptColor;
}
/**
* @param qtColor
* the qtColor to set
*/
public void setQtColor(Color qtColor) {
this.qtColor = qtColor;
}
/**
* @param mtColor
* the mtColor to set
*/
public void setMtColor(Color mtColor) {
this.mtColor = mtColor;
}
/**
* @param tm101Color
* the tm101Color to set
*/
public void setTm101Color(Color tm101Color) {
this.tm101Color = tm101Color;
}
/**
* @param tm100Color
* the tm100Color to set
*/
public void setTm100Color(Color tm100Color) {
this.tm100Color = tm100Color;
}
/**
* @param tm90Color
* the tm90Color to set
*/
public void setTm90Color(Color tm90Color) {
this.tm90Color = tm90Color;
}
/**
* @param tm80Color
* the tm80Color to set
*/
public void setTm80Color(Color tm80Color) {
this.tm80Color = tm80Color;
}
/**
* @param tm70Color
* the tm70Color to set
*/
public void setTm70Color(Color tm70Color) {
this.tm70Color = tm70Color;
}
/**
* @param tm0Color
* the tm0Color to set
*/
public void setTm0Color(Color tm0Color) {
this.tm0Color = tm0Color;
}
/**
* @param highlightedTermColor
* the highlightedTermColor to set
*/
public void setHighlightedTermColor(Color highlightedTermColor) {
this.highlightedTermColor = highlightedTermColor;
}
/**
* @param srcDiffFgColor
* the srcDiffFgColor to set
*/
public void setSrcDiffFgColor(Color srcDiffFgColor) {
this.srcDiffFgColor = srcDiffFgColor;
}
/**
* @param srcDiffBgColor
* the srcDiffBgColor to set
*/
public void setSrcDiffBgColor(Color srcDiffBgColor) {
this.srcDiffBgColor = srcDiffBgColor;
}
/**
* @param tagFgColor
* the tagFgColor to set
*/
public void setTagFgColor(Color tagFgColor) {
this.tagFgColor = tagFgColor;
}
/**
* @param tagBgColor
* the tagBgColor to set
*/
public void setTagBgColor(Color tagBgColor) {
this.tagBgColor = tagBgColor;
}
/**
* @param wrongTagColor
* the wrongTagColor to set
*/
public void setWrongTagColor(Color wrongTagColor) {
this.wrongTagColor = wrongTagColor;
}
/**
* @param errorWordColor
* the errorWordColor to set
*/
public void setErrorWordColor(Color errorWordColor) {
this.errorWordColor = errorWordColor;
}
@Override
public String toString() {
StringBuffer sb = new StringBuffer();
return sb.append(ptColor.toString()).append("-").append(qtColor.toString()).append("-")
.append(mtColor.toString()).append("-").append("-").append(tm101Color.toString()).append("-")
.append(tm100Color.toString()).append("-").append(tm90Color.toString()).append("-")
.append(tm80Color.toString()).append("-").append(tm70Color.toString()).append("-")
.append(tm0Color.toString()).append("-").append(srcDiffFgColor.toString()).append("-")
.append(srcDiffBgColor.toString()).append("-").append(tagFgColor.toString()).append("-")
.append(tagBgColor.toString()).append("-").append(wrongTagColor.toString()).toString();
}
}
| 7,467 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
TmxHeader.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/base_commons/net.heartsome.cat.common.core/src/net/heartsome/cat/common/bean/TmxHeader.java | /**
* TmxHeader.java
*
* Version information :
*
* Date:2013-1-28
*
* Copyright notice :
* 本文件及其附带的相关文件包含机密信息,仅限瀚特盛科技有限公司指定的,与本项目有关的内部人员和客户联络人员查阅和使用。
* 如果您不是本保密声明中指定的收件者,请立即销毁本文件,禁止对本文件或根据本文件中的内容采取任何其他行动,
* 包括但不限于:泄露本文件中的信息、以任何方式制作本文件全部或部分内容之副本、将本文件或其相关副本提供给任何其他人。
*/
package net.heartsome.cat.common.bean;
/**
* @author Jason
* @version
* @since JDK1.6
*/
public class TmxHeader {
private String adminlang;
private String changedate;
private String changeid;
private String creationdate;
private String creationid;
private String creationtool;
private String creationtoolversion;
private String datatype;
/** container of Prop,Note,Ude (XML Element) */
private Object[] items;
private String oencoding;
private String otmf;
private String segtype;
private String srclang;
/** @return the adminlang */
public String getAdminlang() {
return adminlang;
}
/**
* @param adminlang
* the adminlang to set
*/
public void setAdminlang(String adminlang) {
this.adminlang = adminlang;
}
/** @return the changedate */
public String getChangedate() {
return changedate;
}
/**
* @param changedate
* the changedate to set
*/
public void setChangedate(String changedate) {
this.changedate = changedate;
}
/** @return the changeid */
public String getChangeid() {
return changeid;
}
/**
* @param changeid
* the changeid to set
*/
public void setChangeid(String changeid) {
this.changeid = changeid;
}
/** @return the creationdate */
public String getCreationdate() {
return creationdate;
}
/**
* @param creationdate
* the creationdate to set
*/
public void setCreationdate(String creationdate) {
this.creationdate = creationdate;
}
/** @return the creationid */
public String getCreationid() {
return creationid;
}
/**
* @param creationid
* the creationid to set
*/
public void setCreationid(String creationid) {
this.creationid = creationid;
}
/** @return the creationtool */
public String getCreationtool() {
return creationtool;
}
/**
* @param creationtool
* the creationtool to set
*/
public void setCreationtool(String creationtool) {
this.creationtool = creationtool;
}
/** @return the creationtoolversion */
public String getCreationtoolversion() {
return creationtoolversion;
}
/**
* @param creationtoolversion
* the creationtoolversion to set
*/
public void setCreationtoolversion(String creationtoolversion) {
this.creationtoolversion = creationtoolversion;
}
/** @return the datatype */
public String getDatatype() {
return datatype;
}
/**
* @param datatype
* the datatype to set
*/
public void setDatatype(String datatype) {
this.datatype = datatype;
}
/** @return the items */
public Object[] getItems() {
return items;
}
/**
* @param items
* the items to set
*/
public void setItems(Object[] items) {
this.items = items;
}
/** @return the oencoding */
public String getOencoding() {
return oencoding;
}
/**
* @param oencoding
* the oencoding to set
*/
public void setOencoding(String oencoding) {
this.oencoding = oencoding;
}
/** @return the otmf */
public String getOtmf() {
return otmf;
}
/**
* @param otmf
* the otmf to set
*/
public void setOtmf(String otmf) {
this.otmf = otmf;
}
/** @return the segtype */
public String getSegtype() {
return segtype;
}
/**
* @param segtype
* the segtype to set
*/
public void setSegtype(String segtype) {
this.segtype = segtype;
}
/** @return the srclang */
public String getSrclang() {
return srclang;
}
/**
* @param srclang
* the srclang to set
*/
public void setSrclang(String srclang) {
this.srclang = srclang;
}
}
| 4,201 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
DatabaseModelBean.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/base_commons/net.heartsome.cat.common.core/src/net/heartsome/cat/common/bean/DatabaseModelBean.java | /**
* DataBaseModelBean.java
*
* Version information :
*
* Date:Oct 24, 2011
*
* Copyright notice :
* 本文件及其附带的相关文件包含机密信息,仅限瀚特盛科技有限公司指定的,与本项目有关的内部人员和客户联络人员查阅和使用。
* 如果您不是本保密声明中指定的收件者,请立即销毁本文件,禁止对本文件或根据本文件中的内容采取任何其他行动,
* 包括但不限于:泄露本文件中的信息、以任何方式制作本文件全部或部分内容之副本、将本文件或其相关副本提供给任何其他人。
*/
package net.heartsome.cat.common.bean;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
/**
* 数据库管理模块中对应的
* @author Jason
* @version
* @since JDK1.6
*/
public class DatabaseModelBean implements PropertyChangeListener {
/** 在列表中的编号 */
private String id;
/** 数据库类型 */
private String dbType;
/** 数据库名称 */
private String dbName;
/** 数据库实例(Oracle) */
private String instance;
/** 服务器 */
private String host;
/** 端口号 */
private String port;
/** 用户名 */
private String userName;
/** 密码 */
private String password;
/** 数据存放路径(internalDB) */
private String itlDBLocation;
/** 库中的内容是否适用于项目 */
private boolean hasMatch;
private boolean isDefault;
private PropertyChangeSupport propertyChangeSupport = new PropertyChangeSupport(this);
/**
* constructor
*/
public DatabaseModelBean() {
this.dbName = "";
this.dbType = "";
this.host = "";
this.port = "";
this.instance = "";
this.itlDBLocation = "";
this.password = "";
this.userName = "";
this.hasMatch = false;
this.isDefault = false;
}
/** @return the id */
public String getId() {
return id;
}
/**
* @param id
* the id to set
*/
public void setId(String id) {
propertyChangeSupport.firePropertyChange("id", this.id, this.id = id);
}
/** @return the dbType */
public String getDbType() {
return dbType;
}
/**
* @param dbType
* the dbType to set
*/
public void setDbType(String dbType) {
propertyChangeSupport.firePropertyChange("dbType", this.dbType, this.dbType = dbType);
}
/** @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 instance */
public String getInstance() {
return instance;
}
/**
* @param instance
* the instance to set
*/
public void setInstance(String instance) {
propertyChangeSupport.firePropertyChange("instance", this.instance, this.instance = instance);
}
/** @return the host */
public String getHost() {
return host;
}
/**
* @param host
* the host to set
*/
public void setHost(String host) {
propertyChangeSupport.firePropertyChange("host", this.host, this.host = host);
}
/** @return the port */
public String getPort() {
return port;
}
/**
* @param port
* the port to set
*/
public void setPort(String port) {
propertyChangeSupport.firePropertyChange("port", this.port, this.port = port);
}
/** @return the userName */
public String getUserName() {
return userName;
}
/**
* @param userName
* the userName to set
*/
public void setUserName(String userName) {
propertyChangeSupport.firePropertyChange("userName", this.userName, this.userName = userName);
}
/** @return the password */
public String getPassword() {
return password;
}
/**
* @param password
* the password to set
*/
public void setPassword(String password) {
propertyChangeSupport.firePropertyChange("password", this.password, this.password = password);
}
/** @return the itlDBLocation */
public String getItlDBLocation() {
return itlDBLocation;
}
/**
* @param itlDBLocation
* the itlDBLocation to set
*/
public void setItlDBLocation(String itlDBLocation) {
propertyChangeSupport.firePropertyChange("itlDBLocation", this.itlDBLocation,
this.itlDBLocation = itlDBLocation);
}
/** @return the hasMatch */
public boolean isHasMatch() {
return hasMatch;
}
/**
* @param hasMatch
* the hasMatch to set
*/
public void setHasMatch(boolean hasMatch) {
propertyChangeSupport.firePropertyChange("itlDBLocation", this.itlDBLocation, this.hasMatch = hasMatch);
}
/** @return isDefault */
public boolean isDefault() {
return isDefault;
}
/**
* 设置当前数据库是不是默认数据库
* @param isDefault
* the default to set
*/
public void setDefault(boolean isDefault) {
propertyChangeSupport.firePropertyChange("isDefault", this.isDefault, this.isDefault = isDefault);
}
public void addPropertyChangeListener(String propertyName, PropertyChangeListener listener) {
propertyChangeSupport.addPropertyChangeListener(propertyName, listener);
}
public void removePropertyChangeListener(PropertyChangeListener listener) {
propertyChangeSupport.removePropertyChangeListener(listener);
}
public void propertyChange(PropertyChangeEvent arg0) {
}
/**
* 将当前DatabaseModelBean转化为MetaData
* @return {@link MetaData} 通过该MetaData获取数据库连接;
*/
public MetaData toDbMetaData() {
MetaData metaData = new MetaData();
metaData.setDbType(this.getDbType());
metaData.setDatabaseName(this.getDbName());
metaData.setDataPath(this.getItlDBLocation());
metaData.setInstance(this.getInstance());
metaData.setServerName(this.getHost());
metaData.setPort(this.getPort());
metaData.setUserName(this.getUserName());
metaData.setPassword(this.getPassword());
return metaData;
}
/**
* 将数据库元数据转化为当前实例
* @param metaData
* @return ;
*/
public void metaDatatToBean(MetaData metaData){
this.setDbType(metaData.getDbType());
this.setDbName(metaData.getDatabaseName());
this.setInstance(metaData.getInstance());
this.setHost(metaData.getServerName());
this.setPort(metaData.getPort());
this.setUserName(metaData.getUserName());
this.setPassword(metaData.getPassword());
this.setItlDBLocation(metaData.getDataPath());
}
/**
* 将当前实例的内容拷贝到a中.a中的内容将被覆盖
* @return ;
*/
public DatabaseModelBean copyToOtherIntance(DatabaseModelBean a){
a.setId(this.getId());
a.setDbType(this.getDbType());
a.setDbName(this.getDbName());
a.setInstance(this.getInstance());
a.setHost(this.getHost());
a.setPort(this.getPort());
a.setUserName(this.getUserName());
a.setPassword(this.getPassword());
a.setItlDBLocation(this.getItlDBLocation());
a.setHasMatch(this.isHasMatch());
a.setDefault(this.isDefault);
return a;
}
}
| 7,012 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
FileManager.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/base_commons/net.heartsome.cat.common.core/src/net/heartsome/cat/common/file/FileManager.java | package net.heartsome.cat.common.file;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;
import net.heartsome.cat.common.core.resource.Messages;
/**
* 对文件进行操作的工具类
* @author peason
* @version
* @since JDK1.6
*/
public class FileManager {
/**
* 创建压缩包
* @param baseDir
* 所要压缩的根目录(包含绝对路径)
* @param zos
* @param removeFolderPath
* 所排除的目录名或文件名(此目录为 baseDir 的子目录)
* @throws Exception
* ;
*/
public void createZip(String baseDir, ZipOutputStream zos, String removeFolderPath) throws Exception {
List<String> lstRemoveFolderPath = new ArrayList<String>();
lstRemoveFolderPath.add(removeFolderPath);
createZip(baseDir, zos, lstRemoveFolderPath);
}
/**
* 创建压缩包
* @param baseDir
* 所要压缩的根目录(包含绝对路径)
* @param zos
* @param lstRemoveFolderPath
* 所排除的目录名或文件名集合(目录为 baseDir 的子目录)
* @throws Exception
* ;
*/
public void createZip(String baseDir, ZipOutputStream zos, List<String> lstRemoveFolderPath) throws Exception {
if (zos == null) {
return;
}
File folderObject = new File(baseDir);
if (folderObject.exists()) {
List<File> fileList = getSubFiles(new File(baseDir), lstRemoveFolderPath);
ZipEntry ze = null;
byte[] buf = new byte[1024];
int readLen = 0;
for (int i = 0; i < fileList.size(); i++) {
File f = (File) fileList.get(i);
// 创建一个ZipEntry,并设置Name和其它的一些属性
ze = new ZipEntry(getAbsFileName(baseDir, f));
ze.setSize(f.length());
ze.setTime(f.lastModified());
// 将ZipEntry加到zos中,再写入实际的文件内容
zos.putNextEntry(ze);
InputStream is = new BufferedInputStream(new FileInputStream(f));
while ((readLen = is.read(buf, 0, 1024)) != -1) {
zos.write(buf, 0, readLen);
}
is.close();
}
} else {
throw new Exception(MessageFormat.format(Messages.getString("file.FileManager.msg1"),
folderObject.getAbsolutePath()));
}
}
/**
* 将文件添加到压缩包中
* @param zos
* @param baseDir
* 压缩包目录名
* @param sourceFileName
* 压缩文件的绝对路径
* @throws Exception
* ;
*/
public void addFileToZip(ZipOutputStream zos, String baseDir, String sourceFileName) throws Exception {
if (zos == null) {
return;
}
File sourceFile = new File(sourceFileName);
byte[] buf = new byte[1024];
ZipEntry ze = null;
// 创建一个ZipEntry,并设置Name和其它的一些属性
ze = new ZipEntry(getAbsFileName(baseDir, sourceFile));
ze.setSize(sourceFile.length());
ze.setTime(sourceFile.lastModified());
// 将ZipEntry加到zos中,再写入实际的文件内容
zos.putNextEntry(ze);
InputStream is = new BufferedInputStream(new FileInputStream(sourceFile));
int readLen = -1;
while ((readLen = is.read(buf, 0, 1024)) != -1) {
zos.write(buf, 0, readLen);
}
zos.flush();
is.close();
zos.closeEntry();
}
/**
* 对压缩包解压
* @param sourceZip
* 压缩包路径
* @param outFileName
* 解压路径
* @throws IOException
* ;
*/
public void releaseZipToFile(String sourceZip, String outFileName) throws IOException {
ZipFile zfile = new ZipFile(sourceZip);
@SuppressWarnings("rawtypes")
Enumeration zList = zfile.entries();
ZipEntry ze = null;
byte[] buf = new byte[1024];
while (zList.hasMoreElements()) {
// 从ZipFile中得到一个ZipEntry
ze = (ZipEntry) zList.nextElement();
if (ze.isDirectory()) {
continue;
}
// 以ZipEntry为参数得到一个InputStream,并写到OutputStream中
OutputStream os = new BufferedOutputStream(new FileOutputStream(getRealFileName(outFileName, ze.getName())));
InputStream is = new BufferedInputStream(zfile.getInputStream(ze));
int readLen = 0;
while ((readLen = is.read(buf, 0, 1024)) != -1) {
os.write(buf, 0, readLen);
}
is.close();
os.close();
}
zfile.close();
}
/**
* 取得指定目录下的所有文件列表,包括子目录.
* @param baseDir
* File 指定的目录
* @param lstRemoveFolerPath
* 排除的目录名或文件名
* @return 包含java.io.File的List
*/
public List<File> getSubFiles(File baseDir, List<String> lstRemoveFolerPath) {
List<File> ret = new ArrayList<File>();
// File base=new File(baseDir);
File[] tmp = baseDir.listFiles();
String filePath;
tmpLoop: for (int i = 0; i < tmp.length; i++) {
filePath = tmp[i].getAbsolutePath();
if (lstRemoveFolerPath != null && lstRemoveFolerPath.size() > 0) {
for (String path : lstRemoveFolerPath) {
if (filePath.startsWith(path)) {
continue tmpLoop;
}
}
}
if (tmp[i].isFile()) {
ret.add(tmp[i]);
}
if (tmp[i].isDirectory()) {
ret.addAll(getSubFiles(tmp[i], lstRemoveFolerPath));
}
}
return ret;
}
/**
* 给定根目录,返回一个相对路径所对应的实际文件名.
* @param baseDir
* 指定根目录
* @param absFileName
* 相对路径名,来自于ZipEntry中的name
* @return java.io.File 实际的文件
*/
private File getRealFileName(String baseDir, String absFileName) {
// String[] dirs = absFileName.split("/");
// File ret = new File(baseDir);
// if (dirs.length > 1) {
// for (int i = 0; i < dirs.length - 1; i++) {
// ret = new File(ret, dirs[i]);
// }
// }
// if (!ret.exists()) {
// ret.mkdirs();
// }
// ret = new File(ret, dirs[dirs.length - 1]);
// return ret;
String[] dirs = absFileName.split("/");
File ret = new File(baseDir);
if (!ret.exists()) {
ret.mkdirs();
}
if ("/".equals(System.getProperty("file.separator"))) {
for (int i = 0; i < dirs.length; i++) {
dirs[i] = dirs[i].replace("\\", "/");
}
}
if (dirs.length >= 1) {
for (int i = 0; i < dirs.length - 1; i++) {
ret = new File(ret, dirs[i]);
}
if (!ret.exists()) {
ret.mkdirs();
}
ret = new File(ret, dirs[dirs.length - 1]);
if(!ret.exists()){
File p = ret.getParentFile();
if(!p.exists()){
p.mkdirs();
}
}
}
return ret;
}
/**
* 给定根目录,返回另一个文件名的相对路径,用于zip文件中的路径.
* @param baseDir
* java.lang.String 根目录
* @param realFileName
* java.io.File 实际的文件名
* @return 相对文件名
*/
private String getAbsFileName(String baseDir, File realFileName) {
File real = realFileName;
File base = new File(baseDir);
String ret = real.getName();
while (true) {
real = real.getParentFile();
if (real == null)
break;
if (real.equals(base))
break;
else {
ret = real.getName() + "/" + ret;
}
}
return ret;
}
/**
* 删除文件,如果 file 代表的为目录,则删除此目录和目录下的所有文件
* @param file
*/
public void deleteFileOrFolder(File file) {
if (file.exists()) {
if (file.isFile()) {
file.delete();
} else if (file.isDirectory()) {
File files[] = file.listFiles();
for (int i = 0; i < files.length; i++) {
this.deleteFileOrFolder(files[i]);
}
}
file.delete();
}
}
}
| 7,791 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
LanguageConfiger.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/base_commons/net.heartsome.cat.common.core/src/net/heartsome/cat/common/file/LanguageConfiger.java | /**
* LangugeConfiger.java
*
* Version information :
*
* Date:Mar 20, 2012
*
* Copyright notice :
* 本文件及其附带的相关文件包含机密信息,仅限瀚特盛科技有限公司指定的,与本项目有关的内部人员和客户联络人员查阅和使用。
* 如果您不是本保密声明中指定的收件者,请立即销毁本文件,禁止对本文件或根据本文件中的内容采取任何其他行动,
* 包括但不限于:泄露本文件中的信息、以任何方式制作本文件全部或部分内容之副本、将本文件或其相关副本提供给任何其他人。
*/
package net.heartsome.cat.common.file;
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 net.heartsome.cat.common.core.CoreActivator;
import net.heartsome.cat.common.core.resource.Messages;
import net.heartsome.cat.common.locale.Language;
import net.heartsome.xml.vtdimpl.VTDUtils;
import org.eclipse.core.runtime.FileLocator;
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;
/**
* 语言配置,实现从配置文件中存取相应的语言配置,语言code唯一
* @author Jason
* @version
* @since JDK1.6
*/
public class LanguageConfiger {
private VTDUtils vu;
private File langConfigFile;
private AutoPilot ap;
private static final Logger LOGGER = LoggerFactory.getLogger(LanguageConfiger.class);
/**
* 构造器,如果文件不存在先构建文件,再用vtd解析.
*/
public LanguageConfiger() {
String bundlePath;
try {
bundlePath = FileLocator.toFileURL(CoreActivator.getDefault().getBundle().getEntry("")).getPath();
this.langConfigFile = new File(bundlePath + CoreActivator.LANGUAGE_CODE_PATH);
} catch (IOException e) {
LOGGER.error("", e);
}
parseFile();
}
private void parseFile() {
VTDGen vg = new VTDGen();
try {
if (vg.parseFile(langConfigFile.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);
}
}
/**
* 返回所有语言列表,key:code,value:<code>Language</code>
*/
public Map<String, Language> getAllLanguage() {
Map<String, Language> result = new HashMap<String, Language>();
AutoPilot tempAp = new AutoPilot(vu.getVTDNav());
String codeAttr = "code";
String bidiAttr = "bidi";
String imgAttr = "image";
String bidiYes = "Yes";
try {
tempAp.selectXPath("/languages/lang");
while (tempAp.evalXPath() != -1) {
Map<String, String> attrs = vu.getCurrentElementAttributs();
String code = attrs.get(codeAttr);
String bidi = attrs.get(bidiAttr);
String img = attrs.get(imgAttr);
String langName = vu.getElementPureText();
boolean isBidi = false;
if (code != null && langName != null) {
if (bidi != null && bidi.equals(bidiYes)) {
isBidi = true;
}
result.put(code, new Language(code, langName, img == null ? "" : img, isBidi));
}
}
} catch (XPathParseException e) {
LOGGER.error("", e);
} catch (XPathEvalException e) {
LOGGER.error("", e);
} catch (NavException e) {
LOGGER.error("", e);
}
return result;
}
/**
* 返回Code对应的Language对象,如果在配置中找到则返回null
* @param code
* @return ;
*/
public Language getLanguageByCode(String code) {
AutoPilot tempAp = new AutoPilot(vu.getVTDNav());
String bidiAttr = "bidi";
String imgAttr = "image";
String bidiYes = "Yes";
try {
tempAp.selectXPath("/languages/lang[@code='" + code + "']");
if (tempAp.evalXPath() != -1) {
Map<String, String> attrs = vu.getCurrentElementAttributs();
String bidi = attrs.get(bidiAttr);
String img = attrs.get(imgAttr);
String langName = vu.getElementPureText();
boolean isBidi = false;
if (code != null && langName != null) {
if (bidi != null && bidi.equals(bidiYes)) {
isBidi = true;
}
return new Language(code, langName, img == null ? "" : img, isBidi);
}
}
} catch (XPathParseException e) {
LOGGER.error("", e);
} catch (XPathEvalException e) {
LOGGER.error("", e);
} catch (NavException e) {
LOGGER.error("", e);
}
return null;
}
/**
* 返回一组语言Code对应的<code>Language</code>对象,如果此Code在语言配置中未找到,此Language对象只保存Code
* @param codeList
* @return ;
*/
public List<Language> getLanuagesByCodes(List<String> codeList) {
List<Language> result = new ArrayList<Language>();
for (String code : codeList) {
Language lang = getLanguageByCode(code);
if (lang == null) {
lang = new Language(code, "", "", false);
}
result.add(lang);
}
return result;
}
/**
* 通过Code,更新一种语言
* @param code
* 语言代码
* @param newLanguage
* 更新后的语言;
*/
public void updateLanguageByCode(String code, Language newLanguage) {
String newValue = generateLangNode(newLanguage);
XMLModifier xm = vu.update("/languages/lang[@code='" + code + "']", newValue);
try {
vu.bind(xm.outputAndReparse());
saveToFile(xm, langConfigFile);
} catch (Exception e) {
LOGGER.error(Messages.getString("file.LanguageConfiger.logger1"), e);
}
}
public void deleteLanguageByCode(String code) {
if (code != null && !code.equals("")) {
try {
XMLModifier xm = vu.delete("/languages/lang[@code='" + code + "']");
vu.bind(xm.outputAndReparse());
saveToFile(xm, langConfigFile);
} catch (Exception e) {
LOGGER.error(Messages.getString("file.LanguageConfiger.logger2"), e);
}
}
}
/**
* 添加一种语言
* @param newLanguage
* ;
*/
public void addLanguage(Language newLanguage) {
String content = generateLangNode(newLanguage);
if (!content.equals("")) {
try {
XMLModifier xm = vu.insert("/languages/text()", content);
vu.bind(xm.outputAndReparse());
saveToFile(xm, langConfigFile);
} catch (Exception e) {
LOGGER.error(Messages.getString("file.LanguageConfiger.logger3"), e);
}
ap.resetXPath();
}
}
private String generateLangNode(Language language) {
String img = language.getImagePath();
if (img == null) {
img = "";
}
return "<lang bidi=\"" + language.isBidi() + "\" code=\"" + language.getCode() + "\" image=\"" + img + "\">"
+ language.getName() + "</lang>";
}
/**
* 保存文件
* @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);
} catch (TranscodeException e) {
LOGGER.error("", e);
} catch (IOException e) {
LOGGER.error("", e);
}
return false;
}
}
| 7,523 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
XLFValidator.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/base_commons/net.heartsome.cat.common.core/src/net/heartsome/cat/common/file/XLFValidator.java | /**
* XlLFValidator.java
*
* Version information :
*
* Date:2012-5-25
*
* Copyright notice :
* 本文件及其附带的相关文件包含机密信息,仅限瀚特盛科技有限公司指定的,与本项目有关的内部人员和客户联络人员查阅和使用。
* 如果您不是本保密声明中指定的收件者,请立即销毁本文件,禁止对本文件或根据本文件中的内容采取任何其他行动,
* 包括但不限于:泄露本文件中的信息、以任何方式制作本文件全部或部分内容之副本、将本文件或其相关副本提供给任何其他人。
*/
package net.heartsome.cat.common.file;
import java.io.File;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Vector;
import net.heartsome.cat.common.core.Constant;
import net.heartsome.cat.common.core.resource.Messages;
import net.heartsome.cat.common.locale.Language;
import net.heartsome.cat.common.locale.LocaleService;
import net.heartsome.cat.common.resources.ResourceUtils;
import net.heartsome.xml.vtdimpl.VTDUtils;
import org.eclipse.core.filesystem.URIUtil;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.dialogs.MessageDialogWithToggle;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.ximpleware.AutoPilot;
import com.ximpleware.ModifyException;
import com.ximpleware.NavException;
import com.ximpleware.VTDGen;
import com.ximpleware.VTDNav;
import com.ximpleware.XMLModifier;
import com.ximpleware.XPathEvalException;
import com.ximpleware.XPathParseException;
/**
* @author jason
* @version
* @since JDK1.6
*/
public class XLFValidator {
public static Logger logger = LoggerFactory.getLogger(XLFValidator.class);
private static Shell shell;
public static boolean blnMsg1 = false;
public static boolean blnIsOpenConfirmSrc = false;
/** 选择不再询问时,点击的按钮类型 */
public static boolean blnIsOpenConfirmSrcY = false;
public static boolean blnIsOpenConfirmTgt = false;
/** 选择不再询问时,点击的按钮类型 */
public static boolean blnIsOpenConfirmTgtY = false;
private static HashMap<String, Object[]> mapProjectLang = new HashMap<String, Object[]>();
/**
* 验证 XLIFF 文件的语言对是否与项目的语言对一致。
* @param iFile
* ;
* @throws XPathEvalException
* @throws XPathParseException
* @throws NavException
*/
public static boolean validateXliffFile(IFile iFile) {
shell = Display.getDefault().getActiveShell();
try {
Object[] arrObj = getProjectLang(iFile);
if (arrObj == null) {
return false;
}
String xlfFolderPath = iFile.getProject().getFullPath().append(Constant.FOLDER_XLIFF).toOSString();
String xlfFullPath = iFile.getFullPath().toOSString();
if (!xlfFullPath.startsWith(xlfFolderPath)
|| iFile.getParent().getFullPath().toOSString().equals(xlfFolderPath)) {
// 该 XLIFF 文件是 XLIFF 目录的直接子文件或者不在 XLIFF 的目录下
if (!blnMsg1) {
MessageDialogWithToggle dialog = MessageDialogWithToggle.openInformation(shell,
Messages.getString("file.XLFValidator.msgTitle"),
MessageFormat.format(Messages.getString("file.XLFValidator.msg1"), xlfFullPath),
Messages.getString("file.XLFValidator.toggleStateMsg"), false, null, null);
blnMsg1 = dialog.getToggleState();
}
return false;
}
Language projectSrcLang = (Language) arrObj[0];
@SuppressWarnings("unchecked")
List<Language> lstProjectTgtLang = (List<Language>) arrObj[1];
// /test/XLIFF/zh-CN/split/test.xlf (zh-CN 在第三级目录下)
String parentName = xlfFullPath.split(System.getProperty("file.separator").replaceAll("\\\\", "\\\\\\\\"))[3];
Vector<String> languageVector = new Vector<String>();
languageVector.add(parentName);
if (LocaleService.verifyLanguages(languageVector)) {
boolean flag = false;
for (Language lang : lstProjectTgtLang) {
if (lang.getCode().equalsIgnoreCase(parentName)) {
flag = true;
break;
}
}
if (!flag) {
if (!blnMsg1) {
MessageDialogWithToggle dialog = MessageDialogWithToggle.openInformation(shell,
Messages.getString("file.XLFValidator.msgTitle"),
MessageFormat.format(Messages.getString("file.XLFValidator.msg2"), xlfFullPath),
Messages.getString("file.XLFValidator.toggleStateMsg"), false, null, null);
blnMsg1 = dialog.getToggleState();
}
return false;
}
} else {
if (!blnMsg1) {
MessageDialogWithToggle dialog = MessageDialogWithToggle.openInformation(shell,
Messages.getString("file.XLFValidator.msgTitle"),
MessageFormat.format(Messages.getString("file.XLFValidator.msg3"), xlfFullPath),
Messages.getString("file.XLFValidator.toggleStateMsg"), false, null, null);
blnMsg1 = dialog.getToggleState();
}
return false;
}
String xlfSrcLang = null;
String xlfTgtLang = null;
VTDGen vg = new VTDGen();
XMLModifier xm = null;
boolean isConfirmSrc = false;
boolean isConfirmTgt = false;
String fileOsPath = ResourceUtils.iFileToOSPath(iFile);
boolean result = false;
try {
result = vg.parseFile(fileOsPath, true);
} catch (Exception e) {
}
if (!result) {
MessageDialog.openError(shell, Messages.getString("file.XLFValidator.errorTitle"),
MessageFormat.format(Messages.getString("file.XLFValidator.parseError"), fileOsPath));
return false;
}
VTDNav vn = vg.getNav();
VTDUtils vu = new VTDUtils(vn);
AutoPilot ap = new AutoPilot(vn);
ap.declareXPathNameSpace("xml", VTDUtils.XML_NAMESPACE_URL);
ap.selectXPath("/xliff/file");
String original = null;
int tempi = ap.evalXPath();
if (tempi == -1) {
MessageDialog.openError(shell, Messages.getString("file.XLFValidator.errorTitle"),
MessageFormat.format(Messages.getString("file.XLFValidator.parseError"), fileOsPath));
return false;
}
do {
xlfSrcLang = vu.getCurrentElementAttribut("source-language", null);
xlfTgtLang = vu.getCurrentElementAttribut("target-language", null);
original = vu.getCurrentElementAttribut("original", null);
if (original == null || original.trim().isEmpty()) {
MessageDialog.openWarning(shell, Messages.getString("file.XLFValidator.warningTitle"),
MessageFormat.format(Messages.getString("file.XLFValidator.msg10"), xlfFullPath));
return false;
}
String msg = null;
// XLIFF 源语言为空或与项目源语言不一致;
if (xlfSrcLang == null || !xlfSrcLang.equalsIgnoreCase(projectSrcLang.getCode())) {
if (!blnIsOpenConfirmSrc && !isConfirmSrc) {
if (xlfSrcLang == null) {
msg = MessageFormat.format(Messages.getString("file.XLFValidator.msg4"), xlfFullPath,
projectSrcLang.getCode());
} else {
msg = MessageFormat.format(Messages.getString("file.XLFValidator.msg5"), xlfFullPath,
xlfSrcLang.toLowerCase(), projectSrcLang.getCode());
}
MessageDialogWithToggle dialog = new MessageDialogWithToggle(shell,
Messages.getString("file.XLFValidator.msgTitle2"), null, msg, MessageDialog.CONFIRM,
new String[] { IDialogConstants.YES_LABEL, IDialogConstants.NO_LABEL }, 0,
Messages.getString("file.XLFValidator.toggleStateMsg"), false);
int returnCode = dialog.open();
if (returnCode == IDialogConstants.YES_ID) {
isConfirmSrc = true;
blnIsOpenConfirmSrcY = true;
} else if (returnCode == IDialogConstants.NO_ID) {
isConfirmSrc = false;
blnIsOpenConfirmSrcY = false;
}
blnIsOpenConfirmSrc = dialog.getToggleState();
}
if ((isConfirmSrc || (blnIsOpenConfirmSrc && blnIsOpenConfirmSrcY)) && xlfSrcLang != null) {
xm = vu.update(null, xm, "/xliff/file[@original=\"" + original + "\"]/@source-language",
projectSrcLang.getCode(), VTDUtils.CREATE_IF_NOT_EXIST);
} else if (!isConfirmSrc && !(blnIsOpenConfirmSrc && blnIsOpenConfirmSrcY)) {
return false;
}
}
// XLIFF 目标语言为空,(且其所在的 XLIFF 一级子目录名称是项目的目标语言代码之一,已在上面验证)直接设置
if (xlfTgtLang == null || xlfSrcLang == null) {
// XLIFF 文件中源与目标都为空时,由于 VTD 要求不能在一个位置修改两次,因此使用下面的方式插入源与目标到 file 节点中
if (xlfTgtLang == null && xlfSrcLang == null) {
String attrFragment = new StringBuffer(" source-language=\"").append(projectSrcLang.getCode())
.append("\" target-language=\"").append(parentName).append("\"").toString(); // 构建属性片段,“
// attrName="attrValue"
// ”
long i = vn.getOffsetAfterHead(); // 得到开始标记的结束位置
if (xm == null) {
xm = new XMLModifier(vn);
}
if (vn.getEncoding() < VTDNav.FORMAT_UTF_16BE) {
xm.insertBytesAt((int) i - 1, attrFragment.getBytes());
} else {
xm.insertBytesAt(((int) i - 1) << 1, attrFragment.getBytes());
}
} else if (xlfTgtLang == null) {
xm = vu.update(null, xm, "/xliff/file[@original=\"" + original + "\"]/@target-language",
parentName, VTDUtils.CREATE_IF_NOT_EXIST);
} else if (xlfSrcLang == null) {
xm = vu.update(null, xm, "/xliff/file[@original=\"" + original + "\"]/@source-language",
projectSrcLang.getCode(), VTDUtils.CREATE_IF_NOT_EXIST);
}
}
if (xlfTgtLang != null) {
// XLIFF 目标语言非空,但未放在对应的目录下。
boolean flag = false;
for (Language lang : lstProjectTgtLang) {
if (lang.getCode().equalsIgnoreCase(xlfTgtLang)) {
flag = true;
break;
}
}
String message = null;
if (!flag) {
message = MessageFormat.format(Messages.getString("file.XLFValidator.msg6"), xlfFullPath,
xlfTgtLang, parentName);
} else if (!xlfTgtLang.equalsIgnoreCase(parentName)) {
message = MessageFormat.format(Messages.getString("file.XLFValidator.msg7"), xlfFullPath,
xlfTgtLang, parentName);
}
if (!blnIsOpenConfirmTgt && !isConfirmTgt && message != null) {
MessageDialogWithToggle dialog = new MessageDialogWithToggle(shell,
Messages.getString("file.XLFValidator.msgTitle2"), null, message,
MessageDialog.CONFIRM, new String[] { IDialogConstants.YES_LABEL,
IDialogConstants.NO_LABEL }, 0,
Messages.getString("file.XLFValidator.toggleStateMsg"), false);
int returnCode = dialog.open();
if (returnCode == IDialogConstants.YES_ID) {
isConfirmTgt = true;
blnIsOpenConfirmTgtY = true;
} else if (returnCode == IDialogConstants.NO_ID) {
isConfirmTgt = false;
blnIsOpenConfirmTgtY = false;
}
blnIsOpenConfirmTgt = dialog.getToggleState();
}
if ((blnIsOpenConfirmTgt && blnIsOpenConfirmTgtY) || isConfirmTgt) {
xm = vu.update(null, xm, "/xliff/file[@original=\"" + original + "\"]/@target-language",
parentName, VTDUtils.CREATE_IF_NOT_EXIST | VTDUtils.PILOT_TO_END);
// vu.bind(xm.outputAndReparse());
} else if (message != null) {
return false;
}
}
// Bug #2329:文件语言更改成项目语言时应同时更改 source 节点的 xml:lang 属性值,如果 target 节点有 xml:lang 属性,也要修改成项目语言
AutoPilot tempAp = new AutoPilot(vn);
tempAp.declareXPathNameSpace("xml", VTDUtils.XML_NAMESPACE_URL);
xm = vu.update(tempAp, xm, "/xliff/file[@original=\"" + original
+ "\"]/body//trans-unit/source/@xml:lang", projectSrcLang.getCode(),
VTDUtils.CREATE_IF_NOT_EXIST | VTDUtils.PILOT_TO_END);
xm = vu.update(tempAp, xm, "/xliff/file[@original=\"" + original
+ "\"]/body//trans-unit/target/@xml:lang", parentName, VTDUtils.PILOT_TO_END);
} while (ap.evalXPath() != -1);
if (xm != null) {
// vu.bind(xm.outputAndReparse());
vu.bind(vu.updateVTDNav(xm, ResourceUtils.iFileToOSPath(iFile)));
}
vg.clear();
iFile.getProject().refreshLocal(IResource.DEPTH_INFINITE, null);
} catch (XPathParseException e) {
e.printStackTrace();
logger.error(Messages.getString("file.XLFValidator.logger1"), e);
MessageDialog.openInformation(shell, Messages.getString("file.XLFValidator.msgTitle"),
Messages.getString("file.XLFValidator.msg8"));
return false;
} catch (XPathEvalException e) {
e.printStackTrace();
logger.error(Messages.getString("file.XLFValidator.logger1"), e);
MessageDialog.openInformation(shell, Messages.getString("file.XLFValidator.msgTitle"),
Messages.getString("file.XLFValidator.msg8"));
return false;
} catch (NavException e) {
e.printStackTrace();
logger.error(Messages.getString("file.XLFValidator.logger1"), e);
MessageDialog.openInformation(shell, Messages.getString("file.XLFValidator.msgTitle"),
Messages.getString("file.XLFValidator.msg8"));
return false;
} catch (CoreException e) {
logger.error("", e);
} catch (ModifyException e) {
logger.error("", e);
}
return true;
}
public static boolean validateXliffFile(String fileLocalPath) {
IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
IFile file = root.getFileForLocation(URIUtil.toPath(new File(fileLocalPath).toURI()));
if (file == null) {
Shell shell = Display.getDefault().getActiveShell();
MessageDialog.openError(shell, Messages.getString("file.XLFValidator.msgTitle"),
Messages.getString("file.XLFValidator.msg9"));
return false;
}
return validateXliffFile(file);
}
public static boolean validateXlifFileStr(List<String> files) {
for (String file : files) {
if (!validateXliffFile(file)) {
return false;
}
}
return true;
}
public static boolean validateXliffFile(File file) {
IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
IFile ifile = root.getFileForLocation(URIUtil.toPath(file.toURI()));
if (ifile == null) {
Shell shell = Display.getDefault().getActiveShell();
MessageDialog.openError(shell, Messages.getString("file.XLFValidator.msgTitle"),
Messages.getString("file.XLFValidator.msg9"));
return false;
}
return validateXliffFile(ifile);
}
public static boolean validateXlifFiles(List<File> files) {
for (File file : files) {
if (!validateXliffFile(file)) {
return false;
}
}
return true;
}
public static boolean validateXlifIFiles(List<IFile> files) {
for (IFile file : files) {
if (!validateXliffFile(file)) {
return false;
}
}
return true;
}
public static void resetFlag() {
blnMsg1 = false;
blnIsOpenConfirmSrc = false;
blnIsOpenConfirmSrcY = false;
blnIsOpenConfirmTgt = false;
blnIsOpenConfirmTgtY = false;
mapProjectLang.clear();
}
/**
* 获取 iFile 所在项目的源语言与目标语言
* @param iFile
* @return 数组中的第一个值为源语言,类型为 Language;第二个值为目标语言集合,类型为 List<Language>
* @throws NavException
* @throws XPathParseException
* @throws XPathEvalException
* ;
*/
private static Object[] getProjectLang(IFile iFile) throws NavException, XPathParseException, XPathEvalException {
String projectFilePath = iFile.getProject().getLocation().toOSString() + System.getProperty("file.separator")
+ ".config";
if (mapProjectLang.containsKey(projectFilePath)) {
return mapProjectLang.get(projectFilePath);
}
VTDGen vg = new VTDGen();
if (vg.parseFile(projectFilePath, true)) {
VTDNav vn = vg.getNav();
VTDUtils vu = new VTDUtils(vn);
AutoPilot ap = new AutoPilot(vn);
ap.selectXPath("/projectDescription/hs/language/source");
Object[] arrObj = new Object[2];
if (ap.evalXPath() != -1) {
String code = vu.getCurrentElementAttribut("code", "");
String name = vu.getElementContent();
String image = vu.getCurrentElementAttribut("image", "");
String isBidi = vu.getCurrentElementAttribut("isbidi", "No");
arrObj[0] = new Language(code, name, image, isBidi.equals("NO") ? false : true);
}
ap.selectXPath("/projectDescription/hs/language/target");
List<Language> targetLangs = new ArrayList<Language>();
while (ap.evalXPath() != -1) {
String code = vu.getCurrentElementAttribut("code", "");
String name = vu.getElementContent();
String image = vu.getCurrentElementAttribut("image", "");
String isBidi = vu.getCurrentElementAttribut("isbidi", "false");
targetLangs.add(new Language(code, name, image, isBidi.equals("false") ? false : true));
}
arrObj[1] = targetLangs;
return arrObj;
} else {
return null;
}
}
}
| 17,119 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
AbstractFileHandler.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/base_commons/net.heartsome.cat.common.core/src/net/heartsome/cat/common/file/AbstractFileHandler.java | package net.heartsome.cat.common.file;
import java.io.File;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
* 一个抽象的文件处理类。实现了文件处理接口中的创建文件历史访问列表方法。
*
* @author John Zhu
* @see net.heartsome.cat.common.file.FileHandler
*/
public abstract class AbstractFileHandler {
/**
* 打开一个指定文件名称的文件。
* @param filename 要打开的文件名。
* @return
* key = result,value 为 String 类型, 返回打开文件的结果。 1 成功, 0 失败。<br/>
* key = errorMsg,value 为 String 类型,返回错误消息。<br/>
* key = exception,value 为 Exception 类型,返回具体的异常实例。
* */
public abstract Map<String,Object> openFile(String filename);
/**
* 打开一个指定文件名称的文件。
* @param filename 要打开的文件名。
* @param tuCount 已统计的翻译单元数目,用于限制缓存大小。默认为 0。
* @return
* key = result,value 为 String 类型, 返回打开文件的结果。 1 成功, 0 失败。<br/>
* key = errorMsg,value 为 String 类型,返回错误消息。<br/>
* key = exception,value 为 Exception 类型,返回具体的异常实例。
* */
protected abstract Map<String,Object> openFile(String filename,int tuCount);
/**
* 打开一个指定文件实例的文件。
* @param file 要打开的文件实例。
* @return
* key = result,value 为 String 类型, 返回打开文件的结果。 1 成功, 0 失败。<br/>
* key = errorMsg,value 为 String 类型,返回错误消息。<br/>
* key = exception,value 为 Exception 类型,返回具体的异常实例。
* */
public abstract Map<String,Object> openFile(File file);
/**
* 打开一个指定文件实例的文件。
* @param file 要打开的文件实例。
* @param tuCount 已统计的翻译单元数目,用于限制缓存大小。默认为 0。
* @return
* key = result,value 为 String 类型, 返回打开文件的结果。 1 成功, 0 失败。<br/>
* key = errorMsg,value 为 String 类型,返回错误消息。<br/>
* key = exception,value 为 Exception 类型,返回具体的异常实例。
* */
protected abstract Map<String,Object> openFile(File file, int tuCount);
/**
* 打开一组指定文件名称的文件。
* @param files 要打开的一组文件名。
* @return
* key = result,value 为 String 类型, 返回打开文件的结果。 1 成功, 0 失败。<br/>
* key = errorMsg,value 为 String 类型,返回错误消息。<br/>
* key = exception,value 为 Exception 类型,返回具体的异常实例。
* */
public abstract Map<String,Object> openFiles(List<String> files);
/**
* 关闭指定文件名称的文件。
* @param filename 要关闭的文件名。
* @return
* key = result,value 为 String 类型, 返回关闭文件的结果。 1 成功, 0 失败。<br/>
* key = errorMsg,value 为 String 类型,返回错误消息。<br/>
* key = exception,value 为 Exception 类型,返回具体的异常实例。
* */
public abstract Map<String,Object> closeFile(String filename);
/**
* 关闭指定文件实例的文件。
* @param file 要关闭的文件实例。
* @return
* key = result,value 为 String 类型, 返回关闭文件的结果。 1 成功, 0 失败。<br/>
* key = errorMsg,value 为 String 类型,返回错误消息。<br/>
* key = exception,value 为 Exception 类型,返回具体的异常实例。
* */
public abstract Map<String,Object> closeFile(File file);
/**
* 关闭一组指定文件名称的文件。
* @param files 要关闭的一组文件名。
* @return
* key = result,value 为 String 类型, 返回关闭文件的结果。 1 成功, 0 失败。<br/>
* key = errorMsg,value 为 String 类型,返回错误消息。<br/>
* key = exception,value 为 Exception 类型,返回具体的异常实例。
* */
public abstract Map<String,Object> closeFiles(List<String> files);
/**
* 保存指定的源文件为目标文件。
* @param srcFile 源文件。<br/>
* @param tgtFile 目标文件。
* @return
* key = result,value 为 String 类型, 返回保存文件的结果。 1 成功, 0 失败。<br/>
* key = errorMsg,value 为 String 类型,返回错误消息。<br/>
* key = exception,value 为 Exception 类型,返回具体的异常实例。
* */
public abstract Map<String,Object> saveFile(String srcFile,String tgtFile);
/**
* 保存指定的源文件为目标文件。
* @param srcFile 源文件实例。<br/>
* @param tgtFile 目标文件实例。
* @return
* key = result,value 为 String 类型, 返回保存文件的结果。 1 成功, 0 失败。<br/>
* key = errorMsg,value 为 String 类型,返回错误消息。<br/>
* key = exception,value 为 Exception 类型,返回具体的异常实例。
* */
public abstract Map<String,Object> saveFile(File srcFile,File tgtFile);
/**
* 创建文件历史访问列表。
* @param initSize 容器初始化大小。
* @param maxSize 容器最大大小。
* @return 返回一个同步的有序的文件历史访问列表容器。<br/>
* key 为历史访问文件路径。<br/>
* value 为历史访问文件关闭时焦点所在的文本段或是术语的索引。
* */
public Map<String, String> createFileHistory(final int initSize,
final int maxSize) {
return Collections.synchronizedMap(new LinkedHashMap<String, String>(
initSize, 0.75f, true) {
private static final long serialVersionUID = 1L;
@SuppressWarnings("rawtypes")
public boolean removeEldestEntry(Map.Entry entry) {
return size() > maxSize;
}
});
}
}
| 5,840 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
AbstractOperator.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/base_commons/net.heartsome.cat.common.core/src/net/heartsome/cat/common/operator/AbstractOperator.java | package net.heartsome.cat.common.operator;
import java.util.Map;
public abstract class AbstractOperator {
public abstract void undo();
public abstract void redo();
public abstract void exit();
public abstract void setDocumentProperties(Map<String,Object> props);
public abstract Map<String,Object> getDocumentProperties();
public abstract void cut();
public abstract void copy();
public abstract void paste();
}
| 443 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
ResourceUtils.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/base_commons/net.heartsome.cat.common.core/src/net/heartsome/cat/common/resources/ResourceUtils.java | package net.heartsome.cat.common.resources;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import net.heartsome.cat.common.util.CommonFunction;
import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.Path;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IViewPart;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.part.FileEditorInput;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ResourceUtils {
private static final int DEFAULT_BUFFER_SIZE = 16 * 1024;
private static IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
private static Logger LOGGER = LoggerFactory.getLogger(ResourceUtils.class);
/**
* 得到某容器下(IContainer 对象)的指定后缀名的所有文件(包括子文件夹中的文件);
* <p>
* example:
* <li>getFiles(folder, files, "xlf", ".sdlxliff"); // 得到指定文件夹下的所有 XLIFF 文件</li>
* <li>getFiles(folder, files, "xlf", "tmx", "tbx"); // 得到指定文件夹下的所有 XLIFF、TMX、TBX 文件</li>
* </p>
* @param container
* 容器(IContainer 对象)
* @param files
* files 文件集合
* @param fileExtensions
* 文件后缀名
* @throws CoreException
* ;
*/
public static void getFiles(IContainer container, ArrayList<IFile> files, String... fileExtensions)
throws CoreException {
if (files == null) {
files = new ArrayList<IFile>();
}
IResource[] members = container.members();
for (IResource r : members) {
if (r instanceof IFile) {
if (fileExtensions == null || fileExtensions.length == 0
|| CommonFunction.containsIgnoreCase(fileExtensions, r.getFileExtension())) {
files.add((IFile) r);
}
} else if (r instanceof IFolder) {
getFiles((IFolder) r, files, fileExtensions);
}
}
}
/**
* 获取当前文件夹或项目下的所有xliff文件
* @param container
* @param files
* @throws CoreException
*/
public static void getXliffs(IContainer container, ArrayList<IFile> files) throws CoreException {
getFiles(container, files, CommonFunction.xlfExtesionArray);
}
/**
* 将指定的IFile转换成系统的完整路径
* @param iFile
* @return ;
*/
public static String iFileToOSPath(IFile iFile) {
return iFile.getLocation().toOSString();
}
/**
* 将一组IFile对象转换为系统的完整路径
* @param iFiles
* @return ;
*/
public static List<String> IFilesToOsPath(List<IFile> iFiles) {
List<String> list = new ArrayList<String>();
for (int i = 0; i < iFiles.size(); i++) {
list.add(iFileToOSPath(iFiles.get(i)));
}
return list;
}
/**
* 将 {@link org.eclipse.core.resources.IFile} 对象转换为 {@link java.io.File} 对象
* @param iFile
* {@link org.eclipse.core.resources.IFile} 对象
* @return {@link java.io.File} 对象;
*/
public static File iFileToFile(IFile iFile) {
return iFile.getLocation().toFile();
}
/**
* 将一组 {@link org.eclipse.core.resources.IFile} 对象转换为 {@link java.io.File} 对象
* @param iFiles
* {@link org.eclipse.core.resources.IFile} 对象集合
* @return {@link java.io.File} 对象集合;
*/
public static List<File> iFilesToFiles(List<IFile> iFiles) {
ArrayList<File> list = new ArrayList<File>();
for (int i = 0; i < iFiles.size(); i++) {
list.add(iFileToFile(iFiles.get(i)));
}
return list;
}
/**
* 将文件从一个地方复制到另一个地方 peason 2012-02-17
* @param srcPath
* @param dstPath
* @throws IOException
* ;
*/
public static void copyDirectory(File srcPath, File dstPath) throws IOException {
if (srcPath.isDirectory()) {
if (!dstPath.exists()) {
dstPath.mkdirs();
}
String files[] = srcPath.list();
for (int i = 0; i < files.length; i++) {
copyDirectory(new File(srcPath, files[i]), new File(dstPath, files[i]));
}
} else {
if (srcPath.exists()) {
InputStream in = new FileInputStream(srcPath);
OutputStream out = new FileOutputStream(dstPath);
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
}
}
}
/**
* 复制一个文件到另一个文件 --Robert 2013-04-10
* @param in
* 要复制的源文件
* @param out
* 要复制的目标文件
* @throws IOException
*/
public static void copyFile(File in, File out) throws IOException {
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
bis = new BufferedInputStream(new FileInputStream(in));
bos = new BufferedOutputStream(new FileOutputStream(out));
int available = bis.available();
available = available <= 0 ? DEFAULT_BUFFER_SIZE : available;
int chunkSize = Math.min(DEFAULT_BUFFER_SIZE, available);
byte[] buffer = new byte[chunkSize];
int byteread = 0;
while ((byteread = bis.read(buffer)) > 0) {
bos.write(buffer, 0, byteread);
}
} finally {
if (bis != null) {
bis.close();
}
if (bos != null) {
bos.close();
}
}
}
/**
* 得到工作空间中的路径。
* @param conversionItem
* @return ;
*/
public static String toWorkspacePath(String localPath) {
IFile file = root.getFileForLocation(new Path(localPath));
return file != null ? file.getFullPath().toOSString() : localPath;
}
/**
* 得到工作空间中的路径。
* @param conversionItem
* @return ;
*/
public static String toWorkspacePath(IPath localPath) {
IFile file = root.getFileForLocation(localPath);
return file != null ? file.getFullPath().toOSString() : localPath.toOSString();
}
public static IFile fileToIFile(String filePath) {
IPath path = Path.fromOSString(filePath);
IFile iFile = root.getFileForLocation(path);
return iFile;
}
/**
* 将一个file集合转换成IFile集合 robert 2012-05-06
* @param filePath
* @return
*/
public static List<IFile> filesToIFiles(List<File> fileList) {
List<IFile> iFileList = new ArrayList<IFile>();
for (File file : fileList) {
IPath path = Path.fromOSString(file.getAbsolutePath());
iFileList.add(root.getFileForLocation(path));
}
return iFileList;
}
/**
* 将 相对于工作空间的路径转换成 绝对路径 robert 2013-08-01
* @param fullpath
* @return
*/
public static String fullPathToLoction(String fullpath) {
return root.getLocation().append(fullpath).toOSString();
}
/**
* 刷新当前选择项目 ;
*/
public static void refreshCurentSelectProject() {
Display.getDefault().syncExec(new Runnable() {
@SuppressWarnings("unchecked")
public void run() {
IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
if (null == page) {
return;
}
IViewPart viewPart = page.findView("net.heartsome.cat.common.ui.navigator.view");
List<IProject> tempProjects = new ArrayList<IProject>();
if (null != viewPart) {
StructuredSelection selection = (StructuredSelection) viewPart.getSite().getSelectionProvider()
.getSelection();
if (null != selection && !selection.isEmpty()) {
List<Object> selects = selection.toList();
for (Object obj : selects) {
if (obj instanceof IResource) {
IResource resource = (IResource) obj;
IProject project = resource.getProject();
if (tempProjects.contains(project)) {
continue;
}
tempProjects.add(project);
}
}
}
}
IEditorPart activeEditor = page.getActiveEditor();
if (null != activeEditor) {
IEditorInput editorInput = activeEditor.getEditorInput();
if (null != editorInput && editorInput instanceof FileEditorInput) {
FileEditorInput fileEditorInput = (FileEditorInput) editorInput;
IFile file = fileEditorInput.getFile();
IProject project = file.getProject();
if (!tempProjects.contains(project)) {
tempProjects.add(project);
}
}
}
try {
for (IProject project : tempProjects) {
project.refreshLocal(IResource.DEPTH_INFINITE, null);
}
} catch (CoreException e) {
LOGGER.error("", e);
}
}
});
}
/**
* 刷新工作空间 ;
*/
public static void refreshWorkSpace() {
try {
root.refreshLocal(IResource.DEPTH_INFINITE, null);
} catch (CoreException e) {
LOGGER.error("", e);
}
}
}
| 9,212 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
TagStyle.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/base_commons/net.heartsome.cat.common.core/src/net/heartsome/cat/common/innertag/TagStyle.java | package net.heartsome.cat.common.innertag;
import net.heartsome.cat.common.core.CoreActivator;
import org.eclipse.jface.preference.IPreferenceStore;
public enum TagStyle {
/**
* 索引标记样式。仅显示标记索引。
*/
INDEX,
/**
* 简单标记样式。显示标记名称以及索引。
*/
SIMPLE,
/**
* 完整标记样式。显示标记全部内容以及索引。
*/
FULL;
public static TagStyle curStyle;
/**
* 取得下一个标记样式
* @return ;
*/
public TagStyle getNextStyle() {
switch (this) {
case INDEX: {
curStyle = SIMPLE;
return SIMPLE;
}
case SIMPLE: {
curStyle = FULL;
return FULL;
}
case FULL: {
curStyle = INDEX;
return INDEX;
}
default: {
curStyle = SIMPLE;
return SIMPLE;
}
}
}
/**
* 得到默认的标记样式
* @return ;
*/
public static TagStyle getDefault() {
IPreferenceStore store = CoreActivator.getDefault().getPreferenceStore();
int styleIndex = store.getInt("net.heartsome.cat.common.innertag.TagStyle.defaultStyle");
if (styleIndex == 0) {
curStyle = INDEX;
} else if (styleIndex == 1) {
curStyle = SIMPLE;
} else if (styleIndex == 2) {
curStyle = FULL;
}
return curStyle;
}
/**
* 得到默认的标记样式
* @param isInitCurStyle
* 是否初始化 curStyle 变量(只有 XLIFF 编辑器中的 curStyle 才需要初始化,其他的视图不需要,如记忆库匹配视图)
* @return ;
*/
public static TagStyle getDefault(boolean isInitCurStyle) {
if (isInitCurStyle) {
return getDefault();
} else {
return INDEX;
}
}
public static void setTagStyle(TagStyle style) {
curStyle = style;
IPreferenceStore store = CoreActivator.getDefault().getPreferenceStore();
int styleIndex = -1;
switch (style) {
case INDEX: {
styleIndex = 0;
break;
}
case SIMPLE: {
styleIndex = 1;
break;
}
case FULL: {
styleIndex = 2;
break;
}
default: {
styleIndex = 1;
break;
}
}
store.setValue("net.heartsome.cat.common.innertag.TagStyle.defaultStyle", styleIndex);
}
}
| 2,106 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
TagType.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/base_commons/net.heartsome.cat.common.core/src/net/heartsome/cat/common/innertag/TagType.java | package net.heartsome.cat.common.innertag;
public enum TagType {
/**
* 独立标记类型。即可以随意放置的标记。
*/
STANDALONE,
/**
* 开始标记类型。即必须放在成对的结束标记前的标记。
*/
START,
/**
* 结束标记类型。即必须放在成对的开始标记前的标记。
*/
END
}
| 340 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
InnerTagBean.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/base_commons/net.heartsome.cat.common.core/src/net/heartsome/cat/common/innertag/InnerTagBean.java | package net.heartsome.cat.common.innertag;
import org.apache.commons.lang.builder.EqualsBuilder;
/**
* 内部标记实体类
* @author weachy
* @version
* @since JDK1.5
*/
public class InnerTagBean {
/**
* 内部标记实体类
*/
public InnerTagBean() {
}
/**
* 内部标记实体类
* @param index
* 标记索引
* @param name
* 标记名
* @param content
* 标记内容
* @param type
* 标记类型
*/
public InnerTagBean(int index, String name, String content, TagType type) {
this(index, name, content, type, false);
}
/**
* 内部标记实体类
* @param index
* 标记索引
* @param name
* 标记名
* @param content
* 标记内容
* @param type
* 标记类型
* @param wrongTag
* 错误标记标识
*/
public InnerTagBean(int index, String name, String content, TagType type, boolean wrongTag) {
this.index = index;
this.name = name;
this.content = content;
this.type = type;
this.wrongTag = wrongTag;
}
/** 标记索引 */
private int index;
/** 标记名 */
private String name;
/** 标记内容 */
private String content;
/** 标记类型 */
private TagType type;
/** 错误标记 */
private boolean wrongTag;
/**
* 获取标记索引
* @return 标记索引;
*/
public int getIndex() {
return index;
}
/**
* 设置标记索引
* @param index
* 标记索引;
*/
public void setIndex(int index) {
this.index = index;
}
/**
* 获取标记名
* @return 标记名;
*/
public String getName() {
return name;
}
/**
* 设置标记名
* @param name
* 标记名;
*/
public void setName(String name) {
this.name = name;
}
/**
* 获取标记内容
* @return 标记内容;
*/
public String getContent() {
return content;
}
/**
* 设置标记内容
* @param content
* 标记内容;
*/
public void setContent(String content) {
this.content = content;
}
/**
* 获取标记类型
* @return 标记类型
*/
public TagType getType() {
return type;
}
/**
* 设置标记类型
* @param type
* 标记类型
*/
public void setType(TagType type) {
this.type = type;
}
/**
* 设置为错误标记
* @param wrongTag
* 错误标记标识 ;
*/
public void setWrongTag(boolean wrongTag) {
this.wrongTag = wrongTag;
}
/**
* 是否为错误标记
*/
public boolean isWrongTag() {
return wrongTag;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null || !(obj instanceof InnerTagBean)) {
return false;
}
InnerTagBean that = (InnerTagBean) obj;
return new EqualsBuilder().append(that.content, this.content).append(that.index, this.index).append(that.type,
this.type).isEquals();
}
}
| 2,903 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
IInnerTagFactory.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/base_commons/net.heartsome.cat.common.core/src/net/heartsome/cat/common/innertag/factory/IInnerTagFactory.java | package net.heartsome.cat.common.innertag.factory;
import java.util.List;
import net.heartsome.cat.common.innertag.InnerTagBean;
/**
* 内部标记工厂接口
* @author weachy
* @version
* @since JDK1.5
*/
public interface IInnerTagFactory {
/**
* 解析内部标记
* @param xml
* ;
*/
String parseInnerTag(String xml);
/**
* 得到提取内部标记之后的剩余文本。
* @return 提取内部标记之后的剩余文本;
*/
String getText();
/**
* 得到内部标记实体集合 <br/>
* <br/>
* 用法:使用 {@link #getText()} 得到提取标记后的剩余文本,包含占位符。<br/>
* 占位符是由 {@link IPlaceHolderBuilder} 接口的实现类创建。
* @return 内部标记实体集合。
*/
List<InnerTagBean> getInnerTagBeans();
}
| 811 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
PlaceHolderEditModeBuilder.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/base_commons/net.heartsome.cat.common.core/src/net/heartsome/cat/common/innertag/factory/PlaceHolderEditModeBuilder.java | package net.heartsome.cat.common.innertag.factory;
import java.util.List;
import java.util.regex.Pattern;
import net.heartsome.cat.common.innertag.InnerTagBean;
import net.heartsome.cat.common.util.UnicodeConverter;
public class PlaceHolderEditModeBuilder implements IPlaceHolderBuilder {
/** Unicode 前缀 */
private static final String UNICODE_PREFIX = "\\ua0";
/** 最小范围 */
public static final char MIN = '\ua000';
/** 最大范围 */
public static final char MAX = '\ua099';
/** 内部标记正则表达式 */
public static final Pattern PATTERN = Pattern.compile("[" + MIN + "-" + MAX + "]");
/**
* 由占位符得到索引
* @param innerTagBeans
* 此参数可忽略(null)。
* @param placeHolder
* 占位符
* @return 索引;
*/
public int getIndex(List<InnerTagBean> innerTagBeans, String placeHolder) {
String text = UnicodeConverter.convert(placeHolder);
if (text.length() == 6) {
try {
return Integer.parseInt(text.substring(4, 6), 16);
} catch (NumberFormatException e) {
return -1;
}
}
return -1;
}
/**
* 根据索引得到占位符
* @param innerTagBeans
* 此参数可忽略(null)。
* @param index
* 索引
* @return 占位符;
*/
public String getPlaceHolder(List<InnerTagBean> innerTagBeans, int index) {
String hexString = Integer.toHexString(index);
if (hexString.length() == 1) {
hexString = "0" + hexString;
}
String placeHolderString = UNICODE_PREFIX + hexString;
return UnicodeConverter.revert(placeHolderString);
}
}
| 1,591 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
IPlaceHolderBuilder.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/base_commons/net.heartsome.cat.common.core/src/net/heartsome/cat/common/innertag/factory/IPlaceHolderBuilder.java | package net.heartsome.cat.common.innertag.factory;
import java.util.List;
import net.heartsome.cat.common.innertag.InnerTagBean;
public interface IPlaceHolderBuilder {
/**
* 得到内部标记的占位符。
* @param innerTagBeans
* 内部标记集合
* @param index
* 当前标记所在索引
* @return 内部标记占位符;
*/
String getPlaceHolder(List<InnerTagBean> innerTagBeans, int index);
/**
* 根据内部标记占位符得到该内部标记在标记集合中的索引
* @param innerTagBeans
* 内部标记集合
* @param placeHolder
* 内部标记占位符
* @return 索引;
*/
int getIndex(List<InnerTagBean> innerTagBeans, String placeHolder);
}
| 741 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
DefaultPlaceHolderBuilder.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/base_commons/net.heartsome.cat.common.core/src/net/heartsome/cat/common/innertag/factory/DefaultPlaceHolderBuilder.java | package net.heartsome.cat.common.innertag.factory;
import java.util.List;
import net.heartsome.cat.common.innertag.InnerTagBean;
public class DefaultPlaceHolderBuilder implements IPlaceHolderBuilder {
public String getPlaceHolder(List<InnerTagBean> innerTagBeans, int index) {
return "";
}
public int getIndex(List<InnerTagBean> innerTagBeans, String placeHolder) {
return -1;
}
}
| 395 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
XliffInnerTagFactory.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/base_commons/net.heartsome.cat.common.core/src/net/heartsome/cat/common/innertag/factory/XliffInnerTagFactory.java | package net.heartsome.cat.common.innertag.factory;
import static net.heartsome.cat.common.innertag.TagType.END;
import static net.heartsome.cat.common.innertag.TagType.STANDALONE;
import static net.heartsome.cat.common.innertag.TagType.START;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Stack;
import net.heartsome.cat.common.innertag.InnerTagBean;
import net.heartsome.cat.common.innertag.TagStyle;
import net.heartsome.cat.common.innertag.TagType;
public class XliffInnerTagFactory implements IInnerTagFactory {
private static final List<String> standaloneTags = Arrays.asList("x", "bx", "ex", "ph");
private static final List<String> normalTags = Arrays.asList("g", "bpt", "ept", "ph", "it", "mrk", "sub");
private ArrayList<InnerTagBean> beans = new ArrayList<InnerTagBean>();
private String text;
private IPlaceHolderBuilder placeHolderCreater;
private Stack<Integer> indexStack = new Stack<Integer>(); // 索引集合
private int start = -1;
private int maxIndex = 0;
private boolean HasStartTag = false;
/**
* 内部标记工厂默认实现
* @param xml
* XML文本
*/
public XliffInnerTagFactory(String xml) {
this(xml, new DefaultPlaceHolderBuilder());
}
/**
* 内部标记工厂默认实现
* @param placeHolderCreater
* 占位符创建器
*/
public XliffInnerTagFactory(IPlaceHolderBuilder placeHolderCreater) {
this(null, placeHolderCreater);
}
/**
* 内部标记工厂默认实现
* @param xml
* XML文本
* @param placeHolderCreater
* 占位符创建器
*/
public XliffInnerTagFactory(String xml, IPlaceHolderBuilder placeHolderCreater) {
this.placeHolderCreater = placeHolderCreater;
this.text = parseInnerTag(xml);
}
public void reset() {
beans.clear();
text = null;
indexStack.clear(); // 索引集合
start = -1;
maxIndex = 0;
HasStartTag = false;
targetFlg = false;
}
public String getText() {
return text;
}
public List<InnerTagBean> getInnerTagBeans() {
ArrayList<InnerTagBean> innerTagBeans = new ArrayList<InnerTagBean>();
innerTagBeans.addAll(beans);
return innerTagBeans;
}
private boolean targetFlg = false;
public String parseInnerTag(String xml, boolean isEditMode) {
if (xml == null || xml.length() == 0) {
return "";
}
if (!indexStack.empty()) {
indexStack.clear();
}
StringBuffer sbOriginalValue = new StringBuffer(xml);
int beanSize = beans.size();
this.start = -1; // 起始索引
if (beans.size() > 0) {
targetFlg = true;
int index = -1;
for (int i = 0; i < beans.size(); i++) {
InnerTagBean bean = beans.get(i);
if (bean.getType() != TagType.STANDALONE) {
continue;
}
String content = bean.getContent();
index = sbOriginalValue.indexOf(content);
if (index > -1 && (isEditMode || TagStyle.curStyle != TagStyle.FULL)) {
String placeHolder = placeHolderCreater.getPlaceHolder(beans, i);
if(sbOriginalValue.indexOf(placeHolder) != -1){
// Bug #3044 不能正确显示插入的标记
// 已经存在,说明这个标记在译文中是重复的。
continue;
}
sbOriginalValue.replace(index, index + content.length(), placeHolder);
} else if (TagStyle.curStyle == TagStyle.FULL) {
this.start = index + content.length();
}
}
beanSize = beans.size();
} else {
beanSize = -1;
}
while ((start = sbOriginalValue.indexOf("<", start + 1)) > -1) {
int end = sbOriginalValue.indexOf(">", start + 1);
if (end > -1) {
String xmlTag = sbOriginalValue.substring(start, end + 1); // 提取出的内部标记xml形式的文本
String tagName = getTagName(xmlTag);
sbOriginalValue.replace(start, end + 1, xmlTag);
if (xmlTag.indexOf("/>", 1) > -1) { // 独立标签
if (standaloneTags.contains(tagName) || normalTags.contains(tagName)) {
if ("bx".equals(tagName)) {
addInnerTagBean(START, sbOriginalValue, xmlTag, tagName);
} else if ("ex".equals(tagName)) {
addInnerTagBean(END, sbOriginalValue, xmlTag, tagName);
} else {
addInnerTagBean(STANDALONE, sbOriginalValue, xmlTag, tagName);
}
}
} else if (xmlTag.indexOf("</") > -1) { // 结束标签
if (normalTags.contains(tagName)) {
addInnerTagBean(END, sbOriginalValue, xmlTag, tagName);
}
} else if (xmlTag.indexOf(">") > -1) { // 开始标签
if (normalTags.contains(tagName)) {
if ("bpt".equals(tagName)) {
int endIndex = sbOriginalValue.indexOf("</bpt>", start) + "</bpt>".length();
xmlTag = sbOriginalValue.substring(start, endIndex);
sbOriginalValue.replace(start, endIndex, xmlTag);
addInnerTagBean(START, sbOriginalValue, xmlTag, tagName);
} else if ("ept".equals(tagName)) {
int endIndex = sbOriginalValue.indexOf("</ept>", start) + "</ept>".length();
xmlTag = sbOriginalValue.substring(start, endIndex);
sbOriginalValue.replace(start, endIndex, xmlTag);
addInnerTagBean(END, sbOriginalValue, xmlTag, tagName);
} else if ("ph".equals(tagName) || "it".equals(tagName)) {
String tempTagName = "</" + tagName + ">";
int endIndex = sbOriginalValue.indexOf(tempTagName, start) + tempTagName.length();
xmlTag = sbOriginalValue.substring(start, endIndex);
sbOriginalValue.replace(start, endIndex, xmlTag);
addInnerTagBean(STANDALONE, sbOriginalValue, xmlTag, tagName);
} else {
addInnerTagBean(START, sbOriginalValue, xmlTag, tagName);
}
}
}
}
}
if (beanSize > 0) { // 设置为错误标记
for (int i = beanSize; i < beans.size(); i++) {
beans.get(i).setWrongTag(true);
}
}
targetFlg = false;
return sbOriginalValue.toString();
}
/**
* 将带内部标记的文本由XML格式转换为显示格式的文本
* @param xml
* 原始的带内部标记的XML格式的文本
* @return ;
*/
public String parseInnerTag(String xml) {
return parseInnerTag(xml, false);
}
boolean exist = false;
/**
* @param tagType
* @param text
* @param tagContent
* @param tagName
* ;
*/
private void addInnerTagBean(TagType tagType, StringBuffer text, String tagContent, String tagName) {
/* 在文本中插入索引 */
int index = -1;
if (tagType == START) {
HasStartTag = true;
if(targetFlg){
for (int i = 0; i < beans.size(); ++i) {
InnerTagBean bean = beans.get(i);
if (bean.getType() != TagType.START) {
continue;
}
if (bean.getContent().equals(tagContent)) {
String placeHolder = placeHolderCreater.getPlaceHolder(beans, i);
if(text.indexOf(placeHolder) != -1){
// 已经存在,继续寻找。
continue;
}
text.replace(start, start + tagContent.length(), placeHolder);
indexStack.push(bean.getIndex());
exist = true;
return;
}
}
}
maxIndex++;
indexStack.push(maxIndex);
index = maxIndex;
} else if (tagType == END) {
if (!HasStartTag) {
maxIndex++;
indexStack.push(maxIndex);
}
HasStartTag = false;
if (!indexStack.empty()) {
index = indexStack.pop();
if (exist && targetFlg) {
for (int i = 0; i < beans.size(); ++i) {
InnerTagBean bean = beans.get(i);
if (bean.getIndex() == index && bean.getType() == TagType.END) {
String placeHolder = placeHolderCreater.getPlaceHolder(beans, i);
text.replace(start, start + tagContent.length(), placeHolder);
if (!indexStack.isEmpty()) {
HasStartTag = true;
}
return;
}
}
}
}
if (!indexStack.isEmpty()) {
HasStartTag = true;
}
} else if (tagType == STANDALONE) {
maxIndex++;
index = maxIndex;
}
if (index > -1) {
InnerTagBean bean = new InnerTagBean(index, tagName, tagContent, tagType);
beans.add(bean);
String placeHolder = placeHolderCreater.getPlaceHolder(beans, beans.size() - 1);
text.replace(start, start + tagContent.length(), placeHolder);
// 显示完整标记时,start 计算错误,因此添加下行语句
start += placeHolder.length() - 1;
}
}
/**
* 得到标记的名称
* @param xmlTag
* XML格式的标记
* @return 标记名称;
*/
private String getTagName(String xmlTag) {
if (xmlTag.indexOf("</") > -1) { // 结束标记
return xmlTag.substring(2, xmlTag.length() - 1);
}
int end = xmlTag.indexOf("/>", 1); // 独立标记
if (end == -1) {
end = xmlTag.length() - 1; // 开始标记
}
int tempIndex = xmlTag.indexOf(" ", 1);
if (tempIndex > -1 && tempIndex < end) {
end = tempIndex;
}
return xmlTag.substring(1, end);
}
}
| 8,696 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
TmxInnerTagFactory.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/base_commons/net.heartsome.cat.common.core/src/net/heartsome/cat/common/innertag/factory/TmxInnerTagFactory.java | package net.heartsome.cat.common.innertag.factory;
import java.util.List;
import net.heartsome.cat.common.innertag.InnerTagBean;
public class TmxInnerTagFactory implements IInnerTagFactory {
public List<InnerTagBean> getInnerTagBeans() {
return null;
}
public String getText() {
return null;
}
public String parseInnerTag(String xml) {
return null;
}
}
| 371 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
IPreferenceConstants.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/base_commons/net.heartsome.cat.common.core/src/net/heartsome/cat/common/core/IPreferenceConstants.java | package net.heartsome.cat.common.core;
/**
* core 中定义的首选项常量.
* @author cheney
*/
public interface IPreferenceConstants {
/**
* 语言代码。
*/
String LANGUAGECODE = "languagecode";
/**
* 最后一次打开文件目录对话框所选择的目录路径。
*/
String LAST_DIRECTORY = "lastDirectory";
/**
* 是否启用 OO(Open Office),用以支持转换 MSOffice 2003。
*/
String AUTOMATIC_OO = "automaticOO";
}
| 463 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
Constant.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/base_commons/net.heartsome.cat.common.core/src/net/heartsome/cat/common/core/Constant.java | package net.heartsome.cat.common.core;
public class Constant {
/**
* 当前系统运行模式。
*/
public static int RUNNING_MODE = 0;
/**
* 调试模式。该模式下将在控制台输出所有的异常堆栈。
*/
public static final int MODE_DEBUG = 0;
/**
* 部署模式。该模式下将在控制台输出所有的异常堆栈。
*/
public static final int MODE_DEPLOY = 1;
/**
* 操作成功。
*/
public static final int RETURNVALUE_RESULT_SUCCESSFUL = 1;
/**
* 操作失败。
*/
public static final int RETURNVALUE_RESULT_FAILURE = 0;
/**
* 返回值中的操作结果。
*/
public static final String RETURNVALUE_RESULT = "result";
/**
* 返回值。
*/
public static final String RETURNVALUE_VALUE = "value";
/**
* 返回值中的消息文本。
*/
public static final String RETURNVALUE_MSG = "msg";
/**
* 返回值中的异常对象。
*/
public static final String RETURNVALUE_EXCEPTION = "exception";
/**
* 更改大小写模式--全部大写
*/
public static final int CHANGECASE_UPPER = 1;
/**
* 更改大小写模式--全部小写
*/
public static final int CHANGECASE_LOWER = 2;
/**
* 更改大小写模式--句子大写
*/
public static final int CHANGECASE_SENTENCE = 3;
/**
* 更改大小写模式--标题大写
*/
public static final int CHANGECASE_TITLE = 4;
/**
* 更改大小写模式--全部切换
*/
public static final int CHANGECASE_TOGGLE = 5;
/**
* 分隔符
*/
public static final String SEPARATORS_1 = " \r\n\f\t\u2028\u2029,.;\":<>?!()[]{}=+-/*\u00AB\u00BB\u201C\u201D\u201E\uFF00"; //$NON-NLS-1$
/**
* 切割单词所用到的分割符,用于拼写检查等
*/
public static final String SEPARATORS = " \r\n\f\t\u2028\u2029\u00A0,.;\":<>¿?¡!()[]{}=-+/*\u00A7\u00A9\u00AE\u00D7\u2122\u2010\u2011\u2012\u2013\u2014\u2015\u00AB\u00BB\u22D6\u22D7\u227A\u227B\u201C\u201D\u201E\uFF00\uF000\uF001\uF002\uF003\u2310\u00AC\uE000\uE001"; //$NON-NLS-1$
/**
* 产品版本--Ultimate 旗舰版
*/
public static final int EDITION_UE = 4;
/**
* 产品版本--Professional 专业版
*/
public static final int EDITION_PRO = 3;
/**
* 产品版本--Personal 个人版
*/
public static final int EDITION_PE = 2;
/**
* 产品版本--LITE 精简版
*/
public static final int EDITION_LITE = 1;
/**
* “源文件”文件夹
*/
public static final String FOLDER_SRC = "Source";
/**
* “源文件”文件夹
*/
public static final String FOLDER_TGT = "Target";
/**
* “XLIFF”文件夹
*/
public static final String FOLDER_XLIFF = "XLIFF";
/**
* “SKL”文件夹
*/
public static final String FOLDER_SKL = "SKL";
/**
* “Report“文件夹
*/
public static final String FOLDER_REPORT = "Report";
/**
* Intermeddiate文件夹
*/
public static final String FOLDER_INTERMEDDIATE = "Intermediate";
/**
* “其他”文件夹
*/
public static final String FOLDER_OTHER = "Other";
/**
* 内部骨架文件类型
*/
public static final String SKL_INTERNAL_FILE = "internal-file";
/**
* 导航视图ID
*/
public static final String NAVIGATOR_VIEW_ID = "net.heartsome.cat.common.ui.navigator.view";
/**
* 项目下的子文件, .config 文件
*/
public static final String FILE_CONFIG = ".config";
/**
* 产品打开时,删除 workbench.xml 中的编辑器记录,保存在如下文件中 robert 2013-05-16
*/
public static final String TEMP_EDITOR_HISTORY = ".metadata/.tempEditorHistory.xml";
/**
* 产品中资源名称中不能出现的错误字符 robert 2013-05-26
*/
public static final char[] RESOURCE_ERRORCHAR = new char[]{'/', '\\', ':', '?', '"', '<', '>', '|'};
/**
* 项目导出时的包后缀名 robert 2013-05-26
*/
public static final String PROJECT_PACK_EXTENSSION = ".hszip";
}
| 3,902 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
CoreActivator.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/base_commons/net.heartsome.cat.common.core/src/net/heartsome/cat/common/core/CoreActivator.java | package net.heartsome.cat.common.core;
import java.io.InputStream;
import org.eclipse.ui.plugin.AbstractUIPlugin;
import org.osgi.framework.BundleContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class CoreActivator extends AbstractUIPlugin {
/** 插件ID。 */
public static final String PLUGIN_ID = "net.heartsome.cat.common.core";
/** 共享的插件实例。 */
private static CoreActivator plugin;
// 配置文件存放的路径前缀
private static final String PATH_PREF = "/configuration";
// 默认的语言代码文件存放的路径
public static final String LANGUAGE_CODE_PATH = PATH_PREF + "/langCodes.xml";
// 国家代码文件存放的路径
public static final String ISO3166_1_PAHT = PATH_PREF + "/ISO3166-1.xml";
// 语言代码 ISO689-1 文件存放的路径
public static final String ISO639_1_PAHT = PATH_PREF + "/ISO639-1.xml";
// 语言代码 ISO689-2 文件存放的路径
public static final String ISO639_2_PAHT = PATH_PREF + "/ISO639-2.xml";
public final static Logger logger = LoggerFactory.getLogger(CoreActivator.class.getName());
public CoreActivator() {
}
/**
* 启动插件应用,创建共享的插件实例。
* @param context
* the context
* @throws Exception
* the exception
* @see org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext)
*/
public void start(BundleContext context) throws Exception {
super.start(context);
plugin = this;
}
/**
* 停止插件应用,并销毁共享的插件实例。
* @param context
* the context
* @throws Exception
* the exception
* @see org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext)
*/
public void stop(BundleContext context) throws Exception {
plugin = null;
super.stop(context);
}
/**
* 获得默认的共享的插件实例。
* @return the shared instance
*/
public static CoreActivator getDefault() {
return plugin;
}
/**
* @param path
* 相对插件根目录的文件路径,如/configuration/langCodes.xml
* @return 返回插件内部配置文件输入流,如果找不到路径对应的文件,则返回 NULL;
*/
public static InputStream getConfigurationFileInputStream(String path) {
return CoreActivator.class.getResourceAsStream(path);
}
}
| 2,367 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
ImportException.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/base_commons/net.heartsome.cat.common.core/src/net/heartsome/cat/common/core/exception/ImportException.java | /**
* ImportException.java
*
* Version information :
*
* Date:2012-6-29
*
* Copyright notice :
* 本文件及其附带的相关文件包含机密信息,仅限瀚特盛科技有限公司指定的,与本项目有关的内部人员和客户联络人员查阅和使用。
* 如果您不是本保密声明中指定的收件者,请立即销毁本文件,禁止对本文件或根据本文件中的内容采取任何其他行动,
* 包括但不限于:泄露本文件中的信息、以任何方式制作本文件全部或部分内容之副本、将本文件或其相关副本提供给任何其他人。
*/
package net.heartsome.cat.common.core.exception;
/**
* @author jason
* @version
* @since JDK1.6
*/
public class ImportException extends Exception {
/** serialVersionUID. */
private static final long serialVersionUID = 1L;
public ImportException(){
super();
}
public ImportException(String message){
super(message);
}
}
| 965 | 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_commons/net.heartsome.cat.common.core/src/net/heartsome/cat/common/core/resource/Messages.java | package net.heartsome.cat.common.core.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.common.core.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;
}
}
}
| 560 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
FileEncodingDetector.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/base_commons/net.heartsome.cat.common.core/src/net/heartsome/cat/common/util/FileEncodingDetector.java | /**
* FileEncodingDetector.java
*
* Version information :
*
* Date:2012-12-13
*
* Copyright notice :
* 本文件及其附带的相关文件包含机密信息,仅限瀚特盛科技有限公司指定的,与本项目有关的内部人员和客户联络人员查阅和使用。
* 如果您不是本保密声明中指定的收件者,请立即销毁本文件,禁止对本文件或根据本文件中的内容采取任何其他行动,
* 包括但不限于:泄露本文件中的信息、以任何方式制作本文件全部或部分内容之副本、将本文件或其相关副本提供给任何其他人。
*/
package net.heartsome.cat.common.util;
import info.monitorenter.cpdetector.io.ASCIIDetector;
import info.monitorenter.cpdetector.io.CodepageDetectorProxy;
import info.monitorenter.cpdetector.io.JChardetFacade;
import info.monitorenter.cpdetector.io.ParsingDetector;
import info.monitorenter.cpdetector.io.UnicodeDetector;
import java.io.File;
/**
* @author Jason
* @version
* @since JDK1.6
*/
public final class FileEncodingDetector {
public static String detectFileEncoding(File f) {
CodepageDetectorProxy detector = CodepageDetectorProxy.getInstance();
detector.add(UnicodeDetector.getInstance());
detector.add(ASCIIDetector.getInstance());
detector.add(new ParsingDetector(false));
detector.add(JChardetFacade.getInstance());
java.nio.charset.Charset charset = null;
try {
charset = detector.detectCodepage(f.toURI().toURL());
} catch (Exception ex) {
ex.printStackTrace();
}
if (charset != null)
return charset.name();
else
return null;
}
}
| 1,620 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
InnerTagClearUtil.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/base_commons/net.heartsome.cat.common.core/src/net/heartsome/cat/common/util/InnerTagClearUtil.java | /**
* InnerTagClearUtil.java
*
* Version information :
*
* Date:2013-10-21
*
* Copyright notice :
* 本文件及其附带的相关文件包含机密信息,仅限瀚特盛科技有限公司指定的,与本项目有关的内部人员和客户联络人员查阅和使用。
* 如果您不是本保密声明中指定的收件者,请立即销毁本文件,禁止对本文件或根据本文件中的内容采取任何其他行动,
* 包括但不限于:泄露本文件中的信息、以任何方式制作本文件全部或部分内容之副本、将本文件或其相关副本提供给任何其他人。
*/
package net.heartsome.cat.common.util;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* 可在 XLIFF 中使用、而不能在 TMX 中使用的内部标记有:<br/>
* <g> <bx/> <ex/> <x/> <mrk><br/>
* 可在 TMX 中使用、而不能在 XLIFF 中使用的内部标记有: <br/>
* <ut> <hi><br/>
* 主要清理TMX 与Xliff 文本的内部标记不兼容的情况
* @author yule
* @version
* @since JDK1.6
*/
public class InnerTagClearUtil {
private static Pattern XLIFF_CLEAR_PATTERN = Pattern
.compile("<ex.+?/>|<x.+?/>|<bx.+?/>|<mrk.+?>|</mrk>|<g.+?>|</g>");
private static Pattern TMX_CLEAR_PATTERN = Pattern.compile("<ut.*?>.*</ut>|<hi.+?>|</hi>");
private InnerTagClearUtil() {
// single instance
}
/**
* 清理Xliff的内部标记,清理后的文本供TMX使用
* @param xliffXmlContent
* : Xliff源或者目标文本的FullText
* @return ;
*/
public static String clearXliffTag4Tmx(String xliffXmlContent) {
if (null == xliffXmlContent) {
return null;
}
Matcher matcher = XLIFF_CLEAR_PATTERN.matcher(xliffXmlContent);
return matcher.replaceAll("");
}
/**
* 清理TMX的内部标记,清理后的文本供Xliff使用
* @param tmxXmlContent
* @return ;
*/
public static String clearTmx4Xliff(String tmxXmlContent) {
if (null == tmxXmlContent) {
return null;
}
Matcher matcher = TMX_CLEAR_PATTERN.matcher(tmxXmlContent);
return matcher.replaceAll("");
}
}
| 2,161 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
TextUtil.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/base_commons/net.heartsome.cat.common.core/src/net/heartsome/cat/common/util/TextUtil.java | package net.heartsome.cat.common.util;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.MessageFormat;
import java.util.Enumeration;
import java.util.Hashtable;
import net.heartsome.cat.common.core.CoreActivator;
import net.heartsome.cat.common.core.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 weachy
* @version
* @since JDK1.5
*/
public class TextUtil {
private static final Logger LOGGER = LoggerFactory.getLogger(TextUtil.class.getName());
private static Hashtable<String, String> ISOLang;
private static Hashtable<String, String> countries;
private static Hashtable<String, String> descriptions;
private static Hashtable<String, String> isBidi;
private static final String _SPACE = " ";
private TextUtil() {
// 防止此类被实例化
}
public static String cleanString(String input) {
input = input.replaceAll("&", "&"); //$NON-NLS-1$ //$NON-NLS-2$
input = input.replaceAll("<", "<"); //$NON-NLS-1$ //$NON-NLS-2$
input = input.replaceAll(">", ">"); //$NON-NLS-1$ //$NON-NLS-2$
return validChars(input);
}
public static String validChars(String input) {
// Valid: #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD] |
// [#x10000-#x10FFFF]
// Discouraged: [#x7F-#x84], [#x86-#x9F], [#xFDD0-#xFDDF]
//
StringBuffer buffer = new StringBuffer();
char c;
int length = input.length();
for (int i = 0; i < length; i++) {
c = input.charAt(i);
if (c == '\t' || c == '\n' || c == '\r' || c >= '\u0020' && c <= '\uD7DF' || c >= '\uE000' && c <= '\uFFFD') {
// normal character
buffer.append(c);
} else if (c >= '\u007F' && c <= '\u0084' || c >= '\u0086' && c <= '\u009F' || c >= '\uFDD0'
&& c <= '\uFDDF') {
// Control character
buffer.append("&#x" + Integer.toHexString(c) + ";"); //$NON-NLS-1$ //$NON-NLS-2$
} else if (c >= '\uDC00' && c <= '\uDFFF' || c >= '\uD800' && c <= '\uDBFF') {
// Multiplane character
buffer.append(input.substring(i, i + 1));
}
}
return buffer.toString();
}
/**
* @param string
* @param trim
* @return
*/
public static String normalise(String string, boolean trim) {
boolean repeat = false;
String rs = ""; //$NON-NLS-1$
int length = string.length();
for (int i = 0; i < length; i++) {
char ch = string.charAt(i);
if (!Character.isSpaceChar(ch)) {
if (ch != '\n') {
rs = rs + ch;
} else {
rs = rs + " "; //$NON-NLS-1$
repeat = true;
}
} else {
rs = rs + " "; //$NON-NLS-1$
while (i < length - 1 && Character.isSpaceChar(string.charAt(i + 1))) {
i++;
}
}
}
if (repeat == true) {
return normalise(rs, trim);
}
if (trim) {
return rs.trim();
}
return rs;
}
/**
* @param string
* @param trim
* @return robert添加 2011-11-02
*/
public static String normalise(String string) {
return normalise(string, true);
}
/**
* 清除特殊字符
* @param input
* @return
*/
public static String cleanSpecialString(String input) {
input = input.replaceAll("&", "&"); //$NON-NLS-1$ //$NON-NLS-2$
input = input.replaceAll("<", "<"); //$NON-NLS-1$ //$NON-NLS-2$
input = input.replaceAll(">", ">"); //$NON-NLS-1$ //$NON-NLS-2$
input = input.replaceAll("\"", """);
return input;
}
/**
* 恢复特殊字符
* @param input
* @return
*/
public static String resetSpecialString(String input) {
input = input.replaceAll("<", "<"); //$NON-NLS-1$ //$NON-NLS-2$
input = input.replaceAll(">", ">"); //$NON-NLS-1$ //$NON-NLS-2$
input = input.replaceAll(""", "\"");
input = input.replaceAll("&", "&"); //$NON-NLS-1$ //$NON-NLS-2$
return input;
}
public static String getISO639(String code, String langFile) {
if (code.equals("")) { //$NON-NLS-1$
return ""; //$NON-NLS-1$
}
try {
loadISOLang(langFile);
} catch (Exception e) {
e.printStackTrace();
return ""; //$NON-NLS-1$
}
if (ISOLang.containsKey(code.toLowerCase())) {
return ISOLang.get(code.toLowerCase());
}
return ""; //$NON-NLS-1$
}
private static void loadISOLang(String strLangFile) {
if (strLangFile == null) {
return;
}
ISOLang = new Hashtable<String, String>();
VTDGen vg = new VTDGen();
// vg.setDoc(strLangFile.getBytes());
try {
vg.setDoc(readBytesFromIS(CoreActivator.getConfigurationFileInputStream(strLangFile)));
vg.parse(true);
VTDNav vn = vg.getNav();
VTDUtils vu = new VTDUtils(vn);
AutoPilot ap = new AutoPilot(vn);
ap.selectXPath("/languages/lang");
int codeIndex;
String code = null;
String langName;
while ((ap.evalXPath()) != -1) {
codeIndex = vn.getAttrVal("code");
if (codeIndex != -1) {
code = vn.toString(codeIndex);
}
langName = vu.getElementPureText();
if (code != null && langName != null) {
ISOLang.put(code, langName);
}
}
ap.resetXPath();
} catch (NavException e) {
if (LOGGER.isErrorEnabled()) {
String msg = Messages.getString("util.TextUtil.logger1");
Object args[] = { strLangFile };
LOGGER.error(new MessageFormat(msg).format(args), e);
}
} catch (XPathParseException e) {
if (LOGGER.isErrorEnabled()) {
String msg = Messages.getString("util.TextUtil.logger1");
Object args[] = { strLangFile };
LOGGER.error(new MessageFormat(msg).format(args), e);
}
} catch (XPathEvalException e) {
if (LOGGER.isErrorEnabled()) {
String msg = Messages.getString("util.TextUtil.logger1");
Object args[] = { strLangFile };
LOGGER.error(new MessageFormat(msg).format(args), e);
}
} catch (EncodingException e) {
if (LOGGER.isErrorEnabled()) {
String msg = Messages.getString("util.TextUtil.logger1");
Object args[] = { strLangFile };
LOGGER.error(new MessageFormat(msg).format(args), e);
}
} catch (EOFException e) {
if (LOGGER.isErrorEnabled()) {
String msg = Messages.getString("util.TextUtil.logger1");
Object args[] = { strLangFile };
LOGGER.error(new MessageFormat(msg).format(args), e);
}
} catch (EntityException e) {
if (LOGGER.isErrorEnabled()) {
String msg = Messages.getString("util.TextUtil.logger1");
Object args[] = { strLangFile };
LOGGER.error(new MessageFormat(msg).format(args), e);
}
} catch (ParseException e) {
if (LOGGER.isErrorEnabled()) {
String msg = Messages.getString("util.TextUtil.logger1");
Object args[] = { strLangFile };
LOGGER.error(new MessageFormat(msg).format(args), e);
}
} catch (IOException e) {
if (LOGGER.isErrorEnabled()) {
String msg = Messages.getString("util.TextUtil.logger1");
Object args[] = { strLangFile };
LOGGER.error(new MessageFormat(msg).format(args), e);
}
} finally {
vg.clear();
}
}
public static String getCountryName(String country) {
if (country.equals("")) { //$NON-NLS-1$
return ""; //$NON-NLS-1$
}
try {
loadCountries();
} catch (Exception e) {
e.printStackTrace();
return ""; //$NON-NLS-1$
}
if (countries.containsKey(country.toUpperCase())) {
return countries.get(country.toUpperCase());
}
return ""; //$NON-NLS-1$
}
private static void loadCountries() {
String strFile = CoreActivator.ISO3166_1_PAHT;
countries = new Hashtable<String, String>();
VTDGen vg = new VTDGen();
try {
vg.setDoc(readBytesFromIS(CoreActivator.getConfigurationFileInputStream(strFile)));
vg.parse(true);
VTDNav vn = vg.getNav();
VTDUtils vu = new VTDUtils(vn);
AutoPilot ap = new AutoPilot(vn);
ap.selectXPath("/ISO_3166-1_List_en/ISO_3166-1_Entry");
while ((ap.evalXPath()) != -1) {
countries.put(vu.getChildContent("ISO_3166-1_Alpha-2_Code_element"),
vu.getChildContent("ISO_3166-1_Country_name"));
}
ap.resetXPath();
} catch (NavException e) {
if (LOGGER.isErrorEnabled()) {
String msg = Messages.getString("util.TextUtil.logger1");
Object args[] = { strFile };
LOGGER.error(new MessageFormat(msg).format(args), e);
}
} catch (XPathParseException e) {
if (LOGGER.isErrorEnabled()) {
String msg = Messages.getString("util.TextUtil.logger1");
Object args[] = { strFile };
LOGGER.error(new MessageFormat(msg).format(args), e);
}
} catch (XPathEvalException e) {
if (LOGGER.isErrorEnabled()) {
String msg = Messages.getString("util.TextUtil.logger1");
Object args[] = { strFile };
LOGGER.error(new MessageFormat(msg).format(args), e);
}
} catch (EncodingException e) {
if (LOGGER.isErrorEnabled()) {
String msg = Messages.getString("util.TextUtil.logger1");
Object args[] = { strFile };
LOGGER.error(new MessageFormat(msg).format(args), e);
}
} catch (EOFException e) {
if (LOGGER.isErrorEnabled()) {
String msg = Messages.getString("util.TextUtil.logger1");
Object args[] = { strFile };
LOGGER.error(new MessageFormat(msg).format(args), e);
}
} catch (EntityException e) {
if (LOGGER.isErrorEnabled()) {
String msg = Messages.getString("util.TextUtil.logger1");
Object args[] = { strFile };
LOGGER.error(new MessageFormat(msg).format(args), e);
}
} catch (ParseException e) {
if (LOGGER.isErrorEnabled()) {
String msg = Messages.getString("util.TextUtil.logger1");
Object args[] = { strFile };
LOGGER.error(new MessageFormat(msg).format(args), e);
}
} catch (IOException e) {
if (LOGGER.isErrorEnabled()) {
String msg = Messages.getString("util.TextUtil.logger1");
Object args[] = { strFile };
LOGGER.error(new MessageFormat(msg).format(args), e);
}
} finally {
vg.clear();
}
}
public static byte[] readBytesFromIS(InputStream is) throws IOException {
int total = is.available();
byte[] bs = new byte[total];
is.read(bs);
return bs;
}
public static String getLanguageCode(String language) {
if (language.equals("")) { //$NON-NLS-1$
return ""; //$NON-NLS-1$
}
try {
loadLanguages();
} catch (Exception e) {
e.printStackTrace();
return ""; //$NON-NLS-1$
}
Enumeration<String> keys = descriptions.keys();
while (keys.hasMoreElements()) {
String key = keys.nextElement();
if (language.equals(descriptions.get(key) + _SPACE + key)) { //$NON-NLS-1$
return key;
}
}
return language;
}
private static void loadLanguages() {
descriptions = null;
isBidi = null;
descriptions = new Hashtable<String, String>();
isBidi = new Hashtable<String, String>();
String strFile = CoreActivator.LANGUAGE_CODE_PATH;
VTDGen vg = new VTDGen();
try {
vg.setDoc(readBytesFromIS(CoreActivator.getConfigurationFileInputStream(strFile)));
vg.parse(true);
VTDNav vn = vg.getNav();
VTDUtils vu = new VTDUtils(vn);
AutoPilot ap = new AutoPilot(vn);
ap.selectXPath("/languages/lang");
int codeIndex;
String code = null;
int bidiIndex;
String bidi = null;
String langName;
while ((ap.evalXPath()) != -1) {
codeIndex = vn.getAttrVal("code");
if (codeIndex != -1) {
code = vn.toString(codeIndex);
}
bidiIndex = vn.getAttrVal("bidi");
if (bidiIndex != -1) {
bidi = vn.toString(bidiIndex);
}
langName = vu.getElementPureText();
if (code != null && langName != null) {
descriptions.put(code, langName);
}
if (code != null && bidi != null) {
isBidi.put(code, bidi);
}
}
ap.resetXPath();
} catch (NavException e) {
if (LOGGER.isErrorEnabled()) {
String msg = Messages.getString("util.TextUtil.logger1");
Object args[] = { strFile };
LOGGER.error(new MessageFormat(msg).format(args), e);
}
} catch (XPathParseException e) {
if (LOGGER.isErrorEnabled()) {
String msg = Messages.getString("util.TextUtil.logger1");
Object args[] = { strFile };
LOGGER.error(new MessageFormat(msg).format(args), e);
}
} catch (XPathEvalException e) {
if (LOGGER.isErrorEnabled()) {
String msg = Messages.getString("util.TextUtil.logger1");
Object args[] = { strFile };
LOGGER.error(new MessageFormat(msg).format(args), e);
}
} catch (EncodingException e) {
if (LOGGER.isErrorEnabled()) {
String msg = Messages.getString("util.TextUtil.logger1");
Object args[] = { strFile };
LOGGER.error(new MessageFormat(msg).format(args), e);
}
} catch (EOFException e) {
if (LOGGER.isErrorEnabled()) {
String msg = Messages.getString("util.TextUtil.logger1");
Object args[] = { strFile };
LOGGER.error(new MessageFormat(msg).format(args), e);
}
} catch (EntityException e) {
if (LOGGER.isErrorEnabled()) {
String msg = Messages.getString("util.TextUtil.logger1");
Object args[] = { strFile };
LOGGER.error(new MessageFormat(msg).format(args), e);
}
} catch (ParseException e) {
if (LOGGER.isErrorEnabled()) {
String msg = Messages.getString("util.TextUtil.logger1");
Object args[] = { strFile };
LOGGER.error(new MessageFormat(msg).format(args), e);
}
} catch (IOException e) {
if (LOGGER.isErrorEnabled()) {
String msg = Messages.getString("util.TextUtil.logger1");
Object args[] = { strFile };
LOGGER.error(new MessageFormat(msg).format(args), e);
}
} finally {
vg.clear();
}
}
public static String getLanguageName(String language) {
if (language.equals("")) { //$NON-NLS-1$
return ""; //$NON-NLS-1$
}
try {
loadLanguages();
} catch (Exception e) {
e.printStackTrace();
return ""; //$NON-NLS-1$
}
Enumeration<String> keys = descriptions.keys();
while (keys.hasMoreElements()) {
String key = keys.nextElement();
if (key.toLowerCase().equals(language.toLowerCase())) {
return descriptions.get(key) + _SPACE + key; //$NON-NLS-1$
}
}
// code not found on the list
// check if it is possible to build an ISO name
switch (language.length()) {
case 2:
String iso = getISO639(language, CoreActivator.ISO639_1_PAHT); //$NON-NLS-1$
if (iso.equals("")) { //$NON-NLS-1$
return language;
}
return ISOLang.get(language.toLowerCase()) + _SPACE + language; //$NON-NLS-1$
case 3:
iso = getISO639(language, CoreActivator.ISO639_2_PAHT); //$NON-NLS-1$
if (iso.equals("")) { //$NON-NLS-1$
return language;
}
return ISOLang.get(language.toLowerCase()) + _SPACE + language; //$NON-NLS-1$
case 5:
language.replaceAll("_", "-"); //$NON-NLS-1$ //$NON-NLS-2$
if (language.charAt(2) != '-') {
return language;
}
String lang = language.substring(0, 2).toLowerCase();
if (getISO639(lang, CoreActivator.ISO639_1_PAHT).equals("")) { //$NON-NLS-1$ //$NON-NLS-2$
return language;
}
String country = language.substring(3).toUpperCase();
if (getCountryName(country).equals("")) { //$NON-NLS-1$
return language;
}
return ISOLang.get(lang) + " (" + countries.get(country) + ")" + _SPACE + lang + "-" + country; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
case 6:
language.replaceAll("_", "-"); //$NON-NLS-1$ //$NON-NLS-2$
if (language.charAt(3) != '-') {
return language;
}
lang = language.substring(0, 3).toLowerCase();
if (getISO639(lang, CoreActivator.ISO639_2_PAHT).equals("")) { //$NON-NLS-1$ //$NON-NLS-2$
return language;
}
country = language.substring(4).toUpperCase();
if (getCountryName(country).equals("")) { //$NON-NLS-1$
return language;
}
return ISOLang.get(lang) + " (" + countries.get(country) + ")" + _SPACE + lang + "-" + country; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
default:
return language;
}
}
/**
* 获取字符串 str 在字符串 srcStr 中出现第index次的位置,index范围不符合逻辑返回-1. 如:indexOf("abcabdabe","ab",2)=6
* @param srcStr
* 任意字符串
* @param str
* 要搜索的子字符串
* @param index
* str 在 srcStr 中出现的次数
* @param isCaseSensitive
* 是否区分大小写
* @return int str 在 srcStr 中出现第index次的位置
*/
public static int indexOf(String srcStr, String str, int index, boolean isCaseSensitive) {
if (index == 0) {
return -1;
}
if (index == 1) {
if (isCaseSensitive) {
return srcStr.indexOf(str);
} else {
return srcStr.toUpperCase().indexOf(str.toUpperCase());
}
}
if (isCaseSensitive) {
return srcStr.indexOf(str, indexOf(srcStr, str, index - 1, isCaseSensitive) + str.length());
} else {
return srcStr.toUpperCase().indexOf(str.toUpperCase(),
indexOf(srcStr, str, index - 1, isCaseSensitive) + str.length());
}
}
/**
* 当 Sql 语句使用 LIKE 字段时,\ 需要替换成4个 \,%,_,? 需要替换成\\%,\\_,\\?
* @param input
* @return ;
*/
public static String cleanStringByLikeWithMysql(String input) {
if (input == null) {
return "";
}
input = input.replaceAll("\\\\", "\\\\\\\\\\\\\\\\");
input = input.replaceAll("'", "\\\\\\\\'");
input = input.replaceAll("%", "\\\\\\\\%");
input = input.replaceAll("_", "\\\\\\\\_");
return input;
}
/**
* Oracle 数据库 Sql 中 like 查询条件要替换的特殊字符
* @param input
* @return ;
*/
public static String cleanStringByLikeWithOracle(String input) {
if (input == null) {
return "";
}
input = input.replaceAll("\\\\", "\\\\\\\\");
input = input.replaceAll("'", "''");
input = input.replaceAll("%", "\\\\\\\\%");
input = input.replaceAll("_", "\\\\\\\\_");
return input;
}
/**
* Sql Server 数据库 Sql 中 like 查询条件要替换的特殊字符
* @param input
* @return ;
*/
public static String cleanStringByLikeWithMsSql(String input) {
if (input == null) {
return "";
}
input = input.replaceAll("\\\\", "\\\\\\\\");
input = input.replaceAll("'", "''");
// input = input.replaceAll("\"", "\"\"");
// input = input.replaceAll("[", "[[]");
input = input.replaceAll("%", "[%]");
input = input.replaceAll("_", "[_]");
// input = input.replaceAll("^", "[^]");
return input;
}
/**
* Postgre Sql 数据库 Sql 中 like 查询条件要替换的特殊字符
* @param input
* @return ;
*/
public static String cleanStringByLikeWithPostgreSql(String input) {
if (input == null) {
return "";
}
input = input.replaceAll("\\\\", "\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\");
input = input.replaceAll("'", "''");
input = input.replaceAll("%", "\\\\\\\\\\\\\\\\%");
input = input.replaceAll("_", "\\\\\\\\\\\\\\\\_");
return input;
}
/**
* Postgre Sql 数据库 Sql 中 like 查询条件要替换的特殊字符
* @param input
* @return ;
*/
public static String cleanStringByLikeWithHSQL(String input) {
if (input == null) {
return "";
}
input = input.replaceAll("\\\\", "\\\\\\\\\\\\\\\\");
input = input.replaceAll("'", "''");
input = input.replaceAll("%", "\\\\\\\\%");
input = input.replaceAll("_", "\\\\\\\\_");
return input;
}
public static String replaceRegextSql(String input) {
if (input == null) {
return "";
}
input = input.replaceAll("\\\\d", "[0-9]");
input = input.replaceAll("\\\\D", "[^0-9]");
input = input.replaceAll("\\\\w", "[a-zA-Z0-9_]");
input = input.replaceAll("\\\\W", "[^a-zA-Z0-9_]");
input = input.replaceAll("\\\\\\\\.", ".");
input = input.replaceAll("\\\\", "\\\\\\\\\\\\\\\\");
input = input.replaceAll("'", "''");
input = input.replaceAll("\\\\\\\\\\\\\\\\s", "[ \\\\f\\\\n\\\\r\\\\t\\\\v]");
input = input.replaceAll("\\\\\\\\\\\\\\\\S", "[^ \\\\f\\\\n\\\\r\\\\t\\\\v]");
return input;
}
public static String replaceRegextSqlWithMOP(String input) {
if (input == null) {
return "";
}
input = input.replaceAll("\\\\d", "[0-9]");
input = input.replaceAll("\\\\D", "[^0-9]");
input = input.replaceAll("\\\\w", "[a-zA-Z0-9_]");
input = input.replaceAll("\\\\W", "[^a-zA-Z0-9_]");
input = input.replaceAll("\\\\s", "[[:space:]]");
input = input.replaceAll("\\\\S", "[^[:space:]]");
input = input.replaceAll("\\\\\\\\.", ".");
input = input.replaceAll("\\\\", "\\\\\\\\\\\\\\\\");
input = input.replaceAll("'", "''");
return input;
}
/**
* HSQL 使用正则表达式时要替换的字符
* @param input
* @return ;
*/
public static String replaceRegextSqlWithHSQL(String input) {
if (input == null) {
return "";
}
input = input.replaceAll("\\\\d", "[0-9]");
input = input.replaceAll("\\\\D", "[^0-9]");
input = input.replaceAll("\\\\w", "[a-zA-Z0-9_]");
input = input.replaceAll("\\\\W", "[^a-zA-Z0-9_]");
input = input.replaceAll("\\\\\\\\.", ".");
input = input.replaceAll("'", "''");
input = input.replaceAll("\\\\", "\\\\\\\\");
input = input.replaceAll("\\\\\\\\s", "[\\\\f\\\\n\\\\r\\\\t\\\\v]");
input = input.replaceAll("\\\\\\\\S", "[^ \\\\f\\\\n\\\\r\\\\t\\\\v]");
return input;
}
/**
* 将语言进行常态化 robert 2012-02-03
* @param language
* @return ;
*/
public static String normLanguage(String language) {
if ("".equals(language) || language == null) { //$NON-NLS-1$
return ""; //$NON-NLS-1$
}
if (language.length() < 2) {
return language.toLowerCase();
} else {
return language.substring(0, 2).toLowerCase() + language.substring(2, language.length());
}
}
/**
* 将 xml 中的转义字符还原
* @param input
* @return ;
*/
public static String xmlToString(String input) {
if (input == null) {
return "";
}
input = input.replaceAll("<", "<");
input = input.replaceAll(">", ">");
input = input.replaceAll("'", "'");
input = input.replaceAll(""", "\"");
input = input.replaceAll("&", "&");
return input;
}
/**
* 将 input 中的字符串转义
* @param input
* @return ;
*/
public static String stringToXML(String input) {
if (input == null) {
return "";
}
input = input.replaceAll("&", "&");
input = input.replaceAll("<", "<");
input = input.replaceAll(">", ">");
input = input.replaceAll("'", "'");
input = input.replaceAll("\"", """);
return input;
}
/**
* 加载语言,针对插件开发模块 robert 2012-03-15
* @throws Exception
*/
public static Hashtable<String, String> plugin_loadLanguages() throws Exception {
// 语言文件位置
String languageXmlLC_1 = CoreActivator.ISO639_1_PAHT;
String languageXmlLC_2 = CoreActivator.ISO639_2_PAHT;
Hashtable<String, String> _languages = new Hashtable<String, String>();
getLanguages(languageXmlLC_1, _languages);
getLanguages(languageXmlLC_2, _languages);
return _languages;
}
/**
* 加载国家名称,针对插件开发模块 robert 2012-03-15
* @param langXMlLC
* @param _languages
* @throws Exception
*/
public static Hashtable<String, String> plugin_loadCoutries() throws Exception {
// 国家文件位置
String countryXmlLC = CoreActivator.ISO3166_1_PAHT;
Hashtable<String, String> _countries = new Hashtable<String, String>();
VTDGen vg = new VTDGen();
vg.setDoc(readBytesFromIS(CoreActivator.getConfigurationFileInputStream(countryXmlLC)));
vg.parse(true);
VTDNav vn = vg.getNav();
AutoPilot ap = new AutoPilot(vn);
AutoPilot childAP = new AutoPilot(vn);
ap.selectXPath("/ISO_3166-1_List_en/ISO_3166-1_Entry");
while (ap.evalXPath() != -1) {
String code = "";
String name = "";
int index;
vn.push();
childAP.selectXPath("./ISO_3166-1_Alpha-2_Code_element");
if (childAP.evalXPath() != -1) {
if ((index = vn.getText()) != -1) {
code = vn.toString(index).trim().toUpperCase();
}
}
vn.pop();
vn.push();
childAP.selectXPath("./ISO_3166-1_Country_name");
if (childAP.evalXPath() != -1) {
if ((index = vn.getText()) != -1) {
name = vn.toString(index).trim();
}
}
vn.pop();
if (!"".equals(code) && !"".equals(name)) {
_countries.put(code, name);
}
}
return _countries;
}
/**
* ,针对插件开发模块 robert 2012-03-15
* @param langXMlLC
* @param _languages
* @throws Exception
*/
private static void getLanguages(String langXMlLC, Hashtable<String, String> _languages) throws Exception {
VTDGen vg = new VTDGen();
vg.setDoc(readBytesFromIS(CoreActivator.getConfigurationFileInputStream(langXMlLC)));
vg.parse(true);
VTDNav vn = vg.getNav();
AutoPilot ap = new AutoPilot(vn);
ap.selectXPath("/languages/lang");
while (ap.evalXPath() != -1) {
if (vn.getAttrVal("code") != -1 && vn.getText() != -1) {
_languages.put(vn.toString(vn.getAttrVal("code")).toLowerCase(), vn.toString(vn.getText()).trim());
}
}
}
/**
* 半角转全角的函数(SBC case) 任意字符串 全角字符串 全角空格为12288,半角空格为32 其他字符半角(33-126)与全角(65281-65374)的对应关系是:均相差65248
* @param input
* @return ;
*/
public static String toSBC(String input) {
// 半角转全角:
char c[] = input.toCharArray();
for (int i = 0; i < c.length; i++) {
if (c[i] == ' ') {
c[i] = '\u3000';
} else if (c[i] < '\177') {
c[i] = (char) (c[i] + 65248);
}
}
return new String(c);
}
/**
* 全角转半角的函数(DBC case) 任意字符串 半角字符串 全角空格为12288,半角空格为32 其他字符半角(33-126)与全角(65281-65374)的对应关系是:均相差65248
* @param input
* @return ;
*/
public static String toDBC(String input) {
char c[] = input.toCharArray();
for (int i = 0; i < c.length; i++) {
if (c[i] == '\u3000') {
c[i] = ' ';
} else if (c[i] > '\uFF00' && c[i] < '\uFF5F') {
c[i] = (char) (c[i] - 65248);
}
}
return new String(c);
}
/**
* 16进制数字字符集
*/
private static String hexString = "0123456789ABCDEF";
/**
* 将字符串编码成16进制数字,适用于所有字符(包括中文)
*/
public static String encodeHexString(String str) {
// 根据默认编码获取字节数组
byte[] bytes = str.getBytes();
StringBuilder sb = new StringBuilder(bytes.length * 2);
// 将字节数组中每个字节拆解成2位16进制整数
for (int i = 0; i < bytes.length; i++) {
// int d = (bytes[i] & 0x0f) >> 0;
// /System.out.println("bytes["+i+"]:"+bytes[i]+"_"+d);//bytes[i]得到的是对应的字符ASCII值
sb.append(hexString.charAt((bytes[i] & 0xf0) >> 4));// 1-4
sb.append(hexString.charAt((bytes[i] & 0x0f) >> 0));// 1-2
}
return sb.toString();
}
/**
* 将16进制数字解码成字符串,适用于所有字符(包括中文) decode(String bytes)方法里面的bytes字符串必须大写,即toUpperCase()
*/
public static String decodeHexString(String bytes) {
ByteArrayOutputStream baos = new ByteArrayOutputStream(bytes.length() / 2);
// 将每2位16进制整数组装成一个字节
for (int i = 0; i < bytes.length(); i += 2) {
baos.write((hexString.indexOf(bytes.charAt(i)) << 4 | hexString.indexOf(bytes.charAt(i + 1))));
}
return new String(baos.toByteArray());
}
/**
* 不转义实体字符,只转义需要转义的字符
* 视图显示没有处理 单引号和双引号字符
* add by yule 2013-11-21
* @param oldResult
* @return ;
*/
public static String convertMachineTranslateResult(String oldResult) {
if (null == oldResult || oldResult.isEmpty()) {
return "";
}
String replaceEntiyChar = oldResult.replace("&", "&").replace("<", "<").replace(">", ">");
return replaceEntiyChar.replace("&", "&").replace("<", "<").replace(">", ">");
}
}
| 27,781 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
UnicodeConverter.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/base_commons/net.heartsome.cat.common.core/src/net/heartsome/cat/common/util/UnicodeConverter.java | package net.heartsome.cat.common.util;
public class UnicodeConverter {
/**
* 将字符串转成 Unicode 码
* @param str
* 待转字符串
* @return Unicode 码
*/
public static String convert(String str) {
str = (str == null ? "" : str);
String tmp;
StringBuffer sb = new StringBuffer(1000);
char c;
int i, j;
sb.setLength(0);
for (i = 0; i < str.length(); i++) {
c = str.charAt(i);
sb.append("\\u");
j = (c >>> 8); // 取出高8位
tmp = Integer.toHexString(j);
if (tmp.length() == 1)
sb.append("0");
sb.append(tmp);
j = (c & 0xFF); // 取出低8位
tmp = Integer.toHexString(j);
if (tmp.length() == 1)
sb.append("0");
sb.append(tmp);
}
return (new String(sb));
}
/**
* 将 Unicode 码转成字符串
* @param unicode
* unicode 码
* @return 字符串
*/
public static String revert(String unicode) {
unicode = (unicode == null ? "" : unicode);
if (unicode.indexOf("\\u") == -1)// 如果不是unicode码则原样返回
return unicode;
StringBuffer sb = new StringBuffer(1000);
for (int i = 0; i < unicode.length(); i += 6) {
String strTemp = unicode.substring(i, i + 6);
String value = strTemp.substring(2);
int c = 0;
for (int j = 0; j < value.length(); j++) {
char tempChar = value.charAt(j);
int t = 0;
switch (tempChar) {
case 'a':
t = 10;
break;
case 'b':
t = 11;
break;
case 'c':
t = 12;
break;
case 'd':
t = 13;
break;
case 'e':
t = 14;
break;
case 'f':
t = 15;
break;
default:
t = tempChar - 48;
break;
}
c += t * ((int) Math.pow(16, (value.length() - j - 1)));
}
sb.append((char) c);
}
return sb.toString();
}
public static void main(String[] args) {
// int c = 0;
// for (char i = '\uA000'; i <= '\uA099'; i++) {
// c++;
// System.out.println(i);
// }
// System.out.println(c);
System.out.println(revert("\\ua001"));
System.out.println(convert("ꀀ"));
}
}
| 2,052 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
CommonFunction.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/base_commons/net.heartsome.cat.common.core/src/net/heartsome/cat/common/util/CommonFunction.java | package net.heartsome.cat.common.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.DateFormat;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
import java.util.TimeZone;
import java.util.UUID;
import java.util.Vector;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import net.heartsome.cat.common.core.Constant;
import net.heartsome.cat.common.core.resource.Messages;
import net.heartsome.cat.common.resources.ResourceUtils;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.runtime.FileLocator;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IEditorReference;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchListener;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.internal.EditorHistory;
import org.eclipse.ui.internal.EditorHistoryItem;
import org.eclipse.ui.internal.Workbench;
import org.eclipse.ui.part.FileEditorInput;
import org.osgi.framework.Bundle;
import com.ximpleware.AutoPilot;
import com.ximpleware.VTDGen;
import com.ximpleware.VTDNav;
/**
* 公共方法
* @author Gonzalo To change the template for this generated type comment go to Window>Preferences>Java>Code
* Generation>Code and Comments
*/
public class CommonFunction {
/**
* <div style='color:red'>备注:R8所支持的文件后缀名,当后支持文件后缀名要进行扩展时,修改四处,<br>
* 第一即xlfExtensionList常量,<br>
* 第二在xlfExtesionArray变量,<br>
* 第三处在nattable插件的net.heartsome.cat.ts.ui.xliffeditor.nattable.editor编辑器定义里面。<br>
* 第四处为R8XliffExtension常量</div>
* 别,带 $extension$ 标记的地方,手动修改
* robert 2012-06-21
*/
private final static List<String> xlfExtensionList = new ArrayList<String>();
public final static String[] xlfExtesionArray = new String[]{"hsxliff"};
/** R8 xliff文件的后缀名,带“.”的 */
public final static String R8XliffExtension_1 = ".hsxliff";
/** R8 xliff文件的后缀名,不带“.”的 */
public final static String R8XliffExtension = "hsxliff";
/** r8 系统语言,与prefrenceStore中的数据同步。robert 2012-09-15 */
private static String systemLanguage = "en";
private static final String XLIFF_EDITOR_ID = "net.heartsome.cat.ts.ui.xliffeditor.nattable.editor";
static{
xlfExtensionList.add("hsxliff");
xlfExtensionList.add(".hsxliff");
}
/**
* 判断数组中是否包含指定元素
* @param array
* 数组
* @param element
* 元素
* @return ;
*/
public static <T> boolean contains(T[] array, T element) {
if (array == null || array.length == 0) {
return false;
}
for (int i = 0; i < array.length; i++) {
if (array[i] == null) {
if (element == null) {
return true;
}
} else if (array[i].equals(element)) {
return true;
}
}
return false;
}
/**
* 判断忽略大小写时字符串数组中是否包含指定字符串。
* @param stringArray
* 字符串数组
* @param string
* 字符串
* @return ;
*/
public static boolean containsIgnoreCase(String[] stringArray, String string) {
if (stringArray == null || stringArray.length == 0) {
return false;
}
for (int i = 0; i < stringArray.length; i++) {
if (stringArray[i] == null) {
if (string == null) {
return true;
}
} else if (stringArray[i].equalsIgnoreCase(string)) {
return true;
}
}
return false;
}
public static String[] getItemBySeparator(String s, char separator) {
if (s == null) {
return new String[0];
}
String separators = "" + separator; //$NON-NLS-1$
StringTokenizer tokenizer = new StringTokenizer(s, separators);
int size = tokenizer.countTokens();
String[] result = new String[size];
for (int i = 0; i < size; i++) {
result[i] = tokenizer.nextToken();
}
return result;
}
public static String[] vector2StringArray(Vector<String> vector) {
String[] result = new String[vector.size()];
for (int i = 0; i < vector.size(); i++) {
result[i] = vector.get(i);
}
return result;
}
public static void stringArray2Vector(String[] stringArray, Vector<String> vector) {
for (int i = 0; i < stringArray.length; i++) {
vector.add(stringArray[i]);
}
}
/**
* 将数组转为 List
* @param array
* home path
*/
public static <T> List<T> array2List(T[] array) {
ArrayList<T> list = new ArrayList<T>(array.length);
for (int i = 0; i < array.length; i++) {
list.add(array[i]);
}
return list;
}
public static int indexOf(Vector<String> vector, String string) {
for (int i = 0; i < vector.size(); i++) {
if (vector.get(i).equals(string)) {
return i;
}
}
return -1;
}
public static int indexOf(String[] array, String string) {
for (int i = 0; i < array.length; i++) {
if (array[i].equals(string)) {
return i;
}
}
return -1;
}
public static String[] getWords(String s) {
if (s == null) {
return new String[0];
}
StringTokenizer tokenizer = new StringTokenizer(s, Constant.SEPARATORS_1, true);
Vector<String> result = new Vector<String>();
while (tokenizer.hasMoreTokens()) {
String token = tokenizer.nextToken().trim();
if (!token.equals("")) { //$NON-NLS-1$
result.add(token);
}
}
return vector2StringArray(result);
}
public static String retTMXDate() {
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT")); //$NON-NLS-1$
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" : "") + calendar.get(Calendar.DATE); //$NON-NLS-1$ //$NON-NLS-2$
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;
}
public static String retGMTdate(String TMXDate) {
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT")); //$NON-NLS-1$
try {
int second = Integer.parseInt(TMXDate.substring(13, 15));
int minute = Integer.parseInt(TMXDate.substring(11, 13));
int hour = Integer.parseInt(TMXDate.substring(9, 11));
int date = Integer.parseInt(TMXDate.substring(6, 8));
int month = Integer.parseInt(TMXDate.substring(4, 6)) - 1;
int year = Integer.parseInt(TMXDate.substring(0, 4));
calendar.set(year, month, date, hour, minute, second);
DateFormat dt = DateFormat.getDateTimeInstance();
return dt.format(calendar.getTime());
} catch (Exception e) {
return ""; //$NON-NLS-1$
}
}
/**
* 得到文件夹下的所有文件(包括子文件夹中的文件)。
* @param folder
* 文件夹
* @param fileExtension
* 后缀名
* @param list
* 所有文件 ;
*/
public static void getChildFiles(File folder, String fileExtension, List<File> list) {
if (list == null) {
list = new ArrayList<File>();
}
if (folder.exists() && folder.isDirectory()) {
File[] files = folder.listFiles();
for (File file : files) {
if (file.isFile()) {
String fileName = file.getName().toLowerCase();
if (fileName.endsWith("." + fileExtension)) {
list.add(file);
}
} else if (file.isDirectory()) {
getChildFiles(file, fileExtension, list);
}
}
}
}
/**
* break a path down into individual elements and add to a list. example : if a path is /a/b/c/d.txt, the breakdown
* will be [d.txt,c,b,a]
* @param file
* input file
* @return a Vector with the individual elements of the path in reverse order
*/
private static Vector<String> getPathList(File file) throws IOException {
Vector<String> list = new Vector<String>();
File r;
r = file.getCanonicalFile();
while (r != null) {
list.add(r.getName());
r = r.getParentFile();
}
return list;
}
/**
* figure out a string representing the relative path of 'f' with respect to 'r'
* @param r
* home path
* @param f
* path of file
*/
private static String matchPathLists(Vector<String> r, Vector<String> f) {
int i;
int j;
String s = ""; //$NON-NLS-1$
// start at the beginning of the lists
// iterate while both lists are equal
i = r.size() - 1;
j = f.size() - 1;
// first eliminate common root
while (i >= 0 && j >= 0 && r.get(i).equals(f.get(j))) {
i--;
j--;
}
// for each remaining level in the home path, add a ..
for (; i >= 0; i--) {
s += ".." + File.separator; //$NON-NLS-1$
}
// for each level in the file path, add the path
for (; j >= 1; j--) {
s += f.get(j) + File.separator;
}
// file name
if (j >= 0 && j < f.size()) {
s += f.get(j);
}
return s;
}
/**
* get relative path of File 'f' with respect to 'home' directory example : home = /a/b/c f = /a/d/e/x.txt s =
* getRelativePath(home,f) = ../../d/e/x.txt
* @param home
* base path, should be a directory, not a file, or it doesn't make sense
* @param f
* file to generate path for
* @return path from home to f as a string
*/
public static String getRelativePath(String homeFile, String filename) throws Exception {
File home = new File(homeFile);
// If home is a file, get the parent
if (!home.isDirectory()) {
home = new File(home.getParent());
}
File file = new File(filename);
// Check for relative path
if (!home.isAbsolute() || !file.isAbsolute()) {
throw new Exception(Messages.getString("util.CommonFunction.logger1"));
}
Vector<String> homelist;
Vector<String> filelist;
homelist = getPathList(home);
filelist = getPathList(file);
return matchPathLists(homelist, filelist);
}
public static String getAbsolutePath(String homeFile, String relative) throws IOException {
File home = new File(homeFile);
// If home is a file, get the parent
File result;
if (home.isDirectory()) {
result = new File(home.getAbsolutePath(), relative);
} else {
result = new File(home.getParent(), relative);
}
return result.getCanonicalPath();
}
/**
* 验证xliff文件的后缀名 robert 2012-06-20
* @param extention
* @return
*/
public static boolean validXlfExtension(String extention){
return xlfExtensionList.contains(extention);
}
/**
* 通过xliff文件的名称或路径验证xliff文件的后缀名是否合法 robert 2012-06-20
* @param extention
* @return
*/
public static boolean validXlfExtensionByFileName(String xlfName){
if (xlfName.lastIndexOf(".") < 0) {
return false;
}
String extention = xlfName.substring(xlfName.lastIndexOf("."), xlfName.length());
if (extention == null) {
return false;
}
return xlfExtensionList.contains(extention);
}
/**
* 获取当前系统语言
* @return
*/
public static String getSystemLanguage() {
return systemLanguage;
}
/**
* 设置当前系统语言,标识,与preferenceStore中的数据同步
* @return
*/
public static void setSystemLanguage(String systemLanguage) {
CommonFunction.systemLanguage = systemLanguage;
}
/**
* 删除 选中文件集合 中重复的文件 robert 2012-11-09
* @param selectIFileList
*/
public static void removeRepeateSelect(List<IFile> selectIFileList){
HashSet<IFile> set = new HashSet<IFile>(selectIFileList);
selectIFileList.clear();
selectIFileList.addAll(set);
}
/**
* 验证当前版本
* @param editionId
* 版本 Id 值(旗舰版为 U,专业版为 F,个人版为 P,精简版为 L)
* @return ;
*/
public static boolean checkEdition(String editionId) {
return editionId == null ? false : System.getProperty("TSEdition").equals(editionId);
}
/**
* 当删除一个文件时,刷新历史记录 --robert 2012-11-20
*/
@SuppressWarnings("restriction")
public static void refreshHistoryWhenDelete(IEditorInput input){
IWorkbench workbench = PlatformUI.getWorkbench();
if (workbench instanceof Workbench) {
EditorHistory history = ((Workbench) workbench).getEditorHistory();
for (EditorHistoryItem item : history.getItems()) {
if (item.matches(input)) {
history.remove(item);
}
}
history.refresh();
}
}
/**
* 判断指定语言是否是亚洲语系 robert 2012-12-27
* @return
*/
public static boolean isAsiaLang(String lang){
if (lang.toLowerCase().matches("zh.*|ja.*|ko.*|th.*|he.*")) {
return true;
}
return false;
}
/**
* 当程序开始运行时,检查 qa 插件是否存在,如果不存在,则不执行任何操作,如果存在,则检查 configuration\net.heartsome.cat.ts.ui\hunspell
* 下面是否有 hunspell 运行所需要的词典以及运行函数库。如果没有,则需要从 qa 插件中进行获取,并且解压到上述目录下。
* robert 2013-02-28
*/
public static void unZipHunspellDics() throws Exception{
Bundle bundle = Platform.getBundle("net.heartsome.cat.ts.ui.qa");
if (bundle == null) {
return;
}
// 查看解压的 hunspell词典 文件夹是否存在
String configHunspllDicFolder = Platform.getConfigurationLocation().getURL().getPath()
+ "net.heartsome.cat.ts.ui" + System.getProperty("file.separator") + "hunspell"
+ System.getProperty("file.separator") + "hunspellDictionaries";
if (!new File(configHunspllDicFolder).exists()) {
new File(configHunspllDicFolder).mkdirs();
String hunspellDicZipPath = FileLocator.toFileURL(bundle.getEntry("hunspell/hunspellDictionaries.zip")).getPath();
upZipFile(hunspellDicZipPath, configHunspllDicFolder);
}
}
public static String upZipFile(String zipFile, String baseDir) throws IOException {
File f = new File(zipFile);
if (baseDir == null) {
baseDir = f.getPath() + "_files";
}
ZipInputStream zis = new ZipInputStream(new FileInputStream(f));
ZipEntry ze;
byte[] buf = new byte[1024];
while ((ze = zis.getNextEntry()) != null) {
File outFile = getRealFileName(baseDir, ze.getName());
FileOutputStream os = new FileOutputStream(outFile);
int readLen = 0;
while ((readLen = zis.read(buf, 0, 1024)) != -1) {
os.write(buf, 0, readLen);
}
os.close();
}
zis.close();
return baseDir;
}
/**
* 给定根目录,返回一个相对路径所对应的实际文件名.
* @param baseDir
* 指定根目录
* @param absFileName
* 相对路径名,来自于ZipEntry中的name
* @return java.io.File 实际的文件
*/
private static File getRealFileName(String baseDir, String absFileName) {
String[] dirs = absFileName.split("/");
File ret = new File(baseDir);
if (!ret.exists()) {
ret.mkdirs();
}
if ("/".equals(System.getProperty("file.separator"))) {
for (int i = 0; i < dirs.length; i++) {
dirs[i] = dirs[i].replace("\\", "/");
}
}
if (dirs.length >= 1) {
for (int i = 0; i < dirs.length - 1; i++) {
ret = new File(ret, dirs[i]);
}
if (!ret.exists()) {
ret.mkdirs();
}
ret = new File(ret, dirs[dirs.length - 1]);
if(!ret.exists()){
File p = ret.getParentFile();
if(!p.exists()){
p.mkdirs();
}
}
}
return ret;
}
/**
* 关闭指定文件的编辑器 -- robert 2013-04-01
* 备注:这里面的方法,是不能获取 nattable 的实例,故,在处理 合并打开的情况时,是通过 vtd 进行解析 合并临时文件从而获取相关文件的
* @param iFileList
*/
public static void closePointEditor(List<IFile> iFileList){
Map<IFile, IEditorPart> openedIfileMap = new HashMap<IFile, IEditorPart>();
IEditorReference[] referenceArray = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getEditorReferences();
for(IEditorReference reference : referenceArray){
IEditorPart editor = reference.getEditor(true);
IFile iFile = ((FileEditorInput)editor.getEditorInput()).getFile();
// 如果这是一个 nattable 编辑器
if (XLIFF_EDITOR_ID.equals(editor.getSite().getId())) {
String iFilePath = iFile.getLocation().toOSString();
String extension = iFile.getFileExtension();
if ("hsxliff".equals(extension)) {
openedIfileMap.put(iFile, editor);
}else if ("xlp".equals(extension)) {
// 这是合并打开的情况
// 开始解析这个合并打开临时文件,获取合并打开的文件。
VTDGen vg = new VTDGen();
if (vg.parseFile(iFilePath, true)) {
VTDNav vn = vg.getNav();
AutoPilot ap = new AutoPilot(vn);
try {
ap.selectXPath("/mergerFiles/mergerFile/@filePath");
int index = -1;
while ((index = ap.evalXPath()) != -1) {
String fileLC = vn.toString(index + 1);
if (fileLC != null && !"".equals(fileLC)) {
openedIfileMap.put(ResourceUtils.fileToIFile(fileLC), editor);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}else {
// 其他情况,直接将文件丢进去就行了
openedIfileMap.put(iFile, editor);
}
IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
for(IFile curIfile : iFileList){
if (openedIfileMap.containsKey(curIfile)) {
page.closeEditor(openedIfileMap.get(curIfile), false);
}
}
}
}
/**
* 验证资源的合法性 robert 2013-07-01
* @param resourceName
* @return 如果返回的是 null ,则标志验证通过,否则,将返回的 字符串 以对话框的形式弹出
*/
public static String validResourceName(String resourceName){
char[] errorChars = new char[]{'/', '\\', ':', '?', '"', '<', '>', '|'};
if (Platform.getOS().indexOf("win") == -1) {
String errorCharStr = "";
for (int i = 0; i < errorChars.length; i++){
if (resourceName.indexOf(errorChars[i]) != -1) {
errorCharStr += errorChars[i] + "、";
}
}
if (errorCharStr.length() > 0) {
errorCharStr = errorCharStr.substring(0, errorCharStr.length() - 1);
String errorTip = MessageFormat.format(Messages.getString("Commonfunciton.valid.waring"), errorCharStr, resourceName);
return errorTip;
}
}
return null;
}
/**
* 当退出软件时。若有未关闭的 job。进行提示 robert 2013-09-12
* @param jobName
*/
public static void jobCantCancelTip(final Job job){
PlatformUI.getWorkbench().addWorkbenchListener(new IWorkbenchListener() {
public boolean preShutdown(IWorkbench workbench, boolean forced) {
System.out.println("job.isBlocking() = " + (job.getState()));
if (job.getState() != Job.NONE) {
MessageDialog.openInformation(Display.getDefault().getActiveShell(),
Messages.getString("file.XLFValidator.msgTitle"),
MessageFormat.format(Messages.getString("Commonfunction.job.tip"), job.getName()));
return false;
}else {
return true;
}
}
public void postShutdown(IWorkbench workbench) {
}
});
}
/**
* 创建 UUID,唯一标识符 --robert 2013-10-17
* @return
*/
public static String createUUID(){
UUID uuId = UUID.randomUUID();
return uuId.toString();
}
}
| 20,607 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
DateUtils.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/base_commons/net.heartsome.cat.common.core/src/net/heartsome/cat/common/util/DateUtils.java | package net.heartsome.cat.common.util;
import java.text.ParseException;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Locale;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* 时间处理
* @author Jason
* @version
* @since JDK1.6
*/
public class DateUtils {
public static Calendar calendar = new GregorianCalendar(); // 默认当前时间的实例
/**
* 获取现在的年份
* @return
*/
public static int getCurYear() {
return calendar.get(Calendar.YEAR);
}
/**
* 获取现在的年份
* @param calendar
* @return
*/
public static int getCurYear(Calendar calendar) {
return calendar.get(Calendar.YEAR);
}
/**
* 获取现在的月份
* @return
*/
public static int getCurMonth() {
return calendar.get(Calendar.MONTH);
}
/**
* 获取现在的月份
* @param calendar
* @return 月份从0开始
*/
public static int getCurMonth(Calendar calendar) {
return calendar.get(Calendar.MONTH);
}
/**
* 获取现在的日期
* @return
*/
public static int getCurDay() {
return calendar.get(Calendar.DAY_OF_MONTH);
}
/**
* 获取现在的日期
* @param calendar
* @return
*/
public static int getCurDay(Calendar calendar) {
return calendar.get(Calendar.DAY_OF_MONTH);
}
/**
* 获取现在时间
* @return 返回时间类型 yyyy-MM-dd HH:mm:ss
*/
public static Date getNowDate() {
Date currentTime = new Date();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String dateString = formatter.format(currentTime);
ParsePosition pos = new ParsePosition(8);
Date currentTime_2 = formatter.parse(dateString, pos);
return currentTime_2;
}
/**
* 获取现在时间
* @return返回短时间格式 yyyy-MM-dd
*/
public static Date getNowDateShort() {
Date currentTime = new Date();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
String dateString = formatter.format(currentTime);
ParsePosition pos = new ParsePosition(8);
Date currentTime_2 = formatter.parse(dateString, pos);
return currentTime_2;
}
/**
* 获取现在时间
* @return返回字符串格式 yyyy-MM-dd HH:mm:ss
*/
public static String getStringDate() {
Date currentTime = new Date();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String dateString = formatter.format(currentTime);
return dateString;
}
/**
* 获取现在时间
* @return 返回短时间字符串格式yyyy-MM-dd
*/
public static String getStringDateShort() {
Date currentTime = new Date();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
String dateString = formatter.format(currentTime);
return dateString;
}
/**
* 获取时间 小时:分;秒 HH:mm:ss
* @return
*/
public static String getTimeShort() {
SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss");
Date currentTime = new Date();
String dateString = formatter.format(currentTime);
return dateString;
}
/**
* 将长时间格式字符串转换为时间 yyyy-MM-dd HH:mm:ss
* @param strDate
* @return
*/
public static Date strToDateLong(String strDate) {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
ParsePosition pos = new ParsePosition(0);
Date strtodate = formatter.parse(strDate, pos);
return strtodate;
}
/**
* 将长时间格式时间转换为字符串 yyyy-MM-dd HH:mm:ss
* @param dateDate
* @return
*/
public static String dateToStrLong(java.util.Date dateDate) {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String dateString = formatter.format(dateDate);
return dateString;
}
/**
* 将短时间格式时间转换为字符串 yyyy-MM-dd
* @param dateDate
* @param k
* @return
*/
public static String dateToStr(java.util.Date dateDate) {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
String dateString = formatter.format(dateDate);
return dateString;
}
/**
* 将短时间格式字符串转换为时间 yyyy-MM-dd
* @param strDate
* @return
*/
public static Date strToDate(String strDate) {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
ParsePosition pos = new ParsePosition(0);
Date strtodate = formatter.parse(strDate, pos);
return strtodate;
}
/**
* 得到现在时间
* @return
*/
public static Date getNow() {
Date currentTime = new Date();
return currentTime;
}
/**
* 提取一个月中的最后一天
* @param day
* @return
*/
public static Date getLastDate(long day) {
Date date = new Date();
long date_3_hm = date.getTime() - 3600000 * 34 * day;
Date date_3_hm_date = new Date(date_3_hm);
return date_3_hm_date;
}
/**
* 得到现在时间
* @return 字符串 yyyyMMdd HHmmss
*/
public static String getStringToday() {
Date currentTime = new Date();
SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd HHmmss");
String dateString = formatter.format(currentTime);
return dateString;
}
/**
* 得到现在小时
*/
public static String getHour() {
Date currentTime = new Date();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String dateString = formatter.format(currentTime);
String hour;
hour = dateString.substring(11, 13);
return hour;
}
/**
* 得到现在分钟
* @return
*/
public static String getTime() {
Date currentTime = new Date();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String dateString = formatter.format(currentTime);
String min;
min = dateString.substring(14, 16);
return min;
}
/**
* 根据用户传入的时间表示格式,返回当前时间的格式 如果是yyyyMMdd,注意字母y不能大写。
* @param sformat
* yyyyMMddhhmmss
* @return
*/
public static String getUserDate(String sformat) {
Date currentTime = new Date();
SimpleDateFormat formatter = new SimpleDateFormat(sformat);
String dateString = formatter.format(currentTime);
return dateString;
}
/**
* 二个小时时间间的差值,必须保证二个时间都是"HH:MM"的格式,返回字符型的分钟
*/
public static String getTwoHour(String st1, String st2) {
String[] kk = null;
String[] jj = null;
kk = st1.split(":");
jj = st2.split(":");
if (Integer.parseInt(kk[0]) < Integer.parseInt(jj[0]))
return "0";
else {
double y = Double.parseDouble(kk[0]) + Double.parseDouble(kk[1]) / 60;
double u = Double.parseDouble(jj[0]) + Double.parseDouble(jj[1]) / 60;
if ((y - u) > 0)
return y - u + "";
else
return "0";
}
}
/**
* 得到二个日期间的间隔天数
*/
public static String getTwoDay(String sj1, String sj2) {
SimpleDateFormat myFormatter = new SimpleDateFormat("yyyy-MM-dd");
long day = 0;
try {
java.util.Date date = myFormatter.parse(sj1);
java.util.Date mydate = myFormatter.parse(sj2);
day = (date.getTime() - mydate.getTime()) / (24 * 60 * 60 * 1000);
} catch (Exception e) {
return "";
}
return day + "";
}
/**
* 时间前推或后推分钟,其中JJ表示分钟.
*/
public static String getPreTime(String sj1, String jj) {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String mydate1 = "";
try {
Date date1 = format.parse(sj1);
long Time = (date1.getTime() / 1000) + Integer.parseInt(jj) * 60;
date1.setTime(Time * 1000);
mydate1 = format.format(date1);
} catch (Exception e) {
}
return mydate1;
}
/**
* 得到一个时间延后或前移几天的时间,nowdate为时间,delay为前移或后延的天数
*/
public static String getNextDay(String nowdate, String delay) {
try {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
String mdate = "";
Date d = strToDate(nowdate);
long myTime = (d.getTime() / 1000) + Integer.parseInt(delay) * 24 * 60 * 60;
d.setTime(myTime * 1000);
mdate = format.format(d);
return mdate;
} catch (Exception e) {
return "";
}
}
/**
* 判断是否闰年
* @param ddate
* @return
*/
public static boolean isLeapYear(String ddate) {
/**
* 详细设计: 1.被400整除是闰年,否则: 2.不能被4整除则不是闰年 3.能被4整除同时不能被100整除则是闰年 3.能被4整除同时能被100整除则不是闰年
*/
Date d = strToDate(ddate);
GregorianCalendar gc = (GregorianCalendar) Calendar.getInstance();
gc.setTime(d);
int year = gc.get(Calendar.YEAR);
if ((year % 400) == 0)
return true;
else if ((year % 4) == 0) {
if ((year % 100) == 0)
return false;
else
return true;
} else
return false;
}
/**
* 返回美国时间格式 26 Apr 2006
* @param str
* @return
*/
public static String getEDate(String str) {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
ParsePosition pos = new ParsePosition(0);
Date strtodate = formatter.parse(str, pos);
String j = strtodate.toString();
String[] k = j.split(" ");
return k[2] + k[1].toUpperCase() + k[5].substring(2, 4);
}
/**
* 获取一个月的最后一天
* @param dat
* @return
*/
public static String getEndDateOfMonth(String dat) {// yyyy-MM-dd
String str = dat.substring(0, 8);
String month = dat.substring(5, 7);
int mon = Integer.parseInt(month);
if (mon == 1 || mon == 3 || mon == 5 || mon == 7 || mon == 8 || mon == 10 || mon == 12) {
str += "31";
} else if (mon == 4 || mon == 6 || mon == 9 || mon == 11) {
str += "30";
} else {
if (isLeapYear(dat)) {
str += "29";
} else {
str += "28";
}
}
return str;
}
/**
* 判断二个时间是否在同一个周
* @param date1
* @param date2
* @return
*/
public static boolean isSameWeekDates(Date date1, Date date2) {
Calendar cal1 = Calendar.getInstance();
Calendar cal2 = Calendar.getInstance();
cal1.setTime(date1);
cal2.setTime(date2);
int subYear = cal1.get(Calendar.YEAR) - cal2.get(Calendar.YEAR);
if (0 == subYear) {
if (cal1.get(Calendar.WEEK_OF_YEAR) == cal2.get(Calendar.WEEK_OF_YEAR))
return true;
} else if (1 == subYear && 11 == cal2.get(Calendar.MONTH)) {
// 如果12月的最后一周横跨来年第一周的话则最后一周即算做来年的第一周
if (cal1.get(Calendar.WEEK_OF_YEAR) == cal2.get(Calendar.WEEK_OF_YEAR))
return true;
} else if (-1 == subYear && 11 == cal1.get(Calendar.MONTH)) {
if (cal1.get(Calendar.WEEK_OF_YEAR) == cal2.get(Calendar.WEEK_OF_YEAR))
return true;
}
return false;
}
/**
* 产生周序列,即得到当前时间所在的年度是第几周
* @return
*/
public static String getSeqWeek() {
Calendar c = Calendar.getInstance(Locale.CHINA);
String week = Integer.toString(c.get(Calendar.WEEK_OF_YEAR));
if (week.length() == 1)
week = "0" + week;
String year = Integer.toString(c.get(Calendar.YEAR));
return year + week;
}
/**
* 获得一个日期所在的周的星期几的日期,如要找出2002年2月3日所在周的星期一是几号
* @param sdate
* @param num
* @return
*/
public static String getWeek(String sdate, String num) {
// 再转换为时间
Date dd = DateUtils.strToDate(sdate);
Calendar c = Calendar.getInstance();
c.setTime(dd);
if (num.equals("1")) // 返回星期一所在的日期
c.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
else if (num.equals("2")) // 返回星期二所在的日期
c.set(Calendar.DAY_OF_WEEK, Calendar.TUESDAY);
else if (num.equals("3")) // 返回星期三所在的日期
c.set(Calendar.DAY_OF_WEEK, Calendar.WEDNESDAY);
else if (num.equals("4")) // 返回星期四所在的日期
c.set(Calendar.DAY_OF_WEEK, Calendar.THURSDAY);
else if (num.equals("5")) // 返回星期五所在的日期
c.set(Calendar.DAY_OF_WEEK, Calendar.FRIDAY);
else if (num.equals("6")) // 返回星期六所在的日期
c.set(Calendar.DAY_OF_WEEK, Calendar.SATURDAY);
else if (num.equals("0")) // 返回星期日所在的日期
c.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
return new SimpleDateFormat("yyyy-MM-dd").format(c.getTime());
}
/**
* 根据一个日期,返回是星期几的字符串
* @param sdate
* @return
*/
public static String getWeek(String sdate) {
// 再转换为时间
Date date = DateUtils.strToDate(sdate);
Calendar c = Calendar.getInstance();
c.setTime(date);
// int hour=c.get(Calendar.DAY_OF_WEEK);
// hour中存的就是星期几了,其范围 1~7
// 1=星期日 7=星期六,其他类推
return new SimpleDateFormat("EEEE").format(c.getTime());
}
/**
* 此方法未用到,因此未做国际化处理,如果将来要使用此方法,请对方法里面的值做国际化处理
* @param sdate
* @return ;
*/
public static String getWeekStr(String sdate) {
String str = "";
str = DateUtils.getWeek(sdate);
if ("1".equals(str)) {
str = "星期日";
} else if ("2".equals(str)) {
str = "星期一";
} else if ("3".equals(str)) {
str = "星期二";
} else if ("4".equals(str)) {
str = "星期三";
} else if ("5".equals(str)) {
str = "星期四";
} else if ("6".equals(str)) {
str = "星期五";
} else if ("7".equals(str)) {
str = "星期六";
}
return str;
}
/**
* 两个时间之间的天数
* @param date1
* @param date2
* @return
*/
public static long getDays(String date1, String date2) {
if (date1 == null || date1.equals(""))
return 0;
if (date2 == null || date2.equals(""))
return 0;
// 转换为标准时间
SimpleDateFormat myFormatter = new SimpleDateFormat("yyyy-MM-dd");
java.util.Date date = null;
java.util.Date mydate = null;
try {
date = myFormatter.parse(date1);
mydate = myFormatter.parse(date2);
} catch (Exception e) {
}
long day = (date.getTime() - mydate.getTime()) / (24 * 60 * 60 * 1000);
return day + 1;
}
/**
* 形成如下的日历 , 根据传入的一个时间返回一个结构 星期日 星期一 星期二 星期三 星期四 星期五 星期六 下面是当月的各个时间 此函数返回该日历第一行星期日所在的日期
* @param sdate
* @return
*/
public static String getNowMonth(String sdate) {
// 取该时间所在月的一号
sdate = sdate.substring(0, 8) + "01";
// 得到这个月的1号是星期几
Date date = DateUtils.strToDate(sdate);
Calendar c = Calendar.getInstance();
c.setTime(date);
int u = c.get(Calendar.DAY_OF_WEEK);
String newday = DateUtils.getNextDay(sdate, (1 - u) + "");
return newday;
}
/**
* 取得数据库主键 生成格式为yyyymmddhhmmss+k位随机数
* @param k
* 表示是取几位随机数,可以自己定
*/
public static String getNo(int k) {
return getUserDate("yyyyMMddhhmmss") + getRandom(k);
}
/**
* 返回一个随机数
* @param i
* @return
*/
public static String getRandom(int i) {
Random jjj = new Random();
// int suiJiShu = jjj.nextInt(9);
if (i == 0)
return "";
String jj = "";
for (int k = 0; k < i; k++) {
jj = jj + jjj.nextInt(9);
}
return jj;
}
/**
* @param args
*/
public static boolean RightDate(String date) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
if (date == null)
return false;
if (date.length() > 10) {
sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
} else {
sdf = new SimpleDateFormat("yyyy-MM-dd");
}
try {
sdf.parse(date);
} catch (ParseException pe) {
return false;
}
return true;
}
/**
* 返回两个日期间的天数,去除周末的天数
* @param startdate
* ,enddate 格式“yyyy-MM-dd”
* @return
*/
public static int getdaysslice(String startdate, String enddate) {
if (startdate == null || "".equals(startdate.trim()))
return 0;
if (enddate == null || "".equals(enddate.trim()))
return 0;
SimpleDateFormat myFormatter = new SimpleDateFormat("yyyy-MM-dd");
java.util.Date start = null;
java.util.Date end = null;
try {
start = myFormatter.parse(startdate);
end = myFormatter.parse(enddate);
} catch (Exception e) {
return 0;
}
long daynum = (end.getTime() - start.getTime()) / (24 * 60 * 60 * 1000);
Calendar startcalendar = new GregorianCalendar();
startcalendar.setTime(start);
int n = 0;
for (int i = 0; i <= daynum; i++) {
if (startcalendar.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY
|| startcalendar.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) {
startcalendar.add(Calendar.DAY_OF_MONTH, 1);
continue;
}
startcalendar.add(Calendar.DAY_OF_MONTH, 1);
n++;
}
return n;
}
/**
* 返回给定连接符的日期字符串
* @param date
* 需要转换的字符串,separator 日期格式中连接的字符 例如:20071227——>2007-12-27
* @return
*/
public static String formatToYYYYMMDD(String date, String separator) {
if (null == date || "".equals(date) || null == separator || "".equals(separator)) {
return date;
}
StringBuffer sb = new StringBuffer();
String reg = "[0-9]{4}(01|02|03|04|05|06|07|08|09|10|11|12){1}(01|02|03|04|05|06|07|08|09|10|11|12|13|14|15|16|17|18|19|20|21|22|23|24|25|26|27|28|29|30|31){1}";
Pattern p = Pattern.compile(reg);
Matcher m = p.matcher(date);
int offset = 0;
while (m.find(offset)) {
int sIndex = m.start();
int eIndex = m.end();
String tmpPrefix = date.substring(offset, sIndex);
sb.append(tmpPrefix);
String tmpDate = date.substring(sIndex, eIndex);
String tmpYYYY = tmpDate.substring(0, 4);
String tmpMM = tmpDate.substring(4, 6);
String tmpDD = tmpDate.substring(6, 8);
sb.append(tmpYYYY);
sb.append(separator);
sb.append(tmpMM);
sb.append(separator);
sb.append(tmpDD);
offset = m.end();
}
String tmpSuffix = date.substring(offset, date.length());
sb.append(tmpSuffix);
return sb.toString();
}
public static java.sql.Timestamp getTimestampFromUTC(String utcFormat) {
if (utcFormat == null || utcFormat.equals("")) {
return null;
}
SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd'T'HHmmss'Z'");
ParsePosition pos = new ParsePosition(0);
Date strtodate = formatter.parse(utcFormat, pos);
if (strtodate == null) {
strtodate = new Date();
}
return new java.sql.Timestamp(strtodate.getTime());
}
public static Date getDateFromUTC(String utcFormat) {
SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd'T'HHmmssZ");
ParsePosition pos = new ParsePosition(0);
Date strtodate = formatter.parse(utcFormat, pos);
if (strtodate == null) {
strtodate = new Date();
}
return strtodate;
}
public static String formatToUTC(long datetime) {
return formatLongTime(datetime, "yyyyMMdd'T'HHmmss'Z'");
}
public static String formatLongTime(long datetime, String format) {
SimpleDateFormat formatter = new SimpleDateFormat(format);
return formatter.format(new Date(datetime));
}
public static String formatDateFromUTC(String utcFormat) {
if (utcFormat == null || utcFormat.equals("")) {
return null;
}
SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd'T'HHmmss'Z'");
ParsePosition pos = new ParsePosition(0);
Date strtodate = formatter.parse(utcFormat, pos);
if (strtodate == null) {
strtodate = new Date();
}
return formatLongTime(strtodate.getTime(), "yyyy-MM-dd,HH:mm");
}
/**
* @param args
*/
public static void main(String[] args) {
System.out.println(formatToUTC(00));
System.out.println(getTimestampFromUTC("20080415T000000Z"));
System.out.println(getTimestampFromUTC("20080415T043215Z"));
System.out.println(getDateFromUTC("200804015T102502+0800"));
// String test = "Today is 20071227,tommrow is 20071228.";
// System.out.println(test.length());
// String result = DateUtils.formatToYYYYMMDD(test, "-");
System.out.println(formatDateFromUTC("20080415T043215Z"));
// System.out.println(result.length());
// System.out.println(dateToStr(strToDate("20111110000000")));
System.out.println(System.currentTimeMillis());
}
}
| 20,142 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
AbstractShieldCommandStartup.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/base_commons/net.heartsome.cat.common.ui.shield/src/net/heartsome/cat/common/ui/shield/AbstractShieldCommandStartup.java | package net.heartsome.cat.common.ui.shield;
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.text.MessageFormat;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import net.heartsome.cat.common.ui.shield.resource.Messages;
import org.eclipse.core.commands.Command;
import org.eclipse.ui.IStartup;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.commands.ICommandService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* 在工作台初始化后,移除不需要用到的平台默认 command。
* @author cheney
* @since JDK1.6
*/
public abstract class AbstractShieldCommandStartup implements IStartup {
private final static Logger LOGGER = LoggerFactory.getLogger(AbstractShieldCommandStartup.class);
public void earlyStartup() {
Set<String> unusedCommand = getUnusedCommandSet();
IWorkbench workbench = PlatformUI.getWorkbench();
ICommandService commandService = (ICommandService) workbench.getService(ICommandService.class);
Command command;
for (String commandId : unusedCommand) {
command = commandService.getCommand(commandId);
command.undefine();
}
}
/**
* 不需要用到的平台默认 command id 集合。
* @return 不需要用到的平台默认 command id 集合,非 NULL;
*/
abstract protected Set<String> getUnusedCommandSet();
@SuppressWarnings("unchecked")
protected Set<String> readUnusedCommandFromFile(String relativePath) {
Set<String> set = Collections.EMPTY_SET;
File file = ShieldActivator.getFile(relativePath);
if (file != null) {
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
String line = null;
set = new HashSet<String>();
while ((line = br.readLine()) != null) {
// 忽略以 # 开头注释行
if (line.startsWith("#"))
continue;
line = line.trim();
// 忽略空行
if (line.length() == 0)
continue;
set.add(line);
}
} catch (FileNotFoundException e) {
if (LOGGER.isErrorEnabled()) {
String msg = Messages.getString("shield.AbstractShieldCommandStartup.logger1");
Object[] args = { file.getAbsolutePath() };
LOGGER.error(new MessageFormat(msg).format(args), e);
}
} catch (IOException e) {
if (LOGGER.isErrorEnabled()) {
String msg = Messages.getString("shield.AbstractShieldCommandStartup.logger2");
Object[] args = { file.getAbsolutePath() };
LOGGER.error(new MessageFormat(msg).format(args), e);
}
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
if (LOGGER.isErrorEnabled()) {
String msg = Messages.getString("shield.AbstractShieldCommandStartup.logger3");
Object[] args = { file.getAbsolutePath() };
LOGGER.error(new MessageFormat(msg).format(args), e);
}
}
}
}
}
return set;
}
}
| 3,077 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
ShieldActivator.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/base_commons/net.heartsome.cat.common.ui.shield/src/net/heartsome/cat/common/ui/shield/ShieldActivator.java | package net.heartsome.cat.common.ui.shield;
import java.io.File;
import java.net.URL;
import java.text.MessageFormat;
import net.heartsome.cat.common.ui.shield.resource.Messages;
import org.eclipse.core.runtime.FileLocator;
import org.eclipse.ui.plugin.AbstractUIPlugin;
import org.osgi.framework.BundleContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
*此插件的 Activator 类
* @author cheney
* @since JDK1.6
*/
public class ShieldActivator extends AbstractUIPlugin {
public final static String PLUGIN_ID = "net.heartsome.cat.common.ui.shield";
private final static Logger LOGGER = LoggerFactory.getLogger(ShieldActivator.class);
private static ShieldActivator plugin;
public ShieldActivator() {
// TODO Auto-generated constructor stub
}
@Override
public void start(BundleContext context) throws Exception {
super.start(context);
plugin = this;
}
@Override
public void stop(BundleContext context) throws Exception {
plugin = null;
super.stop(context);
}
/**
* Returns the shared instance
* @return the shared instance
*/
public static ShieldActivator getDefault() {
return plugin;
}
/**
* 根据相对于插件根目录的相对路径,在插件中查找相应的文件,查找成功则返回对应的文件对象
* @param relativePath
* 对于插件根目录的相对路径
* @return 查找成功则返回对应的文件对象,否则返回 NULL;
*/
public static File getFile(String relativePath) {
File file = null;
URL langCodesURL = plugin.getBundle().getEntry(relativePath);
if (langCodesURL != null) {
try {
file = new File(FileLocator.toFileURL(langCodesURL).getPath());
} catch (Exception e) {
if (LOGGER.isErrorEnabled()) {
String msg = Messages.getString("shield.ShieldActivator.logger1");
Object[] args = { relativePath };
LOGGER.error(new MessageFormat(msg).format(args), e);
}
}
}
return file;
}
}
| 1,959 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
ShieldStartup.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/base_commons/net.heartsome.cat.common.ui.shield/src/net/heartsome/cat/common/ui/shield/ShieldStartup.java | package net.heartsome.cat.common.ui.shield;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.core.commands.ParameterizedCommand;
import org.eclipse.jface.bindings.Binding;
import org.eclipse.jface.bindings.BindingManager;
import org.eclipse.jface.bindings.Scheme;
import org.eclipse.ui.IStartup;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.internal.keys.BindingService;
import org.eclipse.ui.keys.IBindingService;
/**
* 在工作台初始化后,移除平台默认的 scheme
* @author cheney
* @since JDK1.6
*/
public class ShieldStartup implements IStartup {
private final static String platformDefaultScheme = "org.eclipse.ui.defaultAcceleratorConfiguration";
private final static String platformEmacsScheme = "org.eclipse.ui.emacsAcceleratorConfiguration";
public void earlyStartup() {
IWorkbench workbench = PlatformUI.getWorkbench();
// 在工作台初始化后,移除平台默认的 scheme
IBindingService bindingService = (IBindingService) workbench.getService(IBindingService.class);
Scheme[] schemes = bindingService.getDefinedSchemes();
for (int i = 0; i < schemes.length; i++) {
String id = schemes[i].getId();
if (id.equals(platformDefaultScheme) || id.equals(platformEmacsScheme)) {
schemes[i].undefine();
}
}
}
}
| 1,342 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
DisabledNewEditorHandler.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/base_commons/net.heartsome.cat.common.ui.shield/src/net/heartsome/cat/common/ui/shield/handlers/DisabledNewEditorHandler.java | package net.heartsome.cat.common.ui.shield.handlers;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.commands.IHandler;
import org.eclipse.core.commands.IHandlerListener;
public class DisabledNewEditorHandler implements IHandler {
public void addHandlerListener(IHandlerListener handlerListener) {
}
public void dispose() {
}
public Object execute(ExecutionEvent event) throws ExecutionException {
return null;
}
public boolean isEnabled() {
return false; // 设为不可用
}
public boolean isHandled() {
return true;
}
public void removeHandlerListener(IHandlerListener handlerListener) {
}
}
| 700 | 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_commons/net.heartsome.cat.common.ui.shield/src/net/heartsome/cat/common/ui/shield/resource/Messages.java | package net.heartsome.cat.common.ui.shield.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.common.ui.shield.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;
}
}
}
| 570 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
ResourceToItemsMapper.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/base_commons/net.heartsome.cat.common.ui.navigator.resources/src/org/eclipse/ui/internal/navigator/resources/ResourceToItemsMapper.java | /*******************************************************************************
* Copyright (c) 2000, 2009 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.ui.internal.navigator.resources;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Stack;
import org.eclipse.swt.widgets.Item;
import org.eclipse.ui.navigator.CommonViewer;
import org.eclipse.ui.navigator.ICommonViewerMapper;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.IAdaptable;
/**
* Adds a supplemental map for the CommonViewer to efficiently handle resource
* changes. When objects are added to the Viewer's map, this is called to see
* if there is an associated resource. If so, it's added to the map here.
* When resource change notifications happen, this map is checked, and if the
* resource is found, this class causes the Viewer to be updated. If the
* resource is not found, the notification can be ignored because the object
* corresponding to the resource is not present in the viewer.
*
*/
public class ResourceToItemsMapper implements ICommonViewerMapper {
private static final int NUMBER_LIST_REUSE = 10;
// map from resource to item
private HashMap _resourceToItem;
private Stack _reuseLists;
private CommonViewer _commonViewer;
public ResourceToItemsMapper(CommonViewer viewer) {
_resourceToItem = new HashMap();
_reuseLists = new Stack();
_commonViewer = viewer;
viewer.setMapper(this);
}
public void addToMap(Object element, Item item) {
IResource resource = getCorrespondingResource(element);
if (resource != null) {
Object existingMapping = _resourceToItem.get(resource);
if (existingMapping == null) {
_resourceToItem.put(resource, item);
} else if (existingMapping instanceof Item) {
if (existingMapping != item) {
List list = getNewList();
list.add(existingMapping);
list.add(item);
_resourceToItem.put(resource, list);
}
} else { // List
List list = (List) existingMapping;
if (!list.contains(item)) {
list.add(item);
}
}
}
}
public void removeFromMap(Object element, Item item) {
IResource resource = getCorrespondingResource(element);
if (resource != null) {
Object existingMapping = _resourceToItem.get(resource);
if (existingMapping == null) {
return;
} else if (existingMapping instanceof Item) {
_resourceToItem.remove(resource);
} else { // List
List list = (List) existingMapping;
list.remove(item);
if (list.isEmpty()) {
_resourceToItem.remove(list);
releaseList(list);
}
}
}
}
public void clearMap() {
_resourceToItem.clear();
}
public boolean isEmpty() {
return _resourceToItem.isEmpty();
}
private List getNewList() {
if (!_reuseLists.isEmpty()) {
return (List) _reuseLists.pop();
}
return new ArrayList(2);
}
private void releaseList(List list) {
if (_reuseLists.size() < NUMBER_LIST_REUSE) {
_reuseLists.push(list);
}
}
public boolean handlesObject(Object object) {
return object instanceof IResource;
}
/**
* Must be called from the UI thread.
*
* @param changedResource
* Changed resource
*/
public void objectChanged(Object changedResource) {
Object obj = _resourceToItem.get(changedResource);
if (obj == null) {
// not mapped
} else if (obj instanceof Item) {
updateItem((Item) obj);
} else { // List of Items
List list = (List) obj;
for (int k = 0; k < list.size(); k++) {
updateItem((Item) list.get(k));
}
}
}
private void updateItem(Item item) {
if (!item.isDisposed()) {
_commonViewer.doUpdateItem(item);
}
}
private static IResource getCorrespondingResource(Object element) {
if (element instanceof IResource)
return (IResource) element;
if (element instanceof IAdaptable)
return (IResource) ((IAdaptable) element).getAdapter(IResource.class);
return null;
}
}
| 4,338 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
WorkbenchNavigatorPlugin.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/base_commons/net.heartsome.cat.common.ui.navigator.resources/src/org/eclipse/ui/internal/navigator/resources/plugin/WorkbenchNavigatorPlugin.java | /*******************************************************************************
* Copyright (c) 2003, 2009 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.ui.internal.navigator.resources.plugin;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.ui.plugin.AbstractUIPlugin;
/**
* The main plugin class for the workbench Navigator.
*
* @since 3.2
*/
public class WorkbenchNavigatorPlugin extends AbstractUIPlugin {
// The shared instance.
private static WorkbenchNavigatorPlugin plugin;
/** The plugin id */
public static String PLUGIN_ID = "org.eclipse.ui.navigator.resources"; //$NON-NLS-1$
/**
* Creates a new instance of the receiver
*/
public WorkbenchNavigatorPlugin() {
super();
plugin = this;
}
/**
* @return the shared instance.
*/
public static WorkbenchNavigatorPlugin getDefault() {
return plugin;
}
/**
* @return the workspace instance.
*/
public static IWorkspace getWorkspace() {
return ResourcesPlugin.getWorkspace();
}
/**
* Logs errors.
* @param message The message to log
* @param status The status to log
*/
public static void log(String message, IStatus status) {
if (message != null) {
getDefault().getLog().log(
new Status(IStatus.ERROR, PLUGIN_ID, 0, message, null));
System.err.println(message + "\nReason:"); //$NON-NLS-1$
}
if(status != null) {
getDefault().getLog().log(status);
System.err.println(status.getMessage());
}
}
/**
* Create a status associated with this plugin.
*
* @param severity
* @param aCode
* @param aMessage
* @param exception
* @return A status configured with this plugin's id and the given
* parameters.
*/
public static IStatus createStatus(int severity, int aCode,
String aMessage, Throwable exception) {
return new Status(severity, PLUGIN_ID, aCode,
aMessage != null ? aMessage : "No message.", exception); //$NON-NLS-1$
}
/**
*
* @param aCode
* @param aMessage
* @param exception
* @return A status configured with this plugin's id and the given
* parameters.
*/
public static IStatus createErrorStatus(int aCode, String aMessage,
Throwable exception) {
return createStatus(IStatus.ERROR, aCode, aMessage, exception);
}
/**
*
* @param aMessage
* @param exception
* @return A status configured with this plugin's id and the given
* parameters.
*/
public static IStatus createErrorStatus(String aMessage, Throwable exception) {
return createStatus(IStatus.ERROR, 0, aMessage, exception);
}
/**
*
* @param aMessage
* @return A status configured with this plugin's id and the given
* parameters.
*/
public static IStatus createErrorStatus(String aMessage) {
return createStatus(IStatus.ERROR, 0, aMessage, null);
}
/**
*
* @param aMessage
* @return A status configured with this plugin's id and the given
* parameters.
*/
public static IStatus createInfoStatus(String aMessage) {
return createStatus(IStatus.INFO, 0, aMessage, null);
}
/**
*
* @param aMessage
* @return A status configured with this plugin's id and the given
* parameters.
*/
public static IStatus createWarningStatus(String aMessage) {
return createStatus(IStatus.WARNING, 0, aMessage, null);
}
}
| 3,834 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
NavigatorUIPluginImages.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/base_commons/net.heartsome.cat.common.ui.navigator.resources/src/org/eclipse/ui/internal/navigator/resources/plugin/NavigatorUIPluginImages.java | /*******************************************************************************
* Copyright (c) 2003, 2008 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.ui.internal.navigator.resources.plugin;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Collections;
import org.eclipse.core.runtime.FileLocator;
import org.eclipse.core.runtime.Path;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.resource.ImageRegistry;
import org.eclipse.swt.graphics.Image;
import org.eclipse.ui.internal.navigator.NavigatorPlugin;
/**
* Handles all images and icons for the ui.
*
* <p>
* <strong>EXPERIMENTAL</strong>. This class or interface has been added as part
* of a work in progress. There is a guarantee neither that this API will work
* nor that it will remain the same. Please do not use this API without
* consulting with the Platform/UI team.
* </p>
*
* @since 3.2
*/
public class NavigatorUIPluginImages {
private static URL fgIconLocation;
// Create image registry
private final static ImageRegistry NAVIGATORUIPLUGIN_REGISTRY = NavigatorPlugin.getDefault().getImageRegistry();
// Create the icon location
static {
String pathSuffix = "icons/full/"; //$NON-NLS-1$
fgIconLocation = FileLocator.find(NavigatorPlugin.getDefault().getBundle(), new Path(pathSuffix), Collections.EMPTY_MAP);
}
/**
* Gets the current image.
*
* @param key
* - Name of the icon.
* @return Image
*/
public static Image get(String key) {
return NAVIGATORUIPLUGIN_REGISTRY.get(key);
}
/**
* Create and returns a image descriptor.
*
* @param prefix
* - Icon dir structure.
* @param name
* - The name of the icon.
* @return ImageDescriptor
*/
private static ImageDescriptor create(String prefix, String name) {
return ImageDescriptor.createFromURL(makeIconFileURL(prefix, name));
}
/**
* Creates the icon url
*
* @param prefix
* - Icon dir structure.
* @param name
* - The name of the icon.
* @return URL
*/
private static URL makeIconFileURL(String prefix, String name) {
StringBuffer buffer = new StringBuffer(prefix);
buffer.append(name);
try {
return new URL(fgIconLocation, buffer.toString());
} catch (MalformedURLException ex) {
return null;
}
}
/**
* Sets the three image descriptors for enabled, disabled, and hovered to an
* action. The actions are retrieved from the *lcl16 folders.
*
* @param action
* the action
* @param iconName
* the icon name
*/
public static void setLocalImageDescriptors(IAction action, String iconName) {
setImageDescriptors(action, "lcl16/", iconName); //$NON-NLS-1$
}
/**
* Sets all available image descriptors for the given action.
*
* @param action
* - The action associated with the icon.
* @param type
* - The type of icon.
* @param relPath
* - The relative path of the icon.
*/
public static void setImageDescriptors(IAction action, String type, String relPath) {
// /*relPath= relPath.substring(NAVIGATORUI_NAME_PREFIX_LENGTH);*/
// action.setDisabledImageDescriptor(create("d" + type, relPath));
// //$NON-NLS-1$
// action.setHoverImageDescriptor(create("c" + type, relPath));
// //$NON-NLS-1$
action.setImageDescriptor(create("e" + type, relPath)); //$NON-NLS-1$
}
}
| 3,858 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
PortingActionProvider.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/base_commons/net.heartsome.cat.common.ui.navigator.resources/src/org/eclipse/ui/internal/navigator/resources/actions/PortingActionProvider.java | /*******************************************************************************
* Copyright (c) 2000, 2007 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
* Sebastian Davids <[email protected]> - Collapse all action
* Sebastian Davids <[email protected]> - Images for menu items
*******************************************************************************/
package org.eclipse.ui.internal.navigator.resources.actions;
import java.net.URL;
import java.util.Collections;
import org.eclipse.core.runtime.Assert;
import org.eclipse.core.runtime.FileLocator;
import org.eclipse.core.runtime.Path;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.actions.ExportResourcesAction;
import org.eclipse.ui.actions.ImportResourcesAction;
import org.eclipse.ui.internal.navigator.resources.plugin.WorkbenchNavigatorPlugin;
import org.eclipse.ui.internal.navigator.resources.resource.WorkbenchNavigatorMessages;
import org.eclipse.ui.navigator.CommonActionProvider;
import org.eclipse.ui.navigator.ICommonActionExtensionSite;
import org.eclipse.ui.navigator.ICommonMenuConstants;
import org.eclipse.ui.navigator.ICommonViewerWorkbenchSite;
import org.eclipse.ui.navigator.WizardActionGroup;
/**
* Adds actions for Import/Export wizards. The group is smart, in that it will
* either add actions for Import and Export, or if there are context sensitive
* options available (as defined by <b>org.eclipse.ui.navigator.commonWizard</b>),
* then it will compound these options into a submenu with the appropriate lead
* text ("Import" or "Export").
*
* <p>
* <strong>EXPERIMENTAL</strong>. This class or interface has been added as
* part of a work in progress. There is a guarantee neither that this API will
* work nor that it will remain the same. Please do not use this API without
* consulting with the Platform/UI team.
* </p>
*
* @since 3.2
*/
public class PortingActionProvider extends CommonActionProvider {
private static final String COMMON_NAVIGATOR_IMPORT_MENU = "common.import.menu"; //$NON-NLS-1$
private static final String COMMON_NAVIGATOR_EXPORT_MENU = "common.export.menu"; //$NON-NLS-1$
private ImportResourcesAction importAction;
private ExportResourcesAction exportAction;
private WizardActionGroup importWizardActionGroup;
private WizardActionGroup exportWizardActionGroup;
private boolean disposed = false;
private boolean contribute= false;
public void init(ICommonActionExtensionSite anExtensionSite) {
Assert.isTrue(!disposed);
if (anExtensionSite.getViewSite() instanceof ICommonViewerWorkbenchSite) {
IWorkbenchWindow window = ((ICommonViewerWorkbenchSite) anExtensionSite
.getViewSite()).getWorkbenchWindow();
importAction = new ImportResourcesAction(window);
importAction.setText(WorkbenchNavigatorMessages.PortingActionProvider_ImportResourcesMenu_label);
exportAction = new ExportResourcesAction(window);
exportAction.setText(WorkbenchNavigatorMessages.PortingActionProvider_ExportResourcesMenu_label);
importWizardActionGroup = new WizardActionGroup(window, PlatformUI
.getWorkbench().getImportWizardRegistry(),
WizardActionGroup.TYPE_IMPORT, anExtensionSite.getContentService());
exportWizardActionGroup = new WizardActionGroup(window, PlatformUI
.getWorkbench().getExportWizardRegistry(),
WizardActionGroup.TYPE_EXPORT, anExtensionSite.getContentService());
contribute = true;
}
}
/**
* Extends the superclass implementation to dispose the subgroups.
*/
public void dispose() {
if(!contribute) {
return;
}
importWizardActionGroup.dispose();
exportWizardActionGroup.dispose();
importAction = null;
exportAction = null;
disposed = true;
}
public void fillContextMenu(IMenuManager aMenu) {
if(!contribute) {
return;
}
Assert.isTrue(!disposed);
ISelection selection = getContext().getSelection();
if (!(selection instanceof IStructuredSelection) || ((IStructuredSelection) selection).size() > 1) {
addSimplePortingMenus(aMenu);
} else {
addImportMenu(aMenu);
addExportMenu(aMenu);
}
}
/**
* Returns the image descriptor with the given relative path.
*/
protected ImageDescriptor getImageDescriptor(String relativePath) {
String iconPath = "icons/full/"; //$NON-NLS-1$
URL url = FileLocator.find(WorkbenchNavigatorPlugin.getDefault().getBundle(), new Path(iconPath + relativePath), Collections.EMPTY_MAP);
if (url == null) {
return ImageDescriptor.getMissingImageDescriptor();
}
return ImageDescriptor.createFromURL(url);
}
private void addSimplePortingMenus(IMenuManager aMenu) {
aMenu.appendToGroup(ICommonMenuConstants.GROUP_PORT, importAction);
aMenu.appendToGroup(ICommonMenuConstants.GROUP_PORT, exportAction);
}
private void addImportMenu(IMenuManager aMenu) {
importWizardActionGroup.setContext(getContext());
if (importWizardActionGroup.getWizardActionIds().length == 0) {
aMenu.appendToGroup(ICommonMenuConstants.GROUP_PORT, importAction);
return;
}
IMenuManager submenu = new MenuManager(
WorkbenchNavigatorMessages.PortingActionProvider_ImportResourcesMenu_label,
COMMON_NAVIGATOR_IMPORT_MENU);
importWizardActionGroup.fillContextMenu(submenu);
submenu.add(new Separator(ICommonMenuConstants.GROUP_ADDITIONS));
submenu.add(new Separator());
submenu.add(importAction);
aMenu.appendToGroup(ICommonMenuConstants.GROUP_PORT, submenu);
}
private void addExportMenu(IMenuManager aMenu) {
exportWizardActionGroup.setContext(getContext());
if (exportWizardActionGroup.getWizardActionIds().length == 0) {
aMenu.appendToGroup(ICommonMenuConstants.GROUP_PORT, exportAction);
return;
}
IMenuManager submenu = new MenuManager(
WorkbenchNavigatorMessages.PortingActionProvider_ExportResourcesMenu_label,
COMMON_NAVIGATOR_EXPORT_MENU);
exportWizardActionGroup.fillContextMenu(submenu);
submenu.add(new Separator(ICommonMenuConstants.GROUP_ADDITIONS));
submenu.add(new Separator());
submenu.add(exportAction);
aMenu.appendToGroup(ICommonMenuConstants.GROUP_PORT, submenu);
}
}
| 6,687 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
ResourceMgmtActionProvider.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/base_commons/net.heartsome.cat.common.ui.navigator.resources/src/org/eclipse/ui/internal/navigator/resources/actions/ResourceMgmtActionProvider.java | /*******************************************************************************
* Copyright (c) 2006, 2009 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.ui.internal.navigator.resources.actions;
import java.lang.reflect.InvocationTargetException;
import java.util.Iterator;
import org.eclipse.core.resources.ICommand;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.WorkspaceJob;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.ISchedulingRule;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.StructuredViewer;
import org.eclipse.jface.window.IShellProvider;
import org.eclipse.osgi.util.NLS;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IActionBars;
import org.eclipse.ui.IWorkbenchCommandConstants;
import org.eclipse.ui.actions.ActionFactory;
import org.eclipse.ui.actions.CloseResourceAction;
import org.eclipse.ui.actions.OpenResourceAction;
import org.eclipse.ui.actions.RefreshAction;
import org.eclipse.ui.actions.WorkspaceModifyOperation;
import org.eclipse.ui.ide.IDEActionFactory;
import org.eclipse.ui.internal.ide.IDEWorkbenchPlugin;
import org.eclipse.ui.internal.navigator.NavigatorPlugin;
import org.eclipse.ui.internal.navigator.resources.resource.WorkbenchNavigatorMessages;
import org.eclipse.ui.navigator.CommonActionProvider;
import org.eclipse.ui.navigator.ICommonActionExtensionSite;
import org.eclipse.ui.navigator.ICommonMenuConstants;
/**
* @since 3.2
*/
public class ResourceMgmtActionProvider extends CommonActionProvider {
// private BuildAction buildAction;
//
private OpenResourceAction openProjectAction;
//
private CloseResourceAction closeProjectAction;
//
// private CloseUnrelatedProjectsAction closeUnrelatedProjectsAction;
private RefreshAction refreshAction;
private Shell shell;
/*
* (non-Javadoc)
*
* @see org.eclipse.ui.navigator.CommonActionProvider#init(org.eclipse.ui.navigator .ICommonActionExtensionSite)
*/
public void init(ICommonActionExtensionSite aSite) {
super.init(aSite);
shell = aSite.getViewSite().getShell();
makeActions();
}
public void fillActionBars(IActionBars actionBars) {
actionBars.setGlobalActionHandler(ActionFactory.REFRESH.getId(), refreshAction);
// actionBars.setGlobalActionHandler(IDEActionFactory.BUILD_PROJECT.getId(), buildAction);
actionBars.setGlobalActionHandler(IDEActionFactory.OPEN_PROJECT.getId(), openProjectAction);
actionBars.setGlobalActionHandler(IDEActionFactory.CLOSE_PROJECT.getId(), closeProjectAction);
// actionBars.setGlobalActionHandler(IDEActionFactory.CLOSE_UNRELATED_PROJECTS.getId(),
// closeUnrelatedProjectsAction);
updateActionBars();
}
/**
* Adds the build, open project, close project and refresh resource actions to the context menu.
* <p>
* The following conditions apply: build-only projects selected, auto build disabled, at least one builder present
* open project-only projects selected, at least one closed project close project-only projects selected, at least
* one open project refresh-no closed project selected
* </p>
* <p>
* Both the open project and close project action may be on the menu at the same time.
* </p>
* <p>
* No disabled action should be on the context menu.
* </p>
* @param menu
* context menu to add actions to
*/
public void fillContextMenu(IMenuManager menu) {
IStructuredSelection selection = (IStructuredSelection) getContext().getSelection();
boolean isProjectSelection = true;
boolean hasOpenProjects = false;
boolean hasClosedProjects = false;
boolean hasBuilder = true; // false if any project is closed or does not
// have builder
Iterator resources = selection.iterator();
while (resources.hasNext() && (!hasOpenProjects || !hasClosedProjects || hasBuilder || isProjectSelection)) {
Object next = resources.next();
IProject project = null;
if (next instanceof IProject) {
project = (IProject) next;
} else if (next instanceof IAdaptable) {
project = (IProject) ((IAdaptable) next).getAdapter(IProject.class);
}
if (project == null) {
isProjectSelection = false;
continue;
}
if (project.isOpen()) {
hasOpenProjects = true;
if (hasBuilder && !hasBuilder(project)) {
hasBuilder = false;
}
} else {
hasClosedProjects = true;
hasBuilder = false;
}
}
// if (!selection.isEmpty() && isProjectSelection && !ResourcesPlugin.getWorkspace().isAutoBuilding() &&
// hasBuilder) {
// // Allow manual incremental build only if auto build is off.
// buildAction.selectionChanged(selection);
// menu.appendToGroup(ICommonMenuConstants.GROUP_BUILD, buildAction);
// }
if (isProjectSelection) {
if (hasClosedProjects) {
openProjectAction.selectionChanged(selection);
menu.appendToGroup(ICommonMenuConstants.GROUP_EDIT, openProjectAction);
}
if (hasOpenProjects) {
closeProjectAction.selectionChanged(selection);
menu.appendToGroup(ICommonMenuConstants.GROUP_EDIT, closeProjectAction);
// closeUnrelatedProjectsAction.selectionChanged(selection);
// menu.appendToGroup(ICommonMenuConstants.GROUP_BUILD, closeUnrelatedProjectsAction);
}
}
if (!hasClosedProjects) {
refreshAction.selectionChanged(selection);
refreshAction.setEnabled(!selection.isEmpty());
menu.appendToGroup(ICommonMenuConstants.GROUP_EDIT, refreshAction);
}
}
/**
* Returns whether there are builders configured on the given project.
* @return <code>true</code> if it has builders, <code>false</code> if not, or if this could not be determined
*/
boolean hasBuilder(IProject project) {
try {
ICommand[] commands = project.getDescription().getBuildSpec();
if (commands.length > 0) {
return true;
}
} catch (CoreException e) {
// Cannot determine if project has builders. Project is closed
// or does not exist. Fall through to return false.
}
return false;
}
protected void makeActions() {
IShellProvider sp = new IShellProvider() {
public Shell getShell() {
return shell;
}
};
openProjectAction = new OpenResourceAction(sp);
openProjectAction.setText(WorkbenchNavigatorMessages.actions_ResourceMgmtActionProvider_openProjectAction);
closeProjectAction = new CloseResourceAction(sp);
closeProjectAction.setText(WorkbenchNavigatorMessages.actions_ResourceMgmtActionProvider_closeProjectAction);
//
// closeUnrelatedProjectsAction = new CloseUnrelatedProjectsAction(sp);
// closeUnrelatedProjectsAction.setText("关闭无关的项目");
refreshAction = new RefreshAction(sp) {
public void run() {
final IStatus[] errorStatus = new IStatus[1];
errorStatus[0] = Status.OK_STATUS;
final WorkspaceModifyOperation op = (WorkspaceModifyOperation) createOperation(errorStatus);
WorkspaceJob job = new WorkspaceJob("refresh") { //$NON-NLS-1$
public IStatus runInWorkspace(IProgressMonitor monitor) throws CoreException {
try {
op.run(monitor);
if (shell != null && !shell.isDisposed()) {
shell.getDisplay().asyncExec(new Runnable() {
public void run() {
StructuredViewer viewer = getActionSite().getStructuredViewer();
if (viewer != null && viewer.getControl() != null
&& !viewer.getControl().isDisposed()) {
viewer.refresh();
}
}
});
}
} catch (InvocationTargetException e) {
String msg = NLS.bind(WorkbenchNavigatorMessages.actions_ResourceMgmtActionProvider_logTitle,
getClass().getName(), e.getTargetException());
throw new CoreException(new Status(IStatus.ERROR, NavigatorPlugin.PLUGIN_ID, IStatus.ERROR,
msg, e.getTargetException()));
} catch (InterruptedException e) {
return Status.CANCEL_STATUS;
}
return errorStatus[0];
}
};
ISchedulingRule rule = op.getRule();
if (rule != null) {
job.setRule(rule);
}
job.setUser(true);
job.schedule();
}
};
refreshAction.setText(WorkbenchNavigatorMessages.actions_ResourceMgmtActionProvider_refreshAction);
refreshAction.setDisabledImageDescriptor(getImageDescriptor("dlcl16/refresh_nav.gif"));//$NON-NLS-1$
refreshAction.setImageDescriptor(getImageDescriptor("elcl16/refresh_nav.gif"));//$NON-NLS-1$
refreshAction.setActionDefinitionId(IWorkbenchCommandConstants.FILE_REFRESH);
if (getContext() == null) {
refreshAction.setEnabled(false);
} else {
IStructuredSelection selection = (IStructuredSelection) getContext().getSelection();
refreshAction.selectionChanged(selection);
refreshAction.setEnabled(!selection.isEmpty());
}
// buildAction = new BuildAction(sp, IncrementalProjectBuilder.INCREMENTAL_BUILD);
// buildAction.setActionDefinitionId(IWorkbenchCommandConstants.PROJECT_BUILD_PROJECT);
}
/**
* Returns the image descriptor with the given relative path.
*/
protected ImageDescriptor getImageDescriptor(String relativePath) {
return IDEWorkbenchPlugin.getIDEImageDescriptor(relativePath);
}
public void updateActionBars() {
IStructuredSelection selection = (IStructuredSelection) getContext().getSelection();
refreshAction.selectionChanged(selection);
// buildAction.selectionChanged(selection);
openProjectAction.selectionChanged(selection);
// closeUnrelatedProjectsAction.selectionChanged(selection);
closeProjectAction.selectionChanged(selection);
}
}
| 10,130 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
GotoResourceDialog.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/base_commons/net.heartsome.cat.common.ui.navigator.resources/src/org/eclipse/ui/internal/navigator/resources/actions/GotoResourceDialog.java | /*******************************************************************************
* Copyright (c) 2000, 2009 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.ui.internal.navigator.resources.actions;
import org.eclipse.core.resources.IContainer;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.dialogs.FilteredResourcesSelectionDialog;
import org.eclipse.ui.internal.navigator.INavigatorHelpContextIds;
import org.eclipse.ui.internal.navigator.resources.resource.WorkbenchNavigatorMessages;
/**
* Shows a list of resources to the user with a text entry field for a string
* pattern used to filter the list of resources.
*
*/
/* package */class GotoResourceDialog extends FilteredResourcesSelectionDialog {
/**
* Creates a new instance of the class.
*/
protected GotoResourceDialog(Shell parentShell, IContainer container,
int typesMask) {
super(parentShell, false, container, typesMask);
setTitle(WorkbenchNavigatorMessages.actions_GotoResourceDialog_GoToTitle);
PlatformUI.getWorkbench().getHelpSystem().setHelp(parentShell,
INavigatorHelpContextIds.GOTO_RESOURCE_DIALOG);
}
}
| 1,554 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
OpenFileWithValidAction.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/base_commons/net.heartsome.cat.common.ui.navigator.resources/src/org/eclipse/ui/internal/navigator/resources/actions/OpenFileWithValidAction.java | package org.eclipse.ui.internal.navigator.resources.actions;
import java.io.File;
import java.text.MessageFormat;
import java.util.Iterator;
import net.heartsome.cat.common.file.XLFValidator;
import net.heartsome.cat.common.util.CommonFunction;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IResource;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.util.OpenStrategy;
import org.eclipse.swt.program.Program;
import org.eclipse.ui.IEditorDescriptor;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IEditorReference;
import org.eclipse.ui.IFileEditorInput;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.actions.OpenSystemEditorAction;
import org.eclipse.ui.ide.IDE;
import org.eclipse.ui.internal.ide.DialogUtil;
import org.eclipse.ui.internal.ide.IDEWorkbenchMessages;
import org.eclipse.ui.internal.ide.IIDEHelpContextIds;
import org.eclipse.ui.internal.navigator.resources.resource.WorkbenchNavigatorMessages;
import org.eclipse.ui.part.FileEditorInput;
import com.ximpleware.AutoPilot;
import com.ximpleware.VTDGen;
import com.ximpleware.VTDNav;
/**
* 打开xliff文件,并且验证,该类参照OpenFileAction来写的,并代替OpenFileAction。
* @author robert 2012-06-07
*/
@SuppressWarnings("restriction")
public class OpenFileWithValidAction extends OpenSystemEditorAction {
private IWorkbenchPage page;
/**
* The id of this action.
*/
public static final String ID = PlatformUI.PLUGIN_ID + ".OpenFileWithValidAction";//$NON-NLS-1$
private static final String XLIFF_EDITOR_ID = "net.heartsome.cat.ts.ui.xliffeditor.nattable.editor";
/**
* The editor to open.
*/
private IEditorDescriptor editorDescriptor;
/**
* Creates a new action that will open editors on the then-selected file resources. Equivalent to
* <code>OpenFileAction(page,null)</code>.
* @param page
* the workbench page in which to open the editor
*/
public OpenFileWithValidAction(IWorkbenchPage page) {
this(page, null);
this.page = page;
}
/**
* Creates a new action that will open instances of the specified editor on the then-selected file resources.
* @param page
* the workbench page in which to open the editor
* @param descriptor
* the editor descriptor, or <code>null</code> if unspecified
*/
public OpenFileWithValidAction(IWorkbenchPage page, IEditorDescriptor descriptor) {
super(page);
setText(descriptor == null ? IDEWorkbenchMessages.OpenFileAction_text : descriptor.getLabel());
PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IIDEHelpContextIds.OPEN_FILE_ACTION);
setToolTipText(IDEWorkbenchMessages.OpenFileAction_toolTip);
setId(ID);
this.editorDescriptor = descriptor;
}
/**
* Ensures that the contents of the given file resource are local.
* @param file
* the file resource
* @return <code>true</code> if the file is local, and <code>false</code> if it could not be made local for some
* reason
*/
boolean ensureFileLocal(final IFile file) {
// Currently fails due to Core PR. Don't do it for now
// 1G5I6PV: ITPCORE:WINNT - IResource.setLocal() attempts to modify immutable tree
// file.setLocal(true, IResource.DEPTH_ZERO);
return true;
}
@SuppressWarnings("rawtypes")
@Override
public void run() {
try {
XLFValidator.resetFlag();
Iterator itr = getSelectedResources().iterator();
while (itr.hasNext()) {
IResource resource = (IResource) itr.next();
if (resource instanceof IFile) {
openFile1((IFile) resource);
}
}
XLFValidator.resetFlag();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Opens an editor on the given file resource.
* @param file
* the file resource
*/
void openFile1(IFile file) throws Exception{
try {
boolean activate = OpenStrategy.activateOnOpen();
if (editorDescriptor == null) {
// 如果是nattble打开的,就验证其是否已经被打开
if (!validIsopened(file)) {
return;
}
String filePath = file.getFullPath().toOSString();
// Bug #2519
if (CommonFunction.validXlfExtensionByFileName(file.getName())
|| (filePath.startsWith(File.separator + file.getProject().getName() + File.separator
+ "Intermediate" + File.separator + "Report") && file.getName().endsWith(".html"))) {
// 之前的这块验证 xliff 文件的代码是放在 nattable 打开时,现在改为在调用 nattable 打开之前
// html 是不会验证路径的
if (!file.getFullPath().getFileExtension().equals("html")) {
if (XLFValidator.validateXliffFile(file)) {
IDE.openEditor(page, file, activate);
}
}else {
IDE.openEditor(page, file, activate);
}
} else {
boolean openReult = Program.launch(file.getLocation().toOSString());
if (!openReult) {
MessageDialog.openWarning(page.getWorkbenchWindow().getShell(), WorkbenchNavigatorMessages.navigator_all_dialog_warning,
MessageFormat.format(WorkbenchNavigatorMessages.actions_OpenFileWithValidAction_notFindProgram, new Object[]{file.getLocation().getFileExtension()}));
}
}
} else {
if (ensureFileLocal(file)) {
if (!file.getFullPath().getFileExtension().equals("html")) {
if (XLFValidator.validateXliffFile(file)) {
page.openEditor(new FileEditorInput(file), editorDescriptor.getId(), activate);
}
}else {
page.openEditor(new FileEditorInput(file), editorDescriptor.getId(), activate);
}
}
}
} catch (PartInitException e) {
DialogUtil.openError(page.getWorkbenchWindow().getShell(),
IDEWorkbenchMessages.OpenFileAction_openFileShellTitle, e.getMessage(), e);
}
}
/**
* 验证是否已经被打开
* @param iFile
* @return 如果当前要打开的文件未被打开,那么验证通过,返回true,否则返回false。
*/
private boolean validIsopened(IFile iFile) throws Exception{
String extention = iFile.getFileExtension();
if (IDE.getDefaultEditor(iFile, true) != null
&& XLIFF_EDITOR_ID.equals(IDE.getDefaultEditor(iFile, true).getId())
&& CommonFunction.validXlfExtension(extention)) {
IEditorReference[] editorRes = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage()
.getEditorReferences();
IEditorPart editor = null;
IFile openIFile = null;
String needOpenIfileLc = iFile.getLocation().toOSString();
for (int i = 0; i < editorRes.length; i++) {
if (editorRes[i].getId().equals(XLIFF_EDITOR_ID)) {
// 备注:这里的两行代码已经被注释了,原因是因为 getEditor 方法会让每一个 editor 都初始一次,这并不是本次需求所要的。注意。 2013-01-04
//editor = editorRes[i].getEditor(true);
//openIFile = ((IFileEditorInput) editor.getEditorInput()).getFile();
openIFile = ((IFileEditorInput) editorRes[i].getEditorInput()).getFile();
// 判断是否是合并打开,后缀名为xlp为合并打开,后缀名为xlf为单一打开
if ("xlp".equals(openIFile.getFileExtension())) {
// 开始解析这个合并打开临时文件,获取合并打开的文件。
VTDGen vg = new VTDGen();
if (vg.parseFile(openIFile.getLocation().toOSString(), true)) {
VTDNav vn = vg.getNav();
AutoPilot ap = new AutoPilot(vn);
try {
ap.selectXPath("/mergerFiles/mergerFile/@filePath");
int index = -1;
while ((index = ap.evalXPath()) != -1) {
String fileLC = vn.toString(index + 1);
if (fileLC != null && !"".equals(fileLC)) {
if (fileLC.equals(needOpenIfileLc)) {
editor = editorRes[i].getEditor(true);
page.activate(editor);
return false;
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
} else {
return false;
}
}
}
}
}
return true;
}
}
| 8,013 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
GotoActionProvider.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/base_commons/net.heartsome.cat.common.ui.navigator.resources/src/org/eclipse/ui/internal/navigator/resources/actions/GotoActionProvider.java | /*******************************************************************************
* Copyright (c) 2006, 2009 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
* Oakland Software (Francis Upton - [email protected])
* bug 214271 Undo/redo not enabled if nothing selected
******************************************************************************/
package org.eclipse.ui.internal.navigator.resources.actions;
import org.eclipse.ui.IActionBars;
import org.eclipse.ui.IWorkbenchActionConstants;
import org.eclipse.ui.navigator.CommonActionProvider;
import org.eclipse.ui.navigator.CommonViewer;
import org.eclipse.ui.navigator.ICommonActionExtensionSite;
/**
* @since 3.3
*
*/
public class GotoActionProvider extends CommonActionProvider {
private GotoResourceAction gotoAction;
/*
* (non-Javadoc)
*
* @see org.eclipse.ui.navigator.CommonActionProvider#init(org.eclipse.ui.navigator.ICommonActionExtensionSite)
*/
public void init(ICommonActionExtensionSite anActionSite) {
gotoAction = new GotoResourceAction(anActionSite.getViewSite().getShell(), (CommonViewer)anActionSite.getStructuredViewer());
}
public void fillActionBars(IActionBars actionBars) {
actionBars.setGlobalActionHandler(
IWorkbenchActionConstants.GO_TO_RESOURCE, gotoAction);
updateActionBars();
}
}
| 1,620 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
RefactorActionProvider.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/base_commons/net.heartsome.cat.common.ui.navigator.resources/src/org/eclipse/ui/internal/navigator/resources/actions/RefactorActionProvider.java | /*******************************************************************************
* Copyright (c) 2006, 2008 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
* Oakland Software (Francis Upton - [email protected])
* bug 214271 Undo/redo not enabled if nothing selected
******************************************************************************/
package org.eclipse.ui.internal.navigator.resources.actions;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.ui.IActionBars;
import org.eclipse.ui.actions.ActionContext;
import org.eclipse.ui.navigator.CommonActionProvider;
import org.eclipse.ui.navigator.ICommonActionExtensionSite;
/**
* @since 3.2
*
*/
public class RefactorActionProvider extends CommonActionProvider {
private RefactorActionGroup refactorGroup;
/*
* (non-Javadoc)
*
* @see org.eclipse.ui.navigator.CommonActionProvider#init(org.eclipse.ui.navigator.ICommonActionExtensionSite)
*/
public void init(ICommonActionExtensionSite anActionSite) {
refactorGroup = new RefactorActionGroup(anActionSite.getViewSite().getShell(), (Tree)anActionSite.getStructuredViewer().getControl());
}
public void dispose() {
refactorGroup.dispose();
}
public void fillActionBars(IActionBars actionBars) {
refactorGroup.fillActionBars(actionBars);
}
public void fillContextMenu(IMenuManager menu) {
refactorGroup.fillContextMenu(menu);
}
public void setContext(ActionContext context) {
refactorGroup.setContext(context);
}
public void updateActionBars() {
refactorGroup.updateActionBars();
}
}
| 1,908 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
PropertiesActionProvider.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/base_commons/net.heartsome.cat.common.ui.navigator.resources/src/org/eclipse/ui/internal/navigator/resources/actions/PropertiesActionProvider.java | /*******************************************************************************
* Copyright (c) 2005, 2009 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.ui.internal.navigator.resources.actions;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.core.runtime.Platform;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.ISelectionProvider;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.window.IShellProvider;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IActionBars;
import org.eclipse.ui.IWorkbenchCommandConstants;
import org.eclipse.ui.actions.ActionContext;
import org.eclipse.ui.actions.ActionFactory;
import org.eclipse.ui.dialogs.PropertyDialogAction;
import org.eclipse.ui.navigator.CommonActionProvider;
import org.eclipse.ui.navigator.ICommonActionExtensionSite;
import org.eclipse.ui.navigator.ICommonMenuConstants;
/**
* Adds the properties action to the menu.
*
* @since 3.2
*
*/
public class PropertiesActionProvider extends CommonActionProvider {
private PropertyDialogAction propertiesAction;
private ISelectionProvider delegateSelectionProvider;
public void init(final ICommonActionExtensionSite aSite) {
delegateSelectionProvider = new DelegateSelectionProvider( aSite.getViewSite().getSelectionProvider());
propertiesAction = new PropertyDialogAction(new IShellProvider() {
public Shell getShell() {
return aSite.getViewSite().getShell();
}
},delegateSelectionProvider);
propertiesAction.setText("属性");
propertiesAction.setActionDefinitionId(IWorkbenchCommandConstants.FILE_PROPERTIES);
}
/*
* (non-Javadoc)
*
* @see org.eclipse.ui.actions.ActionGroup#fillContextMenu(org.eclipse.jface.action.IMenuManager)
*/
public void fillContextMenu(IMenuManager menu) {
super.fillContextMenu(menu);
if (propertiesAction.isApplicableForSelection()) {
menu.appendToGroup(ICommonMenuConstants.GROUP_PROPERTIES,
propertiesAction);
}
}
/*
* (non-Javadoc)
*
* @see
* org.eclipse.ui.actions.ActionGroup#fillActionBars(org.eclipse.ui.IActionBars
* )
*/
public void fillActionBars(IActionBars actionBars) {
super.fillActionBars(actionBars);
actionBars.setGlobalActionHandler(ActionFactory.PROPERTIES.getId(),
propertiesAction);
}
/*
* (non-Javadoc)
*
* @see org.eclipse.ui.actions.ActionGroup#setContext(org.eclipse.ui.actions.ActionContext)
*/
public void setContext(ActionContext context) {
super.setContext(context);
propertiesAction.selectionChanged(delegateSelectionProvider
.getSelection());
}
private class DelegateIAdaptable implements IAdaptable {
private Object delegate;
private DelegateIAdaptable(Object o) {
delegate = o;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.core.runtime.IAdaptable#getAdapter(java.lang.Class)
*/
public Object getAdapter(Class adapter) {
if (adapter.isInstance(delegate) || delegate == null) {
return delegate;
}
return Platform.getAdapterManager().getAdapter(delegate, adapter);
}
}
private class DelegateSelectionProvider implements ISelectionProvider {
private ISelectionProvider delegate;
private DelegateSelectionProvider(ISelectionProvider s) {
delegate = s;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.jface.viewers.ISelectionProvider#addSelectionChangedListener(org.eclipse.jface.viewers.ISelectionChangedListener)
*/
public void addSelectionChangedListener(
ISelectionChangedListener listener) {
delegate.addSelectionChangedListener(listener);
}
/*
* (non-Javadoc)
*
* @see org.eclipse.jface.viewers.ISelectionProvider#getSelection()
*/
public ISelection getSelection() {
if (delegate.getSelection() instanceof IStructuredSelection) {
IStructuredSelection sSel = (IStructuredSelection) delegate
.getSelection();
if (sSel.getFirstElement() instanceof IAdaptable) {
return sSel;
}
return new StructuredSelection(new DelegateIAdaptable(sSel
.getFirstElement()));
}
return delegate.getSelection();
}
/*
* (non-Javadoc)
*
* @see org.eclipse.jface.viewers.ISelectionProvider#removeSelectionChangedListener(org.eclipse.jface.viewers.ISelectionChangedListener)
*/
public void removeSelectionChangedListener(
ISelectionChangedListener listener) {
delegate.removeSelectionChangedListener(listener);
}
/*
* (non-Javadoc)
*
* @see org.eclipse.jface.viewers.ISelectionProvider#setSelection(org.eclipse.jface.viewers.ISelection)
*/
public void setSelection(ISelection selection) {
delegate.setSelection(selection);
}
}
}
| 5,231 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
EditActionGroup.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/base_commons/net.heartsome.cat.common.ui.navigator.resources/src/org/eclipse/ui/internal/navigator/resources/actions/EditActionGroup.java | /*******************************************************************************
* Copyright (c) 2006, 2010 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
******************************************************************************/
package org.eclipse.ui.internal.navigator.resources.actions;
import org.eclipse.core.resources.IResource;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.window.IShellProvider;
import org.eclipse.swt.SWT;
import org.eclipse.swt.dnd.Clipboard;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IActionBars;
import org.eclipse.ui.ISharedImages;
import org.eclipse.ui.IWorkbenchCommandConstants;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.actions.ActionGroup;
import org.eclipse.ui.actions.TextActionHandler;
import org.eclipse.ui.ide.ResourceSelectionUtil;
import org.eclipse.ui.internal.navigator.resources.resource.WorkbenchNavigatorMessages;
import org.eclipse.ui.navigator.ICommonMenuConstants;
/**
* @since 3.2
*/
public class EditActionGroup extends ActionGroup {
private Clipboard clipboard;
private CopyAction copyAction;
private DeleteResourceAndCloseEditorAction deleteAction;
private PasteAction pasteAction;
private TextActionHandler textActionHandler;
private Shell shell;
/**
* @param aShell
*/
public EditActionGroup(Shell aShell) {
shell = aShell;
makeActions();
}
public void dispose() {
if (clipboard != null) {
clipboard.dispose();
clipboard = null;
}
super.dispose();
}
public void fillContextMenu(IMenuManager menu) {
IStructuredSelection selection = (IStructuredSelection) getContext().getSelection();
boolean anyResourceSelected = !selection.isEmpty()
&& ResourceSelectionUtil.allResourcesAreOfType(selection, IResource.PROJECT | IResource.FOLDER
| IResource.FILE);
copyAction.selectionChanged(selection);
// menu.appendToGroup(ICommonMenuConstants.GROUP_EDIT, copyAction);
pasteAction.selectionChanged(selection);
// menu.insertAfter(copyAction.getId(), pasteAction);
// menu.appendToGroup(ICommonMenuConstants.GROUP_EDIT, pasteAction);
if (anyResourceSelected) {
deleteAction.selectionChanged(selection);
// menu.insertAfter(pasteAction.getId(), deleteAction);
menu.appendToGroup(ICommonMenuConstants.GROUP_EDIT, deleteAction);
}
}
public void fillActionBars(IActionBars actionBars) {
if (textActionHandler == null) {
textActionHandler = new TextActionHandler(actionBars); // hook
// handlers
}
textActionHandler.setCopyAction(copyAction);
textActionHandler.setPasteAction(pasteAction);
textActionHandler.setDeleteAction(deleteAction);
// renameAction.setTextActionHandler(textActionHandler);
updateActionBars();
textActionHandler.updateActionBars();
}
/**
* Handles a key pressed event by invoking the appropriate action.
* @param event
* The Key Event
*/
public void handleKeyPressed(KeyEvent event) {
if (event.character == SWT.DEL && event.stateMask == 0) {
if (deleteAction.isEnabled()) {
deleteAction.run();
}
// Swallow the event.
event.doit = false;
}
}
protected void makeActions() {
clipboard = new Clipboard(shell.getDisplay());
pasteAction = new PasteAction(shell, clipboard);
pasteAction.setText(WorkbenchNavigatorMessages.actions_EditActionGroup_pasteAction);
ISharedImages images = PlatformUI.getWorkbench().getSharedImages();
pasteAction.setDisabledImageDescriptor(images.getImageDescriptor(ISharedImages.IMG_TOOL_PASTE_DISABLED));
pasteAction.setImageDescriptor(images.getImageDescriptor(ISharedImages.IMG_TOOL_PASTE));
pasteAction.setActionDefinitionId(IWorkbenchCommandConstants.EDIT_PASTE);
copyAction = new CopyAction(shell, clipboard, pasteAction);
copyAction.setText(WorkbenchNavigatorMessages.actions_EditActionGroup_copyAction);
copyAction.setDisabledImageDescriptor(images.getImageDescriptor(ISharedImages.IMG_TOOL_COPY_DISABLED));
copyAction.setImageDescriptor(images.getImageDescriptor(ISharedImages.IMG_TOOL_COPY));
copyAction.setActionDefinitionId(IWorkbenchCommandConstants.EDIT_COPY);
IShellProvider sp = new IShellProvider() {
public Shell getShell() {
return shell;
}
};
deleteAction = new DeleteResourceAndCloseEditorAction(sp);
deleteAction.setText(WorkbenchNavigatorMessages.actions_EditActionGroup_deleteAction);
deleteAction.setDisabledImageDescriptor(images.getImageDescriptor(ISharedImages.IMG_TOOL_DELETE_DISABLED));
deleteAction.setImageDescriptor(images.getImageDescriptor(ISharedImages.IMG_TOOL_DELETE));
deleteAction.setActionDefinitionId(IWorkbenchCommandConstants.EDIT_DELETE);
}
public void updateActionBars() {
IStructuredSelection selection = (IStructuredSelection) getContext().getSelection();
copyAction.selectionChanged(selection);
pasteAction.selectionChanged(selection);
deleteAction.selectionChanged(selection);
}
}
| 5,316 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
GotoResourceAction.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/base_commons/net.heartsome.cat.common.ui.navigator.resources/src/org/eclipse/ui/internal/navigator/resources/actions/GotoResourceAction.java | /*******************************************************************************
* Copyright (c) 2000, 2009 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.ui.internal.navigator.resources.actions;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.internal.navigator.INavigatorHelpContextIds;
/**
* Implements the go to resource action. Opens a dialog and set the navigator
* selection with the resource selected by the user.
*/
public class GotoResourceAction extends Action {
protected Shell shell;
protected TreeViewer viewer;
/**
* @param shell
* @param viewer
*/
public GotoResourceAction(Shell shell, TreeViewer viewer) {
this.shell = shell;
this.viewer = viewer;
PlatformUI.getWorkbench().getHelpSystem().setHelp(this,
INavigatorHelpContextIds.GOTO_RESOURCE_ACTION);
}
/**
* Collect all resources in the workbench open a dialog asking the user to
* select a resource and change the selection in the navigator.
*/
public void run() {
GotoResourceDialog dialog = new GotoResourceDialog(shell,
ResourcesPlugin.getWorkspace().getRoot(), IResource.FILE
| IResource.FOLDER | IResource.PROJECT);
dialog.open();
Object[] result = dialog.getResult();
if (result == null || result.length == 0
|| result[0] instanceof IResource == false) {
return;
}
IResource selection = (IResource) result[0];
viewer.setSelection(new StructuredSelection(selection), true);
}
}
| 2,112 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
RenameResourceAndCloseEditorAction.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/base_commons/net.heartsome.cat.common.ui.navigator.resources/src/org/eclipse/ui/internal/navigator/resources/actions/RenameResourceAndCloseEditorAction.java | /*******************************************************************************
* Copyright (c) 2000, 2008 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.ui.internal.navigator.resources.actions;
import java.io.File;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;
import net.heartsome.cat.common.util.CommonFunction;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.resources.ResourceAttributes;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.dialogs.IInputValidator;
import org.eclipse.jface.dialogs.InputDialog;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.window.IShellProvider;
import org.eclipse.jface.window.Window;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.TreeEditor;
import org.eclipse.swt.events.FocusAdapter;
import org.eclipse.swt.events.FocusEvent;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.widgets.TreeItem;
import org.eclipse.ui.IEditorReference;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.actions.WorkspaceAction;
import org.eclipse.ui.ide.undo.MoveResourcesOperation;
import org.eclipse.ui.ide.undo.WorkspaceUndoUtil;
import org.eclipse.ui.internal.ide.IDEWorkbenchMessages;
import org.eclipse.ui.internal.ide.IDEWorkbenchPlugin;
import org.eclipse.ui.internal.ide.IIDEHelpContextIds;
import org.eclipse.ui.internal.ide.actions.LTKLauncher;
import org.eclipse.ui.internal.navigator.TextActionHandler;
import org.eclipse.ui.part.FileEditorInput;
import com.ximpleware.AutoPilot;
import com.ximpleware.VTDGen;
import com.ximpleware.VTDNav;
/**
* Standard action for renaming the selected resources.
* <p>
* This class may be instantiated; it is not intended to be subclassed.
* </p>
* @noextend This class is not intended to be subclassed by clients.
*/
public class RenameResourceAndCloseEditorAction extends WorkspaceAction {
/*
* The tree editing widgets. If treeEditor is null then edit using the
* dialog. We keep the editorText around so that we can close it if a new
* selection is made.
*/
private TreeEditor treeEditor;
private Tree navigatorTree;
private Text textEditor;
private Composite textEditorParent;
private TextActionHandler textActionHandler;
// The resource being edited if this is being done inline
private IResource inlinedResource;
private boolean saving = false;
/**
* The id of this action.
*/
public static final String ID = PlatformUI.PLUGIN_ID
+ ".RenameResourceAction";//$NON-NLS-1$
/**
* The new path.
*/
private IPath newPath;
private String[] modelProviderIds;
private static final String CHECK_RENAME_TITLE = IDEWorkbenchMessages.RenameResourceAction_checkTitle;
private static final String CHECK_RENAME_MESSAGE = IDEWorkbenchMessages.RenameResourceAction_readOnlyCheck;
private static String RESOURCE_EXISTS_TITLE = IDEWorkbenchMessages.RenameResourceAction_resourceExists;
private static String RESOURCE_EXISTS_MESSAGE = IDEWorkbenchMessages.RenameResourceAction_overwriteQuestion;
private static String PROJECT_EXISTS_MESSAGE = IDEWorkbenchMessages.RenameResourceAction_overwriteProjectQuestion;
private static String PROJECT_EXISTS_TITLE = IDEWorkbenchMessages.RenameResourceAction_projectExists;
private IShellProvider shellProvider;
/**
* Creates a new action. Using this constructor directly will rename using a
* dialog rather than the inline editor of a ResourceNavigator.
*
* @param shell
* the shell for any dialogs
* @deprecated see {@link #RenameResourceAction(IShellProvider)}
*/
public RenameResourceAndCloseEditorAction(Shell shell) {
super(shell, IDEWorkbenchMessages.RenameResourceAction_text);
initAction();
}
/**
* Creates a new action. Using this constructor directly will rename using a
* dialog rather than the inline editor of a ResourceNavigator.
*
* @param provider
* the IShellProvider for any dialogs
* @since 3.4
*/
public RenameResourceAndCloseEditorAction(IShellProvider provider){
super(provider, IDEWorkbenchMessages.RenameResourceAction_text);
shellProvider = provider;
initAction();
}
private void initAction(){
setToolTipText(IDEWorkbenchMessages.RenameResourceAction_toolTip);
setId(ID);
PlatformUI.getWorkbench().getHelpSystem().setHelp(this,
IIDEHelpContextIds.RENAME_RESOURCE_ACTION);
}
/**
* Creates a new action.
*
* @param shell
* the shell for any dialogs
* @param tree
* the tree
* @deprecated see {@link #RenameResourceAction(IShellProvider, Tree)}
*/
public RenameResourceAndCloseEditorAction(Shell shell, Tree tree) {
this(shell);
this.navigatorTree = tree;
this.treeEditor = new TreeEditor(tree);
}
/**
* Creates a new action.
*
* @param provider
* the shell provider for any dialogs
* @param tree
* the tree
* @since 3.4
*/
public RenameResourceAndCloseEditorAction(IShellProvider provider, Tree tree) {
this(provider);
this.navigatorTree = tree;
this.treeEditor = new TreeEditor(tree);
}
/**
* Check if the user wishes to overwrite the supplied resource
*
* @returns true if there is no collision or delete was successful
* @param shell
* the shell to create the dialog in
* @param destination -
* the resource to be overwritten
*/
private boolean checkOverwrite(final Shell shell,
final IResource destination) {
final boolean[] result = new boolean[1];
// Run it inside of a runnable to make sure we get to parent off of the
// shell as we are not in the UI thread.
Runnable query = new Runnable() {
public void run() {
String pathName = destination.getFullPath().makeRelative()
.toString();
String message = RESOURCE_EXISTS_MESSAGE;
String title = RESOURCE_EXISTS_TITLE;
if (destination.getType() == IResource.PROJECT) {
message = PROJECT_EXISTS_MESSAGE;
title = PROJECT_EXISTS_TITLE;
}
result[0] = MessageDialog.openQuestion(shell,
title, MessageFormat.format(message,
new Object[] { pathName }));
}
};
shell.getDisplay().syncExec(query);
return result[0];
}
/**
* Check if the supplied resource is read only or null. If it is then ask
* the user if they want to continue. Return true if the resource is not
* read only or if the user has given permission.
*
* @return boolean
*/
private boolean checkReadOnlyAndNull(IResource currentResource) {
// Do a quick read only and null check
if (currentResource == null) {
return false;
}
// Do a quick read only check
final ResourceAttributes attributes = currentResource
.getResourceAttributes();
if (attributes != null && attributes.isReadOnly()) {
return MessageDialog.openQuestion(shellProvider.getShell(), CHECK_RENAME_TITLE,
MessageFormat.format(CHECK_RENAME_MESSAGE,
new Object[] { currentResource.getName() }));
}
return true;
}
Composite createParent() {
Tree tree = getTree();
Composite result = new Composite(tree, SWT.NONE);
TreeItem[] selectedItems = tree.getSelection();
treeEditor.horizontalAlignment = SWT.LEFT;
treeEditor.grabHorizontal = true;
treeEditor.setEditor(result, selectedItems[0]);
return result;
}
/**
* Get the inset used for cell editors
* @param c the Control
* @return int
*/
private static int getCellEditorInset(Control c) {
return 1; // one pixel wide black border
}
/**
* Create the text editor widget.
*
* @param resource
* the resource to rename
*/
private void createTextEditor(final IResource resource) {
// Create text editor parent. This draws a nice bounding rect.
textEditorParent = createParent();
textEditorParent.setVisible(false);
final int inset = getCellEditorInset(textEditorParent);
if (inset > 0) {
textEditorParent.addListener(SWT.Paint, new Listener() {
public void handleEvent(Event e) {
Point textSize = textEditor.getSize();
Point parentSize = textEditorParent.getSize();
e.gc.drawRectangle(0, 0, Math.min(textSize.x + 4,
parentSize.x - 1), parentSize.y - 1);
}
});
}
// Create inner text editor.
textEditor = new Text(textEditorParent, SWT.NONE);
textEditor.setFont(navigatorTree.getFont());
textEditorParent.setBackground(textEditor.getBackground());
textEditor.addListener(SWT.Modify, new Listener() {
public void handleEvent(Event e) {
Point textSize = textEditor.computeSize(SWT.DEFAULT,
SWT.DEFAULT);
textSize.x += textSize.y; // Add extra space for new
// characters.
Point parentSize = textEditorParent.getSize();
textEditor.setBounds(2, inset, Math.min(textSize.x,
parentSize.x - 4), parentSize.y - 2 * inset);
textEditorParent.redraw();
}
});
textEditor.addListener(SWT.Traverse, new Listener() {
public void handleEvent(Event event) {
// Workaround for Bug 20214 due to extra
// traverse events
switch (event.detail) {
case SWT.TRAVERSE_ESCAPE:
// Do nothing in this case
disposeTextWidget();
event.doit = true;
event.detail = SWT.TRAVERSE_NONE;
break;
case SWT.TRAVERSE_RETURN:
saveChangesAndDispose(resource);
event.doit = true;
event.detail = SWT.TRAVERSE_NONE;
break;
}
}
});
textEditor.addFocusListener(new FocusAdapter() {
public void focusLost(FocusEvent fe) {
saveChangesAndDispose(resource);
closeRelatedEditors();
}
});
if (textActionHandler != null) {
textActionHandler.addText(textEditor);
}
}
/**
* Close the text widget and reset the editorText field.
*/
private void disposeTextWidget() {
if (textActionHandler != null) {
textActionHandler.removeText(textEditor);
}
if (textEditorParent != null) {
textEditorParent.dispose();
textEditorParent = null;
textEditor = null;
treeEditor.setEditor(null, null);
}
}
/**
* Returns the elements that the action is to be performed on. Return the
* resource cached by the action as we cannot rely on the selection being
* correct for inlined text.
*
* @return list of resource elements (element type: <code>IResource</code>)
*/
protected List getActionResources() {
if (inlinedResource == null) {
return super.getActionResources();
}
List actionResources = new ArrayList();
actionResources.add(inlinedResource);
return actionResources;
}
/*
* (non-Javadoc) Method declared on WorkspaceAction.
*/
protected String getOperationMessage() {
return IDEWorkbenchMessages.RenameResourceAction_progress;
}
/*
* (non-Javadoc) Method declared on WorkspaceAction.
*/
protected String getProblemsMessage() {
return IDEWorkbenchMessages.RenameResourceAction_problemMessage;
}
/*
* (non-Javadoc) Method declared on WorkspaceAction.
*/
protected String getProblemsTitle() {
return IDEWorkbenchMessages.RenameResourceAction_problemTitle;
}
/**
* Get the Tree being edited.
*
* @returnTree
*/
private Tree getTree() {
return this.navigatorTree;
}
/**
* Return the new name to be given to the target resource.
*
* @return java.lang.String
* @param resource
* the resource to query status on
*/
protected String queryNewResourceName(final IResource resource) {
final IWorkspace workspace = IDEWorkbenchPlugin.getPluginWorkspace();
final IPath prefix = resource.getFullPath().removeLastSegments(1);
IInputValidator validator = new IInputValidator() {
public String isValid(String string) {
if (resource.getName().equals(string)) {
return IDEWorkbenchMessages.RenameResourceAction_nameMustBeDifferent;
}
IStatus status = workspace.validateName(string, resource
.getType());
if (!status.isOK()) {
return status.getMessage();
}
if (workspace.getRoot().exists(prefix.append(string))) {
return IDEWorkbenchMessages.RenameResourceAction_nameExists;
}
return null;
}
};
InputDialog dialog = new InputDialog(shellProvider.getShell(),
IDEWorkbenchMessages.RenameResourceAction_inputDialogTitle,
IDEWorkbenchMessages.RenameResourceAction_inputDialogMessage,
resource.getName(), validator);
dialog.setBlockOnOpen(true);
int result = dialog.open();
if (result == Window.OK)
return dialog.getValue();
return null;
}
/**
* Return the new name to be given to the target resource or
* <code>null<code>
* if the query was canceled. Rename the currently selected resource using the table editor.
* Continue the action when the user is done.
*
* @param resource the resource to rename
*/
private void queryNewResourceNameInline(final IResource resource) {
// Make sure text editor is created only once. Simply reset text
// editor when action is executed more than once. Fixes bug 22269.
if (textEditorParent == null) {
createTextEditor(resource);
}
textEditor.setText(resource.getName());
// Open text editor with initial size.
textEditorParent.setVisible(true);
Point textSize = textEditor.computeSize(SWT.DEFAULT, SWT.DEFAULT);
textSize.x += textSize.y; // Add extra space for new characters.
Point parentSize = textEditorParent.getSize();
int inset = getCellEditorInset(textEditorParent);
textEditor.setBounds(2, inset, Math.min(textSize.x, parentSize.x - 4),
parentSize.y - 2 * inset);
textEditorParent.redraw();
textEditor.selectAll();
textEditor.setFocus();
}
/*
* (non-Javadoc) Method declared on IAction; overrides method on
* WorkspaceAction.
*/
public void run() {
IResource currentResource = getCurrentResource();
if (currentResource == null || !currentResource.exists()) {
return;
}
if (LTKLauncher.openRenameWizard(getStructuredSelection())) {
return;
}
if (this.navigatorTree == null) {
// Do a quick read only and null check
if (!checkReadOnlyAndNull(currentResource)) {
return;
}
String newName = queryNewResourceName(currentResource);
if (newName == null || newName.equals("")) { //$NON-NLS-1$
return;
}
newPath = currentResource.getFullPath().removeLastSegments(1)
.append(newName);
super.run();
} else {
runWithInlineEditor();
}
}
/**
* 重命名文件时,如果文件在编辑器中已打开,则关闭此文件。 ;
*/
private void closeRelatedEditors() {
IWorkbenchPage page = null;
for (IWorkbenchWindow window : PlatformUI.getWorkbench().getWorkbenchWindows()) {
if (window != null) {
page = window.getActivePage();
break;
}
}
if (page == null) {
return;
}
IEditorReference[] editorReferences = page.getEditorReferences();
List<IResource> selectionResource = getSelectedResources();
final List<IEditorReference> lstCloseEditor = new ArrayList<IEditorReference>();
VTDGen vg = new VTDGen();
AutoPilot ap = new AutoPilot();
for (IEditorReference reference : editorReferences) {
IFile file = ((FileEditorInput) reference.getEditor(true).getEditorInput()).getFile();
if ("xlp".equals(file.getFileExtension())) {
if (vg.parseFile(file.getLocation().toOSString(), true)) {
VTDNav vn = vg.getNav();
ap.bind(vn);
try {
ap.selectXPath("/mergerFiles/mergerFile/@filePath");
int index = -1;
merge: while ((index = ap.evalXPath()) != -1) {
String fileLC = vn.toString(index + 1);
if (fileLC != null && !"".equals(fileLC)) {
for (IResource resource : selectionResource) {
if (resource instanceof IProject || resource instanceof IFolder) {
if (fileLC.startsWith(resource.getLocation().toOSString() + File.separator)) {
lstCloseEditor.add(reference);
break merge;
}
} else if (resource instanceof IFile) {
if (resource.getLocation().toOSString().equals(fileLC)) {
lstCloseEditor.add(reference);
break merge;
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
} else {
for (IResource resource : selectionResource) {
if (resource instanceof IProject) {
if (resource.getLocation().toOSString().equals(file.getProject().getLocation().toOSString())) {
lstCloseEditor.add(reference);
break;
}
} else if (resource instanceof IFolder) {
if (file.getLocation().toOSString()
.startsWith(resource.getLocation().toOSString() + File.separator)) {
lstCloseEditor.add(reference);
break;
}
} else if (resource instanceof IFile) {
if (resource.getLocation().toOSString().equals(file.getLocation().toOSString())) {
lstCloseEditor.add(reference);
break;
}
}
}
}
}
final IWorkbenchPage page2 = page;
Display.getDefault().asyncExec(new Runnable() {
public void run() {
IEditorReference[] arrEditorReference = new IEditorReference[lstCloseEditor.size()];
page2.closeEditors(lstCloseEditor.toArray(arrEditorReference), false);
}
});
}
/*
* Run the receiver using an inline editor from the supplied navigator. The
* navigator will tell the action when the path is ready to run.
*/
private void runWithInlineEditor() {
IResource currentResource = getCurrentResource();
if (!checkReadOnlyAndNull(currentResource)) {
return;
}
queryNewResourceNameInline(currentResource);
}
/**
* Return the currently selected resource. Only return an IResouce if there
* is one and only one resource selected.
*
* @return IResource or <code>null</code> if there is zero or more than
* one resources selected.
*/
private IResource getCurrentResource() {
List resources = getSelectedResources();
if (resources.size() == 1) {
return (IResource) resources.get(0);
}
return null;
}
/**
* @param path
* the path
* @param resource
* the resource
*/
protected void runWithNewPath(IPath path, IResource resource) {
this.newPath = path;
super.run();
}
void displayError(String message) {
if (message == null) {
message = IDEWorkbenchMessages.WorkbenchAction_internalError;
}
MessageDialog.openError(shellProvider.getShell(), getProblemsTitle(), message);
}
/**
* Save the changes and dispose of the text widget.
*
* @param resource -
* the resource to move.
*/
private void saveChangesAndDispose(IResource resource) {
if (saving == true) {
return;
}
saving = true;
// Cache the resource to avoid selection loss since a selection of
// another item can trigger this method
inlinedResource = resource;
final String newName = textEditor.getText();
// Run this in an async to make sure that the operation that triggered
// this action is completed. Otherwise this leads to problems when the
// icon of the item being renamed is clicked (i.e., which causes the
// rename
// text widget to lose focus and trigger this method).
Runnable query = new Runnable() {
public void run() {
try {
if (!newName.equals(inlinedResource.getName())) {
IWorkspace workspace = IDEWorkbenchPlugin
.getPluginWorkspace();
IStatus status = workspace.validateName(newName,
inlinedResource.getType());
if (!status.isOK()) {
displayError(status.getMessage());
} else {
// 验证资源名称是否合法 robert 2013-07-01
String validResult = CommonFunction.validResourceName(newName);
if (validResult != null) {
displayError(validResult);
}else {
IPath newPath = inlinedResource.getFullPath()
.removeLastSegments(1).append(newName);
runWithNewPath(newPath, inlinedResource);
}
}
}
inlinedResource = null;
// Dispose the text widget regardless
disposeTextWidget();
// Ensure the Navigator tree has focus, which it may not if
// the
// text widget previously had focus.
if (navigatorTree != null && !navigatorTree.isDisposed()) {
navigatorTree.setFocus();
}
} finally {
saving = false;
}
}
};
getTree().getShell().getDisplay().asyncExec(query);
}
/**
* The <code>RenameResourceAction</code> implementation of this
* <code>SelectionListenerAction</code> method ensures that this action is
* disabled if any of the selections are not resources or resources that are
* not local.
*/
protected boolean updateSelection(IStructuredSelection selection) {
disposeTextWidget();
if (selection.size() > 1) {
return false;
}
if (!super.updateSelection(selection)) {
return false;
}
IResource currentResource = getCurrentResource();
if (currentResource == null || !currentResource.exists()) {
return false;
}
return true;
}
/**
* Set the text action handler.
*
* @param actionHandler
* the action handler
*/
public void setTextActionHandler(TextActionHandler actionHandler) {
textActionHandler = actionHandler;
}
/**
* Returns the model provider ids that are known to the client that
* instantiated this operation.
*
* @return the model provider ids that are known to the client that
* instantiated this operation.
* @since 3.2
*/
public String[] getModelProviderIds() {
return modelProviderIds;
}
/**
* Sets the model provider ids that are known to the client that
* instantiated this operation. Any potential side effects reported by these
* models during validation will be ignored.
*
* @param modelProviderIds
* the model providers known to the client who is using this
* operation.
* @since 3.2
*/
public void setModelProviderIds(String[] modelProviderIds) {
this.modelProviderIds = modelProviderIds;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.ui.actions.WorkspaceAction#createOperation(org.eclipse.core.runtime.IStatus[])
*
* Overridden to create and execute an undoable operation that performs the
* rename.
* @since 3.3
*/
protected IRunnableWithProgress createOperation(final IStatus[] errorStatus) {
return new IRunnableWithProgress() {
public void run(IProgressMonitor monitor) {
IResource[] resources = (IResource[]) getActionResources()
.toArray(new IResource[getActionResources().size()]);
// Rename is only valid for a single resource. This has already
// been validated.
if (resources.length == 1) {
// check for overwrite
IWorkspaceRoot workspaceRoot = resources[0].getWorkspace()
.getRoot();
IResource newResource = workspaceRoot.findMember(newPath);
boolean go = true;
if (newResource != null) {
go = checkOverwrite(shellProvider.getShell(), newResource);
}
if (go) {
MoveResourcesOperation op = new MoveResourcesOperation(
resources[0],
newPath,
IDEWorkbenchMessages.RenameResourceAction_operationTitle);
op.setModelProviderIds(getModelProviderIds());
try {
PlatformUI
.getWorkbench()
.getOperationSupport()
.getOperationHistory()
.execute(
op,
monitor,
WorkspaceUndoUtil
.getUIInfoAdapter(shellProvider.getShell()));
} catch (ExecutionException e) {
if (e.getCause() instanceof CoreException) {
errorStatus[0] = ((CoreException) e.getCause())
.getStatus();
} else {
errorStatus[0] = new Status(IStatus.ERROR,
PlatformUI.PLUGIN_ID,
getProblemsMessage(), e);
}
}
}
}
}
};
}
}
| 24,878 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
PasteAction.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/base_commons/net.heartsome.cat.common.ui.navigator.resources/src/org/eclipse/ui/internal/navigator/resources/actions/PasteAction.java | /*******************************************************************************
* Copyright (c) 2000, 2008 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.ui.internal.navigator.resources.actions;
import java.util.List;
import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.Assert;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.swt.dnd.Clipboard;
import org.eclipse.swt.dnd.FileTransfer;
import org.eclipse.swt.dnd.TransferData;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.actions.CopyFilesAndFoldersOperation;
import org.eclipse.ui.actions.CopyProjectOperation;
import org.eclipse.ui.actions.SelectionListenerAction;
import org.eclipse.ui.part.ResourceTransfer;
import org.eclipse.ui.internal.navigator.resources.resource.WorkbenchNavigatorMessages;
/**
* Standard action for pasting resources on the clipboard to the selected resource's location.
* <p>
* This class may be instantiated; it is not intended to be subclassed.
* </p>
*
* @since 2.0
*/
/*package*/class PasteAction extends SelectionListenerAction {
/**
* The id of this action.
*/
public static final String ID = PlatformUI.PLUGIN_ID + ".PasteAction";//$NON-NLS-1$
/**
* The shell in which to show any dialogs.
*/
private Shell shell;
/**
* System clipboard
*/
private Clipboard clipboard;
/**
* Creates a new action.
*
* @param shell the shell for any dialogs
* @param clipboard the clipboard
*/
public PasteAction(Shell shell, Clipboard clipboard) {
super(WorkbenchNavigatorMessages.actions_PasteAction_Past_);
Assert.isNotNull(shell);
Assert.isNotNull(clipboard);
this.shell = shell;
this.clipboard = clipboard;
setToolTipText(WorkbenchNavigatorMessages.actions_PasteAction_Paste_selected_resource_s_);
setId(PasteAction.ID);
PlatformUI.getWorkbench().getHelpSystem().setHelp(this, "HelpId"); //$NON-NLS-1$
// TODO INavigatorHelpContextIds.PASTE_ACTION);
}
/**
* Returns the actual target of the paste action. Returns null
* if no valid target is selected.
*
* @return the actual target of the paste action
*/
private IResource getTarget() {
List selectedResources = getSelectedResources();
for (int i = 0; i < selectedResources.size(); i++) {
IResource resource = (IResource) selectedResources.get(i);
if (resource instanceof IProject && !((IProject) resource).isOpen()) {
return null;
}
if (resource.getType() == IResource.FILE) {
resource = resource.getParent();
}
if (resource != null) {
return resource;
}
}
return null;
}
/**
* Returns whether any of the given resources are linked resources.
*
* @param resources resource to check for linked type. may be null
* @return true=one or more resources are linked. false=none of the
* resources are linked
*/
private boolean isLinked(IResource[] resources) {
for (int i = 0; i < resources.length; i++) {
if (resources[i].isLinked()) {
return true;
}
}
return false;
}
/**
* Implementation of method defined on <code>IAction</code>.
*/
public void run() {
// try a resource transfer
ResourceTransfer resTransfer = ResourceTransfer.getInstance();
IResource[] resourceData = (IResource[]) clipboard
.getContents(resTransfer);
if (resourceData != null && resourceData.length > 0) {
if (resourceData[0].getType() == IResource.PROJECT) {
// enablement checks for all projects
for (int i = 0; i < resourceData.length; i++) {
CopyProjectOperation operation = new CopyProjectOperation(
this.shell);
operation.copyProject((IProject) resourceData[i]);
}
} else {
// enablement should ensure that we always have access to a container
IContainer container = getContainer();
CopyFilesAndFoldersOperation operation = new CopyFilesAndFoldersOperation(
this.shell);
operation.copyResources(resourceData, container);
}
return;
}
// try a file transfer
FileTransfer fileTransfer = FileTransfer.getInstance();
String[] fileData = (String[]) clipboard.getContents(fileTransfer);
if (fileData != null) {
// enablement should ensure that we always have access to a container
IContainer container = getContainer();
CopyFilesAndFoldersOperation operation = new CopyFilesAndFoldersOperation(
this.shell);
operation.copyFiles(fileData, container);
}
}
/**
* Returns the container to hold the pasted resources.
*/
private IContainer getContainer() {
List selection = getSelectedResources();
if (selection.get(0) instanceof IFile) {
return ((IFile) selection.get(0)).getParent();
}
return (IContainer) selection.get(0);
}
/**
* The <code>PasteAction</code> implementation of this
* <code>SelectionListenerAction</code> method enables this action if
* a resource compatible with what is on the clipboard is selected.
*
* -Clipboard must have IResource or java.io.File
* -Projects can always be pasted if they are open
* -Workspace folder may not be copied into itself
* -Files and folders may be pasted to a single selected folder in open
* project or multiple selected files in the same folder
*/
protected boolean updateSelection(IStructuredSelection selection) {
if (!super.updateSelection(selection)) {
return false;
}
final IResource[][] clipboardData = new IResource[1][];
shell.getDisplay().syncExec(new Runnable() {
public void run() {
// clipboard must have resources or files
ResourceTransfer resTransfer = ResourceTransfer.getInstance();
clipboardData[0] = (IResource[]) clipboard
.getContents(resTransfer);
}
});
IResource[] resourceData = clipboardData[0];
boolean isProjectRes = resourceData != null && resourceData.length > 0
&& resourceData[0].getType() == IResource.PROJECT;
if (isProjectRes) {
for (int i = 0; i < resourceData.length; i++) {
// make sure all resource data are open projects
// can paste open projects regardless of selection
if (resourceData[i].getType() != IResource.PROJECT
|| ((IProject) resourceData[i]).isOpen() == false) {
return false;
}
}
return true;
}
if (getSelectedNonResources().size() > 0) {
return false;
}
IResource targetResource = getTarget();
// targetResource is null if no valid target is selected (e.g., open project)
// or selection is empty
if (targetResource == null) {
return false;
}
// can paste files and folders to a single selection (file, folder,
// open project) or multiple file selection with the same parent
List selectedResources = getSelectedResources();
if (selectedResources.size() > 1) {
for (int i = 0; i < selectedResources.size(); i++) {
IResource resource = (IResource) selectedResources.get(i);
if (resource.getType() != IResource.FILE) {
return false;
}
if (!targetResource.equals(resource.getParent())) {
return false;
}
}
}
if (resourceData != null) {
// linked resources can only be pasted into projects
if (isLinked(resourceData)
&& targetResource.getType() != IResource.PROJECT
&& targetResource.getType() != IResource.FOLDER) {
return false;
}
if (targetResource.getType() == IResource.FOLDER) {
// don't try to copy folder to self
for (int i = 0; i < resourceData.length; i++) {
if (targetResource.equals(resourceData[i])) {
return false;
}
}
}
return true;
}
TransferData[] transfers = clipboard.getAvailableTypes();
FileTransfer fileTransfer = FileTransfer.getInstance();
for (int i = 0; i < transfers.length; i++) {
if (fileTransfer.isSupportedType(transfers[i])) {
return true;
}
}
return false;
}
}
| 9,431 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
EditActionProvider.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/base_commons/net.heartsome.cat.common.ui.navigator.resources/src/org/eclipse/ui/internal/navigator/resources/actions/EditActionProvider.java | /*******************************************************************************
* Copyright (c) 2006 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
******************************************************************************/
package org.eclipse.ui.internal.navigator.resources.actions;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.ui.IActionBars;
import org.eclipse.ui.actions.ActionContext;
import org.eclipse.ui.navigator.CommonActionProvider;
import org.eclipse.ui.navigator.ICommonActionExtensionSite;
/**
* @since 3.2
*
*/
public class EditActionProvider extends CommonActionProvider {
private EditActionGroup editGroup;
private ICommonActionExtensionSite site;
/*
* (non-Javadoc)
*
* @see org.eclipse.ui.navigator.CommonActionProvider#init(org.eclipse.ui.navigator.ICommonActionExtensionSite)
*/
public void init(ICommonActionExtensionSite anActionSite) {
site = anActionSite;
editGroup = new EditActionGroup(site.getViewSite().getShell());
}
public void dispose() {
editGroup.dispose();
}
public void fillActionBars(IActionBars actionBars) {
editGroup.fillActionBars(actionBars);
}
public void fillContextMenu(IMenuManager menu) {
editGroup.fillContextMenu(menu);
}
public void setContext(ActionContext context) {
editGroup.setContext(context);
}
public void updateActionBars() {
editGroup.updateActionBars();
}
}
| 1,711 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
OpenActionProvider.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/base_commons/net.heartsome.cat.common.ui.navigator.resources/src/org/eclipse/ui/internal/navigator/resources/actions/OpenActionProvider.java | /*******************************************************************************
* Copyright (c) 2005, 2010 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
* [email protected] - bug 288997 [CommonNavigator] Double-clicking an adapted resource in
* Common Navigator does not open underlying IFile
*******************************************************************************/
package org.eclipse.ui.internal.navigator.resources.actions;
import org.eclipse.core.resources.IFile;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.ui.IActionBars;
import org.eclipse.ui.internal.navigator.resources.resource.WorkbenchNavigatorMessages;
import org.eclipse.ui.navigator.CommonActionProvider;
import org.eclipse.ui.navigator.ICommonActionConstants;
import org.eclipse.ui.navigator.ICommonActionExtensionSite;
import org.eclipse.ui.navigator.ICommonMenuConstants;
import org.eclipse.ui.navigator.ICommonViewerWorkbenchSite;
/**
* Provides the open and open with menus for IResources.
* @since 3.2
*/
public class OpenActionProvider extends CommonActionProvider {
private OpenFileWithValidAction openFileAction;
private ICommonViewerWorkbenchSite viewSite = null;
private boolean contribute = false;
public void init(ICommonActionExtensionSite aConfig) {
if (aConfig.getViewSite() instanceof ICommonViewerWorkbenchSite) {
viewSite = (ICommonViewerWorkbenchSite) aConfig.getViewSite();
openFileAction = new OpenFileWithValidAction(viewSite.getPage());
openFileAction.setText(WorkbenchNavigatorMessages.actions_OpenActionProvider_openFileAction);
contribute = true;
}
}
public void fillContextMenu(IMenuManager aMenu) {
if (!contribute || getContext().getSelection().isEmpty()) {
return;
}
IStructuredSelection selection = (IStructuredSelection) getContext().getSelection();
openFileAction.selectionChanged(selection);
if (openFileAction.isEnabled()) {
aMenu.insertAfter(ICommonMenuConstants.GROUP_OPEN, openFileAction);
}
// addOpenWithMenu(aMenu);
}
public void fillActionBars(IActionBars theActionBars) {
if (!contribute) {
return;
}
IStructuredSelection selection = (IStructuredSelection) getContext().getSelection();
if (selection.size() == 1 && selection.getFirstElement() instanceof IFile) {
openFileAction.selectionChanged(selection);
theActionBars.setGlobalActionHandler(ICommonActionConstants.OPEN, openFileAction);
}
}
// private void addOpenWithMenu(IMenuManager aMenu) {
// IStructuredSelection ss = (IStructuredSelection) getContext().getSelection();
//
// if (ss == null || ss.size() != 1) {
// return;
// }
//
// Object o = ss.getFirstElement();
//
// // first try IResource
// IAdaptable openable = (IAdaptable) AdaptabilityUtility.getAdapter(o, IResource.class);
// // otherwise try ResourceMapping
// if (openable == null) {
// openable = (IAdaptable) AdaptabilityUtility.getAdapter(o, ResourceMapping.class);
// } else if (((IResource) openable).getType() != IResource.FILE) {
// openable = null;
// }
//
// if (openable != null) {
// // Create a menu flyout.
//
// IMenuManager submenu = new MenuManager(WorkbenchNavigatorMessages.actions_OpenActionProvider_OpenWithMenu_label,
// ICommonMenuConstants.GROUP_OPEN_WITH);
// /*
// * IMenuManager submenu = new MenuManager(Messages.getString("actions.OpenActionProvider.submenu"),
// * ICommonMenuConstants.GROUP_OPEN_WITH);
// */
// submenu.add(new GroupMarker(ICommonMenuConstants.GROUP_TOP));
// submenu.add(new OpenWithMenu(viewSite.getPage(), openable));
// submenu.add(new GroupMarker(ICommonMenuConstants.GROUP_ADDITIONS));
//
// // Add the submenu.
// if (submenu.getItems().length > 2 && submenu.isEnabled()) {
// aMenu.appendToGroup(ICommonMenuConstants.GROUP_OPEN_WITH, submenu);
// }
// }
// }
}
| 4,190 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
WorkManagementActionProvider.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/base_commons/net.heartsome.cat.common.ui.navigator.resources/src/org/eclipse/ui/internal/navigator/resources/actions/WorkManagementActionProvider.java | /*******************************************************************************
* Copyright (c) 2005, 2008 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.ui.internal.navigator.resources.actions;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.window.IShellProvider;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IActionBars;
import org.eclipse.ui.actions.ActionContext;
import org.eclipse.ui.actions.AddBookmarkAction;
import org.eclipse.ui.actions.AddTaskAction;
import org.eclipse.ui.ide.IDEActionFactory;
import org.eclipse.ui.navigator.CommonActionProvider;
import org.eclipse.ui.navigator.ICommonActionExtensionSite;
/**
* Supports Add Task and Add Bookmark actions.
*
* @since 3.2
*
*/
public class WorkManagementActionProvider extends CommonActionProvider {
private AddTaskAction addTaskAction;
private AddBookmarkAction addBookmarkAction;
public void init(ICommonActionExtensionSite aSite) {
final Shell shell = aSite.getViewSite().getShell();
IShellProvider sp = new IShellProvider() {
public Shell getShell() {
return shell;
}
};
addBookmarkAction = new AddBookmarkAction(sp, true);
addTaskAction = new AddTaskAction(sp);
}
/*
* (non-Javadoc)
*
* @see
* org.eclipse.ui.actions.ActionGroup#fillActionBars(org.eclipse.ui.IActionBars
* )
*/
public void fillActionBars(IActionBars actionBars) {
super.fillActionBars(actionBars);
actionBars.setGlobalActionHandler(IDEActionFactory.BOOKMARK.getId(), addBookmarkAction);
actionBars.setGlobalActionHandler(IDEActionFactory.ADD_TASK.getId(), addTaskAction);
}
/*
* (non-Javadoc)
*
* @see
* org.eclipse.ui.actions.ActionGroup#setContext(org.eclipse.ui.actions.
* ActionContext)
*/
public void setContext(ActionContext context) {
super.setContext(context);
if (context != null && context.getSelection() instanceof IStructuredSelection) {
IStructuredSelection sSel = (IStructuredSelection) context.getSelection();
addBookmarkAction.selectionChanged(sSel);
addTaskAction.selectionChanged(sSel);
} else {
addBookmarkAction.selectionChanged(StructuredSelection.EMPTY);
addTaskAction.selectionChanged(StructuredSelection.EMPTY);
}
}
}
| 2,686 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
WorkingSetActionProvider.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/base_commons/net.heartsome.cat.common.ui.navigator.resources/src/org/eclipse/ui/internal/navigator/resources/actions/WorkingSetActionProvider.java | /*******************************************************************************
* Copyright (c) 2006, 2010 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
* [email protected] - bug 212389 [CommonNavigator] working set issues:
* missing project, window working set inconsistency
*******************************************************************************/
package org.eclipse.ui.internal.navigator.resources.actions;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.util.IPropertyChangeListener;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.jface.viewers.ViewerFilter;
import org.eclipse.ui.IActionBars;
import org.eclipse.ui.IAggregateWorkingSet;
import org.eclipse.ui.IMemento;
import org.eclipse.ui.IWorkbenchPreferenceConstants;
import org.eclipse.ui.IWorkingSet;
import org.eclipse.ui.IWorkingSetManager;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.ResourceWorkingSetFilter;
import org.eclipse.ui.actions.WorkingSetFilterActionGroup;
import org.eclipse.ui.internal.navigator.NavigatorFilterService;
import org.eclipse.ui.internal.navigator.resources.plugin.WorkbenchNavigatorPlugin;
import org.eclipse.ui.internal.navigator.resources.resource.WorkbenchNavigatorMessages;
import org.eclipse.ui.internal.navigator.workingsets.WorkingSetsContentProvider;
import org.eclipse.ui.navigator.CommonActionProvider;
import org.eclipse.ui.navigator.CommonViewer;
import org.eclipse.ui.navigator.ICommonActionExtensionSite;
import org.eclipse.ui.navigator.IExtensionActivationListener;
import org.eclipse.ui.navigator.IExtensionStateModel;
import org.eclipse.ui.navigator.INavigatorContentService;
/**
* @since 3.2
*
*/
public class WorkingSetActionProvider extends CommonActionProvider {
private static final String TAG_CURRENT_WORKING_SET_NAME = "currentWorkingSetName"; //$NON-NLS-1$
private static final String WORKING_SET_FILTER_ID = "org.eclipse.ui.navigator.resources.filters.workingSet"; //$NON-NLS-1$
private boolean contributedToViewMenu = false;
private CommonViewer viewer;
private INavigatorContentService contentService;
private NavigatorFilterService filterService;
private WorkingSetFilterActionGroup workingSetActionGroup;
private WorkingSetRootModeActionGroup workingSetRootModeActionGroup;
private Object originalViewerInput = ResourcesPlugin.getWorkspace().getRoot();
private IExtensionStateModel extensionStateModel;
private boolean emptyWorkingSet;
private IWorkingSet workingSet;
private IPropertyChangeListener topLevelModeListener;
private boolean ignoreFilterChangeEvents;
/**
* Provides a smart listener to monitor changes to the Working Set Manager.
*
*/
public class WorkingSetManagerListener implements IPropertyChangeListener {
private boolean listening = false;
public void propertyChange(PropertyChangeEvent event) {
String property = event.getProperty();
Object newValue = event.getNewValue();
Object oldValue = event.getOldValue();
String newLabel = null;
if (IWorkingSetManager.CHANGE_WORKING_SET_REMOVE.equals(property) && oldValue == workingSet) {
newLabel = ""; //$NON-NLS-1$
setWorkingSet(null);
} else if (IWorkingSetManager.CHANGE_WORKING_SET_NAME_CHANGE.equals(property) && newValue == workingSet) {
newLabel = workingSet.getLabel();
} else if (IWorkingSetManager.CHANGE_WORKING_SET_CONTENT_CHANGE.equals(property) && newValue == workingSet) {
if (workingSet.isAggregateWorkingSet() && workingSet.isEmpty()) {
// act as if the working set has been made null
if (!emptyWorkingSet) {
emptyWorkingSet = true;
setWorkingSetFilter(null);
newLabel = null;
}
} else {
// we've gone from empty to non-empty on our set.
// Restore it.
if (emptyWorkingSet) {
emptyWorkingSet = false;
setWorkingSetFilter(workingSet);
newLabel = workingSet.getLabel();
}
}
}
if (viewer != null) {
if (newLabel != null)
viewer.getCommonNavigator().setWorkingSetLabel(newLabel);
viewer.getFrameList().reset();
viewer.refresh();
}
}
/**
* Begin listening to the correct source if not already listening.
*/
public synchronized void listen() {
if (!listening) {
PlatformUI.getWorkbench().getWorkingSetManager().addPropertyChangeListener(managerChangeListener);
listening = true;
}
}
/**
* Begin listening to the correct source if not already listening.
*/
public synchronized void ignore() {
if (listening) {
PlatformUI.getWorkbench().getWorkingSetManager().removePropertyChangeListener(managerChangeListener);
listening = false;
}
}
}
private IPropertyChangeListener filterChangeListener = new IPropertyChangeListener() {
public void propertyChange(PropertyChangeEvent event) {
if (ignoreFilterChangeEvents)
return;
IWorkingSet newWorkingSet = (IWorkingSet) event.getNewValue();
setWorkingSet(newWorkingSet);
if (newWorkingSet != null) {
if (!contentService.isActive(WorkingSetsContentProvider.EXTENSION_ID)) {
contentService.getActivationService().activateExtensions(
new String[] { WorkingSetsContentProvider.EXTENSION_ID }, false);
contentService.getActivationService().persistExtensionActivations();
}
if (newWorkingSet.isAggregateWorkingSet()) {
IAggregateWorkingSet agWs = (IAggregateWorkingSet) newWorkingSet;
IWorkingSet[] comps = agWs.getComponents();
if (comps.length > 1) {
viewer.getCommonNavigator().setWorkingSetLabel(
WorkbenchNavigatorMessages.actions_WorkingSetActionProvider_multipleWorkingSets);
} else if (comps.length > 0) {
viewer.getCommonNavigator().setWorkingSetLabel(comps[0].getLabel());
} else {
viewer.getCommonNavigator().setWorkingSetLabel(null);
}
} else
viewer.getCommonNavigator().setWorkingSetLabel(workingSet.getLabel());
} else {
viewer.getCommonNavigator().setWorkingSetLabel(null);
}
viewer.getFrameList().reset();
}
};
private WorkingSetManagerListener managerChangeListener = new WorkingSetManagerListener();
private IExtensionActivationListener activationListener = new IExtensionActivationListener() {
private IWorkingSet savedWorkingSet;
public void onExtensionActivation(String aViewerId, String[] theNavigatorExtensionIds, boolean isActive) {
for (int i = 0; i < theNavigatorExtensionIds.length; i++) {
if (WorkingSetsContentProvider.EXTENSION_ID.equals(theNavigatorExtensionIds[i])) {
if (isActive) {
extensionStateModel = contentService.findStateModel(WorkingSetsContentProvider.EXTENSION_ID);
workingSetRootModeActionGroup.setStateModel(extensionStateModel);
extensionStateModel.addPropertyChangeListener(topLevelModeListener);
if (savedWorkingSet != null) {
setWorkingSet(savedWorkingSet);
}
managerChangeListener.listen();
} else {
savedWorkingSet = workingSet;
setWorkingSet(null);
viewer.getCommonNavigator().setWorkingSetLabel(null);
managerChangeListener.ignore();
workingSetRootModeActionGroup.setShowTopLevelWorkingSets(false);
extensionStateModel.removePropertyChangeListener(topLevelModeListener);
}
}
}
}
};
public void init(ICommonActionExtensionSite aSite) {
viewer = (CommonViewer) aSite.getStructuredViewer();
contentService = aSite.getContentService();
filterService = (NavigatorFilterService) contentService.getFilterService();
extensionStateModel = contentService.findStateModel(WorkingSetsContentProvider.EXTENSION_ID);
workingSetActionGroup = new WorkingSetFilterActionGroup(aSite.getViewSite().getShell(), filterChangeListener);
workingSetRootModeActionGroup = new WorkingSetRootModeActionGroup(viewer, extensionStateModel);
topLevelModeListener = new IPropertyChangeListener() {
public void propertyChange(PropertyChangeEvent event) {
setWorkingSet(workingSet);
viewer.getFrameList().reset();
}
};
if (contentService.isActive(WorkingSetsContentProvider.EXTENSION_ID)) {
managerChangeListener.listen();
extensionStateModel.addPropertyChangeListener(topLevelModeListener);
}
contentService.getActivationService().addExtensionActivationListener(activationListener);
}
/**
* Restores the working set filter from the persistence store.
*/
protected void initWorkingSetFilter(String workingSetName) {
IWorkingSet workingSet = null;
if (workingSetName != null && workingSetName.length() > 0) {
IWorkingSetManager workingSetManager = PlatformUI.getWorkbench().getWorkingSetManager();
workingSet = workingSetManager.getWorkingSet(workingSetName);
} else if (PlatformUI.getPreferenceStore().getBoolean(
IWorkbenchPreferenceConstants.USE_WINDOW_WORKING_SET_BY_DEFAULT)) {
// use the window set by default if the global preference is set
workingSet = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getAggregateWorkingSet();
}
if (workingSet != null) {
setWorkingSet(workingSet);
}
}
private void setWorkingSetFilter(IWorkingSet workingSet) {
setWorkingSetFilter(workingSet, FIRST_TIME);
}
private static final boolean FIRST_TIME = true;
private void setWorkingSetFilter(IWorkingSet workingSet, boolean firstTime) {
ResourceWorkingSetFilter workingSetFilter = null;
ViewerFilter[] filters = viewer.getFilters();
for (int i = 0; i < filters.length; i++) {
if (filters[i] instanceof ResourceWorkingSetFilter) {
workingSetFilter = (ResourceWorkingSetFilter) filters[i];
break;
}
}
if (workingSetFilter == null) {
if (firstTime) {
filterService.addActiveFilterIds(new String[] { WORKING_SET_FILTER_ID });
filterService.updateViewer();
setWorkingSetFilter(workingSet, !FIRST_TIME);
return;
}
WorkbenchNavigatorPlugin.log("Required filter " + WORKING_SET_FILTER_ID + //$NON-NLS-1$
" is not present. Working set support will not function correctly.", //$NON-NLS-1$
new Status(IStatus.ERROR, WorkbenchNavigatorPlugin.PLUGIN_ID, "")); //$NON-NLS-1$
return;
}
workingSetFilter.setWorkingSet(emptyWorkingSet ? null : workingSet);
}
/**
* Set current active working set.
*
* @param workingSet
* working set to be activated, may be <code>null</code>
*/
protected void setWorkingSet(IWorkingSet workingSet) {
this.workingSet = workingSet;
emptyWorkingSet = workingSet != null && workingSet.isAggregateWorkingSet() && workingSet.isEmpty();
ignoreFilterChangeEvents = true;
try {
workingSetActionGroup.setWorkingSet(workingSet);
} finally {
ignoreFilterChangeEvents = false;
}
if (viewer != null) {
setWorkingSetFilter(workingSet);
if (workingSet == null || emptyWorkingSet
|| !extensionStateModel.getBooleanProperty(WorkingSetsContentProvider.SHOW_TOP_LEVEL_WORKING_SETS)) {
if (viewer.getInput() != originalViewerInput) {
viewer.setInput(originalViewerInput);
} else {
viewer.refresh();
}
} else {
if (!workingSet.isAggregateWorkingSet()) {
IWorkingSetManager workingSetManager = PlatformUI.getWorkbench().getWorkingSetManager();
viewer.setInput(workingSetManager.createAggregateWorkingSet(
"", "", new IWorkingSet[] { workingSet })); //$NON-NLS-1$ //$NON-NLS-2$
} else {
viewer.setInput(workingSet);
}
}
}
}
public void restoreState(final IMemento aMemento) {
super.restoreState(aMemento);
// Need to run this async to avoid being reentered when processing a selection change
viewer.getControl().getShell().getDisplay().asyncExec(new Runnable() {
public void run() {
boolean showWorkingSets = true;
if (aMemento != null) {
Integer showWorkingSetsInt = aMemento
.getInteger(WorkingSetsContentProvider.SHOW_TOP_LEVEL_WORKING_SETS);
showWorkingSets = showWorkingSetsInt == null || showWorkingSetsInt.intValue() == 1;
extensionStateModel.setBooleanProperty(WorkingSetsContentProvider.SHOW_TOP_LEVEL_WORKING_SETS,
showWorkingSets);
workingSetRootModeActionGroup.setShowTopLevelWorkingSets(showWorkingSets);
String lastWorkingSetName = aMemento.getString(TAG_CURRENT_WORKING_SET_NAME);
initWorkingSetFilter(lastWorkingSetName);
} else {
showWorkingSets = false;
extensionStateModel.setBooleanProperty(WorkingSetsContentProvider.SHOW_TOP_LEVEL_WORKING_SETS,
showWorkingSets);
workingSetRootModeActionGroup.setShowTopLevelWorkingSets(showWorkingSets);
}
}
});
}
public void saveState(IMemento aMemento) {
super.saveState(aMemento);
if (aMemento != null) {
int showWorkingSets = extensionStateModel
.getBooleanProperty(WorkingSetsContentProvider.SHOW_TOP_LEVEL_WORKING_SETS) ? 1 : 0;
aMemento.putInteger(WorkingSetsContentProvider.SHOW_TOP_LEVEL_WORKING_SETS, showWorkingSets);
if (workingSet != null) {
aMemento.putString(TAG_CURRENT_WORKING_SET_NAME, workingSet.getName());
}
}
}
public void fillActionBars(IActionBars actionBars) {
if (!contributedToViewMenu) {
try {
super.fillActionBars(actionBars);
workingSetActionGroup.fillActionBars(actionBars);
if (workingSetRootModeActionGroup != null) {
workingSetRootModeActionGroup.fillActionBars(actionBars);
}
} finally {
contributedToViewMenu = true;
}
}
}
public void dispose() {
super.dispose();
workingSetActionGroup.dispose();
if (workingSetRootModeActionGroup != null) {
workingSetRootModeActionGroup.dispose();
}
managerChangeListener.ignore();
extensionStateModel.removePropertyChangeListener(topLevelModeListener);
contentService.getActivationService().removeExtensionActivationListener(activationListener);
}
/**
* This is used only for the tests.
*
* @return a PropertyChangeListener
*/
public IPropertyChangeListener getFilterChangeListener() {
return filterChangeListener;
}
}
| 14,350 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
WorkingSetRootModeActionGroup.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/base_commons/net.heartsome.cat.common.ui.navigator.resources/src/org/eclipse/ui/internal/navigator/resources/actions/WorkingSetRootModeActionGroup.java | /*******************************************************************************
* Copyright (c) 2006, 2010 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.ui.internal.navigator.resources.actions;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.ContributionItem;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.viewers.StructuredViewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.ui.IActionBars;
import org.eclipse.ui.ISharedImages;
import org.eclipse.ui.IWorkbenchActionConstants;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.actions.ActionGroup;
import org.eclipse.ui.ide.IDE;
import org.eclipse.ui.internal.navigator.resources.plugin.WorkbenchNavigatorPlugin;
import org.eclipse.ui.internal.navigator.resources.resource.WorkbenchNavigatorMessages;
import org.eclipse.ui.internal.navigator.workingsets.WorkingSetsContentProvider;
import org.eclipse.ui.navigator.IExtensionStateModel;
/**
*
* Provides the radio buttons at the top of the view menu that control the root
* of the ProjectExplorer, which is either working sets of projects. When the
* state is changed through the actions, the WorkingSetsContentProvider.SHOW_TOP_LEVEL_WORKING_SETS
* property in the extension state model is updated.
*
* This is installed by the WorkingSetActionProvider.
*
* @since 3.2
*
*/
public class WorkingSetRootModeActionGroup extends ActionGroup {
private IExtensionStateModel stateModel;
private StructuredViewer structuredViewer;
private boolean hasContributedToViewMenu = false;
private IAction workingSetsAction = null;
private IAction projectsAction = null;
private IAction[] actions;
private int currentSelection;
private MenuItem[] items;
private class TopLevelContentAction extends Action {
private final boolean groupWorkingSets;
/**
* Construct an Action that represents a toggle-able state between
* Showing top level Working Sets and Projects.
*
* @param toGroupWorkingSets
*/
public TopLevelContentAction(boolean toGroupWorkingSets) {
super("", AS_RADIO_BUTTON); //$NON-NLS-1$
groupWorkingSets = toGroupWorkingSets;
}
/*
* @see org.eclipse.jface.action.IAction#run()
*/
public void run() {
if (stateModel
.getBooleanProperty(WorkingSetsContentProvider.SHOW_TOP_LEVEL_WORKING_SETS) != groupWorkingSets) {
stateModel.setBooleanProperty(
WorkingSetsContentProvider.SHOW_TOP_LEVEL_WORKING_SETS,
groupWorkingSets);
structuredViewer.getControl().setRedraw(false);
try {
structuredViewer.refresh();
} finally {
structuredViewer.getControl().setRedraw(true);
}
}
}
}
/**
* Create an action group that will listen to the stateModel and update the
* structuredViewer when necessary.
*
* @param aStructuredViewer
* @param aStateModel
*/
public WorkingSetRootModeActionGroup(StructuredViewer aStructuredViewer,
IExtensionStateModel aStateModel) {
super();
structuredViewer = aStructuredViewer;
stateModel = aStateModel;
}
/*
* (non-Javadoc)
*
* @see ActionGroup#fillActionBars(IActionBars)
*/
public void fillActionBars(IActionBars actionBars) {
if (hasContributedToViewMenu)
return;
IMenuManager topLevelSubMenu = new MenuManager(
WorkbenchNavigatorMessages.actions_WorkingSetRootModeActionGroup_Top_Level_Element_);
addActions(topLevelSubMenu);
actionBars.getMenuManager().insertBefore(IWorkbenchActionConstants.MB_ADDITIONS, topLevelSubMenu);
hasContributedToViewMenu = true;
}
/**
* Adds the actions to the given menu manager.
*/
protected void addActions(IMenuManager viewMenu) {
if (actions == null)
actions = createActions();
viewMenu.add(new Separator());
items = new MenuItem[actions.length];
for (int i = 0; i < actions.length; i++) {
final int j = i;
viewMenu.add(new ContributionItem() {
public void fill(Menu menu, int index) {
int style = SWT.CHECK;
if ((actions[j].getStyle() & IAction.AS_RADIO_BUTTON) != 0)
style = SWT.RADIO;
final MenuItem mi = new MenuItem(menu, style, index);
items[j] = mi;
mi.setText(actions[j].getText());
mi.setSelection(currentSelection == j);
mi.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
if (currentSelection == j) {
items[currentSelection].setSelection(true);
return;
}
actions[j].run();
// Update checked state
items[currentSelection].setSelection(false);
currentSelection = j;
items[currentSelection].setSelection(true);
}
});
}
public boolean isDynamic() {
return false;
}
});
}
}
private IAction[] createActions() {
ISharedImages sharedImages = PlatformUI.getWorkbench()
.getSharedImages();
projectsAction = new TopLevelContentAction(false);
projectsAction
.setText(WorkbenchNavigatorMessages.actions_WorkingSetRootModeActionGroup_Project_);
projectsAction.setImageDescriptor(sharedImages
.getImageDescriptor(IDE.SharedImages.IMG_OBJ_PROJECT));
workingSetsAction = new TopLevelContentAction(true);
workingSetsAction
.setText(WorkbenchNavigatorMessages.actions_WorkingSetRootModeActionGroup_Working_Set_);
workingSetsAction.setImageDescriptor(WorkbenchNavigatorPlugin
.getDefault().getImageRegistry().getDescriptor(
"full/obj16/workingsets.gif")); //$NON-NLS-1$
return new IAction[] { projectsAction, workingSetsAction };
}
/**
* Toggle whether top level working sets should be displayed as a group or
* collapse to just show their contents.
*
* @param showTopLevelWorkingSets
*/
public void setShowTopLevelWorkingSets(boolean showTopLevelWorkingSets) {
if (actions == null)
actions = createActions();
currentSelection = showTopLevelWorkingSets ? 1 : 0;
workingSetsAction.setChecked(showTopLevelWorkingSets);
projectsAction.setChecked(!showTopLevelWorkingSets);
if (items != null) {
for (int i = 0; i < items.length; i++) {
if(items[i] != null && actions[i] != null)
items[i].setSelection(actions[i].isChecked());
}
}
if (stateModel != null) {
stateModel.setBooleanProperty(
WorkingSetsContentProvider.SHOW_TOP_LEVEL_WORKING_SETS,
showTopLevelWorkingSets);
}
}
/**
* @param sStateModel
*/
public void setStateModel(IExtensionStateModel sStateModel) {
stateModel = sStateModel;
}
}
| 7,136 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
UndoRedoActionProvider.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/base_commons/net.heartsome.cat.common.ui.navigator.resources/src/org/eclipse/ui/internal/navigator/resources/actions/UndoRedoActionProvider.java | /*******************************************************************************
* Copyright (c) 2006, 2008 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
* (was originally RefactorActionProvider.java)
* Oakland Software (Francis Upton - [email protected])
* bug 214271 Undo/redo not enabled if nothing selected
******************************************************************************/
package org.eclipse.ui.internal.navigator.resources.actions;
import org.eclipse.core.commands.operations.IUndoContext;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.ui.IActionBars;
import org.eclipse.ui.actions.ActionContext;
import org.eclipse.ui.navigator.CommonActionProvider;
import org.eclipse.ui.navigator.ICommonActionExtensionSite;
import org.eclipse.ui.navigator.ICommonViewerWorkbenchSite;
import org.eclipse.ui.operations.UndoRedoActionGroup;
/**
* @since 3.4
*
*/
public class UndoRedoActionProvider extends CommonActionProvider {
private UndoRedoActionGroup undoRedoGroup;
/*
* (non-Javadoc)
*
* @see org.eclipse.ui.navigator.CommonActionProvider#init(org.eclipse.ui.navigator.ICommonActionExtensionSite)
*/
public void init(ICommonActionExtensionSite anActionSite) {
IUndoContext workspaceContext = (IUndoContext) ResourcesPlugin
.getWorkspace().getAdapter(IUndoContext.class);
undoRedoGroup = new UndoRedoActionGroup(((ICommonViewerWorkbenchSite) anActionSite.getViewSite()).getSite(),
workspaceContext, true);
}
public void dispose() {
undoRedoGroup.dispose();
}
public void fillActionBars(IActionBars actionBars) {
undoRedoGroup.fillActionBars(actionBars);
}
public void fillContextMenu(IMenuManager menu) {
undoRedoGroup.fillContextMenu(menu);
}
public void setContext(ActionContext context) {
undoRedoGroup.setContext(context);
}
public void updateActionBars() {
undoRedoGroup.updateActionBars();
}
}
| 2,269 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
NewActionProvider.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/base_commons/net.heartsome.cat.common.ui.navigator.resources/src/org/eclipse/ui/internal/navigator/resources/actions/NewActionProvider.java | /*******************************************************************************
* Copyright (c) 2005, 2008 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.ui.internal.navigator.resources.actions;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.actions.ActionFactory;
import org.eclipse.ui.internal.navigator.resources.resource.WorkbenchNavigatorMessages;
import org.eclipse.ui.navigator.CommonActionProvider;
import org.eclipse.ui.navigator.ICommonActionExtensionSite;
import org.eclipse.ui.navigator.ICommonMenuConstants;
import org.eclipse.ui.navigator.ICommonViewerWorkbenchSite;
import org.eclipse.ui.navigator.WizardActionGroup;
import org.eclipse.ui.wizards.IWizardCategory;
import org.eclipse.ui.wizards.IWizardRegistry;
/**
* Provides the new (artifact creation) menu options for a context menu.
*
* <p>
* The added submenu has the following structure
* </p>
*
* <ul>
* <li>a new generic project wizard shortcut action, </li>
* <li>a separator, </li>
* <li>a set of context senstive wizard shortcuts (as defined by
* <b>org.eclipse.ui.navigator.commonWizard</b>), </li>
* <li>another separator, </li>
* <li>a generic examples wizard shortcut action, and finally </li>
* <li>a generic "Other" new wizard shortcut action</li>
* </ul>
*
* @since 3.2
*
*/
public class NewActionProvider extends CommonActionProvider {
private static final String FULL_EXAMPLES_WIZARD_CATEGORY = "org.eclipse.ui.Examples"; //$NON-NLS-1$
private static final String NEW_MENU_NAME = "common.new.menu";//$NON-NLS-1$
private ActionFactory.IWorkbenchAction showDlgAction;
private IAction newProjectAction;
private IAction newExampleAction;
private WizardActionGroup newWizardActionGroup;
private boolean contribute = false;
public void init(ICommonActionExtensionSite anExtensionSite) {
if (anExtensionSite.getViewSite() instanceof ICommonViewerWorkbenchSite) {
IWorkbenchWindow window = ((ICommonViewerWorkbenchSite) anExtensionSite.getViewSite()).getWorkbenchWindow();
showDlgAction = ActionFactory.NEW_WIZARD_DROP_DOWN.create(window);
showDlgAction.setText(WorkbenchNavigatorMessages.actions_NewActionProvider_NewMenu_label);
contribute = true;
}
}
/**
* Adds a submenu to the given menu with the name "group.new" see
* {@link ICommonMenuConstants#GROUP_NEW}). The submenu contains the following structure:
*
* <ul>
* <li>a new generic project wizard shortcut action, </li>
* <li>a separator, </li>
* <li>a set of context senstive wizard shortcuts (as defined by
* <b>org.eclipse.ui.navigator.commonWizard</b>), </li>
* <li>another separator, </li>
* <li>a generic examples wizard shortcut action, and finally </li>
* <li>a generic "Other" new wizard shortcut action</li>
* </ul>
*/
public void fillContextMenu(IMenuManager menu) {
// append the submenu after the GROUP_NEW group.
menu.insertAfter(ICommonMenuConstants.GROUP_NEW, showDlgAction);
}
/**
* Return whether or not any examples are in the current install.
*
* @return True if there exists a full examples wizard category.
*/
private boolean hasExamples() {
IWizardRegistry newRegistry = PlatformUI.getWorkbench().getNewWizardRegistry();
IWizardCategory category = newRegistry.findCategory(FULL_EXAMPLES_WIZARD_CATEGORY);
return category != null;
}
/* (non-Javadoc)
* @see org.eclipse.ui.actions.ActionGroup#dispose()
*/
public void dispose() {
if (showDlgAction!=null) {
showDlgAction.dispose();
showDlgAction = null;
}
super.dispose();
}
}
| 4,061 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
CopyAction.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/base_commons/net.heartsome.cat.common.ui.navigator.resources/src/org/eclipse/ui/internal/navigator/resources/actions/CopyAction.java | /*******************************************************************************
* Copyright (c) 2000, 2008 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.ui.internal.navigator.resources.actions;
import java.util.Iterator;
import java.util.List;
import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.Assert;
import org.eclipse.core.runtime.IPath;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.swt.SWTError;
import org.eclipse.swt.dnd.Clipboard;
import org.eclipse.swt.dnd.DND;
import org.eclipse.swt.dnd.FileTransfer;
import org.eclipse.swt.dnd.TextTransfer;
import org.eclipse.swt.dnd.Transfer;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.actions.SelectionListenerAction;
import org.eclipse.ui.internal.navigator.resources.resource.WorkbenchNavigatorMessages;
import org.eclipse.ui.part.ResourceTransfer;
/**
* Standard action for copying the currently selected resources to the clipboard.
* <p>
* This class may be instantiated; it is not intended to be subclassed.
* </p>
*
* @since 2.0
*/
/*package*/class CopyAction extends SelectionListenerAction {
/**
* The id of this action.
*/
public static final String ID = PlatformUI.PLUGIN_ID + ".CopyAction"; //$NON-NLS-1$
/**
* The shell in which to show any dialogs.
*/
private Shell shell;
/**
* System clipboard
*/
private Clipboard clipboard;
/**
* Associated paste action. May be <code>null</code>
*/
private PasteAction pasteAction;
/**
* Creates a new action.
*
* @param shell the shell for any dialogs
* @param clipboard a platform clipboard
*/
public CopyAction(Shell shell, Clipboard clipboard) {
super(WorkbenchNavigatorMessages.actions_CopyAction_Cop_);
Assert.isNotNull(shell);
Assert.isNotNull(clipboard);
this.shell = shell;
this.clipboard = clipboard;
setToolTipText(WorkbenchNavigatorMessages.actions_CopyAction_Copy_selected_resource_s_);
setId(CopyAction.ID);
PlatformUI.getWorkbench().getHelpSystem().setHelp(this, "CopyHelpId"); //$NON-NLS-1$
// TODO INavigatorHelpContextIds.COPY_ACTION);
}
/**
* Creates a new action.
*
* @param shell the shell for any dialogs
* @param clipboard a platform clipboard
* @param pasteAction a paste action
*
* @since 2.0
*/
public CopyAction(Shell shell, Clipboard clipboard, PasteAction pasteAction) {
this(shell, clipboard);
this.pasteAction = pasteAction;
}
/**
* The <code>CopyAction</code> implementation of this method defined
* on <code>IAction</code> copies the selected resources to the
* clipboard.
*/
public void run() {
List selectedResources = getSelectedResources();
IResource[] resources = (IResource[]) selectedResources
.toArray(new IResource[selectedResources.size()]);
// Get the file names and a string representation
final int length = resources.length;
int actualLength = 0;
String[] fileNames = new String[length];
StringBuffer buf = new StringBuffer();
for (int i = 0; i < length; i++) {
IPath location = resources[i].getLocation();
// location may be null. See bug 29491.
if (location != null) {
fileNames[actualLength++] = location.toOSString();
}
if (i > 0) {
buf.append("\n"); //$NON-NLS-1$
}
buf.append(resources[i].getName());
}
// was one or more of the locations null?
if (actualLength < length) {
String[] tempFileNames = fileNames;
fileNames = new String[actualLength];
for (int i = 0; i < actualLength; i++) {
fileNames[i] = tempFileNames[i];
}
}
setClipboard(resources, fileNames, buf.toString());
// update the enablement of the paste action
// workaround since the clipboard does not suppot callbacks
if (pasteAction != null && pasteAction.getStructuredSelection() != null) {
pasteAction.selectionChanged(pasteAction.getStructuredSelection());
}
}
/**
* Set the clipboard contents. Prompt to retry if clipboard is busy.
*
* @param resources the resources to copy to the clipboard
* @param fileNames file names of the resources to copy to the clipboard
* @param names string representation of all names
*/
private void setClipboard(IResource[] resources, String[] fileNames,
String names) {
try {
// set the clipboard contents
if (fileNames.length > 0) {
clipboard.setContents(new Object[] { resources, fileNames,
names },
new Transfer[] { ResourceTransfer.getInstance(),
FileTransfer.getInstance(),
TextTransfer.getInstance() });
} else {
clipboard.setContents(new Object[] { resources, names },
new Transfer[] { ResourceTransfer.getInstance(),
TextTransfer.getInstance() });
}
} catch (SWTError e) {
if (e.code != DND.ERROR_CANNOT_SET_CLIPBOARD) {
throw e;
}
if (MessageDialog
.openQuestion(
shell,
WorkbenchNavigatorMessages.actions_CopyAction_msgTitle, // TODO ResourceNavigatorMessages.CopyToClipboardProblemDialog_title, //$NON-NLS-1$
WorkbenchNavigatorMessages.actions_CopyAction_msg)) { //$NON-NLS-1$
setClipboard(resources, fileNames, names);
}
}
}
/**
* The <code>CopyAction</code> implementation of this
* <code>SelectionListenerAction</code> method enables this action if
* one or more resources of compatible types are selected.
*/
protected boolean updateSelection(IStructuredSelection selection) {
if (!super.updateSelection(selection)) {
return false;
}
if (getSelectedNonResources().size() > 0) {
return false;
}
List selectedResources = getSelectedResources();
if (selectedResources.size() == 0) {
return false;
}
boolean projSelected = selectionIsOfType(IResource.PROJECT);
boolean fileFoldersSelected = selectionIsOfType(IResource.FILE
| IResource.FOLDER);
if (!projSelected && !fileFoldersSelected) {
return false;
}
// selection must be homogeneous
if (projSelected && fileFoldersSelected) {
return false;
}
// must have a common parent
IContainer firstParent = ((IResource) selectedResources.get(0))
.getParent();
if (firstParent == null) {
return false;
}
Iterator resourcesEnum = selectedResources.iterator();
while (resourcesEnum.hasNext()) {
IResource currentResource = (IResource) resourcesEnum.next();
if (!currentResource.getParent().equals(firstParent)) {
return false;
}
// resource location must exist
if (currentResource.getLocationURI() == null) {
return false;
}
}
return true;
}
}
| 7,894 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
RefactorActionGroup.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/base_commons/net.heartsome.cat.common.ui.navigator.resources/src/org/eclipse/ui/internal/navigator/resources/actions/RefactorActionGroup.java | /*******************************************************************************
* Copyright (c) 2000, 2010 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
* Sebastian Davids <[email protected]> - Images for menu items (27481)
*******************************************************************************/
package org.eclipse.ui.internal.navigator.resources.actions;
import org.eclipse.core.resources.IResource;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.window.IShellProvider;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.ui.IActionBars;
import org.eclipse.ui.IWorkbenchCommandConstants;
import org.eclipse.ui.actions.ActionFactory;
import org.eclipse.ui.actions.ActionGroup;
import org.eclipse.ui.actions.MoveResourceAction;
import org.eclipse.ui.actions.RenameResourceAction;
import org.eclipse.ui.ide.ResourceSelectionUtil;
import org.eclipse.ui.internal.navigator.resources.resource.WorkbenchNavigatorMessages;
/**
* This is the action group for refactor actions, including global action
* handlers for copy, paste and delete.
*
* @since 2.0
*/
public class RefactorActionGroup extends ActionGroup {
private RenameResourceAndCloseEditorAction renameAction;
private MoveResourceAction moveAction;
private Shell shell;
private Tree tree;
/**
*
* @param aShell
* @param aTree
*/
public RefactorActionGroup(Shell aShell, Tree aTree) {
shell = aShell;
tree = aTree;
makeActions();
}
public void fillContextMenu(IMenuManager menu) {
IStructuredSelection selection = (IStructuredSelection) getContext().getSelection();
boolean anyResourceSelected = !selection.isEmpty()
&& ResourceSelectionUtil.allResourcesAreOfType(selection, IResource.PROJECT | IResource.FOLDER | IResource.FILE);
if (anyResourceSelected) {
moveAction.selectionChanged(selection);
// menu.appendToGroup(ICommonMenuConstants.GROUP_REORGANIZE, moveAction);
renameAction.selectionChanged(selection);
// menu.insertAfter(moveAction.getId(), renameAction);
}
}
public void fillActionBars(IActionBars actionBars) {
// renameAction.setTextActionHandler(textActionHandler);
updateActionBars();
actionBars.setGlobalActionHandler(ActionFactory.MOVE.getId(), moveAction);
actionBars.setGlobalActionHandler(ActionFactory.RENAME.getId(), renameAction);
}
/**
* Handles a key pressed event by invoking the appropriate action.
*
* @param event
* The Key Event
*/
public void handleKeyPressed(KeyEvent event) {
if (event.keyCode == SWT.F2 && event.stateMask == 0) {
if (renameAction.isEnabled()) {
renameAction.run();
}
// Swallow the event.
event.doit = false;
}
}
protected void makeActions() {
IShellProvider sp = new IShellProvider() {
public Shell getShell() {
return shell;
}
};
moveAction = new MoveResourceAction(sp);
moveAction.setText(WorkbenchNavigatorMessages.actions_RefactorActionGroup_moveAction);
moveAction.setActionDefinitionId(IWorkbenchCommandConstants.FILE_MOVE);
renameAction = new RenameResourceAndCloseEditorAction(sp, tree);
renameAction.setText(WorkbenchNavigatorMessages.actions_RefactorActionGroup_renameAction);
renameAction.setActionDefinitionId(IWorkbenchCommandConstants.FILE_RENAME);
}
public void updateActionBars() {
IStructuredSelection selection = (IStructuredSelection) getContext().getSelection();
moveAction.selectionChanged(selection);
renameAction.selectionChanged(selection);
}
}
| 3,948 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
DeleteResourceAndCloseEditorAction.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/base_commons/net.heartsome.cat.common.ui.navigator.resources/src/org/eclipse/ui/internal/navigator/resources/actions/DeleteResourceAndCloseEditorAction.java | /*******************************************************************************
* Copyright (c) 2000, 2011 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
* Benjamin Muskalla <[email protected]>
* - Fix for bug 172574 - [IDE] DeleteProjectDialog inconsequent selection behavior
*******************************************************************************/
package org.eclipse.ui.internal.navigator.resources.actions;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import net.heartsome.cat.common.util.CommonFunction;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.Assert;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.window.IShellProvider;
import org.eclipse.jface.window.Window;
import org.eclipse.osgi.util.NLS;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
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.ui.IEditorInput;
import org.eclipse.ui.IEditorReference;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.actions.SelectionListenerAction;
import org.eclipse.ui.ide.undo.DeleteResourcesOperation;
import org.eclipse.ui.ide.undo.WorkspaceUndoUtil;
import org.eclipse.ui.internal.ide.IDEWorkbenchMessages;
import org.eclipse.ui.internal.ide.IDEWorkbenchPlugin;
import org.eclipse.ui.internal.ide.IIDEHelpContextIds;
import org.eclipse.ui.internal.ide.actions.LTKLauncher;
import org.eclipse.ui.part.FileEditorInput;
import org.eclipse.ui.progress.WorkbenchJob;
import com.ximpleware.AutoPilot;
import com.ximpleware.VTDGen;
import com.ximpleware.VTDNav;
/**
* Standard action for deleting the currently selected resources.
* <p>
* This class may be instantiated; it is not intended to be subclassed.
* </p>
* @noextend This class is not intended to be subclassed by clients.
*/
public class DeleteResourceAndCloseEditorAction extends SelectionListenerAction {
/**
* 修改BUG,默认删除项目的内容
* @author robert
*/
static class DeleteProjectDialog extends MessageDialog {
private IResource[] projects;
private boolean deleteContent = false;
/**
* Control testing mode. In testing mode, it returns true to delete contents and does not pop up the dialog.
*/
private boolean fIsTesting = false;
// private Button radio1;
//
// private Button radio2;
DeleteProjectDialog(Shell parentShell, IResource[] projects) {
super(parentShell, getTitle(projects), null, // accept the
// default window
// icon
getMessage(projects), MessageDialog.QUESTION, new String[] { IDialogConstants.YES_LABEL,
IDialogConstants.NO_LABEL }, 0); // yes is the
// default
this.projects = projects;
setShellStyle(getShellStyle() | SWT.SHEET);
}
static String getTitle(IResource[] projects) {
if (projects.length == 1) {
return IDEWorkbenchMessages.DeleteResourceAction_titleProject1;
}
return IDEWorkbenchMessages.DeleteResourceAction_titleProjectN;
}
static String getMessage(IResource[] projects) {
if (projects.length == 1) {
IProject project = (IProject) projects[0];
return NLS.bind(IDEWorkbenchMessages.DeleteResourceAction_confirmProject1, project.getName());
}
return NLS.bind(IDEWorkbenchMessages.DeleteResourceAction_confirmProjectN, new Integer(projects.length));
}
/*
* (non-Javadoc) Method declared on Window.
*/
protected void configureShell(Shell newShell) {
super.configureShell(newShell);
PlatformUI.getWorkbench().getHelpSystem().setHelp(newShell, IIDEHelpContextIds.DELETE_PROJECT_DIALOG);
}
/*
*
protected Control createCustomArea(Composite parent) {
Composite composite = new Composite(parent, SWT.NONE);
composite.setLayout(new GridLayout());
radio1 = new Button(composite, SWT.RADIO);
radio1.addSelectionListener(selectionListener);
String text1;
if (projects.length == 1) {
IProject project = (IProject) projects[0];
if (project == null || project.getLocation() == null) {
text1 = IDEWorkbenchMessages.DeleteResourceAction_deleteContentsN;
} else {
text1 = NLS.bind(IDEWorkbenchMessages.DeleteResourceAction_deleteContents1, project.getLocation()
.toOSString());
}
} else {
text1 = IDEWorkbenchMessages.DeleteResourceAction_deleteContentsN;
}
radio1.setText(text1);
radio1.setFont(parent.getFont());
// Add explanatory label that the action cannot be undone.
// We can't put multi-line formatted text in a radio button,
// so we have to create a separate label.
Label detailsLabel = new Label(composite, SWT.LEFT);
detailsLabel.setText(IDEWorkbenchMessages.DeleteResourceAction_deleteContentsDetails);
detailsLabel.setFont(parent.getFont());
// indent the explanatory label
GridData data = new GridData();
data.horizontalIndent = IDialogConstants.INDENT;
detailsLabel.setLayoutData(data);
// add a listener so that clicking on the label selects the
// corresponding radio button.
// see https://bugs.eclipse.org/bugs/show_bug.cgi?id=172574
detailsLabel.addMouseListener(new MouseAdapter() {
public void mouseUp(MouseEvent e) {
deleteContent = true;
radio1.setSelection(deleteContent);
radio2.setSelection(!deleteContent);
}
});
// Add a spacer label
new Label(composite, SWT.LEFT);
radio2 = new Button(composite, SWT.RADIO);
radio2.addSelectionListener(selectionListener);
String text2 = IDEWorkbenchMessages.DeleteResourceAction_doNotDeleteContents;
radio2.setText(text2);
radio2.setFont(parent.getFont());
// set initial state
radio1.setSelection(deleteContent);
radio2.setSelection(!deleteContent);
return composite;
}
*/
protected Control createCustomArea(Composite parent) {
Composite composite = new Composite(parent, SWT.NONE);
composite.setLayout(new GridLayout());
String text1;
if (projects.length == 1) {
IProject project = (IProject) projects[0];
if (project == null || project.getLocation() == null) {
text1 = IDEWorkbenchMessages.DeleteResourceAction_deleteContentsN;
} else {
text1 = NLS.bind(IDEWorkbenchMessages.DeleteResourceAction_deleteContents1, project.getLocation()
.toOSString());
}
} else {
text1 = IDEWorkbenchMessages.DeleteResourceAction_deleteContentsN;
}
Label tipLbl = new Label(composite, SWT.NONE);
tipLbl.setFont(parent.getFont());
tipLbl.setText(text1);
deleteContent = true;
Label detailsLabel = new Label(composite, SWT.LEFT);
detailsLabel.setText(IDEWorkbenchMessages.DeleteResourceAction_deleteContentsDetails);
detailsLabel.setFont(parent.getFont());
// indent the explanatory label
GridData data = new GridData();
data.horizontalIndent = IDialogConstants.INDENT;
detailsLabel.setLayoutData(data);
// add a listener so that clicking on the label selects the
// corresponding radio button.
// see https://bugs.eclipse.org/bugs/show_bug.cgi?id=172574
// Add a spacer label
new Label(composite, SWT.LEFT);
return composite;
}
/*
private SelectionListener selectionListener = new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
Button button = (Button) e.widget;
if (button.getSelection()) {
deleteContent = (button == radio1);
}
}
};
*/
boolean getDeleteContent() {
return deleteContent;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.jface.window.Window#open()
*/
public int open() {
// Override Window#open() to allow for non-interactive testing.
if (fIsTesting) {
deleteContent = true;
return Window.OK;
}
return super.open();
}
/**
* Set this delete dialog into testing mode. It won't pop up, and it returns true for deleteContent.
* @param t
* the testing mode
*/
void setTestingMode(boolean t) {
fIsTesting = t;
}
}
/**
* The id of this action.
*/
public static final String ID = PlatformUI.PLUGIN_ID + ".DeleteResourceAction";//$NON-NLS-1$
private IShellProvider shellProvider = null;
/**
* Whether or not we are deleting content for projects.
*/
private boolean deleteContent = false;
/**
* Flag that allows testing mode ... it won't pop up the project delete dialog, and will return
* "delete all content".
*/
protected boolean fTestingMode = false;
private String[] modelProviderIds;
/**
* Creates a new delete resource action.
* @param shell
* the shell for any dialogs
* @deprecated Should take an IShellProvider, see {@link #DeleteResourceAction(IShellProvider)}
*/
public DeleteResourceAndCloseEditorAction(final Shell shell) {
super(IDEWorkbenchMessages.DeleteResourceAction_text);
Assert.isNotNull(shell);
initAction();
setShellProvider(new IShellProvider() {
public Shell getShell() {
return shell;
}
});
}
/**
* Creates a new delete resource action.
* @param provider
* the shell provider to use. Must not be <code>null</code>.
* @since 3.4
*/
public DeleteResourceAndCloseEditorAction(IShellProvider provider) {
super(IDEWorkbenchMessages.DeleteResourceAction_text);
Assert.isNotNull(provider);
initAction();
setShellProvider(provider);
}
/**
* Action initialization.
*/
private void initAction() {
setToolTipText(IDEWorkbenchMessages.DeleteResourceAction_toolTip);
PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IIDEHelpContextIds.DELETE_RESOURCE_ACTION);
setId(ID);
}
private void setShellProvider(IShellProvider provider) {
shellProvider = provider;
}
/**
* Returns whether delete can be performed on the current selection.
* @param resources
* the selected resources
* @return <code>true</code> if the resources can be deleted, and <code>false</code> if the selection contains
* non-resources or phantom resources
*/
private boolean canDelete(IResource[] resources) {
// allow only projects or only non-projects to be selected;
// note that the selection may contain multiple types of resource
if (!(containsOnlyProjects(resources) || containsOnlyNonProjects(resources))) {
return false;
}
if (resources.length == 0) {
return false;
}
// Return true if everything in the selection exists.
for (int i = 0; i < resources.length; i++) {
IResource resource = resources[i];
if (resource.isPhantom()) {
return false;
}
}
return true;
}
/**
* Returns whether the selection contains linked resources.
* @param resources
* the selected resources
* @return <code>true</code> if the resources contain linked resources, and <code>false</code> otherwise
*/
private boolean containsLinkedResource(IResource[] resources) {
for (int i = 0; i < resources.length; i++) {
IResource resource = resources[i];
if (resource.isLinked()) {
return true;
}
}
return false;
}
/**
* Returns whether the selection contains only non-projects.
* @param resources
* the selected resources
* @return <code>true</code> if the resources contains only non-projects, and <code>false</code> otherwise
*/
private boolean containsOnlyNonProjects(IResource[] resources) {
int types = getSelectedResourceTypes(resources);
// check for empty selection
if (types == 0) {
return false;
}
// note that the selection may contain multiple types of resource
return (types & IResource.PROJECT) == 0;
}
/**
* Returns whether the selection contains only projects.
* @param resources
* the selected resources
* @return <code>true</code> if the resources contains only projects, and <code>false</code> otherwise
*/
private boolean containsOnlyProjects(IResource[] resources) {
int types = getSelectedResourceTypes(resources);
// note that the selection may contain multiple types of resource
return types == IResource.PROJECT;
}
/**
* Asks the user to confirm a delete operation.
* @param resources
* the selected resources
* @return <code>true</code> if the user says to go ahead, and <code>false</code> if the deletion should be
* abandoned
*/
private boolean confirmDelete(IResource[] resources) {
if (containsOnlyProjects(resources)) {
return confirmDeleteProjects(resources);
}
return confirmDeleteNonProjects(resources);
}
/**
* Asks the user to confirm a delete operation, where the selection contains no projects.
* @param resources
* the selected resources
* @return <code>true</code> if the user says to go ahead, and <code>false</code> if the deletion should be
* abandoned
*/
private boolean confirmDeleteNonProjects(IResource[] resources) {
String title;
String msg;
if (resources.length == 1) {
title = IDEWorkbenchMessages.DeleteResourceAction_title1;
IResource resource = resources[0];
if (resource.isLinked()) {
msg = NLS.bind(IDEWorkbenchMessages.DeleteResourceAction_confirmLinkedResource1, resource.getName());
} else {
msg = NLS.bind(IDEWorkbenchMessages.DeleteResourceAction_confirm1, resource.getName());
}
} else {
title = IDEWorkbenchMessages.DeleteResourceAction_titleN;
if (containsLinkedResource(resources)) {
msg = NLS.bind(IDEWorkbenchMessages.DeleteResourceAction_confirmLinkedResourceN, new Integer(
resources.length));
} else {
msg = NLS.bind(IDEWorkbenchMessages.DeleteResourceAction_confirmN, new Integer(resources.length));
}
}
return MessageDialog.openQuestion(shellProvider.getShell(), title, msg);
}
/**
* Asks the user to confirm a delete operation, where the selection contains only projects. Also remembers whether
* project content should be deleted.
* @param resources
* the selected resources
* @return <code>true</code> if the user says to go ahead, and <code>false</code> if the deletion should be
* abandoned
*/
private boolean confirmDeleteProjects(IResource[] resources) {
DeleteProjectDialog dialog = new DeleteProjectDialog(shellProvider.getShell(), resources);
dialog.setTestingMode(fTestingMode);
int code = dialog.open();
deleteContent = dialog.getDeleteContent();
return code == 0; // YES
}
/**
* Return an array of the currently selected resources.
* @return the selected resources
*/
private IResource[] getSelectedResourcesArray() {
List selection = getSelectedResources();
IResource[] resources = new IResource[selection.size()];
selection.toArray(resources);
return resources;
}
/**
* Returns a bit-mask containing the types of resources in the selection.
* @param resources
* the selected resources
*/
private int getSelectedResourceTypes(IResource[] resources) {
int types = 0;
for (int i = 0; i < resources.length; i++) {
types |= resources[i].getType();
}
return types;
}
/*
* (non-Javadoc) Method declared on IAction.
*/
public void run() {
final IResource[] resources = getSelectedResourcesArray();
if (!fTestingMode) {
if (LTKLauncher.openDeleteWizard(getStructuredSelection())) {
return;
}
}
// WARNING: do not query the selected resources more than once
// since the selection may change during the run,
// e.g. due to window activation when the prompt dialog is dismissed.
// For more details, see Bug 60606 [Navigator] (data loss) Navigator
// deletes/moves the wrong file
if (!confirmDelete(resources)) {
return;
}
Job deletionCheckJob = new Job(IDEWorkbenchMessages.DeleteResourceAction_checkJobName) {
/*
* (non-Javadoc)
*
* @see org.eclipse.core.runtime.jobs.Job#run(org.eclipse.core.runtime.IProgressMonitor)
*/
protected IStatus run(IProgressMonitor monitor) {
if (resources.length == 0)
return Status.CANCEL_STATUS;
closeRelatedEditors();
scheduleDeleteJob(resources);
return Status.OK_STATUS;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.core.runtime.jobs.Job#belongsTo(java.lang.Object)
*/
public boolean belongsTo(Object family) {
if (IDEWorkbenchMessages.DeleteResourceAction_jobName.equals(family)) {
return true;
}
return super.belongsTo(family);
}
};
deletionCheckJob.schedule();
}
/**
* Schedule a job to delete the resources to delete.
* @param resourcesToDelete
*/
private void scheduleDeleteJob(final IResource[] resourcesToDelete) {
// use a non-workspace job with a runnable inside so we can avoid
// periodic updates
Job deleteJob = new Job(IDEWorkbenchMessages.DeleteResourceAction_jobName) {
public IStatus run(final IProgressMonitor monitor) {
try {
final DeleteResourcesOperation op = new DeleteResourcesOperation(resourcesToDelete,
IDEWorkbenchMessages.DeleteResourceAction_operationLabel, deleteContent);
op.setModelProviderIds(getModelProviderIds());
// If we are deleting projects and their content, do not
// execute the operation in the undo history, since it cannot be
// properly restored. Just execute it directly so it won't be
// added to the undo history.
if (deleteContent && containsOnlyProjects(resourcesToDelete)) {
// We must compute the execution status first so that any user prompting
// or validation checking occurs. Do it in a syncExec because
// we are calling this from a Job.
WorkbenchJob statusJob = new WorkbenchJob("Status checking") { //$NON-NLS-1$
/*
* (non-Javadoc)
*
* @see
* org.eclipse.ui.progress.UIJob#runInUIThread(org.eclipse.core.runtime.IProgressMonitor)
*/
public IStatus runInUIThread(IProgressMonitor monitor) {
return op.computeExecutionStatus(monitor);
}
};
statusJob.setSystem(true);
statusJob.schedule();
try {// block until the status is ready
statusJob.join();
} catch (InterruptedException e) {
// Do nothing as status will be a cancel
}
if (statusJob.getResult().isOK()) {
return op.execute(monitor, WorkspaceUndoUtil.getUIInfoAdapter(shellProvider.getShell()));
}
return statusJob.getResult();
}
return PlatformUI.getWorkbench().getOperationSupport().getOperationHistory()
.execute(op, monitor, WorkspaceUndoUtil.getUIInfoAdapter(shellProvider.getShell()));
} catch (ExecutionException e) {
if (e.getCause() instanceof CoreException) {
return ((CoreException) e.getCause()).getStatus();
}
return new Status(IStatus.ERROR, IDEWorkbenchPlugin.IDE_WORKBENCH, e.getMessage(), e);
}
}
/*
* (non-Javadoc)
*
* @see org.eclipse.core.runtime.jobs.Job#belongsTo(java.lang.Object)
*/
public boolean belongsTo(Object family) {
if (IDEWorkbenchMessages.DeleteResourceAction_jobName.equals(family)) {
return true;
}
return super.belongsTo(family);
}
};
deleteJob.setUser(true);
deleteJob.schedule();
}
/**
* 删除文件时,如果文件在编辑器中已打开,则关闭此文件。 ;
*/
private void closeRelatedEditors() {
IWorkbenchPage page = null;
for (IWorkbenchWindow window : PlatformUI.getWorkbench().getWorkbenchWindows()) {
if (window != null) {
page = window.getActivePage();
break;
}
}
if (page == null) {
return;
}
IEditorReference[] editorReferences = page.getEditorReferences();
final List<IResource> selectionResource = getSelectedResources();
final List<IEditorReference> lstCloseEditor = new ArrayList<IEditorReference>();
final VTDGen vg = new VTDGen();
final AutoPilot ap = new AutoPilot();
final List<IEditorInput> inputList = new ArrayList<IEditorInput>();
for (final IEditorReference reference : editorReferences) {
Display.getDefault().asyncExec(new Runnable() {
public void run() {
IFile file = ((FileEditorInput) reference.getEditor(true).getEditorInput()).getFile();
if ("xlp".equals(file.getFileExtension())) {
if (vg.parseFile(file.getLocation().toOSString(), true)) {
VTDNav vn = vg.getNav();
ap.bind(vn);
try {
ap.selectXPath("/mergerFiles/mergerFile/@filePath");
int index = -1;
merge: while ((index = ap.evalXPath()) != -1) {
String fileLC = vn.toString(index + 1);
if (fileLC != null && !"".equals(fileLC)) {
for (IResource resource : selectionResource) {
if (resource instanceof IProject || resource instanceof IFolder) {
if (fileLC.startsWith(resource.getLocation().toOSString()
+ File.separator)) {
lstCloseEditor.add(reference);
inputList.add(reference.getEditorInput());
break merge;
}
} else if (resource instanceof IFile) {
if (resource.getLocation().toOSString().equals(fileLC)) {
lstCloseEditor.add(reference);
inputList.add(reference.getEditorInput());
break merge;
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
} else {
try {
for (IResource resource : selectionResource) {
if (resource instanceof IProject) {
if (resource.getLocation().toOSString()
.equals(file.getProject().getLocation().toOSString())) {
lstCloseEditor.add(reference);
inputList.add(reference.getEditorInput());
break;
}
} else if (resource instanceof IFolder) {
if (file.getLocation().toOSString()
.startsWith(resource.getLocation().toOSString() + File.separator)) {
lstCloseEditor.add(reference);
inputList.add(reference.getEditorInput());
break;
}
} else if (resource instanceof IFile) {
if (resource.getLocation().toOSString().equals(file.getLocation().toOSString())) {
lstCloseEditor.add(reference);
inputList.add(reference.getEditorInput());
break;
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
});
}
final IWorkbenchPage page2 = page;
Display.getDefault().asyncExec(new Runnable() {
public void run() {
IEditorReference[] arrEditorReference = new IEditorReference[lstCloseEditor.size()];
page2.closeEditors(lstCloseEditor.toArray(arrEditorReference), false);
// 删除文件时,刷新访问记录 robert 2012-11-20
for (IEditorInput input : inputList) {
System.out.println("input = " + input);
CommonFunction.refreshHistoryWhenDelete(input);
}
}
});
}
/**
* The <code>DeleteResourceAction</code> implementation of this <code>SelectionListenerAction</code> method disables
* the action if the selection contains phantom resources or non-resources
*/
protected boolean updateSelection(IStructuredSelection selection) {
return super.updateSelection(selection) && canDelete(getSelectedResourcesArray());
}
/**
* Returns the model provider ids that are known to the client that instantiated this operation.
* @return the model provider ids that are known to the client that instantiated this operation.
* @since 3.2
*/
public String[] getModelProviderIds() {
return modelProviderIds;
}
/**
* Sets the model provider ids that are known to the client that instantiated this operation. Any potential side
* effects reported by these models during validation will be ignored.
* @param modelProviderIds
* the model providers known to the client who is using this operation.
* @since 3.2
*/
public void setModelProviderIds(String[] modelProviderIds) {
this.modelProviderIds = modelProviderIds;
}
}
| 25,041 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
WorkbenchLabelProvider.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/base_commons/net.heartsome.cat.common.ui.navigator.resources/src/org/eclipse/ui/internal/navigator/resources/workbench/WorkbenchLabelProvider.java | /*******************************************************************************
* Copyright (c) 2000, 2011 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
* Fair Isaac Corporation <[email protected]> - http://bugs.eclipse.org/326695
*******************************************************************************/
package org.eclipse.ui.internal.navigator.resources.workbench;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.jface.resource.ColorDescriptor;
import org.eclipse.jface.resource.FontDescriptor;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.resource.JFaceResources;
import org.eclipse.jface.resource.LocalResourceManager;
import org.eclipse.jface.resource.ResourceManager;
import org.eclipse.jface.viewers.DecoratingLabelProvider;
import org.eclipse.jface.viewers.DelegatingStyledCellLabelProvider.IStyledLabelProvider;
import org.eclipse.jface.viewers.IColorProvider;
import org.eclipse.jface.viewers.IFontProvider;
import org.eclipse.jface.viewers.ILabelProvider;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.viewers.LabelProviderChangedEvent;
import org.eclipse.jface.viewers.StyledCellLabelProvider;
import org.eclipse.jface.viewers.StyledString;
import org.eclipse.jface.viewers.StyledString.Styler;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.graphics.FontData;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.RGB;
import org.eclipse.ui.IEditorRegistry;
import org.eclipse.ui.IPropertyListener;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.internal.util.Util;
import org.eclipse.ui.model.IWorkbenchAdapter;
import org.eclipse.ui.model.IWorkbenchAdapter2;
import org.eclipse.ui.model.IWorkbenchAdapter3;
import org.eclipse.ui.plugin.AbstractUIPlugin;
/**
* Provides basic labels for adaptable objects that have the <code>IWorkbenchAdapter</code> adapter associated with
* them. All dispensed images are cached until the label provider is explicitly disposed. This class provides a facility
* for subclasses to define annotations on the labels and icons of adaptable objects.
*/
public class WorkbenchLabelProvider extends LabelProvider implements IColorProvider, IFontProvider,
IStyledLabelProvider {
/**
* Returns a workbench label provider that is hooked up to the decorator mechanism.
* @return a new <code>DecoratingLabelProvider</code> which wraps a <code>
* new <code>WorkbenchLabelProvider</code>
*/
public static ILabelProvider getDecoratingWorkbenchLabelProvider() {
return new DecoratingLabelProvider(new WorkbenchLabelProvider(), PlatformUI.getWorkbench()
.getDecoratorManager().getLabelDecorator());
}
/**
* Listener that tracks changes to the editor registry and does a full update when it changes, since many workbench
* adapters derive their icon from the file associations in the registry.
*/
private IPropertyListener editorRegistryListener = new IPropertyListener() {
public void propertyChanged(Object source, int propId) {
if (propId == IEditorRegistry.PROP_CONTENTS) {
fireLabelProviderChanged(new LabelProviderChangedEvent(WorkbenchLabelProvider.this));
}
}
};
private ResourceManager resourceManager;
/**
* Creates a new workbench label provider.
*/
public WorkbenchLabelProvider() {
PlatformUI.getWorkbench().getEditorRegistry().addPropertyListener(editorRegistryListener);
}
/**
* Returns an image descriptor that is based on the given descriptor, but decorated with additional information
* relating to the state of the provided object. Subclasses may reimplement this method to decorate an object's
* image.
* @param input
* The base image to decorate.
* @param element
* The element used to look up decorations.
* @return the resuling ImageDescriptor.
* @see org.eclipse.jface.resource.CompositeImageDescriptor
*/
protected ImageDescriptor decorateImage(ImageDescriptor input, Object element) {
return input;
}
/**
* Returns a label that is based on the given label, but decorated with additional information relating to the state
* of the provided object. Subclasses may implement this method to decorate an object's label.
* @param input
* The base text to decorate.
* @param element
* The element used to look up decorations.
* @return the resulting text
*/
protected String decorateText(String input, Object element) {
if (element instanceof IFolder) {
IFolder iFolder = (IFolder) element;
input = input + getDecorateFileCount(iFolder);
}
return input;
}
/*
* (non-Javadoc) Method declared on ILabelProvider
*/
public void dispose() {
PlatformUI.getWorkbench().getEditorRegistry().removePropertyListener(editorRegistryListener);
if (resourceManager != null)
resourceManager.dispose();
resourceManager = null;
super.dispose();
}
/**
* Returns the implementation of IWorkbenchAdapter for the given object.
* @param o
* the object to look up.
* @return IWorkbenchAdapter or<code>null</code> if the adapter is not defined or the object is not adaptable.
*/
protected final IWorkbenchAdapter getAdapter(Object o) {
return (IWorkbenchAdapter) Util.getAdapter(o, IWorkbenchAdapter.class);
}
/**
* Returns the implementation of IWorkbenchAdapter2 for the given object.
* @param o
* the object to look up.
* @return IWorkbenchAdapter2 or<code>null</code> if the adapter is not defined or the object is not adaptable.
*/
protected final IWorkbenchAdapter2 getAdapter2(Object o) {
return (IWorkbenchAdapter2) Util.getAdapter(o, IWorkbenchAdapter2.class);
}
/**
* Returns the implementation of IWorkbenchAdapter3 for the given object.
* @param o
* the object to look up.
* @return IWorkbenchAdapter3 or<code>null</code> if the adapter is not defined or the object is not adaptable.
* @since 3.7
*/
protected final IWorkbenchAdapter3 getAdapter3(Object o) {
return (IWorkbenchAdapter3) Util.getAdapter(o, IWorkbenchAdapter3.class);
}
/**
* Lazy load the resource manager
* @return The resource manager, create one if necessary
*/
private ResourceManager getResourceManager() {
if (resourceManager == null) {
resourceManager = new LocalResourceManager(JFaceResources.getResources());
}
return resourceManager;
}
/*
* (non-Javadoc) Method declared on ILabelProvider
*/
public final Image getImage(Object element) {
// obtain the base image by querying the element
ImageDescriptor descriptor = null;
if (element instanceof IProject) {
IProject project = (IProject) element;
if (project.isOpen()) {
descriptor = AbstractUIPlugin.imageDescriptorFromPlugin(
"net.heartsome.cat.common.ui.navigator.resources", "icons/full/obj16/prj_open.png");
} else {
descriptor = AbstractUIPlugin.imageDescriptorFromPlugin(
"net.heartsome.cat.common.ui.navigator.resources", "icons/full/obj16/prj_close.png");
}
} else if (element instanceof IFolder) {
descriptor = AbstractUIPlugin.imageDescriptorFromPlugin("net.heartsome.cat.common.ui.navigator.resources",
"icons/full/obj16/folder.png");
}
else {
IWorkbenchAdapter adapter = getAdapter(element);
if (adapter == null) {
return null;
}
descriptor = adapter.getImageDescriptor(element);
if (descriptor == null) {
return null;
}
// add any annotations to the image descriptor
descriptor = decorateImage(descriptor, element);
}
return (Image) getResourceManager().get(descriptor);
}
/**
* The default implementation of this returns the styled text label for the given element.
* @param element
* the element to evaluate the styled string for
* @return the styled string.
* @since 3.7
*/
public StyledString getStyledText(Object element) {
IWorkbenchAdapter3 adapter = getAdapter3(element);
if (adapter == null) {
// If adapter class doesn't implement IWorkbenchAdapter3 than use
// StyledString with text of element. Since the output of getText is
// already decorated, so we don't need to call decorateText again
// here.
return new StyledString(getText(element));
}
StyledString styledString = adapter.getStyledText(element);
// Now, re-use any existing decorateText implementation, to decorate
// this styledString.
String decorated = decorateText(styledString.getString(), element);
Styler styler = getDecorationStyle(element);
return StyledCellLabelProvider.styleDecoratedString(decorated, styler, styledString);
}
/**
* Sets the {@link org.eclipse.jface.viewers.StyledString.Styler} to be used for string decorations. By default the
* {@link StyledString#DECORATIONS_STYLER decoration style}. Clients can override.
* @param element
* the element that has been decorated
* @return return the decoration style
* @since 3.7
*/
protected Styler getDecorationStyle(Object element) {
return StyledString.DECORATIONS_STYLER;
}
/*
* (non-Javadoc) Method declared on ILabelProvider
*/
public final String getText(Object element) {
// query the element for its label
IWorkbenchAdapter adapter = getAdapter(element);
if (adapter == null) {
return ""; //$NON-NLS-1$
}
String label = adapter.getLabel(element);
// return the decorated label
return decorateText(label, element);
}
/*
* (non-Javadoc)
*
* @see org.eclipse.jface.viewers.IColorProvider#getForeground(java.lang.Object)
*/
public Color getForeground(Object element) {
return getColor(element, true);
}
/*
* (non-Javadoc)
*
* @see org.eclipse.jface.viewers.IColorProvider#getBackground(java.lang.Object)
*/
public Color getBackground(Object element) {
return getColor(element, false);
}
/*
* (non-Javadoc)
*
* @see org.eclipse.jface.viewers.IFontProvider#getFont(java.lang.Object)
*/
public Font getFont(Object element) {
IWorkbenchAdapter2 adapter = getAdapter2(element);
if (adapter == null) {
return null;
}
FontData descriptor = adapter.getFont(element);
if (descriptor == null) {
return null;
}
return (Font) getResourceManager().get(FontDescriptor.createFrom(descriptor));
}
private Color getColor(Object element, boolean forground) {
IWorkbenchAdapter2 adapter = getAdapter2(element);
if (adapter == null) {
return null;
}
RGB descriptor = forground ? adapter.getForeground(element) : adapter.getBackground(element);
if (descriptor == null) {
return null;
}
return (Color) getResourceManager().get(ColorDescriptor.createFrom(descriptor));
}
private String getDecorateFileCount(IFolder ifolder){
IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
String rootPath = root.getLocation().toOSString();
String filePath = ifolder.getFullPath().toOSString();
String folder = rootPath+filePath;
File file = new File(folder);
if(!file.exists()){
return "";
}
List<File> temp = new ArrayList<File>(10);
lookUp(file,temp);
int size = temp.size();
if(null ==temp || temp.isEmpty()){
return "";
}else if(size==1){
return " [1]";
}else{
return " ["+size+"]";
}
}
public void lookUp(File parent, List<File> files) {
if (parent.isDirectory()) {
File[] listFiles = parent.listFiles();
if (listFiles == null || listFiles.length == 0) {
return;
}
for (File file : listFiles) {
if (file.isDirectory()) {
lookUp(file, files);
} else {
// Fix Bug #3714
if(!file.getName().startsWith(".")){// 以点开头的文件不会显示在界面上面
files.add(file);
}
}
}
}
}
}
| 12,196 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
TabbedPropertySheetAdapterFactory.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/base_commons/net.heartsome.cat.common.ui.navigator.resources/src/org/eclipse/ui/internal/navigator/resources/workbench/TabbedPropertySheetAdapterFactory.java | /*******************************************************************************
* Copyright (c) 2006, 2010 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
******************************************************************************/
package org.eclipse.ui.internal.navigator.resources.workbench;
import org.eclipse.core.runtime.IAdapterFactory;
import org.eclipse.ui.navigator.CommonNavigator;
import org.eclipse.ui.navigator.resources.ProjectExplorer;
import org.eclipse.ui.views.properties.IPropertySheetPage;
import org.eclipse.ui.views.properties.tabbed.TabbedPropertySheetPage;
/**
* An property sheet page adapter factory for the Project Explorer.
*
* @since 3.2
*/
public class TabbedPropertySheetAdapterFactory
implements IAdapterFactory {
/*
* (non-Javadoc)
*
* @see org.eclipse.core.runtime.IAdapterFactory#getAdapter(java.lang.Object,
* java.lang.Class)
*/
public Object getAdapter(Object adaptableObject, Class adapterType) {
if (adaptableObject instanceof ProjectExplorer) {
if (IPropertySheetPage.class == adapterType)
return new TabbedPropertySheetPage(
new TabbedPropertySheetProjectExplorerContributor(
(CommonNavigator) adaptableObject));
}
return null;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.core.runtime.IAdapterFactory#getAdapterList()
*/
public Class[] getAdapterList() {
return new Class[] {IPropertySheetPage.class};
}
}
| 1,848 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
TabbedPropertySheetTitleProvider.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/base_commons/net.heartsome.cat.common.ui.navigator.resources/src/org/eclipse/ui/internal/navigator/resources/workbench/TabbedPropertySheetTitleProvider.java | /*******************************************************************************
* Copyright (c) 2006, 2009 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
******************************************************************************/
package org.eclipse.ui.internal.navigator.resources.workbench;
import org.eclipse.jface.viewers.ILabelProvider;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.swt.graphics.Image;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.internal.navigator.resources.plugin.WorkbenchNavigatorPlugin;
import org.eclipse.ui.navigator.IDescriptionProvider;
import org.eclipse.ui.navigator.INavigatorContentService;
import org.eclipse.ui.navigator.resources.ProjectExplorer;
/**
* Defines a label provider for the title bar in the tabbed properties view.
*
* @since 3.2
*/
public class TabbedPropertySheetTitleProvider extends LabelProvider {
private ILabelProvider labelProvider;
private IDescriptionProvider descriptionProvider;
/**
* Constructor for CommonNavigatorTitleProvider.
*/
public TabbedPropertySheetTitleProvider() {
super();
IWorkbenchPart part = PlatformUI.getWorkbench()
.getActiveWorkbenchWindow().getActivePage().findView(ProjectExplorer.VIEW_ID);
INavigatorContentService contentService = (INavigatorContentService) part
.getAdapter(INavigatorContentService.class);
if (contentService != null) {
labelProvider = contentService.createCommonLabelProvider();
descriptionProvider = contentService
.createCommonDescriptionProvider();
} else {
WorkbenchNavigatorPlugin.log(
"Could not acquire INavigatorContentService from part (\"" //$NON-NLS-1$
+ part.getTitle() + "\").", null); //$NON-NLS-1$
}
}
/**
* @see org.eclipse.jface.viewers.ILabelProvider#getImage(java.lang.Object)
*/
public Image getImage(Object object) {
return labelProvider != null ? labelProvider.getImage(object) : null;
}
/**
* @see org.eclipse.jface.viewers.ILabelProvider#getText(java.lang.Object)
*/
public String getText(Object object) {
return descriptionProvider != null ? descriptionProvider
.getDescription(object) : null;
}
}
| 2,502 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
ResourceExtensionLabelProvider.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/base_commons/net.heartsome.cat.common.ui.navigator.resources/src/org/eclipse/ui/internal/navigator/resources/workbench/ResourceExtensionLabelProvider.java | /*******************************************************************************
* Copyright (c) 2003, 2006 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.ui.internal.navigator.resources.workbench;
import org.eclipse.core.resources.IResource;
import org.eclipse.ui.IMemento;
import org.eclipse.ui.model.WorkbenchLabelProvider;
import org.eclipse.ui.navigator.ICommonContentExtensionSite;
import org.eclipse.ui.navigator.ICommonLabelProvider;
/**
* <p>
* <strong>EXPERIMENTAL</strong>. This class or interface has been added as
* part of a work in progress. There is a guarantee neither that this API will
* work nor that it will remain the same. Please do not use this API without
* consulting with the Platform/UI team.
* </p>
* @since 3.2
*/
public class ResourceExtensionLabelProvider extends WorkbenchLabelProvider implements ICommonLabelProvider {
public void init(ICommonContentExtensionSite aConfig) {
//init
}
public String getDescription(Object anElement) {
if (anElement instanceof IResource) {
return ((IResource) anElement).getFullPath().makeRelative().toString();
}
return null;
}
public void restoreState(IMemento aMemento) {
}
public void saveState(IMemento aMemento) {
}
}
| 1,635 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
TabbedPropertySheetProjectExplorerContributor.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/base_commons/net.heartsome.cat.common.ui.navigator.resources/src/org/eclipse/ui/internal/navigator/resources/workbench/TabbedPropertySheetProjectExplorerContributor.java | /*******************************************************************************
* Copyright (c) 2006 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
******************************************************************************/
package org.eclipse.ui.internal.navigator.resources.workbench;
import org.eclipse.ui.navigator.CommonNavigator;
import org.eclipse.ui.views.properties.tabbed.ITabbedPropertySheetPageContributor;
/**
* A tabbed property view contributor for the Project Explorer.
*
* @since 3.2
*/
public class TabbedPropertySheetProjectExplorerContributor implements
ITabbedPropertySheetPageContributor {
private final String contributorId;
protected TabbedPropertySheetProjectExplorerContributor(CommonNavigator aCommonNavigator) {
contributorId = aCommonNavigator.getViewSite().getId();
}
/* (non-Javadoc)
* @see org.eclipse.ui.views.properties.tabbed.ITabbedPropertySheetPageContributor#getContributorId()
*/
public String getContributorId() {
return contributorId;
}
}
| 1,321 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
ResourceLinkHelper.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/base_commons/net.heartsome.cat.common.ui.navigator.resources/src/org/eclipse/ui/internal/navigator/resources/workbench/ResourceLinkHelper.java | /*******************************************************************************
* Copyright (c) 2006, 2007 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.ui.internal.navigator.resources.workbench;
import org.eclipse.core.resources.IFile;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.ide.ResourceUtil;
import org.eclipse.ui.navigator.ILinkHelper;
import org.eclipse.ui.part.FileEditorInput;
/**
*
* Links IFileEditorInput to IFiles, and vice versa.
*
* @since 3.2
*
*/
public class ResourceLinkHelper implements ILinkHelper {
/* (non-Javadoc)
* @see org.eclipse.ui.navigator.ILinkHelper#findSelection(org.eclipse.ui.IEditorInput)
*/
public IStructuredSelection findSelection(IEditorInput anInput) {
IFile file = ResourceUtil.getFile(anInput);
if (file != null) {
return new StructuredSelection(file);
}
return StructuredSelection.EMPTY;
}
/* (non-Javadoc)
* @see org.eclipse.ui.navigator.ILinkHelper#activateEditor(org.eclipse.ui.IWorkbenchPage, org.eclipse.jface.viewers.IStructuredSelection)
*/
public void activateEditor(IWorkbenchPage aPage,
IStructuredSelection aSelection) {
if (aSelection == null || aSelection.isEmpty())
return;
if (aSelection.getFirstElement() instanceof IFile) {
IEditorInput fileInput = new FileEditorInput((IFile) aSelection.getFirstElement());
IEditorPart editor = null;
if ((editor = aPage.findEditor(fileInput)) != null)
aPage.bringToTop(editor);
}
}
}
| 2,051 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
ResourceExtensionSorter.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/base_commons/net.heartsome.cat.common.ui.navigator.resources/src/org/eclipse/ui/internal/navigator/resources/workbench/ResourceExtensionSorter.java | /*******************************************************************************
* Copyright (c) 2006, 2009 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
******************************************************************************/
package org.eclipse.ui.internal.navigator.resources.workbench;
// Sadly, there is nothing that can be done about these warnings, as
// the INavigatorSorterService has a method that returns a ViewerSorter, so
// we can't convert this to a ViewerComparator.
import org.eclipse.ui.views.navigator.ResourceSorter;
/**
* TODO - This refers to the deprecated ResourceSorter, however we are stuck with this
* for the time being because the CommonSorter extension point uses a ViewerSorter.
* We should provide an option for a ViewerComparator and then we can remove this
* class.
*
* @since 3.2
*
*/
public class ResourceExtensionSorter extends ResourceSorter {
/**
* Construct a sorter that uses the name of the resource as its sorting
* criteria.
*
*/
public ResourceExtensionSorter() {
super(ResourceSorter.NAME);
}
}
| 1,382 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
ResourceExtensionContentProvider.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/base_commons/net.heartsome.cat.common.ui.navigator.resources/src/org/eclipse/ui/internal/navigator/resources/workbench/ResourceExtensionContentProvider.java | /*******************************************************************************
* Copyright (c) 2003, 2009 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.ui.internal.navigator.resources.workbench;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IResourceDelta;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.viewers.AbstractTreeViewer;
import org.eclipse.jface.viewers.StructuredViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.swt.widgets.Control;
import org.eclipse.ui.internal.navigator.resources.plugin.WorkbenchNavigatorPlugin;
import org.eclipse.ui.model.WorkbenchContentProvider;
/**
* @since 3.2
*/
public class ResourceExtensionContentProvider extends WorkbenchContentProvider {
private static final Object[] NO_CHILDREN = new Object[0];
private Viewer viewer;
/**
*
*/
public ResourceExtensionContentProvider() {
super();
}
/*
* (non-Javadoc)
*
* @see org.eclipse.ui.model.BaseWorkbenchContentProvider#getElements(java.lang.Object)
*/
public Object[] getElements(Object element) {
return super.getChildren(element);
}
/*
* (non-Javadoc)
*
* @see org.eclipse.ui.model.BaseWorkbenchContentProvider#getChildren(java.lang.Object)
*/
public Object[] getChildren(Object element) {
if(element instanceof IResource)
return super.getChildren(element);
return NO_CHILDREN;
}
/* (non-Javadoc)
* @see org.eclipse.ui.model.BaseWorkbenchContentProvider#hasChildren(java.lang.Object)
*/
public boolean hasChildren(Object element) {
try {
if (element instanceof IContainer) {
IContainer c = (IContainer) element;
if (!c.isAccessible())
return false;
return c.members().length > 0;
}
} catch (CoreException ex) {
WorkbenchNavigatorPlugin.getDefault().getLog().log(
new Status(IStatus.ERROR, WorkbenchNavigatorPlugin.PLUGIN_ID, 0, ex.getMessage(), ex));
return false;
}
return super.hasChildren(element);
}
/* (non-Javadoc)
* @see org.eclipse.ui.model.WorkbenchContentProvider#inputChanged(org.eclipse.jface.viewers.Viewer, java.lang.Object, java.lang.Object)
*/
public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
super.inputChanged(viewer, oldInput, newInput);
this.viewer = viewer;
}
/**
* Process the resource delta.
*
* @param delta
*/
protected void processDelta(IResourceDelta delta) {
Control ctrl = viewer.getControl();
if (ctrl == null || ctrl.isDisposed()) {
return;
}
final Collection runnables = new ArrayList();
processDelta(delta, runnables);
if (runnables.isEmpty()) {
return;
}
//Are we in the UIThread? If so spin it until we are done
if (ctrl.getDisplay().getThread() == Thread.currentThread()) {
runUpdates(runnables);
} else {
ctrl.getDisplay().asyncExec(new Runnable(){
/* (non-Javadoc)
* @see java.lang.Runnable#run()
*/
public void run() {
//Abort if this happens after disposes
Control ctrl = viewer.getControl();
if (ctrl == null || ctrl.isDisposed()) {
return;
}
runUpdates(runnables);
}
});
}
}
/**
* Process a resource delta. Add any runnables
*/
private void processDelta(IResourceDelta delta, Collection runnables) {
//he widget may have been destroyed
// by the time this is run. Check for this and do nothing if so.
Control ctrl = viewer.getControl();
if (ctrl == null || ctrl.isDisposed()) {
return;
}
// Get the affected resource
final IResource resource = delta.getResource();
// If any children have changed type, just do a full refresh of this
// parent,
// since a simple update on such children won't work,
// and trying to map the change to a remove and add is too dicey.
// The case is: folder A renamed to existing file B, answering yes to
// overwrite B.
IResourceDelta[] affectedChildren = delta
.getAffectedChildren(IResourceDelta.CHANGED);
for (int i = 0; i < affectedChildren.length; i++) {
if ((affectedChildren[i].getFlags() & IResourceDelta.TYPE) != 0) {
runnables.add(getRefreshRunnable(resource));
return;
}
}
// Check the flags for changes the Navigator cares about.
// See ResourceLabelProvider for the aspects it cares about.
// Notice we don't care about F_CONTENT or F_MARKERS currently.
int changeFlags = delta.getFlags();
if ((changeFlags & (IResourceDelta.OPEN | IResourceDelta.SYNC
| IResourceDelta.TYPE | IResourceDelta.DESCRIPTION)) != 0) {
// Runnable updateRunnable = new Runnable(){
// public void run() {
// ((StructuredViewer) viewer).update(resource, null);
// }
// };
// runnables.add(updateRunnable);
/* support the Closed Projects filter;
* when a project is closed, it may need to be removed from the view.
*/
runnables.add(getRefreshRunnable(resource.getParent()));
}
// Replacing a resource may affect its label and its children
if ((changeFlags & IResourceDelta.REPLACED) != 0) {
runnables.add(getRefreshRunnable(resource));
return;
}
// Handle changed children .
for (int i = 0; i < affectedChildren.length; i++) {
processDelta(affectedChildren[i], runnables);
}
// @issue several problems here:
// - should process removals before additions, to avoid multiple equal
// elements in viewer
// - Kim: processing removals before additions was the indirect cause of
// 44081 and its varients
// - Nick: no delta should have an add and a remove on the same element,
// so processing adds first is probably OK
// - using setRedraw will cause extra flashiness
// - setRedraw is used even for simple changes
// - to avoid seeing a rename in two stages, should turn redraw on/off
// around combined removal and addition
// - Kim: done, and only in the case of a rename (both remove and add
// changes in one delta).
IResourceDelta[] addedChildren = delta
.getAffectedChildren(IResourceDelta.ADDED);
IResourceDelta[] removedChildren = delta
.getAffectedChildren(IResourceDelta.REMOVED);
if (addedChildren.length == 0 && removedChildren.length == 0) {
return;
}
final Object[] addedObjects;
final Object[] removedObjects;
// Process additions before removals as to not cause selection
// preservation prior to new objects being added
// Handle added children. Issue one update for all insertions.
int numMovedFrom = 0;
int numMovedTo = 0;
if (addedChildren.length > 0) {
addedObjects = new Object[addedChildren.length];
for (int i = 0; i < addedChildren.length; i++) {
addedObjects[i] = addedChildren[i].getResource();
if ((addedChildren[i].getFlags() & IResourceDelta.MOVED_FROM) != 0) {
++numMovedFrom;
}
}
} else {
addedObjects = new Object[0];
}
// Handle removed children. Issue one update for all removals.
if (removedChildren.length > 0) {
removedObjects = new Object[removedChildren.length];
for (int i = 0; i < removedChildren.length; i++) {
removedObjects[i] = removedChildren[i].getResource();
if ((removedChildren[i].getFlags() & IResourceDelta.MOVED_TO) != 0) {
++numMovedTo;
}
}
} else {
removedObjects = new Object[0];
}
// heuristic test for items moving within same folder (i.e. renames)
final boolean hasRename = numMovedFrom > 0 && numMovedTo > 0;
Runnable addAndRemove = new Runnable(){
public void run() {
if (viewer instanceof AbstractTreeViewer) {
AbstractTreeViewer treeViewer = (AbstractTreeViewer) viewer;
// Disable redraw until the operation is finished so we don't
// get a flash of both the new and old item (in the case of
// rename)
// Only do this if we're both adding and removing files (the
// rename case)
if (hasRename) {
treeViewer.getControl().setRedraw(false);
}
try {
if (addedObjects.length > 0) {
treeViewer.add(resource, addedObjects);
}
if (removedObjects.length > 0) {
treeViewer.remove(removedObjects);
}
}
finally {
if (hasRename) {
treeViewer.getControl().setRedraw(true);
}
}
} else {
((StructuredViewer) viewer).refresh(resource);
}
}
};
runnables.add(addAndRemove);
}
/**
* Return a runnable for refreshing a resource.
* @param resource
* @return Runnable
*/
private Runnable getRefreshRunnable(final IResource resource) {
return new Runnable(){
public void run() {
((StructuredViewer) viewer).refresh(resource);
}
};
}
/**
* Run all of the runnables that are the widget updates
* @param runnables
*/
private void runUpdates(Collection runnables) {
Iterator runnableIterator = runnables.iterator();
while(runnableIterator.hasNext()){
((Runnable)runnableIterator.next()).run();
}
}
}
| 9,451 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
WorkbenchNavigatorMessages.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/base_commons/net.heartsome.cat.common.ui.navigator.resources/src/org/eclipse/ui/internal/navigator/resources/resource/WorkbenchNavigatorMessages.java | /*******************************************************************************
* Copyright (c) 2003, 2009 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.ui.internal.navigator.resources.resource;
import org.eclipse.osgi.util.NLS;
/**
* Utility class which helps managing messages
*
*
* @since 3.2
*/
public class WorkbenchNavigatorMessages extends NLS {
/** The bundle properties file */
public static final String BUNDLE_NAME = "org.eclipse.ui.internal.navigator.resources.resource.messages"; //$NON-NLS-1$
public static String navigator_all_dialog_warning;
public static String PortingActionProvider_ImportResourcesMenu_label;
public static String PortingActionProvider_ExportResourcesMenu_label;
public static String actions_NewActionProvider_NewMenu_label;
public static String actions_OpenActionProvider_OpenWithMenu_label;
public static String resources_ResourceDropAdapterAssistant_title;
public static String resources_ResourceDropAdapterAssistant_problemImporting;
public static String resources_ResourceDropAdapterAssistant_problemsMoving;
public static String resources_ResourceDropAdapterAssistant_targetMustBeResource;
public static String resources_ResourceDropAdapterAssistant_canNotDropIntoClosedProject;
public static String resources_ResourceDropAdapterAssistant_resourcesCanNotBeSiblings;
public static String resources_ResourceDropAdapterAssistant_canNotDropProjectIntoProject;
public static String resources_ResourceDropAdapterAssistant_dropOperationErrorOther;
public static String resources_ResourceDropAdapterAssistant_MoveResourceAction_title;
public static String resources_ResourceDropAdapterAssistant_MoveResourceAction_checkMoveMessage;
public static String actions_ResourceMgmtActionProvider_logTitle;
public static String actions_WorkingSetRootModeActionGroup_Top_Level_Element_;
public static String actions_WorkingSetRootModeActionGroup_Project_;
public static String actions_WorkingSetRootModeActionGroup_Working_Set_;
public static String actions_WorkingSetActionProvider_multipleWorkingSets;
public static String actions_CopyAction_Cop_;
public static String actions_CopyAction_Copy_selected_resource_s_;
public static String actions_PasteAction_Past_;
public static String actions_PasteAction_Paste_selected_resource_s_;
public static String actions_GotoResourceDialog_GoToTitle;
public static String resources_ProjectExplorer_toolTip;
public static String resources_ProjectExplorer_toolTip2;
public static String resources_ProjectExplorer_toolTip3;
public static String resources_ProjectExplorerPart_workspace;
public static String resources_ProjectExplorerPart_workingSetModel;
public static String actions_CopyAction_msgTitle;
public static String actions_CopyAction_msg;
public static String actions_EditActionGroup_pasteAction;
public static String actions_EditActionGroup_copyAction;
public static String actions_EditActionGroup_deleteAction;
public static String actions_OpenActionProvider_openFileAction;
public static String actions_RefactorActionGroup_moveAction;
public static String actions_RefactorActionGroup_renameAction;
public static String actions_ResourceMgmtActionProvider_openProjectAction;
public static String actions_ResourceMgmtActionProvider_closeProjectAction;
public static String actions_ResourceMgmtActionProvider_refreshAction;
public static String actions_OpenFileWithValidAction_notFindProgram;
static {
initializeMessages(BUNDLE_NAME, WorkbenchNavigatorMessages.class);
}
}
| 3,926 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
WorkingSetsLabelProvider.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/base_commons/net.heartsome.cat.common.ui.navigator.resources/src/org/eclipse/ui/internal/navigator/workingsets/WorkingSetsLabelProvider.java | /*******************************************************************************
* Copyright (c) 2005, 2009 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.ui.internal.navigator.workingsets;
import org.eclipse.jface.viewers.ILabelProvider;
import org.eclipse.jface.viewers.ILabelProviderListener;
import org.eclipse.swt.graphics.Image;
import org.eclipse.ui.IWorkingSet;
import org.eclipse.ui.model.WorkbenchLabelProvider;
/**
* Provides a text label and icon for Working Sets.
*
*/
public class WorkingSetsLabelProvider implements ILabelProvider {
private WorkbenchLabelProvider labelProvider = new WorkbenchLabelProvider();
public Image getImage(Object element) {
if (element instanceof IWorkingSet)
return labelProvider.getImage(element);
return null;
}
public String getText(Object element) {
if (element instanceof IWorkingSet)
return ((IWorkingSet) element).getLabel();
return null;
}
public void addListener(ILabelProviderListener listener) {
}
public void dispose() {
}
public boolean isLabelProperty(Object element, String property) {
return false;
}
public void removeListener(ILabelProviderListener listener) {
}
}
| 1,575 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
WorkingSetSorter.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/base_commons/net.heartsome.cat.common.ui.navigator.resources/src/org/eclipse/ui/internal/navigator/workingsets/WorkingSetSorter.java | /*******************************************************************************
* Copyright (c) 2006 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
******************************************************************************/
package org.eclipse.ui.internal.navigator.workingsets;
import org.eclipse.jface.viewers.ILabelProvider;
import org.eclipse.jface.viewers.StructuredViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerSorter;
/**
* @since 3.2
*
*/
public class WorkingSetSorter extends ViewerSorter {
public int compare(Viewer viewer, Object e1, Object e2) {
if(viewer instanceof StructuredViewer) {
ILabelProvider labelProvider = (ILabelProvider) ((StructuredViewer)viewer).getLabelProvider();
String text1 = labelProvider.getText(e1);
String text2 = labelProvider.getText(e2);
if(text1 != null) {
return text1.compareTo(text2);
}
}
return -1;
}
}
| 1,249 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
WorkingSetsContentProvider.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/base_commons/net.heartsome.cat.common.ui.navigator.resources/src/org/eclipse/ui/internal/navigator/workingsets/WorkingSetsContentProvider.java | /*******************************************************************************
* Copyright (c) 2005, 2009 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.ui.internal.navigator.workingsets;
import java.util.Map;
import java.util.WeakHashMap;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.jface.util.IPropertyChangeListener;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.ui.IAggregateWorkingSet;
import org.eclipse.ui.IMemento;
import org.eclipse.ui.IWorkingSet;
import org.eclipse.ui.internal.navigator.NavigatorContentService;
import org.eclipse.ui.navigator.CommonNavigator;
import org.eclipse.ui.navigator.CommonViewer;
import org.eclipse.ui.navigator.ICommonContentExtensionSite;
import org.eclipse.ui.navigator.ICommonContentProvider;
import org.eclipse.ui.navigator.IExtensionStateModel;
import org.eclipse.ui.navigator.resources.ProjectExplorer;
/**
* Provides children and parents for IWorkingSets.
*
* @since 3.2.1
*
*/
public class WorkingSetsContentProvider implements ICommonContentProvider {
/**
* The extension id for the WorkingSet extension.
*/
public static final String EXTENSION_ID = "org.eclipse.ui.navigator.resources.workingSets"; //$NON-NLS-1$
/**
* A key used by the Extension State Model to keep track of whether top level Working Sets or
* Projects should be shown in the viewer.
*/
public static final String SHOW_TOP_LEVEL_WORKING_SETS = EXTENSION_ID + ".showTopLevelWorkingSets"; //$NON-NLS-1$
private static final Object[] NO_CHILDREN = new Object[0];
private WorkingSetHelper helper;
private IAggregateWorkingSet workingSetRoot;
private IExtensionStateModel extensionStateModel;
private CommonNavigator projectExplorer;
private CommonViewer viewer;
private IPropertyChangeListener rootModeListener = new IPropertyChangeListener() {
/* (non-Javadoc)
* @see org.eclipse.jface.util.IPropertyChangeListener#propertyChange(org.eclipse.jface.util.PropertyChangeEvent)
*/
public void propertyChange(PropertyChangeEvent event) {
if(SHOW_TOP_LEVEL_WORKING_SETS.equals(event.getProperty())) {
updateRootMode();
}
}
};
/* (non-Javadoc)
* @see org.eclipse.ui.navigator.ICommonContentProvider#init(org.eclipse.ui.navigator.ICommonContentExtensionSite)
*/
public void init(ICommonContentExtensionSite aConfig) {
NavigatorContentService cs = (NavigatorContentService) aConfig.getService();
viewer = (CommonViewer) cs.getViewer();
projectExplorer = viewer.getCommonNavigator();
extensionStateModel = aConfig.getExtensionStateModel();
extensionStateModel.addPropertyChangeListener(rootModeListener);
updateRootMode();
}
/* (non-Javadoc)
* @see org.eclipse.ui.navigator.IMementoAware#restoreState(org.eclipse.ui.IMemento)
*/
public void restoreState(IMemento aMemento) {
}
/* (non-Javadoc)
* @see org.eclipse.ui.navigator.IMementoAware#saveState(org.eclipse.ui.IMemento)
*/
public void saveState(IMemento aMemento) {
}
public Object[] getChildren(Object parentElement) {
if (parentElement instanceof IWorkingSet) {
IWorkingSet workingSet = (IWorkingSet) parentElement;
if (workingSet.isAggregateWorkingSet() && projectExplorer != null) {
switch (projectExplorer.getRootMode()) {
case ProjectExplorer.WORKING_SETS :
return ((IAggregateWorkingSet) workingSet).getComponents();
case ProjectExplorer.PROJECTS :
return getWorkingSetElements(workingSet);
}
}
return getWorkingSetElements(workingSet);
}
return NO_CHILDREN;
}
private IAdaptable[] getWorkingSetElements(IWorkingSet workingSet) {
IAdaptable[] children = workingSet.getElements();
for (int i = 0; i < children.length; i++) {
Object resource = children[i].getAdapter(IResource.class);
if (resource instanceof IProject)
children[i] = (IProject) resource;
}
return children;
}
public Object getParent(Object element) {
if (helper != null)
return helper.getParent(element);
return null;
}
public boolean hasChildren(Object element) {
return true;
}
public Object[] getElements(Object inputElement) {
return getChildren(inputElement);
}
public void dispose() {
helper = null;
extensionStateModel.removePropertyChangeListener(rootModeListener);
}
public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
if (newInput instanceof IWorkingSet) {
IWorkingSet rootSet = (IWorkingSet) newInput;
helper = new WorkingSetHelper(rootSet);
}
}
private void updateRootMode() {
if (projectExplorer == null) {
return;
}
if( extensionStateModel.getBooleanProperty(SHOW_TOP_LEVEL_WORKING_SETS) )
projectExplorer.setRootMode(ProjectExplorer.WORKING_SETS);
else
projectExplorer.setRootMode(ProjectExplorer.PROJECTS);
}
protected class WorkingSetHelper {
private final IWorkingSet workingSet;
private final Map parents = new WeakHashMap();
/**
* Create a Helper class for the given working set
*
* @param set
* The set to use to build the item to parent map.
*/
public WorkingSetHelper(IWorkingSet set) {
workingSet = set;
if (workingSet.isAggregateWorkingSet()) {
IAggregateWorkingSet aggregateSet = (IAggregateWorkingSet) workingSet;
if (workingSetRoot == null)
workingSetRoot = aggregateSet;
IWorkingSet[] components = aggregateSet.getComponents();
for (int componentIndex = 0; componentIndex < components.length; componentIndex++) {
IAdaptable[] elements = getWorkingSetElements(components[componentIndex]);
for (int elementsIndex = 0; elementsIndex < elements.length; elementsIndex++) {
parents.put(elements[elementsIndex], components[componentIndex]);
}
parents.put(components[componentIndex], aggregateSet);
}
} else {
IAdaptable[] elements = getWorkingSetElements(workingSet);
for (int elementsIndex = 0; elementsIndex < elements.length; elementsIndex++) {
parents.put(elements[elementsIndex], workingSet);
}
}
}
/**
*
* @param element
* An element from the viewer
* @return The parent associated with the element, if any.
*/
public Object getParent(Object element) {
if (element instanceof IWorkingSet && element != workingSetRoot)
return workingSetRoot;
return parents.get(element);
}
}
}
| 6,865 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
ResourceDropAdapterAssistant.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/base_commons/net.heartsome.cat.common.ui.navigator.resources/src/org/eclipse/ui/navigator/resources/ResourceDropAdapterAssistant.java | /*******************************************************************************
* Copyright (c) 2006, 2011 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.ui.navigator.resources;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Iterator;
import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.resources.IWorkspaceRunnable;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.MultiStatus;
import org.eclipse.core.runtime.OperationCanceledException;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.dialogs.ErrorDialog;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.util.LocalSelectionTransfer;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.ltk.core.refactoring.CheckConditionsOperation;
import org.eclipse.ltk.core.refactoring.PerformRefactoringOperation;
import org.eclipse.ltk.core.refactoring.Refactoring;
import org.eclipse.ltk.core.refactoring.RefactoringContribution;
import org.eclipse.ltk.core.refactoring.RefactoringCore;
import org.eclipse.ltk.core.refactoring.RefactoringStatus;
import org.eclipse.ltk.core.refactoring.RefactoringStatusEntry;
import org.eclipse.ltk.core.refactoring.resource.MoveResourcesDescriptor;
import org.eclipse.swt.dnd.DND;
import org.eclipse.swt.dnd.DropTargetEvent;
import org.eclipse.swt.dnd.FileTransfer;
import org.eclipse.swt.dnd.TransferData;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.actions.CopyFilesAndFoldersOperation;
import org.eclipse.ui.actions.MoveFilesAndFoldersOperation;
import org.eclipse.ui.actions.ReadOnlyStateChecker;
import org.eclipse.ui.internal.navigator.Policy;
import org.eclipse.ui.internal.navigator.resources.plugin.WorkbenchNavigatorPlugin;
import org.eclipse.ui.internal.navigator.resources.resource.WorkbenchNavigatorMessages;
import org.eclipse.ui.navigator.CommonDropAdapter;
import org.eclipse.ui.navigator.CommonDropAdapterAssistant;
import org.eclipse.ui.part.ResourceTransfer;
/**
*
* Clients may reference this class in the <b>dropAssistant</b> element of a
* <b>org.eclipse.ui.navigator.navigatorContent</b> extension point.
*
* <p>
* Clients may not extend or instantiate this class for any purpose.
* Clients may have no direct dependencies on the contract of this class.
* </p>
*
* @since 3.2
*
*/
public class ResourceDropAdapterAssistant extends CommonDropAdapterAssistant {
private static final IResource[] NO_RESOURCES = new IResource[0];
private RefactoringStatus refactoringStatus;
private IStatus returnStatus;
/*
* (non-Javadoc)
*
* @see org.eclipse.ui.navigator.CommonDropAdapterAssistant#isSupportedType(org.eclipse.swt.dnd.TransferData)
*/
public boolean isSupportedType(TransferData aTransferType) {
return super.isSupportedType(aTransferType)
|| FileTransfer.getInstance().isSupportedType(aTransferType);
}
/*
* (non-Javadoc)
*
* @see org.eclipse.ui.navigator.CommonDropAdapterAssistant#validateDrop(java.lang.Object,
* int, org.eclipse.swt.dnd.TransferData)
*/
public IStatus validateDrop(Object target, int aDropOperation,
TransferData transferType) {
if (!(target instanceof IResource)) {
return WorkbenchNavigatorPlugin
.createStatus(
IStatus.INFO,
0,
WorkbenchNavigatorMessages.resources_ResourceDropAdapterAssistant_targetMustBeResource,
null);
}
IResource resource = (IResource) target;
if (!resource.isAccessible()) {
return WorkbenchNavigatorPlugin
.createErrorStatus(
0,
WorkbenchNavigatorMessages.resources_ResourceDropAdapterAssistant_canNotDropIntoClosedProject,
null);
}
IContainer destination = getActualTarget(resource);
if (destination.getType() == IResource.ROOT) {
return WorkbenchNavigatorPlugin
.createErrorStatus(
0,
WorkbenchNavigatorMessages.resources_ResourceDropAdapterAssistant_resourcesCanNotBeSiblings,
null);
}
String message = null;
// drag within Eclipse?
if (LocalSelectionTransfer.getTransfer().isSupportedType(transferType)) {
IResource[] selectedResources = getSelectedResources();
boolean bProjectDrop = false;
for (int iRes = 0; iRes < selectedResources.length; iRes++) {
IResource res = selectedResources[iRes];
if(res instanceof IProject) {
bProjectDrop = true;
}
}
if(bProjectDrop) {
// drop of projects not supported on other IResources
// "Path for project must have only one segment."
message = WorkbenchNavigatorMessages.resources_ResourceDropAdapterAssistant_canNotDropProjectIntoProject;
} else {
if (selectedResources.length == 0) {
message = WorkbenchNavigatorMessages.resources_ResourceDropAdapterAssistant_dropOperationErrorOther;
} else {
CopyFilesAndFoldersOperation operation;
if (aDropOperation == DND.DROP_COPY) {
if (Policy.DEBUG_DND) {
System.out
.println("ResourceDropAdapterAssistant.validateDrop validating COPY."); //$NON-NLS-1$
}
operation = new CopyFilesAndFoldersOperation(getShell());
} else {
if (Policy.DEBUG_DND) {
System.out
.println("ResourceDropAdapterAssistant.validateDrop validating MOVE."); //$NON-NLS-1$
}
operation = new MoveFilesAndFoldersOperation(getShell());
}
if (operation.validateDestination(destination, selectedResources) != null) {
operation.setVirtualFolders(true);
message = operation.validateDestination(destination, selectedResources);
}
}
}
} // file import?
else if (FileTransfer.getInstance().isSupportedType(transferType)) {
String[] sourceNames = (String[]) FileTransfer.getInstance()
.nativeToJava(transferType);
if (sourceNames == null) {
// source names will be null on Linux. Use empty names to do
// destination validation.
// Fixes bug 29778
sourceNames = new String[0];
}
CopyFilesAndFoldersOperation copyOperation = new CopyFilesAndFoldersOperation(
getShell());
message = copyOperation.validateImportDestination(destination,
sourceNames);
}
if (message != null) {
return WorkbenchNavigatorPlugin.createErrorStatus(0, message, null);
}
return Status.OK_STATUS;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.ui.navigator.CommonDropAdapterAssistant#handleDrop(CommonDropAdapter,
* DropTargetEvent, Object)
*/
public IStatus handleDrop(CommonDropAdapter aDropAdapter,
DropTargetEvent aDropTargetEvent, Object aTarget) {
if (Policy.DEBUG_DND) {
System.out
.println("ResourceDropAdapterAssistant.handleDrop (begin)"); //$NON-NLS-1$
}
// alwaysOverwrite = false;
if (aTarget == null || aDropTargetEvent.data == null) {
return Status.CANCEL_STATUS;
}
IStatus status = null;
IResource[] resources = null;
TransferData currentTransfer = aDropAdapter.getCurrentTransfer();
if (LocalSelectionTransfer.getTransfer().isSupportedType(
currentTransfer)) {
resources = getSelectedResources();
} else if (ResourceTransfer.getInstance().isSupportedType(
currentTransfer)) {
resources = (IResource[]) aDropTargetEvent.data;
}
if (FileTransfer.getInstance().isSupportedType(currentTransfer)) {
status = performFileDrop(aDropAdapter, aDropTargetEvent.data);
} else if (resources != null && resources.length > 0) {
if ((aDropAdapter.getCurrentOperation() == DND.DROP_COPY)
|| (aDropAdapter.getCurrentOperation() == DND.DROP_LINK)) {
if (Policy.DEBUG_DND) {
System.out
.println("ResourceDropAdapterAssistant.handleDrop executing COPY."); //$NON-NLS-1$
}
status = performResourceCopy(aDropAdapter, getShell(),
resources);
} else {
if (Policy.DEBUG_DND) {
System.out
.println("ResourceDropAdapterAssistant.handleDrop executing MOVE."); //$NON-NLS-1$
}
status = performResourceMove(aDropAdapter, resources);
}
}
openError(status);
IContainer target = getActualTarget((IResource) aTarget);
if (target != null && target.isAccessible()) {
try {
target.refreshLocal(IResource.DEPTH_ONE, null);
} catch (CoreException e) {
}
}
return status;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.ui.navigator.CommonDropAdapterAssistant#validatePluginTransferDrop(org.eclipse.jface.viewers.IStructuredSelection,
* java.lang.Object)
*/
public IStatus validatePluginTransferDrop(
IStructuredSelection aDragSelection, Object aDropTarget) {
if (!(aDropTarget instanceof IResource)) {
return WorkbenchNavigatorPlugin
.createStatus(
IStatus.INFO,
0,
WorkbenchNavigatorMessages.resources_ResourceDropAdapterAssistant_targetMustBeResource,
null);
}
IResource resource = (IResource) aDropTarget;
if (!resource.isAccessible()) {
return WorkbenchNavigatorPlugin
.createErrorStatus(
0,
WorkbenchNavigatorMessages.resources_ResourceDropAdapterAssistant_canNotDropIntoClosedProject,
null);
}
IContainer destination = getActualTarget(resource);
if (destination.getType() == IResource.ROOT) {
return WorkbenchNavigatorPlugin
.createErrorStatus(
0,
WorkbenchNavigatorMessages.resources_ResourceDropAdapterAssistant_resourcesCanNotBeSiblings,
null);
}
IResource[] selectedResources = getSelectedResources(aDragSelection);
String message = null;
if (selectedResources.length == 0) {
message = WorkbenchNavigatorMessages.resources_ResourceDropAdapterAssistant_dropOperationErrorOther;
} else {
MoveFilesAndFoldersOperation operation;
operation = new MoveFilesAndFoldersOperation(getShell());
message = operation.validateDestination(destination,
selectedResources);
}
if (message != null) {
return WorkbenchNavigatorPlugin.createErrorStatus(0, message, null);
}
return Status.OK_STATUS;
}
/* (non-Javadoc)
* @see org.eclipse.ui.navigator.CommonDropAdapterAssistant#handlePluginTransferDrop(org.eclipse.jface.viewers.IStructuredSelection, java.lang.Object)
*/
public IStatus handlePluginTransferDrop(IStructuredSelection aDragSelection, Object aDropTarget) {
IContainer target = getActualTarget((IResource) aDropTarget);
IResource[] resources = getSelectedResources(aDragSelection);
MoveFilesAndFoldersOperation operation = new MoveFilesAndFoldersOperation(
getShell());
operation.copyResources(resources, target);
if (target != null && target.isAccessible()) {
try {
target.refreshLocal(IResource.DEPTH_ONE, null);
} catch (CoreException e) {
}
}
return Status.OK_STATUS;
}
/**
* Returns the actual target of the drop, given the resource under the
* mouse. If the mouse target is a file, then the drop actually occurs in
* its parent. If the drop location is before or after the mouse target and
* feedback is enabled, the target is also the parent.
*/
private IContainer getActualTarget(IResource mouseTarget) {
/* if cursor is on a file, return the parent */
if (mouseTarget.getType() == IResource.FILE) {
return mouseTarget.getParent();
}
/* otherwise the mouseTarget is the real target */
return (IContainer) mouseTarget;
}
/**
* Returns the resource selection from the LocalSelectionTransfer.
*
* @return the resource selection from the LocalSelectionTransfer
*/
private IResource[] getSelectedResources() {
ISelection selection = LocalSelectionTransfer.getTransfer()
.getSelection();
if (selection instanceof IStructuredSelection) {
return getSelectedResources((IStructuredSelection)selection);
}
return NO_RESOURCES;
}
/**
* Returns the resource selection from the LocalSelectionTransfer.
*
* @return the resource selection from the LocalSelectionTransfer
*/
private IResource[] getSelectedResources(IStructuredSelection selection) {
ArrayList selectedResources = new ArrayList();
for (Iterator i = selection.iterator(); i.hasNext();) {
Object o = i.next();
if (o instanceof IResource) {
selectedResources.add(o);
} else if (o instanceof IAdaptable) {
IAdaptable a = (IAdaptable) o;
IResource r = (IResource) a.getAdapter(IResource.class);
if (r != null) {
selectedResources.add(r);
}
}
}
return (IResource[]) selectedResources
.toArray(new IResource[selectedResources.size()]);
}
/**
* Performs a resource copy
*/
private IStatus performResourceCopy(CommonDropAdapter dropAdapter,
Shell shell, IResource[] sources) {
MultiStatus problems = new MultiStatus(PlatformUI.PLUGIN_ID, 1,
WorkbenchNavigatorMessages.resources_ResourceDropAdapterAssistant_problemsMoving, null);
mergeStatus(problems, validateTarget(dropAdapter.getCurrentTarget(), dropAdapter.getCurrentTransfer(),
dropAdapter.getCurrentOperation()));
IContainer target = getActualTarget((IResource) dropAdapter.getCurrentTarget());
boolean shouldLinkAutomatically = false;
if (target.isVirtual()) {
shouldLinkAutomatically = true;
for (int i = 0; i < sources.length; i++) {
if ((sources[i].getType() != IResource.FILE) && (sources[i].getLocation() != null)) {
// If the source is a folder, but the location is null (a
// broken link, for example),
// we still generate a link automatically (the best option).
shouldLinkAutomatically = false;
break;
}
}
}
CopyFilesAndFoldersOperation operation = new CopyFilesAndFoldersOperation(shell);
// if the target is a virtual folder and all sources are files, then
// automatically create links
if (shouldLinkAutomatically) {
operation.setCreateLinks(true);
operation.copyResources(sources, target);
} else {
// boolean allSourceAreLinksOrVirtualFolders = true;
// for (int i = 0; i < sources.length; i++) {
// if (!sources[i].isVirtual() && !sources[i].isLinked()) {
// allSourceAreLinksOrVirtualFolders = false;
// break;
// }
// }
// // if all sources are either links or groups, copy then normally,
// // don't show the dialog
// if (!allSourceAreLinksOrVirtualFolders) {
// IPreferenceStore store= IDEWorkbenchPlugin.getDefault().getPreferenceStore();
// String dndPreference= store.getString(target.isVirtual() ? IDEInternalPreferences.IMPORT_FILES_AND_FOLDERS_VIRTUAL_FOLDER_MODE : IDEInternalPreferences.IMPORT_FILES_AND_FOLDERS_MODE);
//
// if (dndPreference.equals(IDEInternalPreferences.IMPORT_FILES_AND_FOLDERS_MODE_PROMPT)) {
// ImportTypeDialog dialog = new ImportTypeDialog(getShell(), dropAdapter.getCurrentOperation(), sources, target);
// dialog.setResource(target);
// if (dialog.open() == Window.OK) {
// if (dialog.getSelection() == ImportTypeDialog.IMPORT_VIRTUAL_FOLDERS_AND_LINKS)
// operation.setVirtualFolders(true);
// if (dialog.getSelection() == ImportTypeDialog.IMPORT_LINK)
// operation.setCreateLinks(true);
// if (dialog.getVariable() != null)
// operation.setRelativeVariable(dialog.getVariable());
// operation.copyResources(sources, target);
// } else
// return problems;
// }
// else
// operation.copyResources(sources, target);
// } else
operation.copyResources(sources, target);
}
return problems;
}
/**
* Performs a resource move
*/
private IStatus performResourceMove(CommonDropAdapter dropAdapter,
IResource[] sources) {
MultiStatus problems = new MultiStatus(PlatformUI.PLUGIN_ID, 1,
WorkbenchNavigatorMessages.resources_ResourceDropAdapterAssistant_problemsMoving, null);
mergeStatus(problems, validateTarget(dropAdapter.getCurrentTarget(), dropAdapter.getCurrentTransfer(),
dropAdapter.getCurrentOperation()));
IContainer target = getActualTarget((IResource) dropAdapter.getCurrentTarget());
boolean shouldLinkAutomatically = false;
if (target.isVirtual()) {
shouldLinkAutomatically = true;
for (int i = 0; i < sources.length; i++) {
if (sources[i].isVirtual() || sources[i].isLinked()) {
shouldLinkAutomatically = false;
break;
}
}
}
if (shouldLinkAutomatically) {
CopyFilesAndFoldersOperation operation = new CopyFilesAndFoldersOperation(getShell());
operation.setCreateLinks(true);
operation.copyResources(sources, target);
} else {
ReadOnlyStateChecker checker = new ReadOnlyStateChecker(getShell(),
WorkbenchNavigatorMessages.resources_ResourceDropAdapterAssistant_MoveResourceAction_title,
WorkbenchNavigatorMessages.resources_ResourceDropAdapterAssistant_MoveResourceAction_checkMoveMessage);
sources = checker.checkReadOnlyResources(sources);
try {
RefactoringContribution contribution = RefactoringCore
.getRefactoringContribution(MoveResourcesDescriptor.ID);
MoveResourcesDescriptor descriptor = (MoveResourcesDescriptor) contribution.createDescriptor();
descriptor.setResourcesToMove(sources);
descriptor.setDestination(target);
refactoringStatus = new RefactoringStatus();
final Refactoring refactoring = descriptor.createRefactoring(refactoringStatus);
returnStatus = null;
IRunnableWithProgress checkOp = new IRunnableWithProgress() {
public void run(IProgressMonitor monitor) {
try {
refactoringStatus = refactoring.checkAllConditions(monitor);
} catch (CoreException ex) {
returnStatus = WorkbenchNavigatorPlugin.createErrorStatus(0, ex.getLocalizedMessage(), ex);
}}
};
if (returnStatus != null)
return returnStatus;
try {
PlatformUI.getWorkbench().getProgressService().run(false, false, checkOp);
} catch (InterruptedException e) {
return Status.CANCEL_STATUS;
} catch (InvocationTargetException e) {
return WorkbenchNavigatorPlugin.createErrorStatus(0, e.getLocalizedMessage(), e);
}
/** Weachy:下行代码用于测试弹出错误对话框 */
// refactoringStatus.addFatalError(RefactoringCoreMessages.MoveResourcesDescriptor_error_destination_not_set);
if (refactoringStatus.hasEntries()) {
RefactoringStatusEntry[] entries = refactoringStatus.getEntries();
StringBuffer message = new StringBuffer();
int severity = 0;
for (RefactoringStatusEntry refactoringStatusEntry : entries) {
if (refactoringStatusEntry.getSeverity() > severity) {
severity = refactoringStatusEntry.getSeverity();
message.replace(0, message.length(), refactoringStatusEntry.getMessage());
} else if (refactoringStatusEntry.getSeverity() == severity) {
message.append("\n\n").append(refactoringStatusEntry.getMessage());
}
}
if (severity == RefactoringStatus.INFO) {
MessageDialog.openInformation(getShell(), WorkbenchNavigatorMessages.resources_ResourceDropAdapterAssistant_MoveResourceAction_title, message.toString());
} else if (severity == RefactoringStatus.WARNING) {
boolean result = MessageDialog.openConfirm(getShell(), WorkbenchNavigatorMessages.resources_ResourceDropAdapterAssistant_MoveResourceAction_title, message.toString());
if (!result) {
return Status.CANCEL_STATUS;
}
} else if (severity == RefactoringStatus.ERROR || severity == RefactoringStatus.FATAL) {
MessageDialog.openError(getShell(), WorkbenchNavigatorMessages.resources_ResourceDropAdapterAssistant_MoveResourceAction_title, message.toString());
return Status.CANCEL_STATUS;
} else {
}
/**
* Weachy:
* RefactoringUI 类需引入 org.eclipse.ltk.ui.refactoring 插件,
* 而 org.eclipse.ltk.ui.refactoring 插件会引入
* org.eclipse.compare、org.eclipse.team.core、org.eclipse.team.ui
* 三个插件。会导致在导航视图、首选项等出现无用的功能项。因此注释以下4行代码。
*/
// Dialog dialog= RefactoringUI.createLightWeightStatusDialog(refactoringStatus, getShell(), WorkbenchNavigatorMessages.MoveResourceAction_title);
// int result = dialog.open();
// if (result != IStatus.OK)
// return Status.CANCEL_STATUS;
}
final PerformRefactoringOperation op = new PerformRefactoringOperation(refactoring,
CheckConditionsOperation.ALL_CONDITIONS);
final IWorkspaceRunnable r = new IWorkspaceRunnable() {
public void run(IProgressMonitor monitor) throws CoreException {
op.run(monitor);
}
};
returnStatus = null;
IRunnableWithProgress refactorOp = new IRunnableWithProgress() {
public void run(IProgressMonitor monitor) {
try {
ResourcesPlugin.getWorkspace().run(r, ResourcesPlugin.getWorkspace().getRoot(), IWorkspace.AVOID_UPDATE, monitor);
} catch (CoreException ex) {
returnStatus = WorkbenchNavigatorPlugin.createErrorStatus(0, ex.getLocalizedMessage(), ex);
}
}
};
if (returnStatus != null)
return returnStatus;
try {
PlatformUI.getWorkbench().getProgressService().run(false, false, refactorOp);
} catch (InterruptedException e) {
return Status.CANCEL_STATUS;
} catch (InvocationTargetException e) {
return WorkbenchNavigatorPlugin.createErrorStatus(0, e.getLocalizedMessage(), e);
}
} catch (CoreException ex) {
return WorkbenchNavigatorPlugin.createErrorStatus(0, ex.getLocalizedMessage(), ex);
} catch (OperationCanceledException e) {
}
}
return problems;
}
/**
* Performs a drop using the FileTransfer transfer type.
*/
private IStatus performFileDrop(final CommonDropAdapter anAdapter, Object data) {
final int currentOperation = anAdapter.getCurrentOperation();
MultiStatus problems = new MultiStatus(PlatformUI.PLUGIN_ID, 0,
WorkbenchNavigatorMessages.resources_ResourceDropAdapterAssistant_problemImporting, null);
mergeStatus(problems,
validateTarget(anAdapter.getCurrentTarget(), anAdapter
.getCurrentTransfer(), currentOperation));
final IContainer target = getActualTarget((IResource) anAdapter
.getCurrentTarget());
final String[] names = (String[]) data;
// Run the import operation asynchronously.
// Otherwise the drag source (e.g., Windows Explorer) will be blocked
// while the operation executes. Fixes bug 16478.
Display.getCurrent().asyncExec(new Runnable() {
public void run() {
getShell().forceActive();
new CopyFilesAndFoldersOperation(getShell()).copyOrLinkFiles(names, target, currentOperation);
}
});
return problems;
}
/**
* Ensures that the drop target meets certain criteria
*/
private IStatus validateTarget(Object target, TransferData transferType,
int dropOperation) {
if (!(target instanceof IResource)) {
return WorkbenchNavigatorPlugin
.createInfoStatus(WorkbenchNavigatorMessages.resources_ResourceDropAdapterAssistant_targetMustBeResource);
}
IResource resource = (IResource) target;
if (!resource.isAccessible()) {
return WorkbenchNavigatorPlugin
.createErrorStatus(WorkbenchNavigatorMessages.resources_ResourceDropAdapterAssistant_canNotDropIntoClosedProject);
}
IContainer destination = getActualTarget(resource);
if (destination.getType() == IResource.ROOT) {
return WorkbenchNavigatorPlugin
.createErrorStatus(WorkbenchNavigatorMessages.resources_ResourceDropAdapterAssistant_resourcesCanNotBeSiblings);
}
String message = null;
// drag within Eclipse?
if (LocalSelectionTransfer.getTransfer().isSupportedType(transferType)) {
IResource[] selectedResources = getSelectedResources();
if (selectedResources.length == 0) {
message = WorkbenchNavigatorMessages.resources_ResourceDropAdapterAssistant_dropOperationErrorOther;
} else {
CopyFilesAndFoldersOperation operation;
if ((dropOperation == DND.DROP_COPY) || (dropOperation == DND.DROP_LINK)) {
operation = new CopyFilesAndFoldersOperation(getShell());
if (operation.validateDestination(destination, selectedResources) != null) {
operation.setVirtualFolders(true);
message = operation.validateDestination(destination, selectedResources);
}
} else {
operation = new MoveFilesAndFoldersOperation(getShell());
if (operation.validateDestination(destination, selectedResources) != null) {
operation.setVirtualFolders(true);
message = operation.validateDestination(destination, selectedResources);
}
}
}
} // file import?
else if (FileTransfer.getInstance().isSupportedType(transferType)) {
String[] sourceNames = (String[]) FileTransfer.getInstance()
.nativeToJava(transferType);
if (sourceNames == null) {
// source names will be null on Linux. Use empty names to do
// destination validation.
// Fixes bug 29778
sourceNames = new String[0];
}
CopyFilesAndFoldersOperation copyOperation = new CopyFilesAndFoldersOperation(
getShell());
message = copyOperation.validateImportDestination(destination,
sourceNames);
}
if (message != null) {
return WorkbenchNavigatorPlugin.createErrorStatus(message);
}
return Status.OK_STATUS;
}
/**
* Adds the given status to the list of problems. Discards OK statuses. If
* the status is a multi-status, only its children are added.
*/
private void mergeStatus(MultiStatus status, IStatus toMerge) {
if (!toMerge.isOK()) {
status.merge(toMerge);
}
}
/**
* Opens an error dialog if necessary. Takes care of complex rules necessary
* for making the error dialog look nice.
*/
private void openError(IStatus status) {
if (status == null) {
return;
}
String genericTitle = WorkbenchNavigatorMessages.resources_ResourceDropAdapterAssistant_title;
int codes = IStatus.ERROR | IStatus.WARNING;
// simple case: one error, not a multistatus
if (!status.isMultiStatus()) {
ErrorDialog
.openError(getShell(), genericTitle, null, status, codes);
return;
}
// one error, single child of multistatus
IStatus[] children = status.getChildren();
if (children.length == 1) {
ErrorDialog.openError(getShell(), status.getMessage(), null,
children[0], codes);
return;
}
// several problems
ErrorDialog.openError(getShell(), genericTitle, null, status, codes);
}
}
| 26,948 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
ResourceDragAdapterAssistant.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/base_commons/net.heartsome.cat.common.ui.navigator.resources/src/org/eclipse/ui/navigator/resources/ResourceDragAdapterAssistant.java | /*******************************************************************************
* Copyright (c) 2006, 2009 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
* Anton Leherbauer (Wind River Systems) - http://bugs.eclipse.org/247294
******************************************************************************/
package org.eclipse.ui.navigator.resources;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.Set;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.Platform;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.swt.dnd.DragSourceEvent;
import org.eclipse.swt.dnd.FileTransfer;
import org.eclipse.swt.dnd.Transfer;
import org.eclipse.ui.internal.navigator.Policy;
import org.eclipse.ui.navigator.CommonDragAdapterAssistant;
import org.eclipse.ui.navigator.INavigatorDnDService;
import org.eclipse.ui.part.ResourceTransfer;
/**
* Clients may reference this class in the <b>dragAssistant</b> element of a
* <b>org.eclipse.ui.navigator.viewer</b> extension point.
*
* <p>
* Clients may not extend or instantiate this class for any purpose other than
* {@link INavigatorDnDService#bindDragAssistant(CommonDragAdapterAssistant)}.
* Clients may have no direct dependencies on the contract of this class.
* </p>
*
* @since 3.2
* @noextend This class is not intended to be subclassed by clients.
*
*/
public class ResourceDragAdapterAssistant extends
CommonDragAdapterAssistant {
private static final Transfer[] SUPPORTED_TRANSFERS = new Transfer[] {
ResourceTransfer.getInstance(),
FileTransfer.getInstance() };
private static final Class IRESOURCE_TYPE = IResource.class;
/*
* (non-Javadoc)
*
* @see org.eclipse.ui.navigator.CommonDragAdapterAssistant#getSupportedTransferTypes()
*/
public Transfer[] getSupportedTransferTypes() {
return SUPPORTED_TRANSFERS;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.ui.navigator.CommonDragAdapterAssistant#setDragData(org.eclipse.swt.dnd.DragSourceEvent,
* org.eclipse.jface.viewers.IStructuredSelection)
*/
public boolean setDragData(DragSourceEvent anEvent,
IStructuredSelection aSelection) {
IResource[] resources = getSelectedResources(aSelection);
if (resources.length > 0) {
if (ResourceTransfer.getInstance().isSupportedType(anEvent.dataType)) {
anEvent.data = resources;
if (Policy.DEBUG_DND) {
System.out
.println("ResourceDragAdapterAssistant.dragSetData set ResourceTransfer"); //$NON-NLS-1$
}
return true;
}
if (FileTransfer.getInstance().isSupportedType(anEvent.dataType)) {
// Get the path of each file and set as the drag data
final int length = resources.length;
int actualLength = 0;
String[] fileNames = new String[length];
for (int i = 0; i < length; i++) {
IPath location = resources[i].getLocation();
// location may be null. See bug 29491.
if (location != null) {
fileNames[actualLength++] = location.toOSString();
}
}
if (actualLength > 0) {
// was one or more of the locations null?
if (actualLength < length) {
String[] tempFileNames = fileNames;
fileNames = new String[actualLength];
for (int i = 0; i < actualLength; i++)
fileNames[i] = tempFileNames[i];
}
anEvent.data = fileNames;
if (Policy.DEBUG_DND)
System.out
.println("ResourceDragAdapterAssistant.dragSetData set FileTransfer"); //$NON-NLS-1$
return true;
}
}
}
return false;
}
private IResource[] getSelectedResources(IStructuredSelection aSelection) {
Set resources = new LinkedHashSet();
IResource resource = null;
for (Iterator iter = aSelection.iterator(); iter.hasNext();) {
Object selected = iter.next();
resource = adaptToResource(selected);
if (resource != null) {
resources.add(resource);
}
}
return (IResource[]) resources.toArray(new IResource[resources.size()]);
}
private IResource adaptToResource(Object selected) {
IResource resource;
if (selected instanceof IResource) {
resource = (IResource) selected;
} else if (selected instanceof IAdaptable) {
resource = (IResource) ((IAdaptable) selected)
.getAdapter(IRESOURCE_TYPE);
} else {
resource = (IResource) Platform.getAdapterManager().getAdapter(
selected, IRESOURCE_TYPE);
}
return resource;
}
}
| 4,774 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
GoIntoActionProvider.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/base_commons/net.heartsome.cat.common.ui.navigator.resources/src/org/eclipse/ui/navigator/resources/GoIntoActionProvider.java | /*******************************************************************************
* Copyright (c) 2006, 2009 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
* Oakland Software (Francis Upton - [email protected])
* bug 214271 Undo/redo not enabled if nothing selected
******************************************************************************/
package org.eclipse.ui.navigator.resources;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.ui.IActionBars;
import org.eclipse.ui.IWorkbenchActionConstants;
import org.eclipse.ui.internal.navigator.framelist.GoIntoAction;
import org.eclipse.ui.navigator.CommonActionProvider;
import org.eclipse.ui.navigator.CommonViewer;
import org.eclipse.ui.navigator.ICommonActionExtensionSite;
/**
* Provides the Go Into action for the {@link ProjectExplorer}
*
* @since 3.4
*
*/
public class GoIntoActionProvider extends CommonActionProvider {
private GoIntoAction goIntoAction;
public void init(ICommonActionExtensionSite anActionSite) {
anActionSite.getViewSite().getShell();
CommonViewer viewer = (CommonViewer) anActionSite.getStructuredViewer();
goIntoAction = new GoIntoAction(viewer.getFrameList());
}
public void dispose() {
goIntoAction.dispose();
}
public void fillActionBars(IActionBars actionBars) {
actionBars.setGlobalActionHandler(IWorkbenchActionConstants.GO_INTO, goIntoAction);
}
public void fillContextMenu(IMenuManager menu) {
menu.appendToGroup("group.new", goIntoAction); //$NON-NLS-1$
}
public void updateActionBars() {
goIntoAction.update();
}
}
| 1,882 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
ProjectExplorer.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/base_commons/net.heartsome.cat.common.ui.navigator.resources/src/org/eclipse/ui/navigator/resources/ProjectExplorer.java | /*******************************************************************************
* Copyright (c) 2007, 2010 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
******************************************************************************/
package org.eclipse.ui.navigator.resources;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.core.runtime.IPath;
import org.eclipse.osgi.util.NLS;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.ui.IAggregateWorkingSet;
import org.eclipse.ui.IPageLayout;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.IWorkingSet;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.internal.navigator.framelist.Frame;
import org.eclipse.ui.internal.navigator.framelist.FrameList;
import org.eclipse.ui.internal.navigator.framelist.TreeFrame;
import org.eclipse.ui.internal.navigator.resources.ResourceToItemsMapper;
import org.eclipse.ui.internal.navigator.resources.resource.WorkbenchNavigatorMessages;
import org.eclipse.ui.model.IWorkbenchAdapter;
import org.eclipse.ui.navigator.CommonNavigator;
import org.eclipse.ui.navigator.INavigatorContentService;
/**
*
* @see CommonNavigator
* @see INavigatorContentService
* @since 3.2
*
*/
public final class ProjectExplorer extends CommonNavigator {
/**
* Provides a constant for the standard instance of the Common Navigator.
*
* @see PlatformUI#getWorkbench()
* @see IWorkbench#getActiveWorkbenchWindow()
* @see IWorkbenchWindow#getActivePage()
*
* @see IWorkbenchPage#findView(String)
* @see IWorkbenchPage#findViewReference(String)
*/
public static final String VIEW_ID = IPageLayout.ID_PROJECT_EXPLORER;
/**
* @since 3.4
*/
public static final int WORKING_SETS = 0;
/**
* @since 3.4
*/
public static final int PROJECTS = 1;
private int rootMode;
/**
* Used only in the case of top level = PROJECTS and only when some
* working sets are selected.
*/
private String workingSetLabel;
public void createPartControl(Composite aParent) {
super.createPartControl(aParent);
if (!false)
getCommonViewer().setMapper(new ResourceToItemsMapper(getCommonViewer()));
}
/**
* The superclass does not deal with the content description, handle it
* here.
*
* @noreference
*/
public void updateTitle() {
super.updateTitle();
Object input = getCommonViewer().getInput();
if (input == null || input instanceof IAggregateWorkingSet) {
setContentDescription(""); //$NON-NLS-1$
return;
}
if (!(input instanceof IResource)) {
if (input instanceof IAdaptable) {
IWorkbenchAdapter wbadapter = (IWorkbenchAdapter) ((IAdaptable) input)
.getAdapter(IWorkbenchAdapter.class);
if (wbadapter != null) {
setContentDescription(wbadapter.getLabel(input));
return;
}
}
setContentDescription(input.toString());
return;
}
IResource res = (IResource) input;
setContentDescription(res.getName());
}
/**
* Returns the tool tip text for the given element.
*
* @param element
* the element
* @return the tooltip
* @noreference
*/
public String getFrameToolTipText(Object element) {
String result;
if (!(element instanceof IResource)) {
if (element instanceof IAggregateWorkingSet) {
result = WorkbenchNavigatorMessages.resources_ProjectExplorerPart_workingSetModel;
} else if (element instanceof IWorkingSet) {
result = ((IWorkingSet) element).getLabel();
} else {
result = super.getFrameToolTipText(element);
}
} else {
IPath path = ((IResource) element).getFullPath();
if (path.isRoot()) {
result = WorkbenchNavigatorMessages.resources_ProjectExplorerPart_workspace;
} else {
result = path.makeRelative().toString();
}
}
if (rootMode == PROJECTS) {
if (workingSetLabel == null)
return result;
if (result.length() == 0)
return NLS.bind(WorkbenchNavigatorMessages.resources_ProjectExplorer_toolTip,
new String[] { workingSetLabel });
return NLS.bind(WorkbenchNavigatorMessages.resources_ProjectExplorer_toolTip2, new String[] {
result, workingSetLabel });
}
// Working set mode. During initialization element and viewer can
// be null.
if (element != null && !(element instanceof IWorkingSet)
&& getCommonViewer() != null) {
FrameList frameList = getCommonViewer().getFrameList();
// Happens during initialization
if (frameList == null)
return result;
int index = frameList.getCurrentIndex();
IWorkingSet ws = null;
while (index >= 0) {
Frame frame = frameList.getFrame(index);
if (frame instanceof TreeFrame) {
Object input = ((TreeFrame) frame).getInput();
if (input instanceof IWorkingSet && !(input instanceof IAggregateWorkingSet)) {
ws = (IWorkingSet) input;
break;
}
}
index--;
}
if (ws != null) {
return NLS.bind(WorkbenchNavigatorMessages.resources_ProjectExplorer_toolTip3,
new String[] { ws.getLabel(), result });
}
return result;
}
return result;
}
/**
* @param mode
* @noreference This method is not intended to be referenced by clients.
* @since 3.4
*/
public void setRootMode(int mode) {
rootMode = mode;
}
/**
* @return the root mode
* @noreference This method is not intended to be referenced by clients.
* @since 3.4
*/
public int getRootMode() {
return rootMode;
}
/**
* @param label
* @noreference This method is not intended to be referenced by clients.
* @since 3.4
*/
public void setWorkingSetLabel(String label) {
workingSetLabel = label;
}
/**
* @return the working set label
* @noreference This method is not intended to be referenced by clients.
* @since 3.4
*/
public String getWorkingSetLabel() {
return workingSetLabel;
}
}
| 6,184 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
ShieldIDECommandStartup.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/base_commons/net.heartsome.cat.common.ui.shield.resources/src/net/heartsome/cat/common/ui/shield/resources/ShieldIDECommandStartup.java | package net.heartsome.cat.common.ui.shield.resources;
import java.util.Set;
import net.heartsome.cat.common.ui.shield.AbstractShieldCommandStartup;
/**
* 在工作台初始化后,移除不需要用到的 ide(org.eclipse.ui org.eclipse.ui.views org.eclipse.ui.workbench.texteditor 插件提供) command。
* @author cheney
* @since JDK1.6
*/
public class ShieldIDECommandStartup extends AbstractShieldCommandStartup {
private final static String CONF_FILE_PATH = "/unusedIDECommand.ini";
@Override
protected Set<String> getUnusedCommandSet() {
return readUnusedCommandFromFile(CONF_FILE_PATH);
}
}
| 618 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
StringUtilsBasic.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/base_plugins/heartsome.java.tools.plugin/src/cn/org/tools/utils/string/StringUtilsBasic.java | /**
* StringUtilsBasic.java
*
* Version information :
*
* Date:Jan 13, 2010
*
* Copyright notice :
*/
package cn.org.tools.utils.string;
import java.text.MessageFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import cn.org.tools.utils.regexp.Regexp;
/**
* 所有关于字符串的基本操作.
* @author simon
* @version
* @since JDK1.6
*/
public class StringUtilsBasic {
/**
* 构造方法.
*/
protected StringUtilsBasic() {
throw new UnsupportedOperationException(); // prevents calls from subclass
}
/**
* 用新的字符串替换旧字符串中需要替换的字符(这个方法的特点是忽略了用作正则的特殊字符).
* @param line
* 需要做替换处理的字符串,如果为NULL,返回NULL
* @param oldString
* 替换的字符串,如果为NULL,返回 line
* @param newString
* 新的字符串,如果为NULL,返回空字符串
* @return String
* 经过处理后的字符串
*/
public static String replaceString(String line, String oldString, String newString) {
return replaceString(line, oldString, newString, false);
}
/**
* 用新的字符串替换旧字符串中需要替换的字符(这个方法的特点是忽略了用作正则的特殊字符).
* @param line
* 需要做替换处理的字符串,如果为 null,返回 null
* @param oldString
* 替换的字符串,如果为 null,返回 line
* @param newString
* 新的字符串,如果为 null,返回空字符串
* @param trimSingleQuotes
* 是否去除除首尾之外的单引号
* @return String
* 经过处理后的字符串
*/
public static String replaceString(String line, String oldString, String newString, boolean trimSingleQuotes) {
if (line == null) {
return null;
}
if (oldString == null) {
return line;
}
if (newString == null) {
newString = "";
}
if (trimSingleQuotes) {
newString = newString.replaceAll("\\\\", "\\\\\\\\");
newString = newString.replaceAll("'", "\\\\'");
}
int i = 0;
i = line.indexOf(oldString, i);
if (i >= 0) {
char[] line2 = line.toCharArray();
char[] newString2 = newString.toCharArray();
int oLength = oldString.length();
StringBuffer buf = new StringBuffer(line2.length);
buf.append(line2, 0, i).append(newString2);
i += oLength;
int j = i;
while ((i = line.indexOf(oldString, i)) > 0) {
buf.append(line2, j, i - j).append(newString2);
i += oLength;
j = i;
}
buf.append(line2, j, line2.length - j);
return buf.toString();
}
return line;
}
/**
* 空值检测.
* @param data
* 要检查的字符串
* @return String
* 如果传入的字符串为 null,返回空串“”,否则返回 data
*/
public static String checkNullStr(String data) {
if (data == null) {
return "";
}
return data;
}
/**
* 如果传入的字符串为 null 或空字符串 则返回 returnValue 空值检测.
* @param data
* 要检查的字符串
* @param returnValue
* data 为空或者 data 中无实际数据时返回的值
* @return String
* data 为空或者 data 中无实际数据时,返回returnValue;否则返回 data
*/
public static String checkNullStr(String data, String returnValue) {
if (data == null || "".equals(data.trim())) {
return returnValue;
}
return data;
}
/**
* 去除字符串 data 首尾的逗号.
* @param data
* 要处理的字符串
* @return String
* 如果 data 为空或者 data 中无实际数据,返回空串"";如果 data 以逗号开始或者结束,
* 则将 data 首尾的逗号删除后返回;否则返回 data
*/
public static String checkStrStartOrEndWithComma(String data) {
if (data == null || "".equals(data.trim())) {
return "";
}
data = data.trim();
if (data.startsWith(",")) {
data = data.substring(data.indexOf(",") + 1, data.length());
}
if (data.endsWith(",")) {
data = data.substring(0, data.lastIndexOf(","));
}
return data;
}
/**
* 去除字符串 data 首尾的 regex 字符串
* @param data
* 要处理的字符串
* @param regex
* data 首尾要删除的字符串
* @return String
* 如果 data 为空或者 data 中无实际数据,返回空串"";如果 data 以 regex 开始或者结束,
* 则将 data 首尾的 regex 删除后返回;否则返回 data
*/
public static String checkStrStartOrEndWithComma(String data, String regex) {
if (data == null || "".equals(data.trim())) {
return "";
}
data = data.trim();
if (data.startsWith(regex)) {
data = data.substring(data.indexOf(regex) + 1, data.length());
}
if (data.endsWith(regex)) {
data = data.substring(0, data.lastIndexOf(regex));
}
return data;
}
/**
* 空值检测.
* @param data
* 要检查的字符串
* @return boolean
* false:空值或者空字符串;true:非空
*/
public static boolean checkNull(String data) {
if (data == null || "".equals(data.trim())) {
return false;
}
data = data.replaceAll(" ", "");
if ("".equals(data.trim())) {
return false;
}
return true;
}
/**
* 空值检测.
* @param data
* 要检查的字符串
* @return boolean
* false:空值或者空字符串;true:非空
*/
public static boolean checkNull(StringBuffer data) {
if (data == null || "".equals(data.toString().trim())) {
return false;
}
String dataStr = data.toString();
dataStr = dataStr.replaceAll(" ", "");
if ("".equals(dataStr.trim())) {
return false;
}
return true;
}
/**
* 清空StringBuffer中的值.
* @param strbf
* 需要被清空的 StringBuffer
* @return StringBuffer
* 清空后的 StringBuffer
*/
public static StringBuffer clearStringBuffer(StringBuffer strbf) {
return strbf.delete(0, strbf.length());
}
/**
* 判断参数 str 是否存在于参数 src 中(即 str 是否是 src 的一个子串).
* @param src
* 用逗号隔开的字符串,例如 simon,terry,steven
* @param str
* 用来判断是否存在的参数,例如 simon 或者 arlene
* @return boolean
* true 表示存在,false 表示不存在;src 或者 str 为空时,返回 false
*/
public static boolean checkExistStr(String src, String str) {
if (!checkNull(src)) {
return false;
}
if (!checkNull(str)) {
return false;
}
return (("," + src + ",").indexOf("," + str + ",") != -1);
}
/**
* 在字符串 src 中去除字符串 str,并保持 str 原有的逗号隔开的规则.
* @param src
* 用逗号隔开的字符串,例如 simon,terry,steven
* @param str
* 去除的参数,例如 simon 或者 arlene
* @return String
* 用逗号隔开的字符串。src 或者 str 为空时,返回 stc
*/
public static String removeExistStr(String src, String str) {
if (!checkNull(src) || !checkNull(str)) {
return src;
}
String result = replaceString("," + src + ",", "," + str, "");
if (result.length() != 1) {
return result.substring(1, result.length() - 1);
} else {
return "";
}
}
/**
* 判断两个字符串数组中有没有重复项.
* @param str1
* 字符串数组1
* @param str2
* 字符串数组2
* @return boolean
* true: 有重复项;false:没有重复项。str1 或者 str2 为空时,返回 false
*/
public static boolean checkExist(String[] str1, String[] str2) {
if (str1 == null || str2 == null) {
return false;
}
List<String> list = Arrays.asList(str2);
for (String str : str1) {
if (list.contains(str)) {
return true;
}
}
return false;
}
/**
* 用字符串数组 replace 中的字符串去替换 source 中的相应字符串.
* 如 source="The disk \"{1}\" contains {0} file(s)."
* replace=new String[]{"1","MyDisk"},则经过该方法处理后的字符串为
* The disk "MyDisk" contains 1 file(s).如果 replace 的长度大于source中的空余位置的个数(即source中{0},{1}...的个数),
* 则超过的部分舍弃,如果 source 中无空余位置,则该方法返回 source
* @param source
* 要替换的字符串
* @param replace
* 替换的字符串数组
* @return String
* 经过替换后的字符串。如果 source 为 null,返回 null;如果 replace 为 null,返回source
*/
public static String replaceString(String source, String[] replace) {
if (source == null) {
return null;
}
MessageFormat message = new MessageFormat(source);
return message.format(replace);
}
/**
* 检查 str 的长度.
* @param str
* 要检查的字符串
* @return boolean
* 如果 str 中有实际数据(即 str 不是只有空格或者换行符组成的字符串),返回 true,否则返回 false
*/
public static boolean hasLength(String str) {
return str != null && str.trim().length() > 0;
}
/**
* 将 value 中 按 separator 分隔的字符串数组替换为 map 中的 value 值(map 中的 key 为要替换的字符串).
* 如:value="abc-def-ghi",separator="-",map中有一个元素,key 为 abc, value 为 123,则经过该方法处理后
* 返回的字符串为 "123-def-ghi"
* @param value
* 要处理的字符串
* @param separator
* 分隔符
* @param map
* key 为 要替换的字符串(也是 value 中按 separator 拆分的字符串数组中的某一项),value 为 新的字符串
* @return String
* 经过处理后的字符串,如果 map 为空,返回 value; 如果 map 中无 value 中按 separator 拆分的字符串数组中的
* 任意一项(即没有可替换的字符串),则返回 value
*/
public static String replaceSeparator(String value, String separator, Map<String, String> map) {
if (map == null || map.size() == 0) {
return value;
}
StringBuilder sb = new StringBuilder();
String[] valueSplit = value.split(separator);
for (int i = 0; i < valueSplit.length; i++) {
String replace = map.get(valueSplit[i]);
if (null != replace && !"".equals(replace)) {
sb.append(replace);
} else {
sb.append(valueSplit[i]);
}
if (i < valueSplit.length - 1) {
sb.append(separator);
}
}
return sb.toString();
}
/**
* 获取字符串 str 在字符串 srcStr 中出现第index次的位置,index范围不符合逻辑返回-1.
* 如:indexOf("abcabdabe","ab",2)=6
* @param srcStr
* 任意字符串
* @param str
* 要搜索的子字符串
* @param index
* str 在 srcStr 中出现的次数
* @return int
* str 在 srcStr 中出现第index次的位置
*/
public static int indexOf(String srcStr, String str, int index) {
if (index == 0) {
return -1;
}
if (index == 1) {
return srcStr.indexOf(str);
}
return srcStr.indexOf(str, indexOf(srcStr, str, index - 1) + str.length());
}
/**
* 比较 string 的字符长度与 maxLength 的关系,一个汉字代表两个字符.
* @param string
* 任意字符串
* @param maxLength
* 规定的最大长度
* @return boolean
* 如果 string 的字符长度不大于 maxLength, 返回 true;如果 string 为空,返回 true;否则返回 false
*/
public static boolean checkMaxLength(String string, int maxLength) {
if (string == null) {
return true;
}
return string.replaceAll("[^\\x00-\\xff]", "**").length() <= maxLength;
}
/**
* 按规定的长度拆分字符串.
* @param string
* 任意字符串
* @param length
* 指定的长度
* @return String[]
* 按指定长度拆分后的字符串数组,如果 string 为 null,返回 null
*/
public static String[] splitString(String string, int length) {
if (string == null) {
return null;
}
char[] bytes = string.toCharArray();
int resultLength = bytes.length / length + 1;
String[] result = new String[resultLength];
for (int i = 0; i < resultLength; i++) {
if (i == resultLength - 1) {
result[i] = new String(bytes, i * length, bytes.length - i * length);
} else {
result[i] = new String(bytes, i * length, length);
}
}
return result;
}
/**
* 获取随机数字符串.
* @return String
* 随机数字符串.
*/
public static String getRandomStr() {
StringBuilder sb = new StringBuilder();
sb.append(System.currentTimeMillis());
sb.append(new Random().nextInt(10000));
return sb.toString();
}
/**
* 将 String 列表转化成字符串,格式是:1,2,3,4,...
* @param list
* 要处理的字符串集合
* @return String
* list 转化后的字符串,如果 list 为 null 或者 list 中无数据,返回空串""
*/
public static String listToString(List<String> list) {
if (list == null || list.size() == 0) {
return "";
}
String temp = list.toString();
return temp.substring(1, temp.length() - 1);
}
/**
* 将 String 列表转化成字符串,格式是:'1','2','3','4',...
* @param list
* 要处理的字符串集合
* @return String
* list 转化后的字符串,如果 list 为 null 或者 list 中无数据,返回空串""
*/
public static String listToStringWithSingleQuote(List<String> list) {
if (list == null || list.size() == 0) {
return "";
}
List<String> newList = new ArrayList<String>();
for (String temp : list) {
newList.add("'" + temp + "'");
}
return listToString(newList);
}
/**
* 将字符串的两端都加上单引号('), 如:singleQuote("a")="'a'"
* @param source
* 任意字符串
* @return String
* source 两端加上单引号的字符串
*/
public static String singleQuote(String source) {
return "'" + source + "'";
}
/**
* 将字符串str按中英文分组,如:str="123测试test",则返回值为[1123, 0测试, 1test],
* 其中List中的每个字符串的首字符为标志位,1代表英文,0代表中文;如果str为空字符串,则返回null
* @param str
* 任意字符串
* @return List<String>
* str 按中英文分组后的字符串集合
*/
public static List<String> getChineseAndEnglish(String str) {
List<String> strList = new ArrayList<String>();
if (str == null || str.trim().equals("")) {
return null;
}
char[] ch = str.toCharArray();
for (int i = 0; i < ch.length; i++) {
if (i == 0) {
if (isChinese(ch[i])) {
strList.add("0" + ch[i]);
} else {
strList.add("1" + ch[i]);
}
} else {
if (isChinese(ch[i]) && isChinese(ch[i - 1])) {
String s = strList.get(strList.size() - 1);
s += ch[i];
strList.remove(strList.size() - 1);
strList.add(s);
} else if (!isChinese(ch[i]) && !isChinese(ch[i - 1])) {
String s = strList.get(strList.size() - 1);
s += ch[i];
strList.remove(strList.size() - 1);
strList.add(s);
} else {
if (isChinese(ch[i])) {
strList.add("0" + ch[i]);
} else {
strList.add("1" + ch[i]);
}
}
}
}
return strList;
}
/**
* 判断字符c是否为中文
* @param c
* 要判断的字符c
* @return boolean
* true:中文,false:英文
*/
public static boolean isChinese(char c) {
Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);
if (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS
|| ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS
|| ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A
|| ub == Character.UnicodeBlock.GENERAL_PUNCTUATION //GENERAL_PUNCTUATION 判断中文的“号
|| ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION //CJK_SYMBOLS_AND_PUNCTUATION 判断中文的。号
|| ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS) //HALFWIDTH_AND_FULLWIDTH_FORMS 判断中文的,号
{
return true;
}
return false;
}
/**
* 判断字符串是否是由小数组成
* @param str
* 要检查的字符串
* @return boolean
* true: str 由小数组成
*/
public static boolean isFloat(String str) {
Pattern patternFig = Pattern.compile(Regexp.RATIONAL_NUMBERS_REGEXP);
Matcher matcherFig = patternFig.matcher(str);
return matcherFig.matches();
}
/**
* 判断字符串是否为日期
* @param str
* 要判断的字符串
* @param format
* 日期格式,按该格式检查字符串
* @return boolean
* 符合为true,不符合为false
*/
public static boolean isDate(String str, String format) {
if (hasLength(str)) {
SimpleDateFormat formatter = new SimpleDateFormat(format);
formatter.setLenient(false);
try {
formatter.format(formatter.parse(str));
} catch (Exception e) {
return false;
}
return true;
}
return false;
}
} | 17,110 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
StringUtilsText.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/base_plugins/heartsome.java.tools.plugin/src/cn/org/tools/utils/string/StringUtilsText.java | /**
* StringUtilsText.java
*
* Version information :
*
* Date:Jan 13, 2010
*
* Copyright notice :
*/
package cn.org.tools.utils.string;
/**
* 涉及文本內容的字符串操作.该类继承了 StringUtilsBasic,自己无任何属性或方法
* @author simon
* @version
* @since JDK1.6
*/
public class StringUtilsText extends StringUtilsBasic {
}
| 368 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
StringUtilsHtml.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/base_plugins/heartsome.java.tools.plugin/src/cn/org/tools/utils/string/StringUtilsHtml.java | /**
* StringUtilsHtml.java
*
* Version information :
*
* Date:Jan 13, 2010
*
* Copyright notice :
*/
package cn.org.tools.utils.string;
import java.util.ArrayList;
/**
* 所有关于 HTML 文档的基本操作.
* @author Terry
* @version
* @since JDK1.6
*/
public class StringUtilsHtml extends StringUtilsBasic {
/**
* 获得 html 格式的单元格,用于设置 table 中的表头。
* @param value
* 单元格的值
* @param align
* 对齐方式。较常用的三个值:"center","left","right"
* @param width
* 单元格的宽度
* @param colspan
* 单元格所占列数
* @param rowspan
* 单元格所占行数
* @return String
* html 格式的 td 标签
*/
public static String getHtmlTdHead(String value, String align, String width, int colspan, int rowspan) {
StringBuilder htmlStr = new StringBuilder();
htmlStr.append("<td align='" + align + "' width='" + width + "' bgcolor='#c3cfdf'");
if (colspan > 1) {
htmlStr.append("colspan='" + colspan + "'");
}
if (rowspan > 1) {
htmlStr.append("rowspan='" + rowspan + "'");
}
htmlStr.append("><p><b>" + value + "</b></p></td>");
return htmlStr.toString();
}
/**
* 获得 html 格式的单元格,用于设置 table 中的表头,此种方式对创建的单元格设置了样式(若使表头固定,width参数可以传入"0%")。
* @param value
* 单元格的值
* @param align
* 对齐方式。较常用的三个值:"center","left","right"
* @param width
* 单元格的宽度
* @param colspan
* 单元格所占列数
* @param rowspan
* 单元格所占行数
* @return String
* html 格式的 td 标签
*/
public static String getHtmlTdHead2(String value, String align, String width, int colspan, int rowspan) {
StringBuilder htmlStr = new StringBuilder();
htmlStr.append("<td align='" + align + "' bgcolor='#c3cfdf'");
if (Integer.parseInt(width.substring(0, width.length() - 1)) > 0) {
htmlStr.append(" width='" + width + "'");
}
htmlStr.append(" style='BORDER-RIGHT: #555 1px solid;BORDER-TOP: #fff 1px solid;BORDER-BOTTOM: #555 1px solid;BORDER-LEFT: #fff 1px solid;TEXT-ALIGN:center;font-size:10pt'");
if (colspan > 1) {
htmlStr.append("colspan='" + colspan + "'");
}
if (rowspan > 1) {
htmlStr.append("rowspan='" + rowspan + "'");
}
htmlStr.append(">" + value + "</td>");
return htmlStr.toString();
}
/**
* 获得 html 格式的单元格,用于设置 table 中的表头。
* @param value
* 单元格的值
* @param align
* 对齐方式。较常用的三个值:"center","left","right"
* @param width
* 单元格的宽度
* @param colspan
* 单元格所占列数
* @param rowspan
* 单元格所占行数
* @param fontsize
* 字体大小
* @return String
* html 格式的 td 标签
*/
public static String getHtmlTdHead(String value, String align, String width, int colspan, int rowspan, int fontsize) {
StringBuilder htmlStr = new StringBuilder();
htmlStr.append("<td align='" + align + "' width='" + width + "' bgcolor='#c3cfdf'");
if (colspan > 1) {
htmlStr.append("colspan='" + colspan + "'");
}
if (rowspan > 1) {
htmlStr.append("rowspan='" + rowspan + "'");
}
htmlStr.append("><p style='font-size: " + fontsize + "pt'><b>" + value + "</b></p></td>");
return htmlStr.toString();
}
/**
* 获得 html 的头.
* @return String
* html 的头.
*/
public static String getHtmlHead() {
StringBuilder htmlStr = new StringBuilder();
htmlStr
.append("<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" /></head><body>");
return htmlStr.toString();
}
/**
* 获得 html 的头,此方式对 html 文档规定了命名空间
* @return the String
* html 的头.
*/
public static String getHtmlHead2() {
StringBuilder htmlStr = new StringBuilder();
htmlStr
.append("<html xmlns=\"http://www.w3.org/1999/xhtml\"><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />");
return htmlStr.toString();
}
/**
* 获得 html 的 DOCTYPE 标签
* @return String
* html 的 DOCTYPE 标签
*/
public static String getHtmlDoctype() {
StringBuilder htmlStr = new StringBuilder();
htmlStr
.append("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">");
return htmlStr.toString();
}
/**
* 获得 html 的 css 样式
* @return String
* 字符串形式的 css 样式
*/
public static String getHtmlCssStyle() {
StringBuilder htmlStr = new StringBuilder();
htmlStr.append("<style type=\"text/css\">\n");
htmlStr.append("<!--\n");
htmlStr.append(".griddiv{\n");
// htmlStr.append("overflow-x:hidden;\n");
// htmlStr.append("border:black 1px solid; \n");
htmlStr.append("BACKGROUND: #F8F9FC;\n");
htmlStr.append("position:relative;\n");
htmlStr.append("text-align:center;\n");
htmlStr.append("}\n");
htmlStr.append(".title /* 新建表头样式 */{\n");
htmlStr.append("height:30px; \n");
htmlStr.append("line-height:30px; \n");
htmlStr.append("overflow:hidden; \n");
htmlStr.append("text-align:center;\n");
htmlStr.append("BORDER-RIGHT: #555 1px solid;\n");
htmlStr.append("BORDER-TOP: #fff 1px solid;\n");
htmlStr.append("BORDER-BOTTOM: #555 1px solid;\n");
htmlStr.append("BORDER-LEFT: #fff 1px solid;\n");
// htmlStr.append("padding:2 1 2 2;\n");用以下4行代替
htmlStr.append("padding-top:2;\n");
htmlStr.append("padding-right:1;\n");
htmlStr.append("padding-bottom:2;\n");
htmlStr.append("padding-left:1;\n");
htmlStr.append("BACKGROUND: #c3cfdf;\n");
htmlStr.append("Font-Size:12pt;\n");
htmlStr.append("Font-Family:Albany AMT,Arial,Lucida Sans;\n");
htmlStr.append("WHITE-SPACE: nowrap;\n");
htmlStr.append("position:relative;\n");
htmlStr.append("display:inline-block;\n");
htmlStr.append("}\n");
htmlStr.append("td{\n");
htmlStr.append("WHITE-SPACE: nowrap;\n");
htmlStr.append("BORDER: #ddd 1px solid;\n");
htmlStr.append("}\n");
htmlStr.append(".cdata {\n");
// htmlStr.append("padding:1 1 1 2;\n");
htmlStr.append("padding-top:1;\n");
htmlStr.append("padding-right:1;\n");
htmlStr.append("padding-bottom:1;\n");
htmlStr.append("padding-left:2;\n");
htmlStr.append("Font-Size:9pt;\n");
htmlStr.append("}\n");
htmlStr.append(".noborder{\n");
htmlStr.append("BORDER: #ddd 0px solid;\n");
htmlStr.append("}\n");
htmlStr.append("-->\n");
htmlStr.append("</style>\n");
return htmlStr.toString();
}
/**
* 获得 html 格式的 table 标签。
* @return String
* html 格式的 table 标签。
*/
public static String getHtmlTable() {
StringBuilder htmlStr = new StringBuilder();
htmlStr.append("<table cellspacing='1' cellpadding='5' "
+ "style='font-size:10pt;font-family:Albany AMT,Arial,Lucida Sans;margin:5px 30px;' width='100%'>\n");
return htmlStr.toString();
}
/**
* 获得 html 格式的单元格,用于设置 table 中的单元格。
* @param value
* 单元格的值
* @param align
* 对齐方式。较常用的三个值:"center","left","right"
* @param width
* 单元格的宽度
* @param colspan
* 单元格所占列数
* @param rowspan
* 单元格所占行数
* @return String
* html 格式的 td 标签
*/
public static String getHtmlTdBody(String value, String align, String width, int colspan, int rowspan) {
StringBuilder htmlStr = new StringBuilder();
htmlStr.append("<td align='" + align + "' width='" + width + "' bgcolor='#e9f0fa'");
if (colspan > 1) {
htmlStr.append(" colspan='" + colspan + "'");
}
if (rowspan > 1) {
htmlStr.append(" rowspan='" + rowspan + "'");
}
htmlStr.append("><p>" + value + "</p></td>\n");
return htmlStr.toString();
}
/**
* 获得 html 格式的单元格,用于设置 table 中的单元格。
* @param value
* 单元格的值
* @param align
* 对齐方式。较常用的三个值:"center","left","right"
* @param colspan
* 单元格所占列数
* @param rowspan
* 单元格所占行数
* @return String
* html 格式的 td 标签
*/
public static String getHtmlTdBody(String value, String align, int colspan, int rowspan) {
StringBuilder htmlStr = new StringBuilder();
htmlStr.append("<td align='" + align + "' bgcolor='#e9f0fa'");
if (colspan > 1) {
htmlStr.append(" colspan='" + colspan + "'");
}
if (rowspan > 1) {
htmlStr.append(" rowspan='" + rowspan + "'");
}
htmlStr.append("><p>" + value + "</p></td>\n");
return htmlStr.toString();
}
/**
* 获得 html 格式的单元格,用于设置 table 中的单元格。
* 该方法在 value 的两端分别加了 num 个空格,目的是在固定表头的情况下保证列宽与表头列宽一致
* @param value
* 单元格的值
* @param align
* 对齐方式。较常用的三个值:"center","left","right"
* @param colspan
* 单元格所占列数
* @param rowspan
* 单元格所占行数
* @param num
* 在 value 两端所加空格的个数
* @return String
* html 格式的 td 标签
*/
public static String getHtmlTdBodyAddBlank(String value, String align, int colspan, int rowspan, int num) {
StringBuilder htmlStr = new StringBuilder();
htmlStr.append("<td align='" + align + "' bgcolor='#e9f0fa' ");
htmlStr.append(" style='TEXT-ALIGN:" + align + ";font-size:10pt'");
if (colspan > 1) {
htmlStr.append(" colspan='" + colspan + "'");
}
if (rowspan > 1) {
htmlStr.append(" rowspan='" + rowspan + "'");
}
htmlStr.append("><p>");
if (align.equals("center")) {
if (num > 0) {
for (int i = 1; i <= num; i++) {
htmlStr.append(" ");
}
}
htmlStr.append(value);
if (num > 0) {
for (int i = 1; i <= num; i++) {
htmlStr.append(" ");
}
}
} else if (align.equals("left")) {
htmlStr.append(value);
if (num > 0) {
for (int i = 1; i <= num * 2; i++) {
htmlStr.append(" ");
}
}
} else if (align.equals("right")) {
if (num > 0) {
for (int i = 1; i <= num * 2; i++) {
htmlStr.append(" ");
}
}
htmlStr.append(value);
} else {
htmlStr.append(value);
}
htmlStr.append("</p></td>\n");
return htmlStr.toString();
}
/**
* 获得 html 格式的单元格,用于设置 table 中的单元格。
* 该方法在 value 的两端分别加了 num 个空格,目的是在固定表头的情况下保证列宽与表头列宽一致
* @param value
* 单元格的值
* @param align
* 对齐方式。较常用的三个值:"center","left","right"
* @param colspan
* 单元格所占列数
* @param rowspan
* 单元格所占行数
* @param num
* 在 value 两端所加空格的个数
* @return String
* html 格式的 td 标签
*/
public static String getHtmlTdBodyAddBlank(String value, String align, int colspan, int rowspan, int num, boolean isWrap) {
StringBuilder htmlStr = new StringBuilder();
htmlStr.append("<td align='" + align + "' bgcolor='#e9f0fa' ");
htmlStr.append(" style='TEXT-ALIGN:" + align + ";font-size:10pt");
if (isWrap) {
htmlStr.append(";word-break:break-all");
}
htmlStr.append("'");
if (colspan > 1) {
htmlStr.append(" colspan='" + colspan + "'");
}
if (rowspan > 1) {
htmlStr.append(" rowspan='" + rowspan + "'");
}
htmlStr.append("><p>");
if (align.equals("center")) {
if (num > 0) {
for (int i = 1; i <= num; i++) {
htmlStr.append(" ");
}
}
htmlStr.append(value);
if (num > 0) {
for (int i = 1; i <= num; i++) {
htmlStr.append(" ");
}
}
} else if (align.equals("left")) {
htmlStr.append(value);
if (num > 0) {
for (int i = 1; i <= num * 2; i++) {
htmlStr.append(" ");
}
}
} else if (align.equals("right")) {
if (num > 0) {
for (int i = 1; i <= num * 2; i++) {
htmlStr.append(" ");
}
}
htmlStr.append(value);
} else {
htmlStr.append(value);
}
htmlStr.append("</p></td>\n");
return htmlStr.toString();
}
/**
* 获得 html 格式的单元格,用于设置 table 中的单元格。
* @param value
* 单元格的值
* @param align
* 对齐方式。较常用的三个值:"center","left","right"
* @param width
* 单元格的宽度
* @param colspan
* 单元格所占列数
* @param rowspan
* 单元格所占行数
* @param fontsize
* 字体大小
* @return String
* html 格式的 td 标签
*/
public static String getHtmlTdBody(String value, String align, String width, int colspan, int rowspan, int fontsize) {
StringBuilder htmlStr = new StringBuilder();
htmlStr.append("<td align='" + align + "' width='" + width + "' bgcolor='#e9f0fa'");
if (colspan > 1) {
htmlStr.append(" colspan='" + colspan + "'");
}
if (rowspan > 1) {
htmlStr.append(" rowspan='" + rowspan + "'");
}
htmlStr.append("><p style='font-size: " + fontsize + "pt'>" + value + "</p></td>\n");
return htmlStr.toString();
}
/**
* 获得 html 格式的单元格,用于设置 table 中的单元格。
* @param value
* 单元格的值
* @param align
* 对齐方式。较常用的三个值:"center","left","right"
* @param width
* 单元格的宽度
* @param colspan
* 单元格所占列数
* @param rowspan
* 单元格所占行数
* @param fontsize
* 字体大小
* @param id
* 单元格的 id
* @param display
* 显示框类型
* @return String
* html 格式的 td 标签
*/
public static String getHtmlTdBody(String value, String align, String width, int colspan, int rowspan,
int fontsize, String id, String display) {
StringBuilder htmlStr = new StringBuilder();
htmlStr.append("<td align='" + align + "' width='" + width + "' bgcolor='#e9f0fa' id='" + id
+ "' style='display:" + display + "; ' ");
if (colspan > 1) {
htmlStr.append(" colspan='" + colspan + "'");
}
if (rowspan > 1) {
htmlStr.append(" rowspan='" + rowspan + "'");
}
htmlStr.append("><p style='font-size: " + fontsize + "pt'>" + value + "</p></td>\n");
return htmlStr.toString();
}
/**
* 获得 html 格式的单元格,用于设置 table 中的单元格。
* @param value
* 单元格的值
* @param align
* 对齐方式。较常用的三个值:"center","left","right"
* @param width
* 单元格的宽度
* @param color
* 单元格的背景颜色
* @param colspan
* 单元格所占列数
* @param rowspan
* 单元格所占行数
* @param bold
* 是否加粗
* @return String
* html 格式的 td 标签
*/
public static String getHtmlTdBody(String value, String align, String width, String color, int colspan,
int rowspan, boolean bold) {
StringBuilder htmlStr = new StringBuilder();
htmlStr.append("<td align='" + align + "' width='" + width + "' bgcolor='" + color + "'");
if (colspan > 1) {
htmlStr.append(" colspan='" + colspan + "'");
}
if (rowspan > 1) {
htmlStr.append(" rowspan='" + rowspan + "'");
}
if (bold) {
htmlStr.append("><b>" + value + "</b></td>\n");
} else {
htmlStr.append("><p>" + value + "</p></td>\n");
}
return htmlStr.toString();
}
/**
* 返回带颜色的字符串.
* @param data
* 任意字符串
* @param color
* 颜色名(如“red”),多个颜色之间以逗号分隔
* @return String
* 带颜色的字符串.
*/
public static String getStrByColor(String data, String color) {
String result = "";
if (!StringUtilsBasic.checkNull(color)) {
return data;
} else {
if (color.indexOf(",") > -1) {
result = "<font color='(" + color + ")'>" + data + "</font>";
} else {
result = "<font color='" + color + "'>" + data + "</font>";
}
}
return result;
}
/**
* 返回换行后的字符串,用于表头固定的表格中的某一列
* @param value
* 要处理的字符串
* @param perRowLen
* 每行的长度
* @return ;
*/
public static String getWrapString(String value, int perRowLen) {
int inputLen = value.getBytes().length;
if (inputLen > perRowLen) {
String input2 = value.replace(",", "").replace("。", "").replace("!", "").replace("……", "").replace("[", "")
.replace("]", "").replace("(", "").replace(")", "").replace("“", "").replace("”", "").replace("?", "")
.replace("、", "").replace(";", "").replace(":", "").replace("‘", "").replace("’", "").replace("《", "")
.replace("》", "").replace("{", "").replace("}", "").replace("——", "");
if (input2.length() == input2.getBytes().length && value.contains(" ")) {
//input 为英文
//将每个单词放进数组中
String[] inputWord = value.split(" ");
String text = "";
//存放每行的数据
ArrayList<String> txtList = new ArrayList<String>();
String[] signArr = new String[]{",", ",", ".", "。", "!", "!", "……", "?", "?", "/"};
for (int i = 0; i < inputWord.length; i++) {
String str = inputWord[i];
if (text.length() < perRowLen && text.length() + str.length() > perRowLen) {
boolean isContainSign = false;
//判断str是否包含标点符号
for (String sign : signArr) {
if (str.contains(sign)) {
String str1 = str.substring(0, str.lastIndexOf(sign) + 1);
txtList.add(text + " " + str1);
text = str.substring(str.lastIndexOf(sign) + 1);
isContainSign = true;
break;
}
}
if (!isContainSign && text.length() + str.length() > perRowLen + 5) {
txtList.add(text);
text = str;
} else if (!isContainSign && text.length() == 0) {
text += str;
txtList.add(text);
text = "";
} else if (!isContainSign) {
text += " " + str;
txtList.add(text);
text = "";
}
} else if (text.length() < perRowLen) {
if (text.length() == 0) {
text += str;
} else {
text += " " + str;
}
if (i == inputWord.length - 1) {
txtList.add(text);
text = "";
}
} else {
boolean isSign = false;
for (String sign : signArr) {
if (str.contains(sign)) {
String str1 = str.substring(0, str.lastIndexOf(sign) + 1);
txtList.add(text + " " + str1);
text = str.substring(str.lastIndexOf(sign) + 1);
isSign = true;
break;
}
}
if (!isSign) {
text += " " + str;
txtList.add(text);
text = "";
}
}
}
value = "";
for (String s : txtList) {
value = value.concat(s + "<br>");
}
if (value.length() > 4) {
value = value.substring(0, value.length() - 4);
}
} else {
//input 为中文或者一个无空格的英文字符串
String subStr = "";
// if (title.matches("[\\u4e00-\\u9fbb]+")) {
char[] ch = value.toCharArray();
double len = 0;
for (char c : ch) {
Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);
//如果第一个字符是标点符号,则该标点符号移到上一行
if (len == 0 && (ub == Character.UnicodeBlock.GENERAL_PUNCTUATION //判断中文的“号
|| ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION //判断中文的。号
|| ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS //判断中文的,号
)) {
if (subStr.length() > 4) {
subStr = subStr.substring(0, subStr.length() - 4) + c + "<br>";
} else {
subStr = c + "";
}
continue;
} else {
subStr += c;
}
if ((int) c >= 0x4E00 && (int) c <= 0x9FA5) {
len += 2.5;
} else {
len += 1;
}
if (len >= perRowLen) {
subStr += "<br>";
len = 0;
}
}
value = subStr;
}
}
return value;
}
}
| 20,419 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
StringUtilsSql.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/base_plugins/heartsome.java.tools.plugin/src/cn/org/tools/utils/string/StringUtilsSql.java | /**
* StringUtilsSql.java
*
* Version information :
*
* Date:Jan 13, 2010
*
* Copyright notice :
*/
package cn.org.tools.utils.string;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import cn.org.tools.utils.constant.Constants;
/**
* 涉及拼凑SQL语句的字符串操作.
* @author simon
* @version
* @since JDK1.6
*/
public class StringUtilsSql extends StringUtilsBasic {
/** The sqllist. */
private List<String> sqllist;
/** The add sql map. */
private HashMap<String, String> addSqlMap;
/** The subname. */
private StringBuffer subname;
/** The subvalue. */
private StringBuffer subvalue;
/** The temp. */
private StringBuffer temp;
/** The Constant OPERATOR_LIKE. */
public static final String OPERATOR_LIKE = "like";
/** The Constant OPERATOR_EQUALS. */
public static final String OPERATOR_EQUALS = "=";
/** The Constant OPERATOR_GREATER. */
public static final String OPERATOR_GREATER = ">";
/** The Constant OPERATOR_LESS. */
public static final String OPERATOR_LESS = "<";
/** The Constant OPERATOR_GREATER_EQUALS. */
public static final String OPERATOR_GREATER_EQUALS = ">=";
/** The Constant OPERATOR_LESS_EQUALS. */
public static final String OPERATOR_LESS_EQUALS = "<=";
/**
* 获得 sql 条件语句.
* @param colName
* 数据库列名
* @param operator
* 操作符(使用本类中定义的操作符常量)
* @param value
* 列值
* @return String
* sql 条件语句
*/
public static String getCondition(String colName, String operator, String value) {
StringBuffer temp = new StringBuffer();
temp.append(colName);
if (OPERATOR_LIKE.equals(operator)) {
temp.append(" " + OPERATOR_LIKE + " '%" + value + "%'");
} else if (OPERATOR_EQUALS.equals(operator)) {
temp.append(" " + OPERATOR_EQUALS + " '" + value + "'");
} else if (OPERATOR_GREATER.equals(operator)) {
temp.append(" " + OPERATOR_GREATER + " '" + value + "'");
} else if (OPERATOR_LESS.equals(operator)) {
temp.append(" " + OPERATOR_LESS + " '" + value + "'");
} else if (OPERATOR_GREATER_EQUALS.equals(operator)) {
temp.append(" " + OPERATOR_GREATER_EQUALS + " '" + value + "'");
} else if (OPERATOR_LESS_EQUALS.equals(operator)) {
temp.append(" " + OPERATOR_LESS_EQUALS + " '" + value + "'");
}
return temp.toString();
}
/**
* 构造方法.
*/
public StringUtilsSql() {
sqllist = new ArrayList<String>();
addSqlMap = new LinkedHashMap<String, String>();
subname = new StringBuffer();
subvalue = new StringBuffer();
temp = new StringBuffer();
}
/**
* 清空数据。
*/
public void clear() {
StringUtilsBasic.clearStringBuffer(subname);
StringUtilsBasic.clearStringBuffer(subvalue);
StringUtilsBasic.clearStringBuffer(temp);
sqllist.clear();
addSqlMap.clear();
}
/**
* 获得 sql 语句.
* @param sql
* 进行查询的SQL语句,如果为空字符串,则根据传入的其它参数组成SQL语句
* @param orderby
* 进行排序的字段名
* @param tablename
* 如果参数 sql 为空字符串,则表示需要查询的表名,否则这个参数将忽略,如果 sql 和 tablename 同时为 null,返回空串""
* @param where
* 查询数据库时的 where 条件
* @param order
* 查询数据库时的排序方式,"ASC"为升序(默认),"DESC"为降序
* @param groupby
* 查询数据库时的分组字段。
* @return String
* 由传入参数组成的 sql 语句
*/
public static String getSql(String sql, String orderby, String tablename, String where, String order, String groupby) {
if (orderby == null) {
orderby = "";
}
if (sql == null && tablename == null) {
return "";
}
if (sql == null) {
sql = "";
}
if (where == null) {
where = "";
}
if (order == null) {
order = "";
}
if (groupby == null) {
groupby = "";
}
if ("".equals(sql)) {
sql = "select * from " + tablename + " where 1=1 " + where;
if (!"".equals(groupby)) {
sql += " group by " + groupby;
}
if (!"".equals(orderby)) {
sql += " order by " + orderby + " " + order;
}
} else {
if (!"".equals(groupby) && sql.indexOf("group by") < 0) {
sql += " group by " + groupby;
}
if ("".equals(orderby)) {
sql += where;
} else {
if (sql.indexOf("order") != -1) {
sql = sql.substring(0, sql.indexOf("order"));
}
sql += where + " order by " + orderby + " " + order;
}
}
return sql;
}
/**
* 获得查询记录数的 sql 语句
* @param sql
* 进行查询的SQL语句
* @return String
* 查询记录数的 sql 语句
*/
public String getCountSql(String sql) {
String countsql = "";
if (!"".equals(sql)) {
countsql = "select count(*) from (" + sql + ") a";
}
return countsql;
}
/**
* 将 sql 语句添加 limit 子句,查询从 startpos 开始(第一条记录为0)的 pagesize 条记录
* @param sql
* 进行查询的SQL语句
* @param startpos
* 开始记录
* @param pagesize
* 记录数
* @return String
* 添加了 limit 子句的 sql 语句
*/
public String getLimitSql(String sql, int startpos, int pagesize) {
String limitsql = "";
if (!"".equals(sql)) {
switch (Constants.DATABASE_TYPE) {
case Constants.DATABASE_TYPE_MYSQL:
limitsql = sql + " limit " + startpos + "," + pagesize;
break;
case Constants.DATABASE_TYPE_MSSQL:
break;
case Constants.DATABASE_TYPE_OROCALE:
break;
default:
break;
}
}
return limitsql;
}
}
| 5,688 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
DateUtilsBasic.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/base_plugins/heartsome.java.tools.plugin/src/cn/org/tools/utils/date/DateUtilsBasic.java | /**
* DateUtilsBasic.java
*
* Version information :
*
* Date:Jan 13, 2010
*
* Copyright notice :
*/
package cn.org.tools.utils.date;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Locale;
import java.util.Random;
import java.util.TimeZone;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import cn.org.tools.utils.constant.Constants;
import cn.org.tools.utils.string.StringUtilsBasic;
/**
* 所有关于日期的基本操作.
* @author Terry
* @version
* @since JDK1.6
*/
public class DateUtilsBasic {
/**
* 构造方法.
*/
protected DateUtilsBasic() {
throw new UnsupportedOperationException(); // prevents calls from subclass
}
/** The Constant YYYY_MM_DD_HH_MM_SS. */
public static final String YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss";
/** The Constant FULL. */
public static final int FULL = DateFormat.FULL;
/**
* 获取当前时间.
* @return String
* 以yyyy-MM-dd HH:mm:ss格式标准
*/
public static String getCurDate() {
SimpleDateFormat sdf = new SimpleDateFormat(YYYY_MM_DD_HH_MM_SS);
return sdf.format(new Date());
}
/**
* 获取当前时间前time的时间.
* @param time
* 毫秒数
* @return String
* 已格式化的时间字符串。
*/
public static String getCurDateBefore(long time) {
SimpleDateFormat sdf = new SimpleDateFormat(YYYY_MM_DD_HH_MM_SS);
return sdf.format(new Date().getTime() - time);
}
/**
* 获取当前日期
* @param format
* 日期/时间格式
* @return String
* 已格式化的时间字符串。
*/
public static String getCurDate(String format) {
SimpleDateFormat sdf = new SimpleDateFormat(format);
return sdf.format(new Date());
}
/**
* 将给定日期格式化为字符串.
* @param date
* 要格式化为时间字符串的时间值。
* @param format
* 日期/时间格式
* @return String
* 已格式化的时间字符串。
*/
public static String getDateStr(Date date, String format) {
SimpleDateFormat sdf = new SimpleDateFormat(format);
return sdf.format(date);
}
/**
* 获取现在的年份.
* @return int
* 公元年
*/
public static int getCurYear() {
return new GregorianCalendar().get(Calendar.YEAR);
}
/**
* 获取现在的月份.
* @return int
* 0表示年的第一个月
*/
public static int getCurMonth() {
return new GregorianCalendar().get(Calendar.MONTH);
}
/**
* 获取当前日期所在月份的天数,假如今天为 2011 年 5 月 3 日,则返回值为 3
* @return int
* 当前日期在当前月份中的天数,一个月中第一天的值为 1。
*/
public static int getCurDay() {
return new GregorianCalendar().get(Calendar.DAY_OF_MONTH);
}
/**
* GMT时间就是英国格林威治时间,也就是世界标准时间,是本初子午线上的地方时,是0时区的区时,与中国的标准时间北京时间(东八区)相差8小时,
* 即晚8小时。 获取现在的格林威治标准时间,也称格林尼治平均时.
* @return String
* 以 yyyyMMddTHHmmssZ 格式标准
*/
public static String getCurGMTDate() {
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
String sec = (calendar.get(Calendar.SECOND) < 10 ? "0" : "") + calendar.get(Calendar.SECOND);
String min = (calendar.get(Calendar.MINUTE) < 10 ? "0" : "") + calendar.get(Calendar.MINUTE);
String hour = (calendar.get(Calendar.HOUR_OF_DAY) < 10 ? "0" : "") + calendar.get(Calendar.HOUR_OF_DAY);
String mday = (calendar.get(Calendar.DATE) < 10 ? "0" : "") + calendar.get(Calendar.DATE);
String mon = (calendar.get(Calendar.MONTH) < 9 ? "0" : "") + (calendar.get(Calendar.MONTH) + 1);
String longyear = "" + calendar.get(Calendar.YEAR);
String date = longyear + mon + mday + "T" + hour + min + sec + "Z";
return date;
}
/**
* 将GMT格式时间的字符串转换为当前时间的字符串.
* @param strGMTDate
* 以yyyyMMddTHHmmssZ格式标准
* @return String
* 以默认语言环境的默认格式化风格的格式,如果发生异常,返回空串""
*/
public static String changeGMTDate2LocalDate(String strGMTDate) {
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
try {
int second = Integer.parseInt(strGMTDate.substring(13, 15));
int minute = Integer.parseInt(strGMTDate.substring(11, 13));
int hour = Integer.parseInt(strGMTDate.substring(9, 11));
int date = Integer.parseInt(strGMTDate.substring(6, 8));
int month = Integer.parseInt(strGMTDate.substring(4, 6)) - 1;
int year = Integer.parseInt(strGMTDate.substring(0, 4));
calendar.set(year, month, date, hour, minute, second);
DateFormat dt = DateFormat.getDateTimeInstance();
return dt.format(calendar.getTime());
} catch (Exception e) {
if (Constants.DEBUG) {
e.printStackTrace();
}
return "";
}
}
/**
* 获取日期字符串中的日,如果月 MM 大于12,则向年 yyyy 进位,日大于当月的最大日期,也向前进位 该方法不使用给定字符串的整个文本。.
* @param strdate
* 截取前 yyyy-MM-dd 模式的字符,将后面的字符舍去
* @return int
* 日期在月份中的天数,1表示第一天, 如果 strdate 不能成功的转换成 Date,返回-1
*/
public static int getDayOfDate(String strdate) {
int result = 0;
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date date = null;
try {
date = sdf.parse(strdate);
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
result = calendar.get(Calendar.DATE);
return result;
} catch (Exception e) {
if (Constants.DEBUG) {
e.printStackTrace();
}
return -1;
}
}
/**
* 获取字符串所表示的日期所在月份第一天的字符串(该类中的 getFirstDayOfMonth 也是同样的意义).
* @param strdate
* 要解析的日期字符串
* @return String
* 如果传入参数为 null 或者解析字符串时发生异常,返回空串""
* @see DateUtilsBasic#getFirstDayOfMonth(String)
*/
public static String getMonthBegin(String strdate) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM");
Date date = null;
try {
date = sdf.parse(strdate);
return sdf1.format(date) + "-01";
} catch (Exception e) {
if (Constants.DEBUG) {
e.printStackTrace();
}
return "";
}
}
/**
* 获取字符串所表示的日期所在月份最后一天的字符串(该类中的 getEndDateOfMonth 和 getLastDayOfMonth 也是同样的意义).
* @param strdate
* 要解析的日期字符串
* @return String
* 如果传入参数为 null 或者解析字符串时发生异常,返回空串""
* @see DateUtilsBasic#getEndDateOfMonth(String)
* @see DateUtilsBasic#getLastDayOfMonth(String)
*/
public static String getMonthEnd(String strdate) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM");
Calendar calendar = Calendar.getInstance();
Date date = null;
try {
date = sdf.parse(strdate);
calendar.setTime(date);
return sdf1.format(date) + "-" + calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
} catch (Exception e) {
if (Constants.DEBUG) {
e.printStackTrace();
}
return "";
}
}
/**
* 比较 strBegin 表示的日期与 strEnd 表示的日期相差多少天.
* @param strBegin
* 开始日期字符串
* @param strEnd
* 结束日期字符串
* @param defaultValue
* 如果解析字符串时发生异常,返回该值。
* @return int
* 如果strBegin在strEnd之后,返回负数
*/
public static int getDifferDays(String strBegin, String strEnd, int defaultValue) {
SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd");
Date date1 = null, date2 = null;
try {
date1 = f.parse(strBegin);
date2 = f.parse(strEnd);
int days = (int) ((date2.getTime() - date1.getTime()) / 86400000);
return days;
} catch (Exception e) {
if (Constants.DEBUG) {
e.printStackTrace();
}
return defaultValue;
}
}
/**
* 比较 strEnd 表示的日期是否在 strBegin 表示的日期之前.
* @param strBegin
* 开始日期(格式为 "HH:mm:ss")
* @param strEnd
* 截止日期(格式为 "HH:mm:ss")
* @return boolean
* 当且仅当 strEnd 表示的瞬间比 strBegin 表示的瞬间早,才返回 true;否则返回 false
* (strEnd 与 strBegin 表示的日期完全相同时,返回 false;解析字符串时发生异常,返回false)。
*/
public static boolean bforeDifferTimes(String strBegin, String strEnd) {
SimpleDateFormat f = new SimpleDateFormat("HH:mm:ss");
Date date1 = null, date2 = null;
try {
date1 = f.parse(strBegin);
date2 = f.parse(strEnd);
return date2.before(date1);
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
/**
* 比较 str2 表示的日期是否在 str1 表示的日期之前.
* @param str1
* 日期字符串1
* @param str2
* 日期字符串2
* @param format
* 日期/时间格式
* @return boolean
* 当且仅当 str2 表示的瞬间比 str1 表示的瞬间早,才返回 true;否则返回 false
* (str2 与 str1 表示的日期完全相同时,返回 false;解析字符串时发生异常,返回false)。
*/
public static boolean bforeDifferTimes(String str1, String str2, String format) {
SimpleDateFormat f = new SimpleDateFormat(format);
Date date1 = null, date2 = null;
try {
date1 = f.parse(str1);
date2 = f.parse(str2);
return date2.before(date1);
} catch (ParseException e) {
e.printStackTrace();
return false;
}
}
/**
* 比较 str2 表示的日期是否在 str1 表示的日期之前.
* @param str1
* 日期字符串1
* @param str2
* 日期字符串2
* @param format
* 日期/时间格式
* @return boolean
* 当且仅当 str2 表示的瞬间比 str1 表示的瞬间早,或者 str2 与 str1 表示的日期完全相同时,才返回 true;否则返回 false
* (解析字符串时发生异常,返回false)。
*/
public static boolean bforeOrEqualDifferTimes(String str1, String str2, String format) {
SimpleDateFormat f = new SimpleDateFormat(format);
Date date1 = null, date2 = null;
try {
date1 = f.parse(str1);
date2 = f.parse(str2);
return date2.before(date1) || date1.equals(date2);
} catch (ParseException e) {
e.printStackTrace();
return false;
}
}
/**
* 检查 str1 表示的日期是否与 str2 表示的日期相同.
* @param str1
* 日期字符串1
* @param str2
* 日期字符串2
* @param format
* 日期/时间格式
* @return boolean
* 日期相同,返回 true;其他情况,返回 false
*/
public static boolean checkEqauls(String str1, String str2, String format) {
SimpleDateFormat f = new SimpleDateFormat(format);
Date date1 = null, date2 = null;
try {
date1 = f.parse(str1);
date2 = f.parse(str2);
return date1.getTime() == date2.getTime();
} catch (ParseException e) {
return false;
}
}
/**
* 获取 nowdate 延后 delay 个工作日的时间,星期六,星期天不算在工作日,星期一,二,三,四,五算工作日.
* @param nowdate
* 日期
* @param delay
* 延后的工作日
* @return Date
* nowdate 延后 delay 个工作日的时间
*/
public static Date getNextDay(Date nowdate, int delay) {
long myTime;
Calendar calendar = new GregorianCalendar();
for (int i = 0; i < delay; i++) {
myTime = (nowdate.getTime() / 1000) + i * 24 * 60 * 60;
calendar.setTimeInMillis(myTime);
if (calendar.get(Calendar.DAY_OF_WEEK) != Calendar.SATURDAY
&& calendar.get(Calendar.DAY_OF_WEEK) != Calendar.SUNDAY) {
nowdate.setTime(myTime * 1000);
}
}
return nowdate;
}
/**
* 获取指定日期所在月份的天数.
* @param date
* 日期格式为 "yyyy-mm-dd hh:MM:ss"
* @return int
* 指定日期所在月份的天数.
*/
public static int getDaysForDate(String date) {
Date curDate = strToDate(date);
Calendar calendar = Calendar.getInstance();
calendar.setTime(curDate);
return calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
}
/**
* 建议改名 getDelaySchoolYear 获取当前时间,经过 num 偏移的学年的字符串.
* @param num
* 偏移量
* @return String
* 当前时间偏移 num 后得到的学年字符串
*/
public static String getYear(int num) {
Calendar calendar = new GregorianCalendar();
int year = calendar.get(Calendar.YEAR) + num;
int month = calendar.get(Calendar.MONTH);
String yearstr = "";
if (month < 8) {
yearstr = String.valueOf(-1) + "/" + String.valueOf(year);
} else {
yearstr = String.valueOf(year) + "/" + String.valueOf(year + 1);
}
return yearstr;
}
/**
* 建议改名 getSchoolYear 获得时间所对应的学年.
* @param parseDate
* 要解析的日期
* @return String
* 如果传入值为null,返回当前学年
*/
public static String getYear(Date parseDate) {
if (parseDate == null) {
return getYear(0);
}
String result = "";
Calendar calendar = Calendar.getInstance();
calendar.setTime(parseDate);
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH);
if (month < 8) {
result = String.valueOf(year - 1) + "/" + String.valueOf(year);
} else {
result = String.valueOf(year) + "/" + String.valueOf(year + 1);
}
return result;
}
/**
* 判断传入的日期是否是今天或在今天之前.
* @param date
* 传入的日期
* @param model
* 日期的模式,例如 "yyyy-MM-dd HH:mm:ss"
* @param defaultVaule
* 如果解析字符串时发生异常,返回该值。
* @return boolean
* 如果date表示的日期在今天或今天之前,返回 true;否则返回 false
*/
public static boolean beforeToday(String date, String model, boolean defaultVaule) {
SimpleDateFormat sdf = new SimpleDateFormat(model);
Date today = new Date();
Date parseDate = null;
try {
parseDate = sdf.parse(date);
return parseDate.before(today);
} catch (Exception e) {
if (Constants.DEBUG) {
e.printStackTrace();
}
return defaultVaule;
}
}
/**
* 获得数字 i 所代表的星期,所对应的短字母.
* @param i
* 数字
* @return String
* 如果i = 1,返回 "S"(即 "SUNDAY" 的首字母);
* 如果i = 2,返回 "M"(即 "MONDAY" 的首字母);
* ...
* 如果i > 7 或 i < 1,返回空串"";
*/
public static String getDayName(int i) {
String dayname = "";
switch (i) {
case Calendar.MONDAY:
dayname = "M";
break;
case Calendar.TUESDAY:
dayname = "T";
break;
case Calendar.WEDNESDAY:
dayname = "W";
break;
case Calendar.THURSDAY:
dayname = "T";
break;
case Calendar.FRIDAY:
dayname = "F";
break;
case Calendar.SATURDAY:
dayname = "S";
break;
case Calendar.SUNDAY:
dayname = "S";
break;
default:
break;
}
return dayname;
}
/**
* 获取月份的完整名.
* @param month
* 0 表示第一月January
* @return String
* 月份的完整名称,如果month < 0 或 month >= 12,返回空串
*/
public static String getMonthStr(int month) {
String[] monthName = { "January", "February", "March", "April", "May", "June", "July", "August", "September",
"October", "November", "December", };
if (month < 0 | month >= 12) {
return "";
} else {
return monthName[month];
}
}
/**
* 转换日期格式.
* @param date
* 要转换的日期
* @return String
* 返回格式为 1 December 1990 的日期字符串,若 date 为空,则返回空串""
*/
public static String getDate(String date) {
if (date == null || date.equals("")) {
return "";
}
String datestr = "";
Date datetime = DateUtilsBasic.strToDate(date);
Calendar c = Calendar.getInstance();
c.setTime(datetime);
datestr += getCurDay(c);
datestr += " " + getMonthStr(getCurMonth(c));
datestr += " " + getCurYear(c);
return datestr;
}
/**
* 获取上一学年.
* @param year
* 学年,yyyy/yyyy模式
* @return String
* 学年 year 的上一学年,yyyy/yyyy模式
*/
public static String getLastYear(String year) {
String[] yearArray = year.split("/");
return (Integer.parseInt(yearArray[0]) - 1) + "/" + (Integer.parseInt(yearArray[1]) - 1);
}
/**
* 获取下一学年.
* @param year
* the year
* @return String
* 学年 year 的下一学年,yyyy/yyyy模式
*/
public static String getNextYear(String year) {
String[] yearArray = year.split("/");
return (Integer.parseInt(yearArray[0]) + 1) + "/" + (Integer.parseInt(yearArray[1]) + 1);
}
/**
* 建议改名, 实现有错 判断时间1是否在时间2之前.
* @param date1
* String 类型的时间1 格式为"yyyy-mm-dd"
* @param date2
* String 类型的时间1 格式为"yyyy-mm-dd"
* @return boolean
* ture: date2 > date 1; false: date2 <= date1
*/
public static boolean getCompareResult(String date1, String date2) {
Calendar calendar1 = Calendar.getInstance();
calendar1.setTime(strToDate(date1));
Calendar calendar2 = Calendar.getInstance();
calendar2.setTime(strToDate(date2));
if (calendar2.after(calendar1)) {
return true;
}
return false;
}
/**
* 建议改名 将毫秒时间转换为时间字符串.
* @param date
* 1970-01-01 00:00:00开始的毫秒数
* @return String
* 时间字符串,以yyyy-MM-dd HH:mm:ss格式
*/
public static String longToStr(long date) {
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(date);
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return formatter.format(calendar.getTime());
}
/**
* 返回指定时间的下一个月.
* @param curDate
* 指定的时间字符串
* @return String
* 时间字符串,以 yyyy-MM-dd 格式
*/
public static String getNextMonth(String curDate) {
Calendar now = Calendar.getInstance();
now.setTime(DateUtilsBasic.strToDate(curDate));
now.add(Calendar.MONTH, 1);
return DateUtilsBasic.dateToStr(new Date(now.getTimeInMillis()));
}
/**
* 返回指定时间的延后或前移几月的时间.
* @param curDate 指定的时间字符串
* @param num 延后或前移的月数
* @return 时间字符串,以 yyyy-MM-dd 格式;
*/
public static String getNextMonth(String curDate, int num) {
Calendar now = Calendar.getInstance();
now.setTime(DateUtilsBasic.strToDate(curDate));
now.add(Calendar.MONTH, num);
return DateUtilsBasic.dateToStr(new Date(now.getTimeInMillis()));
}
/**
* 返回指定时间的上一个月.
* @param curDate
* 指定的时间字符串
* @return String
* 时间字符串,以 yyyy-MM-dd 格式
*/
public static String getPreMonth(String curDate) {
Calendar now = Calendar.getInstance();
now.setTime(DateUtilsBasic.strToDate(curDate));
now.add(Calendar.MONTH, -1);
return DateUtilsBasic.dateToStr(new Date(now.getTimeInMillis()));
}
/**
* 检查 curDate 是否在 startDate 前1天之后,endDate 后1天之前.
* @param startDate
* 开始日期字符串,以 yyyy-MM-dd 格式
* @param endDate
* 结束日期字符串,以 yyyy-MM-dd 格式
* @param curDate
* 要判断的日期字符串,以 yyyy-MM-dd 格式
* @return boolean
* 如果 curDate 在 startDate 前1天之后,在 endDate 后1天之前,返回true;否则返回 false.
*/
public static boolean isBetween(String startDate, String endDate, String curDate) {
Calendar startCalendar = Calendar.getInstance();
startCalendar.setTime(strToDate(startDate));
startCalendar.add(Calendar.DAY_OF_YEAR, -1);
Calendar endCalendar = Calendar.getInstance();
endCalendar.setTime(strToDate(endDate));
endCalendar.add(Calendar.DAY_OF_YEAR, 1);
Calendar curCalendar = Calendar.getInstance();
curCalendar.setTime(strToDate(curDate));
if (startCalendar.before(curCalendar) && curCalendar.before(endCalendar)) {
return true;
}
return false;
}
/**
* 获取日期所在月的第一天(该类中的 getMonthBegin 也是同样的意义).
* @param str
* 日期字符串,以 yyyy-MM-dd 格式
* @return String
* 以 yyyy-MM-dd 格式, 如果传入参数为 null 或者解析字符串时发生异常,返回空串""
* @see DateUtilsBasic#getMonthBegin(String)
*/
public static String getFirstDayOfMonth(String str) {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
Calendar calendar = Calendar.getInstance();
try {
Date date = format.parse(str);
calendar.setTime(date);
calendar.set(Calendar.DAY_OF_MONTH, 1);
return format.format(calendar.getTime());
} catch (Exception e) {
if (Constants.DEBUG) {
e.printStackTrace();
}
return "";
}
}
/**
* 获取日期所在月的最后一天(该类中的 getEndDateOfMonth 和 getMonthEnd 也是同样的意义).
* @param str
* 日期字符串,以 yyyy-MM-dd 格式
* @return String
* 以 yyyy-MM-dd 格式, 如果传入参数为 null 或者解析字符串时发生异常,返回空串""
* @see DateUtilsBasic#getEndDateOfMonth(String)
* @see DateUtilsBasic#getMonthEnd(String)
*/
public static String getLastDayOfMonth(String str) {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
Calendar calendar = Calendar.getInstance();
try {
Date date = format.parse(str);
calendar.setTime(date);
calendar.set(Calendar.DAY_OF_MONTH, 1);
calendar.add(Calendar.MONTH, 1);
calendar.add(Calendar.DAY_OF_YEAR, -1);
return format.format(calendar.getTime());
} catch (Exception e) {
if (Constants.DEBUG) {
e.printStackTrace();
}
return "";
}
}
/**
* 得到指定日期的星期六.
* @param date
* 日期字符串,以 yyyy-MM-dd 格式
* @return String
* 以 yyyy-MM-dd 格式,星期六是该周的最后一天, 如果传入参数为 null 或者解析字符串时发生异常,返回空串""
*/
public static String getSaterdayOfWeek(String date) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
try {
Date datePoint = dateFormat.parse(date);
Calendar c = Calendar.getInstance();
c.setTime(datePoint);
int dayofweek = c.get(Calendar.DAY_OF_WEEK) - 1;
c.add(Calendar.DATE, -dayofweek + 6);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
return sdf.format(c.getTime());
} catch (Exception e) {
if (Constants.DEBUG) {
e.printStackTrace();
}
return "";
}
}
/**
* 得到指定日期所在周的星期天.
* @param date
* 日期字符串,以 yyyy-MM-dd 格式
* @return String
* 以 yyyy-MM-dd 格式,星期天是该周的第一天, 如果传入参数为 null 或者解析字符串时发生异常,返回空串""
*/
public static String getSundayOfWeek(String date) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
try {
Date datePoint = dateFormat.parse(date);
Calendar c = Calendar.getInstance();
c.setTime(datePoint);
int dayofweek = c.get(Calendar.DAY_OF_WEEK) - 1;
c.add(Calendar.DATE, -dayofweek);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
return sdf.format(c.getTime());
} catch (Exception e) {
if (Constants.DEBUG) {
e.printStackTrace();
}
return "";
}
}
/**
* 得到指定日期所在周的第一天(星期天)顺延days天的日期.
* @param date
* 日期字符串,以 yyyy-MM-dd 格式
* @param days
* 顺延的天数,(0--星期天,1--星期一,2--星期二,以此类推)
* @return String
* 以 yyyy-MM-dd 格式, 如果传入参数为 null 或者解析字符串时发生异常,返回空串""
*/
public static String getDateOfWeek(String date, int days) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
try {
Date datePoint = dateFormat.parse(date);
Calendar c = Calendar.getInstance();
c.setTime(datePoint);
int dayofweek = c.get(Calendar.DAY_OF_WEEK) - 1;
c.add(Calendar.DATE, -dayofweek + days);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
return sdf.format(c.getTime());
} catch (Exception e) {
if (Constants.DEBUG) {
e.printStackTrace();
}
return "";
}
}
/**
* 获取日历 calendar 中的年份.
* @param calendar
* 日历
* @return int
* 若calendar为空,返回当前年份
*/
public static int getCurYear(Calendar calendar) {
if (calendar == null) {
return getCurYear();
}
return calendar.get(Calendar.YEAR);
}
/**
* 获取日历 calendar 中的月份.
* @param calendar
* 日历
* @return int
* 月份从0开始,若calendar为空,返回当前月份
*/
public static int getCurMonth(Calendar calendar) {
if (calendar == null) {
return getCurMonth();
}
return calendar.get(Calendar.MONTH);
}
/**
* 获取日历 calendar 中的日期.
* @param calendar
* 日历
* @return int
* 若 calendar 为空,返回当前日期
*/
public static int getCurDay(Calendar calendar) {
if (calendar == null) {
return getCurDay();
}
return calendar.get(Calendar.DAY_OF_MONTH);
}
/**
* 该方法逻辑有问题 获取现在时间.
* @return Date
* 返回时间类型 yyyy-MM-dd HH:mm:ss
*/
public static Date getNowDate() {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date currentTime = new Date();
String dateString = formatter.format(currentTime);
ParsePosition pos = new ParsePosition(8);
Date currentTimeTwo = formatter.parse(dateString, pos);
return currentTimeTwo;
}
/**
* 获取现在时间.
* @return Date
* 返回时间类型 yyyy-MM-dd
*/
public static Date getNowDateShort() {
Date currentTime = new Date();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
String dateString = formatter.format(currentTime);
ParsePosition pos = new ParsePosition(8);
Date currentTimeTwo = formatter.parse(dateString, pos);
return currentTimeTwo;
}
/**
* 获取现在时间.
* @return String
* 返回时间字符串 yyyy-MM-dd HH:mm:ss
*/
public static String getStringDate() {
Date currentTime = new Date();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String dateString = formatter.format(currentTime);
return dateString;
}
/**
* 获取现在时间.
* @return String
* 返回短时间字符串格式 yyyy-MM-dd
*/
public static String getStringDateShort() {
Date currentTime = new Date();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
String dateString = formatter.format(currentTime);
return dateString;
}
/**
* 获取时间 小时:分;秒 HH:mm:ss.
* @return String
* 返回短时间字符串格式 HH:mm:ss.
*/
public static String getTimeShort() {
SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss");
Date currentTime = new Date();
String dateString = formatter.format(currentTime);
return dateString;
}
/**
* 将长时间格式字符串转换为时间 yyyy-MM-dd HH:mm:ss.
* @param strDate
* 指定的日期字符串
* @return Date
* 返回时间类型 yyyy-MM-dd HH:mm:ss
*/
public static Date strToDateLong(String strDate) {
if (strDate == null) {
return null;
}
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
ParsePosition pos = new ParsePosition(0);
Date strtodate = formatter.parse(strDate, pos);
return strtodate;
}
/**
* 将长时间格式时间转换为字符串 yyyy-MM-dd HH:mm:ss.
* @param dateDate
* 指定的日期
* @return String
* 返回时间字符串 yyyy-MM-dd HH:mm:ss
*/
public static String dateToStrLong(java.util.Date dateDate) {
if (dateDate == null) {
dateDate = new Date();
}
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String dateString = formatter.format(dateDate);
return dateString;
}
/**
* 将短时间格式时间转换为字符串 yyyy-MM-dd.
* @param dateDate
* 指定的日期
* @return String
* 返回短时间字符串格式 yyyy-MM-dd
*/
public static String dateToStr(java.util.Date dateDate) {
if (dateDate == null) {
dateDate = new Date();
}
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
String dateString = formatter.format(dateDate);
return dateString;
}
/**
* 将短时间格式字符串转换为时间.
* @param strDate
* 短时间字符串格式 yyyy-MM-dd
* @return Date
* 返回时间类型 yyyy-MM-dd, 如果 strDate 为 null,返回 null
*/
public static Date strToDate(String strDate) {
return strToDate(strDate, "yyyy-MM-dd");
}
/**
* 将时间字符串按指定格式转换为日期
* @param strDate
* 时间字符串
* @param format
* 日期格式
* @return Date
* 返回按指定格式得到的时间, 如果 strDate 为 null,返回 null
*/
public static Date strToDate(String strDate, String format) {
if (strDate == null) {
return null;
}
SimpleDateFormat formatter = new SimpleDateFormat(format);
ParsePosition pos = new ParsePosition(0);
Date strtodate = formatter.parse(strDate, pos);
return strtodate;
}
/**
* 得到现在时间.
* @return Date
* 精确到毫秒
*/
public static Date getNow() {
Date currentTime = new Date();
return currentTime;
}
/**
* 提取一个月中的最后一天.
* @param day
* 毫秒数
* @return Date
* 表示时间值的 Date。
*/
public static Date getLastDate(long day) {
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(day);
calendar.set(Calendar.DAY_OF_MONTH, 1);
calendar.add(Calendar.MONTH, 1);
calendar.add(Calendar.DAY_OF_YEAR, -1);
return calendar.getTime();
}
/**
* 得到现在的时间字符串.
* @return String
* 时间字符串格式 yyyyMMdd HHmmss
*/
public static String getStringToday() {
Date currentTime = new Date();
SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd HHmmss");
String dateString = formatter.format(currentTime);
return dateString;
}
/**
* 得到现在小时.如当前时间为 14:45:55,则返回 14
* @return String
* 当前时间的小时数
*/
public static String getHour() {
Date currentTime = new Date();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String dateString = formatter.format(currentTime);
String hour;
hour = dateString.substring(11, 13);
return hour;
}
/**
* 得到现在分钟..如当前时间为 14:45:55,则返回 45
* @return String
* 在00到59之间
*/
public static String getMinute() {
Date currentTime = new Date();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String dateString = formatter.format(currentTime);
String min;
min = dateString.substring(14, 16);
return min;
}
/**
* 得到现在的秒数.如当前时间为 14:45:55,则返回 55
* @return String
* 在00到59之间
*/
public static String getSecond() {
Date currentTime = new Date();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String dateString = formatter.format(currentTime);
String min;
min = dateString.substring(17, 19);
return min;
}
/**
* 根据用户传入的时间表示格式,返回当前时间的格式 如果是yyyyMMdd,注意字母y不能大写。.
* @param sformat
* 时间格式,若为空,则默认为 yyyyMMddhhmmss
* @return String
* 按指定格式返回的当前时间的格式
*/
public static String getUserDate(String sformat) {
if (sformat == null) {
sformat = "yyyyMMddhhmmss";
}
Date currentTime = new Date();
SimpleDateFormat formatter = new SimpleDateFormat(sformat);
String dateString = formatter.format(currentTime);
return dateString;
}
/**
* 建议修改方法名 两个小时时间间的差值,必须保证两个时间都是"HH:MM"的格式,返回字符串型的小时.
* @param st1
* 时间字符串1
* @param st2
* 时间字符串2
* @return String
* 如果 st1 表示的小时数小于或者等于 st2 表示的小时数,返回0,否则返回 st1 和 st2 表示的小时间的差值
*/
public static String getTwoHour(String st1, String st2) {
String[] kk = null;
String[] jj = null;
kk = st1.split(":");
jj = st2.split(":");
if (Integer.parseInt(kk[0]) < Integer.parseInt(jj[0])) {
return "0";
} else {
double y = Double.parseDouble(kk[0]) + Double.parseDouble(kk[1]) / 60;
double u = Double.parseDouble(jj[0]) + Double.parseDouble(jj[1]) / 60;
if ((y - u) > 0) {
return y - u + "";
} else {
return "0";
}
}
}
/**
* 得到两个日期间的间隔天数.
* @param sj1
* 日期字符串1
* @param sj2
* 日期字符串2
* @return String
* 两个日期间的间隔天数。如果解析字符串时发生异常,返回空串""
*/
public static String getTwoDay(String sj1, String sj2) {
SimpleDateFormat myFormatter = new SimpleDateFormat("yyyy-MM-dd");
long day = 0;
try {
java.util.Date date = myFormatter.parse(sj1);
java.util.Date mydate = myFormatter.parse(sj2);
day = (date.getTime() - mydate.getTime()) / (24 * 60 * 60 * 1000);
return day + "";
} catch (Exception e) {
if (Constants.DEBUG) {
e.printStackTrace();
}
return "";
}
}
/**
* 时间前推或后推 minute 分钟.
* @param strdate
* 时间字符串
* @param minute
* 前推或后推的分钟数
* @return String
* 如果 strdate 不能成功的转换成 Date,或 minute 不能成功的转换为 Integer, 返回空串""
*/
public static String getPreTime(String strdate, String minute) {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String mydate1 = "";
try {
Date date1 = format.parse(strdate);
long longTime = (date1.getTime() / 1000) + Integer.parseInt(minute) * 60;
date1.setTime(longTime * 1000);
mydate1 = format.format(date1);
return mydate1;
} catch (Exception e) {
if (Constants.DEBUG) {
e.printStackTrace();
}
return "";
}
}
/**
* 得到一个时间延后或前移几天的时间
* @param nowdate
* 时间字符串
* @param delay
* 前移或后延的天数.
* @return String
* nowdate 延后或前移 delay 天的时间。如果解析字符串时发生异常,返回空串""
*/
public static String getNextDay(String nowdate, String delay) {
try {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
String mdate = "";
Date d = strToDate(nowdate);
long myTime = (d.getTime() / 1000) + Integer.parseInt(delay) * 24 * 60 * 60;
d.setTime(myTime * 1000);
mdate = format.format(d);
return mdate;
} catch (Exception e) {
return "";
}
}
/**
* 判断是否润年.
* @param ddate
* 时间字符串, “yyyy-MM-dd” 格式
* @return boolean<br>
* true: ddate 表示的年份是闰年;
* false: ddate 表示的年份不是闰年;
*/
public static boolean isLeapYear(String ddate) {
/**
* 详细设计: 1.被400整除是闰年, 2不能被400整除,能被100整除不是闰年 3.不能被100整除,能被4整除则是闰年 4.不能被4整除不是闰年
*/
Date d = strToDate(ddate);
GregorianCalendar gc = (GregorianCalendar) Calendar.getInstance();
gc.setTime(d);
int year = gc.get(Calendar.YEAR);
if ((year % 400) == 0) {
return true;
} else if (year % 100 == 0) {
return false;
} else {
return ((year % 4) == 0);
}
}
/**
* 返回美国时间格式 26 Apr 2006.
* @param str
* 时间字符串
* @return String
* 如果传入的字符串为 2011-06-23,则返回 23JUN11
*/
public static String getEDate(String str) {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
ParsePosition pos = new ParsePosition(0);
Date strtodate = formatter.parse(str, pos);
String j = strtodate.toString();
String[] k = j.split(" ");
return k[2] + k[1].toUpperCase() + k[5].substring(2, 4);
}
/**
* 获取一个月的最后一天(该类中的 getMonthEnd 和 getLastDayOfMonth 也是同样的意义).
* @param dat
* 时间字符串,格式为 yyyy-MM-dd
* @return String
* dat 所表示的月份的最后一天,如 dat="2011-05-04",则返回 "2011-05-31"
* @see DateUtilsBasic#getMonthEnd(String)
* @see DateUtilsBasic#getLastDayOfMonth(String)
*/
public static String getEndDateOfMonth(String dat) {
String str = dat.substring(0, 8);
String month = dat.substring(5, 7);
int mon = Integer.parseInt(month);
if (mon == 1 || mon == 3 || mon == 5 || mon == 7 || mon == 8 || mon == 10 || mon == 12) {
str += "31";
} else if (mon == 4 || mon == 6 || mon == 9 || mon == 11) {
str += "30";
} else {
if (isLeapYear(dat)) {
str += "29";
} else {
str += "28";
}
}
return str;
}
/**
* 判断两个日期是否在同一个周.
* @param date1
* 日期1
* @param date2
* 日期2
* @return boolean<br>
* true: 两个日期在同一周;false: 两个日期不在同一周;</br>
* 注:星期天是一周的第一天,星期六是一周的最后一天.
*/
public static boolean isSameWeekDates(Date date1, Date date2) {
Calendar cal1 = Calendar.getInstance();
Calendar cal2 = Calendar.getInstance();
cal1.setTime(date1);
cal2.setTime(date2);
int subYear = cal1.get(Calendar.YEAR) - cal2.get(Calendar.YEAR);
if (0 == subYear) {
if (cal1.get(Calendar.WEEK_OF_YEAR) == cal2.get(Calendar.WEEK_OF_YEAR)) {
return true;
}
} else if (1 == subYear && 11 == cal2.get(Calendar.MONTH)) {
// 如果12月的最后一周横跨来年第一周的话则最后一周即算做来年的第一周
if (cal1.get(Calendar.WEEK_OF_YEAR) == cal2.get(Calendar.WEEK_OF_YEAR)) {
return true;
}
} else if (-1 == subYear && 11 == cal1.get(Calendar.MONTH)) {
if (cal1.get(Calendar.WEEK_OF_YEAR) == cal2.get(Calendar.WEEK_OF_YEAR)) {
return true;
}
}
return false;
}
/**
* 产生周序列,即得到当前时间所在的年度是第几周.
* @return String
* 格式为:年份 + 周的序号
*/
public static String getSeqWeek() {
Calendar c = Calendar.getInstance(Locale.CHINA);
String week = Integer.toString(c.get(Calendar.WEEK_OF_YEAR));
if (week.length() == 1) {
week = "0" + week;
}
String year = Integer.toString(c.get(Calendar.YEAR));
return year + week;
}
/**
* 建议修改方法名 获得一个日期所在的周的星期几的日期,如要找出2002年2月3日所在周的星期一是几号.
* @param sdate
* 日期字符串
* @param num
* 取"0"到“6”之间的字符串,"0"代表星期天,星期天是一周的第一天
* @return String
* 以 yyyy-MM-dd 模式, 如果 sdate 不能成功的转换为 Date 或 num 不在"0"到"6"之间,返回空串""
*/
public static String getWeek(String sdate, String num) {
//先转换为时间
Date dd = DateUtilsBasic.strToDate(sdate);
if (dd == null) {
return "";
}
Calendar c = Calendar.getInstance();
c.setTime(dd);
if (num.equals("1")) {
c.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
} else if (num.equals("2")) {
c.set(Calendar.DAY_OF_WEEK, Calendar.TUESDAY);
} else if (num.equals("3")) {
c.set(Calendar.DAY_OF_WEEK, Calendar.WEDNESDAY);
} else if (num.equals("4")) {
c.set(Calendar.DAY_OF_WEEK, Calendar.THURSDAY);
} else if (num.equals("5")) {
c.set(Calendar.DAY_OF_WEEK, Calendar.FRIDAY);
} else if (num.equals("6")) {
c.set(Calendar.DAY_OF_WEEK, Calendar.SATURDAY);
} else if (num.equals("0")) {
c.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
} else {
return "";
}
return new SimpleDateFormat("yyyy-MM-dd").format(c.getTime());
}
/**
* 返回日期所处的星期.
* @param sdate
* 日期字符串
* @return String
* 完整的英语星期(Sunday、Monday、Tuesday、Wednesday、Thursday、Friday 和 Saturday),如果 sdate 不能转换为 Date,返回空串""。
*/
public static String getWeek(String sdate) {
// 先转换为时间
Date date = DateUtilsBasic.strToDate(sdate);
if (date == null) {
return "";
}
Calendar c = Calendar.getInstance();
c.setTime(date);
return new SimpleDateFormat("EEEE").format(c.getTime());
}
/**
* 返回日期所代表的星期.
* @param sdate
* 日期字符串
* @return String
* 完整的中文星期("星期日"、"星期一"、"星期二"、"星期三"、"星期四"、"星期五" 和 "星期六"),如果sdate不能成功的转换为Date,返回空串""
*/
public static String getWeekStr(String sdate) {
String result = "";
Date date = strToDate(sdate);
if (date == null) {
return result;
}
Calendar c = Calendar.getInstance();
c.setTime(date);
int day = c.get(Calendar.DAY_OF_WEEK);
switch (day) {
case Calendar.SUNDAY:
return "星期日";
case Calendar.MONDAY:
return "星期一";
case Calendar.TUESDAY:
return "星期二";
case Calendar.WEDNESDAY:
return "星期三";
case Calendar.THURSDAY:
return "星期四";
case Calendar.FRIDAY:
return "星期五";
case Calendar.SATURDAY:
return "星期六";
default:
break;
}
return "";
}
/**
* 两个日期之间的天数.
* @param end
* 日期字符串1,以 yyyy-MM-dd 格式
* @param begin
* 日期字符串2,以 yyyy-MM-dd 格式
* @param defaultValue
* 解析过程中发生异常所返回的值
* @return long
* 返回 begin 和 end 所表示的日期之间的天数;如果 end,begin 不能成功的转换成 Date,返回 defaultValue
*/
public static long getDays(String end, String begin, long defaultValue) {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
java.util.Date endDate = null;
java.util.Date beginDate = null;
try {
endDate = format.parse(end);
beginDate = format.parse(begin);
long day = (endDate.getTime() - beginDate.getTime()) / (24 * 60 * 60 * 1000);
return day + 1;
} catch (Exception e) {
if (Constants.DEBUG) {
e.printStackTrace();
}
return defaultValue;
}
}
/**
* 该方法返回 sdate 所表示日期所在月份的第一天所属星期的星期日(星期日是一周的第一天)的日期,如 sdate="2011-04-15",则返回"2011-03-27".
* @param sdate
* 日期字符串
* @return String
* 以 yyyy-MM-dd 格式,如果sdate不能成功的转换为Date,返回空串""
*/
public static String getNowMonth(String sdate) {
// 该方法返回sdate所表示日期所在月的第一天,所属星期的星期日(星期日是一周的第一天); 形成如下的日历,
// 根据传入的一个时间返回一个结构 星期日 星期一 星期二 星期三 星期四 星期五
// 星期六 下面是当月的各个时间 此函数返回该日历第一行星期日所在的日期.
// 取该时间所在月的一号
String monthBegin = getMonthBegin(sdate);
String weekBegin = getWeek(monthBegin, "0");
return weekBegin;
}
/**
* 取得数据库主键 生成格式为 yyyymmddhhmmss+k 位随机数.
* @param k
* 表示是取几位随机数,可以自己定
* @return String
* 随机数
*/
public static String getNo(int k) {
return getUserDate("yyyyMMddhhmmss") + getRandom(k);
}
/**
* 返回一个随机数.
* @param i
* 随机数的位数
* @return String
* 随机数
*/
public static String getRandom(int i) {
Random jjj = new Random();
if (i == 0) {
return "";
}
String jj = "";
for (int k = 0; k < i; k++) {
jj = jj + jjj.nextInt(9);
}
return jj;
}
/**
* 判断 date 是否可以成功转换为日期.
* @param date
* 日期字符串
* @return boolean
* true: date 可以转换为日期,false: date 不可以转换为日期
*/
public static boolean rightDate(String date) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
if (date == null) {
return false;
}
if (date.length() > 10) {
sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
} else {
sdf = new SimpleDateFormat("yyyy-MM-dd");
}
try {
sdf.parse(date);
} catch (Exception e) {
if (Constants.DEBUG) {
e.printStackTrace();
}
return false;
}
return true;
}
/**
* 判断 datestr 所表示的日期是否是周末.
* @param datestr
* 日期字符串
* @return boolean
* true: datestr 所表示的日期是周末;false: datestr 所表示的日期不是周末
*/
public static boolean isWeekend(String datestr) {
if (datestr == null || "".equals(datestr.trim())) {
return false;
}
SimpleDateFormat myFormatter = new SimpleDateFormat("yyyy-MM-dd");
try {
Date date = myFormatter.parse(datestr);
Calendar calendar = new GregorianCalendar();
calendar.setTime(date);
if (calendar.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY
|| calendar.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) {
return true;
}
} catch (ParseException e) {
return false;
}
return false;
}
/**
* 返回两个日期间的天数,去除周末的天数.
* @param startdate
* 开始日期,格式 “yyyy-MM-dd”
* @param enddate
* 结束日期,格式 “yyyy-MM-dd”
* @return int
* 两个日期间去除周末的天数,如果 startdate 和 enddate 其中有一个是空或者解析过程中发生异常,返回 0
*/
public static int getdaysslice(String startdate, String enddate) {
if (startdate == null || "".equals(startdate.trim())) {
return 0;
}
if (enddate == null || "".equals(enddate.trim())) {
return 0;
}
SimpleDateFormat myFormatter = new SimpleDateFormat("yyyy-MM-dd");
java.util.Date start = null;
java.util.Date end = null;
try {
start = myFormatter.parse(startdate);
end = myFormatter.parse(enddate);
} catch (Exception e) {
if (Constants.DEBUG) {
e.printStackTrace();
}
return 0;
}
long daynum = (end.getTime() - start.getTime()) / (24 * 60 * 60 * 1000);
Calendar startcalendar = new GregorianCalendar();
startcalendar.setTime(start);
int n = 0;
for (int i = 0; i <= daynum; i++) {
if (startcalendar.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY
|| startcalendar.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) {
startcalendar.add(Calendar.DAY_OF_MONTH, 1);
continue;
}
startcalendar.add(Calendar.DAY_OF_MONTH, 1);
n++;
}
return n;
}
/**
* 返回按给定连接符的日期字符串.
* @param date
* 需要转换的字符串,前 8 位需以 yyyyMMdd 格式,separator 日期格式中连接的字符 例如:20071227——>2007-12-27
* @param separator
* 连接符
* @return String
* 按给定连接符连接的日期字符串。如果 date 或者 separator 为空,返回date;如果 date 的长度小于8位,返回 date;
* 如果 date 的长度大于或等于8位,但其5、6位不在 01~12 范围内或者7、8位不在 01~31范围内,则同样返回 date;
* 例如 date="1234567"||"12341301"||"12340132"时,直接将 date 返回
*/
public static String formatToYYYYMMDD(String date, String separator) {
if (null == date || "".equals(date) || null == separator || "".equals(separator)) {
return date;
}
StringBuffer sb = new StringBuffer();
String reg = "[0-9]{4}(01|02|03|04|05|06|07|08|09|10|11|12){1}(01|02|03|04|05|06|07|08|09|10|11|12|13|14|15|16|17|18|19|20|21|22|23|24|25|26|27|28|29|30|31){1}";
Pattern p = Pattern.compile(reg);
Matcher m = p.matcher(date);
int offset = 0;
while (m.find(offset)) {
int sIndex = m.start();
int eIndex = m.end();
String tmpPrefix = date.substring(offset, sIndex);
sb.append(tmpPrefix);
String tmpDate = date.substring(sIndex, eIndex);
String tmpYYYY = tmpDate.substring(0, 4);
String tmpMM = tmpDate.substring(4, 6);
String tmpDD = tmpDate.substring(6, 8);
sb.append(tmpYYYY);
sb.append(separator);
sb.append(tmpMM);
sb.append(separator);
sb.append(tmpDD);
offset = m.end();
}
String tmpSuffix = date.substring(offset, date.length());
sb.append(tmpSuffix);
return sb.toString();
}
/**
* 判断 day 是否在 curTime 之后,且不超过一天.
* @param curTime
* 时间毫秒数
* @param day
* 时间毫秒数
* @return boolean
* 如果 day 在 curTime 之后,且不超过一天,返回true.
*/
public static boolean inThisDay(long curTime, long day) {
if (curTime >= day && curTime < day + 24 * 60 * 60 * 1000) {
return true;
}
return false;
}
/**
* 将当前日期转换为 format 格式的字符串.
* @param format
* 日期格式
* @return String
* format 格式的当前日期字符串
*/
public static String getCurrentDateFormated(String format) {
Date date = new Date();
return changedDateFormat(date, format);
}
/**
* 将日期 date 转换为 format 格式的字符串.
* @param date
* 日期
* @param format
* 日期格式
* @return String
* format 格式的日期字符串
*/
public static String changedDateFormat(Date date, String format) {
try {
if (date == null) {
return "";
}
SimpleDateFormat formatter = new SimpleDateFormat(format);
String dateString = formatter.format(date);
return dateString;
} catch (Exception e) {
if (Constants.DEBUG) {
e.printStackTrace();
}
return "";
}
}
/**
* 获取从 start 到 end 的时间范围内每间隔 pitch 分钟的时间字符串集合.
* 如 getTimeList("2011-05-04 13:00:00", "2011-05-04 13:30:00", 5, "yyyy-MM-dd hh:mm:ss"),
* 则返回的 List 中存放的元素为:2011-05-04 01:00:00, 2011-05-04 01:05:00, 2011-05-04 01:10:00,
* 2011-05-04 01:15:00, 2011-05-04 01:20:00, 2011-05-04 01:25:00, 2011-05-04 01:30:00。
* 注意小时的范围为 01~12
* @param start
* 开始时间
* @param end
* 结束时间
* @param pitch
* 分钟间隔
* @param format
* 时间格式
* @return List<String>
* 从 start 到 end 的时间范围内每间隔 pitch 分钟的时间字符串集合.如果 start 与 end 所表示的时间相同,则 List 中只有 start 一个元素
* 如果解析过程中出现异常,则 List 中无元素,size=0;
*/
public static List<String> getTimeList(String start, String end, int pitch, String format) {
List<String> result = new ArrayList<String>();
SimpleDateFormat formatter = new SimpleDateFormat(format);
try {
Date startDate = formatter.parse(start);
Date endDate = formatter.parse(end);
Calendar startCalendar = Calendar.getInstance();
Calendar endCalendar = Calendar.getInstance();
startCalendar.setTime(startDate);
endCalendar.setTime(endDate);
while (startCalendar.before(endCalendar)) {
result.add(formatter.format(startCalendar.getTime()));
startCalendar.add(Calendar.MINUTE, pitch);
}
if (startCalendar.equals(endCalendar)) {
result.add(formatter.format(startCalendar.getTime()));
}
} catch (ParseException e) {
e.printStackTrace();
}
return result;
}
/**
* 获取从 start 到 end 的时间范围内每间隔 pitch 分钟的时间字符串集合.
* 如 getTimeList("01:00", "01:30", 5),
* 则返回的 List 中存放的元素为:01:00, 01:05, 01:10, 01:15, 01:20, 01:25。
* 注意小时的范围为 00~23
* @param start
* 开始时间,格式为 HH:mm
* @param end
* 结束时间,格式为 HH:mm
* @param pitch
* 分钟间隔
* @return List<String>
* 从 start 到 end 的时间范围内每间隔 pitch 分钟的时间字符串集合.如果 start 与 end 所表示的时间相同或者解析过程中出现异常,则 List 中无元素,size=0;
*/
public static List<String> getTimeList(String start, String end, int pitch) {
List<String> result = new ArrayList<String>();
SimpleDateFormat formatter = new SimpleDateFormat("HH:mm");
try {
Date startDate = formatter.parse(start);
Date endDate = formatter.parse(end);
Calendar startCalendar = Calendar.getInstance();
Calendar endCalendar = Calendar.getInstance();
startCalendar.setTime(startDate);
endCalendar.setTime(endDate);
while (startCalendar.before(endCalendar)) {
result.add(formatter.format(startCalendar.getTime()));
startCalendar.add(Calendar.MINUTE, pitch);
}
} catch (ParseException e) {
e.printStackTrace();
}
return result;
}
/**
* 获取 sdate 所表示的日期对应的星期的序号(1表示星期天,2表示星期一,以此类推).
* @param sdate
* 日期字符串
* @return int
* 星期的序号
*/
public static int getWeekNumber(String sdate) {
Date date = strToDate(sdate);
Calendar c = Calendar.getInstance();
c.setTime(date);
return c.get(Calendar.DAY_OF_WEEK);
}
/**
* 根据出生日期计算年龄.
* @param strBirthDay
* 出生日期字符串
* @param format
* 日期格式
* @return int
* 年龄
* @throws Exception
* the exception
*/
public static int getAge(String strBirthDay, String format) throws Exception {
DateFormat df = new SimpleDateFormat(format);
Date birthDay = df.parse(strBirthDay);
return getAge(birthDay);
}
/**
* 取日期字符串的前16位,即 yyyy-MM-dd hh:mm
* 例如:date="2010-01-20 13:38:10.0",返回 "2010-01-20 13:38"
* @param date
* 日期字符串
* @return String
* date 的前 16 位字符串,如果 date 的位数小于 16 位,则返回 date,如果 date 为空,返回空串""
*/
public static String getDateHHMM(String date) {
if (date == null || "".equals(date.trim())) {
return "";
}
if (date.length() >= 16) {
date = date.substring(0, 16);
}
return date;
}
/**
* 取日期字符串的前10位,即 yyyy-MM-dd
* 例如:date="2010-01-20 13:38:10.0",返回 "2010-01-20"
* @param date
* 日期字符串
* @return String
* date 的前 10 位字符串,如果 date 的位数小于 10 位,则返回 date,如果 date 为空,返回空串""
*/
public static String getDateYYMMDD(String date) {
if (date == null || "".equals(date.trim())) {
return "";
}
if (date.length() >= 10) {
date = date.substring(0, 10);
}
return date;
}
/**
* 根据出生日期计算年龄.
* @param birthDay
* 出生日期
* @return int
* 年龄.
* @throws Exception
* 如果出生日期在当前日期之后,抛出异常
*/
public static int getAge(Date birthDay) throws Exception {
Calendar cal = Calendar.getInstance();
if (cal.before(birthDay)) {
throw new IllegalArgumentException("The birthDay is before Now.It's unbelievable!");
}
int yearNow = cal.get(Calendar.YEAR);
int monthNow = cal.get(Calendar.MONTH);
int dayOfMonthNow = cal.get(Calendar.DAY_OF_MONTH);
cal.setTime(birthDay);
int yearBirth = cal.get(Calendar.YEAR);
int monthBirth = cal.get(Calendar.MONTH);
int dayOfMonthBirth = cal.get(Calendar.DAY_OF_MONTH);
int age = yearNow - yearBirth;
if (monthNow <= monthBirth) {
if (monthNow == monthBirth) {
if (dayOfMonthNow < dayOfMonthBirth) {
age--;
}
} else {
age--;
}
}
return age;
}
/**
* 查看当前时间与指定时间的差值是否是间隔时间段的整数倍
* @param dateStr
* 指定时间字符串
* @param period
* 间隔时间段(天)
* @return boolean
* 是否为整数倍
*/
public static boolean isEqualPeriodDate(String dateStr, long period) {
if (StringUtilsBasic.checkNull(dateStr)) {
String format = "yyyy-MM-dd";
String now = DateUtilsBasic.getCurDate(format);
dateStr = DateUtilsBasic.getDateYYMMDD(dateStr);
return DateUtilsBasic.getDays(now, dateStr, 0) % period == 0;
}
return false;
}
}
| 57,325 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
DateUtilsConvert.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/base_plugins/heartsome.java.tools.plugin/src/cn/org/tools/utils/date/DateUtilsConvert.java | /**
* DateUtilsConvert.java
*
* Version information :
*
* Date:Jan 13, 2010
*
* Copyright notice :
*/
package cn.org.tools.utils.date;
/**
* 该类继承了 DateUtilsBasic,自己无任何属性或方法
* @author Terry
* @version
* @since JDK1.6
*/
public class DateUtilsConvert extends DateUtilsBasic {
}
| 323 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
MailUtils.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/base_plugins/heartsome.java.tools.plugin/src/cn/org/tools/utils/mail/MailUtils.java | /**
* MailUtils.java
*
* Version information :
*
* Date:Jan 13, 2010
*
* Copyright notice :
*/
package cn.org.tools.utils.mail;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.mail.Address;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
/**
* The Class MailUtils.
* @author Terry
* @version
* @since JDK1.6
*/
public class MailUtils {
/**
* 构造方法.
*/
protected MailUtils() {
throw new UnsupportedOperationException(); // prevents calls from subclass
}
/**
* 用来取得 Email 地址的友好称呼。
* @param emailAddress
* Email 地址
* @return String
* 例如: emailAddress="John <[email protected]>" 就返回 John。
*/
public static String getAddressName(String emailAddress) {
String result = "";
if (emailAddress == null) {
return result;
}
try {
InternetAddress address = new InternetAddress(emailAddress);
String text = address.getPersonal();
if (text == null) {
result = emailAddress;
} else {
result = text;
}
} catch (AddressException e) {
e.printStackTrace();
return emailAddress;
}
return result;
}
/**
* 用来取得 Email 地址。
* @param emailAddress
* the email address
* @return String
* 例如: emailAddress="John <[email protected]>" 就返回 [email protected]
*/
public static String getAddress(String emailAddress) {
String result = "";
if (emailAddress == null) {
return result;
}
try {
InternetAddress address = new InternetAddress(emailAddress);
String text = address.getAddress();
if (text == null) {
result = emailAddress;
} else {
result = text;
}
} catch (AddressException e) {
e.printStackTrace();
return emailAddress;
}
return result;
}
/**
* 过滤邮件中的 From 和 To,使邮件不允许发件人和收件人一样.
* @param message
* 邮件对象
* @throws MessagingException
* the messaging exception
*/
public static void removeDumplicate(Message message) throws MessagingException {
Address[] from = message.getFrom();
Address[] to = message.getRecipients(Message.RecipientType.TO);
Address[] cc = message.getRecipients(Message.RecipientType.CC);
Address[] bcc = message.getRecipients(Message.RecipientType.BCC);
Address[] tonew = removeDuplicate(from, to);
Address[] ccnew = removeDuplicate(from, cc);
Address[] bccnew = removeDuplicate(from, bcc);
if (tonew != null) {
message.setRecipients(Message.RecipientType.TO, tonew);
}
if (ccnew != null) {
message.setRecipients(Message.RecipientType.CC, ccnew);
}
if (bccnew != null) {
message.setRecipients(Message.RecipientType.BCC, bccnew);
}
}
/**
* 过滤邮件中的 From 和 To,使邮件不允许发件人和收件人一样.
* @param from
* 发件人,多个发件人以逗号分隔
* @param to
* 收件人,多个收件人以逗号分隔
* @return Address[]
* 收件人数组中过滤掉重复的发件人信息后剩余的集合
* @throws AddressException
* 解析发件人或收件人失败时抛出该异常
*/
public static Address[] removeDuplicate(String from, String to) throws AddressException {
return removeDuplicate(InternetAddress.parse(from), InternetAddress.parse(to));
}
/**
* 过滤邮件中的 From 和 To,使邮件不允许发件人和收件人一样.
* @param from
* 发件人数组
* @param to
* 收件人
* @return Address[]
* 收件人数组中过滤掉重复的发件人信息后剩余的集合
* @throws AddressException
* 解析收件人失败时抛出该异常
*/
public static Address[] removeDuplicate(Address[] from, String to) throws AddressException {
return removeDuplicate(from, InternetAddress.parse(to));
}
/**
* 过滤邮件中的 From 和 To,使邮件不允许发件人和收件人一样.
* @param from
* 发件人地址
* @param to
* 收件人地址集合
* @return List<Address>
* 收件人数组中过滤掉重复的发件人信息后剩余的集合。如果 from 或 to 为 null,返回 to
* @throws AddressException
* 解析失败时抛出该异常
*/
public static List<Address> removeDuplicate(Address from, List<Address> to) throws AddressException {
if (from == null) {
return to;
}
Address[] result = new Address[to.size()];
Address[] removed = removeDuplicate(new Address[]{from}, to.toArray(result));
if (removed == null) {
return to;
}
return Arrays.asList(removed);
}
/**
* 过滤邮件中的 From 和 To,使邮件不允许发件人和收件人一样.
* @param from
* 发件人集合
* @param to
* 收件人集合
* @return List<Address>>
* 收件人数组中过滤掉重复的发件人信息后剩余的集合。如果 from 为 null,返回 to;如果 to 为 null,返回 null
*/
public static List<Address> removeDuplicate(List<Address> from, List<Address> to) {
if (from == null) {
return to;
}
if (to == null) {
return null;
}
Address[] fromArray = new Address[from.size()];
Address[] toArray = new Address[to.size()];
from.toArray(fromArray);
to.toArray(toArray);
Address[] result = removeDuplicate(fromArray, toArray);
return Arrays.asList(result);
}
/**
* 过滤邮件中的 From 和 To,使邮件不允许发件人和收件人一样.
* @param from
* 发件人数组
* @param to
* 收件人数组
* @return Address[]
* 收件人数组中过滤掉重复的发件人信息后剩余的集合。如果 from 为 null,返回 to;如果 to 为 null,返回 null
*/
public static Address[] removeDuplicate(Address[] from, Address[] to) {
if (from == null) {
return to;
}
if (to == null) {
return null;
}
Set<Address> fromSet = new HashSet<Address>();
Set<Address> toSet = new HashSet<Address>();
for (Address address : from) {
fromSet.add(address);
}
for (Address address : to) {
toSet.add(address);
}
toSet.removeAll(fromSet);
InternetAddress[] address = new InternetAddress[toSet.size()];
toSet.toArray(address);
return address;
}
/**
* 检查 email 地址是否有效(此方法无意义,请勿使用该方法,应该删除或者重新写逻辑).
* @param address
* 要检查的 email 地址
* @return boolean
* true:地址有效
*/
public static boolean isValidAddress(String address) {
return true;
}
/**
* The main method.
* @param args
* the arguments
* @throws AddressException
* the address exception
*/
public static void main(String[] args) throws AddressException {
System.out.println(new InternetAddress("a <c> asdf").getAddress());
}
}
| 6,983 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
MessageParser.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/base_plugins/heartsome.java.tools.plugin/src/cn/org/tools/utils/mail/MessageParser.java | /**
* MessageParser.java
*
* Version information :
*
* Date:Jan 13, 2010
*
* Copyright notice :
*/
package cn.org.tools.utils.mail;
import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Part;
import javax.mail.Session;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;
import org.apache.xerces.dom.CoreDocumentImpl;
import org.cyberneko.html.parsers.DOMFragmentParser;
import org.w3c.dom.DocumentFragment;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
/**
* The Class MessageParser.
* @author Terry
* @version
* @since JDK1.6
*/
public class MessageParser {
/** The message. */
private Message message;
/** The text buffer. */
private StringBuffer textBuffer;
/** The max arrow. */
private int maxArrow = 0;
/** The text charset. */
private String textCharset = "UTF-8";
/** The html resource. */
private ResourceFileBean htmlResource;
/**
* 构造方法.
* @param message
* Message 对象
*/
public MessageParser(Message message) {
this.message = message;
}
/**
* 获得消息的发件人.
* @return String
* 发件人地址
* @throws MessagingException
* the messaging exception
*/
public String getFrom() throws MessagingException {
return InternetAddress.toString(message.getFrom());
}
/**
* 获得收件人地址信息.
* @return String
* 收件人地址
* @throws MessagingException
* the messaging exception
*/
public String getTo() throws MessagingException {
return InternetAddress.toString(message.getRecipients(Message.RecipientType.TO));
}
/**
* 获得抄送人地址信息.
* @return String
* 抄送人地址
* @throws MessagingException
* the messaging exception
*/
public String getCc() throws MessagingException {
return InternetAddress.toString(message.getRecipients(Message.RecipientType.CC));
}
/**
* 获得回复人地址信息.
* @return String
* 回复人地址
* @throws MessagingException
* the messaging exception
*/
public String gerReplayTo() throws MessagingException {
return InternetAddress.toString(message.getReplyTo());
}
/**
* 获得消息的主题.
* @return String
* 主题内容.
* @throws MessagingException
* the messaging exception
*/
public String getSubject() throws MessagingException {
return message.getSubject();
}
/**
* 获取消息附件中的文件.
* @return List<ResourceFileBean>
* 文件的集合(每个 ResourceFileBean 对象中存放文件名和 InputStream 对象)
* @throws MessagingException
* the messaging exception
* @throws IOException
* Signals that an I/O exception has occurred.
*/
public List<ResourceFileBean> getFiles() throws MessagingException, IOException {
List<ResourceFileBean> resourceList = new ArrayList<ResourceFileBean>();
Object content = message.getContent();
Multipart mp = null;
if (content instanceof Multipart) {
mp = (Multipart) content;
} else {
return resourceList;
}
for (int i = 0, n = mp.getCount(); i < n; i++) {
Part part = mp.getBodyPart(i);
//此方法返回 Part 对象的部署类型。
String disposition = part.getDisposition();
//Part.ATTACHMENT 指示 Part 对象表示附件。
//Part.INLINE 指示 Part 对象以内联方式显示。
if ((disposition != null) && ((disposition.equals(Part.ATTACHMENT) || (disposition.equals(Part.INLINE))))) {
//part.getFileName():返回 Part 对象的文件名。
String fileName = MimeUtility.decodeText(part.getFileName());
//此方法为 Part 对象返回一个 InputStream 对象
InputStream is = part.getInputStream();
resourceList.add(new ResourceFileBean(fileName, is));
} else if (disposition == null) {
//附件也可以没有部署类型的方式存在
getRelatedPart(part, resourceList);
}
}
return resourceList;
}
/**
* 获取消息附件中的文件.
* @param part
* Part 对象
* @param resourceList
* 文件的集合(每个 ResourceFileBean 对象中存放文件名和 InputStream 对象)
* @throws MessagingException
* the messaging exception
* @throws IOException
* Signals that an I/O exception has occurred.
*/
private void getRelatedPart(Part part, List<ResourceFileBean> resourceList) throws MessagingException, IOException {
//验证 Part 对象的 MIME 类型是否与指定的类型匹配。
if (part.isMimeType("multipart/related")) {
Multipart mulContent = (Multipart) part.getContent();
for (int j = 0, m = mulContent.getCount(); j < m; j++) {
Part contentPart = mulContent.getBodyPart(j);
if (!contentPart.isMimeType("text/*")) {
String fileName = "Resource";
//此方法返回 Part 对象的内容类型。
String type = contentPart.getContentType();
if (type != null) {
type = type.substring(0, type.indexOf("/"));
}
fileName = fileName + "[" + type + "]";
if (contentPart.getHeader("Content-Location") != null
&& contentPart.getHeader("Content-Location").length > 0) {
fileName = contentPart.getHeader("Content-Location")[0];
}
InputStream is = contentPart.getInputStream();
resourceList.add(new ResourceFileBean(fileName, is));
}
}
} else {
Multipart mp = null;
Object content = part.getContent();
if (content instanceof Multipart) {
mp = (Multipart) content;
} else {
return;
}
for (int i = 0, n = mp.getCount(); i < n; i++) {
Part body = mp.getBodyPart(i);
getRelatedPart(body, resourceList);
}
}
}
/**
* 取得纯文本的邮件内容,如果邮件是 HTML 格式的,则会过滤 HTML 标签后返回。.
* @return String
* 纯文本的邮件内容
*/
public String getPlainText() {
try {
String content = getText(message);
return htmlToText(content);
} catch (MessagingException e) {
e.printStackTrace();
return "";
} catch (IOException e) {
e.printStackTrace();
return "";
}
}
/**
* 取得文本内容,如果邮件是 HTML 格式的,则会返回所有 HTML 标签.
* @param p
* Part 对象
* @return String
* 文本内容
* @throws MessagingException
* the messaging exception
* @throws IOException
* Signals that an I/O exception has occurred.
*/
private String getText(Part p) throws MessagingException, IOException {
if (p.isMimeType("text/*")) {
if (p.isMimeType("text/html")) {
htmlResource = new ResourceFileBean("html-file.html", p.getInputStream());
}
String s = (String) p.getContent();
s = MimeUtility.decodeText(s);
String contenttype = p.getContentType();
String[] types = contenttype.split(";");
for (String i : types) {
if (i.toLowerCase().indexOf("charset") > 0) {
String[] values = i.split("=");
if (values != null && values.length >= 2) {
String charSet = values[1].trim();
if (charSet.indexOf("\"") != -1 || charSet.indexOf("\'") != -1) {
charSet = charSet.substring(1, charSet.length() - 1);
}
textCharset = charSet;
}
}
}
return s;
}
if (p.isMimeType("multipart/alternative")) {
Multipart mp = (Multipart) p.getContent();
String text = null;
for (int i = 0; i < mp.getCount(); i++) {
Part bp = mp.getBodyPart(i);
if (bp.isMimeType("text/plain")) {
if (text == null) {
text = getText(bp);
}
break;
} else if (bp.isMimeType("text/html")) {
String s = getText(bp);
if (s != null) {
return s;
}
} else {
return getText(bp);
}
}
return text;
} else if (p.isMimeType("multipart/*")) {
Multipart mp = (Multipart) p.getContent();
for (int i = 0; i < mp.getCount(); i++) {
String s = getText(mp.getBodyPart(i));
if (s != null) {
return s;
}
}
}
return null;
}
/**
* 将 html 格式的文本过滤掉标签.
* @param html
* html 格式的字符串
* @return String
* 过滤掉 html 标签后的文本。如果 html 为空,返回空串""
*/
private String htmlToText(String html) {
if (html == null) {
return "";
}
DOMFragmentParser parser = new DOMFragmentParser();
CoreDocumentImpl codeDoc = new CoreDocumentImpl();
InputSource inSource = new InputSource(new ByteArrayInputStream(html.getBytes()));
inSource.setEncoding(textCharset);
DocumentFragment doc = codeDoc.createDocumentFragment();
try {
parser.parse(inSource, doc);
} catch (Exception e) {
return "";
}
textBuffer = new StringBuffer();
processNode(doc);
return textBuffer.toString();
}
/**
* 遍历节点 node 以过滤所有的 html 标签.
* @param node
* 要遍历的节点
*/
private void processNode(Node node) {
if (node == null) {
return;
}
if ("BR".equals(node.getNodeName())) {
textBuffer.append("\n" + newLine(node));
} else if ("TR".equals(node.getNodeName())) {
textBuffer.append("\n" + newLine(node));
} else if ("DIV".equals(node.getNodeName())) {
textBuffer.append("\n" + newLine(node));
} else if ("BLOCKQUOTE".equals(node.getNodeName())) {
if (node.getAttributes() != null) {
Node item = node.getAttributes().getNamedItem("type");
if (item != null) {
if ("cite".equalsIgnoreCase(item.getNodeValue())) {
textBuffer.append("\n" + newLine(node));
}
}
}
} else if ("LI".equals(node.getNodeName())) {
textBuffer.append("\n" + newLine(node) + " ");
}
if (node.getNodeType() == Node.TEXT_NODE) {
String value = node.getNodeValue();
if (value != null) {
if (value.indexOf("\n") != -1 && "".equals(value.trim())) {
return;
} else if (value.indexOf("\n") != -1) {
if (!"BODY".equals(node.getParentNode().getNodeName())) {
value = value.replaceAll("\n", "");
}
}
}
textBuffer.append(value);
} else if (node.hasChildNodes()) {
NodeList childList = node.getChildNodes();
int childLen = childList.getLength();
for (int count = 0; count < childLen; count++) {
processNode(childList.item(count));
}
} else {
return;
}
}
/**
* 生成一个新行.
* @param node
* 节点
* @return String
* 由 > 组成的字符串
*/
private String newLine(Node node) {
Node parentNode = node;
int count = 0;
while (parentNode != null) {
String parentName = parentNode.getNodeName();
if (parentNode.getAttributes() == null) {
parentNode = parentNode.getParentNode();
continue;
}
Node namedItem = parentNode.getAttributes().getNamedItem("type");
if (namedItem == null) {
parentNode = parentNode.getParentNode();
continue;
}
if ("BLOCKQUOTE".equals(parentName)) {
if ("cite".equalsIgnoreCase(namedItem.getNodeValue())) {
count++;
}
}
parentNode = parentNode.getParentNode();
}
if (count > maxArrow || count == 0) {
maxArrow = count;
}
StringBuffer arrow = new StringBuffer();
for (int i = 0; i < maxArrow; i++) {
if (i == maxArrow - 1) {
arrow.append("> ");
} else {
arrow.append(">");
}
}
return arrow.toString();
}
/**
* 获取消息对象.
* @return Message
* 消息对象.
*/
public Message getMessage() {
return message;
}
/**
* 获取 ResourceFileBean 对象.
* @return ResourceFileBean
* ResourceFileBean 对象
*/
public ResourceFileBean getHtmlResource() {
return htmlResource;
}
/**
* The main method.
* @param args
* the arguments
* @throws IOException
* Signals that an I/O exception has occurred.
*/
public static void main(String[] args) throws IOException {
Properties prep = new Properties();
Session session = Session.getInstance(prep);
try {
Message msg = new MimeMessage(session, new FileInputStream("/data/terry/Desktop/email.eml"));
MessageParser parser = new MessageParser(msg);
System.out.println(parser.getPlainText());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
}
}
}
| 12,553 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
MailSender.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/base_plugins/heartsome.java.tools.plugin/src/cn/org/tools/utils/mail/MailSender.java | /**
* MailSender.java
*
* Version information :
*
* Date:Jan 13, 2010
*
* Copyright notice :
*/
package cn.org.tools.utils.mail;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import javax.mail.Address;
import javax.mail.Authenticator;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeUtility;
import org.apache.commons.mail.EmailAttachment;
import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.HtmlEmail;
import cn.org.tools.utils.string.StringUtilsBasic;
/**
* The Class MailSender.
* @author Terry
* @version
* @since JDK1.6
*/
public class MailSender {
/** The port. */
private int port = 25;
/** The user name. */
private String userName;
/** The password. */
private String password;
/** The props. */
private Properties props;
/** The session. */
private Session session;
/** The SS l_ factory. */
final String strSslFactory = "javax.net.ssl.SSLSocketFactory";
private HtmlEmail email;
/**
* 构造方法.
* @param host
* 邮件服务器,如:"mail.heartsome.net"
* @param userName
* 邮箱用户名
* @param password
* 邮箱密码
*/
public MailSender(String host, String userName, String password) {
this(host, -1, userName, password);
}
/**
* 构造方法.
* @param host
* 邮件服务器,如:"mail.heartsome.net"
* @param port
* 端口号
* @param userName
* 邮箱用户名
* @param password
* 邮箱密码
*/
public MailSender(String host, int port, String userName, String password) {
this(host, "smtp", port, userName, password, false);
}
/**
* 构造方法.
* @param host
* 邮件服务器,如:"mail.heartsome.net"
* @param protocol
* 邮件协议
* @param port
* 端口号
* @param userName
* 邮箱用户名
* @param password
* 邮箱密码
* @param ssl
* 是否应用 SSL 安全协议
*/
public MailSender(String host, String protocol, int port, String userName, String password, boolean ssl) {
props = new Properties();
if (port != -1) {
this.port = port;
}
this.userName = userName;
this.password = password;
props.setProperty("mail." + protocol + ".auth", "true");
props.setProperty("mail.transport.protocol", protocol);
props.setProperty("mail.host", host);
props.setProperty("mail." + protocol + ".port", "" + this.port);
createSession();
email = new HtmlEmail();
email.setCharset("utf-8");
email.setMailSession(session);
if (ssl) {
email.setSSL(true);
}
}
/**
* 创建 session.
*/
private void createSession() {
session = Session.getInstance(props, new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(userName, password);
}
});
session.setDebug(true);
}
/**
* 设置发件人
* @param from
* 发件人邮箱地址
* @throws MessagingException
* @throws EmailException
*/
public void setFrom(String from) throws MessagingException, EmailException {
if (from == null) {
return;
}
Address address = new InternetAddress(from);
Map<String, String> map = getEmailInfo(address.toString());
email.setFrom(map.get("email"), map.get("name"));
}
/**
* 设置收件人,如果有多个收件人,用逗号分隔
* @param to
* 收件人邮箱地址
* @throws MessagingException
* @throws EmailException
*/
public void setTo(String to) throws MessagingException, EmailException {
if (to == null) {
return;
}
Address[] address = InternetAddress.parse(to);
for (Address i : address) {
Map<String, String> map = getEmailInfo(i.toString());
email.addTo(map.get("email"), map.get("name"));
}
}
/**
* 设置抄送人,如果有多个抄送人,用逗号分隔
* @param cc
* 抄送人邮箱地址
* @throws MessagingException
* @throws EmailException ;
*/
public void setCC(String cc) throws MessagingException, EmailException {
if (cc == null) {
return;
}
Address[] address = InternetAddress.parse(cc);
for (Address i : address) {
Map<String, String> map = getEmailInfo(i.toString());
email.addCc(map.get("email"), map.get("name"));
}
}
/**
* 设置密送人,如果有多个密送人,用逗号分隔
* @param bcc
* 密送人邮箱地址
* @throws MessagingException
* @throws EmailException ;
*/
public void setBCC(String bcc) throws MessagingException, EmailException {
if (bcc == null) {
return;
}
Address[] address = InternetAddress.parse(bcc);
for (Address i : address) {
Map<String, String> map = getEmailInfo(i.toString());
email.addBcc(map.get("email"), map.get("name"));
}
}
/**
* 设置回复人,如果有多个回复人,用逗号分隔
* @param reply
* @throws MessagingException
* @throws EmailException ;
*/
public void setReplyTo(String reply) throws MessagingException, EmailException {
if (reply == null) {
return;
}
Address[] address = InternetAddress.parse(reply);
for (Address i : address) {
Map<String, String> map = getEmailInfo(i.toString());
email.addReplyTo(map.get("email"), map.get("name"));
}
}
/**
* 设置主题
* @param subject
* 主题内容
* @throws MessagingException ;
*/
public void setSubject(String subject) throws MessagingException {
if (subject == null) {
return;
}
email.setSubject(subject);
}
/**
* 设置发送日期
* @param date
* 发送日期
* @throws MessagingException ;
*/
public void setSentDate(Date date) throws MessagingException {
if (date == null) {
return;
}
email.setSentDate(date);
}
/**
* 设置要发送的附件
* @param attachment
* 附件数组
* @throws MessagingException
* @throws UnsupportedEncodingException
* @throws EmailException ;
*/
public void setMixMail(File[] attachment) throws MessagingException, UnsupportedEncodingException, EmailException {
if (attachment != null) {
for (File file : attachment) {
EmailAttachment attach = new EmailAttachment();
attach.setPath(file.getAbsolutePath());
attach.setName(MimeUtility.encodeText(file.getName()));
email.attach(attach);
}
}
}
/**
* 设置要发送的附件,并对附件重命名
* @param attachment
* 附件的集合,key 为附件的名称,value为附件
* @throws MessagingException
* @throws UnsupportedEncodingException
* @throws EmailException ;
*/
public void setMixMailRename(Map<String, File> attachment) throws MessagingException, UnsupportedEncodingException,
EmailException {
if (attachment != null) {
for (String fileName : attachment.keySet()) {
EmailAttachment attach = new EmailAttachment();
attach.setPath(attachment.get(fileName).getAbsolutePath());
attach.setName(MimeUtility.encodeText(fileName));
email.attach(attach);
}
}
}
/**
* 设置邮件内容
* @param text
* html格式的邮件内容
* @throws MessagingException
* @throws EmailException ;
*/
public void setHtmlText(String text) throws MessagingException, EmailException {
if (StringUtilsBasic.checkNull(text)) {
email.setHtmlMsg(text);
}
}
/**
* 设置邮件消息
* @param text
* 消息内容
* @throws MessagingException
* @throws EmailException ;
*/
public void setText(String text) throws MessagingException, EmailException {
if (StringUtilsBasic.checkNull(text)) {
email.setMsg(text);
}
}
/**
* 发送邮件
* @throws EmailException ;
*/
public void send() throws EmailException {
email.send();
}
/**
* 过滤邮件中的收件人,抄送人,密送人中重复的邮箱地址,而只保留一条
* @throws AddressException
* @throws EmailException ;
*/
@SuppressWarnings("unchecked")
public void removeDumplicate() throws AddressException, EmailException {
Address from = email.getFromAddress();
List<Address> toList = MailUtils.removeDuplicate(from, email.getToAddresses());
List<Address> ccList = MailUtils.removeDuplicate(from, email.getCcAddresses());
List<Address> bccList = MailUtils.removeDuplicate(from, email.getBccAddresses());
ccList = MailUtils.removeDuplicate(toList, ccList);
bccList = MailUtils.removeDuplicate(toList, bccList);
bccList = MailUtils.removeDuplicate(ccList, bccList);
if (toList != null && toList.size() > 0) {
email.setTo(toList);
}
if (ccList != null && ccList.size() > 0) {
email.setCc(ccList);
}
if (bccList != null && bccList.size() > 0) {
email.setBcc(bccList);
}
}
/**
* 解析由前台传过来的“姓名 <地址>”字符串,得到姓名和地址键值对
* @param str
* “姓名 <地址>”字符串
* @return Map<String, String>
* name 和 email 键值对;
*/
private Map<String, String> getEmailInfo(String str) {
int temp = str.indexOf("<");
int temp1 = str.indexOf(">");
Map<String, String> map = new HashMap<String, String>();
if (temp != -1 && temp1 != -1) {
String name = str.substring(0, temp).trim();
String email = str.substring(temp + 1, temp1).trim();
map.put("name", name);
map.put("email", email);
} else {
int temp2 = str.indexOf("@");
if (temp2 != -1) {
String name = str.substring(0, temp2).trim();
map.put("name", name);
map.put("email", str);
}
}
return map;
}
}
| 9,729 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
ResourceFileBean.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/base_plugins/heartsome.java.tools.plugin/src/cn/org/tools/utils/mail/ResourceFileBean.java | /**
* ResourceFileBean.java
*
* Version information :
*
* Date:Jan 13, 2010
*
* Copyright notice :
*/
package cn.org.tools.utils.mail;
import java.io.InputStream;
/**
* The Class ResourceFileBean.
* @author Terry
* @version
* @since JDK1.6
*/
public class ResourceFileBean {
/** 文件名. */
public String fileName;
/** 输入流. */
public InputStream inputStream;
/**
* 构造方法.
* @param fileName
* 文件名
* @param inputStream
* 输入流
*/
public ResourceFileBean(String fileName, InputStream inputStream) {
this.fileName = fileName;
this.inputStream = inputStream;
}
}
| 647 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
MailReceiver.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/base_plugins/heartsome.java.tools.plugin/src/cn/org/tools/utils/mail/MailReceiver.java | /**
* MailReceiver.java
*
* Version information :
*
* Date:Jan 13, 2010
*
* Copyright notice :
*/
package cn.org.tools.utils.mail;
import java.security.Security;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.Flags;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Store;
/**
* The Class MailReceiver.
* @author Terry
* @version
* @since JDK1.6
*/
public class MailReceiver {
/** The port. */
private int port = 25;
/** The user name. */
private String userName;
/** The password. */
private String password;
/** The props. */
private Properties props;
/** The session. */
private Session session;
/** The folder list. */
private List<Folder> folderList;
/** The store. */
private Store store;
/** The SSL factory. */
final String strSslFactory = "javax.net.ssl.SSLSocketFactory";
/**
* 使用该方法创建对象时,默认使用 POP3 邮件协议,不使用 SSL 安全协议.
* @param host
* 邮件服务器,如:"mail.heartsome.net"
* @param userName
* 邮箱用户名
* @param password
* 邮箱密码
*/
public MailReceiver(String host, String userName, String password) {
this(host, "pop3", 110, userName, password, false);
}
/**
* 构造方法.
* @param host
* 邮件服务器,如:"mail.heartsome.net"
* @param protocol
* 邮件协议
* @param port
* 端口号
* @param userName
* 邮箱用户名
* @param password
* 邮箱密码
* @param ssl
* 是否应用 SSL 安全协议
*/
public MailReceiver(String host, String protocol, int port, String userName, String password, boolean ssl) {
folderList = new ArrayList<Folder>();
props = new Properties();
if (port != -1) {
this.port = port;
}
this.userName = userName;
this.password = password;
props.setProperty("mail.host", host);
props.setProperty("mail.store.protocol", protocol);
props.setProperty("mail." + protocol + ".port", "" + this.port);
if (ssl) {
Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
props.setProperty("mail." + protocol + ".socketFactory.class", strSslFactory);
props.setProperty("mail." + protocol + ".socketFactory.fallback", "false");
props.setProperty("mail." + protocol + ".socketFactory.port", "" + this.port);
}
createSession();
}
/**
* 创建 Session
*/
private void createSession() {
session = Session.getInstance(props, new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(userName, password);
}
});
}
/**
* 接收邮件.
* @param expunge
* 邮件是否删除
* @return List<Message>
* 收到的邮件集合
* @throws MessagingException
* the messaging exception
*/
public List<Message> receive(boolean expunge) throws MessagingException {
List<Message> result = new ArrayList<Message>();
store = session.getStore();
store.connect();
Folder folder = store.getFolder("INBOX");
folder.open(Folder.READ_WRITE);
for (Message message : folder.getMessages()) {
result.add(message);
//设置邮件的 DELETED 标志
message.setFlag(Flags.Flag.DELETED, expunge);
}
folderList.add(folder);
return result;
}
/**
* 释放资源.
* @throws MessagingException
* the messaging exception
*/
public void releaseResource() throws MessagingException {
for (Folder folder : folderList) {
folder.close(true);
}
if (store != null) {
store.close();
}
}
/**
* The main method.
* @param args
* the arguments
* @throws MessagingException
* the messaging exception
*/
public static void main(String[] args) throws MessagingException {
MailReceiver receiver = new MailReceiver("mail.heartsome.net", "pop3", 110, "[email protected]",
"BxKd7T00", false);
receiver.receive(false);
}
}
| 4,173 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
FileBasic.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/base_plugins/heartsome.java.tools.plugin/src/cn/org/tools/utils/file/FileBasic.java | /**
* FileBasic.java
*
* Version information :
*
* Date:Jan 13, 2010
*
* Copyright notice :
*/
package cn.org.tools.utils.file;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
/**
* The Class FileBasic.
* @author Terry
* @version
* @since JDK1.6
*/
public class FileBasic {
/**
* 构造方法.
*/
protected FileBasic() {
throw new UnsupportedOperationException(); // prevents calls from subclass
}
/**
* 计算文件的 MD5 码.
* @param file
* 文件对象
* @return String
* 文件的 MD5 编码
* @throws NoSuchAlgorithmException
* the no such algorithm exception
* @throws IOException
* Signals that an I/O exception has occurred.
*/
public static String getMD5(File file) throws NoSuchAlgorithmException, IOException {
FileInputStream fis = null;
try {
MessageDigest md = MessageDigest.getInstance("MD5");
fis = new FileInputStream(file);
byte[] buffer = new byte[8192];
int length = -1;
while ((length = fis.read(buffer)) != -1) {
md.update(buffer, 0, length);
}
return bytesToString(md.digest());
} finally {
if (fis != null) {
fis.close();
}
}
}
/**
* 将字节数组转换为字符串.
* @param data
* 字节数组
* @return String
* 转换后的字符串
*/
public static String bytesToString(byte[] data) {
char[] hexDigits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
char[] temp = new char[data.length * 2];
for (int i = 0; i < data.length; i++) {
byte b = data[i];
temp[i * 2] = hexDigits[b >>> 4 & 0x0f];
temp[i * 2 + 1] = hexDigits[b & 0x0f];
}
return new String(temp);
}
}
| 1,840 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
Regexp.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/base_plugins/heartsome.java.tools.plugin/src/cn/org/tools/utils/regexp/Regexp.java | /**
* Regexp.java
*
* Version information :
*
* Date:Jan 13, 2010
*
* Copyright notice :
*/
package cn.org.tools.utils.regexp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
/**
* 正则表达式工具类.
* @author Terry
* @version
* @since JDK1.6
*/
public final class Regexp {
/** 保放有四组对应分隔符. */
static final Set<String> SEPARATOR_SET = new TreeSet<String>();
{
SEPARATOR_SET.add("(");
SEPARATOR_SET.add(")");
SEPARATOR_SET.add("[");
SEPARATOR_SET.add("]");
SEPARATOR_SET.add("{");
SEPARATOR_SET.add("}");
SEPARATOR_SET
.add("<\"</span><span>); </span> </li> <li class=\"\"><span> SEPARATOR_SET.add(</span><span class=\"string\">\">");
}
/** 存放各种正规表达式(以key->value的形式). */
public static HashMap<String, String> regexpHash = new HashMap<String, String>();
/** 存放各种正规表达式. */
public static List<String> matchingResultList = new ArrayList<String>();
/**
* 构造方法.
*/
private Regexp() {
}
/**
* 返回 Regexp 实例.
* @return Regexp
* Regexp 实例.
*/
public static Regexp getInstance() {
return new Regexp();
}
/**
* 匹配图象 格式: /相对路径/文件名.后缀 (后缀为gif,dmp,png) 匹配 : /forum/head_icon/admini2005111_ff.gif 或 admini2005111.dmp 不匹配:
* c:/admins4512.gif
*/
public static final String ICON_REGEXP = "^(/{0,1}\\w){1,}\\.(gif|dmp|png|jpg)$|^\\w{1,}\\.(gif|dmp|png|jpg)$";
/** 匹配email地址 格式: [email protected] 匹配 : [email protected] 或 [email protected] 不匹配: foo@bar 或 [email protected] */
public static final String EMAIL_REGEXP = "(?:\\w[-._\\w]*\\w@\\w[-._\\w]*\\w\\.\\w{2,3}$)";
/**
* 匹配并提取url 格式: XXXX://XXX.XXX.XXX.XX/XXX.XXX?XXX=XXX 匹配 : http://www.suncer.com 或news://www 提取(MatchResult
* matchResult=matcher.getMatch()): matchResult.group(0)= http://www.suncer.com:8080/index.html?login=true
* matchResult.group(1) = http matchResult.group(2) = www.suncer.com matchResult.group(3) = :8080
* matchResult.group(4) = /index.html?login=true 不匹配: c:\window
*/
public static final String URL_REGEXP = "(\\w+)://([^/:]+)(:\\d*)?([^\\s]*)";
/**
* 匹配并提取http 格式: http://XXX.XXX.XXX.XX/XXX.XXX?XXX=XXX 或 ftp://XXX.XXX.XXX 或 https://XXX 匹配 :
* http://www.suncer.com:8080/index.html?login=true 提取(MatchResult matchResult=matcher.getMatch()):
* matchResult.group(0)= http://www.suncer.com:8080/index.html?login=true matchResult.group(1) = http
* matchResult.group(2) = www.suncer.com matchResult.group(3) = :8080 matchResult.group(4) = /index.html?login=true
* 不匹配: news://www
*/
public static final String HTTP_REGEXP = "(http|https|ftp)://([^/:]+)(:\\d*)?([^\\s]*)";
/** 匹配日期 格式(首位不为0): XXXX-XX-XX 或 XXXX XX XX 或 XXXX-X-X 范围:1900--2099 匹配 : 2005-04-04 不匹配: 01-01-01. */
public static final String DATE_REGEXP = "^((((19){1}|(20){1})d{2})|d{2})[-\\s]{1}[01]{1}d{1}[-\\s]{1}[0-3]{1}d{1}$";
/**
* 匹配电话 格式为: 0XXX-XXXXXX(10-13位首位必须为0) 或0XXX XXXXXXX(10-13位首位必须为0) 或 (0XXX)XXXXXXXX(11-14位首位必须为0) 或
* XXXXXXXX(6-8位首位不为0) 或 XXXXXXXXXXX(11位首位不为0) 匹配 : 0371-123456 或 (0371)1234567 或 (0371)12345678 或 010-123456 或
* 010-12345678 或 12345678912 不匹配: 1111-134355 或 0123456789.
*/
public static final String PHONE_REGEXP = "^(?:0[0-9]{2,3}[-\\s]{1}|\\(0[0-9]{2,4}\\))[0-9]{6,8}$|^[1-9]{1}[0-9]{5,7}$|^[1-9]{1}[0-9]{10}$";
/**
* 匹配身份证 格式为: XXXXXXXXXX(10位) 或 XXXXXXXXXXXXX(13位) 或 XXXXXXXXXXXXXXX(15位) 或 XXXXXXXXXXXXXXXXXX(18位) 匹配 :
* 0123456789123 不匹配: 0123456.
*/
public static final String ID_CARD_REGEXP = "^\\d{10}|\\d{13}|\\d{15}|\\d{18}$";
/** 匹配邮编代码 格式为: XXXXXX(6位) 匹配 : 012345 不匹配: 0123456. */
public static final String ZIP_REGEXP = "^[0-9]{6}$";
/**
* 匹配邮编代码 不包括特殊字符的匹配 (字符串中不包括符号 数学次方号^ 单引号' 双引号" 分号; 逗号, 帽号: 数学减号- 右尖括号> 左尖括号< 反斜杠\ 即空格,制表符,回车符等 ) 格式为: x 或 一个一上的字符 匹配 :
* 012345 不匹配: 0123456.
*/
public static final String NON_SPECIAL_CHAR_REGEXP = "^[^'\"\\;,:-<>\\s].+$";
/** 匹配非负整数(正整数 + 0). */
public static final String NON_NEGATIVE_INTEGERS_REGEXP = "^\\d+$";
/** 匹配不包括零的非负整数(正整数 > 0). */
public static final String NON_ZERO_NEGATIVE_INTEGERS_REGEXP = "^[1-9]+\\d*$";
/** 匹配正整数. */
public static final String POSITIVE_INTEGER_REGEXP = "^[0-9]*[1-9][0-9]*$";
/** 匹配非正整数(负整数 + 0). */
public static final String NON_POSITIVE_INTEGERS_REGEXP = "^((-\\d+)|(0+))$";
/** 匹配负整数. */
public static final String NEGATIVE_INTEGERS_REGEXP = "^-[0-9]*[1-9][0-9]*$";
/** 匹配整数. */
public static final String INTEGER_REGEXP = "^-?\\d+$";
/** 匹配非负浮点数(正浮点数 + 0). */
public static final String NON_NEGATIVE_RATIONAL_NUMBERS_REGEXP = "^\\d+(\\.\\d+)?$";
/** 匹配正浮点数. */
public static final String POSITIVE_RATIONAL_NUMBERS_REGEXP = "^(([0-9]+\\.[0-9]*[1-9][0-9]*";
/** 匹配非正浮点数(负浮点数 + 0). */
public static final String NON_POSITIVE_RATIONAL_NUMBERS_REGEXP = "^((-\\d+(\\.\\d+)?)|(0+(\\.0+)?))$";
/** 匹配负浮点数. */
public static final String NEGATIVE_RATIONAL_NUMBERS_REGEXP = "^(-(([0-9]+\\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\\.[0-9]+)|([0-9]*[1-9][0-9]*)))$";
/** 匹配浮点数. */
public static final String RATIONAL_NUMBERS_REGEXP = "^(-?\\d+)(\\.\\d+)?$";
/** 匹配由26个英文字母组成的字符串. */
public static final String LETTER_REGEXP = "^[A-Za-z]+$";
/** 匹配由26个英文字母的大写组成的字符串. */
public static final String UPWARD_LETTER_REGEXP = "^[A-Z]+$";
/** 匹配由26个英文字母的小写组成的字符串. */
public static final String LOWER_LETTER_REGEXP = "^[a-z]+$";
/** 匹配由数字和26个英文字母组成的字符串. */
public static final String LETTER_NUMBER_REGEXP = "^[A-Za-z0-9]+$";
/** 匹配由数字、26个英文字母或者下划线组成的字符串. */
public static final String LETTER_NUMBER_UNDERLINE_REGEXP = "^\\w+$";
/** 匹配由数字、26个英文字母、汉字或者下划线组成的字符串. */
public static final String USERNAME_EN_CN = "^[\\w\u4e00-\u9fa5]*$";
/**
* 添加正规表达式 (以key->value的形式存储).
* @param regexpName
* 正规表达式名称 `
* @param regexp
* 正规表达式内容
*/
public void putRegexpHash(String regexpName, String regexp) {
regexpHash.put(regexpName, regexp);
}
/**
* 得到正规表达式内容 (通过key名提取出value[正规表达式内容]).
* @param regexpName
* 正规表达式名称
* @return String
* 正规表达式内容,如果根据名称找不到内容,则返回空串""
*/
public String getRegexpHash(String regexpName) {
if (regexpHash.get(regexpName) != null) {
return ((String) regexpHash.get(regexpName));
} else {
System.out.println("在regexpHash中没有此正规表达式");
return "";
}
}
/**
* 清除正规表达式存放单元.
*/
public void clearRegexpHash() {
regexpHash.clear();
return;
}
}
| 7,551 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
Base64Utils.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/base_plugins/heartsome.java.tools.plugin/src/cn/org/tools/utils/code/Base64Utils.java | /**
* Base64Utils.java
*
* Version information :
*
* Date:Jan 13, 2010
*
* Copyright notice :
*/
package cn.org.tools.utils.code;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.commons.codec.binary.Base64;
/**
* 对文件进行 Base64 编码/解码的工具类.
* @author Terry
* @version
* @since JDK1.6
*/
public class Base64Utils {
/** 缓冲区大小,单位是 KB. */
private int buffer;
/**
* 构造方法.
*/
public Base64Utils() {
this(1);
}
/**
* 构造方法.
* @param buffer
* 缓冲区大小
*/
public Base64Utils(int buffer) {
this.buffer = buffer;
}
/**
* 对文件加密.
* @param inFile
* 要加密的文件
* @param outFile
* 加密后的文件
* @throws IOException
* Signals that an I/O exception has occurred.
*/
public void encode(File inFile, File outFile) throws IOException {
if (!inFile.exists()) {
return;
}
FileInputStream fis;
fis = new FileInputStream(inFile);
FileOutputStream fos = new FileOutputStream(outFile);
encode(fis, fos);
fis.close();
fos.close();
}
/**
* 对文件加密.
* @param fis
* 文件输入流,用于读入源文件
* @param fos
* 文件输出流,用于加密后写入文件
* @throws IOException
* Signals that an I/O exception has occurred.
*/
public void encode(FileInputStream fis, FileOutputStream fos) throws IOException {
byte[] buf = new byte[buffer * 1024 * 3];
byte[] write = null;
int i = 0;
while ((i = fis.read(buf)) != -1) {
if (i < buf.length) {
byte[] temp = new byte[i];
System.arraycopy(buf, 0, temp, 0, i);
//对字节数组中指定的内容执行Base64 编码
write = Base64.encodeBase64(temp);
} else {
write = Base64.encodeBase64(buf);
}
fos.write(write, 0, write.length);
}
}
/**
* 对文件解密.
* @param inFile
* 要解密的文件
* @param outFile
* 解密后的文件
* @throws IOException
* Signals that an I/O exception has occurred.
*/
public void decode(File inFile, File outFile) throws IOException {
if (!inFile.exists()) {
return;
}
FileInputStream fis;
fis = new FileInputStream(inFile);
FileOutputStream fos = new FileOutputStream(outFile);
decode(fis, fos);
fis.close();
fos.close();
}
/**
* 对文件解密.
* @param fis
* 文件输入流,用于读入源文件
* @param fos
* 文件输出流,用于解密后写入文件
* @throws IOException
* Signals that an I/O exception has occurred.
*/
public void decode(FileInputStream fis, FileOutputStream fos) throws IOException {
byte[] buf = new byte[buffer * 1024 * 4];
byte[] write = null;
int i = 0;
while ((i = fis.read(buf)) != -1) {
if (i < buf.length) {
byte[] temp = new byte[i];
System.arraycopy(buf, 0, temp, 0, i);
//对字节数组中指定的内容执行 Base64 解码
write = Base64.decodeBase64(temp);
} else {
write = Base64.decodeBase64(buf);
}
fos.write(write, 0, write.length);
}
}
}
| 3,226 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
Arith.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/base_plugins/heartsome.java.tools.plugin/src/cn/org/tools/utils/math/Arith.java | /**
* Arith.java
*
* Version information :
*
* Date:Jan 13, 2010
*
* Copyright notice :
*/
package cn.org.tools.utils.math;
import java.math.BigDecimal;
import java.util.Random;
/**
* 由于Java的简单类型不能够精确的对浮点数进行运算,该工具类提供精确的浮点数运算,包括加减乘除和四舍五入。.
* @author peason
* @version
* @since JDK1.6
*/
public final class Arith {
/** 默认除法运算精度. */
private static final int DEF_DIV_SCALE = 10;
/**
* 构造方法,该类不能实例化
*/
private Arith() {
}
/**
* 提供精确的加法运算。
* @param v1
* 被加数
* @param v2
* 加数
* @return double
* 两个参数的和
*/
public static double add(double v1, double v2) {
BigDecimal b1 = new BigDecimal(Double.toString(v1));
BigDecimal b2 = new BigDecimal(Double.toString(v2));
double result = b1.add(b2).doubleValue();
b1 = null;
b2 = null;
return result;
}
/**
* 获得随机数.
* @param num
* 生成的随机数最大值:num - 1
* @return int
* 生成的随机数的范围:[0,num)
*/
public static int random(int num) {
Random random = new Random();
return Math.abs(random.nextInt()) % num;
}
/**
* 提供精确的减法运算。.
* @param v1
* 被减数
* @param v2
* 减数
* @return double
* 两个参数的差
*/
public static double sub(double v1, double v2) {
BigDecimal b1 = new BigDecimal(Double.toString(v1));
BigDecimal b2 = new BigDecimal(Double.toString(v2));
double result = b1.subtract(b2).doubleValue();
b1 = null;
b2 = null;
return result;
}
/**
* 提供精确的乘法运算。.
* @param v1
* 被乘数
* @param v2
* 乘数
* @return double
* 两个参数的乘积
*/
public static double mul(double v1, double v2) {
BigDecimal b1 = new BigDecimal(Double.toString(v1));
BigDecimal b2 = new BigDecimal(Double.toString(v2));
double result = b1.multiply(b2).doubleValue();
b1 = null;
b2 = null;
return result;
}
/**
* 提供(相对)精确的除法运算,当发生除不尽的情况时,精确到 小数点以后10位,以后的数字四舍五入。.
* @param v1
* 被除数
* @param v2
* 除数
* @return double
* 两个参数的商
*/
public static double div(double v1, double v2) {
return div(v1, v2, DEF_DIV_SCALE);
}
/**
* The main method.
* @param args
* the arguments
*/
public static void main(String[] args) {
System.out.println(5 / 4 + 1);
System.out.println(random(6));
// System.out.println(div(1, 9, -1));
}
/**
* 提供(相对)精确的除法运算。当发生除不尽的情况时,由 scale 参数指定精度,以后的数字四舍五入。.
* @param v1
* 被除数
* @param v2
* 除数
* @param scale
* 表示需要精确到小数点以后几位。
* @return double
* 两个参数的商
*/
public static double div(double v1, double v2, int scale) {
if (scale < 0) {
throw new IllegalArgumentException("The scale must be a positive integer or zero");
}
BigDecimal b1 = new BigDecimal(Double.toString(v1));
BigDecimal b2 = new BigDecimal(Double.toString(v2));
double result = b1.divide(b2, scale, BigDecimal.ROUND_HALF_UP).doubleValue();
b1 = null;
b2 = null;
return result;
}
/**
* 提供精确的小数位四舍五入处理。.
* @param v
* 需要四舍五入的数字
* @param scale
* 小数点后保留几位
* @return double
* 四舍五入后的结果
*/
public static double round(double v, int scale) {
if (scale < 0) {
throw new IllegalArgumentException("The scale must be a positive integer or zero");
}
BigDecimal b = new BigDecimal(Double.toString(v));
BigDecimal one = new BigDecimal("1");
double result = b.divide(one, scale, BigDecimal.ROUND_HALF_UP).doubleValue();
b = null;
one = null;
return result;
}
}
| 4,098 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
Calculator.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/base_plugins/heartsome.java.tools.plugin/src/cn/org/tools/utils/math/Calculator.java | /**
* Calculator.java
*
* Version information :
*
* Date:Jan 13, 2010
*
* Copyright notice :
*/
package cn.org.tools.utils.math;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.StringCharacterIterator;
import java.util.Stack;
import java.util.Vector;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* 对数学表达式求值的工具类.
* @author Terry
* @version
* @since JDK1.6
*/
public class Calculator {
/**
* 构造方法.
*/
protected Calculator() {
throw new UnsupportedOperationException(); // prevents calls from subclass
}
/**
* The main method.
* @param args
* the arguments
* @throws IOException
* Signals that an I/O exception has occurred.
*/
public static void main(String[] args) throws IOException {
String strInput;
double fOutput;
//测试用例:1-3*(4-(2+5*3)+5)-6/(1+2)=23
//测试用例:11.2+3.1*(423-(2+5.7*3.4)+5.6)-6.4/(15.5+24)=1273.4199746835445
while (true) {
System.out.print("输入表达式: ");
System.out.flush();
strInput = getString();
if (strInput.equals("")) {
break;
}
// 以下对输入字符串做规则处理
strInput = Calculator.checkexpression(strInput);
if (strInput.equals("")) {
System.out.println(" 表达式出错 ");
}
// 以下对输入字符串做表达式转换
Vector<String> vCompute = Calculator.getexpression(strInput);
for (int i = 0; i < vCompute.size(); i++) {
System.out.println("" + vCompute.get(i));
}
// 以下进行后缀表达式转换
Vector<String> vTmpPrefix = Calculator.transformprefix(vCompute);
for (int i = 0; i < vTmpPrefix.size(); i++) {
System.out.println(vTmpPrefix.get(i));
}
// 以下进行后缀表达式运算
fOutput = Calculator.evaluateprefix(vTmpPrefix);
System.out.println("结果 = " + fOutput);
}
}
/**
* 静态方法,用来从控制台读入表达式.
* @return String
* 表达式字符串
* @throws IOException
* Signals that an I/O exception has occurred.
*/
private static String getString() throws IOException {
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
String s = br.readLine();
return s;
}
/**
* 输入字符串转换.把从控制台读入的字符串转成表达式存在一个队列中. 例:123+321 存为"123""+""321"
* @param str
* 表达式字符串
* @return Vector<String>
* 表达式集合
*/
private static Vector<String> getexpression(String str) {
Vector<String> vTemp = new Vector<String>();
char[] temp = new char[str.length()];
str.getChars(0, str.length(), temp, 0);
String fi = "";
int i = 0;
// 匹配数字和小数点
String regexFig = "[\\.\\d]";
// 匹配运算符(+,-,*,/)和括号("(",")")
String regexOperator = "[\\+\\-\\*/\\(\\)]";
Pattern pattertFig = Pattern.compile(regexFig);
Pattern patternOperator = Pattern.compile(regexOperator);
Matcher m = null;
boolean b;
while (i < str.length()) {
Character c = new Character(temp[i]);
String s = c.toString();
m = patternOperator.matcher(s);
b = m.matches();
if (b) {
vTemp.add(fi);
fi = "";
vTemp.add(s);
}
m = pattertFig.matcher(s);
b = m.matches();
if (b) {
fi = fi + s;
}
i++;
}
vTemp.add(fi);
return vTemp;
}
/**
* 转换中序表示式为前序表示式.
* @param parmVExpression
* 表示式的集合
* @return Vector<String>
* 转换后的前序表示式
*/
private static Vector<String> transformprefix(Vector<String> parmVExpression) {
Vector<String> vPrefix = new Vector<String>();
Stack<String> stackTmp = new Stack<String>();
// 匹配正浮点数
String strRegexFloat = "\\d+(\\.\\d+)?";
Pattern patternFloat = Pattern.compile(strRegexFloat);
Matcher m = null;
boolean b;
String strElem = "";
for (int i = 0; i < parmVExpression.size(); i++) {
strElem = parmVExpression.get(i).toString();
m = patternFloat.matcher(strElem);
b = m.matches();
if (b) {
vPrefix.add(strElem);
}
if (strElem.equals("+") || strElem.equals("-")) {
if (stackTmp.isEmpty()) {
stackTmp.push(strElem);
} else {
while (!stackTmp.isEmpty()) {
String strTmp = stackTmp.peek();
if (strTmp.equals("(")) {
break;
} else {
vPrefix.add(stackTmp.pop());
}
}
stackTmp.push(strElem);
}
}
if (strElem.equals("*") || strElem.equals("/")) {
if (stackTmp.isEmpty()) {
stackTmp.push(strElem);
} else {
while (!stackTmp.isEmpty()) {
String strTmp = stackTmp.peek();
if (strTmp.equals("(") || strTmp.equals("+") || strTmp.equals("-")) {
break;
} else {
vPrefix.add(stackTmp.pop());
}
}
stackTmp.push(strElem);
}
}
if (strElem.equals("(")) {
stackTmp.push(strElem);
}
if (strElem.equals(")")) {
while (!stackTmp.isEmpty()) {
String strTmp = stackTmp.peek();
if (strTmp.equals("(")) {
stackTmp.pop();
break;
} else {
vPrefix.add(stackTmp.pop());
}
}
}
}
while (!stackTmp.isEmpty()) {
vPrefix.add(stackTmp.pop());
}
return vPrefix;
}
/**
* 前缀表示式求值.
* @param parmVPrefix
* 前缀表示式的集合
* @return double
* 前缀表示式的值
*/
private static strictfp double evaluateprefix(Vector<String> parmVPrefix) {
String strTmp = "";
double num1, num2, interans = 0;
Stack<Double> stackCompute = new Stack<Double>();
int i = 0;
while (i < parmVPrefix.size()) {
strTmp = parmVPrefix.get(i).toString();
if (!strTmp.equals("+") && !strTmp.equals("-") && !strTmp.equals("*") && !strTmp.equals("/")) {
interans = stackCompute.push(Double.parseDouble(strTmp));
} else {
num2 = (stackCompute.pop());
num1 = (stackCompute.pop());
if (strTmp.equals("+")) {
interans = num1 + num2;
}
if (strTmp.equals("-")) {
interans = num1 - num2;
}
if (strTmp.equals("*")) {
interans = num1 * num2;
}
if (strTmp.equals("/")) {
interans = num1 / num2;
}
stackCompute.push(interans);
}
i++;
}
return interans;
}
/**
* 表达式求值。
* @param parmStrInput
* 表达式字符串
* @return double
* 表达式的值
*/
public static strictfp double evaluateprefix(String parmStrInput) {
Vector<String> vCompute = Calculator.getexpression(parmStrInput);
Vector<String> vTmpPrefix = Calculator.transformprefix(vCompute);
return Calculator.evaluateprefix(vTmpPrefix);
}
/**
* 括号匹配检测.
* @param str
* 表达式字符串
* @return boolean
* 如果表达式括号匹配,返回true,否则返回 false
*/
public static boolean checkbracket(String str) {
Stack<Character> stackCheck = new Stack<Character>();
boolean booFlag = true;
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
switch (ch) {
case '(':
stackCheck.push(ch);
break;
case ')':
if (!stackCheck.isEmpty()) {
char chx = stackCheck.pop();
if (ch == ')' && chx != '(') {
booFlag = false;
}
} else {
booFlag = false;
}
break;
default:
break;
}
}
if (!stackCheck.isEmpty()) {
booFlag = false;
}
return booFlag;
}
/**
* 表达式正确性规则处理与校验.
* @param str
* 表达式
* @return String
* 如果表达式非法,返回空串"",否则返回表达式
*/
public static String checkexpression(String str) {
if (str == null || "".equals(str.trim())) {
return "";
}
StringCharacterIterator sci = new StringCharacterIterator(str);
char lastChar = sci.last();
switch (lastChar) {
case '+':
return "";
case '*':
return "";
case '-':
return "";
case '/':
return "";
default:
break;
}
if (!Calculator.checkbracket(str)) {
return "";
}
Stack<Character> stackCheck = new Stack<Character>();
Stack<Character> stackTmp = new Stack<Character>();
String strResultOne = "";
// 匹配合法的运算字符"数字,.,+,-,*,/,(,),"
String strRegex = "^[\\.\\d\\+\\-\\*/\\(\\)]+$";
Pattern patternFiltrate = Pattern.compile(strRegex);
Matcher m = patternFiltrate.matcher(str);
boolean booFiltrate = m.matches();
if (!booFiltrate) {
strResultOne = "";
return strResultOne;
}
// 匹配非法的浮点数.
String strErrFloat = ".*(\\.\\d*){2,}.*";
Pattern patternErrFloat = Pattern.compile(strErrFloat);
Matcher matcherErrFloat = patternErrFloat.matcher(str);
boolean booErrFloat = matcherErrFloat.matches();
if (booErrFloat) {
strResultOne = "";
return strResultOne;
}
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
if (checkfig(ch)) {
if (!stackTmp.isEmpty() && stackTmp.peek() == ')') {
strResultOne = "";
return strResultOne;
}
stackTmp.push(ch);
strResultOne = strResultOne + ch;
}
switch (ch) {
case '(':
if (!stackTmp.isEmpty() && stackTmp.peek() == '.') {
strResultOne = "";
return strResultOne;
}
stackCheck.push(ch);
if (stackTmp.isEmpty() || (!checkfig(stackTmp.peek()) && stackTmp.peek() != ')')) {
strResultOne = strResultOne + ch;
} else {
strResultOne = strResultOne + "*" + ch;
}
stackTmp.push(ch);
break;
case ')':
if (!stackCheck.isEmpty()) {
char chx = stackCheck.pop();
if (ch == ')' && chx != '(') {
strResultOne = "";
return strResultOne;
}
} else {
strResultOne = "";
return strResultOne;
}
if (stackTmp.peek() == '.' || (!checkfig(stackTmp.peek()) && stackTmp.peek() != ')')) {
strResultOne = "";
return strResultOne;
}
stackTmp.push(ch);
strResultOne = strResultOne + ch;
break;
case '+':
case '-':
if (!stackTmp.isEmpty()
&& (stackTmp.peek() == '+' || stackTmp.peek() == '-' || stackTmp.peek() == '*' || stackTmp.peek() == '/' || stackTmp
.peek() == '.')) {
strResultOne = "";
return strResultOne;
}
if (stackTmp.isEmpty() || stackTmp.peek() == '(') {
strResultOne = strResultOne + "0" + ch;
} else {
strResultOne = strResultOne + ch;
}
stackTmp.push(ch);
break;
case '*':
case '/':
if (stackTmp.isEmpty() || stackTmp.peek() == '.' || (!checkfig(stackTmp.peek()) && stackTmp.peek() != ')')) {
strResultOne = "";
return strResultOne;
}
stackTmp.push(ch);
strResultOne = strResultOne + ch;
break;
case '.':
if (stackTmp.isEmpty() || !checkfig(stackTmp.peek())) {
strResultOne = strResultOne + "0" + ch;
} else {
strResultOne = strResultOne + ch;
}
stackTmp.push(ch);
break;
default:
break;
}
}
if (!stackCheck.isEmpty()) {
strResultOne = "";
return strResultOne;
}
return strResultOne;
}
/**
* 数字匹配检测
* @param ch
* 要检测的对象
* @return boolean
* 如果该对象仅有一个数字组成,返回 true,否则返回 false
*/
private static boolean checkfig(Object ch) {
String s = ch.toString();
// 匹配数字
String strRegexfig = "\\d";
Pattern patternFig = Pattern.compile(strRegexfig);
Matcher matcherFig = patternFig.matcher(s);
boolean booFig = matcherFig.matches();
return booFig;
}
};
| 11,555 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.