code
stringlengths
1
2.01M
repo_name
stringlengths
3
62
path
stringlengths
1
267
language
stringclasses
231 values
license
stringclasses
13 values
size
int64
1
2.01M
package com.jzzms.bsp.model.urss; import java.io.Serializable; import com.jzzms.framework.core.Model; public class Role extends Model { private static final long serialVersionUID = 1339081058890L; private Integer id; private Integer appId; private String code; private String name; private Integer comId; public Integer getId() { return id; } public void setId(Integer id) { entityMap.put("id", id); this.id = id; } public Integer getAppId() { return appId; } public void setAppId(Integer appId) { entityMap.put("appId", appId); this.appId = appId; } public String getCode() { return code; } public void setCode(String code) { entityMap.put("code", code); this.code = code; } public String getName() { return name; } public void setName(String name) { entityMap.put("name", name); this.name = name; } public Integer getComId() { return comId; } public void setComId(Integer comId) { entityMap.put("comId", comId); this.comId = comId; } @Override public Serializable getPK() { return id; } }
zz-ms
trunk/zz-ms-v1.0/sourcecode/bsp/src/com/jzzms/bsp/model/urss/Role.java
Java
asf20
1,130
package com.jzzms.bsp.model.urss; import java.io.Serializable; import com.jzzms.framework.core.Model; public class UserRole extends Model { private static final long serialVersionUID = 1339081058968L; private Integer id; private Integer userId; private Integer roleId; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public Integer getUserId() { return userId; } public void setUserId(Integer userId) { entityMap.put("userId", userId); this.userId = userId; } public Integer getRoleId() { return roleId; } public void setRoleId(Integer roleId) { entityMap.put("roleId", roleId); this.roleId = roleId; } @Override public Serializable getPK() { return id; } }
zz-ms
trunk/zz-ms-v1.0/sourcecode/bsp/src/com/jzzms/bsp/model/urss/UserRole.java
Java
asf20
786
package com.jzzms.bsp.model.urss; import java.io.Serializable; import com.jzzms.framework.core.Model; public class User extends Model { private static final long serialVersionUID = 1339081058921L; private Integer id; private String userName; private String password; private Integer comId; private Integer employeeId; public Integer getId() { return id; } public void setId(Integer id) { entityMap.put("id", id); this.id = id; } public String getUserName() { return userName; } public void setUserName(String userName) { entityMap.put("userName", userName); this.userName = userName; } public String getPassword() { return password; } public void setPassword(String password) { entityMap.put("password", password); this.password = password; } public Integer getComId() { return comId; } public void setComId(Integer comId) { entityMap.put("comId", comId); this.comId = comId; } public Integer getEmployeeId() { return employeeId; } public void setEmployeeId(Integer employeeId) { entityMap.put("employeeId", employeeId); this.employeeId = employeeId; } @Override public Serializable getPK() { return id; } }
zz-ms
trunk/zz-ms-v1.0/sourcecode/bsp/src/com/jzzms/bsp/model/urss/User.java
Java
asf20
1,247
package com.jzzms.bsp.model.urss; import java.io.Serializable; import com.jzzms.framework.core.Model; public class OrgType extends Model { private static final long serialVersionUID = 1339081058765L; private Integer id; private String code; private String name; public Integer getId() { return id; } public void setId(Integer id) { entityMap.put("id", id); this.id = id; } public String getCode() { return code; } public void setCode(String code) { entityMap.put("code", code); this.code = code; } public String getName() { return name; } public void setName(String name) { entityMap.put("name", name); this.name = name; } @Override public Serializable getPK() { return id; } }
zz-ms
trunk/zz-ms-v1.0/sourcecode/bsp/src/com/jzzms/bsp/model/urss/OrgType.java
Java
asf20
771
package com.jzzms.bsp.model.urss; import java.io.Serializable; import com.jzzms.framework.core.Model; public class Permission extends Model { private static final long serialVersionUID = 1339081058812L; private Integer id; private String resId; private String funId; private String appId; private Integer memberId; private String memberType; private String orgIds; private String orgType; public Integer getId() { return id; } public void setId(Integer id) { entityMap.put("id", id); this.id = id; } public String getResId() { return resId; } public void setResId(String resId) { entityMap.put("resId", resId); this.resId = resId; } public String getFunId() { return funId; } public void setFunId(String funId) { entityMap.put("funId", funId); this.funId = funId; } public String getAppId() { return appId; } public void setAppId(String appId) { entityMap.put("appId", appId); this.appId = appId; } public Integer getMemberId() { return memberId; } public void setMemberId(Integer memberId) { entityMap.put("memberId", memberId); this.memberId = memberId; } public String getMemberType() { return memberType; } public void setMemberType(String memberType) { entityMap.put("memberType", memberType); this.memberType = memberType; } public String getOrgIds() { return orgIds; } public void setOrgIds(String orgIds) { entityMap.put("orgIds", orgIds); this.orgIds = orgIds; } public String getOrgType() { return orgType; } public void setOrgType(String orgType) { entityMap.put("orgType", orgType); this.orgType = orgType; } @Override public Serializable getPK() { return id; } }
zz-ms
trunk/zz-ms-v1.0/sourcecode/bsp/src/com/jzzms/bsp/model/urss/Permission.java
Java
asf20
1,784
package com.jzzms.bsp.model.urss; import java.io.Serializable; import com.jzzms.framework.core.Model; public class Function extends Model { private static final long serialVersionUID = 1339081058656L; private Integer id; private String name; private String url; private String smallImg; private String bigImg; private String funCode; private Integer orderIndex; private Integer appId; private Integer parentId; public Integer getId() { return id; } public void setId(Integer id) { entityMap.put("id", id); this.id = id; } public String getName() { return name; } public void setName(String name) { entityMap.put("name", name); this.name = name; } public String getUrl() { return url; } public void setUrl(String url) { entityMap.put("url", url); this.url = url; } public String getSmallImg() { return smallImg; } public void setSmallImg(String smallImg) { entityMap.put("smallImg", smallImg); this.smallImg = smallImg; } public String getBigImg() { return bigImg; } public void setBigImg(String bigImg) { entityMap.put("bigImg", bigImg); this.bigImg = bigImg; } public String getFunCode() { return funCode; } public void setFunCode(String funCode) { entityMap.put("funCode", funCode); this.funCode = funCode; } public Integer getOrderIndex() { return orderIndex; } public void setOrderIndex(Integer orderIndex) { entityMap.put("orderIndex", orderIndex); this.orderIndex = orderIndex; } public Integer getAppId() { return appId; } public void setAppId(Integer appId) { entityMap.put("appId", appId); this.appId = appId; } public Integer getParentId() { return parentId; } public void setParentId(Integer parentId) { entityMap.put("parentId", parentId); this.parentId = parentId; } @Override public Serializable getPK() { return id; } }
zz-ms
trunk/zz-ms-v1.0/sourcecode/bsp/src/com/jzzms/bsp/model/urss/Function.java
Java
asf20
1,966
package com.jzzms.bsp.model.urss; import java.io.Serializable; import com.jzzms.framework.core.Model; public class EmployeeOrg extends Model { private static final long serialVersionUID = 1339081058625L; private Integer id; private Integer orgId; private Integer employeeId; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public Integer getOrgId() { return orgId; } public void setOrgId(Integer orgId) { entityMap.put("orgId", orgId); this.orgId = orgId; } public Integer getEmployeeId() { return employeeId; } public void setEmployeeId(Integer employeeId) { entityMap.put("employeeId", employeeId); this.employeeId = employeeId; } @Override public Serializable getPK() { return id; } }
zz-ms
trunk/zz-ms-v1.0/sourcecode/bsp/src/com/jzzms/bsp/model/urss/EmployeeOrg.java
Java
asf20
814
package com.jzzms.bsp.model.urss; import java.io.Serializable; import com.jzzms.framework.core.Model; public class Employee extends Model { private static final long serialVersionUID = 1339081058578L; private Integer id; private String name; private String code; private String email; private String mobile; private String telephone; public Integer getId() { return id; } public void setId(Integer id) { entityMap.put("id", id); this.id = id; } public String getName() { return name; } public void setName(String name) { entityMap.put("name", name); this.name = name; } public String getCode() { return code; } public void setCode(String code) { entityMap.put("code", code); this.code = code; } public String getEmail() { return email; } public void setEmail(String email) { entityMap.put("email", email); this.email = email; } public String getMobile() { return mobile; } public void setMobile(String mobile) { entityMap.put("mobile", mobile); this.mobile = mobile; } public String getTelephone() { return telephone; } public void setTelephone(String telephone) { entityMap.put("telephone", telephone); this.telephone = telephone; } @Override public Serializable getPK() { return id; } }
zz-ms
trunk/zz-ms-v1.0/sourcecode/bsp/src/com/jzzms/bsp/model/urss/Employee.java
Java
asf20
1,351
package com.jzzms.bsp.model.urss; import java.io.Serializable; import java.util.Date; import com.jzzms.framework.core.Model; public class Company extends Model { private static final long serialVersionUID = 1339081058468L; private Integer id; private String comName; private String address; private String contactName; private String fax; private String zip; private String allowUser; private Date startTime; private Date endTime; private Date regTime; public Integer getId() { return id; } public void setId(Integer id) { entityMap.put("id", id); this.id = id; } public String getComName() { return comName; } public void setComName(String comName) { entityMap.put("comName", comName); this.comName = comName; } public String getAddress() { return address; } public void setAddress(String address) { entityMap.put("address", address); this.address = address; } public String getContactName() { return contactName; } public void setContactName(String contactName) { entityMap.put("contactName", contactName); this.contactName = contactName; } public String getFax() { return fax; } public void setFax(String fax) { entityMap.put("fax", fax); this.fax = fax; } public String getZip() { return zip; } public void setZip(String zip) { entityMap.put("zip", zip); this.zip = zip; } public String getAllowUser() { return allowUser; } public void setAllowUser(String allowUser) { entityMap.put("allowUser", allowUser); this.allowUser = allowUser; } public Date getStartTime() { return startTime; } public void setStartTime(Date startTime) { entityMap.put("startTime", startTime); this.startTime = startTime; } public Date getEndTime() { return endTime; } public void setEndTime(Date endTime) { entityMap.put("endTime", endTime); this.endTime = endTime; } public Date getRegTime() { return regTime; } public void setRegTime(Date regTime) { entityMap.put("regTime", regTime); this.regTime = regTime; } @Override public Serializable getPK() { return id; } }
zz-ms
trunk/zz-ms-v1.0/sourcecode/bsp/src/com/jzzms/bsp/model/urss/Company.java
Java
asf20
2,203
package com.jzzms.bsp.model.urss; import java.io.Serializable; import com.jzzms.framework.core.Model; public class OrgDetail extends Model { private static final long serialVersionUID = 1339081058703L; private Integer id; private Integer orgId; private String path; private String value; public Integer getId() { return id; } public void setId(Integer id) { entityMap.put("id", id); this.id = id; } public Integer getOrgId() { return orgId; } public void setOrgId(Integer orgId) { entityMap.put("orgId", orgId); this.orgId = orgId; } public String getPath() { return path; } public void setPath(String path) { entityMap.put("path", path); this.path = path; } public String getValue() { return value; } public void setValue(String value) { entityMap.put("value", value); this.value = value; } @Override public Serializable getPK() { return id; } }
zz-ms
trunk/zz-ms-v1.0/sourcecode/bsp/src/com/jzzms/bsp/model/urss/OrgDetail.java
Java
asf20
963
package com.jzzms.bsp.model.urss; import java.io.Serializable; import com.jzzms.framework.core.Model; public class App extends Model { private static final long serialVersionUID = 1339081058015L; private Integer id; private String name; private String code; public Integer getId() { return id; } public void setId(Integer id) { entityMap.put("id", id); this.id = id; } public String getName() { return name; } public void setName(String name) { entityMap.put("name", name); this.name = name; } public String getCode() { return code; } public void setCode(String code) { entityMap.put("code", code); this.code = code; } @Override public Serializable getPK() { return id; } }
zz-ms
trunk/zz-ms-v1.0/sourcecode/bsp/src/com/jzzms/bsp/model/urss/App.java
Java
asf20
767
/** * Copyright : http://www.orientpay.com , 2007-2012 * Project : oecs-g2-common-framework-trunk * $Id$ * $Revision$ * Last Changed by ZhouXushun at 2011-8-4 下午02:05:36 * $URL$ * * Change Log * Author Change Date Comments *------------------------------------------------------------- * ZhouXushun 2011-8-4 Initailized */ package com.jzzms.framework.exception; import com.jzzms.framework.core.Constants; /** * 系统异常基类 * */ public class BaseAppException extends Exception { private static final long serialVersionUID = 2465305628320590970L; private String errMsg; private String errCode; public BaseAppException() { super(); this.errMsg = Constants.DEFAULT_ERR_MSG; this.errCode = Constants.DEFAULT_ERR_CODE; } public BaseAppException(String errMsg, String errCode, Throwable cause) { super(errMsg + errCode, cause); this.errMsg = errMsg; this.errCode = errCode; } public BaseAppException(String errCode, Throwable cause) { super(errCode, cause); this.errMsg = cause.getMessage(); this.errCode = errCode; } public BaseAppException(String errMsg, String errCode) { super(errMsg + errCode); this.errMsg = errMsg; this.errCode = errCode; } public BaseAppException(String errMsg) { super(errMsg); this.errMsg = errMsg; this.errCode = Constants.DEFAULT_ERR_CODE; } public BaseAppException(Throwable cause) { super(cause); if(cause instanceof BaseAppException){ BaseRuntimeException e = (BaseRuntimeException)cause; this.errCode = e.getErrCode(); this.errMsg = e.getErrMsg(); } else if(cause instanceof BaseRuntimeException){ BaseAppException e = (BaseAppException)cause; this.errCode = e.getErrCode(); this.errMsg = e.getErrMsg(); } else{ this.errMsg = cause.getMessage(); this.errCode = Constants.DEFAULT_ERR_CODE; } } /** * Property accessor of errCode * @return the errCode */ public String getErrCode() { return errCode; } public String getErrMsg(){ return errMsg; } }
zz-ms
trunk/zz-ms-v1.0/sourcecode/framework/src/com/jzzms/framework/exception/BaseAppException.java
Java
asf20
2,483
/** * Copyright : http://www.orientpay.com , 2007-2012 * Project : oecs-g2-common-framework-trunk * $Id$ * $Revision$ * Last Changed by ZhouXushun at 2011-8-4 下午02:05:36 * $URL$ * * Change Log * Author Change Date Comments *------------------------------------------------------------- * ZhouXushun 2011-8-4 Initailized */ package com.jzzms.framework.exception; import com.jzzms.framework.core.Constants; /** * 系统异常基类 * */ public class BaseRuntimeException extends RuntimeException { private static final long serialVersionUID = 2465305628320590970L; private String errMsg; private String errCode; public BaseRuntimeException() { super(); this.errMsg = Constants.DEFAULT_ERR_MSG; this.errCode = Constants.DEFAULT_ERR_CODE; } public BaseRuntimeException(String errMsg, String errCode, Throwable cause) { super(errMsg + errCode, cause); this.errMsg = errMsg; this.errCode = errCode; } public BaseRuntimeException(String errCode, Throwable cause) { super(errCode, cause); this.errMsg = cause.getMessage(); this.errCode = errCode; } public BaseRuntimeException(String errMsg, String errCode) { super(errMsg + errCode); this.errMsg = errMsg; this.errCode = errCode; } public BaseRuntimeException(String errMsg) { super(errMsg); this.errMsg = errMsg; this.errCode = Constants.DEFAULT_ERR_CODE; } public BaseRuntimeException(Throwable cause) { super(cause); if(cause instanceof BaseRuntimeException){ BaseRuntimeException e = (BaseRuntimeException)cause; this.errCode = e.getErrCode(); this.errMsg = e.getErrMsg(); } else if(cause instanceof BaseAppException){ BaseAppException e = (BaseAppException)cause; this.errCode = e.getErrCode(); this.errMsg = e.getErrMsg(); } else{ this.errMsg = cause.getMessage(); this.errCode = Constants.DEFAULT_ERR_CODE; } } /** * Property accessor of errCode * @return the errCode */ public String getErrCode() { return errCode; } public String getErrMsg(){ return errMsg; } }
zz-ms
trunk/zz-ms-v1.0/sourcecode/framework/src/com/jzzms/framework/exception/BaseRuntimeException.java
Java
asf20
2,519
/** * Copyright : http://www.orientpay.com , 2007-2012 * Project : oecs-g2-framework-trunk * $Id$ * $Revision$ * Last Changed by jason at 2011-9-17 下午4:03:53 * $URL$ * * Change Log * Author Change Date Comments *------------------------------------------------------------- * jason 2011-9-17 Initailized */ package com.jzzms.framework.service; import java.io.Serializable; import java.util.Date; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.ibatis.session.RowBounds; import org.springframework.transaction.annotation.Transactional; import com.jzzms.framework.core.Constants; import com.jzzms.framework.core.Model; import com.jzzms.framework.dao.Dao; import com.jzzms.framework.orm.query.ZzMsCriterion; import com.jzzms.framework.orm.query.Order; import com.jzzms.framework.orm.query.Page; import com.jzzms.framework.orm.query.PropertyFilter; import com.jzzms.framework.util.common.ModelUpdateInfoUtils; import com.jzzms.framework.util.common.ZzMsCriterionUtils; import com.jzzms.framework.util.lang.DateTimeUtils; /** * 领域对象的业务管理类基类. * * 提供了领域对象的简单CRUD方法. * * @param <T> 领域对象类型 * @param <PK> 领域对象的主键类型 * */ @Transactional public abstract class DefaultEntityService <T extends Model, PK extends Serializable>{ protected Log log = LogFactory.getLog(getClass()); /** * 在子类实现的回调函数,为EntityManager提供默认CRUD操作所需的DAO. */ protected abstract Dao<T, PK> getDao(); // CRUD函数 // @Transactional(readOnly = true) public T get(PK id) { return getDao().get(id); } @Transactional public void save(T entity) { getDao().save(entity); } @Transactional public void update(T entity) { update(entity, false); } @Transactional @SuppressWarnings("unchecked") //是否以秒为精度,否则以毫秒为精度,默认以毫秒为精度 public void update(T entity, boolean secondPrecision) { Serializable pks = entity.getPK(); if(pks != null){ try{ T dbEntity = getDao().get((PK)pks); if(dbEntity != null){ Date dbDate = ModelUpdateInfoUtils.getModelUpdateTime(dbEntity); log.debug("dbDate :" + dbDate.getTime()); Date date = ModelUpdateInfoUtils.getModelUpdateTime(entity); log.debug("modelDate :" + date.getTime()); if(dbDate != null){ //如果不相符,则为脏数据 if(!dbDate.equals(date)){ if(!secondPrecision){ log.warn("the date (not secondPrecision) is dirty :" + entity); throw new IllegalStateException("the date is dirty"); } else{ //以秒为精度 long diff = DateTimeUtils.diffTwoDateWithTime(date, dbDate); if(diff/1000 != 0){ log.warn("the date (secondPrecision) is dirty :" + entity); throw new IllegalStateException("the date is dirty"); } } } } } } catch(Exception e){ log.info(e.getMessage(), e); if(e instanceof IllegalStateException){ throw ((IllegalStateException)e); } } } //设置更新时间 ModelUpdateInfoUtils.updateModelUpdateTime(entity); getDao().update(entity); } @Transactional public void delete(PK id) { getDao().delete(id); } /** * 按id逻辑删除对象. */ @Transactional public void logicDel(final PK id){ T t =get(id); ModelUpdateInfoUtils.setModelInvalidStatus(t); getDao().update(t); } @Transactional public void delete(List<PK> ids) { if(ids != null && ids.size() > 0){ Dao<T, PK> dao = getDao(); for(PK id : ids){ dao.delete(id); } } } @Transactional(readOnly = true) public List<T> getAll() { ZzMsCriterion criterion = new ZzMsCriterion(); return getDao().find(criterion, null); } @Transactional(readOnly = true) public Page<T> getAll(Page<T> page) { return search(page, null); } @Transactional(readOnly = true) public Page<T> search(Page<T> page, List<PropertyFilter> filters) { ZzMsCriterion criterion = ZzMsCriterionUtils.createOecsCriterion(page, filters); RowBounds rowBounds = ZzMsCriterionUtils.createRowBounds(page); //开始查询 List<T> result = getDao().find(criterion, rowBounds); page.setResult(result); //处理是否需要统计记录数 if(page.isAutoCount()){ page.setTotalCount(getDao().count(criterion)); } return page; } @Transactional(readOnly = true) public List<T> search(List<PropertyFilter> filters) { return search(filters, null); } @Transactional(readOnly = true) public List<T> search(List<PropertyFilter> filters ,List<Order> orders) { ZzMsCriterion criterion = new ZzMsCriterion(filters); if(orders != null){ StringBuilder orderBySb = new StringBuilder(); StringBuilder orderSb = new StringBuilder(); int i = 0; for(Order order : orders){ if(i != 0){ orderBySb.append(Constants.COMMA_SIGN_SPLIT_NAME); orderSb.append(Constants.COMMA_SIGN_SPLIT_NAME); } i++; orderBySb.append(order.getOrderBy()); orderSb.append(order.getOrder()); } criterion.setOrderBy(orderBySb.toString()); criterion.setOrder(orderSb.toString()); } return getDao().find(criterion, null); } }
zz-ms
trunk/zz-ms-v1.0/sourcecode/framework/src/com/jzzms/framework/service/DefaultEntityService.java
Java
asf20
6,639
package com.jzzms.framework.service.security; /** * 这个接口是以前spring版本中的,现在的spring版本中不存在,由于项目需要且使用方便,故加入到项目当中 * @author jason * */ public abstract interface UrlMatcher { public abstract Object compile(String paramString); public abstract boolean pathMatchesUrl(Object paramObject, String paramString); public abstract String getUniversalMatchPattern(); public abstract boolean requiresLowerCaseUrl(); }
zz-ms
trunk/zz-ms-v1.0/sourcecode/framework/src/com/jzzms/framework/service/security/UrlMatcher.java
Java
asf20
512
/** * Copyright : http://www.orientpay.com , 2007-2012 * Project : oecs-g2-common-framework-trunk * $Id$ * $Revision$ * Last Changed by ZhouXushun at 2011-8-15 下午01:59:33 * $URL$ * * Change Log * Author Change Date Comments *------------------------------------------------------------- * ZhouXushun 2011-8-15 Initailized */ package com.jzzms.framework.service.security; import org.springframework.security.core.GrantedAuthority; /** * 用户用于权限访问的资源 * */ public class GrantedAuthorityImpl implements GrantedAuthority { private static final long serialVersionUID = 2778921792207272406L; private String resource; private String resourceType; public GrantedAuthorityImpl(String resource) { this.resource = resource; } public GrantedAuthorityImpl(String resourceType, String resource) { this.resourceType = resourceType; this.resource = resource; } /** * Property accessor of resource * * @return the resource */ public String getResource() { return resource; } /** * @param resource * the resource to set */ public void setResource(String resource) { this.resource = resource; } /** * Property accessor of resourceType * * @return the resourceType */ public String getResourceType() { return resourceType; } /** * @param resourceType * the resourceType to set */ public void setResourceType(String resourceType) { this.resourceType = resourceType; } public String getAuthority() { return null; } }
zz-ms
trunk/zz-ms-v1.0/sourcecode/framework/src/com/jzzms/framework/service/security/GrantedAuthorityImpl.java
Java
asf20
1,805
/** * Copyright : http://www.orientpay.com , 2007-2012 * Project : oecs-g2-common-framework-trunk * $Id$ * $Revision$ * Last Changed by ZhouXushun at 2011-8-12 下午05:25:48 * $URL$ * * Change Log * Author Change Date Comments *------------------------------------------------------------- * ZhouXushun 2011-8-12 Initailized */ package com.jzzms.framework.service.security; import org.springframework.security.authentication.dao.SaltSource; import org.springframework.security.authentication.encoding.PasswordEncoder; import org.springframework.security.authentication.encoding.ShaPasswordEncoder; import org.springframework.security.core.userdetails.UserDetails; /** * 用户口令加密 * */ public class UserPasswordSaltSource implements SaltSource { public static final String USER_PASSWORD_SALT_PREFIX = "jzzms:"; private static PasswordEncoder passwordEncoder = new ShaPasswordEncoder(); public Object getSalt(UserDetails user) { return USER_PASSWORD_SALT_PREFIX + user.getUsername(); } public Object getSalt(String userName) { return USER_PASSWORD_SALT_PREFIX + userName; } public static String encodePassword(String password, String salt) { return passwordEncoder.encodePassword(password, USER_PASSWORD_SALT_PREFIX + salt); } }
zz-ms
trunk/zz-ms-v1.0/sourcecode/framework/src/com/jzzms/framework/service/security/UserPasswordSaltSource.java
Java
asf20
1,397
package com.jzzms.framework.service.security; import org.springframework.util.AntPathMatcher; import org.springframework.util.PathMatcher; public class AntUrlPathMatcher implements UrlMatcher { private boolean requiresLowerCaseUrl; private PathMatcher pathMatcher; public AntUrlPathMatcher() { this(true); } public AntUrlPathMatcher(boolean requiresLowerCaseUrl) { this.requiresLowerCaseUrl = true; this.pathMatcher = new AntPathMatcher(); this.requiresLowerCaseUrl = requiresLowerCaseUrl; } public Object compile(String path) { if (this.requiresLowerCaseUrl) { return path.toLowerCase(); } return path; } public void setRequiresLowerCaseUrl(boolean requiresLowerCaseUrl) { this.requiresLowerCaseUrl = requiresLowerCaseUrl; } public boolean pathMatchesUrl(Object path, String url) { if (("/**".equals(path)) || ("**".equals(path))) { return true; } return this.pathMatcher.match((String) path, url); } public String getUniversalMatchPattern() { return "/**"; } public boolean requiresLowerCaseUrl() { return this.requiresLowerCaseUrl; } public String toString() { return super.getClass().getName() + "[requiresLowerCase='" + this.requiresLowerCaseUrl + "']"; } }
zz-ms
trunk/zz-ms-v1.0/sourcecode/framework/src/com/jzzms/framework/service/security/AntUrlPathMatcher.java
Java
asf20
1,283
/** * Copyright : http://www.orientpay.com , 2007-2012 * Project : oecs-g2-merchant-trunk * $Id$ * $Revision$ * Last Changed by yujs at 2011-11-2 上午11:20:47 * $URL$ * * Change Log * Author Change Date Comments *------------------------------------------------------------- * yujs 2011-11-2 Initailized */ package com.jzzms.framework.service.security; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.security.core.Authentication; import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler; public class LoginSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler { protected final Log log = LogFactory.getLog(getClass()); public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException,ServletException { log.info("用户登录成功,开始跳转..."); log.info("用户登录成功,跳转完成:" + getRealIp(request)); super.onAuthenticationSuccess(request, response, authentication); } /** * 获取访问者真实ip地址 * @param request * @return */ private String getRealIp(HttpServletRequest request) { String ip = request.getHeader("x-forwarded-for"); if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("Proxy-Client-IP"); } if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("WL-Proxy-Client-IP"); } if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getRemoteAddr(); } return ip; } }
zz-ms
trunk/zz-ms-v1.0/sourcecode/framework/src/com/jzzms/framework/service/security/LoginSuccessHandler.java
Java
asf20
2,063
/** * Copyright : http://www.orientpay.com , 2007-2012 * Project : oecs-g2-merchant-trunk * $Id$ * $Revision$ * Last Changed by yujs at 2011-11-2 上午11:20:47 * $URL$ * * Change Log * Author Change Date Comments *------------------------------------------------------------- * yujs 2011-11-2 Initailized */ package com.jzzms.framework.service.security; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.security.core.AuthenticationException; import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler; public class LoginFailureHandler extends SimpleUrlAuthenticationFailureHandler { protected final Log log = LogFactory.getLog(getClass()); public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws ServletException,IOException { log.info("用户登录失败,记录信息..."); log.debug("记录信息完毕 :" + getRealIp(request)); request.getSession().setAttribute("errorMessage", "密码错误,请重新输入!"); super.onAuthenticationFailure(request, response, exception); } /** * 获取访问者真实ip地址 * @param request * @return */ private String getRealIp(HttpServletRequest request) { String ip = request.getHeader("x-forwarded-for"); if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("Proxy-Client-IP"); } if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("WL-Proxy-Client-IP"); } if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getRemoteAddr(); } return ip; } }
zz-ms
trunk/zz-ms-v1.0/sourcecode/framework/src/com/jzzms/framework/service/security/LoginFailureHandler.java
Java
asf20
2,173
package com.jzzms.framework.service.security; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.security.access.ConfigAttribute; import org.springframework.security.access.SecurityConfig; import org.springframework.security.web.FilterInvocation; import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource; /** * * 此类在初始化时,应该取到所有资源及其对应角色的定义 * */ public class InvocationSecurityMetadataSource implements FilterInvocationSecurityMetadataSource { protected Log log = LogFactory.getLog(getClass()); private UrlMatcher urlMatcher = new AntUrlPathMatcher(); private static Map<String, Collection<ConfigAttribute>> resourceMap = null; public InvocationSecurityMetadataSource() { loadResourceDefine(); } private void loadResourceDefine() { log.debug("loadResourceDefine ..."); resourceMap = new HashMap<String, Collection<ConfigAttribute>>(); Collection<ConfigAttribute> atts = new ArrayList<ConfigAttribute>(); ConfigAttribute ca = new SecurityConfig("ROLE_USER"); atts.add(ca); resourceMap.put("/bsp/index.action", atts); Collection<ConfigAttribute> attsno = new ArrayList<ConfigAttribute>(); ConfigAttribute cano = new SecurityConfig("ROLE_NO"); attsno.add(cano); resourceMap.put("/index.jsp", attsno); } // According to a URL, Find out permission configuration of this URL. public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException { log.debug("getAttr, object ->" + object); // guess object is a URL. String url = ((FilterInvocation)object).getRequestUrl(); Iterator<String> ite = resourceMap.keySet().iterator(); while (ite.hasNext()) { String resURL = ite.next(); if (urlMatcher.pathMatchesUrl(resURL, url)) { return resourceMap.get(resURL); } } return null; } public boolean supports(Class<?> clazz) { return true; } public Collection<ConfigAttribute> getAllConfigAttributes() { return null; } }
zz-ms
trunk/zz-ms-v1.0/sourcecode/framework/src/com/jzzms/framework/service/security/InvocationSecurityMetadataSource.java
Java
asf20
2,497
/** * Copyright : http://www.orientpay.com , 2007-2012 * Project : oecs-g2-common-framework-trunk * $Id$ * $Revision$ * Last Changed by ZhouXushun at 2011-8-15 上午11:45:50 * $URL$ * * Change Log * Author Change Date Comments *------------------------------------------------------------- * ZhouXushun 2011-8-15 Initailized * ZhouXushun 2011-9-26 处理resource和url为空时的空指针异常 * */ package com.jzzms.framework.service.security; import java.util.Collection; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.factory.InitializingBean; import org.springframework.context.ApplicationContext; import org.springframework.security.access.AccessDecisionManager; import org.springframework.security.access.AccessDeniedException; import org.springframework.security.access.ConfigAttribute; import org.springframework.security.authentication.InsufficientAuthenticationException; import org.springframework.security.core.Authentication; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.web.FilterInvocation; import com.jzzms.framework.core.Constants; import com.jzzms.framework.service.cache.Cacheable; import com.jzzms.framework.util.common.SystemPropertyUtils; import com.jzzms.framework.util.lang.AssertUtils; /** * 权限判断 * * 系统目前的权限相关的都移到此类上来了 * 只处理url和button类型的资源,其他的资源无须判断,都由页面在生成的时候判断好了再显示的 */ public class AccessDecisionService implements AccessDecisionManager, InitializingBean, Cacheable { protected Log log = LogFactory.getLog(getClass()); //匹配方式 //private UrlMatcher urlMatcher; //是否转成小写比较 private boolean lowercaseComparisons = true; //是否匹配ANT PATH private boolean useAntPath = true; // 是否保护所有的没有记录的 private boolean protectAllResource = false; //应用系统代码 private String appCode; //appCode所有需要受保护的资源 //List<ResourceDTO> protectedResourceList; //资源加载管理器 //private UserLoginedLoadService sysInitLoadService; public AccessDecisionService(){ //protectedResourceList = new ArrayList<ResourceDTO>(10); } //此类初始化后的操作 public void afterPropertiesSet() throws Exception { log.debug("afterPropertiesSet ..."); appCode = SystemPropertyUtils.getString(Constants.SYSTEM_PROPERTY_APPCODE_KEY, ""); log.debug("appCode : " + appCode); AssertUtils.notNull(appCode); } public void decide(Authentication authentication, Object securityObject, Collection<ConfigAttribute> configAttributes) throws AccessDeniedException, InsufficientAuthenticationException { log.debug("decide ..."); if (authentication == null || !authentication.isAuthenticated() || authentication.getPrincipal() == null) { log.debug("Not Authenticated"); throw new InsufficientAuthenticationException("Not Authenticated"); } Object principal = authentication.getPrincipal(); if (!(principal instanceof UserDetails)) { log.debug("Not support for [" + principal + "]"); throw new InsufficientAuthenticationException("Not support for [" + principal + "]"); } //UserDetailsImpl userDetails = (UserDetailsImpl) authentication.getPrincipal(); //String url = null; if (securityObject instanceof FilterInvocation) { //FilterInvocation filter = (FilterInvocation) securityObject; //url = filter.getRequestUrl(); } } public boolean supports(ConfigAttribute attribute) { return true; } public boolean supports(Class<?> clazz) { return true; } public synchronized void init(ApplicationContext ctx){ log.debug("init..."); reInit(); } public synchronized void reInit(){ log.debug("reInit..."); } //得到用户的权限 protected Collection<GrantedAuthority> getUserGrantedAuthrities(String appCode, String operatorId) { return null; } public boolean isLowercaseComparisons() { return lowercaseComparisons; } public void setLowercaseComparisons(boolean lowercaseComparisons) { this.lowercaseComparisons = lowercaseComparisons; } public boolean isUseAntPath() { return useAntPath; } public void setUseAntPath(boolean useAntPath) { this.useAntPath = useAntPath; } public boolean isProtectAllResource() { return protectAllResource; } public void setProtectAllResource(boolean protectAllResource) { this.protectAllResource = protectAllResource; } }
zz-ms
trunk/zz-ms-v1.0/sourcecode/framework/src/com/jzzms/framework/service/security/AccessDecisionService.java
Java
asf20
5,237
package com.jzzms.framework.service.security; import java.util.Collection; import java.util.Iterator; import org.springframework.security.access.AccessDecisionManager; import org.springframework.security.access.AccessDeniedException; import org.springframework.security.access.ConfigAttribute; import org.springframework.security.access.SecurityConfig; import org.springframework.security.authentication.InsufficientAuthenticationException; import org.springframework.security.core.Authentication; import org.springframework.security.core.GrantedAuthority; public class AccessDecisionMngImpl implements AccessDecisionManager { // In this method, need to compare authentication with configAttributes. // 1, A object is a URL, a filter was find permission configuration by this // URL, and pass to here. // 2, Check authentication has attribute in permission configuration // (configAttributes) // 3, If not match corresponding authentication, throw a // AccessDeniedException. public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes) throws AccessDeniedException, InsufficientAuthenticationException { if (configAttributes == null) { return; } System.out.println("-------" + object.toString()); // object is a URL. Iterator<ConfigAttribute> ite = configAttributes.iterator(); while (ite.hasNext()) { ConfigAttribute ca = ite.next(); String needRole = ((SecurityConfig) ca).getAttribute(); for (GrantedAuthority ga : authentication.getAuthorities()) { if (needRole.equals(ga.getAuthority())) { // ga is user's role. return; } } } System.out.println("throw new AccessDeniedException('no right')------" + object.toString()); //throw new AccessDeniedException("no right"); } public boolean supports(ConfigAttribute attribute) { // TODO Auto-generated method stub return true; } public boolean supports(Class<?> clazz) { return true; } }
zz-ms
trunk/zz-ms-v1.0/sourcecode/framework/src/com/jzzms/framework/service/security/AccessDecisionMngImpl.java
Java
asf20
2,013
/** * Copyright : http://www.orientpay.com , 2007-2012 * Project : oecs-g2-framework-trunk * $Id$ * $Revision$ * Last Changed by jason at 2011-10-19 下午4:49:33 * $URL$ * * Change Log * Author Change Date Comments *------------------------------------------------------------- * jason 2011-10-19 Initailized */ package com.jzzms.framework.validate.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * 邮件 * */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface ZzMsEmail { public String message() default "value should be email."; }
zz-ms
trunk/zz-ms-v1.0/sourcecode/framework/src/com/jzzms/framework/validate/annotation/ZzMsEmail.java
Java
asf20
768
/** * Copyright : http://www.orientpay.com , 2007-2012 * Project : oecs-g2-framework-trunk * $Id$ * $Revision$ * Last Changed by jason at 2011-10-17 下午12:38:09 * $URL$ * * Change Log * Author Change Date Comments *------------------------------------------------------------- * jason 2011-10-17 Initailized */ package com.jzzms.framework.validate.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * 字母 * */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface ZzMsAlphanumeric { public String message() default "The value should be alphanumeric only."; }
zz-ms
trunk/zz-ms-v1.0/sourcecode/framework/src/com/jzzms/framework/validate/annotation/ZzMsAlphanumeric.java
Java
asf20
792
/** * Copyright : http://www.orientpay.com , 2007-2012 * Project : oecs-g2-framework-trunk * $Id$ * $Revision$ * Last Changed by jason at 2011-10-19 下午4:51:17 * $URL$ * * Change Log * Author Change Date Comments *------------------------------------------------------------- * jason 2011-10-19 Initailized */ package com.jzzms.framework.validate.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * 最大长度 * */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface ZzMsMaxLength { public int max() default Integer.MIN_VALUE; public String message() default "Value of the length is not in expected scope."; }
zz-ms
trunk/zz-ms-v1.0/sourcecode/framework/src/com/jzzms/framework/validate/annotation/ZzMsMaxLength.java
Java
asf20
854
/** * Copyright : http://www.orientpay.com , 2007-2012 * Project : oecs-g2-framework-trunk * $Id$ * $Revision$ * Last Changed by jason at 2011-10-19 下午4:55:54 * $URL$ * * Change Log * Author Change Date Comments *------------------------------------------------------------- * jason 2011-10-19 Initailized */ package com.jzzms.framework.validate.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * 最小值 * */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface ZzMsMin { public double min() default Integer.MIN_VALUE; public String message() default "Start time should not later than min value"; }
zz-ms
trunk/zz-ms-v1.0/sourcecode/framework/src/com/jzzms/framework/validate/annotation/ZzMsMin.java
Java
asf20
843
/** * Copyright : http://www.orientpay.com , 2007-2012 * Project : oecs-g2-framework-trunk * $Id$ * $Revision$ * Last Changed by jason at 2011-10-17 上午9:53:56 * $URL$ * * Change Log * Author Change Date Comments *------------------------------------------------------------- * jason 2011-10-17 Initailized */ package com.jzzms.framework.validate.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * 日期 * */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface ZzMsDate { public String message() default "Value is not a date."; }
zz-ms
trunk/zz-ms-v1.0/sourcecode/framework/src/com/jzzms/framework/validate/annotation/ZzMsDate.java
Java
asf20
766
/** * Copyright : http://www.orientpay.com , 2007-2012 * Project : oecs-g2-framework-trunk * $Id$ * $Revision$ * Last Changed by jason at 2011-10-19 下午4:54:58 * $URL$ * * Change Log * Author Change Date Comments *------------------------------------------------------------- * jason 2011-10-19 Initailized */ package com.jzzms.framework.validate.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * 长度范围 * */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface ZzMsRangeLength { public int min() default 0; public int max() default Integer.MAX_VALUE; public String message() default "Value of the length is not in expected scope."; }
zz-ms
trunk/zz-ms-v1.0/sourcecode/framework/src/com/jzzms/framework/validate/annotation/ZzMsRangeLength.java
Java
asf20
889
/** * Copyright : http://www.orientpay.com , 2007-2012 * Project : oecs-g2-framework-trunk * $Id$ * $Revision$ * Last Changed by jason at 2011-10-19 下午4:55:39 * $URL$ * * Change Log * Author Change Date Comments *------------------------------------------------------------- * jason 2011-10-19 Initailized */ package com.jzzms.framework.validate.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * 最大值 * */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface ZzMsMax { public double max() default Integer.MAX_VALUE; public String message() default "Start time should not later than min value"; }
zz-ms
trunk/zz-ms-v1.0/sourcecode/framework/src/com/jzzms/framework/validate/annotation/ZzMsMax.java
Java
asf20
843
/** * Copyright : http://www.orientpay.com , 2007-2012 * Project : oecs-g2-framework-trunk * $Id$ * $Revision$ * Last Changed by jason at 2011-10-19 下午4:53:47 * $URL$ * * Change Log * Author Change Date Comments *------------------------------------------------------------- * jason 2011-10-19 Initailized */ package com.jzzms.framework.validate.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * 最小长度 * */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface ZzMsMinLength { public int min() default 0; public String message() default "Value of the length is not in expected scope."; }
zz-ms
trunk/zz-ms-v1.0/sourcecode/framework/src/com/jzzms/framework/validate/annotation/ZzMsMinLength.java
Java
asf20
836
/** * Copyright : http://www.orientpay.com , 2007-2012 * Project : oecs-g2-framework-trunk * $Id$ * $Revision$ * Last Changed by jason at 2011-10-19 下午4:42:49 * $URL$ * * Change Log * Author Change Date Comments *------------------------------------------------------------- * jason 2011-10-19 Initailized */ package com.jzzms.framework.validate.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * 字符 * */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface ZzMsLettersOnly { public String message() default "value should be letters."; }
zz-ms
trunk/zz-ms-v1.0/sourcecode/framework/src/com/jzzms/framework/validate/annotation/ZzMsLettersOnly.java
Java
asf20
776
/** * Copyright : http://www.orientpay.com , 2007-2012 * Project : oecs-g2-framework-trunk * $Id$ * $Revision$ * Last Changed by jason at 2011-10-19 下午4:46:30 * $URL$ * * Change Log * Author Change Date Comments *------------------------------------------------------------- * jason 2011-10-19 Initailized */ package com.jzzms.framework.validate.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * 电话号码 和 手机 * */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface ZzMsPhone { public String message() default "Value is not a phone."; }
zz-ms
trunk/zz-ms-v1.0/sourcecode/framework/src/com/jzzms/framework/validate/annotation/ZzMsPhone.java
Java
asf20
784
/** * Copyright : http://www.orientpay.com , 2007-2012 * Project : oecs-g2-framework-trunk * $Id$ * $Revision$ * Last Changed by jason at 2011-10-19 下午4:50:32 * $URL$ * * Change Log * Author Change Date Comments *------------------------------------------------------------- * jason 2011-10-19 Initailized */ package com.jzzms.framework.validate.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * 带小数点的数字 * */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface ZzMsNumber { public String message() default "Value is not a number."; }
zz-ms
trunk/zz-ms-v1.0/sourcecode/framework/src/com/jzzms/framework/validate/annotation/ZzMsNumber.java
Java
asf20
784
/** * Copyright : http://www.orientpay.com , 2007-2012 * Project : oecs-g2-framework-trunk * $Id$ * $Revision$ * Last Changed by jason at 2011-10-19 下午4:49:49 * $URL$ * * Change Log * Author Change Date Comments *------------------------------------------------------------- * jason 2011-10-19 Initailized */ package com.jzzms.framework.validate.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * 地址格式 * */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface ZzMsUrl { public String message() default "This is not an url."; }
zz-ms
trunk/zz-ms-v1.0/sourcecode/framework/src/com/jzzms/framework/validate/annotation/ZzMsUrl.java
Java
asf20
769
/** * Copyright : http://www.orientpay.com , 2007-2012 * Project : oecs-g2-framework-trunk * $Id$ * $Revision$ * Last Changed by jason at 2011-10-18 上午9:08:57 * $URL$ * * Change Log * Author Change Date Comments *------------------------------------------------------------- * jason 2011-10-18 Initailized */ package com.jzzms.framework.validate.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * 不能为空 * */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface ZzMsRequired { public String message() default "This should not to be empty."; }
zz-ms
trunk/zz-ms-v1.0/sourcecode/framework/src/com/jzzms/framework/validate/annotation/ZzMsRequired.java
Java
asf20
784
/** * Copyright : http://www.orientpay.com , 2007-2012 * Project : oecs-g2-framework-trunk * $Id$ * $Revision$ * Last Changed by jason at 2011-10-19 下午4:49:08 * $URL$ * * Change Log * Author Change Date Comments *------------------------------------------------------------- * jason 2011-10-19 Initailized */ package com.jzzms.framework.validate.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * 邮政编码 * */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface ZzMsPostCode { public String message() default "Value is not a postcode."; }
zz-ms
trunk/zz-ms-v1.0/sourcecode/framework/src/com/jzzms/framework/validate/annotation/ZzMsPostCode.java
Java
asf20
779
/** * Copyright : http://www.orientpay.com , 2007-2012 * Project : oecs-g2-framework-trunk * $Id$ * $Revision$ * Last Changed by jason at 2011-10-19 下午4:50:49 * $URL$ * * Change Log * Author Change Date Comments *------------------------------------------------------------- * jason 2011-10-19 Initailized */ package com.jzzms.framework.validate.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * 数字 * */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface ZzMsDigits { public String message() default "Value is not a digits."; }
zz-ms
trunk/zz-ms-v1.0/sourcecode/framework/src/com/jzzms/framework/validate/annotation/ZzMsDigits.java
Java
asf20
769
/** * Copyright : http://www.orientpay.com , 2007-2012 * Project : oecs-g2-framework-trunk * $Id$ * $Revision$ * Last Changed by jason at 2011-10-19 下午4:55:25 * $URL$ * * Change Log * Author Change Date Comments *------------------------------------------------------------- * jason 2011-10-19 Initailized */ package com.jzzms.framework.validate.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * 值的范围 * */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface ZzMsRange { public double min() default Integer.MIN_VALUE; public double max() default Integer.MAX_VALUE; public String message() default "Value is not in expected scope."; }
zz-ms
trunk/zz-ms-v1.0/sourcecode/framework/src/com/jzzms/framework/validate/annotation/ZzMsRange.java
Java
asf20
891
/** * Copyright : http://www.orientpay.com , 2007-2012 * Project : oecs-g2-framework-trunk * $Id$ * $Revision$ * Last Changed by jason at 2011-10-17 下午12:44:45 * $URL$ * * Change Log * Author Change Date Comments *------------------------------------------------------------- * jason 2011-10-17 Initailized */ package com.jzzms.framework.validate; import java.lang.annotation.Annotation; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.jzzms.framework.core.Constants; import com.jzzms.framework.util.lang.ReflectionUtils; import com.jzzms.framework.validate.handler.ZzMsHandler; /** * 数据校验器 * */ public class Validator { protected static final Log log = LogFactory.getLog(Validator.class); // protected Map<String, ZzMsHandler> annotationHandlerMap; public final static String HANDLER_CLASS_PREFIX = "com.orientpay.oecs.framework.validate.handler"; public final static String HANDLER_CLAS_SUFFIX = "Handler"; public final static String HANDLER_NAME_PREFIX = "Oecs"; public final static String ANNOTATION_CLASS_PREFIX = "com.orientpay.oecs.framework.validate.annotation"; private static Validator validator = new Validator(); private Validator() { annotationHandlerMap = new HashMap<String, ZzMsHandler>(); } /** * get the Validator object * * @return Validator object */ public static Validator getInstance() { return validator; } public void validate(Object validatedObj) throws Exception { if (null == validatedObj) { log.info("The input validatedObj is null."); return; } Class<?> currentClass = validatedObj.getClass(); while (currentClass != null) { Field[] fields = currentClass.getDeclaredFields(); for (Field elem : fields) { validateField(validatedObj, elem); } Class<?> superClass = currentClass.getSuperclass(); if(superClass != null){ currentClass = validatedObj.getClass().isAssignableFrom(superClass) ? superClass : null; } } } private void validateField(Object validatedObj, Field field) throws Exception{ // check whether the field is also AnnotationValidable if(validatedObj.getClass().isAssignableFrom(field.getType())){ Object destValue = ReflectionUtils.invokeGetterMethod(validatedObj, field.getName()); if(destValue == null) { return; } else { validate(destValue); } } List<Annotation> annotations = getValidateAnnotations(field); if (annotations != null && annotations.size() > 0) { // loop each field annotations for (Annotation annotation : annotations) { String annotationSimpleName = annotation.annotationType().getSimpleName(); ZzMsHandler handler = annotationHandlerMap.get(annotationSimpleName); if(handler == null){ String className = HANDLER_CLASS_PREFIX + Constants.DOT_SIGN_SPLIT_NAME + annotationSimpleName + HANDLER_CLAS_SUFFIX; try { handler = (ZzMsHandler) Class.forName(className).newInstance(); annotationHandlerMap.put(annotationSimpleName, handler); } catch (Exception ex) { log.warn("WARN", ex); throw new IllegalStateException(ex); } } if(handler != null){ handler.validate(validatedObj, field); } } } } public static List<Annotation> getValidateAnnotations(Field field) { List<Annotation> annotations = new ArrayList<Annotation>(); Annotation[] annos = field.getAnnotations(); for (Annotation elem : annos) { if (elem.annotationType().getName().startsWith(ANNOTATION_CLASS_PREFIX)) { annotations.add(elem); } } return annotations; } }
zz-ms
trunk/zz-ms-v1.0/sourcecode/framework/src/com/jzzms/framework/validate/Validator.java
Java
asf20
4,625
/** * Copyright : http://www.orientpay.com , 2007-2012 * Project : oecs-g2-framework-trunk * $Id$ * $Revision$ * Last Changed by jason at 2011-10-19 下午5:23:03 * $URL$ * * Change Log * Author Change Date Comments *------------------------------------------------------------- * jason 2011-10-19 Initailized */ package com.jzzms.framework.validate.handler; import java.lang.reflect.Field; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.jzzms.framework.util.lang.ReflectionUtils; import com.jzzms.framework.validate.annotation.ZzMsLettersOnly; /** * 只能为字符 * */ public class ZzMsLettersOnlyHandler implements ZzMsHandler { protected final Log log = LogFactory.getLog(getClass()); public void validate(Object validatedObj, Field field) throws Exception { Object obj = ReflectionUtils.invokeGetterMethod(validatedObj, field.getName()); if(obj != null){ boolean result = StringUtils.isAlpha(obj.toString()); log.debug("obj value is :" + obj.toString()); if(!result){ log.info("the obj is invalidate for LettersOnly"); String message = field.getAnnotation(ZzMsLettersOnly.class).message(); throw new IllegalArgumentException(message); } } } }
zz-ms
trunk/zz-ms-v1.0/sourcecode/framework/src/com/jzzms/framework/validate/handler/ZzMsLettersOnlyHandler.java
Java
asf20
1,466
/** * Copyright : http://www.orientpay.com , 2007-2012 * Project : oecs-g2-framework-trunk * $Id$ * $Revision$ * Last Changed by jason at 2011-10-17 下午12:55:07 * $URL$ * * Change Log * Author Change Date Comments *------------------------------------------------------------- * jason 2011-10-17 Initailized */ package com.jzzms.framework.validate.handler; import java.lang.reflect.Field; /** * 验证接口 * */ public interface ZzMsHandler { public void validate(Object validatedObj, Field field) throws Exception; }
zz-ms
trunk/zz-ms-v1.0/sourcecode/framework/src/com/jzzms/framework/validate/handler/ZzMsHandler.java
Java
asf20
597
/** * Copyright : http://www.orientpay.com , 2007-2012 * Project : oecs-g2-framework-trunk * $Id$ * $Revision$ * Last Changed by jason at 2011-10-19 下午5:26:11 * $URL$ * * Change Log * Author Change Date Comments *------------------------------------------------------------- * jason 2011-10-19 Initailized */ package com.jzzms.framework.validate.handler; import java.lang.reflect.Field; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.jzzms.framework.util.lang.ReflectionUtils; import com.jzzms.framework.validate.annotation.ZzMsRequired; /** * 不允许为空 * */ public class ZzMsRequiredHandler implements ZzMsHandler { protected final Log log = LogFactory.getLog(getClass()); public void validate(Object validatedObj, Field field) throws Exception { Object obj = ReflectionUtils.invokeGetterMethod(validatedObj, field.getName()); if(obj == null){ log.info("the obj can not be null"); String message = field.getAnnotation(ZzMsRequired.class).message(); throw new IllegalArgumentException(message); } else{ boolean result = StringUtils.isNotBlank(obj.toString()); log.debug("obj value is :" + obj.toString()); if(!result){ log.info("the obj can not be null String"); String message = field.getAnnotation(ZzMsRequired.class).message(); throw new IllegalArgumentException(message); } } } }
zz-ms
trunk/zz-ms-v1.0/sourcecode/framework/src/com/jzzms/framework/validate/handler/ZzMsRequiredHandler.java
Java
asf20
1,674
/** * Copyright : http://www.orientpay.com , 2007-2012 * Project : oecs-g2-framework-trunk * $Id$ * $Revision$ * Last Changed by jason at 2011-10-19 下午5:23:24 * $URL$ * * Change Log * Author Change Date Comments *------------------------------------------------------------- * jason 2011-10-19 Initailized */ package com.jzzms.framework.validate.handler; import java.lang.reflect.Field; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.jzzms.framework.util.lang.ReflectionUtils; import com.jzzms.framework.validate.annotation.ZzMsMax; /** * 最大值 * */ public class ZzMsMaxHandler implements ZzMsHandler { protected final Log log = LogFactory.getLog(getClass()); public void validate(Object validatedObj, Field field) throws Exception { Object obj = ReflectionUtils.invokeGetterMethod(validatedObj, field.getName()); if(obj != null){ boolean result = StringUtils.isNumeric(obj.toString()); log.debug("obj value is :" + obj.toString()); if(!result){ log.info("the obj is not a number"); String message = field.getAnnotation(ZzMsMax.class).message(); throw new IllegalArgumentException(message); } else{ double value = Double.parseDouble(obj.toString()); double maxValue = field.getAnnotation(ZzMsMax.class).max(); if(value > maxValue){ log.info("the obj is great than max value :" + maxValue); String message = field.getAnnotation(ZzMsMax.class).message(); throw new IllegalArgumentException(message); } } } } }
zz-ms
trunk/zz-ms-v1.0/sourcecode/framework/src/com/jzzms/framework/validate/handler/ZzMsMaxHandler.java
Java
asf20
1,896
/** * Copyright : http://www.orientpay.com , 2007-2012 * Project : oecs-g2-framework-trunk * $Id$ * $Revision$ * Last Changed by jason at 2011-10-19 下午5:21:50 * $URL$ * * Change Log * Author Change Date Comments *------------------------------------------------------------- * jason 2011-10-19 Initailized */ package com.jzzms.framework.validate.handler; import java.lang.reflect.Field; import java.util.Date; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.jzzms.framework.util.lang.DateTimeUtils; import com.jzzms.framework.util.lang.ReflectionUtils; import com.jzzms.framework.validate.annotation.ZzMsDate; /** * 日期的判断 * */ public class ZzMsDateHandler implements ZzMsHandler { protected final Log log = LogFactory.getLog(getClass()); public void validate(Object validatedObj, Field field) throws Exception { Object obj = ReflectionUtils.invokeGetterMethod(validatedObj, field.getName()); if(obj != null){ if(obj instanceof Date){ return; } Date date = DateTimeUtils.stringFormatToDate(obj.toString(), null); if(date == null){ log.info("the obj is invalidate for date"); String message = field.getAnnotation(ZzMsDate.class).message(); throw new IllegalArgumentException(message); } } } }
zz-ms
trunk/zz-ms-v1.0/sourcecode/framework/src/com/jzzms/framework/validate/handler/ZzMsDateHandler.java
Java
asf20
1,524
/** * Copyright : http://www.orientpay.com , 2007-2012 * Project : oecs-g2-framework-trunk * $Id$ * $Revision$ * Last Changed by jason at 2011-10-19 下午5:22:24 * $URL$ * * Change Log * Author Change Date Comments *------------------------------------------------------------- * jason 2011-10-19 Initailized */ package com.jzzms.framework.validate.handler; import java.lang.reflect.Field; import java.util.regex.Pattern; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.jzzms.framework.util.lang.ReflectionUtils; import com.jzzms.framework.validate.annotation.ZzMsDigits; /** * 数字校验器 * */ public class ZzMsDigitsHandler implements ZzMsHandler { protected final Log log = LogFactory.getLog(getClass()); public void validate(Object validatedObj, Field field) throws Exception { Object obj = ReflectionUtils.invokeGetterMethod(validatedObj, field.getName()); if(obj != null){ Pattern pattern = Pattern.compile("[0-9]*"); boolean result = pattern.matcher(obj.toString()).matches(); log.debug("obj value is :" + obj.toString()); if(!result){ log.info("the obj is invalidate for digits"); String message = field.getAnnotation(ZzMsDigits.class).message(); throw new IllegalArgumentException(message); } } } }
zz-ms
trunk/zz-ms-v1.0/sourcecode/framework/src/com/jzzms/framework/validate/handler/ZzMsDigitsHandler.java
Java
asf20
1,516
/** * Copyright : http://www.orientpay.com , 2007-2012 * Project : oecs-g2-framework-trunk * $Id$ * $Revision$ * Last Changed by jason at 2011-10-19 下午5:24:03 * $URL$ * * Change Log * Author Change Date Comments *------------------------------------------------------------- * jason 2011-10-19 Initailized */ package com.jzzms.framework.validate.handler; import java.lang.reflect.Field; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.jzzms.framework.util.lang.ReflectionUtils; import com.jzzms.framework.validate.annotation.ZzMsMin; /** * 最小值 * */ public class ZzMsMinHandler implements ZzMsHandler { protected final Log log = LogFactory.getLog(getClass()); public void validate(Object validatedObj, Field field) throws Exception { Object obj = ReflectionUtils.invokeGetterMethod(validatedObj, field.getName()); if(obj != null){ boolean result = StringUtils.isNumeric(obj.toString()); log.debug("obj value is :" + obj.toString()); if(!result){ log.info("the obj is not a number"); String message = field.getAnnotation(ZzMsMin.class).message(); throw new IllegalArgumentException(message); } else{ double value = Double.parseDouble(obj.toString()); double minValue = field.getAnnotation(ZzMsMin.class).min(); if(value < minValue){ log.info("the obj is less than max value :" + minValue); String message = field.getAnnotation(ZzMsMin.class).message(); throw new IllegalArgumentException(message); } } } } }
zz-ms
trunk/zz-ms-v1.0/sourcecode/framework/src/com/jzzms/framework/validate/handler/ZzMsMinHandler.java
Java
asf20
1,895
/** * Copyright : http://www.orientpay.com , 2007-2012 * Project : oecs-g2-framework-trunk * $Id$ * $Revision$ * Last Changed by jason at 2011-10-19 下午5:23:46 * $URL$ * * Change Log * Author Change Date Comments *------------------------------------------------------------- * jason 2011-10-19 Initailized */ package com.jzzms.framework.validate.handler; import java.lang.reflect.Field; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.jzzms.framework.util.lang.ReflectionUtils; import com.jzzms.framework.validate.annotation.ZzMsMaxLength; /** * 最大长度 * */ public class ZzMsMaxLengthHandler implements ZzMsHandler { protected final Log log = LogFactory.getLog(getClass()); public void validate(Object validatedObj, Field field) throws Exception { Object obj = ReflectionUtils.invokeGetterMethod(validatedObj, field.getName()); if(obj != null){ log.debug("obj value is :" + obj.toString()); double maxValue = field.getAnnotation(ZzMsMaxLength.class).max(); int value = obj.toString().length(); if(value > maxValue){ log.info("the obj length is great than max value :" + maxValue); String message = field.getAnnotation(ZzMsMaxLength.class).message(); throw new IllegalArgumentException(message); } } } }
zz-ms
trunk/zz-ms-v1.0/sourcecode/framework/src/com/jzzms/framework/validate/handler/ZzMsMaxLengthHandler.java
Java
asf20
1,503
/** * Copyright : http://www.orientpay.com , 2007-2012 * Project : oecs-g2-framework-trunk * $Id$ * $Revision$ * Last Changed by jason at 2011-10-19 下午5:25:06 * $URL$ * * Change Log * Author Change Date Comments *------------------------------------------------------------- * jason 2011-10-19 Initailized */ package com.jzzms.framework.validate.handler; import java.lang.reflect.Field; import java.util.regex.Pattern; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.jzzms.framework.util.lang.ReflectionUtils; import com.jzzms.framework.validate.annotation.ZzMsPhone; /** * 是否为电话号码 * */ public class ZzMsPhoneHandler implements ZzMsHandler { protected final Log log = LogFactory.getLog(getClass()); public void validate(Object validatedObj, Field field) throws Exception { Object obj = ReflectionUtils.invokeGetterMethod(validatedObj, field.getName()); if(obj != null){ boolean result = checkPhoneNo(obj.toString()); if(!result){ log.info("the obj is invalidate for digits"); String message = field.getAnnotation(ZzMsPhone.class).message(); throw new IllegalArgumentException(message); } } } protected static boolean checkPhoneNo(String phoneNo){ //mobile phone Pattern mpPattern = Pattern.compile("^(0)?1\\d{10}$"); boolean mpResult = mpPattern.matcher(phoneNo).matches(); //home phone Pattern hpPattern = Pattern.compile("^(0\\d{2,3})?(-)?\\d{7,8}(-(\\d)+)?$"); boolean hpResult = hpPattern.matcher(phoneNo).matches(); return (mpResult || hpResult); } //pass public static void main(String [] args){ System.out.println("13564539543:" + checkPhoneNo("13564539543")); System.out.println("013564539543:" + checkPhoneNo("013564539543")); System.out.println("23564539543:" + checkPhoneNo("23564539543")); System.out.println("021-51560909:" + checkPhoneNo("021-51560909")); System.out.println("02151560909:" + checkPhoneNo("02151560909")); System.out.println("51560909:" + checkPhoneNo("51560909")); System.out.println("021a51560909:" + checkPhoneNo("021a51560909")); System.out.println("0215156090977:" + checkPhoneNo("0215156090977")); System.out.println("515609098:" + checkPhoneNo("5a5609098")); System.out.println("5156090989999:" + checkPhoneNo("515609098999")); System.out.println("02151560909-99:" + checkPhoneNo("02151560909-99")); System.out.println("021-51560909-99:" + checkPhoneNo("021-51560909-99")); System.out.println("02151560909-:" + checkPhoneNo("02151560909-")); System.out.println("51560909-44a" + checkPhoneNo("51560909-44a")); } }
zz-ms
trunk/zz-ms-v1.0/sourcecode/framework/src/com/jzzms/framework/validate/handler/ZzMsPhoneHandler.java
Java
asf20
3,017
/** * Copyright : http://www.orientpay.com , 2007-2012 * Project : oecs-g2-framework-trunk * $Id$ * $Revision$ * Last Changed by jason at 2011-10-19 下午5:25:19 * $URL$ * * Change Log * Author Change Date Comments *------------------------------------------------------------- * jason 2011-10-19 Initailized */ package com.jzzms.framework.validate.handler; import java.lang.reflect.Field; import java.util.regex.Pattern; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.jzzms.framework.util.lang.ReflectionUtils; import com.jzzms.framework.validate.annotation.ZzMsPostCode; /** * 邮政编码校验器 * */ public class ZzMsPostCodeHandler implements ZzMsHandler { protected final Log log = LogFactory.getLog(getClass()); public void validate(Object validatedObj, Field field) throws Exception { Object obj = ReflectionUtils.invokeGetterMethod(validatedObj, field.getName()); if(obj != null){ Pattern pattern = Pattern.compile("[0-9]*"); boolean result = pattern.matcher(obj.toString()).matches(); log.debug("obj value is :" + obj.toString()); if((!result) || obj.toString().length() != 6){ log.info("the obj is invalidate for digits"); String message = field.getAnnotation(ZzMsPostCode.class).message(); throw new IllegalArgumentException(message); } } } }
zz-ms
trunk/zz-ms-v1.0/sourcecode/framework/src/com/jzzms/framework/validate/handler/ZzMsPostCodeHandler.java
Java
asf20
1,558
/** * Copyright : http://www.orientpay.com , 2007-2012 * Project : oecs-g2-framework-trunk * $Id$ * $Revision$ * Last Changed by jason at 2011-10-19 下午5:25:36 * $URL$ * * Change Log * Author Change Date Comments *------------------------------------------------------------- * jason 2011-10-19 Initailized */ package com.jzzms.framework.validate.handler; import java.lang.reflect.Field; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.jzzms.framework.util.lang.ReflectionUtils; import com.jzzms.framework.validate.annotation.ZzMsRange; /** * 指定范围 * */ public class ZzMsRangeHandler implements ZzMsHandler { protected final Log log = LogFactory.getLog(getClass()); public void validate(Object validatedObj, Field field) throws Exception { Object obj = ReflectionUtils.invokeGetterMethod(validatedObj, field.getName()); if(obj != null){ boolean result = StringUtils.isNumeric(obj.toString()); log.debug("obj value is :" + obj.toString()); if(!result){ log.info("the obj is not a number"); String message = field.getAnnotation(ZzMsRange.class).message(); throw new IllegalArgumentException(message); } else{ double value = Double.parseDouble(obj.toString()); double maxValue = field.getAnnotation(ZzMsRange.class).max(); double minValue = field.getAnnotation(ZzMsRange.class).min(); if(value > maxValue || value < minValue){ log.info("the obj is out of scope :" + minValue +"," + maxValue); String message = field.getAnnotation(ZzMsRange.class).message(); throw new IllegalArgumentException(message); } } } } }
zz-ms
trunk/zz-ms-v1.0/sourcecode/framework/src/com/jzzms/framework/validate/handler/ZzMsRangeHandler.java
Java
asf20
2,016
/** * Copyright : http://www.orientpay.com , 2007-2012 * Project : oecs-g2-framework-trunk * $Id$ * $Revision$ * Last Changed by jason at 2011-10-19 下午5:25:54 * $URL$ * * Change Log * Author Change Date Comments *------------------------------------------------------------- * jason 2011-10-19 Initailized */ package com.jzzms.framework.validate.handler; import java.lang.reflect.Field; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.jzzms.framework.util.lang.ReflectionUtils; import com.jzzms.framework.validate.annotation.ZzMsRangeLength; /** * 长度范围 * */ public class ZzMsRangeLengthHandler implements ZzMsHandler { protected final Log log = LogFactory.getLog(getClass()); public void validate(Object validatedObj, Field field) throws Exception { Object obj = ReflectionUtils.invokeGetterMethod(validatedObj, field.getName()); if(obj != null){ log.debug("obj value is :" + obj.toString()); double maxValue = field.getAnnotation(ZzMsRangeLength.class).max(); double minValue = field.getAnnotation(ZzMsRangeLength.class).min(); int value = obj.toString().length(); if(value > maxValue || value < minValue){ log.info("the obj length is out of scope :" + minValue +"," + maxValue); String message = field.getAnnotation(ZzMsRangeLength.class).message(); throw new IllegalArgumentException(message); } } } }
zz-ms
trunk/zz-ms-v1.0/sourcecode/framework/src/com/jzzms/framework/validate/handler/ZzMsRangeLengthHandler.java
Java
asf20
1,626
/** * Copyright : http://www.orientpay.com , 2007-2012 * Project : oecs-g2-framework-trunk * $Id$ * $Revision$ * Last Changed by jason at 2011-10-19 下午5:20:14 * $URL$ * * Change Log * Author Change Date Comments *------------------------------------------------------------- * jason 2011-10-19 Initailized */ package com.jzzms.framework.validate.handler; import java.lang.reflect.Field; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.jzzms.framework.util.lang.ReflectionUtils; import com.jzzms.framework.validate.annotation.ZzMsAlphanumeric; /** * 字母 * */ public class ZzMsAlphanumericHandler implements ZzMsHandler{ protected final Log log = LogFactory.getLog(getClass()); public void validate(Object validatedObj, Field field) throws Exception { Object obj = ReflectionUtils.invokeGetterMethod(validatedObj, field.getName()); if(obj != null){ boolean result = StringUtils.isAlphanumeric(obj.toString()); log.debug("obj value is :" + obj.toString()); if(!result){ log.info("the obj is invalidate for Alphanumeric"); String message = field.getAnnotation(ZzMsAlphanumeric.class).message(); throw new IllegalArgumentException(message); } } } }
zz-ms
trunk/zz-ms-v1.0/sourcecode/framework/src/com/jzzms/framework/validate/handler/ZzMsAlphanumericHandler.java
Java
asf20
1,473
/** * Copyright : http://www.orientpay.com , 2007-2012 * Project : oecs-g2-framework-trunk * $Id$ * $Revision$ * Last Changed by jason at 2011-10-19 下午5:22:50 * $URL$ * * Change Log * Author Change Date Comments *------------------------------------------------------------- * jason 2011-10-19 Initailized */ package com.jzzms.framework.validate.handler; import java.lang.reflect.Field; import java.util.regex.Pattern; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.jzzms.framework.util.lang.ReflectionUtils; import com.jzzms.framework.validate.annotation.ZzMsEmail; /** * 邮箱校验器 * */ public class ZzMsEmailHandler implements ZzMsHandler { protected final Log log = LogFactory.getLog(getClass()); public void validate(Object validatedObj, Field field) throws Exception { Object obj = ReflectionUtils.invokeGetterMethod(validatedObj, field.getName()); if(obj != null){ Pattern pattern = Pattern.compile("[\\w\\.\\-]+@([\\w\\-]+\\.)+[\\w\\-]+"); boolean result = pattern.matcher(obj.toString()).matches(); log.debug("obj value is :" + obj.toString()); if(!result){ log.info("the obj is invalidate for email"); String message = field.getAnnotation(ZzMsEmail.class).message(); throw new IllegalArgumentException(message); } } } }
zz-ms
trunk/zz-ms-v1.0/sourcecode/framework/src/com/jzzms/framework/validate/handler/ZzMsEmailHandler.java
Java
asf20
1,543
/** * Copyright : http://www.orientpay.com , 2007-2012 * Project : oecs-g2-framework-trunk * $Id$ * $Revision$ * Last Changed by jason at 2011-10-19 下午5:24:43 * $URL$ * * Change Log * Author Change Date Comments *------------------------------------------------------------- * jason 2011-10-19 Initailized */ package com.jzzms.framework.validate.handler; import java.lang.reflect.Field; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.jzzms.framework.util.lang.ReflectionUtils; import com.jzzms.framework.validate.annotation.ZzMsNumber; /** * 数字校验器 * */ public class ZzMsNumberHandler implements ZzMsHandler { protected final Log log = LogFactory.getLog(getClass()); public void validate(Object validatedObj, Field field) throws Exception { Object obj = ReflectionUtils.invokeGetterMethod(validatedObj, field.getName()); if(obj != null){ boolean result = StringUtils.isNumeric(obj.toString()); log.debug("obj value is :" + obj.toString()); if(!result){ log.info("the obj is invalidate for number"); String message = field.getAnnotation(ZzMsNumber.class).message(); throw new IllegalArgumentException(message); } } } }
zz-ms
trunk/zz-ms-v1.0/sourcecode/framework/src/com/jzzms/framework/validate/handler/ZzMsNumberHandler.java
Java
asf20
1,448
/** * Copyright : http://www.orientpay.com , 2007-2012 * Project : oecs-g2-framework-trunk * $Id$ * $Revision$ * Last Changed by jason at 2011-10-19 下午5:24:21 * $URL$ * * Change Log * Author Change Date Comments *------------------------------------------------------------- * jason 2011-10-19 Initailized */ package com.jzzms.framework.validate.handler; import java.lang.reflect.Field; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.jzzms.framework.util.lang.ReflectionUtils; import com.jzzms.framework.validate.annotation.ZzMsMinLength; /** * 最小长度 * */ public class ZzMsMinLengthHandler implements ZzMsHandler { protected final Log log = LogFactory.getLog(getClass()); public void validate(Object validatedObj, Field field) throws Exception { Object obj = ReflectionUtils.invokeGetterMethod(validatedObj, field.getName()); if(obj != null){ log.debug("obj value is :" + obj.toString()); double minValue = field.getAnnotation(ZzMsMinLength.class).min(); int value = obj.toString().length(); if(value > minValue){ log.info("the obj length is less than max value :" + minValue); String message = field.getAnnotation(ZzMsMinLength.class).message(); throw new IllegalArgumentException(message); } } } }
zz-ms
trunk/zz-ms-v1.0/sourcecode/framework/src/com/jzzms/framework/validate/handler/ZzMsMinLengthHandler.java
Java
asf20
1,496
/** * Copyright : http://www.orientpay.com , 2007-2012 * Project : oecs-g2-framework-trunk * $Id$ * $Revision$ * Last Changed by jason at 2011-10-19 下午5:26:28 * $URL$ * * Change Log * Author Change Date Comments *------------------------------------------------------------- * jason 2011-10-19 Initailized */ package com.jzzms.framework.validate.handler; import java.lang.reflect.Field; import java.util.regex.Pattern; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.jzzms.framework.util.lang.ReflectionUtils; import com.jzzms.framework.validate.annotation.ZzMsUrl; /** * URL地址 * */ public class ZzMsUrlHandler implements ZzMsHandler { protected final Log log = LogFactory.getLog(getClass()); public void validate(Object validatedObj, Field field) throws Exception { Object obj = ReflectionUtils.invokeGetterMethod(validatedObj, field.getName()); if(obj != null){ Pattern pattern = Pattern.compile("^[a-zA-z]+://[^\\s]*$"); boolean result = pattern.matcher(obj.toString()).matches(); log.debug("obj value is :" + obj.toString()); if(!result){ log.info("the obj is invalidate for url"); String message = field.getAnnotation(ZzMsUrl.class).message(); throw new IllegalArgumentException(message); } } } }
zz-ms
trunk/zz-ms-v1.0/sourcecode/framework/src/com/jzzms/framework/validate/handler/ZzMsUrlHandler.java
Java
asf20
1,513
/** * Copyright : http://www.orientpay.com , 2007-2012 * Project : oecs-g2-framework-trunk * $Id$ * $Revision$ * Last Changed by jason at 2011-9-13 下午4:47:42 * $URL$ * * Change Log * Author Change Date Comments *------------------------------------------------------------- * jason 2011-9-13 Initailized */ package com.jzzms.framework.view.listener; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.context.ApplicationContext; import org.springframework.web.context.support.WebApplicationContextUtils; import com.jzzms.framework.core.Constants; import com.jzzms.framework.service.cache.CacheManagerService; import com.jzzms.framework.util.common.SpringContextUtils; /** * 系统加载监听器 * */ public class ContextLoaderListener implements ServletContextListener{ protected Log log = LogFactory.getLog(getClass()); public void contextInitialized(ServletContextEvent arg0) { log.debug("contextInitialized begin..."); ApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(arg0.getServletContext()); CacheManagerService cacheManager = (CacheManagerService)ctx.getBean(Constants.CACHE_MANAGER_BEAN_NAME); cacheManager.init(ctx); log.debug("init springContextUtils..."); SpringContextUtils.init(ctx); log.debug("contextInitialized end"); } public void contextDestroyed(ServletContextEvent arg0) { log.debug("contextDestroyed !"); } }
zz-ms
trunk/zz-ms-v1.0/sourcecode/framework/src/com/jzzms/framework/view/listener/ContextLoaderListener.java
Java
asf20
1,720
package com.jzzms.framework.view.filter; import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import org.springframework.security.access.SecurityMetadataSource; import org.springframework.security.access.intercept.AbstractSecurityInterceptor; import org.springframework.security.access.intercept.InterceptorStatusToken; import org.springframework.security.web.FilterInvocation; import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource; public class FilterSecurityInterceptor extends AbstractSecurityInterceptor implements Filter { private FilterInvocationSecurityMetadataSource securityMetadataSource; public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { FilterInvocation fi = new FilterInvocation(request, response, chain); invoke(fi); } public FilterInvocationSecurityMetadataSource getSecurityMetadataSource() { return this.securityMetadataSource; } public Class<? extends Object> getSecureObjectClass() { return FilterInvocation.class; } public void invoke(FilterInvocation fi) throws IOException, ServletException { InterceptorStatusToken token = super.beforeInvocation(fi); try { fi.getChain().doFilter(fi.getRequest(), fi.getResponse()); } finally { super.afterInvocation(token, null); } } public SecurityMetadataSource obtainSecurityMetadataSource() { return this.securityMetadataSource; } public void setSecurityMetadataSource(FilterInvocationSecurityMetadataSource newSource) { this.securityMetadataSource = newSource; } public void destroy() { } public void init(FilterConfig arg0) throws ServletException { } }
zz-ms
trunk/zz-ms-v1.0/sourcecode/framework/src/com/jzzms/framework/view/filter/FilterSecurityInterceptor.java
Java
asf20
1,952
/** * Copyright : http://www.orientpay.com , 2007-2012 * Project : oecs-g2-framework-trunk * $Id$ * $Revision$ * Last Changed by jason at 2011-11-1 下午7:04:06 * $URL$ * * Change Log * Author Change Date Comments *------------------------------------------------------------- * jason 2011-11-1 Initailized */ package com.jzzms.framework.view.filter; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.apache.commons.lang.StringUtils; import org.springframework.security.authentication.AuthenticationServiceException; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.AuthenticationException; import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; import org.springframework.security.web.util.TextEscapeUtils; import com.jzzms.framework.core.Constants; import com.jzzms.framework.util.common.SystemPropertyUtils; /** * 带验证码的认证过滤器 * */ public class ValidateCodeAuthFilter extends UsernamePasswordAuthenticationFilter { private boolean postOnly = true; private boolean allowEmptyValidateCode = true; @Override public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException { if (postOnly && !request.getMethod().equals("POST")) { throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod()); } //check validate code add by zhouxushun String validatcodeFlag = SystemPropertyUtils.getString(Constants.SPRING_SECURITY_FORM_VCODE_KEY); if(!isAllowEmptyValidateCode() && "true".equalsIgnoreCase(validatcodeFlag)){ checkValidateCode((HttpServletRequest)request); } String username = obtainUsername(request); String password = obtainPassword(request); if (username == null) { username = ""; } if (password == null) { password = ""; } username = username.trim(); UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, password); HttpSession session = request.getSession(false); if (session != null || getAllowSessionCreation()) { request.getSession().setAttribute(SPRING_SECURITY_FORM_USERNAME_KEY, TextEscapeUtils.escapeEntities(username)); } setDetails(request, authRequest); return this.getAuthenticationManager().authenticate(authRequest); } protected void checkValidateCode(HttpServletRequest request) { String sessionValidateCode = obtainSessionValidateCode(request); String validateCodeParameter = obtainValidateCodeParameter(request); if (StringUtils.isEmpty(validateCodeParameter) || !sessionValidateCode.equalsIgnoreCase(validateCodeParameter)) { throw new AuthenticationServiceException("validateCode.notEquals"); } } protected String obtainSessionValidateCode(HttpServletRequest request) { String randCode = (String)request.getSession().getAttribute(Constants.SPRING_SECURITY_RANDS_IN_SESSION); //不需要移除,因为不是防止重复提交 //request.getSession().removeAttribute(AbdfConstants.SPRING_SECURITY_RANDS_IN_SESSION); return randCode; } protected String obtainValidateCodeParameter(HttpServletRequest request) { return request.getParameter(Constants.SPRING_SECURITY_FORM_VCODE_KEY); } public boolean isPostOnly() { return postOnly; } public void setPostOnly(boolean postOnly) { this.postOnly = postOnly; } public boolean isAllowEmptyValidateCode() { return allowEmptyValidateCode; } public void setAllowEmptyValidateCode(boolean allowEmptyValidateCode) { this.allowEmptyValidateCode = allowEmptyValidateCode; } }
zz-ms
trunk/zz-ms-v1.0/sourcecode/framework/src/com/jzzms/framework/view/filter/ValidateCodeAuthFilter.java
Java
asf20
4,279
package com.jzzms.framework.view.action; import java.util.HashMap; import java.util.Map; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.struts2.interceptor.RequestAware; import org.apache.struts2.interceptor.SessionAware; import com.opensymphony.xwork2.ActionSupport; public abstract class SimpleActionSupport extends ActionSupport implements RequestAware, SessionAware { private static final long serialVersionUID = -6780542633093121352L; protected Log log = LogFactory.getLog(getClass()); protected Map<String, Object> request = new HashMap<String, Object>(); protected Map<String, Object> session = new HashMap<String, Object>(); /** 进行增删改操作后,以redirect方式重新打开action默认页的result名.*/ public static final String RELOAD = "reload"; public static final String LIST = "list"; protected boolean flag; //-- 简化分页 --// /** * Action函数, 默认的action函数, 默认调用list()函数. */ public abstract String execute() throws Exception; public Object getSessionAttribute(String key) { if(session.containsKey(key)) { return session.get(key); } return null; } public void setRequestAttribute(String key, Object object) { if(request.containsKey(key)) { request.remove(key); request.put(key, object); } else { request.put(key, object); } } /** * 设置HttpSession中Attribute的简化函数. */ public void setSessionAttribute(String key, Object object) { if(session.containsKey(key)) { session.remove(key); session.put(key, object); } else { session.put(key, object); } } public void setSession(Map<String, Object> arg0) { if(arg0 != null && arg0.size() > 0){ session.putAll(arg0); } } public void setRequest(Map<String, Object> arg0) { if(arg0 != null && arg0.size() > 0){ request.putAll(arg0); } } }
zz-ms
trunk/zz-ms-v1.0/sourcecode/framework/src/com/jzzms/framework/view/action/SimpleActionSupport.java
Java
asf20
2,061
package com.jzzms.framework.view.action; import com.jzzms.framework.core.Constants; import com.jzzms.framework.orm.query.Page; import com.opensymphony.xwork2.ModelDriven; import com.opensymphony.xwork2.Preparable; /** * Struts2中典型CRUD Action的抽象基类. * * 主要定义了对Preparable,ModelDriven接口的使用,以及CRUD函数和返回值的命名. * *ActionSupport 基类提供了string input()、返回值为input 的函数,因此在此不需要进行声明input方法 * @param <T> CRUDAction所管理的对象类型. * * @author */ public abstract class CrudActionSupport<T> extends SimpleActionSupport implements ModelDriven<T>, Preparable { private static final long serialVersionUID = -6780542633093121350L; protected Page<T> page; protected String pk; /** * Action函数, 默认的action函数, 默认调用list()函数. */ public String execute() throws Exception { String ret = list(); setRequestAttribute(Constants.PAGEINFO_IN_REQUEST, getPage()); return ret; } //-- CRUD Action函数 --// /** * Action函数,显示Entity列表界面. * return SUCCESS. */ public abstract String list() throws Exception; /** * Action函数,新增或修改Entity. * return RELOAD. */ public abstract String save() throws Exception; /** * Action函数,新增或修改Entity. * return RELOAD. */ public String view() throws Exception { input(); return SUCCESS; } /** * Action函数,删除Entity. * return RELOAD. */ public abstract String delete() throws Exception; // Preparable函数 // /** * 实现空的prepare()函数,屏蔽所有Action函数公共的二次绑定. */ public void prepare() throws Exception { } /** * 在save()前执行二次绑定. */ public void prepareSave() throws Exception { prepareModel(); } /** * 在input()前执行二次绑定. */ public void prepareInput() throws Exception { prepareModel(); } /** * 等同于prepare()的内部函数,供prepardMethodName()函数调用. */ protected abstract void prepareModel() throws Exception; /** * 获取分页以及结果集 * @return */ public Page<T> getPage(){ if(page == null){ page = new Page<T>(Constants.DEFAULT_PAGE_SIZE); //设置分页的参数 //page.setPageNum() page.setAutoPage(true); page.setAutoCount(false); } return page; } }
zz-ms
trunk/zz-ms-v1.0/sourcecode/framework/src/com/jzzms/framework/view/action/CrudActionSupport.java
Java
asf20
2,474
/** * Copyright : http://www.orientpay.com , 2007-2012 * Project : oecs-g2-common-framework-trunk * $Id$ * $Revision$ * Last Changed by ZhouXushun at 2011-9-6 下午04:26:39 * $URL$ * * Change Log * Author Change Date Comments *------------------------------------------------------------- * ZhouXushun 2011-9-6 Initailized */ package com.jzzms.framework.dao; import java.io.Serializable; import java.util.List; import org.apache.ibatis.session.RowBounds; import com.jzzms.framework.orm.query.ZzMsCriterion; /** * DAO的基接口 * 其他基类都可以实现该或者基础该接口 */ public interface Dao<T, PK extends Serializable>{ /** * 保存新增的对象. */ public void save(final T entity); /** * 保存修改的对象. */ public void update(final T entity); /** * 按id删除对象. */ public void delete(final PK id); /** * 按id获取对象. */ public T get(final PK id); /** * 根据分页获取数据, rowBounds如果为空,则没有分页 */ List<T> find(ZzMsCriterion criterion, RowBounds rowBounds); /** * 计算总记录数 * @param criterion * @return */ public long count(ZzMsCriterion criterion); }
zz-ms
trunk/zz-ms-v1.0/sourcecode/framework/src/com/jzzms/framework/dao/Dao.java
Java
asf20
1,374
/** * Copyright : http://www.orientpay.com , 2007-2012 * Project : oecs-framework * $Id$ * $Revision$ * Last Changed by gaowm at 2012-4-6 下午7:46:16 * $URL$ * * Change Log * Author Change Date Comments *------------------------------------------------------------- * gaowm 2012-4-6 Initailized */ package com.jzzms.framework.dao; /** * dao扫描接口 * */ public @interface ZzMsMapper { }
zz-ms
trunk/zz-ms-v1.0/sourcecode/framework/src/com/jzzms/framework/dao/ZzMsMapper.java
Java
asf20
460
/** * Copyright : http://www.orientpay.com , 2007-2012 * Project : oecs-g2-common-framework-trunk * $Id$ * $Revision$ * Last Changed by ZhouXushun at 2011-8-26 下午02:40:45 * $URL$ * * Change Log * Author Change Date Comments *------------------------------------------------------------- * ZhouXushun 2011-8-26 Initailized */ package com.jzzms.framework.orm.dialect; /** * MYSQL本地语言 * */ public class MySQLDialect extends Dialect { public boolean supportsLimitOffset() { return true; } public boolean supportsLimit() { return true; } public String getLimitString(String sql, int offset, String offsetPlaceholder, int limit, String limitPlaceholder) { if (offset > 0) { return sql + " limit " + offsetPlaceholder + "," + limitPlaceholder; } return sql + " limit " + limitPlaceholder; } }
zz-ms
trunk/zz-ms-v1.0/sourcecode/framework/src/com/jzzms/framework/orm/dialect/MySQLDialect.java
Java
asf20
1,100
/** * Copyright : http://www.orientpay.com , 2007-2012 * Project : oecs-g2-common-framework-trunk * $Id$ * $Revision$ * Last Changed by ZhouXushun at 2011-8-26 下午02:40:04 * $URL$ * * Change Log * Author Change Date Comments *------------------------------------------------------------- * ZhouXushun 2011-8-26 Initailized */ package com.jzzms.framework.orm.dialect; /** * oracle本地语言 * */ public class OracleDialect extends Dialect { public boolean supportsLimit() { return true; } public boolean supportsLimitOffset() { return true; } public String getLimitString(String sql, int offset, String offsetPlaceholder, int limit, String limitPlaceholder) { sql = sql.trim(); boolean isForUpdate = false; if (sql.toLowerCase().endsWith(" for update")) { sql = sql.substring(0, sql.length() - 11); isForUpdate = true; } StringBuffer pagingSelect = new StringBuffer(sql.length() + 100); if (offset > 0) pagingSelect.append("select * from ( select row_.*, rownum rownum_ from ( "); else { pagingSelect.append("select * from ( "); } pagingSelect.append(sql); if (offset > 0) { String endString = offsetPlaceholder + "+" + limitPlaceholder; pagingSelect.append(" ) row_ ) where rownum_ <= " + endString + " and rownum_ > " + offsetPlaceholder); } else { pagingSelect.append(" ) where rownum <= " + limitPlaceholder); } if (isForUpdate) { pagingSelect.append(" for update"); } return pagingSelect.toString(); } }
zz-ms
trunk/zz-ms-v1.0/sourcecode/framework/src/com/jzzms/framework/orm/dialect/OracleDialect.java
Java
asf20
1,977
/** * Copyright : http://www.orientpay.com , 2007-2012 * Project : oecs-g2-common-framework-trunk * $Id$ * $Revision$ * Last Changed by ZhouXushun at 2011-8-26 下午02:34:31 * $URL$ * * Change Log * Author Change Date Comments *------------------------------------------------------------- * ZhouXushun 2011-8-26 Initailized */ package com.jzzms.framework.orm.dialect; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * 本地数据库语言 * */ public class Dialect { public boolean supportsLimit() { return false; } public boolean supportsLimitOffset() { return supportsLimit(); } public String getLimitString(String sql, int offset, int limit) { return getLimitString(sql, offset, Integer.toString(offset), limit, Integer.toString(limit)); } public String getLimitString(String sql, int offset, String offsetPlaceholder, int limit, String limitPlaceholder) { throw new UnsupportedOperationException("paged queries not supported"); } public String getCountSQL(String sql) { String countQueryString = null; if (isWarp(sql)) countQueryString = "select count(*) from (" + removeOrders(sql) + ") _COUNT_FOR_SQL_"; else { countQueryString = " select count(*) " + removeSelect(removeOrders(sql)); } return countQueryString; } private static String removeOrders(String hql) { Pattern p = Pattern.compile("order\\s*by[\\w|\\W|\\s|\\S]*", 2); Matcher m = p.matcher(hql); StringBuffer sb = new StringBuffer(); while (m.find()) { m.appendReplacement(sb, ""); } m.appendTail(sb); return sb.toString(); } private static boolean isWarp(String hql) { Pattern p = Pattern.compile("(group\\s*by[\\w|\\W|\\s|\\S]*|union)+", 2); Matcher m = p.matcher(hql); return m.find(); } private static String removeSelect(String hql) { int beginPos = hql.toLowerCase().indexOf("from"); return hql.substring(beginPos); } }
zz-ms
trunk/zz-ms-v1.0/sourcecode/framework/src/com/jzzms/framework/orm/dialect/Dialect.java
Java
asf20
2,558
/** * Copyright : http://www.orientpay.com , 2007-2012 * Project : oecs-g2-common-framework-trunk * $Id$ * $Revision$ * Last Changed by ZhouXushun at 2011-8-26 下午02:33:47 * $URL$ * * Change Log * Author Change Date Comments *------------------------------------------------------------- * ZhouXushun 2011-8-26 Initailized */ package com.jzzms.framework.orm.query; import java.io.Serializable; /** * 分页行数设定对象 * */ public class RowBounds implements Serializable { private static final long serialVersionUID = 154393093419524432L; // 默认分页长度 public final static int NO_ROW_OFFSET = 0; // 默认最到行数 public final static int NO_ROW_LIMIT = Integer.MAX_VALUE; // 默认对象 public final static RowBounds DEFAULT = new RowBounds(); private int offset; private int limit; private String countSQL; // 是否统计总数 private boolean isCountRowNum = false; public RowBounds() { this.offset = NO_ROW_OFFSET; this.limit = NO_ROW_LIMIT; this.isCountRowNum = false; } public RowBounds(int offset, int limit) { this.offset = offset; this.limit = limit; this.isCountRowNum = true; } public RowBounds(int offset, int limit, boolean isCountRowNum) { this.offset = offset; this.limit = limit; this.isCountRowNum = isCountRowNum; } public int getOffset() { return offset; } public int getLimit() { return limit; } public void setDefault() { this.limit = DEFAULT.limit; this.offset = DEFAULT.offset; } public boolean isCountRowNum() { return isCountRowNum; } public void setCountRowNum(boolean isCountRowNum) { this.isCountRowNum = isCountRowNum; } public String getCountSQL() { return countSQL; } }
zz-ms
trunk/zz-ms-v1.0/sourcecode/framework/src/com/jzzms/framework/orm/query/RowBounds.java
Java
asf20
2,052
/** * Copyright : http://www.orientpay.com , 2007-2012 * Project : oecs-g2-common-framework-trunk * $Id$ * $Revision$ * Last Changed by ZhouXushun at 2011-9-16 下午03:29:53 * $URL$ * * Change Log * Author Change Date Comments *------------------------------------------------------------- * ZhouXushun 2011-9-16 Initailized */ package com.jzzms.framework.orm.query; /** * 属性比较类型. 目前IN 只支持字符串的类型 * */ public enum MatchType { NEQ, EQ, LIKE, LT, GT, LE,GE, NULL, NOTNULL, IN ,LLIKE, RLIKE; public String express(){ if("LIKE".equals(this.name()) || "LLIKE".equals(this.name()) || "RLIKE".equals(this.name()) ){ return "LIKE"; } if("LT".equals(this.name())){ return "<"; } if("GT".equals(this.name())){ return ">"; } if("LE".equals(this.name())){ return "<="; } if("GE".equals(this.name())){ return ">="; } if("NULL".equals(this.name())){ return "is null"; } if("NOTNULL".equals(this.name())){ return "is not null"; } if("IN".equals(this.name())){ return "in"; } if("NEQ".equals(this.name())){ return "<>"; } return "="; } public String expressStart(){ if("LIKE".equals(this.name()) || "LLIKE".equals(this.name())){ return "%"; } if("IN".equals(this.name())){ return "("; } return ""; } public String expressEnd(){ if("LIKE".equals(this.name()) || "RLIKE".equals(this.name()) ){ return "%"; } if("IN".equals(this.name())){ return ")"; } return ""; } public boolean outputValue(){ if("NULL".equals(this.name()) || "NOTNULL".equals(this.name())){ return false; } return true; } }
zz-ms
trunk/zz-ms-v1.0/sourcecode/framework/src/com/jzzms/framework/orm/query/MatchType.java
Java
asf20
2,110
/** * Copyright : http://www.orientpay.com , 2007-2012 * Project : oecs-g2-framework-trunk * $Id$ * $Revision$ * Last Changed by jason at 2011-9-16 上午11:56:00 * $URL$ * * Change Log * Author Change Date Comments *------------------------------------------------------------- * jason 2011-9-16 Initailized */ package com.jzzms.framework.orm.query; import org.apache.commons.lang.StringUtils; import com.jzzms.framework.util.common.PropertyFilterUtils; import com.jzzms.framework.util.lang.AssertUtils; import com.jzzms.framework.util.lang.ReflectionUtils; /** * 与具体ORM实现无关的属性过滤条件封装类. * * PropertyFilter主要记录页面中简单的搜索过滤条件,比Hibernate的Criterion要简单. * * */ public class PropertyFilter { /** 多个属性间OR关系的分隔符. */ public static final String OR_SEPARATOR = "_OR_"; private String[] propertyNames = null; private Class<?> propertyType = null; private Object propertyValue = null; private MatchType matchType = null; private String propertyTypeCode = null; public PropertyFilter() { } public PropertyFilter(MatchType matchType, PropertyType propertyType,String fieldName, String value){ this((matchType.name() + propertyType.name() + "_" + fieldName), value); } /** * @param filterName 比较属性字符串,含待比较的比较类型、属性值类型及属性列表. * eg. LIKES_NAME_OR_LOGIN_NAME * @param value 待比较的值. */ public PropertyFilter(final String filterName, final String value) { String matchTypeStr = StringUtils.substringBefore(filterName, "_"); String matchTypeCode = StringUtils.substring(matchTypeStr, 0, matchTypeStr.length() - 1); this.propertyTypeCode = StringUtils.substring(matchTypeStr, matchTypeStr.length() - 1, matchTypeStr.length()); try { matchType = Enum.valueOf(MatchType.class, matchTypeCode); } catch (RuntimeException e) { throw new IllegalArgumentException("filter type of " + filterName + " is illegal", e); } try { propertyType = Enum.valueOf(PropertyType.class, propertyTypeCode).getValue(); } catch (RuntimeException e) { throw new IllegalArgumentException("filter property type of " + filterName + " is illegal", e); } String propertyNameStr = StringUtils.substringAfter(filterName, "_"); propertyNames = StringUtils.splitByWholeSeparator(propertyNameStr, PropertyFilter.OR_SEPARATOR); AssertUtils.isTrue(propertyNames.length > 0, "filter name of " + filterName + "is illegal"); //按entity property中的类型将字符串转化为实际类型. this.propertyValue = ReflectionUtils.convertStringToObject(value, propertyType); } /** * 是否比较多个属性. */ public boolean isMultiProperty() { return (propertyNames.length > 1); } /** * 获取比较值的类型. */ public PropertyType getPropertyType(){ return PropertyType.valueOf(propertyTypeCode); } /** * 获取比较属性名称列表. */ public String[] getPropertyNames() { return propertyNames; } /** * 获取唯一的比较属性名称. */ public String getPropertyName() { if (propertyNames.length > 1) { throw new IllegalArgumentException("There are not only one property"); } return propertyNames[0]; } /** * 获取比较值. */ public Object getPropertyValue() { return propertyValue; } /** * 获取比较方式类型. */ public MatchType getMatchType() { return matchType; } /** * 获取Filter的Sql语句 * @return */ public String getSqlString(){ String sql = PropertyFilterUtils.propertyFilter2SqlString(this); return sql; } }
zz-ms
trunk/zz-ms-v1.0/sourcecode/framework/src/com/jzzms/framework/orm/query/PropertyFilter.java
Java
asf20
4,207
/** * Copyright : http://www.orientpay.com , 2007-2012 * Project : oecs-g2-framework-trunk * $Id$ * $Revision$ * Last Changed by jason at 2011-9-17 下午5:15:39 * $URL$ * * Change Log * Author Change Date Comments *------------------------------------------------------------- * jason 2011-9-17 Initailized */ package com.jzzms.framework.orm.query; import org.apache.commons.lang.StringUtils; /** * SQL 排序对象 * */ public class Order { //排序字段 private String orderBy; //排序方式 private String order; public Order(){ } public Order(String orderBy, String order){ this.orderBy = orderBy; setOrder(order); } public String getOrderBy() { return orderBy; } public void setOrderBy(String orderBy) { this.orderBy = orderBy; } public String getOrder() { return order; } public void setOrder(String order) { if(StringUtils.isBlank(order)){ this.order = Page.DESC; return; } if(Page.ASC.equalsIgnoreCase(order)){ this.order = Page.ASC; return; } this.order = Page.DESC; } }
zz-ms
trunk/zz-ms-v1.0/sourcecode/framework/src/com/jzzms/framework/orm/query/Order.java
Java
asf20
1,303
/** * Copyright : http://www.orientpay.com , 2007-2012 * Project : oecs-g2-common-framework-trunk * $Id$ * $Revision$ * Last Changed by ZhouXushun at 2011-9-16 下午03:30:43 * $URL$ * * Change Log * Author Change Date Comments *------------------------------------------------------------- * ZhouXushun 2011-9-16 Initailized * Zhouxushun 2011-11-14 add array property type */ package com.jzzms.framework.orm.query; import java.util.Date; import com.jzzms.framework.core.Constants; /** * 属性数据类型. * */ public enum PropertyType { S(String.class), I(Integer.class), L(Long.class), N(Double.class), D(Date.class), B(Boolean.class), A(String.class); private Class<?> clazz; PropertyType(Class<?> clazz) { this.clazz = clazz; } public Class<?> getValue() { return clazz; } public String expressStart(){ if("S".equals(this.name())){ return "'"; } if("D".equals(this.name())){ return "to_date('"; } return ""; } public String expressEnd(){ if("S".equals(this.name())){ return "'"; } if("D".equals(this.name())){ return "','" + Constants.ORACLE_LONG_TIME_FORMAT + "')"; } return ""; } }
zz-ms
trunk/zz-ms-v1.0/sourcecode/framework/src/com/jzzms/framework/orm/query/PropertyType.java
Java
asf20
1,410
/** * Copyright : http://www.orientpay.com , 2007-2012 * Project : oecs-g2-common-framework-trunk * $Id$ * $Revision$ * Last Changed by ZhouXushun at 2011-9-16 下午04:31:57 * $URL$ * * Change Log * Author Change Date Comments *------------------------------------------------------------- * ZhouXushun 2011-9-16 Initailized */ package com.jzzms.framework.orm.query; import java.io.Serializable; import java.util.Collections; import java.util.List; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.jzzms.framework.core.Constants; /** * 东方亿付查询查询共用类 * */ public class ZzMsCriterion implements Serializable { private static final long serialVersionUID = -7164611833406678484L; protected Log log = LogFactory.getLog(getClass()); public static final String ACS = "ACS"; public static final String DESC = "DESC"; private String order = DESC; private String orderBy; @SuppressWarnings("unchecked") private List<PropertyFilter> criteria = Collections.EMPTY_LIST; //嵌套的扩展查询条件 @SuppressWarnings("unchecked") private List<PropertyFilter> extraCriteria = Collections.EMPTY_LIST; public ZzMsCriterion(){ } public ZzMsCriterion(List<PropertyFilter> criteria){ this.criteria = criteria; } public ZzMsCriterion(List<PropertyFilter> criteria, String orderBy){ this.criteria = criteria; this.orderBy = orderBy; } public ZzMsCriterion(List<PropertyFilter> criteria, String orderBy, String order){ this.criteria = criteria; this.orderBy = orderBy; this.order = order; } /** * Property accessor of order * * @return the order */ public String getOrder() { return order; } /** * @param order * the order to set */ public void setOrder(String order) { this.order = order; } /** * Property accessor of orderBy * * @return the orderBy */ public String getOrderBy() { return orderBy; } /** * @param orderBy * the orderBy to set */ public void setOrderBy(String orderBy) { this.orderBy = orderBy; } /** * Property accessor of criteria * * @return the criteria */ public List<PropertyFilter> getCriteria() { return criteria; } /** * @param criteria * the criteria to set */ public void setCriteria(List<PropertyFilter> criteria) { this.criteria = criteria; } public String getWhereSqlString(){ return constructSqlString(criteria); } public String getExtraWhereSqlString(){ return constructSqlString(extraCriteria); } public String getOrderBySqlString(){ if(StringUtils.isNotBlank(orderBy)){ //拼装order条件 StringBuilder sb = new StringBuilder(" ORDER BY "); String[] orderBys = StringUtils.split(orderBy, ','); if(StringUtils.isBlank(order)){ order = DESC; } String [] orders = StringUtils.split(order, ','); int i = 0; for (String orderBy : orderBys) { if(i != 0){ sb.append(" " + Constants.COMMA_SIGN_SPLIT_NAME + " "); } sb.append(orderBy); String curOrder = DESC; if(orders.length == 1){ curOrder = orders[0]; } else{ if((i + 1) > orders.length){ curOrder = DESC; } else{ curOrder = orders[i]; } } sb.append(" " + curOrder); i++; } log.debug("getOrderBySqlString :" + sb.toString()); return sb.toString(); } return ""; } public List<PropertyFilter> getExtraCriteria() { return extraCriteria; } public void setExtraCriteria(List<PropertyFilter> extraCriteria) { this.extraCriteria = extraCriteria; } protected String constructSqlString(List<PropertyFilter> in){ //查询参数 if(in != null && in.size() > 0){ StringBuilder sb = new StringBuilder(); for(PropertyFilter filter : in){ sb.append("and" + filter.getSqlString()); } log.debug("getWhereSqlString :" + sb.toString()); return sb.toString(); } return ""; } }
zz-ms
trunk/zz-ms-v1.0/sourcecode/framework/src/com/jzzms/framework/orm/query/ZzMsCriterion.java
Java
asf20
5,101
/** * Copyright : http://www.orientpay.com , 2007-2012 * Project : oecs-g2-framework-trunk * $Id$ * $Revision$ * Last Changed by jason at 2011-9-17 下午3:41:36 * $URL$ * * Change Log * Author Change Date Comments *------------------------------------------------------------- * jason 2011-9-17 Initailized * zhouxushun 2012-5-3 考虑电视分页的特殊性,MIN_PAGESIZE 大小由原来的5改成4 * */ package com.jzzms.framework.orm.query; import java.io.Serializable; import java.util.Collections; import java.util.List; import org.apache.commons.lang.StringUtils; /** * 与具体ORM实现无关的分页参数及查询结果封装. * 注意所有序号从1开始. * * @param <T> Page中记录的类型. */ public class Page<T> implements Serializable{ private static final long serialVersionUID = -8126702682606137927L; public static final int MIN_PAGESIZE = 4; public static final int DEFAULT_PAGESIZE = 20; public static final int MAX_PAGESIZE = 200; public static final int DEFAULT_PAGENUMSHOWN = 10; // 公共变量 public static final String ASC = "asc"; public static final String DESC = "desc"; //分页参数 protected int pageNum = 1; protected int numPerPage = DEFAULT_PAGESIZE; protected String orderField = null; protected String orderDirection = ASC; protected boolean autoCount = true; protected boolean autoPage = true; protected int pageNumShown = DEFAULT_PAGENUMSHOWN; //返回结果 protected List<T> result = null; protected long totalCount = -1; //扩展记录 protected Object extraObj = null; // 构造函数 public Page() { super(); } public Page(final int pageSize) { setNumPerPage(pageSize); } public Page(final int pageSize, final boolean autoCount) { setNumPerPage(pageSize); this.autoCount = autoCount; } /** * 获得当前页的页号,序号从1开始,默认为1. */ public int getPageNum() { return pageNum; } /** * 设置当前页的页号,序号从1开始,低于1时自动调整为1. */ public void setPageNum(int pageNum) { this.pageNum = pageNum; if (pageNum < 1) { this.pageNum = 1; } } /** * 获得每页的记录数量,默认为20. */ public int getNumPerPage() { return numPerPage; } /** * 设置每页的记录数量,超出MIN_PAGESIZE与MAX_PAGESIZE范围时会自动调整. */ public void setNumPerPage(final int numPerPage) { this.numPerPage = numPerPage; if (numPerPage < MIN_PAGESIZE) { this.numPerPage = MIN_PAGESIZE; } if (numPerPage > MAX_PAGESIZE) { this.numPerPage = MAX_PAGESIZE; } } /** * 根据pageNo和pageSize计算当前页第一条记录在总结果集中的位置,序号从0开始. */ public int getFirst() { return ((pageNum - 1) * numPerPage); } /** * 获得排序字段,无默认值.多个排序字段时用','分隔,仅在Criterion查询时有效. */ public String getOrderField() { return orderField; } /** * 设置排序字段.多个排序字段时用','分隔.仅在Criterion查询时有效. */ public void setOrderField(final String orderField) { this.orderField = orderField; } /** * 是否已设置排序字段,仅在Criterion查询时有效. */ public boolean isOrderBySetted() { return StringUtils.isNotBlank(orderField); } /** * 获得排序方向,默认为asc,仅在Criterion查询时有效. * * @param order 可选值为desc或asc,多个排序字段时用','分隔. */ public String getOrderDirection() { return orderDirection; } /** * 设置排序方式向,仅在Criterion查询时有效. * * @param order 可选值为desc或asc,多个排序字段时用','分隔. */ public void setOrderDirection(final String orderDirection) { //检查order字符串的合法值 String[] orders = StringUtils.split(orderDirection, ','); for (String orderStr : orders) { if (!StringUtils.equalsIgnoreCase(DESC, orderStr) && !StringUtils.equalsIgnoreCase(ASC, orderStr)) throw new IllegalArgumentException("排序方向" + orderStr + "不是合法值"); } this.orderDirection = orderDirection.toLowerCase(); } /** * 取得分页参数的组合字符串. * 将多个分页参数组合成一个字符串方便在页面上的传递,格式为pageNo|orderBy|order. */ public String getPageRequest() { return getPageNum() + "|" + StringUtils.defaultString(getOrderField()) + "|" + getOrderDirection(); } /** * 设置分页参数的组合字符串. * 将多个分页参数组合成一个字符串方便在页面上的传递,格式为pageNo|orderBy|order. */ public void setPageRequest(final String pageRequest) { if (StringUtils.isBlank(pageRequest)) return; String[] params = StringUtils.splitPreserveAllTokens(pageRequest, '|'); if (StringUtils.isNumeric(params[0])) { setPageNum(Integer.valueOf(params[0])); } if (StringUtils.isNotBlank(params[1])) { setOrderField(params[1]); } if (StringUtils.isNotBlank(params[2])) { setOrderDirection(params[2]); } } /** * 查询对象时是否自动另外执行count查询获取总记录数,默认为false,仅在Criterion查询时有效. */ public boolean isAutoCount() { return autoCount; } /** * 查询对象时是否自动另外执行count查询获取总记录数,仅在Criterion查询时有效. */ public void setAutoCount(final boolean autoCount) { this.autoCount = autoCount; } // 查询结果函数 /** * 取得页内的记录列表. */ public List<T> getResult() { if (result == null) return Collections.emptyList(); return result; } public void setResult(final List<T> result) { this.result = result; } /** * 取得总记录数,默认值为-1. */ public long getTotalCount() { return totalCount; } public void setTotalCount(final long totalCount) { this.totalCount = totalCount; } /** * 根据pageSize与totalCount计算总页数,默认值为-1. */ public long getTotalPages() { if (totalCount < 0) return -1; long count = totalCount / numPerPage; if (totalCount % numPerPage > 0) { count++; } return count; } /** * 是否还有下一页. */ public boolean isHasNext() { return (pageNum + 1 <= getTotalPages()); } /** * 取得下页的页号,序号从1开始. */ public int getNextPage() { if (isHasNext()) return pageNum + 1; else return pageNum; } /** * 是否还有上一页. */ public boolean isHasPre() { return (pageNum - 1 >= 1); } /** * 取得上页的页号,序号从1开始. */ public int getPrePage() { if (isHasPre()) return pageNum - 1; else return pageNum; } /** * 取得反转的排序方向. * 如果有以','分隔的多个排序方向,逐一进行反转. */ public String getInverseOrder() { String[] orders = StringUtils.split(orderDirection, ','); for (int i = 0; i < orders.length; i++) { if (DESC.equals(orders[i])) { orders[i] = ASC; } else { orders[i] = DESC; } } return StringUtils.join(orders); } public boolean isAutoPage() { return autoPage; } public void setAutoPage(boolean autoPage) { this.autoPage = autoPage; } public Object getExtraObj() { return extraObj; } public void setExtraObj(Object extraObj) { this.extraObj = extraObj; } public int getPageNumShown() { return pageNumShown; } public void setPageNumShown(int pageNumShown) { this.pageNumShown = pageNumShown; } }
zz-ms
trunk/zz-ms-v1.0/sourcecode/framework/src/com/jzzms/framework/orm/query/Page.java
Java
asf20
8,876
/** * Copyright : http://www.orientpay.com , 2007-2012 * Project : oecs-g2-common-framework-trunk * $Id$ * $Revision$ * Last Changed by ZhouXushun at 2011-8-26 下午02:43:08 * $URL$ * * Change Log * Author Change Date Comments *------------------------------------------------------------- * ZhouXushun 2011-8-26 Initailized */ package com.jzzms.framework.orm.mybatis; import org.mybatis.spring.SqlSessionFactoryBean; import com.jzzms.framework.orm.dialect.Dialect; import com.jzzms.framework.orm.dialect.OracleDialect; /** * OECS的SqlSessionFactoryBean * * 添加了分页查询和行数总计 */ public class ZzMsSqlSessionFactoryBean extends SqlSessionFactoryBean { // 需要被注入的值 private String dialectClass = "com.jzzms.framework.orm.dialect.MySQLDialect"; private Dialect dialect = new OracleDialect(); /** * @param dialectValue * the dialectValue to set */ public void setDialectClass(String dialectClass) { this.dialectClass = dialectClass; try { dialect = (Dialect) Class.forName(dialectClass).newInstance(); } catch (Exception e) { throw new IllegalArgumentException(dialectClass +" : can not init!"); } } public String getDialectClass(){ return dialectClass; } public Dialect getDialect(){ return dialect; } }
zz-ms
trunk/zz-ms-v1.0/sourcecode/framework/src/com/jzzms/framework/orm/mybatis/ZzMsSqlSessionFactoryBean.java
Java
asf20
1,511
/** * Copyright : http://www.orientpay.com , 2007-2012 * Project : oecs-g2-common-framework-trunk * $Id$ * $Revision$ * Last Changed by ZhouXushun at 2011-8-26 下午03:13:16 * $URL$ * * Change Log * Author Change Date Comments *------------------------------------------------------------- * ZhouXushun 2011-8-26 Initailized */ package com.jzzms.framework.orm.mybatis; import java.util.Properties; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.ibatis.executor.Executor; import org.apache.ibatis.mapping.BoundSql; import org.apache.ibatis.mapping.MappedStatement; import org.apache.ibatis.mapping.MappedStatement.Builder; import org.apache.ibatis.mapping.SqlSource; import org.apache.ibatis.plugin.Interceptor; import org.apache.ibatis.plugin.Intercepts; import org.apache.ibatis.plugin.Invocation; import org.apache.ibatis.plugin.Plugin; import org.apache.ibatis.plugin.Signature; import org.apache.ibatis.session.ResultHandler; import org.apache.ibatis.session.RowBounds; import com.jzzms.framework.orm.dialect.Dialect; /** * mybatis分页拦截器 * */ @Intercepts({@Signature(type=Executor.class,method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class})}) public class PaginationInterceptor implements Interceptor{ public static final Log log = LogFactory.getLog(PaginationInterceptor.class); private final static int MAPPED_STATEMENT_INDEX = 0; private final static int PARAMETER_INDEX = 1; private final static int ROWBOUNDS_INDEX = 2; private final static int MAX_VALUE_CONDITION = RowBounds.NO_ROW_LIMIT; private Dialect dialect; public Object intercept(Invocation invocation) throws Throwable { final Object[] queryArgs = invocation.getArgs(); if(queryArgs[ROWBOUNDS_INDEX] != null){ final RowBounds rowBounds = (RowBounds)queryArgs[ROWBOUNDS_INDEX]; if(rowBounds.getLimit() < MAX_VALUE_CONDITION){ processIntercept(invocation.getArgs()); } } queryArgs[ROWBOUNDS_INDEX] = org.apache.ibatis.session.RowBounds.DEFAULT; return invocation.proceed(); } private void processIntercept(final Object[] queryArgs) { MappedStatement ms = (MappedStatement)queryArgs[MAPPED_STATEMENT_INDEX]; Object parameter = queryArgs[PARAMETER_INDEX]; final RowBounds rowBounds = (RowBounds)queryArgs[ROWBOUNDS_INDEX]; if (rowBounds != null) { int offset = rowBounds.getOffset(); int limit = rowBounds.getLimit(); if (dialect.supportsLimit() && (offset != RowBounds.NO_ROW_OFFSET || limit != RowBounds.NO_ROW_LIMIT)) { log.debug("Pagination query prepare ..."); BoundSql boundSql = ms.getBoundSql(parameter); String sql = boundSql.getSql().trim(); if (dialect.supportsLimitOffset()) { sql = dialect.getLimitString(sql, offset, limit); offset = RowBounds.NO_ROW_OFFSET; } else { sql = dialect.getLimitString(sql, 0, limit); } BoundSql newBoundSql = new BoundSql(ms.getConfiguration(),sql, boundSql.getParameterMappings(), boundSql.getParameterObject()); log.debug("Mybatis Page Search:"+ sql.replaceAll("\n", "")); MappedStatement newMs = copyFromMappedStatement(ms, new BoundSqlSqlSource(newBoundSql)); queryArgs[MAPPED_STATEMENT_INDEX] = newMs; } } queryArgs[ROWBOUNDS_INDEX]= RowBounds.DEFAULT; } private MappedStatement copyFromMappedStatement(MappedStatement ms,SqlSource newSqlSource) { Builder builder = new MappedStatement.Builder(ms.getConfiguration(),ms.getId(),newSqlSource,ms.getSqlCommandType()); builder.resource(ms.getResource()); builder.fetchSize(ms.getFetchSize()); builder.statementType(ms.getStatementType()); builder.keyGenerator(ms.getKeyGenerator()); if(ms.getKeyProperties() != null && ms.getKeyProperties().length > 0){ builder.keyProperty(ms.getKeyProperties()[0]); } builder.timeout(ms.getTimeout()); builder.parameterMap(ms.getParameterMap()); builder.resultMaps(ms.getResultMaps()); builder.resultSetType(ms.getResultSetType()); builder.cache(ms.getCache()); builder.flushCacheRequired(ms.isFlushCacheRequired()); builder.statementType(ms.getStatementType()); MappedStatement newMs = builder.build(); return newMs; } public Object plugin(Object target) { return Plugin.wrap(target, this); } public static class BoundSqlSqlSource implements SqlSource { BoundSql boundSql; public BoundSqlSqlSource(BoundSql boundSql) { this.boundSql = boundSql; } public BoundSql getBoundSql(Object parameterObject) { return boundSql; } } public void setProperties(Properties props) { String dialectClass = props.getProperty("dialect"); try { dialect = (Dialect) Class.forName(dialectClass).newInstance(); } catch (Exception e) { throw new IllegalArgumentException(dialectClass +" : can not init!"); } } }
zz-ms
trunk/zz-ms-v1.0/sourcecode/framework/src/com/jzzms/framework/orm/mybatis/PaginationInterceptor.java
Java
asf20
5,768
/** * Copyright : http://www.orientpay.com , 2007-2012 * Project : oecs-g2-common-framework-trunk * $Id$ * $Revision$ * Last Changed by ZhouXushun at 2011-9-5 下午01:55:46 * $URL$ * * Change Log * Author Change Date Comments *------------------------------------------------------------- * ZhouXushun 2011-9-5 Initailized */ package com.jzzms.framework.core; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.Properties; import javax.sql.DataSource; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.factory.FactoryBean; import org.springframework.beans.factory.InitializingBean; /** * 从数据库里读取配置 * 实现参考http://forum.springsource.org/showthread.php?t=57246 * */ public class DatabaseProperties extends Properties implements InitializingBean, FactoryBean<Properties> { private static final long serialVersionUID = -4936201138182312441L; private static final Log log = LogFactory.getLog(DatabaseProperties.class); private DataSource datasource; //数据源 private String query; //读取的sql public DatabaseProperties(DataSource datasource, String query) { this.datasource = datasource; this.query = query; } public void afterPropertiesSet() throws Exception { initProperties(); } public Properties getObject() throws Exception { return this; } public Class<?> getObjectType() { return Properties.class; } public boolean isSingleton() { return true; } //初始化 private void initProperties() { Connection connection = null; try { connection = datasource.getConnection(); PreparedStatement ps = connection.prepareStatement(query); ResultSet rs = ps.executeQuery(); while (rs.next()) { String key = rs.getString(1); String value = rs.getString(2); if (key != null && value != null) { log.info("load property. Key=" + key + ",Value=" + value); this.setProperty(key, value); } } rs.close(); ps.close(); } catch (Exception e) { log.error(e); } finally { if (connection != null) { try { connection.close(); } catch (Exception e) { log.error(e); } } } } }
zz-ms
trunk/zz-ms-v1.0/sourcecode/framework/src/com/jzzms/framework/core/DatabaseProperties.java
Java
asf20
2,840
/** * Copyright : http://www.orientpay.com , 2007-2012 * Project : oecs-g2-common-framework-trunk * $Id$ * $Revision$ * Last Changed by ZhouXushun at 2011-8-4 下午03:52:49 * $URL$ * * Change Log * Author Change Date Comments *------------------------------------------------------------- * ZhouXushun 2011-8-4 Initailized */ package com.jzzms.framework.core; /** * 常量定义 * */ public interface Constants { //?符号 public static final String QUESTION_SIGN_SPLIT_NAME = "?"; //@符号 public static final String AT_SIGN_SPLIT_NAME = "@"; //common public static final String COMMA_SIGN_SPLIT_NAME = ","; //- public static final String LINE_SIGN_SPLIT_NAME = "-"; //下划线 public static final String UNDERLINE_SIGN_SPLIT_NAME = "_"; //DOT public static final String DOT_SIGN_SPLIT_NAME = "."; //semicolon public static final String SEMICOLON_SIGN_SPLIT_NAME = ";"; //COLON public static final String COLON_SIGN_SPLIT_NAME = ":"; public static final long GLOBAL_SYSTEM_OPER_ID = -1; public static final int GLOBAL_DATA_MAX_LENGTH = 1000; //默认编码 public static final String DEFAULT_CHARSET_NAME = "UTF-8"; //默认报文接口编码 public static final String DEFAULT_PROTOCOL_CHARSET_NAME = "GBK"; //报文接口类型--WEBSERVICE public static final String MSG_INTERFACE_TYPE_WEBSERVICE = "WEBSERVICE"; //报文接口类型--socket public static final String MSG_INTERFACE_TYPE_SOCKET = "SOCKET"; //报文接口类型--hessian public static final String MSG_INTERFACE_TYPE_HESSIAN = "HESSIAN"; //默认的时间格式 public static final String DEFUALT_SHOT_TIME_FORMAT = "yyyy-MM-dd"; public static final String DEFUALT_LONG_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss"; public static final String ORACLE_LONG_TIME_FORMAT = "yyyy-MM-dd hh24:mi:ss"; public static final String NO_SPLIT_SHOT_TIME_FORMAT = "yyyyMMdd"; public static final String STAMP_TIME_FORMAT = "yyyyMMddHHmmss"; public static final String MONTH_TIME_FORMAT = "yyyyMM"; public static final String XML_CONF_NAME_EXT = ".xml"; //配置名称 public static final String EXCLUDE_CONFIG_NAME = "exclude"; //系统属性文件名 public static final String SYSTEM_PROPERTY_FILENAME = "system.properties"; //系统代号属性KEY public static final String SYSTEM_PROPERTY_APPCODE_KEY = "sys.app.code"; //cache管理器bean名称 public static final String CACHE_MANAGER_BEAN_NAME = "oecsCacheManageService"; //AccessDecisionManager public static final String ACCESS_DECISION_BEAN_NAME = "accessDecisionService"; //AccessDecisionManager public static final String AUDIT_LOG_BEAN_NAME = "auditLogService"; //AccessDecisionManager public static final String DICT_CACHE_SERVICE_BEAN_NAME = "oecsDictCacheService"; //TerminologyCacheService public static final String TERM_CACHE_SERVICE_BEAN_NAME = "terminologyCacheService"; //DictConvertCacheService public static final String DICT_CONVERT_CACHE_SERVICE_BEAN_NAME ="dictConvertCacheService"; //PAGEINFO_IN_REQUEST public static final String PAGEINFO_IN_REQUEST = "pageinfo_in_request"; public static final int DEFAULT_PAGE_SIZE = 20; //全局数据字典 :有效/无效 public final String DICT_GLOBAL_STATUS_VALIDATE = "V"; public final String DICT_GLOBAL_STATUS_INVALIDATE = "I"; //全局数据字典:是/否 public final String DICT_GLOBAL_YESNO_YES = "Y"; public final String DICT_GLOBAL_YESNO_NO = "N"; //全局处理状态P 处理中 public final String DICT_GLOBAL_RESULT_PROCESSING = "P"; public final String DICT_GLOBAL_RESULT_FAIL = "F"; public final String DICT_GLOBAL_RESULT_SUCCESS = "S"; public final String DICT_GLOBAL_RESULT_UNPROCESS = "U"; //随机数 public static final String SPRING_SECURITY_RANDS_IN_SESSION = "KAPTCHA_SESSION_KEY"; //"j_spring_rands_in_session"; public static final String SPRING_SECURITY_FORM_VCODE_KEY = "j_validatecode"; public static final String SPRING_SECURITY_CHECK_NAME = "j_spring_security_check"; //token public static final String OECS_TOKEN_CHECK_NAME_IN_SESSION = "oecs_token_check_in_session"; public static final String OECS_TOKEN_CHECK_NAME = "o_token_check"; public static final String OECS_TOKEN_ERR_BACK_URL_NAME = "o_token_err_url"; //首页是否已经做过初始化 public static final String ACTION_INDEX_INIT_IN_SESSION = "index_init_in_session"; //当前登录用户 public static final String CUR_USER_DETAIL_IN_SESSION = "cur_user_detail_in_session"; //当前登录用户该系统下的菜单树信息 public static final String CUR_USER_ALL_MENU_IN_SESSION = "cur_user_all_menu_in_session"; //用户快捷菜单 public static final String CUR_USER_SHORTCUT_IN_SESSION = "cur_user_shortcut_in_session"; //当前应用信息信息 public static final String CUR_APP_INFO_IN_REQUEST = "cur_app_info_in_request"; public static final String CUR_USER_APPS_IN_REQUEST = "cur_user_apps_in_request"; //当前系统菜单信息 public static final String CUR_APP_MENUS_IN_REQUEST = "cur_app_menus_in_request"; //当前菜单树 public static final String CUR_MENU_TREE_IN_REQUEST = "cur_menu_tree_in_request"; //用户菜单树FOR RENDER public static final String MENU_TREE_FOR_RENDER_IN_REQUEST = "menu_tree_for_render_in_request"; //是否重新初始化首页参数 public static final String REINIT_INDEX_PARAMETER_NAME = "reInit"; //是否重新初始化首页参数 public static final String FAVORITE_PARAMETER_NAME = "favorite"; //hessian客户端调用者信息in hessian context public static final String HESSIAN_CLIENT_INFO_IN_HESSIAN = "hessian_client_info_in_hessian"; //资源类型 SET_AP_RESOURCE_TYPE public static final String SET_AP_RESOURCE_TYPE_APP = "APP"; public static final String SET_AP_RESOURCE_TYPE_MEU = "MEU"; public static final String SET_AP_RESOURCE_TYPE_MET = "MET"; public static final String SET_AP_RESOURCE_TYPE_BTN = "BTN"; public static final String SET_AP_RESOURCE_TYPE_URL = "URL"; public static final String SET_AP_RESOURCE_TYPE_FRG = "FRG"; //授权目标类型 public static final String SET_AP_PERMISSION_TARGET_TYPE_OPER = "OPER"; public static final String SET_AP_PERMISSION_TARGET_TYPE_ROLE = "ROLE"; //授权资源类型 public static final String SET_AP_PERMISSION_RES_TYPE_RES = "RES"; public static final String SET_AP_PERMISSION_RES_TYPE_REG = "REG"; //服务器状态 正常、准备停止、停止、日切中 public static final String SVR_STATE_NORMAL = "NORM"; public static final String SVR_STATE_STOP = "STOP"; public static final String SVR_STATE_PRE_STOO = "PSTP"; public static final String SVR_STATE_DAUT = "DAUT"; //没有可用的接口池 public static final String SWITCH_NO_ACTIVE_POOL = "switch.no.active.pool"; //默认异常代号信息 public static final String DEFAULT_ERR_MSG = "sys.unkown.err.msg"; //默认四位的异常代码 public static final String DEFAULT_ERR_CODE = "9999"; //默认2位的异常代号 public static final String DEFAULT_THIRD_PART_ERR_CODE = "99"; //默认2位的返回代号 public static final String DEFAULT_RESPONSE_CODE = "00"; //默认的字段描述 public static final String DEFAULT_DB_COLUMN_VALUE = "N/A"; // 刷新cache和数据库配置的key参数 public static final String SYSTEM_REFRESH_PARAM_KEY = "sys.refresh.param.key"; // 后台管理系统缓存刷新列表代号 public static final String SERVERS_CACHE_LIST_CODE = "servers.cache.list"; }
zz-ms
trunk/zz-ms-v1.0/sourcecode/framework/src/com/jzzms/framework/core/Constants.java
Java
asf20
8,974
/** * Copyright : http://www.orientpay.com , 2007-2012 * Project : oecs-g2-common-framework-trunk * $Id$ * $Revision$ * Last Changed by ZhouXushun at 2011-8-4 下午04:53:49 * $URL$ * * Change Log * Author Change Date Comments *------------------------------------------------------------- * ZhouXushun 2011-8-4 Initailized */ package com.jzzms.framework.core; import java.util.HashMap; /** * ThreadLocal上下文 * */ public class ThreadLocalContext { private static final ThreadLocal<ThreadLocalContext> localContext = new ThreadLocal<ThreadLocalContext>(); private int count; private HashMap<String, Object> values = new HashMap<String, Object>(); private ThreadLocalContext() { } /** * Sets the request serviceContext. * * */ public static ThreadLocalContext begin() { ThreadLocalContext context = localContext.get(); if (context == null) { context = new ThreadLocalContext(); localContext.set(context); } context.count++; return context; } /** * Returns the service request. */ public static ThreadLocalContext getContext() { return localContext.get(); } /** * Add a object. */ public void addValue(String key, Object value) { values.put(key, value); } /** * Gets a object. */ public Object getValue(String key) { return values.get(key); } /** * Gets a header from the context. */ public static Object getContextValue(String header) { ThreadLocalContext context = localContext.get(); if (context != null) { return context.getValue(header); } return null; } /** * Cleanup at the end of a request. */ public static void end() { ThreadLocalContext context = localContext.get(); if (context != null && --context.count == 0) { context.values.clear(); } } }
zz-ms
trunk/zz-ms-v1.0/sourcecode/framework/src/com/jzzms/framework/core/ThreadLocalContext.java
Java
asf20
2,192
/** * Copyright : http://www.orientpay.com , 2007-2012 * Project : oecs-g2-common-framework-trunk * $Id$ * $Revision$ * Last Changed by ZhouXushun at 2011-8-4 下午03:54:13 * $URL$ * * Change Log * Author Change Date Comments *------------------------------------------------------------- * ZhouXushun 2011-8-4 Initailized */ package com.jzzms.framework.core; import java.io.Serializable; import java.util.HashMap; import java.util.Map; /** * 所有Model的基类 * */ public abstract class Model implements Serializable{ private static final long serialVersionUID = -7346901881796052757L; //用来保存修改的字段 protected Map<String, Object> entityMap = new HashMap<String, Object>(); public Map<String, Object> getEntityMap() { return entityMap; } public abstract Serializable getPK(); }
zz-ms
trunk/zz-ms-v1.0/sourcecode/framework/src/com/jzzms/framework/core/Model.java
Java
asf20
884
/** * Copyright : http://www.orientpay.com , 2007-2012 * Project : oecs-g2-common-framework-trunk * $Id$ * $Revision$ * Last Changed by ZhouXushun at 2011-8-15 上午11:39:51 * $URL$ * * Change Log * Author Change Date Comments *------------------------------------------------------------- * ZhouXushun 2011-8-15 Initailized */ package com.jzzms.framework.core; import java.io.Serializable; import java.util.Collection; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.userdetails.UserDetails; /** * SpringSecurity UserDetails impl * */ public class UserDetailsImpl implements UserDetails, Serializable { private static final long serialVersionUID = 4779719257045848137L; private Collection<GrantedAuthority> grantedAuthority; // 用户唯一的ID private String userId; // 用户名 private String username; // 用户真实姓名 private String realname; // 登录方式,目前支持口令和动态密码 private String loginType; // 密码 private String password; // 默认的系统appCode private String defautAppCode; // 扩展信息 private Object extraInfo; // 是否已经初始化权限信息 private boolean initAuthInfoFlag; // 用户部门信息 private String userOrgName; public void setAuthorities(Collection<GrantedAuthority> value) { this.grantedAuthority = value; } public void setUsername(String username) { this.username = username; } public void setPassword(String password) { this.password = password; } public Collection<GrantedAuthority> getAuthorities() { return grantedAuthority; } public String getPassword() { return password; } public String getUsername() { return username; } public boolean isAccountNonExpired() { return true; } public boolean isAccountNonLocked() { return true; } public boolean isCredentialsNonExpired() { return true; } public boolean isEnabled() { return true; } public Object getExtraInfo() { return extraInfo; } public void setExtraInfo(Object extraInfo) { this.extraInfo = extraInfo; } public boolean isInitAuthInfoFlag() { return initAuthInfoFlag; } public void setInitAuthInfoFlag(boolean initAuthInfoFlag) { this.initAuthInfoFlag = initAuthInfoFlag; } public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } /** * Property accessor of grantedAuthority * * @return the grantedAuthority */ public Collection<GrantedAuthority> getGrantedAuthority() { return grantedAuthority; } /** * @param grantedAuthority * the grantedAuthority to set */ public void setGrantedAuthority(Collection<GrantedAuthority> grantedAuthority) { this.grantedAuthority = grantedAuthority; } /** * Property accessor of realname * * @return the realname */ public String getRealname() { return realname; } /** * @param realname * the realname to set */ public void setRealname(String realname) { this.realname = realname; } /** * Property accessor of loginType * * @return the loginType */ public String getLoginType() { return loginType; } /** * @param loginType * the loginType to set */ public void setLoginType(String loginType) { this.loginType = loginType; } /** * Property accessor of defautAppCode * * @return the defautAppCode */ public String getDefautAppCode() { return defautAppCode; } /** * @param defautAppCode * the defautAppCode to set */ public void setDefautAppCode(String defautAppCode) { this.defautAppCode = defautAppCode; } public String getUserOrgName() { return userOrgName; } public void setUserOrgName(String userOrgName) { this.userOrgName = userOrgName; } }
zz-ms
trunk/zz-ms-v1.0/sourcecode/framework/src/com/jzzms/framework/core/UserDetailsImpl.java
Java
asf20
4,662
/** * Copyright : http://www.orientpay.com , 2007-2012 * Project : oecs-g2-utility-trunk * $Id$ * $Revision$ * Last Changed by jason at 2011-11-29 下午12:51:26 * $URL$ * * Change Log * Author Change Date Comments *------------------------------------------------------------- * jason 2011-11-29 Initailized */ package com.jzzms.framework.util.lang; import java.math.BigDecimal; import java.text.DecimalFormat; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * 数字处理帮助类 * */ public class NumberUtils { public static void main(String[] args) { float a = 1.1f; float b = 2.2f; System.out.println(NumberUtils.add(a, b)); System.out.println(NumberUtils.sub(a, b)); System.out.println(NumberUtils.mul(a, b)); System.out.println(NumberUtils.div(a, b)); System.out.println(NumberUtils.round(a)); System.out.println(NumberUtils.numberNotPointFormat(b * 10)); } // 加法 public static float add(float v1, float v2) { BigDecimal b1 = new BigDecimal(Float.toString(v1)); BigDecimal b2 = new BigDecimal(Float.toString(v2)); return b1.add(b2).floatValue(); } // 减法 public static float sub(float v1, float v2) { BigDecimal b1 = new BigDecimal(Float.toString(v1)); BigDecimal b2 = new BigDecimal(Float.toString(v2)); return b1.subtract(b2).floatValue(); } // 乘法 public static float mul(float v1, float v2) { BigDecimal b1 = new BigDecimal(Float.toString(v1)); BigDecimal b2 = new BigDecimal(Float.toString(v2)); return b1.multiply(b2).floatValue(); } // 除法 public static float div(float v1, float v2) { BigDecimal b1 = new BigDecimal(Float.toString(v1)); BigDecimal b2 = new BigDecimal(Float.toString(v2)); return b1.divide(b2, 3, BigDecimal.ROUND_HALF_UP).floatValue(); } // 截取3位 public static float round(float v) { BigDecimal b = new BigDecimal(Float.toString(v)); BigDecimal one = new BigDecimal("1"); return b.divide(one, 3, BigDecimal.ROUND_HALF_UP).floatValue(); } public static String numberFormat(String pattern, double value) { return new DecimalFormat(pattern).format(value); } public static String numberPointFormat(double value) { return new DecimalFormat("0.00").format(value); } public static String numberNotPointFormat(double value) { return new DecimalFormat("0").format(value); } public static String numberNotPointFormat(BigDecimal bd){ return numberNotPointFormat(bd, 100); } public static String numberNotPointFormat(BigDecimal bd, int scale){ double d = bd.doubleValue() * scale; return numberNotPointFormat(d); } public static BigDecimal StringNotPointFormat(String bd, float scale){ return BigDecimal.valueOf(mul(Long.parseLong(bd), scale)); } public static long StringToLong(String str){ if(isNumber(str)){ return Long.parseLong(str); } return -1; } public static int StringToInteger(String str){ if(isNumber(str)){ return Integer.parseInt(str); } return -1; } // 检查是否是数字 public static boolean isNumber(String value) { String patternStr = "^\\d+$"; Pattern p = Pattern.compile(patternStr, Pattern.CASE_INSENSITIVE); // 忽略大小写; Matcher m = p.matcher(value); return m.find(); } }
zz-ms
trunk/zz-ms-v1.0/sourcecode/framework/src/com/jzzms/framework/util/lang/NumberUtils.java
Java
asf20
3,759
/** * Copyright : http://www.orientpay.com , 2007-2012 * Project : oecs-g2-common-utility-trunk * $Id$ * $Revision$ * Last Changed by ZhouXushun at 2011-8-8 上午11:41:33 * $URL$ * * Change Log * Author Change Date Comments *------------------------------------------------------------- * ZhouXushun 2011-8-8 Initailized */ package com.jzzms.framework.util.lang; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.net.URL; import java.net.URLConnection; import java.util.Properties; /** * 资源工具类 * */ public class ResourcesUtils { private ResourcesUtils(){ } public static URL getResourceURL(String resource) throws IOException { return getResourceURL(ClassLoaderUtils.getDefaultClassLoader(), resource); } public static URL getResourceURL(ClassLoader loader, String resource) throws IOException { URL url = null; if (loader != null){ url = loader.getResource(resource); } if (url == null){ url = ClassLoader.getSystemResource(resource); } if (url == null){ throw new IOException("Could not find resource " + resource); } return url; } public static InputStream getResourceAsStream(String resource) throws IOException { return getResourceAsStream(ClassLoaderUtils.getDefaultClassLoader(), resource); } public static InputStream getResourceAsStream(ClassLoader loader, String resource) throws IOException { InputStream in = null; if (loader != null){ in = loader.getResourceAsStream(resource); } if (in == null){ in = ClassLoader.getSystemResourceAsStream(resource); } if(in == null){ in = new FileInputStream(new File(resource)); } return in; } public static Properties getResourceAsProperties(String resource) throws IOException { Properties props = new Properties(); InputStream in = null; String propfile = resource; in = getResourceAsStream(propfile); props.load(in); in.close(); return props; } public static Properties getResourceAsProperties(ClassLoader loader, String resource) throws IOException { Properties props = new Properties(); InputStream in = null; String propfile = resource; in = getResourceAsStream(loader, propfile); props.load(in); in.close(); return props; } public static Reader getResourceAsReader(String resource) throws IOException { return new InputStreamReader(getResourceAsStream(resource)); } public static Reader getResourceAsReader(ClassLoader loader, String resource) throws IOException { return new InputStreamReader(getResourceAsStream(loader, resource)); } public static File getResourceAsFile(String resource) throws IOException { return new File(getResourceURL(resource).getFile()); } public static File getResourceAsFile(ClassLoader loader, String resource) throws IOException { return new File(getResourceURL(loader, resource).getFile()); } public static InputStream getUrlAsStream(String urlString) throws IOException { URL url = new URL(urlString); URLConnection conn = url.openConnection(); return conn.getInputStream(); } public static Reader getUrlAsReader(String urlString) throws IOException { return new InputStreamReader(getUrlAsStream(urlString)); } public static Properties getUrlAsProperties(String urlString) throws IOException { Properties props = new Properties(); InputStream in = null; String propfile = urlString; in = getUrlAsStream(propfile); props.load(in); in.close(); return props; } public static Class<?> classForName(String className) throws ClassNotFoundException { Class<?> clazz = null; try { clazz = ClassLoaderUtils.getDefaultClassLoader().loadClass(className); } catch (Exception e) { } if (clazz == null) { clazz = Class.forName(className); } return clazz; } public static Object instantiate(String className) throws ClassNotFoundException, InstantiationException, IllegalAccessException { return instantiate(classForName(className)); } public static Object instantiate(Class<?> clazz) throws InstantiationException, IllegalAccessException { return clazz.newInstance(); } }
zz-ms
trunk/zz-ms-v1.0/sourcecode/framework/src/com/jzzms/framework/util/lang/ResourcesUtils.java
Java
asf20
5,021
/** * Copyright : http://www.orientpay.com , 2007-2012 * Project : oecs-g2-common-utility-trunk * $Id$ * $Revision$ * Last Changed by ZhouXushun at 2011-8-3 下午05:14:07 * $URL$ * * Change Log * Author Change Date Comments *------------------------------------------------------------- * ZhouXushun 2011-8-3 Initailized */ package com.jzzms.framework.util.lang; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.List; import org.apache.commons.beanutils.ConvertUtils; import org.apache.commons.beanutils.PropertyUtils; import org.apache.commons.beanutils.converters.DateConverter; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * 反射工具类 * */ public class ReflectionUtils { private static Log log = LogFactory.getLog(ReflectionUtils.class); static { DateConverter dc = new DateConverter(); dc.setUseLocaleFormat(true); dc.setPatterns(new String[] { "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyyMMdd" }); ConvertUtils.register(dc, Date.class); } /** * 调用Getter方法. */ public static Object invokeGetterMethod(Object target, String propertyName) { String getterMethodName = "get" + StringUtils.capitalize(propertyName); return invokeMethod(target, getterMethodName, new Class[] {}, new Object[] {}); } /** * 调用Setter方法.使用value的Class来查找Setter方法. */ public static void invokeSetterMethod(Object target, String propertyName, Object value) { invokeSetterMethod(target, propertyName, value, null); } /** * 调用Setter方法. * * @param propertyType * 用于查找Setter方法,为空时使用value的Class替代. */ public static void invokeSetterMethod(Object target, String propertyName, Object value, Class<?> propertyType) { Class<?> type = propertyType != null ? propertyType : value.getClass(); String setterMethodName = "set" + StringUtils.capitalize(propertyName); invokeMethod(target, setterMethodName, new Class[] { type }, new Object[] { value }); } /** * 直接读取对象属性值, 无视private/protected修饰符, 不经过getter函数. */ public static Object getFieldValue(final Object object, final String fieldName) { Field field = getDeclaredField(object, fieldName); if (field == null) { throw new IllegalArgumentException("Could not find field [" + fieldName + "] on target [" + object + "]"); } makeAccessible(field); Object result = null; try { result = field.get(object); } catch (IllegalAccessException e) { log.error("ERROR", e); } return result; } /** * 直接设置对象属性值, 无视private/protected修饰符, 不经过setter函数. */ public static void setFieldValue(final Object object, final String fieldName, final Object value) { Field field = getDeclaredField(object, fieldName); if (field == null) { throw new IllegalArgumentException("Could not find field [" + fieldName + "] on target [" + object + "]"); } makeAccessible(field); try { field.set(object, value); } catch (IllegalAccessException e) { log.error("ERROR", e);; } } /** * 直接调用对象方法, 无视private/protected修饰符. */ public static Object invokeMethod(final Object object, final String methodName, final Class<?>[] parameterTypes, final Object[] parameters) { Method method = getDeclaredMethod(object, methodName, parameterTypes); if (method == null) { throw new IllegalArgumentException("Could not find method [" + methodName + "] on target [" + object + "]"); } method.setAccessible(true); try { return method.invoke(object, parameters); } catch (Exception e) { throw convertReflectionExceptionToUnchecked(e); } } /** * 循环向上转型, 获取对象的DeclaredField. * * 如向上转型到Object仍无法找到, 返回null. */ public static Field getDeclaredField(final Object object, final String fieldName) { if (object == null) { log.debug("object is null"); return null; } if (StringUtils.isBlank(fieldName)) { log.debug("fieldName is null"); return null; } for (Class<?> superClass = object.getClass(); superClass != Object.class; superClass = superClass.getSuperclass()) { try { return superClass.getDeclaredField(fieldName); } catch (NoSuchFieldException e) { // NOSONAR ,Field不在当前类定义,继续向上转型 } } return null; } /** * 强行设置Field可访问. */ protected static void makeAccessible(final Field field) { if (!Modifier.isPublic(field.getModifiers()) || !Modifier.isPublic(field.getDeclaringClass().getModifiers())) { field.setAccessible(true); } } /** * 循环向上转型, 获取对象的DeclaredMethod. * * 如向上转型到Object仍无法找到, 返回null. */ protected static Method getDeclaredMethod(Object object, String methodName, Class<?>[] parameterTypes) { if (object == null) { log.debug("object is null"); return null; } for (Class<?> superClass = object.getClass(); superClass != Object.class; superClass = superClass.getSuperclass()) { try { return superClass.getDeclaredMethod(methodName, parameterTypes); } catch (NoSuchMethodException e) { // NOSONAR, Method不在当前类定义,继续向上转型 } } return null; } /** * 通过反射, 获得Class定义中声明的父类的泛型参数的类型. 如无法找到, 返回Object.class. eg. public UserDao * extends HibernateDao<User> * * @param clazz * The class to introspect * @return the first generic declaration, or Object.class if cannot be * determined */ @SuppressWarnings("unchecked") public static <T> Class<T> getSuperClassGenricType(final Class<?> clazz) { return (Class<T>) getSuperClassGenricType(clazz, 0); } /** * 通过反射, 获得定义Class时声明的父类的泛型参数的类型. 如无法找到, 返回Object.class. * * 如public UserDao extends HibernateDao<User,Long> * * @param clazz * clazz The class to introspect * @param index * the Index of the generic ddeclaration,start from 0. * @return the index generic declaration, or Object.class if cannot be * determined */ public static Class<?> getSuperClassGenricType(final Class<?> clazz, final int index) { Type genType = clazz.getGenericSuperclass(); if (!(genType instanceof ParameterizedType)) { log.warn(clazz.getSimpleName() + "'s superclass not ParameterizedType"); return Object.class; } Type[] params = ((ParameterizedType) genType).getActualTypeArguments(); if (index >= params.length || index < 0) { log.warn("Index: " + index + ", Size of " + clazz.getSimpleName() + "'s Parameterized Type: " + params.length); return Object.class; } if (!(params[index] instanceof Class)) { log.warn(clazz.getSimpleName() + " not set the actual class on superclass generic parameter"); return Object.class; } return (Class<?>) params[index]; } /** * 提取集合中的对象的属性(通过getter函数), 组合成List. * * @param collection * 来源集合. * @param propertyName * 要提取的属性名. */ public static List<?> convertElementPropertyToList(final Collection<?> collection, final String propertyName) { List<Object> list = new ArrayList<Object>(); try { for (Object obj : collection) { list.add(PropertyUtils.getProperty(obj, propertyName)); } } catch (Exception e) { throw convertReflectionExceptionToUnchecked(e); } return list; } /** * 提取集合中的对象的属性(通过getter函数), 组合成由分割符分隔的字符串. * * @param collection * 来源集合. * @param propertyName * 要提取的属性名. * @param separator * 分隔符. */ public static String convertElementPropertyToString(final Collection<?> collection, final String propertyName, final String separator) { List<?> list = convertElementPropertyToList(collection, propertyName); return StringUtils.join(list, separator); } /** * 转换字符串到相应类型. * * @param value * 待转换的字符串 * @param toType * 转换目标类型 */ public static Object convertStringToObject(String value, Class<?> toType) { try { return ConvertUtils.convert(value, toType); } catch (Exception e) { throw convertReflectionExceptionToUnchecked(e); } } /** * 将反射时的checked exception转换为unchecked exception. */ public static RuntimeException convertReflectionExceptionToUnchecked(Exception e) { if (e instanceof IllegalAccessException || e instanceof IllegalArgumentException || e instanceof NoSuchMethodException) { return new IllegalArgumentException("Reflection Exception.", e); } else if (e instanceof InvocationTargetException) { return new RuntimeException("Reflection Exception.", ((InvocationTargetException) e).getTargetException()); } else if (e instanceof RuntimeException) { return (RuntimeException) e; } return new RuntimeException("Unexpected Checked Exception.", e); } }
zz-ms
trunk/zz-ms-v1.0/sourcecode/framework/src/com/jzzms/framework/util/lang/ReflectionUtils.java
Java
asf20
12,559
/** * Copyright : http://www.orientpay.com , 2007-2012 * Project : oecs-g2-common-utility-trunk * $Id$ * $Revision$ * Last Changed by ZhouXushun at 2011-8-5 下午05:48:35 * $URL$ * * Change Log * Author Change Date Comments *------------------------------------------------------------- * ZhouXushun 2011-8-5 Initailized */ package com.jzzms.framework.util.lang; import java.util.Collection; import java.util.Map; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang.StringUtils; /** * 断言类 用于检查参数,抛出运行时异常 * */ public class AssertUtils { private AssertUtils() { } public static void isTrue(boolean expression, String message) { if (!(expression)){ throw new IllegalArgumentException(message); } } public static void isTrue(boolean expression) { isTrue(expression, "[Assertion failed] - this expression must be true"); } public static void isNull(Object object, String message) { if (object != null){ throw new IllegalArgumentException(message); } } public static void isNull(Object object) { isNull(object, "[Assertion failed] - the object argument must be null"); } public static void notNull(Object object, String message) { if (object == null){ throw new IllegalArgumentException(message); } } public static void notNull(Object object) { notNull(object, "[Assertion failed] - this argument is required; it must not be null"); } public static void hasLength(String text, String message) { if (StringUtils.isBlank(text)){ throw new IllegalArgumentException(message); } } public static void hasLength(String text) { hasLength(text, "[Assertion failed] - this String argument must have length; it must not be null or empty"); } public static void hasText(String text, String message) { if (StringUtils.isBlank(text)){ throw new IllegalArgumentException(message); } } public static void hasText(String text) { hasText(text, "[Assertion failed] - this String argument must have text; it must not be null, empty, or blank"); } public static void doesNotContain(String textToSearch, String substring, String message) { if ((StringUtils.isBlank(textToSearch)) || (StringUtils.isBlank(substring)) || (textToSearch.indexOf(substring) == -1)){ return; } throw new IllegalArgumentException(message); } public static void doesNotContain(String textToSearch, String substring) { doesNotContain(textToSearch, substring, "[Assertion failed] - this String argument must not contain the substring [" + substring + "]"); } public static void notEmpty(Object[] array, String message) { if (array == null || array.length == 0){ throw new IllegalArgumentException(message); } } public static void notEmpty(Object[] array) { notEmpty(array, "[Assertion failed] - this array must not be empty: it must contain at least 1 element"); } public static void noNullElements(Object[] array, String message) { if (array != null){ for (int i = 0; i < array.length; ++i){ if (array[i] == null){ throw new IllegalArgumentException(message); } } } } public static void noNullElements(Object[] array) { noNullElements(array, "[Assertion failed] - this array must not contain any null elements"); } public static void notEmpty(Collection<?> collection, String message) { if (CollectionUtils.isEmpty(collection)){ throw new IllegalArgumentException(message); } } public static void notEmpty(Collection<?> collection) { notEmpty(collection, "[Assertion failed] - this collection must not be empty: it must contain at least 1 element"); } public static void notEmpty(Map<?,?> map, String message) { if (map == null || map.size() == 0){ throw new IllegalArgumentException(message); } } public static void notEmpty(Map<?,?> map) { notEmpty(map, "[Assertion failed] - this map must not be empty; it must contain at least one entry"); } public static void isInstanceOf(Class<?> clazz, Object obj) { isInstanceOf(clazz, obj, ""); } public static void isInstanceOf(Class<?> type, Object obj, String message) { notNull(type, "Type to check against must not be null"); if (!(type.isInstance(obj))) throw new IllegalArgumentException(message + "Object of class [" + ((obj != null) ? obj.getClass().getName() : "null") + "] must be an instance of " + type); } public static void isAssignable(Class<?> superType, Class<?> subType) { isAssignable(superType, subType, ""); } public static void isAssignable(Class<?> superType, Class<?> subType, String message) { notNull(superType, "Type to check against must not be null"); if ((subType == null) || (!(superType.isAssignableFrom(subType)))) throw new IllegalArgumentException(message + subType + " is not assignable to " + superType); } public static void state(boolean expression, String message) { if (!(expression)) throw new IllegalStateException(message); } public static void state(boolean expression) { state(expression, "[Assertion failed] - this state invariant must be true"); } }
zz-ms
trunk/zz-ms-v1.0/sourcecode/framework/src/com/jzzms/framework/util/lang/AssertUtils.java
Java
asf20
6,529
/** * Copyright : http://www.orientpay.com , 2007-2012 * Project : oecs-g2-common-utility-trunk * $Id$ * $Revision$ * Last Changed by ZhouXushun at 2011-8-23 上午11:34:12 * $URL$ * * Change Log * Author Change Date Comments *------------------------------------------------------------- * ZhouXushun 2011-8-23 Initailized */ package com.jzzms.framework.util.lang; import java.sql.Timestamp; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.GregorianCalendar; import org.apache.commons.lang.StringUtils; /** * 邮戳帮助类 * */ public class TimestampUtils { private TimestampUtils() { } public static Timestamp getCurrentDate() { return new Timestamp(new java.util.Date().getTime()); } public static Timestamp getCurrentDateWithoutTime() { return clearTimePart(getCurrentDate()); } public static Timestamp getCurrentTimestamp() { return new Timestamp(System.currentTimeMillis()); } public static Timestamp getCertainTimestamp(int year, int month, int date) { java.util.Calendar gc = GregorianCalendar.getInstance(); gc.clear(); gc.set(Calendar.YEAR, year); gc.set(Calendar.MONTH, month - 1); gc.set(Calendar.DATE, date); return new Timestamp(gc.getTime().getTime()); } public static Timestamp getCertainTimestamp(int year, int month, int date, int hour, int minute, int second) { java.util.Calendar gc = GregorianCalendar.getInstance(); gc.set(Calendar.YEAR, year); gc.set(Calendar.MONTH, month - 1); gc.set(Calendar.DATE, date); gc.set(Calendar.HOUR_OF_DAY, hour); gc.set(Calendar.MINUTE, minute); gc.set(Calendar.SECOND, second); gc.set(Calendar.MILLISECOND, 0); return new Timestamp(gc.getTime().getTime()); } /* * return YYYY-MM-DD */ public static String TimestampToDateString(Timestamp tVal) { if (tVal == null) { return ""; } SimpleDateFormat format = new SimpleDateFormat(DateTimeUtils.DEFUALT_SHOT_TIME_FORMAT); return format.format(tVal); } public static String timestampToDateString(Timestamp tVal, String formatStr) { if (tVal == null) { return ""; } if (StringUtils.isBlank(formatStr)) { return TimestampToDateString(tVal); } SimpleDateFormat format = new SimpleDateFormat(formatStr); return format.format(tVal); } /* * when tVal = 2004-11-26 16:10:51.743 invoke ClearTimePart(t); return * 2004-11-26 */ public static Timestamp clearTimePart(Timestamp tVal) { java.util.Calendar gc = GregorianCalendar.getInstance(); gc.clear(); gc.setTime(tVal); gc.set(Calendar.HOUR_OF_DAY, 0); gc.set(Calendar.MINUTE, 0); gc.set(Calendar.SECOND, 0); gc.set(Calendar.MILLISECOND, 0); return new Timestamp(gc.getTime().getTime()); } /* * when tVal = 2004-11-26 16:10:51.743 invoke TimestampMove(t, 0, -3, -2); * return 2004-08-24 16:10:51.743 */ public static Timestamp timestampMove(Timestamp tVal, int year, int month, int day) { java.util.Calendar gc = GregorianCalendar.getInstance(); gc.clear(); gc.setTime(tVal); if (year != 0) gc.set(Calendar.YEAR, gc.get(Calendar.YEAR) + year); if (month != 0) gc.set(Calendar.MONTH, gc.get(Calendar.MONTH) + month); if (day != 0) gc.set(Calendar.DATE, gc.get(Calendar.DATE) + day); return new Timestamp(gc.getTime().getTime()); } /* * when tVal = 2004-11-26 invoke getTimeEnd(t, 12); return 2005-11-25 * 23:59:59.999 */ public static Timestamp getTimeEnd(Timestamp timestart, int monthlength) { java.util.Calendar gc = GregorianCalendar.getInstance(); gc.clear(); gc.setTime(timestart); if (monthlength != 0) { gc.set(Calendar.MONTH, gc.get(Calendar.MONTH) + monthlength); gc.set(Calendar.DATE, gc.get(Calendar.DATE) - 1); gc.set(Calendar.HOUR_OF_DAY, 23); gc.set(Calendar.MINUTE, 59); gc.set(Calendar.SECOND, 59); gc.set(Calendar.MILLISECOND, 999); } return new Timestamp(gc.getTime().getTime()); } /** * @param timestart * 开始时间 * @param type * (Y:lengeth:表示以年为单位;M:表示以月为单位;D:表示以天为单位) * @param length * 长度 * @return */ public static Timestamp getTimeEnd(Timestamp timestart, String type, int length) { java.util.Calendar gc = GregorianCalendar.getInstance(); gc.clear(); gc.setTime(timestart); if ("Y".equals(type)) { gc.set(Calendar.MONTH, gc.get(Calendar.MONTH) + length * 12); } else if ("M".equals(type)) { gc.set(Calendar.MONTH, gc.get(Calendar.MONTH) + length); } else if ("D".equals(type)) { gc.set(Calendar.MONTH, gc.get(Calendar.MONTH)); gc.set(Calendar.DATE, gc.get(Calendar.DATE) + length); } if (length > 0){ gc.set(Calendar.DATE, gc.get(Calendar.DATE) - 1); } gc.set(Calendar.HOUR_OF_DAY, 23); gc.set(Calendar.MINUTE, 59); gc.set(Calendar.SECOND, 59); gc.set(Calendar.MILLISECOND, 999); return new Timestamp(gc.getTime().getTime()); } /** * 得到该月份的第一天邮戳 * * @return */ public static Timestamp getMonthFirstDay(Timestamp timestart) { java.util.Calendar gc = GregorianCalendar.getInstance(); gc.clear(); gc.setTime(timestart); gc.set(Calendar.DAY_OF_MONTH, 1); gc.set(Calendar.HOUR_OF_DAY, 0); gc.set(Calendar.MINUTE, 0); gc.set(Calendar.SECOND, 0); gc.set(Calendar.MILLISECOND, 0); return new Timestamp(gc.getTime().getTime()); } public static int getDaysBetweenTwoDay(Timestamp timestart, Timestamp timeend) { int days = (int) ((timestart.getTime() - timeend.getTime()) / (24 * 60 * 60 * 1000) + 1); return days; } /* * when tVal = 2004-11-26 invoke getTimeEndWithoutTime(t, 12); return * 2005-11-25 23:59:59.999 */ public static Timestamp getTimeEndWithoutTime(Timestamp timestart, int monthlength) { return clearTimePart(getTimeEnd(timestart, monthlength)); } /** * @param timestart * 开始时间 * @param type * (Y:lengeth:表示以年为单位;M:表示以月为单位;D:表示以天为单位) * @param length * 长度 * @return */ public static Timestamp getTimeEndWithoutTime(Timestamp timestart, String type, int length) { return clearTimePart(getTimeEnd(timestart, type, length)); } public static Timestamp getDateEnd(Timestamp timestart, String type, int length) { java.util.Calendar gc = GregorianCalendar.getInstance(); gc.clear(); gc.setTime(timestart); if (length > 0) { if ("Y".equals(type)) { gc.set(Calendar.MONTH, gc.get(Calendar.MONTH) + length * 12); } else if ("M".equals(type)) { gc.set(Calendar.MONTH, gc.get(Calendar.MONTH) + length); } else if ("D".equals(type)) { gc.set(Calendar.DATE, gc.get(Calendar.DATE) + length); } } gc.set(Calendar.HOUR_OF_DAY, 0); gc.set(Calendar.MINUTE, 0); gc.set(Calendar.SECOND, 0); gc.set(Calendar.MILLISECOND, 0); return new Timestamp(gc.getTime().getTime()); } public static void main(String[] args) { System.out.println(TimestampUtils.getCurrentDate()); System.out.println(TimestampUtils.getCurrentDate()); System.out.println(TimestampUtils.getTimeEnd(getCurrentTimestamp(), "D", 1)); System.out.println(TimestampUtils.getMonthFirstDay(getCurrentTimestamp())); } public static Timestamp stringToTimestamp(String strVal) { Timestamp dt = null; if (strVal != null && !strVal.equals("")) { if (strVal.indexOf("-") < 0) { strVal = "2010-01-01 " + strVal; } if (strVal.indexOf(":") < 0) { // 缺少时间部分,补上 strVal += " 00:00:00"; } try { dt = Timestamp.valueOf(strVal); } catch (Exception e) { } } return dt; } }
zz-ms
trunk/zz-ms-v1.0/sourcecode/framework/src/com/jzzms/framework/util/lang/TimestampUtils.java
Java
asf20
10,219
/** * Copyright : http://www.orientpay.com , 2007-2012 * Project : oecs-g2-common-utility * $Id$ * $Revision$ * Last Changed by ZhouXushun at 2011-8-1 下午06:56:10 * $URL$ * * Change Log * Author Change Date Comments *------------------------------------------------------------- * ZhouXushun 2011-8-1 Initailized */ package com.jzzms.framework.util.lang; /** * Hex 处理工具类 * */ public class HexUtils { // 16进制 public static final char[] hex = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; private HexUtils(){ } /** * 把用十六进制字符串描述的数据转成byte类型 * @param b * @return */ public static final byte[] fromHex(String b) { char[] data = b.toCharArray(); int l = data.length; byte[] out = new byte[l >> 1]; int i = 0; for (int j = 0; j < l;) { int f = Character.digit(data[(j++)], 16) << 4; f |= Character.digit(data[(j++)], 16); out[i] = (byte) (f & 0xFF); ++i; } return out; } /** * 把byte类型转成用十六进制字符串描述的字符串 * @param b * @return */ public static final String toHex(byte[] b) { char[] buf = new char[b.length * 2]; int j; int i = j = 0; for (; i < b.length; ++i) { int k = b[i]; buf[(j++)] = hex[(k >>> 4 & 0xF)]; buf[(j++)] = hex[(k & 0xF)]; } return new String(buf); } }
zz-ms
trunk/zz-ms-v1.0/sourcecode/framework/src/com/jzzms/framework/util/lang/HexUtils.java
Java
asf20
1,723
/** * Copyright : http://www.orientpay.com , 2007-2012 * Project : oecs-g2-common-utility-trunk * $Id$ * $Revision$ * Last Changed by ZhouXushun at 2011-8-2 下午03:00:24 * $URL$ * * Change Log * Author Change Date Comments *------------------------------------------------------------- * ZhouXushun 2011-8-2 Initailized */ package com.jzzms.framework.util.lang; import java.io.Serializable; import java.net.InetAddress; /** * UUID工具生成类 * */ public class UuidUtils { private final static String sep = ""; private static final int IP; private static short counter = (short) 0; private static final int JVM = (int) (System.currentTimeMillis() >>> 8); static { int ipadd; try { ipadd = IptoInt(InetAddress.getLocalHost().getAddress()); } catch (Exception e) { ipadd = 0; } IP = ipadd; } private UuidUtils() { } protected static int IptoInt(byte[] bytes) { int result = 0; for (int i = 0; i < 4; i++) { result = (result << 8) - Byte.MIN_VALUE + (int) bytes[i]; } return result; } protected static int getJVM() { return JVM; } /** * Unique in a millisecond for this JVM instance (unless there are > * Short.MAX_VALUE instances created in a millisecond) */ protected static short getCount() { synchronized (UuidUtils.class) { if (counter < 0){ counter = 0; } return counter++; } } /** * Unique in a local network */ protected static int getIP() { return IP; } /** * Unique down to millisecond */ protected static short getHiTime() { return (short) (System.currentTimeMillis() >>> 32); } protected static int getLoTime() { return (int) System.currentTimeMillis(); } protected static String format(int intval) { String formatted = Integer.toHexString(intval); StringBuffer buf = new StringBuffer("00000000"); buf.replace(8 - formatted.length(), 8, formatted); return buf.toString(); } protected static String format(short shortval) { String formatted = Integer.toHexString(shortval); StringBuffer buf = new StringBuffer("0000"); buf.replace(4 - formatted.length(), 4, formatted); return buf.toString(); } public static Serializable generate() { return new StringBuffer(36).append(format(getIP())) .append(sep) .append(format(getJVM())) .append(sep) .append(format(getHiTime())) .append(sep) .append(format(getLoTime())) .append(sep) .append(format(getCount())) .toString(); } }
zz-ms
trunk/zz-ms-v1.0/sourcecode/framework/src/com/jzzms/framework/util/lang/UuidUtils.java
Java
asf20
3,274
/** * Copyright : http://www.orientpay.com , 2007-2012 * Project : oecs-g2-utility-trunk * $Id$ * $Revision$ * Last Changed by jason at 2011-11-1 上午11:04:12 * $URL$ * * Change Log * Author Change Date Comments *------------------------------------------------------------- * jason 2011-11-1 Initailized */ package com.jzzms.framework.util.lang; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.Map; import org.apache.commons.beanutils.PropertyUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * 对象操作工具类 * */ public class ObjectUtils { private static final Log log = LogFactory.getLog(ObjectUtils.class); private ObjectUtils(){ } /** * 得到方法的值 * @param property * @param object * @return */ public static Object getMethodValue(String property, Object object) { /*Field[] fields = object.getClass().getDeclaredFields(); Object valueObject = null; for (int j = 0; j < fields.length; j++) { if (fields[j].getName().equals(property)) { String firstChar = fields[j].getName().substring(0, 1); String leaveChar = fields[j].getName().substring(1); String methodName = firstChar.toUpperCase() + leaveChar; try { Method meth = object.getClass().getMethod("get" + methodName, null); valueObject = meth.invoke(object, null); } catch (Exception ex) { ex.printStackTrace(); } break; } } return valueObject;*/ //add by zhouxushun 2011-11-22 to support map if(object instanceof Map){ Map<?, ?> objMap = (Map<?, ?>)object; return objMap.get(property); } //end String firstChar = property.substring(0, 1); String leaveChar = property.substring(1); String methodName = firstChar.toUpperCase() + leaveChar; Object ret = null; try { Method method = getAllMethod("get" + methodName, object.getClass()); if(method != null){ //ret = method.invoke(object, null); ret = method.invoke(object, new Object[]{}); } } catch(Exception e){ log.warn(e.getMessage(), e); } return ret; } /** * 递归获取对象的值 * @param property * @param object * @return */ public static Object getMethodValueForRecursion(String property, Object object) { if (property == null || object == null) { return null; } if (property.indexOf(".") == -1) { return getMethodValue(property, object); } else { String theFirstProperty = property.substring(0, property.indexOf(".")); String theSecondProperty = property.substring(property.indexOf(".") + 1); Object firstObj = getMethodValue(theFirstProperty, object); return getMethodValueForRecursion(theSecondProperty, firstObj); } } /** * 对象复制 * @param srcObject * @param targetClassName * @return */ @SuppressWarnings("unchecked") public static Object objectCopy(Object srcObject, String targetClassName) { Object targetObject = null; if ((srcObject == null) || (targetClassName == null)) { return null; } if (srcObject instanceof Collection) { Iterator<Object> iter = ((Collection<Object>) srcObject).iterator(); Collection<Object> coll = new ArrayList<Object>(); Object item = null; Object targetItem = null; while (iter.hasNext()) { item = iter.next(); targetItem = deepObjectCopy(item, targetClassName); coll.add(targetItem); } targetObject = coll; } else { targetObject = deepObjectCopy(srcObject, targetClassName); } return targetObject; } /** * * @param srcObject * @param targetClassName * @return */ private static Object deepObjectCopy(Object srcObject, String targetClassName) { Class<?> targetClass = null; Object targetObject = null; try { targetClass = Class.forName(targetClassName); targetObject = targetClass.newInstance(); PropertyUtils.copyProperties(targetObject, srcObject); } catch (Exception e) { log.warn(e.getMessage(), e); } return targetObject; } /** * 需要重构,简单的基本类型进行拷贝 * @param srcObject * @param targetClassName * @return */ public static Object objectPrimitiveCopy(Object srcObject, String targetClassName){ try { Object targetObject = Class.forName(targetClassName).newInstance(); return objectPrimitiveCopy(srcObject,targetObject,false); } catch (Exception e) { log.warn(e.getMessage(), e); return null; } } /** * 需要重构,简单的基本类型进行拷贝 * @param srcObject * @param targetClassName * @return */ public static Object objectPrimitiveCopy(Object srcObject, Object targetObject, boolean valueFromSrc){ Class<?> valueClass = null; if(valueFromSrc){ valueClass = srcObject.getClass(); } else{ valueClass = targetObject.getClass(); } try { Field[] fields = valueClass.getDeclaredFields(); for(Field field : fields){ Class<?> fieldType = field.getType(); //如果是基本类型,字符串,boolean、integer、long、double类型 if(fieldType.isPrimitive() || fieldType.getName().equals(String.class.getName()) || fieldType.getName().equals(Boolean.class.getName()) || fieldType.getName().equals(Integer.class.getName()) || fieldType.getName().equals(Long.class.getName()) || fieldType.getName().equals(Double.class.getName()) ){ String property = field.getName(); Object value = getMethodValue(property,srcObject); setMethodValue(property,targetObject,value); } } } catch (Exception e) { log.warn(e.getMessage(), e); } return targetObject; } public static String strArroStringSQL(String[] strArr) { if (strArr == null || strArr.length == 0) return ""; StringBuffer sb = new StringBuffer(); for (int i = 0; i < strArr.length; i++) { sb.append("'" + strArr[i] + "',"); } String returnValue = sb.toString(); returnValue = returnValue.substring(0, returnValue.length() - 1); return returnValue; } public static boolean isHaveProperty(String property, Class<?> objClass) { Field[] fields = objClass.getDeclaredFields(); boolean flag = false; for (int j = 0; j < fields.length; j++) { if (fields[j].getName().equals(property)) { flag = true; break; } } return flag; } @SuppressWarnings("unchecked") public static void setMethodValue(String property, Object object, Object propertyValue) { String firstChar = property.substring(0, 1); String leaveChar = property.substring(1); String methodName = firstChar.toUpperCase() + leaveChar; //add by zhouxushun 2011-11-22 to support map if(object instanceof Map){ Map<String, Object> objMap = (Map<String, Object>)object; objMap.put(property, propertyValue); return; } //end try { Method meth = null; Class<?> fieldType = null; //Method method = object.getClass().getDeclaredMethod("get" + methodName,null); Method method = getAllMethod("get" + methodName, object.getClass()); if(method != null){ fieldType = method.getReturnType(); } else{ fieldType = object.getClass().getDeclaredField(property).getType(); } if(fieldType != null){ if(propertyValue == null){ return; } //如果为基本类型 if(fieldType.isPrimitive()){ if(propertyValue instanceof Boolean){ meth = object.getClass().getMethod("set" + methodName, Boolean.TYPE); } else if(propertyValue instanceof Integer){ meth = object.getClass().getMethod("set" + methodName, Integer.TYPE); } else if(propertyValue instanceof Long){ meth = object.getClass().getMethod("set" + methodName, Long.TYPE); } else if(propertyValue instanceof Double){ meth = object.getClass().getMethod("set" + methodName, Double.TYPE); } } else{ meth = object.getClass().getMethod("set" + methodName, propertyValue.getClass()); } if(meth != null){ meth.invoke(object, propertyValue); } } } catch (Exception ex) { ex.printStackTrace(); } } public static void setMethodValueForRecursion(String property, Object object, Object value) { if (property == null || object == null) { return; } if (property.indexOf(".") == -1) { setMethodValue(property, object,value); } else { String theFirstProperty = property.substring(0, property.indexOf(".")); String theSecondProperty = property.substring(property.indexOf(".") + 1); Object firstObj = getMethodValue(theFirstProperty, object); setMethodValueForRecursion(theSecondProperty, firstObj, value); } } protected static Method getAllMethod(String methodName, Class<?> clazz){ if(clazz==null){ return null; } try{ //Method method = object.getClass().getDeclaredMethod("get" + methodName, Null.class); Method method = clazz.getDeclaredMethod(methodName, new Class[]{}); return method; } catch(Exception e){ return getAllMethod(methodName, clazz.getSuperclass()); } } }
zz-ms
trunk/zz-ms-v1.0/sourcecode/framework/src/com/jzzms/framework/util/lang/ObjectUtils.java
Java
asf20
11,633
/** * Copyright : http://www.orientpay.com , 2007-2012 * Project : oecs-g2-common-utility-trunk * $Id$ * $Revision$ * Last Changed by ZhouXushun at 2011-8-4 下午03:24:25 * $URL$ * * Change Log * Author Change Date Comments *------------------------------------------------------------- * ZhouXushun 2011-8-4 Initailized */ package com.jzzms.framework.util.lang; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.net.URLEncoder; import org.apache.commons.lang.StringEscapeUtils; import org.apache.commons.net.util.Base64; /** * 各种格式的编码加码工具类. * * 集成Commons-Codec,Commons-Lang及JDK提供的编解码方法. * */ public class EncodeUtils { public static final String DEFAULT_CHARSET_NAME = "UTF-8"; public static final String GBK_CHARSET_NAME = "GBK"; /** * Hex编码. */ public static String hexEncode(byte[] input) { return HexUtils.toHex(input); } /** * Hex解码. */ public static byte[] hexDecode(String input) { try { return HexUtils.fromHex(input); } catch (Exception e) { throw new IllegalStateException("Hex Decoder exception", e); } } /** * Base64编码. */ public static String base64Encode(byte[] input) { return new String(Base64.encodeBase64(input)); } /** * Base64编码, URL安全(将Base64中的URL非法字符如+,/=转为其他字符, 见RFC3548). */ public static String base64UrlSafeEncode(byte[] input) { return Base64.encodeBase64URLSafeString(input); } /** * Base64解码. */ public static byte[] base64Decode(String input) { return Base64.decodeBase64(input); } /** * URL 编码, Encode默认为UTF-8. */ public static String urlEncode(String input) { return urlEncode(input, DEFAULT_CHARSET_NAME); } /** * URL 编码. */ public static String urlEncode(String input, String encoding) { try { return URLEncoder.encode(input, encoding); } catch (UnsupportedEncodingException e) { throw new IllegalArgumentException("Unsupported Encoding Exception", e); } } /** * URL 解码, Encode默认为UTF-8. */ public static String urlDecode(String input) { return urlDecode(input, DEFAULT_CHARSET_NAME); } /** * URL 解码. */ public static String urlDecode(String input, String encoding) { try { return URLDecoder.decode(input, encoding); } catch (UnsupportedEncodingException e) { throw new IllegalArgumentException("Unsupported Encoding Exception", e); } } /** * Html 转码. */ public static String htmlEscape(String html) { return StringEscapeUtils.escapeHtml(html); } /** * Html 解码. */ public static String htmlUnescape(String htmlEscaped) { return StringEscapeUtils.unescapeHtml(htmlEscaped); } /** * Xml 转码. */ public static String xmlEscape(String xml) { return StringEscapeUtils.escapeXml(xml); } /** * Xml 解码. */ public static String xmlUnescape(String xmlEscaped) { return StringEscapeUtils.unescapeXml(xmlEscaped); } }
zz-ms
trunk/zz-ms-v1.0/sourcecode/framework/src/com/jzzms/framework/util/lang/EncodeUtils.java
Java
asf20
3,568
/** * Copyright : http://www.orientpay.com , 2007-2012 * Project : oecs-g2-common-utility-trunk * $Id$ * $Revision$ * Last Changed by ZhouXushun at 2011-8-3 下午05:42:54 * $URL$ * * Change Log * Author Change Date Comments *------------------------------------------------------------- * ZhouXushun 2011-8-3 Initailized */ package com.jzzms.framework.util.lang; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.RandomAccessFile; import java.util.ArrayList; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * 文件操作帮助类 * */ public class FileUtils { private static Log log = LogFactory.getLog(FileUtils.class); private FileUtils(){ } public static boolean isFileExsit(String filePathAndName){ log.debug("filePathAndName... filePathAndName--> " + filePathAndName); try{ File file = new File(filePathAndName); if(file.exists()){ return true; } else{ return false; } } catch(Exception e){ log.error(null, e); return false; } } public static boolean makeDir(String filePath){ log.debug("makeDir... filePath--> " + filePath); try{ File file = new File(filePath); if(file.exists()){ return true; } else{ if(file.mkdirs()){ return true; } else{ return false; } } } catch(Exception e){ log.error(null, e); return false; } } /** * 删除文件 * @param fileName * @return */ public static boolean deleteFile(String fileName) { return new File(fileName).delete(); } /** * 读取文件内容,并把每行作为string存放到list中 * @param file * @return * @throws IOException */ public static List<String> readFile(File file) throws IOException { List<String> content = new ArrayList<String>(); FileReader reader = new FileReader(file); BufferedReader br = new BufferedReader(reader); String lineInfo = br.readLine(); while (lineInfo != null) { content.add(lineInfo); lineInfo = br.readLine(); } br.close(); reader.close(); return content; } public static void writeFile(String filePath, String fileName, List<String> fileContent) throws IOException { File file = new File(filePath + fileName); file.createNewFile(); FileWriter write = new FileWriter(file); for (int i = 0; i < fileContent.size(); i++) { write.write(fileContent.get(i)); } write.flush(); write.close(); } public static String getLastLine(File file) throws IOException { String lastLine = ""; RandomAccessFile rf = new RandomAccessFile(file, "r"); long count = file.length(); String beginLine = rf.readLine(); if (beginLine != null) { long seek=0; String secondLine=rf.readLine(); if(secondLine!=null){ seek=count - secondLine.length() * 2; }else{ seek=count - beginLine.length() * 2; } if(seek<0){ seek=0; } rf.seek(seek); } String ss = beginLine; while (ss != null) { lastLine = ss; ss = rf.readLine(); } rf.close(); return lastLine; } public static String readFileToString(File file) throws IOException { StringBuffer sb = null; BufferedReader in = null; try { in = new BufferedReader(new FileReader(file)); sb = new StringBuffer(); for (String line; (line = in.readLine()) != null;) { sb.append(line + "\r\n"); } } finally { if (in != null) in.close(); } return sb.toString(); } public static String readFileToStringByEncoding(File file, String encoding) throws IOException { StringBuffer sb = null; BufferedReader in = null; try { InputStreamReader read = new InputStreamReader(new FileInputStream(file), encoding); in = new BufferedReader(read); sb = new StringBuffer(); for (String line; (line = in.readLine()) != null;) { sb.append(line + "\r\n"); } } finally { if (in != null) in.close(); } return sb.toString(); } public static void writeFileByEncoding(String filePath, String fileName, String fileContent, String encoding) throws IOException { BufferedWriter out = null; try { File file = new File(filePath); if (!file.exists()) { file.mkdirs(); } file = new File(filePath + fileName); file.createNewFile(); OutputStreamWriter write = new OutputStreamWriter(new FileOutputStream(file), encoding); out = new BufferedWriter(write); out.write(fileContent); } finally { out.flush(); out.close(); } } public static void writeFileByEncoding(String fileFullPath,String fileContent,String encoding) throws IOException{ int lastCommIndex = fileFullPath.lastIndexOf("/"); String filePath = fileFullPath.substring(0,lastCommIndex + 1); String fileName = fileFullPath.substring(lastCommIndex + 1); writeFileByEncoding(filePath,fileName,fileContent,encoding); } }
zz-ms
trunk/zz-ms-v1.0/sourcecode/framework/src/com/jzzms/framework/util/lang/FileUtils.java
Java
asf20
6,501
/** * Copyright : http://www.orientpay.com , 2007-2012 * Project : oecs-g2-utility-trunk * $Id$ * $Revision$ * Last Changed by jason at 2011-10-22 上午11:17:22 * $URL$ * * Change Log * Author Change Date Comments *------------------------------------------------------------- * jason 2011-10-22 Initailized */ package com.jzzms.framework.util.lang; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.lang.StringUtils; /** * 字符串扩展功能工具类 * */ public class StringExUtils { public static final String COMMA_SIGN_SPLIT_NAME = ","; private StringExUtils(){ } /** * 占位符处理 * param 为用逗号隔开 * @return */ public static String stringHolderParse(String originStr, String param, String split){ if(StringUtils.isBlank(originStr)){ return StringUtils.EMPTY; } Pattern pattern = Pattern.compile("\\{\\d\\}"); Matcher matcher = pattern.matcher(originStr); int count = 0; while(matcher.find()){ count++; } if(count > 0){ if(StringUtils.isBlank(split)){ split = COMMA_SIGN_SPLIT_NAME; } if(StringUtils.isBlank(param)){ param = StringUtils.EMPTY; } String [] params = param.split(split); for(int i = 0; i< count; i++){ String value = (params.length < (i + 1)) ? "" : params[i]; originStr = originStr.replaceAll("\\{" + i + "\\}", value); } } return originStr; } public static String stringToCertCharset(String str, String charset){ try{ return new String(str.getBytes(), charset); } catch(Exception e){ return str; } } public static String byteToCertCharset(byte [] bytes, String charset){ try{ return new String(bytes, charset); } catch(Exception e){ return new String(); } } public static void main(String [] args){ Pattern pattern = Pattern.compile("\\{\\d\\}"); Matcher matcher = pattern.matcher("hello0 {0}, hello1 {1}, hello2{2}打法"); int count = 0; while(matcher.find()){ count++; } System.out.println(count); count = 0; matcher = pattern.matcher("hello0 {0}, hello1 {1}打法的"); while(matcher.find()){ count++; } System.out.println(count); count = 0; matcher = pattern.matcher("hello0 {0}"); while(matcher.find()){ count++; } System.out.println(count); count = 0; matcher = pattern.matcher("hello0"); while(matcher.find()){ count++; } System.out.println(count); System.out.println(stringHolderParse("hello0 {0}, hello1 {1}打法的","1,2,3", null)); System.out.println(stringHolderParse("hello0 {0}, hello1 {1}打法的","1", null)); System.out.println(stringHolderParse("hello0 {0}, hello1 {1}打法的","", null)); } }
zz-ms
trunk/zz-ms-v1.0/sourcecode/framework/src/com/jzzms/framework/util/lang/StringExUtils.java
Java
asf20
3,427
/** * Copyright : http://www.orientpay.com , 2007-2012 * Project : oecs-g2-common-utility-trunk * $Id$ * $Revision$ * Last Changed by ZhouXushun at 2011-8-3 下午05:17:28 * $URL$ * * Change Log * Author Change Date Comments *------------------------------------------------------------- * ZhouXushun 2011-8-3 Initailized */ package com.jzzms.framework.util.lang; import java.lang.reflect.Method; import java.net.URL; import java.net.URLClassLoader; import java.util.List; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * 类加载器的帮助类 * */ public class ClassLoaderUtils { protected static Log log = LogFactory.getLog(ClassLoaderUtils.class); private ClassLoaderUtils() { } public static void addURL(String url, ClassLoader classLoader) { log.debug("addURL(),url->" + url); if (StringUtils.isBlank(url)) { return; } ClassLoader threadContextClassLoader = classLoader; if (threadContextClassLoader == null) { threadContextClassLoader = Thread.currentThread().getContextClassLoader(); } boolean is = threadContextClassLoader instanceof URLClassLoader; if (is) { try { URL realUrl = new URL(url); URLClassLoader curr = (URLClassLoader) threadContextClassLoader; Method add = URLClassLoader.class.getDeclaredMethod("addURL", new Class[] { URL.class }); add.setAccessible(true); add.invoke(curr, new Object[] { realUrl }); } catch (Exception e) { log.warn("WARN", e); throw new IllegalArgumentException(e); } } else { log.warn("the classloader is not a URLClassLoader type!"); throw new IllegalArgumentException("the classloader is not a URLClassLoader type!"); } } public static ClassLoader getDefaultClassLoader() { ClassLoader cl = null; try { cl = Thread.currentThread().getContextClassLoader(); } catch (Throwable e) { log.info("INFO", e); } if (cl == null) { cl = ClassLoaderUtils.class.getClassLoader(); } return cl; } public static void removeURL(String url, ClassLoader classLoader){ //TODO 等待实现,从classloader中删除某个url } public static void removeURL(String [] urls, ClassLoader classLoader){ if(urls != null && urls.length > 0 && classLoader != null){ for(String url : urls){ removeURL(url, classLoader); } } } public static void removeURL(List<String> urlList, ClassLoader classLoader){ if(urlList != null && urlList.size() > 0 && classLoader != null){ for(String url : urlList){ removeURL(url, classLoader); } } } }
zz-ms
trunk/zz-ms-v1.0/sourcecode/framework/src/com/jzzms/framework/util/lang/ClassLoaderUtils.java
Java
asf20
3,157
/** * Copyright : http://www.orientpay.com , 2007-2012 * Project : oecs-g2-common-utility-trunk * $Id$ * $Revision$ * Last Changed by ZhouXushun at 2011-8-4 下午02:56:15 * $URL$ * * Change Log * Author Change Date Comments * ------------------------------------------------------------- * ZhouXushun 2011-8-4 Initailized */ package com.jzzms.framework.util.lang; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * 日期时间帮助类 * */ public class DateTimeUtils { private static final Log log = LogFactory.getLog(DateTimeUtils.class); // 默认的时间格式 public static final String DEFUALT_SHOT_TIME_FORMAT = "yyyy-MM-dd"; public static final String SHOT_DATE_FORMAT = "yyyyMMdd"; public static final String DEFUALT_LONG_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss"; public static final String LONG_TIME_FORMAT = "HH:mm:ss"; public static final String SHOT_TIME_FORMAT = "HHmmss"; private DateTimeUtils() { } /** * 清除小时分钟和秒 */ public static Date clearHourMiniteSecond(Date date) { if (date == null) { return null; } Calendar gc = GregorianCalendar.getInstance(); gc.clear(); gc.setTime(date); gc.set(Calendar.HOUR_OF_DAY, 0); gc.set(Calendar.MINUTE, 0); gc.set(Calendar.SECOND, 0); gc.set(Calendar.MILLISECOND, 0); return gc.getTime(); } /** * 按照指定格式返回当前时间,如果格式为空,则默认为yyyy-MM-dd * * @param dateFormat * @return */ public static String getCurrentDateToString(String dateFormat) { if (StringUtils.isBlank(dateFormat)) { dateFormat = DEFUALT_SHOT_TIME_FORMAT; } SimpleDateFormat sdf = new SimpleDateFormat(dateFormat); return sdf.format(getCurrentDate()); } /** * 按照指定格式返回当前时间,如果格式为空,则默认为yyyy-MM-dd * * @param dateFormat * @return */ public static Date stringFormatToDate(String date, String dateFormat) { if (date == null) { return null; } if (StringUtils.isBlank(dateFormat)) { if (date.length() > 10) { dateFormat = DEFUALT_LONG_TIME_FORMAT; } else { dateFormat = DEFUALT_SHOT_TIME_FORMAT; } } try { SimpleDateFormat sdf = new SimpleDateFormat(dateFormat); return sdf.parse(date); } catch (Exception e) { log.info("INFO", e); return null; } } /** * 格式化日期输出,如果格式为空,则默认为yyyy-MM-dd * * @param date * @param dateFormat * @return */ public static String dateToStringFormat(Date date, String dateFormat) { if (date == null) { return ""; } if (StringUtils.isBlank(dateFormat)) { dateFormat = DEFUALT_SHOT_TIME_FORMAT; } try { SimpleDateFormat sdf = new SimpleDateFormat(dateFormat); return sdf.format(date); } catch (Exception e) { log.info("INFO", e); return null; } } /** * 得到当前时间 * * @return */ public static Date getCurrentDate() { return new Date(); } /** * 比较两个时间的间隔,单位为毫秒 * * @param endDate * @param startDate * @return */ public static int diffTwoDateWithTime(Date endDate, Date startDate) { if (startDate == null || endDate == null) { return -1; } int diff = (int) (endDate.getTime() - startDate.getTime()); return diff; } /** * 比较两个时间的间隔,单位为小时 * * @param startDate * @param endDate * @return */ public static int diffTwoDateWithHour(Date startDate, Date endDate) { return (int) ((endDate.getTime() - startDate.getTime()) / (60 * 60 * 1000) + 1); } /** * 时间增加一天Calendar的使用 * @param s * @param n * @return */ public static String addDate(String s, int n) { try { SimpleDateFormat sdf = new SimpleDateFormat(SHOT_DATE_FORMAT); Calendar cd = Calendar.getInstance(); cd.setTime(sdf.parse(s)); cd.add(Calendar.DATE, n);// 增加一天 // cd.add(Calendar.MONTH, n);//增加一个月 return sdf.format(cd.getTime()); } catch (Exception e) { log.info("INFO", e); return null; } } }
zz-ms
trunk/zz-ms-v1.0/sourcecode/framework/src/com/jzzms/framework/util/lang/DateTimeUtils.java
Java
asf20
5,351
/** * Copyright : http://www.orientpay.com , 2007-2012 * Project : oecs-g2-framework-trunk * $Id$ * $Revision$ * Last Changed by jason at 2011-9-22 下午10:19:23 * $URL$ * * Change Log * Author Change Date Comments *------------------------------------------------------------- * jason 2011-9-22 Initailized */ package com.jzzms.framework.util.common; import java.util.List; import org.apache.ibatis.session.RowBounds; import com.jzzms.framework.orm.query.ZzMsCriterion; import com.jzzms.framework.orm.query.Page; import com.jzzms.framework.orm.query.PropertyFilter; /** * OecsCriterion 工具类 * */ public class ZzMsCriterionUtils { private ZzMsCriterionUtils(){ } public static ZzMsCriterion createOecsCriterion(Page<?> page, List<PropertyFilter> filters){ ZzMsCriterion criterion = new ZzMsCriterion(); //设置排序参数 if(page.isOrderBySetted()){ criterion.setOrderBy(page.getOrderField()); criterion.setOrder(page.getOrderDirection()); } //设置查询参数 if(filters != null && filters.size() > 0){ criterion.setCriteria(filters); } return criterion; } public static RowBounds createRowBounds(Page<?> page){ RowBounds rowBounds = null; //设置分页参数 if(page.isAutoPage()){ int limit = (page.getPageNum() - 1) * page.getNumPerPage(); rowBounds = new RowBounds(limit, page.getNumPerPage()); } return rowBounds; } }
zz-ms
trunk/zz-ms-v1.0/sourcecode/framework/src/com/jzzms/framework/util/common/ZzMsCriterionUtils.java
Java
asf20
1,687
/** * Copyright : http://www.orientpay.com , 2007-2012 * Project : oecs-g2-framework-trunk * $Id$ * $Revision$ * Last Changed by jason at 2011-9-18 下午7:05:51 * $URL$ * * Change Log * Author Change Date Comments *------------------------------------------------------------- * jason 2011-9-18 Initailized */ package com.jzzms.framework.util.common; import java.io.Serializable; import java.util.Date; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.math.NumberUtils; import com.jzzms.framework.core.Constants; import com.jzzms.framework.core.UserDetailsImpl; import com.jzzms.framework.util.lang.DateTimeUtils; import com.jzzms.framework.util.lang.ReflectionUtils; /** * model更新的辅助类 * */ public class ModelUpdateInfoUtils { //创建和修改信息 public static final String CREATE_TIME = "createTime"; public static final String CREATE_OPER_ID = "createOperId"; public static final String CREATE_OPER_NAME = "createOperName"; public static final String LAST_MOD_TIME = "updateTime"; public static final String LAST_MOD_OPER_ID = "updateOperId"; public static final String LAST_MOD_OPER_NAME = "updateOperName"; public static final String STATUS = "status"; //主键 public static final String ID = "id"; public static final String CODE = "code"; public static final String APP_CODE = "appCode"; private ModelUpdateInfoUtils(){ } //更新时间 public static void updateModelUpdateTime(Object object){ if(object == null){ return; } //做更新 if(ReflectionUtils.getDeclaredField(object,LAST_MOD_TIME) != null){ ReflectionUtils.invokeSetterMethod(object, LAST_MOD_TIME, new Date()); } } public static Date getModelUpdateTime(Object object){ if(object == null){ return null; } try{ if(ReflectionUtils.getDeclaredField(object,LAST_MOD_TIME) != null){ Object dateObj = ReflectionUtils.invokeGetterMethod(object, LAST_MOD_TIME); if(dateObj instanceof Date){ return (Date)dateObj; } } } catch(Exception e){ } return null; } public static void updateModelInfo(Serializable object, UserDetailsImpl user){ if(object == null || user == null){ return; } if(ReflectionUtils.getDeclaredField(object,LAST_MOD_OPER_ID) != null){ if(StringUtils.isNotBlank(user.getUserId())){ Long operId = NumberUtils.toLong(user.getUserId()); ReflectionUtils.invokeSetterMethod(object, LAST_MOD_OPER_ID, operId); } } if(ReflectionUtils.getDeclaredField(object,LAST_MOD_OPER_NAME) != null){ ReflectionUtils.invokeSetterMethod(object, LAST_MOD_OPER_NAME, user.getRealname()); } //如果主键为空,则设置创建 if(ReflectionUtils.getDeclaredField(object,ID) != null){ Object idValue = ReflectionUtils.getFieldValue(object, ID); if(idValue == null || "".equals(idValue)){ //一定要设置为空,要不然无法插入数据库 ReflectionUtils.setFieldValue(object, ID, null); updateModelCreateInfo(object,user); updateModelUpdateTime(object); } } else if(ReflectionUtils.getDeclaredField(object,CODE) != null || ReflectionUtils.getDeclaredField(object,APP_CODE) != null){ Object createTime = ReflectionUtils.getFieldValue(object, CREATE_TIME); if(createTime == null){ updateModelCreateInfo(object,user); updateModelUpdateTime(object); } } } protected static void updateModelCreateInfo(Serializable object, UserDetailsImpl user){ if(ReflectionUtils.getDeclaredField(object,CREATE_TIME) != null){ ReflectionUtils.invokeSetterMethod(object, CREATE_TIME, DateTimeUtils.getCurrentDate()); } if(ReflectionUtils.getDeclaredField(object,CREATE_OPER_ID) != null){ if(StringUtils.isNotBlank(user.getUserId())){ Long operId = NumberUtils.toLong(user.getUserId()); ReflectionUtils.invokeSetterMethod(object, CREATE_OPER_ID, operId); } } if(ReflectionUtils.getDeclaredField(object,CREATE_OPER_NAME) != null){ ReflectionUtils.invokeSetterMethod(object, CREATE_OPER_NAME, user.getRealname()); } } public static void createModelInfoBySys(Serializable object, String transCode){ if(ReflectionUtils.getDeclaredField(object,CREATE_TIME) != null){ ReflectionUtils.invokeSetterMethod(object, CREATE_TIME, DateTimeUtils.getCurrentDate()); } if(ReflectionUtils.getDeclaredField(object,CREATE_OPER_ID) != null){ ReflectionUtils.invokeSetterMethod(object, CREATE_OPER_ID, Constants.GLOBAL_SYSTEM_OPER_ID); } if(ReflectionUtils.getDeclaredField(object,CREATE_OPER_NAME) != null){ ReflectionUtils.invokeSetterMethod(object, CREATE_OPER_NAME, transCode); } if(ReflectionUtils.getDeclaredField(object,LAST_MOD_TIME) != null){ ReflectionUtils.invokeSetterMethod(object, LAST_MOD_TIME, DateTimeUtils.getCurrentDate()); } updateModelInfoBySys(object, transCode); } public static void updateModelInfoBySys(Serializable object, String transCode){ if(ReflectionUtils.getDeclaredField(object,LAST_MOD_OPER_ID) != null){ ReflectionUtils.invokeSetterMethod(object, LAST_MOD_OPER_ID, Constants.GLOBAL_SYSTEM_OPER_ID); } if(ReflectionUtils.getDeclaredField(object,LAST_MOD_OPER_NAME) != null){ ReflectionUtils.invokeSetterMethod(object, LAST_MOD_OPER_NAME, transCode); } } public static void setModelInvalidStatus(Serializable object){ if(ReflectionUtils.getDeclaredField(object,STATUS) != null){ ReflectionUtils.invokeSetterMethod(object, STATUS, Constants.DICT_GLOBAL_STATUS_INVALIDATE); } } }
zz-ms
trunk/zz-ms-v1.0/sourcecode/framework/src/com/jzzms/framework/util/common/ModelUpdateInfoUtils.java
Java
asf20
6,634
/** * Copyright : http://www.orientpay.com , 2007-2012 * Project : oecs-g2-utility-trunk * $Id$ * $Revision$ * Last Changed by jason at 2011-9-13 下午5:19:43 * $URL$ * * Change Log * Author Change Date Comments *------------------------------------------------------------- * jason 2011-9-13 Initailized */ package com.jzzms.framework.util.common; import java.io.IOException; import java.util.Properties; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.jzzms.framework.util.lang.ResourcesUtils; /** * 系统属性配置文件工具类 * */ public class SystemPropertyUtils { protected static final Log log = LogFactory.getLog(SystemPropertyUtils.class); protected static final String SYSTEM_PROPERTY_FILENAME = "system.properties"; private static Properties prop; private SystemPropertyUtils(){ } public static String getString(String aKey){ return getString(aKey,""); } public static String getString(String aKey,String defaultValue){ String value = (String)prop.get(aKey); if(StringUtils.isBlank(value)){ log.debug("the property is null"); value = defaultValue; } log.debug("the property is ->" + value); return value; } static{ try { prop = ResourcesUtils.getResourceAsProperties(SYSTEM_PROPERTY_FILENAME); } catch (IOException e) { log.error("ERROR", e); throw new RuntimeException("Could not find : " + SYSTEM_PROPERTY_FILENAME,e); } } }
zz-ms
trunk/zz-ms-v1.0/sourcecode/framework/src/com/jzzms/framework/util/common/SystemPropertyUtils.java
Java
asf20
1,743
/** * Copyright : http://www.orientpay.com , 2007-2012 * Project : oecs-g2-framework-trunk * $Id$ * $Revision$ * Last Changed by jason at 2011-9-16 下午12:43:02 * $URL$ * * Change Log * Author Change Date Comments *------------------------------------------------------------- * jason 2011-9-16 Initailized */ package com.jzzms.framework.util.common; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.Iterator; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import org.apache.commons.beanutils.PropertyUtils; import org.apache.commons.lang.StringUtils; import com.jzzms.framework.core.Constants; import com.jzzms.framework.orm.query.MatchType; import com.jzzms.framework.orm.query.PropertyFilter; import com.jzzms.framework.orm.query.PropertyType; import com.jzzms.framework.util.lang.AssertUtils; import com.jzzms.framework.util.lang.DateTimeUtils; import com.jzzms.framework.util.lang.ReflectionUtils; /** * TODO Add class descriptions * */ public class PropertyFilterUtils { /** * 根据对象ID集合,整理合并集合. * * 默认对象主键的名称名为"id". * * @see #mergeByCheckedIds(Collection, Collection, Class, String) */ public static <T, ID> void mergeByCheckedIds(final Collection<T> srcObjects, final Collection<ID> checkedIds,final Class<T> clazz) { mergeByCheckedIds(srcObjects, checkedIds, clazz, "id"); } /** * 根据对象ID集合,整理合并集合. * * 页面发送变更后的子对象id列表时,删除原来的子对象集合再根据页面id列表创建一个全新的集合这种看似最简单的做法是不行的. * 因此采用如此的整合算法:在源集合中删除id不在目标集合中的对象,根据目标集合中的id创建对象并添加到源集合中. * 因为新建对象只有ID被赋值, 因此本函数不适合于cascade-save-or-update自动持久化子对象的设置. * * @param srcObjects 源集合,元素为对象. * @param checkedIds 目标集合,元素为ID. * @param clazz 集合中对象的类型 * @param idName 对象主键的名称 */ public static <T, ID> void mergeByCheckedIds(final Collection<T> srcObjects, final Collection<ID> checkedIds, final Class<T> clazz, final String idName) { //参数校验 AssertUtils.notNull(srcObjects, "scrObjects can not be null"); AssertUtils.hasText(idName, "idName can not be null"); AssertUtils.notNull(clazz, "clazz can not be null"); //目标集合为空, 删除源集合中所有对象后直接返回. if (checkedIds == null) { srcObjects.clear(); return; } //遍历源集合,如果其id不在目标ID集合中的对象,进行删除. //同时,在目标集合中删除已在源集合中的id,使得目标集合中剩下的id均为源集合中没有的id. Iterator<T> srcIterator = srcObjects.iterator(); try { while (srcIterator.hasNext()) { T element = srcIterator.next(); Object id; id = PropertyUtils.getProperty(element, idName); if (!checkedIds.contains(id)) { srcIterator.remove(); } else { checkedIds.remove(id); } } //ID集合目前剩余的id均不在源集合中,创建对象,为id属性赋值并添加到源集合中. for (ID id : checkedIds) { T obj = clazz.newInstance(); PropertyUtils.setProperty(obj, idName, id); srcObjects.add(obj); } } catch (Exception e) { throw ReflectionUtils.convertReflectionExceptionToUnchecked(e); } } /** * 根据按PropertyFilter命名规则的Request参数,创建PropertyFilter列表. * 默认Filter属性名前缀为filter_. * * @see #buildPropertyFilters(HttpServletRequest, String) */ public static List<PropertyFilter> buildPropertyFilters(final HttpServletRequest request) { return buildPropertyFilters(request, "filter_"); } /** * 根据按PropertyFilter命名规则的Request参数,创建PropertyFilter列表. * 默认Filter属性名前缀为filter_. * * @see #buildPropertyFilters(HttpServletRequest, String) */ public static List<PropertyFilter> buildPropertyFilters(Map<String, Object> request) { return buildPropertyFilters(request, "filter_"); } /** * 根据按PropertyFilter命名规则的Request参数,创建PropertyFilter列表. * PropertyFilter命名规则为Filter属性前缀_比较类型属性类型_属性名. * * eg. * filter_EQS_name * filter_LIKES_name_OR_email */ public static List<PropertyFilter> buildPropertyFilters(final HttpServletRequest request, final String filterPrefix) { //从request中获取含属性前缀名的参数,构造去除前缀名后的参数Map. Map<String, Object> filterParamMap = ServletUtils.getParametersStartingWith(request, filterPrefix); return buildPropertyFilters(filterParamMap, filterPrefix); } /** * 根据按PropertyFilter命名规则的Request参数,创建PropertyFilter列表. * PropertyFilter命名规则为Filter属性前缀_比较类型属性类型_属性名. * * eg. * filter_EQS_name * filter_LIKES_name_OR_email */ public static List<PropertyFilter> buildPropertyFilters(Map<String, Object> filterParamMap, final String filterPrefix) { List<PropertyFilter> filterList = new ArrayList<PropertyFilter>(); //分析参数Map,构造PropertyFilter列表 for (Map.Entry<String, Object> entry : filterParamMap.entrySet()) { String filterName = entry.getKey(); Object valueObj = entry.getValue(); String value = null; if(valueObj instanceof String){ value = (String)valueObj; } //如果value值为空,则忽略此filter. if (StringUtils.isNotBlank(value)) { PropertyFilter filter = new PropertyFilter(filterName, value); filterList.add(filter); } } return filterList; } public static String propertyFilter2SqlString(PropertyFilter filter){ String[] propertyNames = filter.getPropertyNames(); StringBuilder sb = new StringBuilder(); if(filter.isMultiProperty()){ sb.append(" ("); } boolean isFirst = true; for(String propertyName : propertyNames){ if(StringUtils.isNotBlank(propertyName)){ if(isFirst){ isFirst = false; } else{ sb.append("OR"); } sb.append(propertyFilter2SqlString(propertyName, filter)); } } if(filter.isMultiProperty()){ sb.append(") "); } return sb.toString(); } protected static String propertyFilter2SqlString(String propertyName, PropertyFilter filter){ PropertyType propertyType = filter.getPropertyType(); Object propertyValue = filter.getPropertyValue(); MatchType matchType = filter.getMatchType(); StringBuilder sb = new StringBuilder(" " + propertyName); sb.append(" " + matchType.express() + " "); if(matchType.outputValue()){ sb.append(propertyType.expressStart()); sb.append(matchType.expressStart()); if(propertyValue != null && propertyValue instanceof Date){ Date date = (Date)propertyValue; sb.append(DateTimeUtils.dateToStringFormat(date, Constants.DEFUALT_LONG_TIME_FORMAT)); } else{ sb.append(propertyValue); } sb.append(matchType.expressEnd()); sb.append(propertyType.expressEnd() + " "); } return sb.toString(); } public static void main(String [] args){ PropertyType propertyType = PropertyType.D; MatchType matchType = MatchType.LLIKE; System.out.println(propertyType.name()); System.out.println(matchType.name()); String query1 = "LIKES_NAME_OR_LOGIN_NAME"; PropertyFilter f1 = new PropertyFilter(query1, "admin"); System.out.println(propertyFilter2SqlString(f1)); String query2 = "LLIKES_NAME_OR_LOGIN_NAME"; PropertyFilter f2 = new PropertyFilter(query2, "admin"); System.out.println(propertyFilter2SqlString(f2)); String query3 = "RLIKES_NAME_OR_LOGIN_NAME"; PropertyFilter f3 = new PropertyFilter(query3, "admin"); System.out.println(propertyFilter2SqlString(f3)); String query4 = "EQS_NAME"; PropertyFilter f4 = new PropertyFilter(query4, "admin"); System.out.println(propertyFilter2SqlString(f4)); String query5 = "GEI_NAME"; PropertyFilter f5 = new PropertyFilter(query5, "1"); System.out.println(propertyFilter2SqlString(f5)); String query6 = "GTI_NAME"; PropertyFilter f6 = new PropertyFilter(query6, "1"); System.out.println(propertyFilter2SqlString(f6)); String query7 = "EQD_NAME"; PropertyFilter f7 = new PropertyFilter(query7, "2011-02-03"); System.out.println(propertyFilter2SqlString(f7)); String query8 = "EQN_NAME"; PropertyFilter f8 = new PropertyFilter(query8, "1"); System.out.println(propertyFilter2SqlString(f8)); String query9 = "EQS_NAME"; PropertyFilter f9 = new PropertyFilter(query9, "admin"); System.out.println(propertyFilter2SqlString(f9)); String query10 = "GTD_CREATE_OR_LASTUPD"; PropertyFilter f10 = new PropertyFilter(query10, "2011-02-03 12:12:01"); System.out.println(propertyFilter2SqlString(f10)); String query11 = "INA_STATUS"; PropertyFilter f11 = new PropertyFilter(query11, "'A','B','C','D'"); System.out.println(propertyFilter2SqlString(f11)); String query12 = "NULLS_STATUS"; PropertyFilter f12 = new PropertyFilter(query12,null); System.out.println(propertyFilter2SqlString(f12)); } }
zz-ms
trunk/zz-ms-v1.0/sourcecode/framework/src/com/jzzms/framework/util/common/PropertyFilterUtils.java
Java
asf20
11,033
/** * Copyright : http://www.orientpay.com , 2007-2012 * Project : oecs-g2-common-framework-trunk * $Id$ * $Revision$ * Last Changed by ZhouXushun at 2011-8-8 上午11:46:29 * $URL$ * * Change Log * Author Change Date Comments *------------------------------------------------------------- * ZhouXushun 2011-8-8 Initailized */ package com.jzzms.framework.util.common; import java.io.PrintStream; import java.text.MessageFormat; import java.util.Enumeration; import java.util.Iterator; import java.util.Properties; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.jzzms.framework.core.Constants; /** * request 工具类 * */ public class RequestUtils { private static final Log log = LogFactory.getLog(RequestUtils.class); private static Properties headerMap; private static String defaultMobile; static { /* * InputStream in = RequestUtils.class.getResourceAsStream( * "/cn/com/eaglenetworks/abdf/view/util/mobile_match.properties"); * headerMap = new Properties(); try{ headerMap.load(in); defaultMobile * = headerMap.getProperty("empty"); } catch(IOException e){ * log.error("ERROR",e); } */ headerMap = new Properties(); headerMap.put("x-up-calling-line-id", "{0}"); headerMap.put("x-up-subno", "86{0}_gateway"); headerMap.put("X-Imsi", "{0}"); headerMap.put("X-WAP-ClientID", "{0}"); headerMap.put("X-Network-info", "{2},{0},{1}"); } public static boolean isMultipart(HttpServletRequest req) { return ((req.getContentType() != null) && (req.getContentType() .toLowerCase().startsWith("multipart"))); } public static Cookie getCookie(HttpServletRequest request, String name) { Cookie[] cookies = request.getCookies(); if (cookies == null) { return null; } for (int i = 0; i < cookies.length; i++) { if (name.equals(cookies[i].getName())) { return cookies[i]; } } return null; } public static void setCookie(HttpServletRequest request, HttpServletResponse response, String name, String value, int maxAge) { Cookie cookie = new Cookie(name, value); cookie.setMaxAge(maxAge); String serverName = request.getServerName(); String domain = getDomainOfServerName(serverName); if (domain != null && domain.indexOf('.') != -1) { cookie.setDomain('.' + domain); } cookie.setPath("/"); response.addCookie(cookie); } public static String getDomainOfServerName(String host) { if (isIPAddr(host)) { return null; } String[] names = StringUtils.split(host, '.'); int len = names.length; if (len >= 2) { return names[len - 2] + '.' + names[len - 1]; } return host; } public static String getHeader(HttpServletRequest req, String name) { String value = req.getHeader(name); if (value != null) return value; Enumeration<?> names = req.getHeaderNames(); while (names.hasMoreElements()) { String n = (String) names.nextElement(); if (n.equalsIgnoreCase(name)) { return req.getHeader(n); } } return null; } public static String getUrlPrefix(HttpServletRequest req) { StringBuffer url = new StringBuffer(req.getScheme()); url.append("://"); url.append(req.getServerName()); int port = req.getServerPort(); if (port != 80) { url.append(":"); url.append(port); } return url.toString(); } public static String getRequestURL(HttpServletRequest req) { StringBuffer url = new StringBuffer(req.getRequestURI()); String param = req.getQueryString(); if (param != null) { url.append('?'); url.append(param); } String path = url.toString(); return path.substring(req.getContextPath().length()); } public static void dumpHeaders(PrintStream out, HttpServletRequest req) { Enumeration<?> names = req.getHeaderNames(); while (names.hasMoreElements()) { String name = (String) names.nextElement(); out.println(name + "=" + req.getHeader(name)); } } /** * 用于支持WAP * * @param req * @return */ public static String getRequestMobile(HttpServletRequest req) { String mobile = defaultMobile; Iterator<?> keys = headerMap.keySet().iterator(); while (keys.hasNext()) { String header = (String) keys.next(); String value = getHeader(req, header); if (value != null) { String pattern = (String) headerMap.get(header); MessageFormat mf = new MessageFormat(pattern); try { Object[] vs = mf.parse(value); mobile = (String) vs[0]; if (mobile.startsWith("86")) { mobile = mobile.substring(2); } break; } catch (Exception e) { log.warn("error", e); dumpHeaders(req, System.err); continue; } } } return mobile; } public static void dumpHeaders(HttpServletRequest req, PrintStream out) { Enumeration<?> hds = req.getHeaderNames(); while (hds.hasMoreElements()) { String name = (String) hds.nextElement(); out.println(name + "=" + req.getHeader(name)); } } public static boolean support(HttpServletRequest req, String contentType) { String accept = getHeader(req, "accept"); if (accept != null) { accept = accept.toLowerCase(); return accept.indexOf(contentType.toLowerCase()) != -1; } return false; } public static boolean isMozillaCompatible(HttpServletRequest req) { String user_agent = req.getHeader("user-agent"); return user_agent == null || user_agent.indexOf("Mozilla") != -1; } public static int getParam(HttpServletRequest req, String param, int defaultValue) { try { String value = req.getParameter(param); if (value == null) { return defaultValue; } int idx = value.indexOf('#'); if (idx != -1) { value = value.substring(0, idx); } return Integer.parseInt(value); } catch (Exception e) { log.error("error ", e); } return defaultValue; } public static String getParam(HttpServletRequest req, String param, String defaultValue) { String value = req.getParameter(param); return (StringUtils.isEmpty(value)) ? defaultValue : value; } public static boolean isIPAddr(String addr) { if (StringUtils.isEmpty(addr)) { return false; } String[] ips = StringUtils.split(addr, '.'); if (ips.length != 4) { return false; } try { int ipa = Integer.parseInt(ips[0]); int ipb = Integer.parseInt(ips[1]); int ipc = Integer.parseInt(ips[2]); int ipd = Integer.parseInt(ips[3]); return ipa >= 0 && ipa <= 255 && ipb >= 0 && ipb <= 255 && ipc >= 0 && ipc <= 255 && ipd >= 0 && ipd <= 255; } catch (Exception e) { } return false; } public static String convert2UTF8(String src){ if(StringUtils.isBlank(src)){ return src; } String ret = ""; try{ ret = new String(src.getBytes("ISO-8859-1"),Constants.DEFAULT_CHARSET_NAME); } catch(Exception e){ log.debug("warn : cannot convert :" + src); ret = src; } return ret; } }
zz-ms
trunk/zz-ms-v1.0/sourcecode/framework/src/com/jzzms/framework/util/common/RequestUtils.java
Java
asf20
9,168
/** * Copyright : http://www.orientpay.com , 2007-2012 * Project : oecs-g2-framework-trunk * $Id$ * $Revision$ * Last Changed by jason at 2011-9-22 下午1:24:00 * $URL$ * * Change Log * Author Change Date Comments *------------------------------------------------------------- * jason 2011-9-22 Initailized */ package com.jzzms.framework.util.common; import java.io.IOException; import javax.servlet.http.HttpServletResponse; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * 实现获取Response绕过jsp/freemaker直接输出文本的简化函数. * */ public class AjaxRenderUtils { //header 常量定义 private static final String ENCODING_PREFIX = "encoding"; private static final String NOCACHE_PREFIX = "no-cache"; private static final String ENCODING_DEFAULT = "UTF-8"; private static final boolean NOCACHE_DEFAULT = true; private static Log log = LogFactory.getLog(AjaxRenderUtils.class); /** * 直接输出内容的简便函数. * eg. * render("text/plain", "hello", "encoding:GBK"); * render("text/plain", "hello", "no-cache:false"); * render("text/plain", "hello", "encoding:GBK", "no-cache:false"); * * @param headers 可变的header数组,目前接受的值为"encoding:"或"no-cache:",默认值分别为UTF-8和true. */ public static void render(HttpServletResponse response, final String contentType, final String content, final String... headers) { try { //分析headers参数 String encoding = ENCODING_DEFAULT; boolean noCache = NOCACHE_DEFAULT; for (String header : headers) { String headerName = StringUtils.substringBefore(header, ":"); String headerValue = StringUtils.substringAfter(header, ":"); if (StringUtils.equalsIgnoreCase(headerName, ENCODING_PREFIX)) { encoding = headerValue; } else if (StringUtils.equalsIgnoreCase(headerName, NOCACHE_PREFIX)) { noCache = Boolean.parseBoolean(headerValue); } else{ throw new IllegalArgumentException(headerName + "is not a legal argument"); } } //设置headers参数 String fullContentType = contentType + ";charset=" + encoding; response.setContentType(fullContentType); if (noCache) { response.setHeader("Pragma", "No-cache"); response.setHeader("Cache-Control", "no-cache"); response.setDateHeader("Expires", 0); } response.getWriter().write(content); } catch (IOException e) { log.error("ERROR", e); } } /** * 直接输出文本. * @see #render(String, String, String...) */ public static void renderText(HttpServletResponse response, final String text, final String... headers) { render(response, "text/plain", text, headers); } /** * 直接输出HTML. * @see #render(String, String, String...) */ public static void renderHtml(HttpServletResponse response, final String html, final String... headers) { render(response, "text/html", html, headers); } /** * 直接输出XML. * @see #render(String, String, String...) */ public static void renderXml(HttpServletResponse response, final String xml, final String... headers) { render(response, "text/xml", xml, headers); } /** * 直接输出JSON. * * @param string json字符串. * @see #render(String, String, String...) */ public static void renderJson(HttpServletResponse response, final String string, final String... headers) { render(response, "application/json", string, headers); } /** * 直接输出JSON. * * @param object Java对象,将被转化为json字符串. Object 可以为map,也可以为普通对象 * @see #render(String, String, String...) */ public static void renderJson(HttpServletResponse response, final Object object, final String... headers) { throw new IllegalAccessError("not implement yet@"); //String jsonString = ""; /*if(object instanceof List){ jsonString = JSONArray.fromObject(object).toString(); } else{ jsonString = JSONObject.fromObject(object).toString(); }*/ //renderJson(response, jsonString, headers); } }
zz-ms
trunk/zz-ms-v1.0/sourcecode/framework/src/com/jzzms/framework/util/common/AjaxRenderUtils.java
Java
asf20
4,831