Commit 9a6a806b authored by jay's avatar jay

first commit

parents

Too many changes to show.

To preserve performance only 1000 of 1000+ files are displayed.

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.house365</groupId>
<artifactId>house365-framework</artifactId>
<packaging>jar</packaging>
<version>1.0.0-SNAPSHOT</version>
<name>house365-framework</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<spring.version>4.1.4.RELEASE</spring.version>
<old.spring.version>3.2.6.RELEASE</old.spring.version>
<com.fasterxml.jackson.core.version>2.4.4</com.fasterxml.jackson.core.version>
<house365.version>1.0.0-SNAPSHOT</house365.version>
<jdk.version>1.8</jdk.version>
</properties>
<repositories>
<repository>
<id>public</id>
<name>public</name>
<url>http://192.168.108.60/nexus/repository/public/</url>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>public</id>
<name>public</name>
<url>http://192.168.108.60/nexus/repository/public/</url>
</pluginRepository>
</pluginRepositories>
<distributionManagement>
<snapshotRepository>
<id>snapshots</id>
<name>Snapshots</name>
<url>http://192.168.108.60/nexus/repository/snapshots/</url>
</snapshotRepository>
<repository>
<id>releases</id>
<name>Releases</name>
<url>http://192.168.108.60/nexus/repository/releases/</url>
</repository>
</distributionManagement>
<dependencies>
<!-- commons begin -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.3.2</version>
</dependency>
<!-- commons end -->
<!-- spring begin -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-expression</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${old.spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- spring end -->
<!-- javax servlet begin -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.2</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!-- javax servlet end -->
<!-- ibatis begin -->
<dependency>
<groupId>org.apache.ibatis</groupId>
<artifactId>ibatis-sqlmap</artifactId>
<version>2.3.4.726</version>
</dependency>
<!-- ibatis end -->
<!-- redis begin -->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.6.0</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
<version>1.4.1.RELEASE</version>
</dependency>
<!-- redis end -->
<!--log begin -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.12</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.6.1</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>1.6.6</version>
</dependency>
<!--log end -->
<!-- json-lib begin -->
<dependency>
<groupId>net.sf.json-lib</groupId>
<artifactId>json-lib</artifactId>
<version>2.4</version>
<classifier>jdk15</classifier>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${com.fasterxml.jackson.core.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>${com.fasterxml.jackson.core.version}</version>
</dependency>
<!-- json-lib end -->
<!-- fastdfs begin -->
<dependency>
<groupId>org.csource.fastdfs</groupId>
<artifactId>org.csource.fastdfs</artifactId>
<version>1.2.4</version>
</dependency>
<!-- fastdfs end -->
<!-- aspectj begin -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.6.8</version>
</dependency>
<!-- aspectj end -->
<!-- jersey-client begin -->
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-bundle</artifactId>
<version>1.18</version>
</dependency>
<dependency>
<groupId>org.codehaus.jettison</groupId>
<artifactId>jettison</artifactId>
<version>1.3.7</version>
</dependency>
<!-- jersey-client end -->
<!-- apache-httpclient begin -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.3.6</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
<version>4.3.3</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.3.6</version>
</dependency>
<!-- apache-httpclient end -->
<!-- house365 begin -->
<dependency>
<groupId>com.house365</groupId>
<artifactId>house365-tags</artifactId>
<version>${house365.version}</version>
</dependency>
<dependency>
<groupId>com.house365</groupId>
<artifactId>house365-util</artifactId>
<version>${house365.version}</version>
</dependency>
<!-- house365 end -->
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.2</version>
<configuration>
<source>${jdk.version}</source>
<target>${jdk.version}</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
/**
* Description: <类功能描述-必填>
* Copyright: Copyright (c)2012
* Company: house365
* @author: duhui
* @version: 1.0
* Create at: 2012-12-21 下午4:22:51
*
* Modification History:
* Date Author Version Description
* ------------------------------------------------------------------
* 2015-1-21 duhui 1.0 如果修改了;必填
*/
package com.house365.beans.system;
import java.io.Serializable;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
/**
* <p>
* 系统领域对象的基类
* </p>
* <br>
* 系统领域对象的基类,实现了Serializable接口。Allen. Lee
* DomainObject还覆写了hashCode()方法和equals()方法。这两个方法都将基于代理主键进行操作。
* 只有代理主键相等,领域对象才相等。如果创建的对象的entityId均未赋值,则直接比较物理地址。
*
* @author duhui
* @version 1.0 , 2014-12-27
* @see
*/
public class DomainObject implements Serializable {
/**
*
*/
private static final long serialVersionUID = 6234793910389347162L;
/**
* 领域对象的代理主键.
*/
private Integer id;
/*-------------------- construtors --------------------*/
/**
* 默认构造函数。
*
*/
public DomainObject() {
}
/**
* 通过代理主键构造领域对象。
*
* @param id
*/
public DomainObject(Integer id) {
this();
this.id = id;
}
/*----------------- public methods --------------------*/
/**
* 获取领域对象代理主键。
*
* @return
*/
public Integer getId() {
return id;
}
/**
* 设置领域对象代理主键。
*
* @param id
*/
public void setId(Integer id) {
this.id = id;
}
/**
* 覆写基类的hashCode方法,如果代理主键不为null,返回Id对应的hashCode值,否则返回基类的hashCode值。
*
* @return
*/
@Override
public int hashCode() {
return new HashCodeBuilder().append(id).toHashCode();
}
/**
* 根据代理主键判断领域对象是否相同。
*
* @see Object#equals(Object)
*/
@Override
public boolean equals(Object target) {
if (target == null) {
return false;
}
if (target == this) {
return true;
}
if (target.getClass() != this.getClass()) {
return false;
}
DomainObject t = (DomainObject) target;
// 如果领域对象的Id为空,直接判断物理地址
if (id == 0 || t.getId() == 0) {
return t == this;
}
return new EqualsBuilder().append(id, t.getId()).isEquals();
}
}
package com.house365.beans.system;
import java.io.Serializable;
/**
* 分页对象<br>
*/
public class Page implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
/**
* 第一页
*/
public static final int FIRST_PAGE = 1;
/**
* 每页10条数
*/
public static final int DEFAULT_PAGE_SIZE = 10;
/**
* 每页5条数
*/
public static final int FIVE_PAGE_SIZE = 5;
/**
* 每页8条数
*/
public static final int EIGHT_PAGE_SIZE = 8;
/**
* 每页20条数
*/
public static final int TWENTY_PAGE_SIZE = 20;
/**
* 每页15条数
*/
public static final int FIFTEEN_PAGE_SIZE = 15;
/**
* 每页有多少条记录
*/
private int pageSize = DEFAULT_PAGE_SIZE;
/**
* 总页数
*/
private int pages;
/**
* 当前页
*/
private int currentPage = 1;
/**
* 总条数
*/
private int records;
/**
*
*/
public Page() {
this(FIRST_PAGE, DEFAULT_PAGE_SIZE);
}
/**
* @param pageSize
*/
public Page(int pageSize) {
this(FIRST_PAGE, pageSize);
}
/**
* @param currentPage
* @param pageSize
*/
public Page(int currentPage, int pageSize) {
this.currentPage = currentPage;
this.pageSize = pageSize;
}
/**
* @param currentPage
* @param pageSize
* @param records
*/
public Page(int currentPage, int pageSize, int records) {
this.currentPage = currentPage;
this.pageSize = pageSize;
this.records = records;
}
/**
* @return the pageSize
*/
public int getPageSize() {
return pageSize;
}
/**
* @param pageSize the pageSize to set
*/
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
/**
* @return the pages
*/
public int getPages() {
return pages;
}
/**
* @param pages the pages to set
*/
public void setPages(int pages) {
this.pages = pages;
}
/**
* @return the currentPage
*/
public int getCurrentPage() {
return currentPage;
}
/**
* @param currentPage the currentPage to set
*/
public void setCurrentPage(int currentPage) {
this.currentPage = currentPage;
}
/**
* 判断是否第一页 <br>
*
* @return
* @see
*/
public boolean isFirstPage() {
return currentPage == 1;
}
/**
* 判断是否最后一页 <br>
*
* @return
* @see
*/
public boolean isLastPage() {
return currentPage == pages;
}
/**
* 当前页第一条的位置<br>
*
* @return
* @see
*/
public int getStartRecord() {
return (currentPage - 1) * pageSize;
}
/**
* 当前页最后一条的位置<br>
*
* @return
* @see
*/
public int getEndRecord() {
return getStartRecord() + getPageSize();
}
/**
* @return the records
*/
public int getRecords() {
return records;
}
/**
* @param records records
*/
public void setRecords(int records) {
this.records = records;
int n = records % pageSize;
if (n > 0) {
pages = records / pageSize + 1;
} else {
pages = records / pageSize;
}
/*
* 如果当前页码小于第一页,强制将其设置成第一页
*/
if (currentPage < FIRST_PAGE) {
currentPage = FIRST_PAGE;
}
/*
* 如果当前页码大于总页码,强制设置成总页码
* 20160126 -by xu 测试反应这个不合理,超出页码返回空就好
*/
// if (pages > 0 && currentPage > pages) {
// currentPage = pages;
// }
}
/**
* 下一页<br>
*
* @return
* @see
*/
public int getNextPage() {
int next = 0;
if (isLastPage()) {
next = pages;
} else {
next = currentPage + 1;
}
currentPage = next;
return next;
}
/**
* 前一页 <br>
*
* @return
* @see
*/
public int getPreviousPage() {
int previous = 0;
if (isFirstPage()) {
previous = 1;
} else {
previous = currentPage - 1;
}
currentPage = previous;
return previous;
}
}
package com.house365.beans.system;
import org.apache.commons.lang3.StringUtils;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;
/**
* 查询参数基类
*
* @param <T>
* 结果对象类型,一般为领域对象
*/
public class QueryParams<T> {
/**
* added by ixr_wang
*/
private T entity;
/**
* 原始查询条件
*/
private Map<String, Object> searchParams;
/**
* 查询过滤
*/
private Map<String, SearchFilter> searchFilters = new HashMap<String, SearchFilter>();
/**
* 排序列 added by andy_luo
*/
private String orderColumn;
/**
* 排序方式。只允许两个值。desc和asc
*/
private String orderMode = "desc";
/**
* 可以通过该参数直接指定查询多少条。
*/
private int limit;
/**
* 分页控制器
*/
private Page paging = new Page();
/**
* 无参构造器
*/
public QueryParams() {
}
/**
* 带查询条件构造器
*
* @param searchParams
* 查询条件
*/
public QueryParams(Map<String, Object> searchParams) {
setSearchParams(searchParams);
}
/**
* @return the limit
*/
public int getLimit() {
return limit;
}
/**
* @param limit
* the limit to set
*/
public void setLimit(int limit) {
this.limit = limit;
}
/**
* @return the orderColumn
*/
public String getOrderColumn() {
return orderColumn;
}
/**
* @param orderColumn
* the orderMode to set
*/
public void setOrderColumn(String orderColumn) {
this.orderColumn = orderColumn;
}
/**
* @return the orderMode
*/
public String getOrderMode() {
return orderMode;
}
/**
* @param orderMode
* the orderMode to set
*/
public void setOrderMode(String orderMode) {
this.orderMode = orderMode;
}
/**
* @return the paging
*/
public Page getPaging() {
return paging;
}
/**
* @param paging
* the paging to set
*/
public void setPaging(Page paging) {
this.paging = paging;
}
/**
* @return the searchParams
*/
public Map<String, Object> getSearchParams() {
return searchParams;
}
/**
* @param searchParams
* the searchParams to set
*/
public void setSearchParams(Map<String, Object> searchParams) {
this.searchParams = searchParams;
buildSearchFilters(searchParams);
}
/**
* 构建过滤条件
*
* @param searchParams
* 查询条件
*/
private void buildSearchFilters(Map<String, Object> searchParams) {
Map<String, Object> tmpSearchParams = new HashMap<String, Object>();
// Trim空格
for (String key : searchParams.keySet()) {
Object value = searchParams.get(key);
if (null != value && value instanceof String) {
value = value.toString().trim();
}
tmpSearchParams.put(key, value);
}
searchParams.clear();
searchParams.putAll(tmpSearchParams);
for (Map.Entry<String, Object> entry : searchParams.entrySet()) {
String key = entry.getKey();
Object value = entry.getValue();
// 如果value为空,不作为筛选条件
if (value == null) {
continue;
}
if (!key.startsWith("ISNOTNULL") && !key.startsWith("ISNULL") && value instanceof String && StringUtils.isBlank((String) value)) {
continue;
}
String[] names = StringUtils.split(key, "_");
int namesLen = names.length;
// 这里预留后两部分,用于类型转换
if (2 > namesLen && 3 < namesLen) {
throw new IllegalArgumentException(key + " is not a valid search filter name");
}
String filedName = names[1];
Operation operation = Operation.valueOf(names[0]);
if (3 <= namesLen) {
String dateStyle = names[2];
try {
value = convert(dateStyle, value);
} catch (ParseException e) {
throw new IllegalArgumentException(key + " is not a date type");
}
}
if(key.startsWith("ISNOTNULL") || key.startsWith("ISNULL")){
this.searchFilters.put(filedName, new SearchFilter("", operation.operator));
}else{
this.searchFilters.put(filedName, new SearchFilter(operation.operator, operation.convertValue(value)));
}
}
}
/**
* 取值转换
*
* @param style
* 类型
* @param value
* 原始值
* @return 转换值
* @throws ParseException
* 解析异常
*/
private Object convert(String style, Object value) throws ParseException {
return new SimpleDateFormat(style).parse((String) value);
}
/**
* @return the searchFilters
*/
public Map<String, SearchFilter> getSearchFilters() {
return searchFilters;
}
/**
* @return the entity
*/
public T getEntity() {
return entity;
}
/**
* @param entity
* the entity to set
*/
public void setEntity(T entity) {
this.entity = entity;
}
/**
* 操作枚举类
*
* @author duhui
*/
enum Operation {
/**
* 等值比较
*/
EQ("="),
/**
* 不等值比较
*/
NOTEQ("!="),
/**
* 大于比较
*/
GT(">"),
/**
* 小于比较
*/
LT("<"),
/**
* 大于等于比较
*/
GTE(">="),
/**
* 小于等于比较
*/
LTE("<="),
/**
* 模糊匹配
*/
LIKE("like"),
IN("in"),
/**
* 反向模糊匹配
*/
NOTLIKE("not like"),
ISNOTNULL("is not null"),
ISNULL("is null"),
REGEXP("regexp");
/**
* 操作符
*/
private String operator;
/**
* 枚举构造器
*
* @param operator 操作符
*/
private Operation(String operator) {
this.operator = operator;
}
/**
* @return the operator
*/
public String getOperator() {
return operator;
}
/**
* 值转换<br>
* 根据操作符的不同构造不同的值形式
*
* @param value 原始值
* @return 改造值
*/
public Object convertValue(Object value) {
switch (this) {
// 当使用like或not like时,需要在value两侧增加%,以达到模糊查询的目的
case LIKE:
case NOTLIKE:
return "%" + value + "%";
default:
return value;
}
}
}
}
package com.house365.beans.system;
import java.io.Serializable;
public class SearchFilter implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
/**
* 操作<br>
* =;!=;&gt;;&lt;;&gt;=;&lt;=;like;not like;
*/
private String operation;
/**
* 比较的值
*/
private Object value;
public SearchFilter() {
// TODO Auto-generated constructor stub
}
public SearchFilter(String operation, Object value) {
setOperation(operation);
setValue(value);
}
public String getOperation() {
return operation;
}
public void setOperation(String operation) {
this.operation = operation;
}
public Object getValue() {
return value;
}
public void setValue(Object value) {
this.value = value;
}
}
package com.house365.beans.system;
import java.io.Serializable;
import java.util.Date;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
/**
* 登录用户属性信息
*/
public final class UserAttributes implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
/**
* 属性列表
*/
private Map<String, Object> attributes;
/**
* 构造属性列表
*
* @param attributes
*/
public UserAttributes(Map<String, Object> attributes) {
this.attributes = attributes;
}
/**
* 获取当前登录人IP
*
* @return 当前登录人IP,null if not login
*/
public String getCurrentUserIp() {
if (null == attributes) {
return null;
} else {
Object obj = attributes.get("ip");
if (null == obj) {
return null;
} else {
return obj.toString();
}
}
}
/**
* 获取登录用户的自然人ID
*
* @return 自然人ID
*/
public Integer getNaturlPersonId() {
if (null == attributes) {
return null;
} else {
Object obj = attributes.get("naturlPersonId");
if (null == obj) {
return null;
} else {
return Integer.parseInt(obj.toString());
}
}
}
/**
* 获取登录用户的公司ID
*
* @return 公司ID
*/
public Integer getCompanyId() {
if (null == attributes) {
return null;
} else {
Object obj = attributes.get("companyId");
if (null == obj) {
return null;
} else {
return Integer.parseInt(obj.toString());
}
}
}
/**
* 获取登录用户登录时间
*
* @return 登录时间
*/
public Date getLoginTime() {
if (null == attributes) {
return null;
} else {
return new Date(Long.parseLong(attributes.get("loginTime")
.toString()));
}
}
/**
* 获取登录用户登出时间
*
* @return 登出时间
*/
public Date getExitTime() {
if (null == null) {
return null;
} else {
return new Date(Long.parseLong(attributes.get("exitTime")
.toString()));
}
}
/**
* 获取登录用户登录类型
*
* @return 登录类型
*/
public Integer getLoginType() {
if (null == attributes) {
return null;
} else {
return Integer.parseInt(attributes.get("loginType").toString());
}
}
/**
* 获取登录用户的登录名
*
* @return 登录名
*/
public String getAccount() {
if (null == attributes) {
return null;
} else {
return attributes.get("account").toString();
}
}
/**
* 获取登录用户的英文名
*
* @return 英文名
*/
public String getNameEn() {
if (null == attributes) {
return null;
} else {
return (String) attributes.get("nameEn");
}
}
/**
* 获取登录用户的中文名
*
* @return 中文名
*/
public String getNameCn() {
if (null == attributes) {
return null;
} else {
return (String) attributes.get("nameCn");
}
}
/**
* 获取登录用户的登录ID
*
* @return 登录ID
*/
public Integer getLoginId() {
if (null == attributes) {
return null;
} else {
Object obj = attributes.get("loginId");
if (null == obj) {
return null;
} else {
return Integer.parseInt(obj.toString());
}
}
}
/**
* 获取登录用户的职员ID
*
* @return 职员ID
*/
public Integer getEmployeeId() {
if (null == attributes) {
return null;
} else {
Object obj = attributes.get("employeeId");
if (null == obj) {
return null;
} else {
return Integer.parseInt(obj.toString());
}
}
}
/**
* 获取用户角色数组
*
* @return 用户角色数组
*/
public String[] getRoles() {
if (null == attributes) {
return new String[] {};
} else {
return StringUtils.split((String) attributes.get("roles"), ",");
}
}
/**
* 获取用户权限数组
*
* @return 用户权限数组
*/
public String[] getPermissions() {
if (null == attributes) {
return new String[] {};
} else {
return StringUtils.split((String) attributes.get("permissions"),
",");
}
}
/**
* 获取用户是否具有指定权限
*
* @param role
* 用于比对的权限
* @return 是否具有该权限<li>true--具有该权限<li>false--不具有该权限
*/
public boolean hasRole(String role) {
String[] roles = getRoles();
if (null == null) {
return false;
} else {
for (String r : roles) {
if (r.equalsIgnoreCase(role)) {
return true;
}
}
return false;
}
}
}
package com.house365.commons.system;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* 死循环线程
*
* @author duhui
*
*/
public abstract class AbstractWhileRunnable implements Runnable {
/**
* 日志记录器
*/
private static final Logger LOGGER = LoggerFactory
.getLogger(AbstractWhileRunnable.class);
/**
* 延时毫秒数
*/
private final long delayTime;
/**
* 构造死循环线程<br>
*
* @param delayTime
* 延时毫秒数 <br>
* 如果设置小于等于0,默认使用1
*/
public AbstractWhileRunnable(final long delayTime) {
if (0 < delayTime) {
this.delayTime = delayTime;
} else {
this.delayTime = 1;
}
}
/**
* 构造死循环线程<br>
*
* 默认使用延时毫秒数为1
*/
public AbstractWhileRunnable() {
this(1);
}
/*
* (non-Javadoc)
*
* @see java.lang.Runnable#run()
*/
public final void run() {
while (true) {
try {
execute();
} catch (Throwable ex) {
LOGGER.warn("线程执行过程发生异常", ex);
} finally {
try {
Thread.sleep(getDelayTime());
} catch (Throwable ex) {
LOGGER.warn("线程睡眠过程发生异常", ex);
}
}
}
}
/**
* 获取延时毫秒数
*
* @return 延时毫秒数
*/
private final long getDelayTime() {
return this.delayTime;
}
/**
* 业务执行
*/
protected abstract void execute() throws Exception;
}
package com.house365.commons.system;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
/**
* 注解工具
*
* @author duhui
*
*/
public class AnnotationUtils {
/**
* 获取一个方法的所有注解
*
* @param method
* @return
*/
public static Annotation[] getAnnotations(Method method) {
return method.getAnnotations();
}
/**
* 获取方法的一个注解类型
*
* @param method
* @param annotationType
* @return
*/
public static Annotation getAnnotation(Method method, Class annotationType) {
return method.getAnnotation(annotationType);
}
/**
* 查找一个方法是有某注解
*
* @param method
* @param annotationType
* @return
*/
public static Annotation findAnnotation(Method method, Class annotationType) {
Annotation annotation = getAnnotation(method, annotationType);
Class cl = method.getDeclaringClass();
do {
if (annotation != null)
break;
cl = cl.getSuperclass();
if (cl == null || cl.equals(Object.class))
break;
try {
Method equivalentMethod = cl.getDeclaredMethod(
method.getName(), method.getParameterTypes());
annotation = getAnnotation(equivalentMethod, annotationType);
} catch (NoSuchMethodException ex) {
}
} while (true);
return annotation;
}
/**
* 查找一个类的某种注解类型
*
* @param clazz
* @param annotationType
* @return
*/
public static Annotation findAnnotation(Class clazz, Class annotationType) {
Annotation annotation = clazz.getAnnotation(annotationType);
if (annotation != null)
return annotation;
Class clazzes[] = clazz.getInterfaces();
int len = clazzes.length;
for (int i = 0; i < len; i++) {
Class ifc = clazzes[i];
annotation = findAnnotation(ifc, annotationType);
if (annotation != null)
return annotation;
}
if (clazz.getSuperclass() == null
|| Object.class.equals(clazz.getSuperclass()))
return null;
else
return findAnnotation(clazz.getSuperclass(), annotationType);
}
/**
* 查找包含某种注解类型的Class类型的Class
*
* @param annotationType
* @param clazz
* @return
*/
public static Class findAnnotationDeclaringClass(Class annotationType,
Class clazz) {
if (clazz == null || clazz.equals(Object.class))
return null;
else
return isAnnotationDeclaredLocally(annotationType, clazz) ? clazz
: findAnnotationDeclaringClass(annotationType,
clazz.getSuperclass());
}
/**
* 检查一个类是否包含一个特定的注解类型
*
* @param annotationType
* @param clazz
* @return
*/
public static boolean isAnnotationDeclaredLocally(Class annotationType,
Class clazz) {
boolean declaredLocally = false;
Iterator i$ = Arrays.asList(clazz.getDeclaredAnnotations()).iterator();
do {
if (!i$.hasNext())
break;
Annotation annotation = (Annotation) i$.next();
if (!annotation.annotationType().equals(annotationType))
continue;
declaredLocally = true;
break;
} while (true);
return declaredLocally;
}
/**
* 如果指定类型的注释存在于此元素上,则返回 true,否则返回 false
*
* @param annotationType
* @param clazz
* @return
*/
public static boolean isAnnotationInherited(Class annotationType,
Class clazz) {
return clazz.isAnnotationPresent(annotationType)
&& !isAnnotationDeclaredLocally(annotationType, clazz);
}
/**
* 获取注解所有的属性
*
* @param annotation
* @return
*/
public static Map getAnnotationAttributes(Annotation annotation) {
Map attrs = new HashMap();
Method methods[] = annotation.annotationType().getDeclaredMethods();
for (int j = 0; j < methods.length; j++) {
Method method = methods[j];
if (method.getParameterTypes().length != 0
|| method.getReturnType() == Void.TYPE)
continue;
try {
attrs.put(method.getName(),
method.invoke(annotation, new Object[0]));
} catch (Exception ex) {
throw new IllegalStateException(
"Could not obtain annotation attribute values", ex);
}
}
return attrs;
}
/**
* 获取注解对应的value值
*
* @param annotation
* @return
*/
public static Object getValue(Annotation annotation) {
return getValue(annotation, "value");
}
/**
* 获取注解对应的属性值
*
* @param annotation
* @param attributeName
* @return
*/
public static Object getValue(Annotation annotation, String attributeName) {
try {
Method method = annotation.annotationType().getDeclaredMethod(
attributeName, new Class[0]);
return method.invoke(annotation, new Object[0]);
} catch (Exception ex) {
return null;
}
}
/**
* 获取注解默认value值
*
* @param annotation
* @return
*/
public static Object getDefaultValue(Annotation annotation) {
return getDefaultValue(annotation, "value");
}
/**
* 获取注解默认属性值
*
* @param annotation
* @param attributeName
* @return
*/
public static Object getDefaultValue(Annotation annotation,
String attributeName) {
return getDefaultValue(annotation.annotationType(), attributeName);
}
/**
* 获得注解的value的值
*
* @param annotationType
* @return
*/
public static Object getDefaultValue(Class annotationType) {
return getDefaultValue(annotationType, "value");
}
/**
* 获取注解的value的值
*
* @param annotationType
* @param attributeName
* @return
*/
public static Object getDefaultValue(Class annotationType,
String attributeName) {
try {
Method method = annotationType.getDeclaredMethod(attributeName,
new Class[0]);
return method.getDefaultValue();
} catch (Exception ex) {
return null;
}
}
/**
*
*/
static final String VALUE = "value";
}
package com.house365.commons.system;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.apache.commons.beanutils.PropertyUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* 属性自动填充工具
*
* @author duhui
*
*/
public abstract class AutoFieldsUtils {
/**
* 日志记录器
*/
private static final Logger LOGGER = LoggerFactory.getLogger(AutoFieldsUtils.class);
/**
* createUserid
*/
private static final String AUTO_CREATE_USER_ID_FIELD = "createUserid";
/**
* createUsername
*/
private static final String AUTO_CREATE_USER_NAME_FIELD = "createUsername";
/**
* createDatetime
*/
private static final String AUTO_CREATE_DATETIME_FIELD = "createDatetime";
/**
* createIp
*/
private static final String AUTO_CREATE_IP_FIELD = "createIp";
/**
* updateUserid
*/
private static final String AUTO_UPDATE_USER_ID_FIELD = "updateUserid";
/**
* updateUsername
*/
private static final String AUTO_UPDATE_USER_NAME_FIELD = "updateUsername";
/**
* updateDatetime
*/
private static final String AUTO_UPDATE_DATETIME_FIELD = "updateDatetime";
/**
* updateIp
*/
private static final String AUTO_UPDATE_IP_FIELD = "updateIp";
/**
* 缓存指定对象是否有指定属性createUserid
*/
private static final Map<String, Boolean> AUTO_CREATE_USER_ID_CACHE = new ConcurrentHashMap<String, Boolean>();
/**
* 缓存指定对象是否有指定属性createUsername
*/
private static final Map<String, Boolean> AUTO_CREATE_USER_NAME_CACHE = new ConcurrentHashMap<String, Boolean>();
/**
* 缓存指定对象是否有指定属性createDatetime
*/
private static final Map<String, Boolean> AUTO_CREATE_DATETIME_CACHE = new ConcurrentHashMap<String, Boolean>();
/**
* 缓存指定对象是否有指定属性createIp
*/
private static final Map<String, Boolean> AUTO_CREATE_IP_CACHE = new ConcurrentHashMap<String, Boolean>();
/**
* 缓存指定对象是否有指定属性updateUserid
*/
private static final Map<String, Boolean> AUTO_UPDATE_USER_ID_CACHE = new ConcurrentHashMap<String, Boolean>();
/**
* 缓存指定对象是否有指定属性updateUsername
*/
private static final Map<String, Boolean> AUTO_UPDATE_USER_NAME_CACHE = new ConcurrentHashMap<String, Boolean>();
/**
* 缓存指定对象是否有指定属性updateDatetime
*/
private static final Map<String, Boolean> AUTO_UPDATE_DATETIME_CACHE = new ConcurrentHashMap<String, Boolean>();
/**
* 缓存指定对象是否有指定属性updateIp
*/
private static final Map<String, Boolean> AUTO_UPDATE_IP_CACHE = new ConcurrentHashMap<String, Boolean>();
/**
* 设置自动属性
*
* @param entity 需要填充的对象
* @param create 是否为创建操作,创建时只设置创建时间、创建IP、创建人ID,创建人名称,否则只设置修改时间、修改IP、修改人ID、修改人姓名
*/
public void setAutoFields(Object entity, boolean create) {
try {
// 顺序切勿调整,这样可以保证在未登录时,依然可以尽可能设置一些值
if (create) {
setCreateField(entity);
} else {
setUpdateField(entity);
}
} catch (Exception e) {
LOGGER.warn("用户信息无法获取,操作对象的用户相关信息将无法填充");
}
}
/**
* 设置修改参数
*
* @param entity 实体
* @throws Exception 异常
*/
private void setUpdateField(Object entity) throws Exception {
// 修改时间
setField(entity, AUTO_UPDATE_DATETIME_CACHE, AUTO_UPDATE_DATETIME_FIELD, getCurrentTimestamp());
// 请求IP
setField(entity, AUTO_UPDATE_IP_CACHE, AUTO_UPDATE_IP_FIELD, getCurrentUserIp());
// 修改用户ID
setField(entity, AUTO_UPDATE_USER_ID_CACHE, AUTO_UPDATE_USER_ID_FIELD, getCurrentUserId());
// 修改用户姓名
setField(entity, AUTO_UPDATE_USER_NAME_CACHE, AUTO_UPDATE_USER_NAME_FIELD, getCurrentUserName());
}
/**
* 设置创建参数
*
* @param entity 实体
* @throws Exception 异常
*/
private void setCreateField(Object entity) throws Exception {
// 创建时间
setField(entity, AUTO_CREATE_DATETIME_CACHE, AUTO_CREATE_DATETIME_FIELD, getCurrentTimestamp());
// 请求IP
setField(entity, AUTO_CREATE_IP_CACHE, AUTO_CREATE_IP_FIELD, getCurrentUserIp());
// 创建用户ID
setField(entity, AUTO_CREATE_USER_ID_CACHE, AUTO_CREATE_USER_ID_FIELD, getCurrentUserId());
// 创建用户姓名
setField(entity, AUTO_CREATE_USER_NAME_CACHE, AUTO_CREATE_USER_NAME_FIELD, getCurrentUserName());
}
/**
* 设置对象属性
*
* @param entity the entity
* @param cache the cache
* @param fieldName 需要设置的属性
* @param fieldValue 属性值
* @throws Exception throw Exception
*/
private void setField(Object entity, Map<String, Boolean> cache, String fieldName, Object fieldValue)
throws Exception {
Boolean needSet = isNeedSet(entity, cache, fieldName);
if (needSet) {
if (null == fieldValue) {
if (LOGGER.isWarnEnabled()) {
LOGGER.warn("set " + fieldName + " for " + entity.getClass().getName() + " is null");
}
} else {
PropertyUtils.setProperty(entity, fieldName, fieldValue);
}
}
}
/**
* 是否需要设置<br>
* 当存在对应类信息,则获取,不存在则获取是否包含对应属性,将结果缓存起来以便后续使用
*
* @param entity
* @param cache
* @param fieldName
* @return
* @throws Exception
*/
private Boolean isNeedSet(Object entity, Map<String, Boolean> cache, String fieldName) throws Exception {
String clazzName = entity.getClass().getName();
Boolean needSet = cache.get(clazzName);
if (needSet == null) {
needSet = hasField(entity, fieldName);
cache.put(clazzName, needSet);
}
return needSet;
}
/**
* 是否包含指定属性
*
* @param entity
* @param fieldName
* @return
*/
private Boolean hasField(Object entity, String fieldName) {
Boolean result;
try {
result = PropertyUtils.getPropertyDescriptor(entity, fieldName) != null;
} catch (Throwable e) {
result = false;
}
return result;
}
/**
* 获取当前用户ID
*
* @return 当前用户ID
*/
protected abstract Integer getCurrentUserId();
/**
* 获取当前用户姓名
*
* @return 当前用户姓名
*/
protected abstract String getCurrentUserName();
/**
* 获取当前用户IP
*
* @return 当前用户IP
*/
protected abstract String getCurrentUserIp();
/**
* 获取当前时间
*
* @return 当前时间
*/
protected static Date getCurrentTimestamp() {
return new Date();
}
}
\ No newline at end of file
package com.house365.commons.system;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* 自定义注释注解
*
* @author duhui
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.TYPE, ElementType.METHOD, ElementType.FIELD, ElementType.PARAMETER })
public @interface Description {
// 方法的描述
public String desc();
// 返回值的描述
public String returnDesc() default "";
// 类型
public enum type {
STRING, SHORT, INT, BOOLEAN, LONG, INTEGER, OBJECT
};
// 类型
public type type() default type.STRING;
// 参数列表
public DescriptionParameter[] parameters() default @DescriptionParameter(name = "", nameDesc = "");
}
package com.house365.commons.system;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* 自定义参数注释注解
*
* @author duhui
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface DescriptionParameter {
// 参数类型
public enum ParameterType {
STRING, SHORT, INT, BOOL, LONG, OBJECT
};
// 参数名
public String name();
// 参数描述
public String nameDesc();
// 参数类型
public ParameterType type() default ParameterType.STRING;
}
package com.house365.commons.system;
import com.google.common.base.Joiner;
import com.house365.web.util.MemoryPropertyPlaceholderConfigurer;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.csource.common.MyException;
import org.csource.common.NameValuePair;
import org.csource.fastdfs.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
/**
* FastDFS文件操作工具类
*
* @author bvnb
* @version [v1.0.0, 2015年1月24日]
* @see [相关类/方法](可选)
* @since [产品/模块版本] (可选)
*/
public final class FastDFSUtil {
private static final Logger logger = LoggerFactory.getLogger(FastDFSUtil.class);
private static final String EMPTY = "";
private static TrackerClient trackerClient;
private static TrackerServer trackerServer;
private static StorageServer storageServer;
private static StorageClient storageClient;
//文件URL通用前缀
private static String fileUrlPrefix;
//服务器环境:生产环境production或测试环境test
private static String env;
static {
try {
//从配置文件中获取
fileUrlPrefix = MemoryPropertyPlaceholderConfigurer.getContextProperty("system.default.fileServer");
env = MemoryPropertyPlaceholderConfigurer.getContextProperty("system.env");
String classPath = new File(FastDFSUtil.class.getResource("/").getFile()).getCanonicalPath();
String fdfsConf = "/fdfs_client.conf";
if ("production".equalsIgnoreCase(env)) {
fdfsConf = "/fdfs_client_" + env + ".conf";
}
String configFilePath = classPath + fdfsConf;
logger.debug("配置文件:" + configFilePath);
ClientGlobal.init(configFilePath);
trackerClient = new TrackerClient();
trackerServer = trackerClient.getConnection();
storageClient = new StorageClient(trackerServer, storageServer);
} catch (IOException e) {
e.printStackTrace();
} catch (MyException e) {
e.printStackTrace();
}
}
/**
* 上传本地文件
*
* @param localFilename 本地文件绝对路径
* @return 可访问的文件URL;<br>
* return <b>""</b> if fail
*/
public static String uploadFile(String localFilename) {
String fileUrl = EMPTY;
List<String> result = uploadFileAndGetAll(localFilename);
int indexOfFileUlr = 2; // 文件 URL 在结果数组中的索引
if (CollectionUtils.isNotEmpty(result) && result.size() > indexOfFileUlr) {
fileUrl = result.get(indexOfFileUlr);
}
return fileUrl;
}
/**
* 上传本地文件,返回 FastDFS 文件信息
*
* @param localFilename 本地文件绝对路径
* @return 3 elements string list if success:<br>
* <ul><li>results[0]: the group name to store the file </li></ul>
* <ul><li>results[1]: the new created filename</li></ul>
* <ul><li>results[2]: the new created file url</li></ul>
* return <b>empty list</b> if fail
*/
public static List<String> uploadFileAndGetAll(String localFilename) {
File file = new File(localFilename);
if (!file.exists() || !file.isFile()) {
logger.error("当前文件不存在或不是文件,上传失败");
return null;
}
List<String> list = new ArrayList<String>();
String[] results = new String[3];
String fileUrl = EMPTY;
String fileExt = getFileSuffix(localFilename);
try {
NameValuePair[] metaList = new NameValuePair[3];
metaList[0] = new NameValuePair("fileName", file.getName());
metaList[1] = new NameValuePair("fileExt", fileExt);
metaList[2] = new NameValuePair("fileLength", EMPTY + file.length());
logger.info("*******************metaList[0]*************************" + metaList[0]);
logger.info("*******************metaList[1]*************************" + metaList[1]);
logger.info("*******************metaList[2]*************************" + metaList[2]);
results = storageClient.upload_file(localFilename, fileExt, metaList);
if ("production".equalsIgnoreCase(env)) {
fileUrlPrefix = MemoryPropertyPlaceholderConfigurer.getContextProperty("fastdfs.storage." + results[0]);
}
fileUrl = fileUrlPrefix + results[1];
list.add(results[0]);
list.add(results[1]);
list.add(fileUrl);
logger.debug("groupName:" + results[0] + ",remoteFilename:" + results[1]);
} catch (IOException e) {
e.printStackTrace();
} catch (MyException e) {
e.printStackTrace();
}
return list;
}
/**
* 以流的方式上传文件
*
* @param inStream
* @param uploadFileName
* @return 可访问的文件URL
* @throws IOException
*/
public static String uploadFileByStream(InputStream inStream, String uploadFileName) throws IOException {
byte[] fileBuffer = new byte[inStream.available()];
inStream.read(fileBuffer);
return uploadFileByByteArray(fileBuffer, uploadFileName);
}
/**
* 以字节数组的方式上传文件
*
* @param fileBuffer
* @param uploadFileName
* @return 可访问的文件URL
* @throws IOException
*/
public static String uploadFileByByteArray(byte[] fileBuffer, String uploadFileName) throws IOException {
String fileExtName = EMPTY;
if (uploadFileName.contains(".")) {
fileExtName = getFileSuffix(uploadFileName);
} else {
logger.error("Fail to upload file, because the format of filename is illegal.");
return EMPTY;
}
NameValuePair[] metaList = new NameValuePair[3];
metaList[0] = new NameValuePair("fileName", uploadFileName);
metaList[1] = new NameValuePair("fileExtName", fileExtName);
metaList[2] = new NameValuePair("fileLength", String.valueOf(fileBuffer.length));
String remoteFilename = EMPTY;
try {
// results[0]: groupName, results[1]: remoteFilename.
logger.info("=fileBuffer===" + fileBuffer + "==fileExtName=" + fileExtName + "==metaList==" + metaList);
String[] results = storageClient.upload_file(fileBuffer, fileExtName, metaList);
if ("production".equalsIgnoreCase(env)) {
fileUrlPrefix = MemoryPropertyPlaceholderConfigurer.getContextProperty("fastdfs.storage." + results[0]);
}
//根据group 切换图片域名
logger.info("=fileUrlPrefix===" + fileUrlPrefix + "==results[0]=" + results[0] + "==results[1]=" + results[1] );
logger.info("*******************results*************************" + Joiner.on(",").join(results));
remoteFilename = fileUrlPrefix + results[1];
logger.info("**************remoteFilename************************" + remoteFilename);
} catch (MyException e) {
logger.error(e.getMessage() + "Upload file " + uploadFileName + " fails", e);
}
return remoteFilename;
}
/**
* 获取文件后缀名,不含.
*
* @param fileName
* @return 文件后缀
*/
public static String getFileSuffix(String fileName) {
String suffix = EMPTY;
if (!StringUtils.isBlank(fileName)) {
suffix = fileName.substring(fileName.lastIndexOf('.') + 1);
}
return suffix;
}
/**
* 从 storage server 删除指定文件,返回 0 表示删除成功
*
* @param remote_filename
* @return 0 for success, none zero for fail (error code)
*/
public static int deleteFile(String remote_filename, String group_name) throws IOException, MyException {
int result = storageClient.delete_file(group_name, remote_filename);
return result;
}
}
package com.house365.commons.system;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
/**
* 泛型工具
*
* @author duhui
*
*/
public class GenericsUtils {
/**
* 通过反射,获得定义Class时声明的父类的范型参数的类型.<br>
* 如public CusCustomerDaoImpl extends DefaultDaoImpl&lt;CusCustomerEntity&gt;返回
* <code>com.house365.app.valueobject.entity.crm.CusCustomerEntity</code>
*
* @param clazz
* 内省类
* @return 第一个泛型参数类型, 当不能确定时,返回 <code>Object.class</code>
*/
public static Class<?> getSuperClassGenricType(Class<?> clazz) {
return getSuperClassGenricType(clazz, 0);
}
/**
* 通过反射,获得定义Class时声明的父类的范型参数的类型.<br>
* 如public CusCustomerDaoImpl extends DefaultDaoImpl&lt;CusCustomerEntity&gt;返回
* <code>com.house365.app.valueobject.entity.crm.CusCustomerEntity</code>
*
* @param clazz
* 内省类
* @param index
* 泛型参数索引,从0开始
* @return 指定索引的泛型参数类型, 当不能确定时,返回 <code>Object.class</code>
*/
public static Class<?> getSuperClassGenricType(Class<?> clazz, int index) throws IndexOutOfBoundsException {
Type genType = clazz.getGenericSuperclass();
if (!(genType instanceof ParameterizedType)) {
return Object.class;
}
Type[] params = ((ParameterizedType) genType).getActualTypeArguments();
if (index >= params.length || index < 0) {
return Object.class;
}
if (!(params[index] instanceof Class)) {
return Object.class;
}
return (Class<?>) params[index];
}
}
\ No newline at end of file
/*
* Copyright (C), 2002-2015, 江苏三六五网络股份有限公司
* FileName: ImUtils.java
* Author: jiangzhou
* Date: 2015年6月11日 上午9:09:35
* Description:
* History:
* <author> <time> <version> <desc>
* 修改人姓名 修改时间 版本号 描述
*/
package com.house365.commons.system;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.house365.web.util.MemoryPropertyPlaceholderConfigurer;
/**
* IM发送方法
*
* @author jiangzhou
* @version [v1.0.0, 2015年2月11日]
* @see [相关类/方法](可选)
* @since [产品/模块版本] (可选)
*/
public class ImUtils {
/**
* 日志记录器
*/
private static final Logger LOGGER = LoggerFactory.getLogger(ImUtils.class);
/**
*
* 调用IM发送消息接口 发送IM找房内容
*
* @author jiangzhou
* @version [v1.0.0, 2015年2月11日]
* @param msg 发送内容
* @throws Exception
* @since [产品/模块版本](可选)
*/
@SuppressWarnings("rawtypes")
public static String sendIminfo(List phonlist, String msg, String json) {
// 调用接口返回值
String jsonStr = "";
String phone = "";
// 取得IM接口URL
String imUrl = MemoryPropertyPlaceholderConfigurer.getContextProperty("system.im.sendUrl");
if (null == imUrl) {
return "";
}
try {
// 设置IM内容编码
msg = URLEncoder.encode(msg, "UTF-8");
json = URLEncoder.encode(json, "UTF-8");
if(phonlist.size()>0){
phone= phonlist.toString().replace("[", "").replace("]", "").replace(" ", "");
}
imUrl = imUrl + "&" + "ids=" + phone + "&msgmeta=" + json + "&msg=" + msg;
URL url = new URL(imUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
String line;
while ((line = in.readLine()) != null) {
jsonStr += line;
}
in.close();
} catch (Exception e) {
LOGGER.error("IM接口异常:发送IM失败!");
}
return jsonStr;
}
}
package com.house365.commons.system;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* IP工具
*
* @author duhui
*
*/
public class IpUtils {
/**
* 日志记录器
*/
private static final Logger LOGGER = LoggerFactory.getLogger(IpUtils.class);
/**
* 主机名
*/
private static String hostName = "";
/**
* IP
*/
private static String ip = "";
/**
* MAC地址
*/
private static String macAddress = "";
/**
* 网络地址列表
*/
private static InetAddress[] inetAddresses = null;
/**
* @return the hostName
*/
public static final String getHostName() {
if (StringUtils.isEmpty(hostName)) {
synchronized (IpUtils.class) {
if (StringUtils.isEmpty(hostName)) {
bindingIp();
}
}
}
return hostName;
}
/**
* @return the ip
*/
public static final String getIp() {
if (StringUtils.isEmpty(ip)) {
synchronized (IpUtils.class) {
if (StringUtils.isEmpty(ip)) {
bindingIp();
}
}
}
return ip;
}
/**
* @return the macAddress
*/
public static final String getMacAddress() {
if (StringUtils.isEmpty(macAddress)) {
synchronized (IpUtils.class) {
if (StringUtils.isEmpty(macAddress)) {
bindingIp();
}
}
}
return macAddress;
}
/**
* @return the inetAddresses
*/
public static final InetAddress[] getInetAddresses() {
if (ArrayUtils.isEmpty(inetAddresses)) {
synchronized (IpUtils.class) {
if (ArrayUtils.isEmpty(inetAddresses)) {
bindingIp();
}
}
}
return inetAddresses;
}
/**
* 绑定IP
*/
private static final void bindingIp() {
ProcessBuilder processBuilder = null;
Process process = null;
try {
processBuilder = new ProcessBuilder("ifconfig");
process = processBuilder.start();
} catch (IOException ex) {
processBuilder = new ProcessBuilder("ipconfig");
try {
process = processBuilder.start();
} catch (IOException e) {
return;
}
}
BufferedReader br = new BufferedReader(new InputStreamReader(
process.getInputStream()));
String line = null;
try {
line = br.readLine();
while (!line.contains("www.cdc.com")) {
line = br.readLine();
}
} catch (IOException ex) {
return;
}
int beginIndex = line.indexOf("www.cdc.com");
int endIndex = line.indexOf(' ', beginIndex);
if (-1 == endIndex) {
endIndex = line.length();
}
line = line.substring(beginIndex, endIndex);
InetAddress inetAddress;
try {
inetAddress = InetAddress.getByName(line);
hostName = inetAddress.getHostName();
ip = inetAddress.getHostAddress();
inetAddresses = InetAddress.getAllByName(hostName);
bindingMacAddress(inetAddress);
} catch (Exception ex) {
LOGGER.error("获取本地IP失败", ex);
}
}
/**
* 绑定MAC地址
*
* @throws SocketException
*/
private static void bindingMacAddress(InetAddress inetAddress)
throws Exception {
NetworkInterface ni = NetworkInterface.getByInetAddress(inetAddress);
byte[] macs = ni.getHardwareAddress();
StringBuffer macBuffer = new StringBuffer(32);
String mac = "";
for (int i = 0; i < macs.length; i++) {
mac = Integer.toHexString(macs[i] & 0xFF);
if (1 == mac.length()) {
mac = '0' + mac;
}
macBuffer.append(mac + "-");
}
macBuffer.deleteCharAt(macBuffer.length() - 1);
macAddress = macBuffer.toString();
}
/**
* 获取完整IP
*
* @return 完整IP<br>
* hostName/ip/macAddress
*/
public static final String fullIp() {
StringBuffer buffer = new StringBuffer();
buffer.append(getHostName());
buffer.append("/");
buffer.append(getIp());
buffer.append("/");
buffer.append(getMacAddress());
return buffer.toString();
}
/**
* 获取简易完整IP
*
* @return 简易完整IP<br>
* hostName/ip
*/
public static final String sampleFullIp() {
StringBuffer buffer = new StringBuffer();
buffer.append(getHostName());
buffer.append("/");
buffer.append(getIp());
return buffer.toString();
}
public static void main(String[] args) {
try {
System.out.println(IpUtils.getHostName());
System.out.println(IpUtils.getInetAddresses());
System.out.println(IpUtils.getIp());
System.out.println(IpUtils.getMacAddress());
} catch (Exception e) {
}
}
}
package com.house365.commons.system;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.Locale;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.Header;
import org.apache.http.HttpHost;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.ProtocolException;
import org.apache.http.client.CircularRedirectException;
import org.apache.http.client.RedirectStrategy;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpHead;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.client.utils.URIUtils;
import org.apache.http.impl.client.RedirectLocations;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.Args;
import org.apache.http.util.Asserts;
import org.apache.http.util.TextUtils;
/**
* Created by 365 on 2016/1/13.
*/
public class MyRedirectStrategy implements RedirectStrategy{
private final Log log = LogFactory.getLog(getClass());
/**
* @deprecated (4.3) use {@link HttpClientContext#REDIRECT_LOCATIONS}.
*/
@Deprecated
public static final String REDIRECT_LOCATIONS = "http.protocol.redirect-locations";
public static final MyRedirectStrategy INSTANCE = new MyRedirectStrategy();
/**
* Redirectable methods.
*/
private static final String[] REDIRECT_METHODS = new String[]{HttpGet.METHOD_NAME, HttpHead.METHOD_NAME};
public MyRedirectStrategy() {
super();
}
public boolean isRedirected(
final HttpRequest request, final HttpResponse response, final HttpContext context
) throws ProtocolException {
Args.notNull(request, "HTTP request");
Args.notNull(response, "HTTP response");
final int statusCode = response.getStatusLine().getStatusCode();
final String method = request.getRequestLine().getMethod();
final Header locationHeader = response.getFirstHeader("location");
switch (statusCode) {
case HttpStatus.SC_MOVED_TEMPORARILY:
return isRedirectable(method) && locationHeader != null;
case HttpStatus.SC_MOVED_PERMANENTLY:
case HttpStatus.SC_TEMPORARY_REDIRECT:
return isRedirectable(method);
case HttpStatus.SC_SEE_OTHER:
return true;
default:
return false;
} //end of switch
}
public URI getLocationURI(
final HttpRequest request, final HttpResponse response, final HttpContext context
) throws ProtocolException {
Args.notNull(request, "HTTP request");
Args.notNull(response, "HTTP response");
Args.notNull(context, "HTTP context");
final HttpClientContext clientContext = HttpClientContext.adapt(context);
//get the location header to find out where to redirect to
final Header locationHeader = response.getFirstHeader("location");
if (locationHeader == null) {
// got a redirect response, but no location header
throw new ProtocolException(
"Received redirect response " + response.getStatusLine() + " but no location header");
}
final String location = locationHeader.getValue();
if (this.log.isDebugEnabled()) {
this.log.debug("Redirect requested to location '" + location + "'");
}
final RequestConfig config = clientContext.getRequestConfig();
URI uri = createLocationURI(location);
// rfc2616 demands the location value be a complete URI
// Location = "Location" ":" absoluteURI
try {
if (!uri.isAbsolute()) {
if (!config.isRelativeRedirectsAllowed()) {
throw new ProtocolException("Relative redirect location '" + uri + "' not allowed");
}
// Adjust location URI
final HttpHost target = clientContext.getTargetHost();
Asserts.notNull(target, "Target host");
final URI requestURI = new URI(request.getRequestLine().getUri());
final URI absoluteRequestURI = URIUtils.rewriteURI(requestURI, target, false);
uri = URIUtils.resolve(absoluteRequestURI, uri);
}
} catch (final URISyntaxException ex) {
throw new ProtocolException(ex.getMessage(), ex);
}
RedirectLocations redirectLocations = (RedirectLocations) clientContext.getAttribute(
HttpClientContext.REDIRECT_LOCATIONS);
if (redirectLocations == null) {
redirectLocations = new RedirectLocations();
context.setAttribute(HttpClientContext.REDIRECT_LOCATIONS, redirectLocations);
}
if (!config.isCircularRedirectsAllowed()) {
if (redirectLocations.contains(uri)) {
throw new CircularRedirectException("Circular redirect to '" + uri + "'");
}
}
redirectLocations.add(uri);
return uri;
}
/**
* @since 4.1
*/
protected URI createLocationURI(final String location) throws ProtocolException {
try {
URL url = new URL(location);
URI uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(), url.getQuery(), null);
final URIBuilder b = new URIBuilder(uri.normalize());
final String host = b.getHost();
if (host != null) {
b.setHost(host.toLowerCase(Locale.US));
}
final String path = b.getPath();
if (TextUtils.isEmpty(path)) {
b.setPath("/");
}
return b.build();
} catch (final URISyntaxException ex) {
throw new ProtocolException("Invalid redirect URI: " + location, ex);
} catch (MalformedURLException ex) {
throw new ProtocolException("Invalid redirect URI: " + location, ex);
}
}
/**
* @since 4.2
*/
protected boolean isRedirectable(final String method) {
for (final String m : REDIRECT_METHODS) {
if (m.equalsIgnoreCase(method)) {
return true;
}
}
return false;
}
public HttpUriRequest getRedirect(
final HttpRequest request, final HttpResponse response, final HttpContext context
) throws ProtocolException {
final URI uri = getLocationURI(request, response, context);
final String method = request.getRequestLine().getMethod();
if (method.equalsIgnoreCase(HttpHead.METHOD_NAME)) {
return new HttpHead(uri);
} else if (method.equalsIgnoreCase(HttpGet.METHOD_NAME)) {
return new HttpGet(uri);
} else {
final int status = response.getStatusLine().getStatusCode();
if (status == HttpStatus.SC_TEMPORARY_REDIRECT) {
return RequestBuilder.copy(request).setUri(uri).build();
} else {
return new HttpGet(uri);
}
}
}
}
package com.house365.commons.system;
import org.apache.commons.lang3.StringUtils;
import javax.servlet.http.HttpServletRequest;
/**
* 远程IP工具
*
* @author chengjianfang
* @version v1.0.0 2015-03-18
*/
public class RemoteIpUtils {
/**
* 获取IP地址
*
* @param request HTTP请求
* @return IP地址
*/
public static final String getIpAddr(HttpServletRequest request) {
String ip = request.getHeader("x-forwarded-for");
if (notRealIp(ip)) {
ip = request.getHeader("Proxy-Client-IP");
if (notRealIp(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
if (notRealIp(ip)) {
ip = request.getRemoteAddr();
}
}
}
return ip;
}
/**
* 是否非真实IP
*
* @param ip IP值
* @return 是否非真实IP<li>true--不是真实IP<li>false--是真实IP
*/
private static final boolean notRealIp(final String ip) {
return StringUtils.isEmpty(ip) || StringUtils.equalsIgnoreCase("unknown", ip);
}
}
package com.house365.commons.system;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.List;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.NameValuePair;
import org.apache.http.client.utils.HttpClientUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.WebResource;
/**
* 访问外部接口的工具类
* @author zhaodeshan
* @version [版本号, 2015年1月31日]
* @see [相关类/方法](可选)
* @since [产品/模块版本] (可选)
*/
public final class RestUtil {
private static final Logger LOG = LoggerFactory.getLogger(RestUtil.class);
/**
* 获取外部接口返回的JSON对象
* @author zhaodeshan
* @version [版本号, 2015年1月31日]
* @param url 请求地址
* @param queryParams 请求参数
* @param claxx 要转换的对象类型
* @return 对象
* @throws JsonParseException
* @throws JsonMappingException
* @throws IOException
* @since [产品/模块版本](可选)
*/
public static <T> T getForObject(String url,List<NameValuePair> queryParams,Class<T> claxx) throws JsonParseException, JsonMappingException, IOException
{
if (StringUtils.isBlank(url)) {
LOG.error("请求Url不能为空!");
return null;
}
String result = getForString(url, queryParams);
if (StringUtils.isBlank(result)) {
return null;
}
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
return mapper.readValue(result, claxx);
}
/**
* 直接获取外部接口返回的JSON字符串
* @author zhaodeshan
* @version [版本号, 2015年1月31日]
* @param url 请求地址
* @param queryParams 请求参数
* @return JSON字符串
* @since [产品/模块版本](可选)
*/
public static String getForString(String url,List<NameValuePair> queryParams)
{
Client client = Client.create();
client.setConnectTimeout(600000);
client.setReadTimeout(600000);
WebResource resource = client
.resource(url);
for (NameValuePair entry : queryParams) {
resource = resource.queryParam(entry.getName(),entry.getValue()==null?"":entry.getValue());
}
String result = resource.get(String.class);
client.destroy();
return result;
}
public static String postForString(String url,MultivaluedMap<String, String> params)
{
Client client = Client.create();
WebResource resource = client
.resource(url);
String result = resource.type(MediaType.APPLICATION_FORM_URLENCODED).post(String.class, params);
client.destroy();
return result;
}
public static <T> T postForObject(String url,MultivaluedMap<String, String> params,Class<T> claxx) throws JsonParseException, JsonMappingException, IOException
{
if (StringUtils.isBlank(url)) {
LOG.error("请求Url不能为空!");
return null;
}
String result = postForString(url, params);
if (StringUtils.isBlank(result)) {
return null;
}
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
return mapper.readValue(result, claxx);
}
public static <T> List<T> postForList(String url,MultivaluedMap<String, String> params,Class<T> claxx) throws JsonParseException, JsonMappingException, IOException, URISyntaxException
{
if (StringUtils.isBlank(url)) {
LOG.error("请求Url不能为空!");
return null;
}
String result = postForString(url, params);
if (StringUtils.isBlank(result)) {
return null;
}
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
return mapper.readValue(result,
mapper.getTypeFactory().constructCollectionType(
List.class, claxx));
}
/**
* 获取外部接口返回的JSON Array对象
* @author zhaodeshan
* @version [版本号, 2015年1月31日]
* @param url 请求地址
* @param queryParams 请求参数
* @param claxx 对象类型
* @return List<T>
* @throws JsonParseException
* @throws JsonMappingException
* @throws IOException
* @throws URISyntaxException
* @since [产品/模块版本](可选)
*/
public static <T> List<T> getForList(String url,List<NameValuePair> queryParams,Class<T> claxx) throws JsonParseException, JsonMappingException, IOException, URISyntaxException
{
if (StringUtils.isBlank(url)) {
LOG.error("请求Url不能为空!");
return null;
}
String result = HttpClientUtil.doGet(url, queryParams);
if (StringUtils.isBlank(result)) {
return null;
}
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
return mapper.readValue(result,
mapper.getTypeFactory().constructCollectionType(
List.class, claxx));
}
}
package com.house365.constant;
/**
* 外部接口URL
*
* @author zhaodeshan
* @version [版本号, 2015年2月10日]
* @see [相关类/方法](可选)
* @since [产品/模块版本] (可选)
*/
public interface ExternalUrls {
String NEW_HOUSE = "http://newapi.house365.com/projects/name";
String NEW_HOUSE2 = "http://newapi.house365.com/projects/name";
String CHECK_NEWS = "http://mapi.house365.com/cms/mobile_news.php";
String COMMON_URL = "http://mtapi.house365.com/";
String CHECK_BLOCK = "http://172.17.1.95/esf/web/check_block.php";
String POST_URL = "http://api.house365.com/sh/api_check_threadidisexist.php";
}
package com.house365.rest.context;
/**
* APP首页模块类型枚举类
* @author zhaodeshan
* @version [版本号, 2015年2月15日]
* @see [相关类/方法](可选)
* @since [产品/模块版本] (可选)
*/
public enum AppModuleTypeEnum {
/**
* 横幅广告类型
*/
BANNER_AD,
/**
* 楼层类型
*/
APP_FRAME,
/**
* 联版广告类型
*/
SERIES_AD,
/**
* 功能入口类型
*/
APP_PORTAL,
/**
* 核心模块类型
*/
CORE_MODULE
}
package com.house365.rest.context;
/**
* @author duhui
* @version [v1.0.0, 2015年1月24日]
*/
public interface ITranscation {
/**
* 事务回滚
* @return 事务回滚预留结果,暂无用途
*/
Object rollback();
/**
* 事务提交
*/
void commit();
}
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment